@encore.dev/sdk 2.0.0-beta.10 → 2.0.0-beta.13

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.
@@ -1,6 +1,8 @@
1
1
  import {afterAll, describe, expect, test} from 'bun:test';
2
2
  import http2 from 'node:http2';
3
3
  import type {AddressInfo} from 'node:net';
4
+ import {join} from 'node:path';
5
+ import {pathToFileURL} from 'node:url';
4
6
 
5
7
  /**
6
8
  * Spans reach the collector when the process is stopped with a signal. The app
@@ -34,8 +36,19 @@ afterAll(() => {
34
36
  receiver.close();
35
37
  });
36
38
 
39
+ /** With `SHUTDOWN_TEST_RUNTIME=node`, the apps run under Node, on the built
40
+ * package (`cargo xtask build-ts-runtime`), as an app bundled for Node does;
41
+ * else under Bun, on the sources. */
42
+ const node = process.env.SHUTDOWN_TEST_RUNTIME === 'node';
43
+ const sdkRoot = join(import.meta.dir, '../..', node ? 'dist' : '');
44
+
45
+ /** The SDK's module at `path`, as an app's script imports it. */
46
+ function sdk(path: string): string {
47
+ return JSON.stringify(pathToFileURL(join(sdkRoot, path)).href);
48
+ }
49
+
37
50
  const APP = `
38
- import { tracerProvider } from "${import.meta.dir}/../../otel";
51
+ import { tracerProvider } from ${sdk('otel.js')};
39
52
 
40
53
  tracerProvider().getTracer("app").startSpan("ended before signal").end();
41
54
  // Keeps the process alive, as a server does.
@@ -44,8 +57,8 @@ const APP = `
44
57
  `;
45
58
 
46
59
  const DRAINING = `
47
- import { tracerProvider } from "${import.meta.dir}/../../otel";
48
- import { onShutdown } from "${import.meta.dir}/../../shutdown/mod";
60
+ import { tracerProvider } from ${sdk('otel.js')};
61
+ import { onShutdown } from ${sdk('shutdown/mod.js')};
49
62
 
50
63
  const span = tracerProvider().getTracer("app").startSpan("in flight at signal");
51
64
  const timer = setInterval(() => {}, 1000);
@@ -60,7 +73,7 @@ const DRAINING = `
60
73
  // Shuts down as NestJS's enableShutdownHooks() does: its own listener awaits
61
74
  // the app's hooks, then removes itself and re-raises the signal.
62
75
  const OWN_HOOKS = `
63
- import "${import.meta.dir}/mod";
76
+ import ${sdk('internal/runtime/mod.js')};
64
77
 
65
78
  const timer = setInterval(() => {}, 1000);
