Skip to content

Commit 50748c5

Browse files
committed
add generator support to tracing channel
1 parent 8c32389 commit 50748c5

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

lib/diagnostics_channel.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,8 @@ function tracingChannelFrom(nameOrChannels, name) {
281281
}
282282

283283
class TracingChannel {
284+
#generatorChannel
285+
284286
constructor(nameOrChannels) {
285287
for (let i = 0; i < traceEvents.length; ++i) {
286288
const eventName = traceEvents[i];
@@ -428,6 +430,58 @@ class TracingChannel {
428430
}
429431
});
430432
}
433+
434+
*traceGenerator(fn, context = {}, thisArg, ...args) {
435+
if (!this.hasSubscribers) {
436+
return ReflectApply(fn, thisArg, args);
437+
}
438+
439+
const { start, end, asyncStart, asyncEnd, error } = this;
440+
441+
if (!this.#generatorChannel) {
442+
this.#generatorChannel = this.tracingChannel({
443+
start: this.channel(start.name.slice(0, -6) + ':next:start'),
444+
end: this.channel(end.name.slice(0, -4) + ':next:end'),
445+
asyncStart: this.channel(asyncStart.name.slice(0, -11) + ':next:asyncStart'),
446+
asyncEnd: this.channel(asyncEnd.name.slice(0, -9) + ':next:asyncEnd'),
447+
error: this.channel(error.name.slice(0, -6) + ':next:error'),
448+
});
449+
}
450+
451+
const gen = this.traceSync(fn, context, thisArg, ...args);
452+
453+
gen.next = (...args) => this.traceSync(gen.next, context, gen, ...args);
454+
gen.return = (...args) => this.traceSync(gen.return, context, gen, ...args);
455+
gen.throw = (...args) => this.traceSync(gen.throw, context, gen, ...args);
456+
457+
yield* gen;
458+
}
459+
460+
async *traceAsyncGenerator(fn, context = {}, thisArg, ...args) {
461+
if (!this.hasSubscribers) {
462+
return ReflectApply(fn, thisArg, args);
463+
}
464+
465+
const { start, end, asyncStart, asyncEnd, error } = this;
466+
467+
if (!this.#generatorChannel) {
468+
this.#generatorChannel = this.tracingChannel({
469+
start: this.channel(start.name.slice(0, -6) + ':next:start'),
470+
end: this.channel(end.name.slice(0, -4) + ':next:end'),
471+
asyncStart: this.channel(asyncStart.name.slice(0, -11) + ':next:asyncStart'),
472+
asyncEnd: this.channel(asyncEnd.name.slice(0, -9) + ':next:asyncEnd'),
473+
error: this.channel(error.name.slice(0, -6) + ':next:error'),
474+
});
475+
}
476+
477+
const gen = this.traceSync(fn, context, thisArg, ...args);
478+
479+
gen.next = (...args) => this.tracePromise(gen.next, context, gen, ...args);
480+
gen.return = (...args) => this.tracePromise(gen.return, context, gen, ...args);
481+
gen.throw = (...args) => this.tracePromise(gen.throw, context, gen, ...args);
482+
483+
yield* gen;
484+
}
431485
}
432486

433487
function tracingChannel(nameOrChannels) {

0 commit comments

Comments
 (0)