-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.js
807 lines (692 loc) · 25.5 KB
/
context.js
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
/* eslint-disable max-len */
'use strict';
const util = require('util');
const assert = require('assert');
const wrapEmitter = require('emitter-listener');
const async_hooks = require('async_hooks');
const CONTEXTS_SYMBOL = 'cls@contexts';
const ERROR_SYMBOL = 'error@context';
const DBG_EXCLUDE_BOOT = true;
// make this directly accessible
const stats = {
maxSetLength: 0, // maximum number of pushed contexts
slowExits: 0, // count of slow path exits (not top of stack)
fastExits: 0, // count of fast path exits (top of stack)
totalContextsCreated: 0,
activeContexts: 0,
// <debugging root contexts>
//activeCounts: new Map(),
//rootContextSwitches: 0,
//rootContextSwitchEnters: 0,
//rootContextSwitchExits: 0,
//transitions: [], // testing only - a lot of data
// </debugging root contexts>
// raw counts for each async_hooks callback
inits: 0,
befores: 0,
afters: 0,
destroys: 0,
};
const metrics = {
hooks: {},
errors: {
beforeNoInit: [],
afterNoInit: [],
destroyNoInit: [],
},
stats,
};
let currentUid = -1;
const inspectOpts = {showHidden: true, depth: 2};
module.exports = {
getNamespace: getNamespace,
createNamespace: createNamespace,
destroyNamespace: destroyNamespace,
reset: reset,
ERROR_SYMBOL: ERROR_SYMBOL
};
function Namespace(name, options = {}) {
this.name = name;
// changed in 2.7: no default context
this.active = null; // the active context, if any
this._set = []; // place to store inactive contexts
this.id = null;
this._contexts = new Map(); // maps asyncIDs to context objects
this._indent = '';
//
// options.debug - true or an object with additional settings
//
this.debug = !!options.debug;
// don't modify the argument object. add a format object if not
// present.
if (typeof options.debug !== 'object') {
options = Object.assign({}, options, {debug: {}});
}
this.prefix = options.debug.prefix || '<cls>';
this.dbgShowActive = options.debug.showActive;
this.dbgShowContext = options.debug.showContext;
this.dbgShowBoot = options.debug.showBoot;
this.write = options.debug.output || process._rawDebug;
// formatters that can replace the default formatting
if (!options.format) {
options.format = {};
}
this.formatContext = options.format.context;
this.setGetValues = options.format.setGetValues || {};
this.shortContextFilter = options.format.shortContextFilter;
// options.captureHooks - capture hook counts for inits, befores, afters, and destroys.
// one object with 4 properties is created for each asyncID so this is only suitable
// for use in a reasonably short, limited context like a single test. e.g. the restify
// probe test only has three tests and will generate 7300 lines of output.
this.captureHooks = options.captureHooks;
}
Namespace.prototype.getMetrics = function getMetrics () {
metrics.stats.rootContextSwitches = metrics.stats.rootContextSwitchEnters + metrics.stats.rootContextSwitchExits;
// make copies so the caller can fiddle with the returned object.
const lmetrics = Object.assign({}, metrics);
lmetrics.hooks = Object.assign({}, metrics.hooks);
lmetrics.errors = Object.assign({}, metrics.errors);
lmetrics.stats = Object.assign({}, metrics.stats);
return lmetrics;
};
Namespace.prototype.set = function set(key, value) {
if (!this.active) {
throw new Error('No context available. ns.run() or ns.bind() must be called first.');
}
this.active[key] = value;
if (this.debug) {
const indentStr = this._indent;
const at = activeContext(this);
this.write(`${indentStr}~SET (context: active): ${this.fmtSetGet(key, value)} currentUid:${currentUid}${at}`);
}
return value;
};
Namespace.prototype.get = function get (key) {
if (this.debug) {
const info = getDebugInfo();
if (info.eaID !== 1) {
const {eaID, triggerId} = info;
const indentStr = this._indent;
let value = undefined;
let no = 'no-';
if (this.active) {
value = this.active[key];
no = '';
}
const ctxText = getContextText(this, this.active);
this.write(`${indentStr}~GET (context: ${no}active): ${this.fmtSetGet(key, value)} currentUid:${currentUid} hooksCurID:${eaID} triggerId:${triggerId} ${ctxText}`);
}
}
return this.active ? this.active[key] : undefined;
};
//
// options.newContext - true to force clean context
//
Namespace.prototype.createContext = function createContext (options = {}) {
// Prototype inherit existing context if creating a new child context within existing context.
let context;
if (options.newContext || !this.active) {
stats.totalContextsCreated += 1;
context = Object.create({_id: stats.totalContextsCreated});
} else {
context = Object.create(this.active);
}
context._ns_name = this.name;
context.id = currentUid;
if (this.debug) {
const flag = (options.newContext || !this.active) ? '-NEW' : '';
const {eaID, triggerId} = getDebugInfo();
const indentStr = this._indent;
const ctxText = this.fmtContext(context);
this.write(`${indentStr}~CREATE${flag}: currentUid:${currentUid} execAsyncId:${eaID} triggerId:${triggerId} context:${ctxText}`);
}
return context;
};
Namespace.prototype.run = function run(fn, options) {
let context = this.createContext(options);
this.enter(context);
try {
if (this.debug) {
const triggerId = async_hooks.triggerAsyncId();
const execAsyncID = async_hooks.executionAsyncId();
const indentStr = this._indent;
const ctxText = getContextText(this, context);
this.write(`${indentStr}~RUN: currentUid:${currentUid} triggerId:${triggerId} execAsyncID:${execAsyncID} ${ctxText}`);
}
fn(context);
return context;
} catch (exception) {
if (exception) {
exception[ERROR_SYMBOL] = context;
}
throw exception;
} finally {
if (this.debug) {
const triggerId = async_hooks.triggerAsyncId();
const execAsyncID = async_hooks.executionAsyncId();
const indentStr = this._indent;
const ctxText = getContextText(this, context);
this.write(`${indentStr}~RUN-FINALLY: currentUid:${currentUid} triggerId:${triggerId} execAsyncID:${execAsyncID} ${ctxText}`);
}
this.exit(context);
}
};
Namespace.prototype.runAndReturn = function runAndReturn(fn, options) {
let value;
this.run(function (context) {
value = fn(context);
}, options);
return value;
};
/**
* Uses global Promise and assumes Promise is cls friendly or wrapped already.
* @param {function} fn
* @returns {*}
*/
Namespace.prototype.runPromise = function runPromise(fn, options) {
let context = this.createContext(options);
this.enter(context);
let promise = fn(context);
if (!promise || !promise.then || !promise.catch) {
throw new Error('fn must return a promise.');
}
if (this.debug) {
this.write(`~RUN-PROMISE-BEFORE: (${this.name}) currentUid: ${currentUid} ${util.inspect(context)}`);
}
return promise
.then(result => {
if (this.debug) {
this.write(`~RUN-PROMISE-THEN: (${this.name}) currentUid: ${currentUid} ${util.inspect(context)}`);
}
this.exit(context);
return result;
})
.catch(err => {
err[ERROR_SYMBOL] = context;
if (this.debug) {
this.write(`~RUN-PROMISE-CATCH: (${this.name}) currentUid: ${currentUid} ${util.inspect(context)}`);
}
this.exit(context);
throw err;
});
};
Namespace.prototype.bind = function bindFactory(fn, context) {
if (!context) {
if (!this.active) {
context = this.createContext();
} else {
context = this.active;
}
}
let self = this;
return function clsBind() {
self.enter(context);
try {
return fn.apply(this, arguments);
} catch (exception) {
if (exception) {
exception[ERROR_SYMBOL] = context;
}
throw exception;
} finally {
self.exit(context);
}
};
};
Namespace.prototype.enter = function enter(context) {
assert.ok(context, 'context must be provided for entering');
// if entering a new context increment the active contexts and count how many times that number
// of active contexts has been occurred.
//let root = ''
//let info = null;
//if (context.__proto__.hasOwnProperty('_id')) {
// stats.activeContexts += 1;
// const activeContexts = stats.activeContexts;
// stats.activeCounts[activeContexts] = (stats.activeCounts[stats.activeContexts] || 0) + 1;
// if (this.active && this.active._id !== context._id) {
// stats.rootContextSwitchEnters += 1;
// root = ` (${this.active._id}=>${context._id})`
// }
//}
//info = this.active ? `${this.active._id}:${this.active.test}-${this.active.d}` : null
//stats.transitions.push(`e${root} ${info} => ${context._id}:${context.test}`)
this._set.push(this.active);
if (this._set.length > stats.maxSetLength) {
stats.maxSetLength = this._set.length;
}
this.active = context;
if (this.debug) {
const {eaID, triggerId} = getDebugInfo();
const indentStr = this._indent;
const ctxText = getContextText(this, context);
this.write(`${indentStr}~ENTER: currentUid:${currentUid} triggerId:${triggerId} execAsyncID:${eaID} ${ctxText}`);
}
};
Namespace.prototype.exit = function exit(context) {
assert.ok(context, 'context must be provided for exiting');
// if exiting a root context then decrement the active contexts.
//if (context.__proto__ === Object.prototype) {
//if (context.__proto__.hasOwnProperty('_id')) {
// stats.activeContexts -= 1;
//}
// helper
const debug = how => {
const {eaID, triggerId} = getDebugInfo();
const indentStr = this._indent;
const ctxText = getContextText(this, context);
this.write(`${indentStr}~EXIT-${how}: currentUid:${currentUid} triggerId:${triggerId} execAsyncID:${eaID} ${ctxText}`);
};
// Fast path for most exits that are at the top of the stack
if (this.active === context) {
assert.ok(this._set.length, 'can\'t remove top context');
//const previousContext = this._set[this._set.length - 1];
//let root = ''
//let info = null;
//if (previousContext && previousContext._id !== context._id) {
// stats.rootContextSwitchExits += 1;
// root = ` (${context._id}=>${previousContext._id})`
//}
//info = previousContext ? `${previousContext._id}:${previousContext.test}-${previousContext.d}` : null
//stats.transitions.push(`x${root} ${context._id}:${context.test} => ${info}`)
this.active = this._set.pop();
stats.fastExits += 1;
if (this.debug) {
debug('fast');
}
return;
}
// Fast search in the stack using lastIndexOf
let index = this._set.lastIndexOf(context);
if (index < 0) {
if (this.debug) {
this.write('??ERROR?? context exiting but not entered - ignoring: ' + util.inspect(context));
}
assert.ok(index >= 0, 'context not currently entered; can\'t exit. \n' + util.inspect(this) + '\n' + util.inspect(context));
} else {
assert.ok(index, 'can\'t remove top context');
stats.slowExits += 1;
this._set.splice(index, 1);
if (this.debug) {
debug('slow');
}
}
};
Namespace.prototype.bindEmitter = function bindEmitter(emitter) {
assert.ok(emitter.on && emitter.addListener && emitter.emit, 'can only bind real EEs');
let namespace = this;
let thisSymbol = 'context@' + this.name;
// Capture the context active at the time the emitter is bound.
function attach(listener) {
if (!listener) {
return;
}
if (!listener[CONTEXTS_SYMBOL]) {
listener[CONTEXTS_SYMBOL] = Object.create(null);
}
listener[CONTEXTS_SYMBOL][thisSymbol] = {
namespace: namespace,
context: namespace.active
};
}
// At emit time, bind the listener within the correct context.
function bind(unwrapped) {
if (!(unwrapped && unwrapped[CONTEXTS_SYMBOL])) {
return unwrapped;
}
let wrapped = unwrapped;
let unwrappedContexts = unwrapped[CONTEXTS_SYMBOL];
Object.keys(unwrappedContexts).forEach(function (name) {
let thunk = unwrappedContexts[name];
wrapped = thunk.namespace.bind(wrapped, thunk.context);
});
return wrapped;
}
wrapEmitter(emitter, attach, bind);
};
/**
* If an error comes out of a namespace, it will have a context attached to it.
* This function knows how to find it.
*
* @param {Error} exception Possibly annotated error.
*/
Namespace.prototype.fromException = function fromException(exception) {
return exception[ERROR_SYMBOL];
};
function getNamespace(name) {
return process.namespaces[name];
}
function createNamespace(name, options = {}) {
assert.ok(name, 'namespace must be given a name.');
let namespace = new Namespace(name, options);
if (options.debug) {
namespace.write(`NS-CREATE-NAMESPACE (${name})`);
}
namespace.id = currentUid;
const hook = async_hooks.createHook({
init (asyncId, type, triggerId, resource) {
stats.inits += 1;
const eaID = currentUid = async_hooks.executionAsyncId();
//CHAIN Parent's Context onto child if none exists. This is needed to pass net-events.spec
// let initContext = namespace.active;
// if(!initContext && triggerId) {
// let parentContext = namespace._contexts.get(triggerId);
// if (parentContext) {
// namespace.active = parentContext;
// namespace._contexts.set(currentUid, parentContext);
// if (DEBUG) {
// const indentStr = namespace._indent;
// debug2(`${indentStr}INIT [${type}] WITH PARENT CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);
// }
// } else if (DEBUG) {
// const indentStr = namespace._indent;
// debug2(`${indentStr}INIT [${type}] MISSING CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);
// }
// }else {
// namespace._contexts.set(currentUid, namespace.active);
// if (DEBUG) {
// const indentStr = namespace._indent;
// debug2(`${indentStr}INIT [${type}] asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);
// }
// }
if (namespace.captureHooks) {
if (asyncId in metrics.hooks) {
// the asyncId has already been seen.
metrics.hooks[asyncId].inits += 1;
} else {
// it's a new asyncId
metrics.hooks[asyncId] = {
type,
inits: 1, befores: 0, afters: 0, destroys: 0,
triggerId,
eaID,
bootstrap: eaID === 1,
};
}
}
//
// if there is an active context associate it with this asyncId.
//
if (namespace.active) {
namespace._contexts.set(asyncId, namespace.active);
if (namespace.debug) {
const indentStr = namespace._indent;
const at = activeContext(namespace);
namespace.write(`${indentStr}@INIT (context: active) [${type}] asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} ${at} resource:${resource}`);
}
} else if (currentUid === 0) {
// CurrentId will be 0 when triggered from C++. Promise events
// https://nodejs.org/api/async_hooks.html
const triggerId = async_hooks.triggerAsyncId();
const triggerIdContext = namespace._contexts.get(triggerId);
if (triggerIdContext) {
namespace._contexts.set(asyncId, triggerIdContext);
if (namespace.debug) {
const indentStr = namespace._indent;
const at = activeContext(namespace);
namespace.write(`${indentStr}@INIT (context: triggerAsyncId) [${type}] asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} ${at} resource:${resource}`);
}
} else if (namespace.debug) {
const indentStr = namespace._indent;
const at = activeContext(namespace);
namespace.write(`${indentStr}@INIT (context: missing - triggerAsyncId) [${type}] asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} ${at} resource:${resource}`);
}
} else if (namespace.debug) {
// seems like there are missing INITs
const indentStr = namespace._indent;
const at = activeContext(namespace);
namespace.write(`${indentStr}@INIT (context: missing - currentUid ${currentUid}) [${type}] asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} ${at} resource:${resource}`);
}
if (namespace.debug && type === 'PROMISE'){
namespace.write('@INIT PROMISE', util.inspect(resource, {showHidden: true}));
const parentId = resource.parentId;
const indentStr = namespace._indent;
const at = activeContext(namespace);
namespace.write(`${indentStr}@INIT (noop) [${type}] parentId:${parentId} asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} ${at} resource:${resource}`);
}
},
before (asyncId) {
stats.befores += 1;
currentUid = async_hooks.executionAsyncId();
let context;
/*
if(currentUid === 0){
// CurrentId will be 0 when triggered from C++. Promise events
// https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid
//const triggerId = async_hooks.triggerAsyncId();
context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId);
}else{
context = namespace._contexts.get(currentUid);
}
*/
if (namespace.captureHooks) {
if (asyncId in metrics.hooks) {
metrics.hooks[asyncId].befores += 1;
} else {
metrics.errors.beforeNoInit.push(asyncId);
}
}
//HACK to work with promises until they are fixed in node > 8.1.1
context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid);
if (context) {
if (namespace.debug) {
const triggerId = async_hooks.triggerAsyncId();
const indentStr = namespace._indent;
const ctxText = getContextText(namespace, context);;
namespace.write(`${indentStr}@BEFORE (context: from _contexts) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId}${ctxText}`);
namespace._indent += ' ';
}
namespace.enter(context);
} else if (namespace.debug) {
const triggerId = async_hooks.triggerAsyncId();
const indentStr = namespace._indent;
const ctxText = getContextText(namespace, context);;
namespace.write(`${indentStr}@BEFORE (context: missing) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId}${ctxText}`);
namespace._indent = namespace._indent.slice(2);
}
},
after (asyncId) {
stats.afters += 1;
currentUid = async_hooks.executionAsyncId();
let context; // = namespace._contexts.get(currentUid);
if (namespace.captureHooks) {
if (asyncId in metrics.hooks) {
metrics.hooks[asyncId].afters += 1;
} else {
metrics.errors.afterNoInit.push(asyncId);
}
}
/*
if(currentUid === 0){
// CurrentId will be 0 when triggered from C++. Promise events
// https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid
//const triggerId = async_hooks.triggerAsyncId();
context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId);
}else{
context = namespace._contexts.get(currentUid);
}
*/
//HACK to work with promises until they are fixed in node > 8.1.1
context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid);
if (context) {
if (namespace.debug) {
const triggerId = async_hooks.triggerAsyncId();
namespace._indent = namespace._indent.slice(2);
const indentStr = namespace._indent;
const ctxText = getContextText(namespace, context);;
namespace.write(`${indentStr}@AFTER (context: from _contexts) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId}${ctxText}`);
}
namespace.exit(context);
} else if (namespace.debug) {
const triggerId = async_hooks.triggerAsyncId();
namespace._indent = namespace._indent.slice(2);
const indentStr = namespace._indent;
const ctxText = getContextText(namespace, context);;
namespace.write(`${indentStr}@AFTER (context: missing) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId}${ctxText}`);
}
},
destroy (asyncId) {
stats.destroys += 1;
currentUid = async_hooks.executionAsyncId();
if (namespace.captureHooks) {
if (asyncId in metrics.hooks) {
metrics.hooks[asyncId].destroys += 1;
} else {
metrics.errors.destroyNoInit.push(asyncId);
}
}
if (namespace.debug) {
const triggerId = async_hooks.triggerAsyncId();
const indentStr = namespace._indent;
const context = namespace._contexts.get(asyncId);
const existText = context ? 'found' : 'missing';
const ctxText = getContextText(namespace, context);;
namespace.write(`${indentStr}@DESTROY ${existText} currentUid:${currentUid} asyncId:${asyncId} triggerId:${triggerId} ${ctxText}`);
}
namespace._contexts.delete(asyncId);
},
//promiseResolve (asyncId) {
// currentUid = async_hooks.executionAsyncId();
// if (DEBUG) {
// const triggerId = async_hooks.triggerAsyncId();
// const indentStr = namespace._indent;
// debug2(`${indentStr}DESTROY currentUid:${currentUid} asyncId:${asyncId} triggerId:${triggerId} ${at} context:${util.inspect(namespace._contexts.get(currentUid))}`);
// }
//}
});
hook.enable();
namespace._hook = hook;
process.namespaces[name] = namespace;
return namespace;
}
function destroyNamespace (name) {
let namespace = getNamespace(name);
assert.ok(namespace, 'can\'t delete nonexistent namespace! "' + name + '"');
assert.ok(namespace.id, 'don\'t assign to process.namespaces directly! ' + util.inspect(namespace));
delete process.namespaces[name];
}
function reset () {
// must unregister async listeners
if (process.namespaces) {
Object.keys(process.namespaces).forEach(function (name) {
destroyNamespace(name);
});
}
process.namespaces = Object.create(null);
}
process.namespaces = {};
//
// Namespace-specific formatters.
//
Namespace.prototype.fmtContext = function fmtContext (ctx) {
let text;
// was a context formatter specified?
if (this.formatContext) {
text = this.formatContext(ctx);
if (text) {
return text;
}
}
if (typeof ctx === 'function') {
return 'function()';
}
return util.inspect(ctx, inspectOpts);
};
Namespace.prototype.fmtSetGet = function fmtSetGet (key, value) {
if (key in this.setGetValues) {
return `${key}=${this.setGetValues[key](value)}`;
}
return `${key}=${util.inspect(value)}`;
};
function getContextText (ns, context) {
if (ns.dbgShowContext !== 'short') {
return longContext(ns, context);
}
return shortContext(ns);
}
Namespace.prototype.shortContext = function () {
const filter = this.shortContextFilter || (() => true);
const ckeys = [...this._contexts.keys()].filter(k => filter(this._contexts.get(k)));
// map contexts to their ids.
const skeys = this._set.filter(c => c).map(c => c.id);
return `c[${ckeys.join(',')}], s[${skeys.join(',')}]`;
};
//
// formatters independent of the namespace
//
// find the id to preface the context with.
function activeContext (ns, active) {
if (!ns || !ns._contexts || !ns._set) {
return 'bad-namespace';
}
if (!ns.dbgShowActive) {
return '';
}
if (!active) {
active = ns.active;
}
// find the id for the context
let ctxID = '?';
for (let [key, ctx] of ns._contexts) {
if (ctx === active) {
ctxID = key;
break;
}
}
const t = active === ns.active ? '(active)' : '';
return `${ctxID}${t}=>${ns.fmtContext(context)}`;
}
// the long form context
function longContext (ns, context) {
if (!ns || !ns._contexts || !ns._set) {
return 'bad-namespace';
}
let ctxKey = '';
const ctext = [...ns._contexts.keys()].map(k => {
const ctx = ns._contexts.get(k);
if (ctx === context) {
ctxKey = `${k}=>`;
}
return `${k} => ${ns.fmtContext(ctx)}`;
});
const stext = ns._set.map(c => ns.fmtContext(c));
const sep = '\n ';
return `\n context:${ctxKey}${ns.fmtContext(context)},\n _contexts:${ctext.join(sep)},\n _set(${stext.length}):${stext.join(sep)}`;
}
// short form context is always namespace-specific.
function shortContext (ns) {
if (!ns || !ns._contexts || !ns._set) {
return 'bad-namespace';
}
return ns.shortContext();
}
// placeholder in case it's useful to format resources (TickObject, UDPWRAP, etc.)
/* eslint-disable-next-line no-unused-vars */
function fmtResource (type, resource) {
return '';
}
/*
function debug2(...args) {
process._rawDebug(PREFIX, `${util.format(...args)}`);
}
// */
function getDebugInfo () {
const info = {
eaID: async_hooks.executionAsyncId(),
triggerId: async_hooks.triggerAsyncId(),
};
info.show = !DBG_EXCLUDE_BOOT || (info.eaID !== 1 && info.triggerId !== 1);
return info;
};
/*function getFunctionName(fn) {
if (!fn) {
return fn;
}
if (typeof fn === 'function') {
if (fn.name) {
return fn.name;
}
return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
} else if (fn.constructor && fn.constructor.name) {
return fn.constructor.name;
}
}*/