66
79
  const onSignal = async (signal) => {
@@ -76,7 +89,7 @@ const OWN_HOOKS = `
76
89
 
77
90
  // Shuts down in its own listener, then exits with a code of its own.
78
91
  const OWN_EXIT = `
79
- import "${import.meta.dir}/mod";
92
+ import ${sdk('internal/runtime/mod.js')};
80
93
 
81
94
  setInterval(() => {}, 1000);
82
95
  process.on("SIGTERM", async () => {
@@ -89,7 +102,7 @@ const OWN_EXIT = `
89
102
 
90
103
  // Closes everything it has open in its own listener, setting an exit code.
91
104
  const OWN_IDLE = `
92
- import "${import.meta.dir}/mod";
105
+ import ${sdk('internal/runtime/mod.js')};
93
106
 
94
107
  const timer = setInterval(() => {}, 1000);
95
108
  process.on("SIGTERM", async () => {
@@ -104,8 +117,8 @@ const OWN_IDLE = `
104
117
  // Shuts down as OWN_HOOKS does, beside a drain Encore registered itself, as
105
118
  // its API framework's server does.
106
119
  const OWN_HOOKS_SERVED = `
107
- import "${import.meta.dir}/mod";
108
- import { onShutdownInternal } from "${import.meta.dir}/shutdown";
120
+ import ${sdk('internal/runtime/mod.js')};
121
+ import { onShutdownInternal } from ${sdk('internal/runtime/shutdown.js')};
109
122
 
110
123
  onShutdownInternal(() => {});
111
124
  const timer = setInterval(() => {}, 1000);
@@ -123,7 +136,7 @@ const OWN_HOOKS_SERVED = `
123
136
  // Handles the signal itself, holding the shutdown back until it is done; a
124
137
  // timer it leaves running doesn't keep the process alive.
125
138
  const OWN_HOLD = `
126
- import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
139
+ import * as shutdown from ${sdk('shutdown/mod.js')};
127
140
 
128
141
  setInterval(() => {}, 1000);
129
142
  const held = shutdown.hold();
@@ -137,7 +150,7 @@ const OWN_HOLD = `
137
150
 
138
151
  // A job in flight at the signal holds the shutdown back for its scope.
139
152
  const USING = `
140
- import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
153
+ import * as shutdown from ${sdk('shutdown/mod.js')};
141
154
 
142
155
  async function job() {
143
156
  using _ = shutdown.hold();
@@ -150,7 +163,7 @@ const USING = `
150
163
 
151
164
  // A callback is told the shutdown began, and when cleanup does.
152
165
  const CONTEXT = `
153
- import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
166
+ import * as shutdown from ${sdk('shutdown/mod.js')};
154
167
 
155
168
  setInterval(() => {}, 1000);
156
169
  shutdown.onShutdown(({ signal, deadline }) => {
@@ -162,7 +175,7 @@ const CONTEXT = `
162
175
 
163
176
  // Never releases its hold: only the deadline or a second Ctrl-C ends it.
164
177
  const STUCK = `
165
- import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
178
+ import * as shutdown from ${sdk('shutdown/mod.js')};
166
179
 
167
180
  setInterval(() => {}, 1000);
168
181
  shutdown.hold();
@@ -171,9 +184,9 @@ const STUCK = `
171
184
 
172
185
  // Runs the runtime as encore.dev's \`run\` does, which handles the signals.
173
186
  const HOSTED = `
174
- import { tracerProvider } from "${import.meta.dir}/../../otel";
175
- import { RT, runUntilShutdown } from "${import.meta.dir}/mod";
176
- import { onShutdown } from "${import.meta.dir}/../../shutdown/mod";
187
+ import { tracerProvider } from ${sdk('otel.js')};
188
+ import { RT, runUntilShutdown } from ${sdk('internal/runtime/mod.js')};
189
+ import { onShutdown } from ${sdk('shutdown/mod.js')};
177
190
 
178
191
  const span = tracerProvider().getTracer("app").startSpan("in flight at signal");
179
192
  onShutdown(async () => {
@@ -186,11 +199,57 @@ const HOSTED = `
186
199
  process.exit(await exited);
187
200
  `;
188
201
 
202
+ // Runs the runtime as HOSTED does, with SIGTERM heard by the runtime alone,
203
+ // as on Windows it alone hears the console close. Not under Node on POSIX,
204
+ // which dies of a SIGTERM no JavaScript listens for.
205
+ const HOSTED_RUNTIME_ONLY = `
206
+ const on = process.on;
207
+ process.on = function (event, listener) {
208
+ return event === "SIGTERM" ? this : on.call(this, event, listener);
209
+ };
210
+ const { tracerProvider } = await import(${sdk('otel.js')});
211
+ const { RT, runUntilShutdown } = await import(${sdk('internal/runtime/mod.js')});
212
+ const { onShutdown } = await import(${sdk('shutdown/mod.js')});
213
+
214
+ const span = tracerProvider().getTracer("app").startSpan("in flight at signal");
215
+ onShutdown(async () => {
216
+ await new Promise((resolve) => setTimeout(resolve, 300));
217
+ span.end();
218
+ });
219
+ const exited = runUntilShutdown(RT);
220
+ setTimeout(() => console.log("ready"), 500);
221
+ process.exit(await exited);
222
+ `;
223
+
224
+ // Runs the runtime without a cooperative shutdown, with an onBegin callback,
225
+ // and SIGTERM heard by the runtime alone, saying whether the callback had run
226
+ // by the time runForever resolved: its caller exits the process then.
227
+ const NON_COOPERATIVE_ON_BEGIN = `
228
+ const on = process.on;
229
+ process.on = function (event, listener) {
230
+ return event === "SIGTERM" ? this : on.call(this, event, listener);
231
+ };
232
+ const { RT } = await import(${sdk('internal/runtime/mod.js')});
233
+
234
+ let began = false;
235
+ const exited = RT.runForever(false, () => {
236
+ began = true;
237
+ });
238
+ setTimeout(() => console.log("ready"), 500);
239
+ const code = await exited;
240
+ console.log(began ? "onBegin ran first" : "resolved before onBegin ran");
241
+ process.exit(code);
242
+ `;
243
+
189
244
  type Signal = 'SIGTERM' | 'SIGINT';
190
245
 
246
+ const windows = process.platform === 'win32';
247
+
191
248
  /** Runs `script` as the app, stops it with `signals` of `kind` (or the
192
249
  * signals listed, in order), `gap` ms apart, once it prints `ready`, and returns its exit code and how long it
193
- * took to exit after the first signal. */
250
+ * took to exit after the first signal. On Windows, which has no signals to
251
+ * send it, it asks the app to stop as the daemon does, through the event the
252
+ * app listens for: as one SIGTERM. */
194
253
  async function runApp(
195
254
  script: string,
196
255
  signals = 1,
@@ -203,8 +262,15 @@ async function runApp(
203
262
  out: string;
204
263
  ms: number;
205
264
  }> {
265
+ const kinds = Array.isArray(kind) ? kind : Array<Signal>(signals).fill(kind);
266
+ if (windows && kinds.join() !== 'SIGTERM') {
267
+ throw new Error('on Windows, an app can only be asked to stop once');
268
+ }
269
+ const stop = windows ? await stopEvent() : undefined;
206
270
  const proc = Bun.spawn({
207
- cmd: [process.execPath, '-e', script],
271
+ cmd: node
272
+ ? ['node', '--input-type=module', '-e', script]
273
+ : [process.execPath, '-e', script],
208
274
  cwd: import.meta.dir,
209
275
  env: {
210
276
  ...process.env,
@@ -212,6 +278,7 @@ async function runApp(
212
278
  ENCORE_RUNTIME_CONFIG: runtimeConfig(collector, telemetry),
213
279
  // Nothing is exported on a timer while the test runs.
214
280
  OTEL_BSP_SCHEDULE_DELAY: '60000',
281
+ ...(stop && {ENCORE_STOP_EVENT: stop.name}),
215
282
  },
216
283
  stdout: 'pipe',
217
284
  stderr: 'inherit',
@@ -226,19 +293,102 @@ async function runApp(
226
293
  };
227
294
  while (!out.split('\n').some(l => l.trim() === 'ready') && (await read()));
228
295
  const start = performance.now();
229
- const kinds = Array.isArray(kind) ? kind : Array<Signal>(signals).fill(kind);
230
296
  for (const [i, k] of kinds.entries()) {
231
297
  if (i > 0) await Bun.sleep(gap);
232
- proc.kill(k);
298
+ if (!stop) proc.kill(k);
299
+ else if (!(await stop.set())) {
300
+ proc.kill();
301
+ throw new Error('the app does not listen for the stop request');
302
+ }
233
303
  }
234
304
  const timeout = setTimeout(() => proc.kill('SIGKILL'), 20_000);
235
305
  while (await read());
236
306
  await proc.exited;
237
307
  clearTimeout(timeout);
308
+ stop?.close();
238
309
  const ms = performance.now() - start;
239
310
  return {code: proc.exitCode, signal: proc.signalCode, out, ms};
240
311
  }
241
312
 
313
+ /** The event a process is asked to stop through on Windows, made as the
314
+ * daemon makes it, with the event the process sets once it listens. */
315
+ interface StopEvent {
316
+ /** Its name, for `ENCORE_STOP_EVENT`. */
317
+ name: string;
318
+ /** Sets it, saying whether a process listened for it. */
319
+ set(): Promise<boolean>;
320
+ close(): void;
321
+ }
322
+
323
+ let stopEvents = 0;
324
+
325
+ /** Makes a {@link StopEvent}, in a PowerShell process that holds it open. */
326
+ async function stopEvent(): Promise<StopEvent> {
327
+ const name = `Local\\encore-test-stop-${process.pid}-${++stopEvents}`;
328
+ const ps = Bun.spawn({
329
+ cmd: [
330
+ 'powershell.exe',
331
+ '-NoProfile',
332
+ '-NonInteractive',
333
+ '-Command',
334
+ STOP_EVENT_PS,
335
+ ],
336
+ env: {...process.env, STOP_EVENT: name},
337
+ stdin: 'pipe',
338
+ stdout: 'pipe',
339
+ stderr: 'inherit',
340
+ });
341
+ const reader = ps.stdout.getReader();
342
+ const decoder = new TextDecoder();
343
+ let buf = '';
344
+ const line = async (): Promise<string | undefined> => {
345
+ for (;;) {
346
+ const nl = buf.indexOf('\n');
347
+ if (nl >= 0) {
348
+ const l = buf.slice(0, nl).trim();
349
+ buf = buf.slice(nl + 1);
350
+ return l;
351
+ }
352
+ const {done, value} = await reader.read();
353
+ if (done) return undefined;
354
+ buf += decoder.decode(value);
355
+ }
356
+ };
357
+ const created = await line();
358
+ if (created !== 'created') throw new Error(`no stop event: ${created}`);
359
+ return {
360
+ name,
361
+ async set() {
362
+ void ps.stdin.write('set\n');
363
+ void ps.stdin.flush();
364
+ return (await line()) === 'listening=True';
365
+ },
366
+ close() {
367
+ void ps.stdin.end();
368
+ },
369
+ };
370
+ }
371
+
372
+ /** Makes the events `STOP_EVENT` names, manual-reset as the daemon's are,
373
+ * then sets the stop event for each line read, writing first whether a
374
+ * process listened for it. */
375
+ const STOP_EVENT_PS = `
376
+ $m = [System.Threading.EventResetMode]::ManualReset
377
+ $stop = New-Object System.Threading.EventWaitHandle($false, $m, $env:STOP_EVENT)
378
+ $listening = New-Object System.Threading.EventWaitHandle($false, $m, "$($env:STOP_EVENT)-listening")
379
+ [Console]::Out.WriteLine('created')
380
+ while ($null -ne [Console]::In.ReadLine()) {
381
+ [Console]::Out.WriteLine("listening=$($listening.WaitOne(0))")
382
+ [void]$stop.Set()
383
+ }
384
+ `;
385
+
386
+ /** A test that stops its app with signals of its own, or the app with one:
387
+ * POSIX only. Windows has no signals to send: there `kill()` ends the
388
+ * process at once, and Ctrl-Break, the one signal a child can be sent alone,
389
+ * ends a Bun process whatever it listens for. */
390
+ const posixTest = test.skipIf(windows);
391
+
242
392
  describe('shutdown', () => {
243
393
  test('SIGTERM flushes ended spans', async () => {
244
394
  const {code} = await runApp(APP);
@@ -269,32 +419,70 @@ describe('shutdown', () => {
269
419
  expect(code).toBe(0);
270
420
  }, 30_000);
271
421
 
272
- test("an app's own signal handling finishes before cleanup", async () => {
273
- received.length = 0;
274
- const {code, signal, out} = await runApp(OWN_HOOKS, 1, false);
275
- expect(out).toContain('hooks done');
276
- // It dies of the signal it re-raised, as it meant to.
277
- expect(code).toBeNull();
278
- expect(signal).toBe('SIGTERM');
279
- }, 30_000);
280
-
281
- test("an app's own signal handling is waited for beside Encore's drain", async () => {
282
- const {code, signal, out} = await runApp(OWN_HOOKS_SERVED, 1, false);
283
- expect(out).toContain('hooks done');
284
- expect(code).toBeNull();
285
- expect(signal).toBe('SIGTERM');
286
- }, 30_000);
287
-
288
- test("another signal isn't taken for the app's own raised again", async () => {
289
- const {code, signal, out} = await runApp(OWN_HOOKS, 2, false, [
290
- 'SIGTERM',
291
- 'SIGINT',
292
- ]);
293
- // The SIGINT came while its hooks ran; it still dies of its own SIGTERM.
294
- expect(out).toContain('hooks done');
295
- expect(code).toBeNull();
296
- expect(signal).toBe('SIGTERM');
297
- }, 30_000);
422
+ test.skipIf(node && !windows)(
423
+ 'a host running the runtime runs the drains on a signal only it hears',
424
+ async () => {
425
+ received.length = 0;
426
+ const {code, ms} = await runApp(HOSTED_RUNTIME_ONLY);
427
+ expect(received).toContainEqual({
428
+ name: 'in flight at signal',
429
+ finished: true,
430
+ });
431
+ expect(code).toBe(0);
432
+ // The app told the runtime it drained: it didn't wait for the deadline.
433
+ expect(ms).toBeLessThan(4000);
434
+ },
435
+ 30_000,
436
+ );
437
+
438
+ test.skipIf(node && !windows)(
439
+ 'runForever resolves only once onBegin has run',
440
+ async () => {
441
+ const {code, out} = await runApp(NON_COOPERATIVE_ON_BEGIN);
442
+ expect(out).toContain('onBegin ran first');
443
+ expect(code).toBe(0);
444
+ },
445
+ 30_000,
446
+ );
447
+
448
+ posixTest(
449
+ "an app's own signal handling finishes before cleanup",
450
+ async () => {
451
+ received.length = 0;
452
+ const {code, signal, out} = await runApp(OWN_HOOKS, 1, false);
453
+ expect(out).toContain('hooks done');
454
+ // It dies of the signal it re-raised, as it meant to.
455
+ expect(code).toBeNull();
456
+ expect(signal).toBe('SIGTERM');
457
+ },
458
+ 30_000,
459
+ );
460
+
461
+ posixTest(
462
+ "an app's own signal handling is waited for beside Encore's drain",
463
+ async () => {
464
+ const {code, signal, out} = await runApp(OWN_HOOKS_SERVED, 1, false);
465
+ expect(out).toContain('hooks done');
466
+ expect(code).toBeNull();
467
+ expect(signal).toBe('SIGTERM');
468
+ },
469
+ 30_000,
470
+ );
471
+
472
+ posixTest(
473
+ "another signal isn't taken for the app's own raised again",
474
+ async () => {
475
+ const {code, signal, out} = await runApp(OWN_HOOKS, 2, false, [
476
+ 'SIGTERM',
477
+ 'SIGINT',
478
+ ]);
479
+ // The SIGINT came while its hooks ran; it still dies of its own SIGTERM.
480
+ expect(out).toContain('hooks done');
481
+ expect(code).toBeNull();
482
+ expect(signal).toBe('SIGTERM');
483
+ },
484
+ 30_000,
485
+ );
298
486
 
299
487
  test('an app that exits itself keeps its exit code', async () => {
300
488
  received.length = 0;
@@ -336,22 +524,30 @@ describe('shutdown', () => {
336
524
  expect(code).toBe(1);
337
525
  }, 30_000);
338
526
 
339
- test('a second Ctrl-C stops waiting for the app', async () => {
340
- const {code, ms} = await runApp(STUCK, 2, false, 'SIGINT', 1500);
341
- // Forced, cleanup finishes in time.
342
- expect(code).toBe(0);
343
- expect(ms).toBeLessThan(4000);
344
- }, 30_000);
345
-
346
- test('a repeated signal does not cut shutdown short', async () => {
347
- received.length = 0;
348
- const {code} = await runApp(DRAINING, 2);
349
- expect(received).toContainEqual({
350
- name: 'in flight at signal',
351
- finished: true,
352
- });
353
- expect(code).toBe(0);
354
- }, 30_000);
527
+ posixTest(
528
+ 'a second Ctrl-C stops waiting for the app',
529
+ async () => {
530
+ const {code, ms} = await runApp(STUCK, 2, false, 'SIGINT', 1500);
531
+ // Forced, cleanup finishes in time.
532
+ expect(code).toBe(0);
533
+ expect(ms).toBeLessThan(4000);
534
+ },
535
+ 30_000,
536
+ );
537
+
538
+ posixTest(
539
+ 'a repeated signal does not cut shutdown short',
540
+ async () => {
541
+ received.length = 0;
542
+ const {code} = await runApp(DRAINING, 2);
543
+ expect(received).toContainEqual({
544
+ name: 'in flight at signal',
545
+ finished: true,
546
+ });
547
+ expect(code).toBe(0);
548
+ },
549
+ 30_000,
550
+ );
355
551
  });
356
552
 
357
553
  /** The spans of an `ExportTraceServiceRequest`. */
@@ -435,21 +631,16 @@ function runtimeConfig(collector: string, telemetry: boolean): string {
435
631
  ];
436
632
  const str = (field: number, value: string): number[] =>
437
633
  msg(field, [...new TextEncoder().encode(value)]);
438
- const enumField = (field: number, value: number): number[] => [
439
- ...varint(field << 3),
440
- ...varint(value),
441
- ];
442
634
 
443
635
  // Environment{app_id=1, env_name=4}
444
636
  const environment = [...str(1, 'app'), ...str(4, 'test')];
445
637
  // Deployment{hosted_services=5, observability=7}; HostedService{name=1};
446
- // Observability{telemetry=4}; Telemetry{collector=4};
447
- // TelemetryDestination{receiver=2 (ENCORE=1), otlp_grpc=10};
638
+ // Observability{tracing=1}; TracingProvider{otlp_grpc=11};
448
639
  // OtlpGrpc{endpoint=1}
449
- const destination = [...enumField(2, 1), ...msg(10, str(1, collector))];
640
+ const provider = msg(11, str(1, collector));
450
641
  const deployment = [
451
642
  ...msg(5, str(1, 'svc')),
452
- ...(telemetry ? msg(7, msg(4, msg(4, destination))) : []),
643
+ ...(telemetry ? msg(7, msg(1, provider)) : []),
453
644
  ];
454
645
  // RuntimeConfig{environment=1, deployment=3}
455
646
  const cfg = [...msg(1, environment), ...msg(3, deployment)];
@@ -39,7 +39,13 @@ export interface ShutdownContext {
39
39
  /** Called when shutdown begins. Cleanup waits for what it returns to settle. */
40
40
  export type ShutdownCallback = (ctx: ShutdownContext) => void | Promise<void>;
41
41
 
42
- const SIGNALS = ['SIGTERM', 'SIGINT'] as const;
42
+ /** The signals that begin the shutdown. Under Node on Windows Ctrl-Break
43
+ * too, which the daemon sends a process that doesn't listen for its stop
44
+ * request; Bun dies of it, whatever it listens for. */
45
+ const SIGNALS: readonly NodeJS.Signals[] =
46
+ process.platform === 'win32' && !process.versions.bun
47
+ ? ['SIGTERM', 'SIGINT', 'SIGBREAK']
48
+ : ['SIGTERM', 'SIGINT'];
43
49
  /** How long after the first signal the same one again is a new one, not the
44
50
  * first delivered twice: a process group's runner may forward the signal its
45
51
  * members already received. */
@@ -203,7 +209,8 @@ export function forceCleanup(): void {
203
209
  rt().forceShutdownCleanup();
204
210
  }
205
211
 
206
- /** Begins the shutdown on SIGTERM or SIGINT, and exits once it completes:
212
+ /** Begins the shutdown on SIGTERM or SIGINT, or on Windows when the daemon
213
+ * asks the process to stop, and exits once it completes:
207
214
  * with `process.exitCode` (0 unless the app set it) if cleanup finished
208
215
  * within the shutdown deadline, else 1. A second SIGINT, a second Ctrl-C,
209
216
  * forces cleanup.
@@ -213,15 +220,19 @@ export function forceCleanup(): void {
213
220
  * open. */
214
221
  export function watchShutdownSignals(): void {
215
222
  for (const s of SIGNALS) process.on(s, onSignal);
223
+ // Windows has no SIGTERM: the daemon sets an event instead, which comes
224
+ // as SIGTERM, to the app's own listeners too.
225
+ rt().watchStopRequest(() => void process.emit('SIGTERM', 'SIGTERM'));
216
226
  }
217
227
 
218
228
  /** Runs `rt` until its shutdown completes, returning the exit code. The
219
- * runtime handles SIGTERM and SIGINT; on them the shutdown begins here too,
220
- * and cleanup waits for the app's holds. */
229
+ * runtime handles SIGTERM and SIGINT, and on Windows the console closing;
230
+ * on them the shutdown begins here too, and cleanup waits for the app's
231
+ * holds. */
221
232
  export function runUntilShutdown(r: Runtime): Promise<number> {
222
233
  runtime = r;
223
234
  hosted = true;
224
- return r.runForever(true);
235
+ return r.runForever(true, begin);
225
236
  }
226
237
 
227
238
  /** Has `sig` force cleanup when it comes again, as a second SIGINT does. */
@@ -2,6 +2,7 @@ import {afterAll, describe, expect, test} from 'bun:test';
2
2
  import {mkdtempSync, rmSync, writeFileSync} from 'node:fs';
3
3
  import {tmpdir} from 'node:os';
4
4
  import {join} from 'node:path';
5
+ import {pathToFileURL} from 'node:url';
5
6
 
6
7
  /**
7
8
  * Measurements reach the metrics destination: Encore metrics under the
@@ -20,13 +21,16 @@ afterAll(() => rmSync(dir, {recursive: true, force: true}));
20
21
  const api = Bun.resolveSync('@opentelemetry/api', infra);
21
22
  const mod = join(infra, 'dist', 'metrics', 'mod.js');
22
23
  const root = join(infra, 'dist', 'mod.js');
24
+ /** The module at `path` as a string literal for a script to import: a file
25
+ * URL, as Node takes no Windows path for an ES module. */
26
+ const specifier = (path: string) => JSON.stringify(pathToFileURL(path).href);
23
27
 
24
28
  writeFileSync(
25
29
  join(dir, 'worker.mjs'),
26
30
  `
27
31
  import { parentPort } from "node:worker_threads";
28
- import { metrics } from ${JSON.stringify(api)};
29
- import * as m from ${JSON.stringify(mod)};
32
+ import { metrics } from ${specifier(api)};
33
+ import * as m from ${specifier(mod)};
30
34
  new m.Counter("orders_placed", { unit: "{order}" }).add(2);
31
35
  metrics.setGlobalMeterProvider(m.meterProvider());
32
36
  metrics.getMeter("app").createObservableGauge("worker_depth")
@@ -44,9 +48,9 @@ writeFileSync(
44
48
  join(dir, 'main.mjs'),
45
49
  `
46
50
  import { Worker } from "node:worker_threads";
47
- import { metrics } from ${JSON.stringify(api)};
48
- import { meterProvider } from ${JSON.stringify(root)};
49
- import * as m from ${JSON.stringify(mod)};
51
+ import { metrics } from ${specifier(api)};
52
+ import { meterProvider } from ${specifier(root)};
53
+ import * as m from ${specifier(mod)};
50
54
  new m.Counter("orders_placed", { unit: "{order}" }).increment();
51
55
  // Not exported: the runtime registers no global meter provider.
52
56
  metrics.getMeter("app").createCounter("before_registration").add(1);
package/otel.test.ts CHANGED
@@ -1,4 +1,11 @@
1
1
  import {describe, expect, test} from 'bun:test';
2
+ import {join} from 'node:path';
3
+
4
+ /** A module of this package, as a string literal for the probe to import:
5
+ * joined, not spliced. On Windows, Bun loads a module again under a path with
6
+ * a `/` where the package's own imports have a backslash, and the probe would
7
+ * set the context in a copy of the module the SDK doesn't read. */
8
+ const here = (path: string) => JSON.stringify(join(import.meta.dir, path));
2
9
 
3
10
  /**
4
11
  * The runtime registers no OpenTelemetry API global; Encore's providers are
@@ -9,10 +16,10 @@ import {describe, expect, test} from 'bun:test';
9
16
  */
10
17
  const probe = `
11
18
  import { context, metrics, propagation, ROOT_CONTEXT, createContextKey, trace } from "@opentelemetry/api";
12
- import { meterProvider, tracerProvider } from ${JSON.stringify(`${import.meta.dir}/mod`)};
13
- import { TracerProvider, MeterProvider, activeCtxBytes } from ${JSON.stringify(`${import.meta.dir}/internal/otel/index`)};
14
- import { withContext } from ${JSON.stringify(`${import.meta.dir}/internal/otel/context`)};
15
- import { Field } from ${JSON.stringify(`${import.meta.dir}/reqctx/mod`)};
19
+ import { meterProvider, tracerProvider } from ${here('mod')};
20
+ import { TracerProvider, MeterProvider, activeCtxBytes } from ${here('internal/otel/index')};
21
+ import { withContext } from ${here('internal/otel/context')};
22
+ import { Field } from ${here('reqctx/mod')};
16
23
 
17
24
  const key = createContextKey("probe");
18
25
  const ctx = Buffer.alloc(25, 1);
package/package.json CHANGED
@@ -201,10 +201,10 @@
201
201
  "format:check": "prettier --check .",
202
202
  "lint": "eslint . --max-warnings=0",
203
203
  "lint:fix": "eslint . --fix --max-warnings=0",
204
- "test": "bun test",
204
+ "test": "bun test --isolate",
205
205
  "typecheck": "tsc --noEmit"
206
206
  },
207
207
  "sideEffects": false,
208
208
  "type": "module",
209
- "version": "2.0.0-beta.10"
209
+ "version": "2.0.0-beta.13"
210
210
  }
@@ -53,7 +53,7 @@ describe('ordered topics', () => {
53
53
  });
54
54
 
55
55
  test('a key cannot be empty', () => {
56
- expect(outcomes.empty).toContain('cannot be empty');
56
+ expect(outcomes.empty).toContain('orderingKey must be a non-empty string');
57
57
  });
58
58
 
59
59
  test("an ordered topic's message needs a key", () => {
@@ -231,7 +231,8 @@ describe('fetch', () => {
231
231
  `${third.url}/landed`,
232
232
  ]);
233
233
 
234
- // 307 keeps the method and body, but not the credentials or fields.
234
+ // 307 keeps the method and body, but not the credentials, fields or
235
+ // trace, as a request made to the third party directly does not.
235
236
  const landed = third.received[0]!;
236
237
  expect(landed).toMatchObject({
237
238
  path: '/landed',
@@ -242,12 +243,34 @@ describe('fetch', () => {
242
243
  for (const name of Object.keys(landed.headers)) {
243
244
  expect(name).not.toStartWith('x-encore-meta-ctx-');
244
245
  }
246
+ expect(landed.headers.traceparent).toBeUndefined();
247
+ expect(landed.headers.tracestate).toBeUndefined();
245
248
 
246
249
  // 303 within the services turns into a GET, and still carries them.
247
250
  const within = svc.received.find(r => r.path === '/billing/landed')!;
248
251
  expect(within.method).toBe('GET');
249
252
  expect(within.body).toBe('');
250
253
  expect(within.headers['x-encore-meta-ctx-plan']).toBe('InBybyI');
254
+ expect(within.headers.traceparent).toBe(TRACEPARENT);
255
+ expect(within.headers.tracestate).toBe('encore=rc,vendor=1');
256
+ } finally {
257
+ svc.stop();
258
+ third.stop();
259
+ }
260
+ });
261
+
262
+ test('a redirect away from a service keeps a traceparent the request carries', async () => {
263
+ const third = server();
264
+ const svc = server({
265
+ '/away': () => Response.redirect(`${third.url}/landed`, 307),
266
+ });
267
+ try {
268
+ config.services = {billing: svc.url};
269
+ const own = `00-${'1'.repeat(32)}-${'2'.repeat(16)}-01`;
270
+ await withContext(callContext, () =>
271
+ client('billing').fetch('away', {headers: {traceparent: own}}),
272
+ );
273
+ expect(third.received[0]!.headers.traceparent).toBe(own);
251
274
  } finally {
252
275
  svc.stop();
253
276
  third.stop();