forked from angular/zone.js
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathasync_hooks.ts
256 lines (231 loc) · 7.72 KB
/
async_hooks.ts
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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* patch nodejs async operations (timer, promise, net...) with
* nodejs async_hooks
*/
Zone.__load_patch('node_async_hooks', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
let async_hooks;
try {
async_hooks = require('async_hooks');
Zone.__mode__ = 'asynchooks';
global.__Zone_disable_node_timers = true;
global.__Zone_disable_nextTick = true;
global.__Zone_disable_handleUnhandledPromiseRejection = true;
global.__Zone_disable_crypto = true;
global.__Zone_disable_fs = true;
} catch (err) {
print(err.message);
return;
}
const DEBUG = false;
const PROMISE_PROVIDER = 'PROMISE';
const TICKOBJ_PROVIDER = 'TickObject';
const TIMER_PROVIDER = 'Timeout';
const TIMERWRAP_PROVIDER = 'TIMERWRAP';
const SET_INTERVAL = 'setInterval';
const SET_TIMEOUT = 'setTimeout';
const NEXT_TICK = 'process.nextTick';
const periodicProviders = ['STATWATCHER', 'HTTPPARSER', 'TCPWRAP'];
const NUMBER = 'number';
const noop = function() {};
let isPromiseTick = false;
interface AsyncHooksContext {
zone?: Zone;
id: number;
task?: Task;
isDeleted?: boolean;
}
const idPromise: AsyncHooksContext[] = [];
const idMicroTasks: AsyncHooksContext[] = [];
const idMacroTasks: AsyncHooksContext[] = [];
if ((process as any).setUncaughtExceptionCaptureCallback) {
(process as any).setUncaughtExceptionCaptureCallback((error: any) => {
const zone = Zone.current;
(zone as any)._zoneDelegate.handleError(zone, error);
});
}
process.on('unhandledRejection', (reason: any, p: any) => {
const zone = Zone.current;
(zone as any)._zoneDelegate.handleError(zone, error);
});
function binarySearch(array: AsyncHooksContext[], id: number): AsyncHooksContext {
let low = 0, high = array.length - 1, mid;
while (low <= high) {
mid = Math.floor((low + high) / 2);
const midCtx = array[mid];
if (midCtx.id === id) {
return midCtx;
} else if (midCtx.id < id)
low = mid + 1;
else
high = mid - 1;
}
return null;
}
function clearAsyncHooksContext(ctx: AsyncHooksContext) {
ctx.task = null;
ctx.zone = null;
ctx.isDeleted = true;
}
function cancelTask(task: Task, id: number) {
if (task.source === SET_TIMEOUT) {
clearTimeout((task.data as any).args);
} else if (task.source === SET_INTERVAL) {
clearInterval((task.data as any).args);
}
}
function print(...args: string[]) {
if (!DEBUG) {
return;
}
if (!args) {
return;
}
(process as any)._rawDebug(args.join(' '));
}
function printObj(obj: any) {
if (!DEBUG) {
return;
}
/*print(Object.keys(obj)
.map((key: any) => {
return key + ':' + obj[key];
})
.join(','));
*/
}
api.setPromiseTick = (flag: boolean) => {
isPromiseTick = flag;
};
function promiseInit(id: number, triggerId: number, parentHandle: any) {
if (!parentHandle) {
print('no parenthandle');
return;
}
const promise = parentHandle.promise;
const originalThen = promise.then;
const zone = Zone.current;
idPromise.push({id, zone});
promise.then = function(onResolve: any, onReject: any) {
const task = zone.scheduleMicroTask(PROMISE_PROVIDER, noop, null, noop);
isPromiseTick = true;
process.nextTick(() => {
task.zone.runTask(task, null, null);
originalThen.call(this, onResolve, onReject);
});
};
}
function scheduleMicroTask(id: number, provider: string, triggerId: number, parentHandle: any) {
const zone = Zone.current;
const task = zone.scheduleMicroTask(NEXT_TICK, noop, null, noop);
idMicroTasks.push({id, zone, task});
}
function scheduleMacroTask(
id: number, provider: string, triggerId: number, parentHandle: any, delay?: number,
isPeriodic = false) {
const zone = Zone.current;
const data: any = {isPeriodic: isPeriodic};
if (delay) {
data.delay = delay;
}
data.args = parentHandle;
let source: string = provider;
if (isPeriodic) {
source = provider === TIMER_PROVIDER ? SET_INTERVAL : provider;
} else if (provider === TIMER_PROVIDER) {
source = SET_TIMEOUT;
}
const task = zone.scheduleMacroTask(source, noop, data, noop, () => {
cancelTask(task, id);
});
idMacroTasks.push({id, zone, task});
}
function init(id: number, provider: string, triggerId: number, parentHandle: any) {
print('init', provider, id.toString());
if (isPromiseTick) {
isPromiseTick = false;
return;
}
if (provider === TIMERWRAP_PROVIDER) {
return;
}
if (provider === PROMISE_PROVIDER) {
promiseInit(id, triggerId, parentHandle);
} else if (provider === TICKOBJ_PROVIDER) {
scheduleMicroTask(id, provider, triggerId, parentHandle);
return;
} else {
if (provider === TIMER_PROVIDER && parentHandle && typeof parentHandle._repeat === NUMBER) {
scheduleMacroTask(id, provider, triggerId, parentHandle, parentHandle._idleTimeout, true);
} else if (periodicProviders.indexOf(provider) >= 0) {
scheduleMacroTask(id, provider, triggerId, parentHandle, undefined, true);
} else {
printObj(parentHandle);
scheduleMacroTask(
id, provider, triggerId, parentHandle,
typeof parentHandle._idleTimeout === NUMBER ? parentHandle._idleTimeout : undefined,
false);
}
}
}
function before(id: number) {
let currentAsyncContext = binarySearch(idPromise, id);
if (currentAsyncContext) {
api.setAsyncContext(currentAsyncContext);
return;
}
currentAsyncContext = binarySearch(idMicroTasks, id);
if (!currentAsyncContext) {
currentAsyncContext = binarySearch(idMacroTasks, id);
}
if (currentAsyncContext) {
print(
'before ',
currentAsyncContext && currentAsyncContext.task && currentAsyncContext.task.source,
id.toString());
api.beforeRunTask(currentAsyncContext.zone, currentAsyncContext.task);
(currentAsyncContext.zone as any).invokeTask(currentAsyncContext.task, null, null);
}
}
function after(id: number) {
let currentAsyncContext = binarySearch(idPromise, id);
if (currentAsyncContext) {
api.setAsyncContext(null);
clearAsyncHooksContext(currentAsyncContext);
return;
}
currentAsyncContext = binarySearch(idMicroTasks, id);
if (!currentAsyncContext) {
currentAsyncContext = binarySearch(idMacroTasks, id);
}
print(
'after ',
currentAsyncContext && currentAsyncContext.task && currentAsyncContext.task.source,
id.toString());
if (currentAsyncContext) {
api.afterRunTask(currentAsyncContext.zone, currentAsyncContext.task);
if (!(currentAsyncContext.task && currentAsyncContext.task.data &&
currentAsyncContext.task.data.isPeriodic)) {
clearAsyncHooksContext(currentAsyncContext);
}
}
}
function destroy(id: number) {
const currentAsyncContext = binarySearch(idMacroTasks, id);
if (currentAsyncContext && currentAsyncContext.task) {
print('cancel async context', currentAsyncContext.task.source, id.toString());
printObj((currentAsyncContext.task.data as any).args);
if (currentAsyncContext.task.state !== 'notScheduled') {
currentAsyncContext.zone.cancelTask(currentAsyncContext.task);
}
clearAsyncHooksContext(currentAsyncContext);
}
}
async_hooks.createHook({init, before, after, destroy}).enable();
});