1 | import { logger } from './logger';
|
2 |
|
3 | type Thread = {};
|
4 |
|
5 | let currentThread: Thread | undefined = undefined;
|
6 | export async function thread(fn: () => Promise<void>) {
|
7 | currentThread = {} as Thread;
|
8 | await fn();
|
9 | currentThread = undefined;
|
10 | }
|
11 | export function getCurrentThread() {
|
12 | if (currentThread === undefined) throw new Error('CurrentThread is undefined');
|
13 | return currentThread;
|
14 | }
|
15 | export function threadPause<T>(val: T) {
|
16 | currentThread = undefined;
|
17 | return val;
|
18 | }
|
19 | export function threadContinue<T>(thread: Thread, val: T) {
|
20 | currentThread = thread;
|
21 | return val;
|
22 | }
|
23 | export function setDataToCurrentThread(key: symbol, val: unknown) {
|
24 | const thread = getCurrentThread();
|
25 | thread[key as never] = val as never;
|
26 | }
|
27 | export function getDataFromCurrentThread<T>(key: symbol) {
|
28 | const thread = getCurrentThread();
|
29 | return thread[key as never] as T | undefined;
|
30 | }
|
31 |
|
32 | const callSymbol = Symbol('Call');
|
33 |
|
34 | function getParentId() {
|
35 | const parentId = getDataFromCurrentThread<string>(callSymbol);
|
36 | return parentId;
|
37 | }
|
38 |
|
39 | function 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 |
|
46 | function exit<T>(parentId: string | undefined, val?: T) {
|
47 | setDataToCurrentThread(callSymbol, parentId);
|
48 | return val;
|
49 | }
|
50 | async function foo(_x: number) {
|
51 | const parentId = enter('foo');
|
52 | 1 + 2;
|
53 | if (Math) {
|
54 | throw 1;
|
55 | }
|
56 | exit(parentId);
|
57 | }
|
58 |
|
59 | async 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 | }
|
68 | thread(async () => {
|
69 | await x();
|
70 | });
|