@encore.dev/sdk 0.0.0 → 2.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/LICENSE +362 -0
  2. package/README.md +122 -2
  3. package/app_meta.test.ts +134 -0
  4. package/app_meta.ts +186 -0
  5. package/config/config.test.ts +381 -0
  6. package/config/config.ts +178 -0
  7. package/config/mod.ts +14 -0
  8. package/config/secrets.ts +147 -0
  9. package/config/value.ts +243 -0
  10. package/cron/mod.ts +23 -0
  11. package/dist/app_meta.d.ts +93 -0
  12. package/dist/app_meta.js +65 -0
  13. package/dist/app_meta.js.map +1 -0
  14. package/dist/config/config.d.ts +105 -0
  15. package/dist/config/config.js +87 -0
  16. package/dist/config/config.js.map +1 -0
  17. package/dist/config/mod.d.ts +4 -0
  18. package/dist/config/mod.js +3 -0
  19. package/dist/config/mod.js.map +1 -0
  20. package/dist/config/secrets.d.ts +92 -0
  21. package/dist/config/secrets.js +80 -0
  22. package/dist/config/secrets.js.map +1 -0
  23. package/dist/config/value.d.ts +51 -0
  24. package/dist/config/value.js +178 -0
  25. package/dist/config/value.js.map +1 -0
  26. package/dist/cron/mod.d.ts +22 -0
  27. package/dist/cron/mod.js +9 -0
  28. package/dist/cron/mod.js.map +1 -0
  29. package/dist/internal/otel/backend.d.ts +50 -0
  30. package/dist/internal/otel/backend.js +2 -0
  31. package/dist/internal/otel/backend.js.map +1 -0
  32. package/dist/internal/otel/context.d.ts +10 -0
  33. package/dist/internal/otel/context.js +34 -0
  34. package/dist/internal/otel/context.js.map +1 -0
  35. package/dist/internal/otel/context_manager.d.ts +22 -0
  36. package/dist/internal/otel/context_manager.js +120 -0
  37. package/dist/internal/otel/context_manager.js.map +1 -0
  38. package/dist/internal/otel/encode.d.ts +112 -0
  39. package/dist/internal/otel/encode.js +290 -0
  40. package/dist/internal/otel/encode.js.map +1 -0
  41. package/dist/internal/otel/index.d.ts +9 -0
  42. package/dist/internal/otel/index.js +9 -0
  43. package/dist/internal/otel/index.js.map +1 -0
  44. package/dist/internal/otel/meter.d.ts +73 -0
  45. package/dist/internal/otel/meter.js +265 -0
  46. package/dist/internal/otel/meter.js.map +1 -0
  47. package/dist/internal/otel/propagator.d.ts +14 -0
  48. package/dist/internal/otel/propagator.js +61 -0
  49. package/dist/internal/otel/propagator.js.map +1 -0
  50. package/dist/internal/otel/provider.d.ts +9 -0
  51. package/dist/internal/otel/provider.js +19 -0
  52. package/dist/internal/otel/provider.js.map +1 -0
  53. package/dist/internal/otel/request_context.d.ts +11 -0
  54. package/dist/internal/otel/request_context.js +20 -0
  55. package/dist/internal/otel/request_context.js.map +1 -0
  56. package/dist/internal/otel/span.d.ts +61 -0
  57. package/dist/internal/otel/span.js +206 -0
  58. package/dist/internal/otel/span.js.map +1 -0
  59. package/dist/internal/otel/tracer.d.ts +15 -0
  60. package/dist/internal/otel/tracer.js +65 -0
  61. package/dist/internal/otel/tracer.js.map +1 -0
  62. package/dist/internal/reqtrack/mod.d.ts +6 -0
  63. package/dist/internal/reqtrack/mod.js +28 -0
  64. package/dist/internal/reqtrack/mod.js.map +1 -0
  65. package/dist/internal/runtime/meter.d.ts +11 -0
  66. package/dist/internal/runtime/meter.js +22 -0
  67. package/dist/internal/runtime/meter.js.map +1 -0
  68. package/dist/internal/runtime/mod.d.ts +12 -0
  69. package/dist/internal/runtime/mod.js +28 -0
  70. package/dist/internal/runtime/mod.js.map +1 -0
  71. package/dist/internal/runtime/napi/napi.cjs +122 -0
  72. package/dist/internal/runtime/napi/napi.d.cts +601 -0
  73. package/dist/internal/runtime/shutdown.d.ts +13 -0
  74. package/dist/internal/runtime/shutdown.js +56 -0
  75. package/dist/internal/runtime/shutdown.js.map +1 -0
  76. package/dist/internal/utils/constraints.d.ts +9 -0
  77. package/dist/internal/utils/constraints.js +2 -0
  78. package/dist/internal/utils/constraints.js.map +1 -0
  79. package/dist/log/index.d.ts +39 -0
  80. package/dist/log/index.js +44 -0
  81. package/dist/log/index.js.map +1 -0
  82. package/dist/log/logger.d.ts +123 -0
  83. package/dist/log/logger.js +203 -0
  84. package/dist/log/logger.js.map +1 -0
  85. package/dist/log/runtime.d.ts +19 -0
  86. package/dist/log/runtime.js +22 -0
  87. package/dist/log/runtime.js.map +1 -0
  88. package/dist/log/stderr.d.ts +9 -0
  89. package/dist/log/stderr.js +25 -0
  90. package/dist/log/stderr.js.map +1 -0
  91. package/dist/metrics/mod.d.ts +315 -0
  92. package/dist/metrics/mod.js +488 -0
  93. package/dist/metrics/mod.js.map +1 -0
  94. package/dist/mod.d.ts +6 -0
  95. package/dist/mod.js +4 -0
  96. package/dist/mod.js.map +1 -0
  97. package/dist/otel.d.ts +9 -0
  98. package/dist/otel.js +13 -0
  99. package/dist/otel.js.map +1 -0
  100. package/dist/pubsub/encoding.d.ts +3 -0
  101. package/dist/pubsub/encoding.js +10 -0
  102. package/dist/pubsub/encoding.js.map +1 -0
  103. package/dist/pubsub/mod.d.ts +6 -0
  104. package/dist/pubsub/mod.js +3 -0
  105. package/dist/pubsub/mod.js.map +1 -0
  106. package/dist/pubsub/refs.d.ts +12 -0
  107. package/dist/pubsub/refs.js +11 -0
  108. package/dist/pubsub/refs.js.map +1 -0
  109. package/dist/pubsub/subscription.d.ts +128 -0
  110. package/dist/pubsub/subscription.js +39 -0
  111. package/dist/pubsub/subscription.js.map +1 -0
  112. package/dist/pubsub/topic.d.ts +148 -0
  113. package/dist/pubsub/topic.js +164 -0
  114. package/dist/pubsub/topic.js.map +1 -0
  115. package/dist/req_meta.d.ts +47 -0
  116. package/dist/req_meta.js +26 -0
  117. package/dist/req_meta.js.map +1 -0
  118. package/dist/services/index.d.ts +12 -0
  119. package/dist/services/index.js +22 -0
  120. package/dist/services/index.js.map +1 -0
  121. package/dist/shutdown/mod.d.ts +23 -0
  122. package/dist/shutdown/mod.js +24 -0
  123. package/dist/shutdown/mod.js.map +1 -0
  124. package/dist/storage/objects/bucket.d.ts +216 -0
  125. package/dist/storage/objects/bucket.js +123 -0
  126. package/dist/storage/objects/bucket.js.map +1 -0
  127. package/dist/storage/objects/error.d.ts +14 -0
  128. package/dist/storage/objects/error.js +81 -0
  129. package/dist/storage/objects/error.js.map +1 -0
  130. package/dist/storage/objects/mod.d.ts +4 -0
  131. package/dist/storage/objects/mod.js +3 -0
  132. package/dist/storage/objects/mod.js.map +1 -0
  133. package/dist/storage/objects/refs.d.ts +31 -0
  134. package/dist/storage/objects/refs.js +20 -0
  135. package/dist/storage/objects/refs.js.map +1 -0
  136. package/dist/storage/postgres/database.d.ts +295 -0
  137. package/dist/storage/postgres/database.js +378 -0
  138. package/dist/storage/postgres/database.js.map +1 -0
  139. package/dist/storage/postgres/mod.d.ts +2 -0
  140. package/dist/storage/postgres/mod.js +2 -0
  141. package/dist/storage/postgres/mod.js.map +1 -0
  142. package/dist/storage/redis/commands.d.ts +573 -0
  143. package/dist/storage/redis/commands.js +637 -0
  144. package/dist/storage/redis/commands.js.map +1 -0
  145. package/dist/storage/redis/database.d.ts +302 -0
  146. package/dist/storage/redis/database.js +336 -0
  147. package/dist/storage/redis/database.js.map +1 -0
  148. package/dist/storage/redis/mod.d.ts +88 -0
  149. package/dist/storage/redis/mod.js +84 -0
  150. package/dist/storage/redis/mod.js.map +1 -0
  151. package/dist/storage/redis/native.d.ts +8 -0
  152. package/dist/storage/redis/native.js +11 -0
  153. package/dist/storage/redis/native.js.map +1 -0
  154. package/dist/storage/redis/options.d.ts +89 -0
  155. package/dist/storage/redis/options.js +53 -0
  156. package/dist/storage/redis/options.js.map +1 -0
  157. package/dist/storage/redis/pubsub.d.ts +53 -0
  158. package/dist/storage/redis/pubsub.js +88 -0
  159. package/dist/storage/redis/pubsub.js.map +1 -0
  160. package/dist/storage/redis/reply.d.ts +256 -0
  161. package/dist/storage/redis/reply.js +572 -0
  162. package/dist/storage/redis/reply.js.map +1 -0
  163. package/dist/storage/redis/scan.d.ts +11 -0
  164. package/dist/storage/redis/scan.js +76 -0
  165. package/dist/storage/redis/scan.js.map +1 -0
  166. package/dist/storage/redis/script.d.ts +91 -0
  167. package/dist/storage/redis/script.js +143 -0
  168. package/dist/storage/redis/script.js.map +1 -0
  169. package/dist/storage/redis/target.d.ts +47 -0
  170. package/dist/storage/redis/target.js +82 -0
  171. package/dist/storage/redis/target.js.map +1 -0
  172. package/dist/storage/redis/wire.d.ts +105 -0
  173. package/dist/storage/redis/wire.js +333 -0
  174. package/dist/storage/redis/wire.js.map +1 -0
  175. package/dist/tsconfig.build.tsbuildinfo +1 -0
  176. package/dist/types/mod.d.ts +42 -0
  177. package/dist/types/mod.js +65 -0
  178. package/dist/types/mod.js.map +1 -0
  179. package/internal/otel/backend.ts +60 -0
  180. package/internal/otel/context.test.ts +70 -0
  181. package/internal/otel/context.ts +48 -0
  182. package/internal/otel/context_manager.test.ts +154 -0
  183. package/internal/otel/context_manager.ts +141 -0
  184. package/internal/otel/encode.test.ts +266 -0
  185. package/internal/otel/encode.ts +408 -0
  186. package/internal/otel/index.ts +20 -0
  187. package/internal/otel/meter.test.ts +231 -0
  188. package/internal/otel/meter.ts +332 -0
  189. package/internal/otel/propagator.test.ts +105 -0
  190. package/internal/otel/propagator.ts +68 -0
  191. package/internal/otel/provider.ts +23 -0
  192. package/internal/otel/request_context.ts +32 -0
  193. package/internal/otel/span.ts +252 -0
  194. package/internal/otel/tracer.test.ts +352 -0
  195. package/internal/otel/tracer.ts +104 -0
  196. package/internal/reqtrack/mod.ts +39 -0
  197. package/internal/runtime/meter.ts +26 -0
  198. package/internal/runtime/mod.ts +41 -0
  199. package/internal/runtime/napi/napi.cjs +122 -0
  200. package/internal/runtime/napi/napi.d.cts +601 -0
  201. package/internal/runtime/shutdown.test.ts +248 -0
  202. package/internal/runtime/shutdown.ts +64 -0
  203. package/internal/utils/constraints.ts +12 -0
  204. package/log/index.ts +107 -0
  205. package/log/logger.test.ts +194 -0
  206. package/log/logger.ts +308 -0
  207. package/log/runtime.test.ts +65 -0
  208. package/log/runtime.ts +40 -0
  209. package/log/stderr.test.ts +23 -0
  210. package/log/stderr.ts +24 -0
  211. package/metrics/export.test.ts +337 -0
  212. package/metrics/mod.test.ts +180 -0
  213. package/metrics/mod.ts +619 -0
  214. package/mod.ts +22 -0
  215. package/otel.test.ts +84 -0
  216. package/otel.ts +17 -0
  217. package/package.json +121 -5
  218. package/pubsub/encoding.ts +8 -0
  219. package/pubsub/mod.ts +14 -0
  220. package/pubsub/pubsub.test.ts +186 -0
  221. package/pubsub/refs.ts +22 -0
  222. package/pubsub/subscription.ts +180 -0
  223. package/pubsub/topic.test.ts +121 -0
  224. package/pubsub/topic.ts +212 -0
  225. package/req_meta.ts +75 -0
  226. package/services/index.test.ts +30 -0
  227. package/services/index.ts +21 -0
  228. package/shutdown/mod.ts +24 -0
  229. package/storage/objects/bucket.ts +338 -0
  230. package/storage/objects/error.ts +94 -0
  231. package/storage/objects/mod.ts +35 -0
  232. package/storage/objects/refs.ts +69 -0
  233. package/storage/postgres/database.integration.test.ts +175 -0
  234. package/storage/postgres/database.test.ts +241 -0
  235. package/storage/postgres/database.ts +497 -0
  236. package/storage/postgres/mod.ts +15 -0
  237. package/storage/redis/commands.ts +1221 -0
  238. package/storage/redis/database.ts +466 -0
  239. package/storage/redis/mod.ts +135 -0
  240. package/storage/redis/native.ts +11 -0
  241. package/storage/redis/options.ts +119 -0
  242. package/storage/redis/pubsub.ts +92 -0
  243. package/storage/redis/redis.test.ts +706 -0
  244. package/storage/redis/reply.ts +705 -0
  245. package/storage/redis/runtime.test.ts +233 -0
  246. package/storage/redis/scan.ts +125 -0
  247. package/storage/redis/script.ts +162 -0
  248. package/storage/redis/target.ts +131 -0
  249. package/storage/redis/wire.ts +369 -0
  250. package/types/mod.ts +92 -0
