src/vs/base/test/common/virtualScheduling/trace.ts

172 LOC · 167 covered · 5 uncovered · 16 ranges · 2121 concepts · 7 introducers · 1304 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- processor.ts ×17
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { BugIndicatingError } from '../../../common/errors.js';
7 >
8 > /**
9 > * # Trace — causal-chain attribution for scheduled work
10 > *
11 > * A {@link Trace} is an immutable value identifying a causal chain. Every
12 > * non-root trace carries a `parent`; the head of the chain has no parent.
13 > * Use {@link child} to extend a chain when scheduling follow-up work.
14 > *
15 > * Traces are used to answer "who caused this?" for any virtual event:
16 > * useful for debugging, for per-owner termination, and for attribution in
17 > * error messages.
18 > */
19 > export class Trace {
20 > private static _idCounter = 0;
21 > public readonly id: number = ++Trace._idCounter;
22 > public readonly root: Trace;
23 > public readonly depth: number;
24 >
25 > constructor(
26 > public readonly parent: Trace | undefined,
27 > public readonly label: string,
28 > public readonly stack: string | undefined = undefined,
29 > ) {
30 > this.root = parent?.root ?? this;
31 > this.depth = (parent?.depth ?? -1) + 1;
32 > }
33 >
34 > child(label: string, stack?: string): Trace {
35 > return new Trace(this, label, stack); trace.ts ×1
36 > }
38 > /** "#id label ← #id label ← … ← #id label" */
39 > describe(): string {
40 > const parts: string[] = []; trace.ts ×2
41 > for (let t: Trace | undefined = this; t; t = t.parent) {
42 > parts.push(`#${t.id} ${t.label}`);
43 > }
44 > return parts.join(' ← ');
45 > }
47 > toString(): string { return this.describe(); }
48 > }
49 >
50 > /** Sentinel for "no known causal predecessor". */
51 > export const ROOT_TRACE: Trace = new Trace(undefined, '<root>');
52 >
53 > export function createTraceRoot(label: string, stack?: string): Trace {
54 > return new Trace(undefined, label, stack); trace.ts ×1
55 > }
57 > interface Frame {
58 > readonly trace: Trace;
59 > readonly prev: Frame | undefined;
60 > }
61 >
62 > const ROOT_FRAME: Frame = { trace: ROOT_TRACE, prev: undefined };
63 >
64 > /**
65 > * Options for {@link TraceContext.runAsHandler}.
66 > *
67 > * # Why this is a per-call option
68 > *
69 > * `runAsHandler` cannot restore the previous trace synchronously: microtasks
70 > * enqueued by `fn` (including awaited continuations) must observe the new
71 > * trace. So the reset is deferred — but it must fire after the *closure* of
72 > * the microtask queue (the current microtask plus every microtask it
73 > * recursively enqueues), not just one drain.
74 > *
75 > * Per spec, the host doesn't run a macrotask until the microtask queue is
76 > * empty, so any macrotask primitive (`setTimeout(0)`, `setImmediate`, the
77 > * `setTimeout0` shim) achieves this. Letting the *caller* supply the sink
78 > * means:
79 > *
80 > * - the {@link VirtualTimeProcessor} can route the reset through the same
81 > * primitive its embedding uses for its own host hops, eliminating any
82 > * race between the processor's hops and the trace-reset timer;
83 > *
84 > * - production code without a processor can still use a real
85 > * `setTimeout(0)`-based sink and get the same semantics;
86 > *
87 > * - tests can install a deterministic sink (e.g. a hand-driven queue) for
88 > * fully synchronous assertions.
89 > */
90 > export interface RunAsHandlerOptions {
91 > /**
92 > * Sink for the deferred trace-reset.
93 > *
94 > * Must invoke `reset` after the microtask closure that follows the
95 > * `runAsHandler` call returns — i.e. on the next host macrotask.
96 > */
97 > readonly afterMicrotaskClosure: (reset: () => void) => void;
98 > }
99 >
100 > /**
101 > * Holds the mutable "current trace frame" slot. Construct fresh instances
102 > * for test isolation, or use {@link TraceContext.instance} for shared state.
103 > */
104 > export class TraceContext {
105 > public static readonly instance = new TraceContext();
106 >
107 > private _current: Frame = ROOT_FRAME;
108 > private _isHandlerRunning = false;
109 >
110 > currentTrace(): Trace { return this._current.trace; }
111 >
112 > /**
113 > * Install `t` as current for the synchronous duration of `fn`, then
114 > * restore. Nestable. Microtasks enqueued by fn that run after fn returns
115 > * see the *restored* trace — use {@link runAsHandler} when continuation
116 > * inheritance is wanted.
117 > */
118 > runWithTrace<T>(t: Trace, fn: () => T): T {
119 > const prev = this._current; trace.ts ×2
120 > const next: Frame = { trace: t, prev };
121 > this._current = next;
122 > try {
123 > return fn();
124 > } finally {
125 > if (this._current !== next) {
126 // eslint-disable-next-line no-unsafe-finally
127 throw new BugIndicatingError(
128 `runWithTrace: unexpected mutation of current frame.`
129 );
130 }
131 > this._current = prev; trace.ts ×2
132 > }
133 > }
135 > /**
136 > * Install `t` as current and run `fn`. The trace stays current through
137 > * the microtask closure that follows `fn`, so awaited continuations
138 > * inside fn observe `t`. The reset is dispatched via
139 > * `opts.afterMicrotaskClosure`.
140 > *
141 > * Throws on synchronous re-entry: timer callbacks never nest on the
142 > * same JS stack frame, so this only fires for misuse.
143 > */
144 > runAsHandler<T>(t: Trace, fn: () => T, opts: RunAsHandlerOptions): T {
145 > if (this._isHandlerRunning) { trace.ts ×2
146 > throw new Error( trace.ts ×2
147 > `runAsHandler: re-entrant invocation. ` +
148 > `current=${this._current.trace.describe()}, incoming=${t.describe()}`
149 > );
150 > }
151 > const prev = this._current; trace.ts ×2
152 > const next: Frame = { trace: t, prev };
153 > this._current = next;
154 > this._isHandlerRunning = true;
155 > try {
156 > return fn();
157 > } finally {
158 > this._isHandlerRunning = false;
159 > opts.afterMicrotaskClosure(() => {
160 > // Identity guard: another handler may have run between us
161 > // queuing this reset and it firing. Each runAsHandler mints
162 > // a fresh frame, so reference-equality detects staleness.
163 > if (this._current === next) { this._current = prev; }
164 > });
165 > }
166 > }
168 > _resetForTesting(): void {
169 > this._current = ROOT_FRAME; trace.ts ×1
170 > this._isHandlerRunning = false;
171 > }