1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
|
// Hardcoded module "node:async_hooks"
// Bun is only going to implement AsyncLocalStorage and AsyncResource (partial).
// The other functions are deprecated anyways, and would impact performance too much.
// API: https://nodejs.org/api/async_hooks.html
//
// JSC has been patched to include a special global variable $asyncContext which is set to
// a constant InternalFieldTuple<[AsyncContextData, never]>. `get` and `set` read/write to the
// first element of this tuple. Inside of PromiseOperations.js, we "snapshot" the context (store it
// in the promise reaction) and then just before we call .then, we restore it.
//
// This means context tracking is *kind-of* manual. If we recieve a callback in native code
// - In Zig, call jsValue.withAsyncContextIfNeeded(); which returns another JSValue. Store that and
// then run .call() on it later.
// - In C++, call AsyncContextFrame::withAsyncContextIfNeeded(jsValue). Then to call it,
// use AsyncContextFrame:: call(...) instead of JSC:: call.
//
// The above functions will return the same JSFunction if the context is empty, and there are many
// other checks to ensure that AsyncLocalStorage has virtually no impact on performance when not in
// use. But the nature of this approach makes the implementation *itself* very low-impact on performance.
//
// AsyncContextData is an immutable array managed in here, formatted [key, value, key, value] where
// each key is an AsyncLocalStorage object and the value is the associated value.
//
const { cleanupLater, setAsyncHooksEnabled } = $lazy("async_hooks");
function get(): ReadonlyArray<any> | undefined {
$debug("get", $getInternalField($asyncContext, 0));
return $getInternalField($asyncContext, 0);
}
function set(contextValue: ReadonlyArray<any> | undefined) {
$debug("set", contextValue);
return $putInternalField($asyncContext, 0, contextValue);
}
class AsyncLocalStorage {
#disableCalled = false;
constructor() {
setAsyncHooksEnabled(true);
}
static bind(fn, ...args: any) {
return this.snapshot().bind(null, fn, ...args);
}
static snapshot() {
var context = get();
return (fn, ...args) => {
var prev = get();
set(context);
try {
return fn(...args);
} catch (error) {
throw error;
} finally {
set(prev);
}
};
}
enterWith(store) {
cleanupLater();
var context = get();
if (!context) {
set([this, store]);
return;
}
var { length } = context;
for (var i = 0; i < length; i += 2) {
if (context[i] === this) {
const clone = context.slice();
clone[i + 1] = store;
set(clone);
return;
}
}
set(context.concat(this, store));
}
exit(cb, ...args) {
return this.run(undefined, cb, ...args);
}
run(store, callback, ...args) {
var context = get() as any[]; // we make sure to .slice() before mutating
var hasPrevious = false;
var previous;
var i = 0;
var contextWasInit = !context;
if (contextWasInit) {
set((context = [this, store]));
} else {
// it's safe to mutate context now that it was cloned
context = context!.slice();
i = context.indexOf(this);
if (i > -1) {
hasPrevious = true;
previous = context[i + 1];
context[i + 1] = store;
} else {
context.push(this, store);
}
set(context);
}
try {
return callback(...args);
} catch (e) {
throw e;
} finally {
// Note: early `return` will prevent `throw` above from working. I think...
// Set AsyncContextFrame to undefined if we are out of context values
if (!this.#disableCalled) {
var context2 = get()! as any[];
if (context2 === context && contextWasInit) {
set(undefined);
} else {
context2 = context2.slice(); // array is cloned here
if (hasPrevious) {
context2[i + 1] = previous;
set(context2);
} else {
context2.splice(i, 2);
set(context2.length ? context2 : undefined);
}
}
}
}
}
disable() {
// In this case, we actually do want to mutate the context state
if (!this.#disableCalled) {
var context = get() as any[];
if (context) {
var { length } = context;
for (var i = 0; i < length; i += 2) {
if (context[i] === this) {
context.splice(i, 2);
set(context.length ? context : undefined);
break;
}
}
}
this.#disableCalled = true;
}
}
getStore() {
var context = get();
if (!context) return;
var { length } = context;
for (var i = 0; i < length; i += 2) {
if (context[i] === this) return context[i + 1];
}
}
}
class AsyncResource {
type;
#snapshot;
constructor(type, options) {
if (typeof type !== "string") {
throw new TypeError('The "type" argument must be of type string. Received type ' + typeof type);
}
setAsyncHooksEnabled(true);
this.type = type;
this.#snapshot = get();
}
emitBefore() {
return true;
}
emitAfter() {
return true;
}
asyncId() {
return 0;
}
triggerAsyncId() {
return 0;
}
emitDestroy() {
//
}
runInAsyncScope(fn, thisArg, ...args) {
var prev = get();
set(this.#snapshot);
try {
return fn.apply(thisArg, args);
} catch (error) {
throw error;
} finally {
set(prev);
}
}
bind(fn, thisArg) {
if (typeof fn !== "function") {
const invalidArgType = new TypeError('The "fn" argument must be of type function. Received type ' + typeof fn);
invalidArgType.code = "ERR_INVALID_ARG_TYPE";
throw invalidArgType;
}
let bound;
if (thisArg === undefined) {
const resource = this;
bound = function (...args) {
return resource.runInAsyncScope(resource, undefined, args as any);
};
} else {
bound = this.runInAsyncScope.bind(this, fn, thisArg);
}
}
static bind(fn, type, thisArg) {
type = type || fn.name;
const boundFn = AsyncResource.prototype["bind"];
return boundFn.call(new AsyncResource(type || "bound-anonymous-fn", undefined), fn, thisArg);
}
}
// The rest of async_hooks is not implemented and is stubbed with no-ops and warnings.
function createWarning(message) {
let warned = false;
var wrapped = function () {
if (warned) return;
// zx does not need createHook to function
const isFromZX = new Error().stack!.includes("zx/build/core.js");
if (isFromZX) return;
warned = true;
console.warn("[bun] Warning:", message);
};
return wrapped;
}
const createHookNotImpl = createWarning(
"async_hooks.createHook is not implemented in Bun. Hooks can still be created but will never be called.",
);
function createHook(callbacks) {
return {
enable: createHookNotImpl,
disable: createHookNotImpl,
};
}
const executionAsyncIdNotImpl = createWarning(
"async_hooks.executionAsyncId/triggerAsyncId are not implemented in Bun. It will return 0 every time.",
);
function executionAsyncId() {
executionAsyncIdNotImpl();
return 0;
}
function triggerAsyncId() {
return 0;
}
const executionAsyncResourceWarning = createWarning(
"async_hooks.executionAsyncResource is not implemented in Bun. It returns a reference to process.stdin every time.",
);
function executionAsyncResource() {
executionAsyncResourceWarning();
return process.stdin;
}
const asyncWrapProviders = {
NONE: 0,
DIRHANDLE: 1,
DNSCHANNEL: 2,
ELDHISTOGRAM: 3,
FILEHANDLE: 4,
FILEHANDLECLOSEREQ: 5,
FIXEDSIZEBLOBCOPY: 6,
FSEVENTWRAP: 7,
FSREQCALLBACK: 8,
FSREQPROMISE: 9,
GETADDRINFOREQWRAP: 10,
GETNAMEINFOREQWRAP: 11,
HEAPSNAPSHOT: 12,
HTTP2SESSION: 13,
HTTP2STREAM: 14,
HTTP2PING: 15,
HTTP2SETTINGS: 16,
HTTPINCOMINGMESSAGE: 17,
HTTPCLIENTREQUEST: 18,
JSSTREAM: 19,
JSUDPWRAP: 20,
MESSAGEPORT: 21,
PIPECONNECTWRAP: 22,
PIPESERVERWRAP: 23,
PIPEWRAP: 24,
PROCESSWRAP: 25,
PROMISE: 26,
QUERYWRAP: 27,
SHUTDOWNWRAP: 28,
SIGNALWRAP: 29,
STATWATCHER: 30,
STREAMPIPE: 31,
TCPCONNECTWRAP: 32,
TCPSERVERWRAP: 33,
TCPWRAP: 34,
TTYWRAP: 35,
UDPSENDWRAP: 36,
UDPWRAP: 37,
SIGINTWATCHDOG: 38,
WORKER: 39,
WORKERHEAPSNAPSHOT: 40,
WRITEWRAP: 41,
ZLIB: 42,
CHECKPRIMEREQUEST: 43,
PBKDF2REQUEST: 44,
KEYPAIRGENREQUEST: 45,
KEYGENREQUEST: 46,
KEYEXPORTREQUEST: 47,
CIPHERREQUEST: 48,
DERIVEBITSREQUEST: 49,
HASHREQUEST: 50,
RANDOMBYTESREQUEST: 51,
RANDOMPRIMEREQUEST: 52,
SCRYPTREQUEST: 53,
SIGNREQUEST: 54,
TLSWRAP: 55,
VERIFYREQUEST: 56,
INSPECTORJSBINDING: 57,
};
export default {
AsyncLocalStorage,
createHook,
executionAsyncId,
triggerAsyncId,
executionAsyncResource,
asyncWrapProviders,
AsyncResource,
};
|