@@ -0,0 +1,70 @@
1
+ import {beforeAll, expect, test} from 'bun:test';
2
+ import {
3
+ context,
4
+ ROOT_CONTEXT,
5
+ trace,
6
+ TraceFlags,
7
+ type Span as ApiSpan,
8
+ } from '@opentelemetry/api';
9
+ import type {Backend} from './backend';
10
+ import {activeContext, withContext} from './context';
11
+ import {TracerProvider} from './provider';
12
+
13
+ /** Span id n = 00..0n; a child keeps its parent's trace id. */
14
+ class FakeBackend implements Backend {
15
+ n = 0;
16
+ parents: (Buffer | undefined)[] = [];
17
+
18
+ startSpan(name: string, kind: number, parent: Buffer | undefined) {
19
+ this.parents.push(parent);
20
+ const ctx = Buffer.alloc(25);
21
+ if (parent) parent.copy(ctx, 0, 0, 16);
22
+ else ctx.fill(0xaa, 0, 16);
23
+ ctx[23] = ++this.n;
24
+ ctx[24] = 1;
25
+ return {ctx, tracestate: '', startUnixNanos: 1000n, startMonoNanos: 7n};
26
+ }
27
+
28
+ endSpan() {}
29
+ }
30
+
31
+ const REQUEST = {
32
+ traceId: '0af7651916cd43dd8448eb211c80319c',
33
+ spanId: 'b7ad6b7169203331',
34
+ traceFlags: TraceFlags.SAMPLED,
35
+ };
36
+
37
+ // Encore's context manager is not the global, and no other is.
38
+ beforeAll(() => context.disable());
39
+
40
+ test('a span in an Encore context is a child of its span', () => {
41
+ const backend = new FakeBackend();
42
+ const tracer = new TracerProvider(backend).getTracer('t');
43
+ const request = trace.setSpanContext(ROOT_CONTEXT, REQUEST);
44
+ withContext(request, () => {
45
+ tracer.startSpan('child').end();
46
+ tracer.startActiveSpan('active', (span: ApiSpan) => span.end());
47
+ });
48
+ expect(backend.parents.map(p => p?.toString('hex', 0, 24))).toEqual([
49
+ REQUEST.traceId + REQUEST.spanId,
50
+ REQUEST.traceId + REQUEST.spanId,
51
+ ]);
52
+ });
53
+
54
+ test("an active span is active in Encore's context", () => {
55
+ const backend = new FakeBackend();
56
+ const tracer = new TracerProvider(backend).getTracer('t');
57
+ const request = trace.setSpanContext(ROOT_CONTEXT, REQUEST);
58
+ withContext(request, () =>
59
+ tracer.startActiveSpan('active', (span: ApiSpan) => {
60
+ expect(trace.getSpan(activeContext())?.spanContext().spanId).toBe(
61
+ span.spanContext().spanId,
62
+ );
63
+ tracer.startSpan('grandchild').end();
64
+ expect(backend.parents[1]?.toString('hex', 16, 24)).toBe(
65
+ span.spanContext().spanId,
66
+ );
67
+ span.end();
68
+ }),
69
+ );
70
+ });
@@ -0,0 +1,48 @@
1
+ import {
2
+ context,
3
+ createContextKey,
4
+ ROOT_CONTEXT,
5
+ type Context,
6
+ } from '@opentelemetry/api';
7
+ import {ContextManager} from './context_manager';
8
+
9
+ /** Encore's context manager. Without a global one, Encore's own requests
10
+ * are tracked in it, so infra calls, logs, and exemplars still see them. */
11
+ const manager = new ContextManager();
12
+ let isGlobal = false;
13
+
14
+ const PROBE = createContextKey('encore.context-manager-probe');
15
+
16
+ /** Whether this thread's OTel API has a context manager: the API's no-op
17
+ * default keeps no context. */
18
+ function hasContextManager(): boolean {
19
+ return (
20
+ context.with(ROOT_CONTEXT.setValue(PROBE, true), () =>
21
+ context.active().getValue(PROBE),
22
+ ) === true
23
+ );
24
+ }
25
+
26
+ /** Registers Encore's context manager as this thread's OTel API global,
27
+ * unless another is registered. Returns whether Encore's is the global. */
28
+ export function installContextManager(): boolean {
29
+ if (!isGlobal && !hasContextManager()) {
30
+ isGlobal = context.setGlobalContextManager(manager);
31
+ }
32
+ return isGlobal;
33
+ }
34
+
35
+ /** The active context: the global context manager's, falling back to
36
+ * Encore's own when the global has none. */
37
+ export function activeContext(): Context {
38
+ const ctx = context.active();
39
+ return isGlobal || ctx !== ROOT_CONTEXT ? ctx : manager.active();
40
+ }
41
+
42
+ /** Runs `fn` with `ctx` active, in Encore's context manager too when it is
43
+ * not the global. */
44
+ export function withContext<T>(ctx: Context, fn: () => T): T {
45
+ return isGlobal
46
+ ? context.with(ctx, fn)
47
+ : context.with(ctx, () => manager.with(ctx, fn));
48
+ }
@@ -0,0 +1,154 @@
1
+ import {describe, expect, test} from 'bun:test';
2
+ import {createContextKey, ROOT_CONTEXT} from '@opentelemetry/api';
3
+ import {EventEmitter} from 'node:events';
4
+ import {ContextManager} from './context_manager';
5
+
6
+ const KEY = createContextKey('k');
7
+
8
+ describe('ContextManager', () => {
9
+ const mgr = new ContextManager();
10
+ const get = () => mgr.active().getValue(KEY);
11
+
12
+ test('root outside any scope', () => {
13
+ expect(mgr.active()).toBe(ROOT_CONTEXT);
14
+ });
15
+
16
+ test("with returns the callback's value and restores the outer context", () => {
17
+ const ctx = ROOT_CONTEXT.setValue(KEY, 1);
18
+ expect(mgr.with(ctx, get)).toBe(1);
19
+ expect(mgr.active()).toBe(ROOT_CONTEXT);
20
+ });
21
+
22
+ test('survives await', async () => {
23
+ const got = await mgr.with(ROOT_CONTEXT.setValue(KEY, 'a'), async () => {
24
+ await Promise.resolve();
25
+ await new Promise(r => setImmediate(r));
26
+ return get();
27
+ });
28
+ expect(got).toBe('a');
29
+ });
30
+
31
+ test('survives setTimeout', async () => {
32
+ const got = await mgr.with(
33
+ ROOT_CONTEXT.setValue(KEY, 't'),
34
+ () => new Promise(resolve => setTimeout(() => resolve(get()), 1)),
35
+ );
36
+ expect(got).toBe('t');
37
+ });
38
+
39
+ test('Promise.all branches keep their own contexts', async () => {
40
+ const branch = (v: string, ms: number) =>
41
+ mgr.with(ROOT_CONTEXT.setValue(KEY, v), async () => {
42
+ await new Promise(r => setTimeout(r, ms));
43
+ return get();
44
+ });
45
+ expect(await Promise.all([branch('x', 5), branch('y', 1)])).toEqual([
46
+ 'x',
47
+ 'y',
48
+ ]);
49
+ });
50
+
51
+ test('nested with', async () => {
52
+ const seen = await mgr.with(
53
+ ROOT_CONTEXT.setValue(KEY, 'outer'),
54
+ async () => {
55
+ const inner = await mgr.with(
56
+ mgr.active().setValue(KEY, 'inner'),
57
+ async () => {
58
+ await new Promise(r => setTimeout(r, 1));
59
+ return get();
60
+ },
61
+ );
62
+ return [inner, get()];
63
+ },
64
+ );
65
+ expect(seen).toEqual(['inner', 'outer']);
66
+ });
67
+
68
+ test('with passes thisArg and args', () => {
69
+ const self = {n: 2};
70
+ const got = mgr.with(
71
+ ROOT_CONTEXT,
72
+ function (this: typeof self, x: number) {
73
+ return this.n * x;
74
+ },
75
+ self,
76
+ 3,
77
+ );
78
+ expect(got).toBe(6);
79
+ });
80
+
81
+ test('bind runs a function in the bound context', () => {
82
+ const ctx = ROOT_CONTEXT.setValue(KEY, 'bound');
83
+ const fn = mgr.bind(ctx, (x: number) => [x, get()]);
84
+ expect(fn.length).toBe(1);
85
+ expect(fn(1)).toEqual([1, 'bound']);
86
+ expect(mgr.with(ROOT_CONTEXT.setValue(KEY, 'other'), () => fn(2))).toEqual([
87
+ 2,
88
+ 'bound',
89
+ ]);
90
+ });
91
+
92
+ test('bind runs EventEmitter listeners in the bound context', () => {
93
+ const ee = new EventEmitter();
94
+ expect(mgr.bind(ROOT_CONTEXT.setValue(KEY, 'ee'), ee)).toBe(ee);
95
+ const seen: unknown[] = [];
96
+ mgr.with(ROOT_CONTEXT.setValue(KEY, 'other'), () => {
97
+ ee.on('a', () => seen.push(['on', get()]));
98
+ ee.once('a', () => seen.push(['once', get()]));
99
+ ee.prependListener('a', () => seen.push(['prepend', get()]));
100
+ });
101
+ ee.emit('a');
102
+ ee.emit('a');
103
+ expect(seen).toEqual([
104
+ ['prepend', 'ee'],
105
+ ['on', 'ee'],
106
+ ['once', 'ee'],
107
+ ['prepend', 'ee'],
108
+ ['on', 'ee'],
109
+ ]);
110
+ });
111
+
112
+ test('removeListener and off remove bound listeners', () => {
113
+ const ee = mgr.bind(ROOT_CONTEXT.setValue(KEY, 'ee'), new EventEmitter());
114
+ const calls: string[] = [];
115
+ const a = () => calls.push('a');
116
+ const b = () => calls.push('b');
117
+ const c = () => calls.push('c');
118
+ ee.on('x', a);
119
+ ee.once('x', b);
120
+ ee.on('x', c);
121
+ ee.removeListener('x', a);
122
+ ee.off('x', b);
123
+ ee.emit('x');
124
+ expect(calls).toEqual(['c']);
125
+ expect(ee.listenerCount('x')).toBe(1);
126
+ });
127
+
128
+ test('removeAllListeners on a bound emitter', () => {
129
+ const ee = mgr.bind(ROOT_CONTEXT, new EventEmitter());
130
+ const f = () => {};
131
+ ee.on('x', f);
132
+ ee.on('y', f);
133
+ ee.removeAllListeners('x');
134
+ expect(ee.listenerCount('x')).toBe(0);
135
+ expect(ee.listenerCount('y')).toBe(1);
136
+ ee.removeAllListeners();
137
+ expect(ee.listenerCount('y')).toBe(0);
138
+ });
139
+
140
+ test('binding an emitter twice keeps the first context', () => {
141
+ const ee = new EventEmitter();
142
+ mgr.bind(ROOT_CONTEXT.setValue(KEY, 1), ee);
143
+ mgr.bind(ROOT_CONTEXT.setValue(KEY, 2), ee);
144
+ let seen: unknown;
145
+ ee.on('x', () => (seen = get()));
146
+ ee.emit('x');
147
+ expect(seen).toBe(1);
148
+ });
149
+
150
+ test('bind returns non-functions unchanged', () => {
151
+ const obj = {a: 1};
152
+ expect(mgr.bind(ROOT_CONTEXT, obj)).toBe(obj);
153
+ });
154
+ });
@@ -0,0 +1,141 @@
1
+ import {AsyncLocalStorage} from 'node:async_hooks';
2
+ import {EventEmitter} from 'node:events';
3
+ import {
4
+ ROOT_CONTEXT,
5
+ type Context,
6
+ type ContextManager as ApiContextManager,
7
+ } from '@opentelemetry/api';
8
+
9
+ type Listener = (...args: unknown[]) => unknown;
10
+ type Event = string | symbol;
11
+ /** Per event, each listener's bound wrapper. */
12
+ type PatchMap = Map<Event, WeakMap<Listener, Listener>>;
13
+
14
+ const ADD_LISTENER_METHODS = [
15
+ 'addListener',
16
+ 'on',
17
+ 'once',
18
+ 'prependListener',
19
+ 'prependOnceListener',
20
+ ] as const;
21
+ const REMOVE_LISTENER_METHODS = ['removeListener', 'off'] as const;
22
+
23
+ /** OTel context on `AsyncLocalStorage`: follows `await`, timers, and
24
+ * callbacks. */
25
+ export class ContextManager implements ApiContextManager {
26
+ private als = new AsyncLocalStorage<Context>();
27
+ /** Bound emitters' patched listeners. */
28
+ private patched = new WeakMap<EventEmitter, PatchMap>();
29
+ /** Set while a patched add method runs, so one that calls another (`once`
30
+ * calls `on`) binds the listener once. */
31
+ private adding = false;
32
+
33
+ active(): Context {
34
+ return this.als.getStore() ?? ROOT_CONTEXT;
35
+ }
36
+
37
+ with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(
38
+ ctx: Context,
39
+ fn: F,
40
+ thisArg?: ThisParameterType<F>,
41
+ ...args: A
42
+ ): ReturnType<F> {
43
+ const cb = thisArg == null ? fn : fn.bind(thisArg);
44
+ return this.als.run(ctx, cb as never, ...args) as ReturnType<F>;
45
+ }
46
+
47
+ /** Binds a function, or an `EventEmitter`'s listeners added from now
48
+ * on, to `ctx`. An emitter keeps the context it was first bound to. */
49
+ bind<T>(ctx: Context, target: T): T {
50
+ if (target instanceof EventEmitter) {
51
+ this.bindEmitter(ctx, target);
52
+ return target;
53
+ }
54
+ if (typeof target !== 'function') return target;
55
+ // Preserve the manager while the wrapper receives the caller's dynamic this.
56
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
57
+ const manager = this;
58
+ const fn = target as unknown as Listener;
59
+ const bound = function (this: unknown, ...args: unknown[]) {
60
+ return manager.with(ctx, () => fn.apply(this, args));
61
+ };
62
+ Object.defineProperty(bound, 'length', {value: fn.length});
63
+ return bound as unknown as T;
64
+ }
65
+
66
+ private bindEmitter(ctx: Context, ee: EventEmitter) {
67
+ if (this.patched.has(ee)) return;
68
+ this.patched.set(ee, new Map());
69
+ const e = ee as unknown as Record<string, unknown>;
70
+ for (const name of ADD_LISTENER_METHODS) {
71
+ if (typeof e[name] === 'function') {
72
+ e[name] = this.patchAdd(ee, e[name] as Listener, ctx);
73
+ }
74
+ }
75
+ for (const name of REMOVE_LISTENER_METHODS) {
76
+ if (typeof e[name] === 'function') {
77
+ e[name] = this.patchRemove(ee, e[name] as Listener);
78
+ }
79
+ }
80
+ if (typeof ee.removeAllListeners === 'function') {
81
+ e.removeAllListeners = this.patchRemoveAll(
82
+ ee,
83
+ ee.removeAllListeners as Listener,
84
+ );
85
+ }
86
+ }
87
+
88
+ private patchAdd(ee: EventEmitter, original: Listener, ctx: Context) {
89
+ // Preserve the manager while the wrapper receives the caller's dynamic this.
90
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
91
+ const manager = this;
92
+ return function (this: unknown, event: Event, listener: Listener) {
93
+ if (manager.adding) return original.call(this, event, listener);
94
+ const map = manager.patched.get(ee)!;
95
+ let listeners = map.get(event);
96
+ if (listeners === undefined) {
97
+ listeners = new WeakMap();
98
+ map.set(event, listeners);
99
+ }
100
+ const bound = manager.bind(ctx, listener);
101
+ listeners.set(listener, bound);
102
+ manager.adding = true;
103
+ try {
104
+ return original.call(this, event, bound);
105
+ } finally {
106
+ manager.adding = false;
107
+ }
108
+ };
109
+ }
110
+
111
+ private patchRemove(ee: EventEmitter, original: Listener) {
112
+ // Preserve the manager while the wrapper receives the caller's dynamic this.
113
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
114
+ const manager = this;
115
+ return function (this: unknown, event: Event, listener: Listener) {
116
+ const bound = manager.patched.get(ee)?.get(event)?.get(listener);
117
+ return original.call(this, event, bound ?? listener);
118
+ };
119
+ }
120
+
121
+ private patchRemoveAll(ee: EventEmitter, original: Listener) {
122
+ // Preserve the manager while the wrapper receives the caller's dynamic this.
123
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
124
+ const manager = this;
125
+ return function (this: unknown, ...args: unknown[]) {
126
+ const map = manager.patched.get(ee);
127
+ if (args.length === 0) map?.clear();
128
+ else map?.delete(args[0] as Event);
129
+ return original.apply(this, args);
130
+ };
131
+ }
132
+
133
+ enable(): this {
134
+ return this;
135
+ }
136
+
137
+ disable(): this {
138
+ this.als.disable();
139
+ return this;
140
+ }
141
+ }
@@ -0,0 +1,266 @@
1
+ // Golden fixture `crates/encore_telemetry/src/testdata/golden.hex`: lowercase hex of
2
+ // `encodeEnd(golden)`, one line, trailing newline. `UPDATE_GOLDEN=1`
3
+ // rewrites it. Decoded by a Rust test with `SpanEnd::from_packed`.
4
+ //
5
+ // Values:
6
+ // scope "svc" version "1.2.3"
7
+ // name "svc.Op", kind CLIENT (2), status ERROR "boom"
8
+ // trace id 0102030405060708090a0b0c0d0e0f10, span id 0a0b0c0d0e0f1011,
9
+ // trace flags 01, tracestate "vendor=k:v,other=x"
10
+ // parent span id 1112131415161718
11
+ // start unix 1700000000000000000, start mono 42,
12
+ // end unix 1700000000000001000
13
+ // span attributes, in order:
14
+ // s STR "héllo", b BOOL true, i I64 -7, f F64 1.5,
15
+ // big I64 9007199254740993 (bigint), sa STR_ARRAY ["x", "y"], ba BOOL_ARRAY [true, false],
16
+ // ia I64_ARRAY [1, -2, 3], fa F64_ARRAY [1.5, 2]
17
+ // events:
18
+ // "exception" at 1700000000000000500, exception.message STR "boom"
19
+ // "retry" at 1700000000000000700, no attributes
20
+ // link: trace id 3132333435363738393a3b3c3d3e3f40, span id
21
+ // 4142434445464748, flags 01, tracestate "k=v", l I64 3
22
+
23
+ import {describe, expect, test} from 'bun:test';
24
+ import {existsSync, readFileSync, writeFileSync} from 'node:fs';
25
+ import {createTraceState, type Attributes} from '@opentelemetry/api';
26
+ import {
27
+ ATTR_LEN,
28
+ encodeEnd,
29
+ encodeStart,
30
+ EVENT_LEN,
31
+ HEADER_LEN,
32
+ ITEM_LEN,
33
+ LINK_LEN,
34
+ MAX_COUNT,
35
+ timeToUnixNanos,
36
+ toValue,
37
+ TYPE_BOOL,
38
+ TYPE_BOOL_ARRAY,
39
+ TYPE_F64,
40
+ TYPE_F64_ARRAY,
41
+ TYPE_I64,
42
+ TYPE_I64_ARRAY,
43
+ TYPE_STR,
44
+ TYPE_STR_ARRAY,
45
+ type PackedSpanEnd,
46
+ } from './encode';
47
+
48
+ const GOLDEN_PATH = `${import.meta.dir}/../../../../../crates/encore_telemetry/src/testdata/golden.hex`;
49
+
50
+ const golden: PackedSpanEnd = {
51
+ scope: {name: 'svc', version: '1.2.3'},
52
+ name: 'svc.Op',
53
+ kind: 2,
54
+ statusCode: 2,
55
+ statusMessage: 'boom',
56
+ tracestate: 'vendor=k:v,other=x',
57
+ ctx: Buffer.from(
58
+ '0102030405060708090a0b0c0d0e0f10' + '0a0b0c0d0e0f1011' + '01',
59
+ 'hex',
60
+ ),
61
+ parentSpanId: Buffer.from('1112131415161718', 'hex'),
62
+ startUnixNanos: 1_700_000_000_000_000_000n,
63
+ startMonoNanos: 42n,
64
+ endUnixNanos: 1_700_000_000_000_001_000n,
65
+ attributes: {
66
+ s: 'héllo',
67
+ b: true,
68
+ i: -7,
69
+ f: 1.5,
70
+ big: 9007199254740993n,
71
+ sa: ['x', 'y'],
72
+ ba: [true, false],
73
+ ia: [1, -2, 3],
74
+ fa: [1.5, 2],
75
+ } as unknown as Attributes,
76
+ events: [
77
+ {
78
+ name: 'exception',
79
+ timeUnixNanos: 1_700_000_000_000_000_500n,
80
+ attributes: {'exception.message': 'boom'},
81
+ },
82
+ {name: 'retry', timeUnixNanos: 1_700_000_000_000_000_700n},
83
+ ],
84
+ links: [
85
+ {
86
+ context: {
87
+ traceId: '3132333435363738393a3b3c3d3e3f40',
88
+ spanId: '4142434445464748',
89
+ traceFlags: 1,
90
+ traceState: createTraceState('k=v'),
91
+ },
92
+ attributes: {l: 3},
93
+ },
94
+ ],
95
+ };
96
+
97
+ function tableOff(buf: Buffer): number {
98
+ return (
99
+ HEADER_LEN +
100
+ buf.readUInt32LE(8) * ATTR_LEN +
101
+ buf.readUInt32LE(12) * ITEM_LEN +
102
+ buf.readUInt32LE(16) * EVENT_LEN +
103
+ buf.readUInt32LE(20) * LINK_LEN
104
+ );
105
+ }
106
+
107
+ function data(buf: Buffer, off: number): Buffer {
108
+ const start = tableOff(buf) + buf.readUInt32LE(off);
109
+ return buf.subarray(start, start + buf.readUInt32LE(off + 4));
110
+ }
111
+
112
+ const str = (buf: Buffer, off: number) => data(buf, off).toString('utf8');
113
+ const attr = (i: number) => HEADER_LEN + i * ATTR_LEN;
114
+
115
+ describe('encodeEnd', () => {
116
+ const buf = encodeEnd(golden);
117
+
118
+ test('matches the golden fixture', () => {
119
+ const got = buf.toString('hex');
120
+ if (process.env.UPDATE_GOLDEN === '1' || !existsSync(GOLDEN_PATH)) {
121
+ if (process.env.UPDATE_GOLDEN !== '1') {
122
+ throw new Error(`missing ${GOLDEN_PATH}; run with UPDATE_GOLDEN=1`);
123
+ }
124
+ writeFileSync(GOLDEN_PATH, got + '\n');
125
+ }
126
+ expect(got).toBe(readFileSync(GOLDEN_PATH, 'utf8').trim());
127
+ });
128
+
129
+ test('header', () => {
130
+ expect(buf[0]).toBe(1);
131
+ expect(buf[1]).toBe(2);
132
+ expect(buf[2]).toBe(2);
133
+ expect(buf[3]).toBe(1);
134
+ expect(buf.readUInt32LE(4)).toBe(9);
135
+ expect(buf.readUInt32LE(8)).toBe(11);
136
+ expect(buf.readUInt32LE(12)).toBe(9);
137
+ expect(buf.readUInt32LE(16)).toBe(2);
138
+ expect(buf.readUInt32LE(20)).toBe(1);
139
+ expect(str(buf, 24)).toBe('svc.Op');
140
+ expect(str(buf, 32)).toBe('boom');
141
+ expect(str(buf, 40)).toBe('vendor=k:v,other=x');
142
+ expect(buf.toString('hex', 48, 64)).toBe(
143
+ '0102030405060708090a0b0c0d0e0f10',
144
+ );
145
+ expect(buf.toString('hex', 64, 72)).toBe('0a0b0c0d0e0f1011');
146
+ expect(buf.toString('hex', 72, 80)).toBe('1112131415161718');
147
+ expect(buf.readBigUInt64LE(80)).toBe(1_700_000_000_000_000_000n);
148
+ expect(buf.readBigUInt64LE(88)).toBe(42n);
149
+ expect(buf.readBigUInt64LE(96)).toBe(1_700_000_000_000_001_000n);
150
+ expect(str(buf, 104)).toBe('svc');
151
+ expect(str(buf, 112)).toBe('1.2.3');
152
+ });
153
+
154
+ test('attributes', () => {
155
+ const types = Array.from({length: 11}, (_, i) => buf[attr(i) + 8]);
156
+ expect(types).toEqual([
157
+ TYPE_STR,
158
+ TYPE_BOOL,
159
+ TYPE_I64,
160
+ TYPE_F64,
161
+ TYPE_I64,
162
+ TYPE_STR_ARRAY,
163
+ TYPE_BOOL_ARRAY,
164
+ TYPE_I64_ARRAY,
165
+ TYPE_F64_ARRAY,
166
+ TYPE_STR,
167
+ TYPE_I64,
168
+ ]);
169
+ expect(str(buf, attr(0))).toBe('s');
170
+ expect(str(buf, attr(0) + 16)).toBe('héllo');
171
+ expect(buf[attr(1) + 16]).toBe(1);
172
+ expect(buf.readBigInt64LE(attr(2) + 16)).toBe(-7n);
173
+ expect(buf.readDoubleLE(attr(3) + 16)).toBe(1.5);
174
+ expect(buf.readBigInt64LE(attr(4) + 16)).toBe(9007199254740993n);
175
+ const items = HEADER_LEN + 11 * ATTR_LEN;
176
+ // ia: items [4, 7)
177
+ expect(buf.readUInt32LE(attr(7) + 16)).toBe(4);
178
+ expect(buf.readUInt32LE(attr(7) + 20)).toBe(3);
179
+ expect(buf.readBigInt64LE(items + 5 * ITEM_LEN)).toBe(-2n);
180
+ expect(str(buf, items + ITEM_LEN)).toBe('y');
181
+ });
182
+
183
+ test('events and links', () => {
184
+ const events = HEADER_LEN + 11 * ATTR_LEN + 9 * ITEM_LEN;
185
+ expect(str(buf, events)).toBe('exception');
186
+ expect(buf.readBigUInt64LE(events + 8)).toBe(1_700_000_000_000_000_500n);
187
+ expect(buf.readUInt32LE(events + 16)).toBe(9);
188
+ expect(buf.readUInt32LE(events + 20)).toBe(1);
189
+ expect(str(buf, events + EVENT_LEN)).toBe('retry');
190
+ expect(buf.readUInt32LE(events + EVENT_LEN + 20)).toBe(0);
191
+ const link = events + 2 * EVENT_LEN;
192
+ expect(buf.toString('hex', link, link + 24)).toBe(
193
+ '3132333435363738393a3b3c3d3e3f40' + '4142434445464748',
194
+ );
195
+ expect(buf[link + 24]).toBe(1);
196
+ expect(str(buf, link + 28)).toBe('k=v');
197
+ expect(buf.readUInt32LE(link + 36)).toBe(10);
198
+ expect(buf.readUInt32LE(link + 40)).toBe(1);
199
+ });
200
+ });
201
+
202
+ describe('encodeStart', () => {
203
+ test('scope, attributes, and links, zero header', () => {
204
+ const buf = encodeStart({name: 'lib'}, {a: 'x'}, golden.links);
205
+ expect(buf[0]).toBe(1);
206
+ expect(buf.readUInt32LE(4)).toBe(1);
207
+ expect(buf.readUInt32LE(20)).toBe(1);
208
+ expect(buf.subarray(48, 104).every(b => b === 0)).toBe(true);
209
+ expect(str(buf, 104)).toBe('lib');
210
+ expect(str(buf, 112)).toBe('');
211
+ });
212
+
213
+ test('counts are capped', () => {
214
+ const attrs: Attributes = {};
215
+ for (let i = 0; i < MAX_COUNT + 5; i++) attrs[`k${i}`] = i;
216
+ expect(encodeStart({name: 'lib'}, attrs, undefined).readUInt32LE(4)).toBe(
217
+ MAX_COUNT,
218
+ );
219
+ });
220
+ });
221
+
222
+ describe('toValue', () => {
223
+ test('numbers', () => {
224
+ expect(toValue(2)).toEqual({t: TYPE_I64, v: 2n});
225
+ expect(toValue(2.5)).toEqual({t: TYPE_F64, v: 2.5});
226
+ expect(toValue(2 ** 60)).toEqual({t: TYPE_F64, v: 2 ** 60});
227
+ expect(toValue(1n << 70n)).toEqual({t: TYPE_I64, v: (1n << 63n) - 1n});
228
+ expect(toValue(-(1n << 70n))).toEqual({t: TYPE_I64, v: -(1n << 63n)});
229
+ });
230
+
231
+ test('arrays drop mixed and null items', () => {
232
+ expect(toValue(['a', 1, null, 'b'])).toEqual({
233
+ t: TYPE_STR_ARRAY,
234
+ v: ['a', 'b'],
235
+ });
236
+ expect(toValue([null, true, 'x'])).toEqual({
237
+ t: TYPE_BOOL_ARRAY,
238
+ v: [true],
239
+ });
240
+ expect(toValue([1, 2.5])).toEqual({t: TYPE_F64_ARRAY, v: [1, 2.5]});
241
+ expect(toValue([1, 2n])).toEqual({t: TYPE_I64_ARRAY, v: [1n, 2n]});
242
+ expect(toValue([])).toEqual({t: TYPE_STR_ARRAY, v: []});
243
+ });
244
+
245
+ test('unsupported', () => {
246
+ expect(toValue(undefined)).toBeUndefined();
247
+ expect(toValue(null)).toBeUndefined();
248
+ expect(toValue({})).toBeUndefined();
249
+ expect(toValue([{}])).toBeUndefined();
250
+ expect(toValue(new Uint8Array([1]))).toBeUndefined();
251
+ });
252
+ });
253
+
254
+ describe('timeToUnixNanos', () => {
255
+ test('inputs', () => {
256
+ expect(timeToUnixNanos([1_700_000_000, 5])).toBe(
257
+ 1_700_000_000_000_000_005n,
258
+ );
259
+ expect(timeToUnixNanos(new Date(1_700_000_000_000))).toBe(
260
+ 1_700_000_000_000_000_000n,
261
+ );
262
+ expect(timeToUnixNanos(1_700_000_000_000.5)).toBe(
263
+ 1_700_000_000_000_500_000n,
264
+ );
265
+ });
266
+ });