forked from google/pprof-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest-otel-thread-ctx.ts
More file actions
856 lines (788 loc) · 28.2 KB
/
Copy pathtest-otel-thread-ctx.ts
File metadata and controls
856 lines (788 loc) · 28.2 KB
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
/*
* Copyright 2026 Datadog, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Vendored from https://github.com/polarsignals/custom-labels/tree/otel-thread-ctx-wip/js/test/
// (originally js/test/test.js, ported to TypeScript). Kept as a
// near-verbatim copy: edits should ideally land upstream first and be
// ported here, so the two stay in sync. We plan to drop this vendored
// copy once the upstream package is suitable to depend on directly.
// Tests intentionally use array holes to verify the writer's positional
// attribute encoding (where a hole means "no value at this key index").
/* eslint-disable no-sparse-arrays */
import assert from 'assert';
import {strict as strictAssert} from 'assert';
import {spawnSync} from 'node:child_process';
import {existsSync} from 'node:fs';
import {join} from 'node:path';
import {
ThreadContext,
getContext,
clearContext,
getProcessContextAttributes,
_currentRecordBytes,
} from '../src/otel-thread-ctx';
// Helpers bridging the old positional-attrs test shape to the new
// ThreadContext-first API.
interface PosOpts {
traceId: Uint8Array;
spanId: Uint8Array;
attributes?: Array<string | null | undefined>;
}
function tcRun<T>(fn: () => T, opts: PosOpts): T {
return new ThreadContext(opts.traceId, opts.spanId, opts.attributes).run(fn);
}
function tcEnter(opts: PosOpts): void {
new ThreadContext(opts.traceId, opts.spanId, opts.attributes).enter();
}
function tcAppend(
attributes: Array<string | null | undefined> | undefined,
): void {
getContext()!.appendAttributes(attributes);
}
function tcIsTruncated(): boolean {
return getContext()?.isTruncated() ?? false;
}
const isLinux = process.platform === 'linux';
// AsyncContextFrame (the writer's discovery substrate) is opt-in on Node
// 22/23 (via --experimental-async-context-frame) and on by default in
// Node 24+ (disable-able via --no-async-context-frame). The TS layer
// refuses to install the hook when ACF isn't available, so the entire
// describe block is skipped in that case. Mirrors the source-side
// asyncContextFrameError logic.
const isAsyncContextFrameAvailable = (() => {
if (process.execArgv.includes('--no-async-context-frame')) return false;
const major = Number(process.versions.node.split('.')[0]);
if (major >= 24) return true;
if (major >= 22) {
return process.execArgv.includes('--experimental-async-context-frame');
}
return false;
})();
// Returns a plain Uint8Array (not a Buffer) so assert.deepStrictEqual against
// other Uint8Arrays — including the one the addon returns — succeeds.
function bytesFromHex(hex: string): Uint8Array {
return Uint8Array.from(Buffer.from(hex, 'hex'));
}
const TRACE_ID_BYTES = bytesFromHex('0102030405060708090a0b0c0d0e0f10');
const SPAN_ID_BYTES = bytesFromHex('1112131415161718');
interface Header {
traceId: Uint8Array;
spanId: Uint8Array;
valid: number;
reserved: number;
attrsDataSize: number;
}
function decodeHeader(bytes: Uint8Array): Header {
strictAssert.ok(
bytes.length >= 28,
`record must be at least 28 bytes, got ${bytes.length}`,
);
const attrsDataSize = bytes[26] | (bytes[27] << 8);
strictAssert.equal(
bytes.length,
28 + attrsDataSize,
`record length (${bytes.length}) must equal 28 + attrs_data_size (${attrsDataSize})`,
);
return {
traceId: bytes.slice(0, 16),
spanId: bytes.slice(16, 24),
valid: bytes[24],
reserved: bytes[25],
attrsDataSize,
};
}
// Returns the attribute payload as a positional sparse array, mirroring the
// writer's input shape: index N is the value for uint8 key index N on the
// wire; unset slots are array holes.
function decodeAttrs(bytes: Uint8Array): Array<string | undefined> {
const hdr = decodeHeader(bytes);
const out: Array<string | undefined> = [];
let i = 28;
const end = i + hdr.attrsDataSize;
while (i < end) {
const idx = bytes[i++];
const len = bytes[i++];
out[idx] = Buffer.from(bytes.slice(i, i + len)).toString('utf8');
i += len;
}
strictAssert.equal(
i,
end,
'attrs payload must be exactly attrsDataSize bytes',
);
return out;
}
function captureBytes(opts: {
traceId: Uint8Array;
spanId: Uint8Array;
attributes?: Array<string | null | undefined>;
}): Uint8Array {
let bytes: Uint8Array | undefined;
tcRun(() => {
bytes = _currentRecordBytes();
}, opts);
return bytes as Uint8Array;
}
(isLinux && isAsyncContextFrameAvailable ? describe : describe.skip)(
'OTEP-4947 thread context (Linux-only)',
() => {
describe('ThreadContext construction', () => {
it('accepts Uint8Array trace and span IDs', () => {
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
});
const hdr = decodeHeader(bytes);
strictAssert.deepEqual(hdr.traceId, TRACE_ID_BYTES);
strictAssert.deepEqual(hdr.spanId, SPAN_ID_BYTES);
strictAssert.equal(hdr.valid, 1);
strictAssert.equal(hdr.reserved, 0);
strictAssert.equal(hdr.attrsDataSize, 0);
});
it('accepts Buffer (Uint8Array subclass) trace and span IDs', () => {
const bytes = captureBytes({
traceId: Buffer.from(TRACE_ID_BYTES),
spanId: Buffer.from(SPAN_ID_BYTES),
});
const hdr = decodeHeader(bytes);
strictAssert.deepEqual(hdr.traceId, TRACE_ID_BYTES);
strictAssert.deepEqual(hdr.spanId, SPAN_ID_BYTES);
});
it('rejects wrong-length traceId', () => {
strictAssert.throws(
() =>
captureBytes({traceId: new Uint8Array(8), spanId: SPAN_ID_BYTES}),
/traceId must be/,
);
});
it('rejects wrong-length spanId', () => {
strictAssert.throws(
() =>
captureBytes({traceId: TRACE_ID_BYTES, spanId: new Uint8Array(4)}),
/spanId must be/,
);
});
it('rejects non-Uint8Array traceId', () => {
strictAssert.throws(
() =>
captureBytes({
traceId: 'a'.repeat(32) as unknown as Uint8Array,
spanId: SPAN_ID_BYTES,
}),
/traceId must be/,
);
});
});
describe('attribute encoding', () => {
it('leaves attrs_data empty when no attributes are provided', () => {
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
});
strictAssert.equal(decodeHeader(bytes).attrsDataSize, 0);
});
it('encodes attributes by position', () => {
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: ['GET', '/api/v1/widgets'],
});
strictAssert.deepEqual(decodeAttrs(bytes), ['GET', '/api/v1/widgets']);
});
it('skips null and undefined slots', () => {
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: ['zero', null, undefined, 'three'],
});
strictAssert.deepEqual(decodeAttrs(bytes), ['zero', , , 'three']);
});
it('skips trailing array holes', () => {
const attributes: Array<string | undefined> = [];
attributes[5] = 'five';
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes,
});
strictAssert.deepEqual(decodeAttrs(bytes), [, , , , , 'five']);
});
it('coerces non-string values via toString', () => {
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: [42 as unknown as string, true as unknown as string],
});
strictAssert.deepEqual(decodeAttrs(bytes), ['42', 'true']);
});
it('truncates values longer than 255 bytes to 255', () => {
const long = 'x'.repeat(300);
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: [long],
});
strictAssert.deepEqual(decodeAttrs(bytes), ['x'.repeat(255)]);
});
it('does not split a multibyte UTF-8 codepoint at the truncation boundary', () => {
const euro = '€';
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: [euro.repeat(86)],
});
strictAssert.deepEqual(decodeAttrs(bytes), [euro.repeat(85)]);
strictAssert.equal(decodeHeader(bytes).attrsDataSize, 2 + 255);
const bytes2 = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: [euro.repeat(84) + 'éé'],
});
strictAssert.deepEqual(decodeAttrs(bytes2), [euro.repeat(84) + 'é']);
strictAssert.equal(decodeHeader(bytes2).attrsDataSize, 2 + 254);
});
it('right-sizes an empty record to 28 bytes', () => {
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
});
strictAssert.equal(bytes.length, 28);
});
it('right-sizes a one-short-attribute record to 28 + 2 + len bytes', () => {
const bytes = captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: ['GET'],
});
strictAssert.equal(bytes.length, 28 + 2 + 3);
});
it('skip-and-continue truncates past the 612-byte cap', () => {
const a = 'a'.repeat(255);
const b = 'b'.repeat(255);
const c = 'c'.repeat(255);
const d = 'd'.repeat(30);
let bytes: Uint8Array | undefined;
let truncated = false;
tcRun(
() => {
bytes = _currentRecordBytes();
truncated = tcIsTruncated();
},
{
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: [a, b, c, d],
},
);
strictAssert.deepEqual(decodeAttrs(bytes!), [a, b, , d]);
strictAssert.equal(decodeHeader(bytes!).attrsDataSize, 514 + 32);
strictAssert.equal(truncated, true);
});
it('rejects attributes array longer than 256', () => {
const tooLong: Array<string | undefined> = new Array(257);
strictAssert.throws(
() =>
captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: tooLong,
}),
/must not exceed 256/,
);
});
it('rejects non-array attributes argument', () => {
strictAssert.throws(
() =>
captureBytes({
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: {not: 'an array'} as unknown as Array<string>,
}),
/attributes must be an array/,
);
});
});
describe('runWithContext lifecycle', () => {
it('returns the callback result', () => {
const result = tcRun(() => 'ok', {
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
});
strictAssert.equal(result, 'ok');
});
it('has no active record outside the call', () => {
strictAssert.equal(_currentRecordBytes(), undefined);
});
it('has no active record after the call returns', () => {
tcRun(() => undefined, {
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
});
strictAssert.equal(_currentRecordBytes(), undefined);
});
it('restores the parent context after a nested call returns', () => {
const outerOpts = {traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES};
const innerSpanBytes = bytesFromHex('aabbccddeeff0011');
const innerOpts = {traceId: TRACE_ID_BYTES, spanId: innerSpanBytes};
tcRun(() => {
const outerBefore = decodeHeader(_currentRecordBytes()!).spanId;
tcRun(() => {
const inner = decodeHeader(_currentRecordBytes()!).spanId;
strictAssert.deepEqual(inner, innerSpanBytes);
}, innerOpts);
const outerAfter = decodeHeader(_currentRecordBytes()!).spanId;
strictAssert.deepEqual(outerBefore, outerAfter);
strictAssert.deepEqual(outerAfter, SPAN_ID_BYTES);
}, outerOpts);
});
it('keeps the same record after awaits', async () => {
await tcRun(
async () => {
const before = decodeHeader(_currentRecordBytes()!).spanId;
await Promise.resolve();
const afterMicro = decodeHeader(_currentRecordBytes()!).spanId;
await new Promise(setImmediate);
const afterMacro = decodeHeader(_currentRecordBytes()!).spanId;
strictAssert.deepEqual(before, SPAN_ID_BYTES);
strictAssert.deepEqual(afterMicro, SPAN_ID_BYTES);
strictAssert.deepEqual(afterMacro, SPAN_ID_BYTES);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('keeps concurrent async calls isolated', async () => {
const aSpan = bytesFromHex('1111111111111111');
const bSpan = bytesFromHex('2222222222222222');
async function run(spanBytes: Uint8Array) {
return tcRun(
async () => {
const observed: Uint8Array[] = [];
for (let i = 0; i < 4; i++) {
observed.push(decodeHeader(_currentRecordBytes()!).spanId);
await Promise.resolve();
}
return observed;
},
{traceId: TRACE_ID_BYTES, spanId: spanBytes},
);
}
const [aObs, bObs] = await Promise.all([run(aSpan), run(bSpan)]);
for (const s of aObs) strictAssert.deepEqual(s, aSpan);
for (const s of bObs) strictAssert.deepEqual(s, bSpan);
});
});
describe('enterWithContext', () => {
it('attaches the record to the current async scope', async () => {
await tcRun(
() => {
strictAssert.deepEqual(
decodeHeader(_currentRecordBytes()!).spanId,
SPAN_ID_BYTES,
);
const newSpan = bytesFromHex('aabbccddeeff0011');
tcEnter({traceId: TRACE_ID_BYTES, spanId: newSpan});
strictAssert.deepEqual(
decodeHeader(_currentRecordBytes()!).spanId,
newSpan,
);
return Promise.resolve().then(() => {
strictAssert.deepEqual(
decodeHeader(_currentRecordBytes()!).spanId,
newSpan,
);
});
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
strictAssert.equal(_currentRecordBytes(), undefined);
});
});
describe('clearContext', () => {
it('detaches the active record within a scope', () => {
tcRun(
() => {
strictAssert.ok(_currentRecordBytes());
clearContext();
strictAssert.equal(_currentRecordBytes(), undefined);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('drops the active record so getContext returns undefined', () => {
tcRun(
() => {
strictAssert.ok(getContext() !== undefined);
clearContext();
strictAssert.equal(getContext(), undefined);
strictAssert.equal(tcIsTruncated(), false);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('is idempotent (calling with no context or twice is a no-op)', () => {
clearContext();
strictAssert.equal(_currentRecordBytes(), undefined);
tcRun(
() => {
clearContext();
clearContext();
strictAssert.equal(_currentRecordBytes(), undefined);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('lets a nested runWithContext re-establish a record', () => {
tcRun(
() => {
clearContext();
const innerSpan = bytesFromHex('aabbccddeeff0011');
tcRun(
() => {
strictAssert.deepEqual(
decodeHeader(_currentRecordBytes()!).spanId,
innerSpan,
);
},
{traceId: TRACE_ID_BYTES, spanId: innerSpan},
);
// After the inner runWithContext returns, we're back to the
// post-clear state in the outer scope.
strictAssert.equal(_currentRecordBytes(), undefined);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('lets enterWithContext re-establish a record', () => {
tcRun(
() => {
clearContext();
const newSpan = bytesFromHex('aabbccddeeff0011');
tcEnter({traceId: TRACE_ID_BYTES, spanId: newSpan});
strictAssert.deepEqual(
decodeHeader(_currentRecordBytes()!).spanId,
newSpan,
);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
});
describe('appendAttributes', () => {
it('adds entries to the current record', () => {
tcRun(
() => {
strictAssert.deepEqual(decodeAttrs(_currentRecordBytes()!), [
'GET',
]);
tcAppend([, , '200']);
strictAssert.deepEqual(decodeAttrs(_currentRecordBytes()!), [
'GET',
,
'200',
]);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES, attributes: ['GET']},
);
});
it('writes in-place when bytes fit in the slack', () => {
tcRun(
() => {
const before = _currentRecordBytes()!;
tcAppend([, 'ab']);
const after = _currentRecordBytes()!;
strictAssert.deepEqual(decodeAttrs(after), ['xxx', 'ab']);
strictAssert.equal(after.length, before.length + 2 + 2);
strictAssert.deepEqual(after.slice(0, 26), before.slice(0, 26));
strictAssert.deepEqual(after.slice(28, 33), before.slice(28, 33));
strictAssert.equal(after[24], 1);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES, attributes: ['xxx']},
);
});
it('grows the record geometrically when slack runs out', () => {
tcRun(
() => {
const v = 'y'.repeat(60);
for (let i = 0; i < 8; i++) {
const append: Array<string | undefined> = [];
append[i] = v;
tcAppend(append);
}
const decoded = decodeAttrs(_currentRecordBytes()!);
for (let i = 0; i < 8; i++) {
strictAssert.equal(decoded[i], v, `slot ${i}`);
}
strictAssert.equal(
decodeHeader(_currentRecordBytes()!).attrsDataSize,
8 * 62,
);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('is a no-op when given an empty array', () => {
tcRun(
() => {
const before = _currentRecordBytes();
tcAppend([]);
const after = _currentRecordBytes();
strictAssert.deepEqual(after, before);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('is a no-op when all slots are null/undefined', () => {
tcRun(
() => {
const before = _currentRecordBytes();
tcAppend([null, undefined, , null]);
const after = _currentRecordBytes();
strictAssert.deepEqual(after, before);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('silently drops entries past the 612-byte cap and sets the truncated flag', () => {
const big = 'a'.repeat(255);
tcRun(
() => {
tcAppend([big, big]);
strictAssert.equal(tcIsTruncated(), false);
tcAppend([, , big]);
strictAssert.equal(tcIsTruncated(), true);
strictAssert.equal(
decodeHeader(_currentRecordBytes()!).attrsDataSize,
514,
);
const small = 'x'.repeat(30);
tcAppend([, , , small]);
const decoded = decodeAttrs(_currentRecordBytes()!);
strictAssert.equal(decoded[0], big);
strictAssert.equal(decoded[1], big);
strictAssert.equal(decoded[2], undefined);
strictAssert.equal(decoded[3], small);
strictAssert.equal(tcIsTruncated(), true);
},
{traceId: TRACE_ID_BYTES, spanId: SPAN_ID_BYTES},
);
});
it('propagates through async continuations', async () => {
await tcRun(
async () => {
tcAppend([, 'after-await']);
await Promise.resolve();
strictAssert.deepEqual(decodeAttrs(_currentRecordBytes()!), [
'before',
'after-await',
]);
},
{
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: ['before'],
},
);
});
});
describe('isContextTruncated', () => {
it('returns false outside a context', () => {
strictAssert.equal(tcIsTruncated(), false);
});
it('returns false for a non-truncated record', () => {
tcRun(
() => {
strictAssert.equal(tcIsTruncated(), false);
},
{
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: ['GET', '/x'],
},
);
});
it('reflects appended-then-overflowed entries', () => {
tcRun(
() => {
strictAssert.equal(tcIsTruncated(), false);
tcAppend([
,
,
'c'.repeat(255),
,
,
'd'.repeat(255),
,
,
'e'.repeat(255),
]);
strictAssert.equal(tcIsTruncated(), true);
},
{
traceId: TRACE_ID_BYTES,
spanId: SPAN_ID_BYTES,
attributes: ['a', 'b'],
},
);
});
});
describe('invalidate', () => {
it('flips the record valid byte to 0 in place', () => {
// Verified through the shared record: same ThreadContext reference
// observed by any async-context frame that inherits it sees the
// new valid=0 the moment we call invalidate() on any of them.
const ctx = new ThreadContext(TRACE_ID_BYTES, SPAN_ID_BYTES);
ctx.run(() => {
strictAssert.equal(decodeHeader(_currentRecordBytes()!).valid, 1);
ctx.invalidate();
strictAssert.equal(decodeHeader(_currentRecordBytes()!).valid, 0);
});
});
it('is idempotent', () => {
const ctx = new ThreadContext(TRACE_ID_BYTES, SPAN_ID_BYTES);
ctx.run(() => {
ctx.invalidate();
ctx.invalidate();
strictAssert.equal(decodeHeader(_currentRecordBytes()!).valid, 0);
});
});
it('appendAttributes after invalidate mutates attrs_data but leaves valid=0', () => {
// valid is a separate byte from attrs_data — an invalidated record
// can still grow via appendAttributes; readers MUST honor
// valid==0 and ignore the record regardless.
const ctx = new ThreadContext(TRACE_ID_BYTES, SPAN_ID_BYTES);
ctx.run(() => {
ctx.invalidate();
ctx.appendAttributes([, 'late']);
const hdr = decodeHeader(_currentRecordBytes()!);
strictAssert.equal(hdr.valid, 0);
strictAssert.equal(hdr.attrsDataSize, 6); // key(1) + len(1) + 'late'(4)
});
});
});
describe('getProcessContextAttributes', () => {
it('rejects non-array keys', () => {
strictAssert.throws(
() => getProcessContextAttributes({} as unknown as string[]),
/must be an array/,
);
});
it('rejects more than 256 keys', () => {
const tooMany = Array.from({length: 257}, (_, i) => `k${i}`);
strictAssert.throws(
() => getProcessContextAttributes(tooMany),
/exceeds 256/,
);
});
it('rejects duplicate names', () => {
strictAssert.throws(
() => getProcessContextAttributes(['x', 'y', 'x']),
/duplicate key name/,
);
});
it('rejects non-string entries', () => {
strictAssert.throws(
() => getProcessContextAttributes(['ok', 42 as unknown as string]),
/must be a string/,
);
});
it('returns the expected shape', () => {
const keys = ['http.method', 'http.route', 'user.id'];
const pca = getProcessContextAttributes(keys);
strictAssert.equal(pca['threadlocal.schema_version'], 'nodejs_v1_dev');
strictAssert.deepEqual(pca['threadlocal.attribute_key_map'], keys);
strictAssert.equal(pca['threadlocal.wrapped_object_offset'], 24);
strictAssert.equal(pca['threadlocal.tagged_size'], 8);
strictAssert.equal(pca['threadlocal.native_wrap_fields_offset'], 24);
strictAssert.equal(pca['threadlocal.js_map_table_offset'], 0x18);
strictAssert.equal(
pca['threadlocal.ordered_hash_map_header_size'],
0x10,
);
strictAssert.deepEqual(Object.keys(pca).sort(), [
'threadlocal.attribute_key_map',
'threadlocal.js_map_table_offset',
'threadlocal.native_wrap_fields_offset',
'threadlocal.ordered_hash_map_header_size',
'threadlocal.schema_version',
'threadlocal.tagged_size',
'threadlocal.wrapped_object_offset',
]);
});
it('is frozen and a defensive copy', () => {
const keys = ['http.method', 'http.route'];
const pca = getProcessContextAttributes(keys);
strictAssert.ok(Object.isFrozen(pca));
strictAssert.ok(Object.isFrozen(pca['threadlocal.attribute_key_map']));
keys.push('mutated.after');
strictAssert.deepEqual(pca['threadlocal.attribute_key_map'], [
'http.method',
'http.route',
]);
strictAssert.throws(() => {
(pca as unknown as Record<string, string>)[
'threadlocal.schema_version'
] = 'tampered';
}, /read-only|read only|TypeError/i);
});
});
describe('discovery contract', () => {
it('exports otel_thread_ctx_nodejs_v1 as a TLS dynsym', function () {
const addon = join(
__dirname,
'..',
'..',
'build',
'Release',
'dd_pprof.node',
);
// The prebuild-install / node-gyp-build CI matrix runs against a
// prebuilt binary that lives outside build/Release; only the
// build-from-source path produces this exact file.
if (!existsSync(addon)) {
this.skip();
}
const r = spawnSync('readelf', ['--dyn-syms', '--wide', addon], {
encoding: 'utf8',
});
if (r.error && (r.error as NodeJS.ErrnoException).code === 'ENOENT') {
this.skip();
}
strictAssert.equal(r.status, 0, `readelf failed: ${r.stderr}`);
const line = r.stdout
.split('\n')
.find(l => /\sotel_thread_ctx_nodejs_v1$/.test(l));
assert.ok(
line,
'otel_thread_ctx_nodejs_v1 not present in dynamic symbol table',
);
assert.match(
line!,
/\bTLS\b/,
`expected TLS type, got: ${line!.trim()}`,
);
assert.match(
line!,
/\bGLOBAL\b/,
`expected GLOBAL binding, got: ${line!.trim()}`,
);
assert.match(
line!,
/\bDEFAULT\b/,
`expected DEFAULT visibility, got: ${line!.trim()}`,
);
});
});
},
);