UNPKG

1.71 kBPlain TextView Raw
1import { logger } from './logger';
2
3type Thread = {};
4
5let currentThread: Thread | undefined = undefined;
6export async function thread(fn: () => Promise<void>) {
7 currentThread = {} as Thread;
8 await fn();
9 currentThread = undefined;
10}
11export function getCurrentThread() {
12 if (currentThread === undefined) throw new Error('CurrentThread is undefined');
13 return currentThread;
14}
15export function threadPause<T>(val: T) {
16 currentThread = undefined;
17 return val;
18}
19export function threadContinue<T>(thread: Thread, val: T) {
20 currentThread = thread;
21 return val;
22}
23export function setDataToCurrentThread(key: symbol, val: unknown) {
24 const thread = getCurrentThread();
25 thread[key as never] = val as never;
26}
27export function getDataFromCurrentThread<T>(key: symbol) {
28 const thread = getCurrentThread();
29 return thread[key as never] as T | undefined;
30}
31
32const callSymbol = Symbol('Call');
33
34function getParentId() {
35 const parentId = getDataFromCurrentThread<string>(callSymbol);
36 return parentId;
37}
38
39function enter(name: string) {
40 const parentId = getParentId();
41 const currentId = logger.trace('call', { name, timestamp: Date.now() });
42 setDataToCurrentThread(callSymbol, currentId);
43 return parentId;
44}
45
46function exit<T>(parentId: string | undefined, val?: T) {
47 setDataToCurrentThread(callSymbol, parentId);
48 return val;
49}
50async function foo(_x: number) {
51 const parentId = enter('foo');
52 1 + 2;
53 if (Math) {
54 throw 1;
55 }
56 exit(parentId);
57}
58
59async function x() {
60 const thread = getCurrentThread();
61 const parentId = enter('x');
62 try {
63 const y = threadContinue(thread, await threadPause(foo(1)));
64 return exit(parentId, y);
65 } catch (e) {}
66 return exit(parentId, 123);
67}
68thread(async () => {
69 await x();
70});