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

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.
@@ -57,6 +57,118 @@ const DRAINING = `
57
57
  console.log("ready");
58
58
  `;
59
59
 
60
+ // Shuts down as NestJS's enableShutdownHooks() does: its own listener awaits
61
+ // the app's hooks, then removes itself and re-raises the signal.
62
+ const OWN_HOOKS = `
63
+ import "${import.meta.dir}/mod";
64
+
65
+ const timer = setInterval(() => {}, 1000);
66
+ const onSignal = async (signal) => {
67
+ await new Promise((resolve) => setTimeout(resolve, 300));
68
+ clearInterval(timer);
69
+ console.log("hooks done");
70
+ process.off("SIGTERM", onSignal);
71
+ process.kill(process.pid, signal);
72
+ };
73
+ process.on("SIGTERM", onSignal);
74
+ console.log("ready");
75
+ `;
76
+
77
+ // Shuts down in its own listener, then exits with a code of its own.
78
+ const OWN_EXIT = `
79
+ import "${import.meta.dir}/mod";
80
+
81
+ setInterval(() => {}, 1000);
82
+ process.on("SIGTERM", async () => {
83
+ await new Promise((resolve) => setTimeout(resolve, 300));
84
+ console.log("hooks done");
85
+ process.exit(3);
86
+ });
87
+ console.log("ready");
88
+ `;
89
+
90
+ // Closes everything it has open in its own listener, setting an exit code.
91
+ const OWN_IDLE = `
92
+ import "${import.meta.dir}/mod";
93
+
94
+ const timer = setInterval(() => {}, 1000);
95
+ process.on("SIGTERM", async () => {
96
+ await new Promise((resolve) => setTimeout(resolve, 300));
97
+ clearInterval(timer);
98
+ console.log("hooks done");
99
+ process.exitCode = 4;
100
+ });
101
+ console.log("ready");
102
+ `;
103
+
104
+ // Shuts down as OWN_HOOKS does, beside a drain Encore registered itself, as
105
+ // its API framework's server does.
106
+ const OWN_HOOKS_SERVED = `
107
+ import "${import.meta.dir}/mod";
108
+ import { onShutdownInternal } from "${import.meta.dir}/shutdown";
109
+
110
+ onShutdownInternal(() => {});
111
+ const timer = setInterval(() => {}, 1000);
112
+ const onSignal = async (signal) => {
113
+ await new Promise((resolve) => setTimeout(resolve, 300));
114
+ clearInterval(timer);
115
+ console.log("hooks done");
116
+ process.off("SIGTERM", onSignal);
117
+ process.kill(process.pid, signal);
118
+ };
119
+ process.on("SIGTERM", onSignal);
120
+ console.log("ready");
121
+ `;
122
+
123
+ // Handles the signal itself, holding the shutdown back until it is done; a
124
+ // timer it leaves running doesn't keep the process alive.
125
+ const OWN_HOLD = `
126
+ import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
127
+
128
+ setInterval(() => {}, 1000);
129
+ const held = shutdown.hold();
130
+ process.on("SIGTERM", async () => {
131
+ await new Promise((resolve) => setTimeout(resolve, 300));
132
+ console.log("hooks done");
133
+ held.release();
134
+ });
135
+ console.log("ready");
136
+ `;
137
+
138
+ // A job in flight at the signal holds the shutdown back for its scope.
139
+ const USING = `
140
+ import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
141
+
142
+ async function job() {
143
+ using _ = shutdown.hold();
144
+ await new Promise((resolve) => setTimeout(resolve, 600));
145
+ console.log("job done");
146
+ }
147
+ void job();
148
+ console.log("ready");
149
+ `;
150
+
151
+ // A callback is told the shutdown began, and when cleanup does.
152
+ const CONTEXT = `
153
+ import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
154
+
155
+ setInterval(() => {}, 1000);
156
+ shutdown.onShutdown(({ signal, deadline }) => {
157
+ console.log("began", shutdown.signal.aborted, deadline > Date.now());
158
+ signal.addEventListener("abort", () => console.log("cleanup"));
159
+ });
160
+ console.log("ready");
161
+ `;
162
+
163
+ // Never releases its hold: only the deadline or a second Ctrl-C ends it.
164
+ const STUCK = `
165
+ import * as shutdown from "${import.meta.dir}/../../shutdown/mod";
166
+
167
+ setInterval(() => {}, 1000);
168
+ shutdown.hold();
169
+ console.log("ready");
170
+ `;
171
+
60
172
  // Runs the runtime as encore.dev's \`run\` does, which handles the signals.
61
173
  const HOSTED = `
62
174
  import { tracerProvider } from "${import.meta.dir}/../../otel";
@@ -74,16 +186,30 @@ const HOSTED = `
74
186
  process.exit(await exited);
75
187
  `;
76
188
 
77
- /** Runs `script` as the app, stops it with `signals` SIGTERMs 100ms apart
78
- * once it prints `ready`, and returns its exit code. */
79
- async function runApp(script: string, signals = 1): Promise<number | null> {
189
+ type Signal = 'SIGTERM' | 'SIGINT';
190
+
191
+ /** Runs `script` as the app, stops it with `signals` of `kind` (or the
192
+ * 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. */
194
+ async function runApp(
195
+ script: string,
196
+ signals = 1,
197
+ telemetry = true,
198
+ kind: Signal | Signal[] = 'SIGTERM',
199
+ gap = 100,
200
+ ): Promise<{
201
+ code: number | null;
202
+ signal: string | null;
203
+ out: string;
204
+ ms: number;
205
+ }> {
80
206
  const proc = Bun.spawn({
81
207
  cmd: [process.execPath, '-e', script],
82
208
  cwd: import.meta.dir,
83
209
  env: {
84
210
  ...process.env,
85
211
  NODE_ENV: 'production',
86
- ENCORE_RUNTIME_CONFIG: runtimeConfig(collector),
212
+ ENCORE_RUNTIME_CONFIG: runtimeConfig(collector, telemetry),
87
213
  // Nothing is exported on a timer while the test runs.
88
214
  OTEL_BSP_SCHEDULE_DELAY: '60000',
89
215
  },
@@ -91,24 +217,31 @@ async function runApp(script: string, signals = 1): Promise<number | null> {
91
217
  stderr: 'inherit',
92
218
  });
93
219
  const decoder = new TextDecoder();
220
+ const reader = proc.stdout.getReader();
94
221
  let out = '';
95
- for await (const chunk of proc.stdout) {
96
- out += decoder.decode(chunk);
97
- if (out.split('\n').some(l => l.trim() === 'ready')) break;
98
- }
99
- for (let i = 0; i < signals; i++) {
100
- if (i > 0) await Bun.sleep(100);
101
- proc.kill('SIGTERM');
222
+ const read = async (): Promise<boolean> => {
223
+ const {done, value} = await reader.read();
224
+ if (!done) out += decoder.decode(value);
225
+ return !done;
226
+ };
227
+ while (!out.split('\n').some(l => l.trim() === 'ready') && (await read()));
228
+ const start = performance.now();
229
+ const kinds = Array.isArray(kind) ? kind : Array<Signal>(signals).fill(kind);
230
+ for (const [i, k] of kinds.entries()) {
231
+ if (i > 0) await Bun.sleep(gap);
232
+ proc.kill(k);
102
233
  }
103
234
  const timeout = setTimeout(() => proc.kill('SIGKILL'), 20_000);
235
+ while (await read());
104
236
  await proc.exited;
105
237
  clearTimeout(timeout);
106
- return proc.exitCode;
238
+ const ms = performance.now() - start;
239
+ return {code: proc.exitCode, signal: proc.signalCode, out, ms};
107
240
  }
108
241
 
109
242
  describe('shutdown', () => {
110
243
  test('SIGTERM flushes ended spans', async () => {
111
- const code = await runApp(APP);
244
+ const {code} = await runApp(APP);
112
245
  expect(received).toContainEqual({
113
246
  name: 'ended before signal',
114
247
  finished: true,
@@ -118,7 +251,7 @@ describe('shutdown', () => {
118
251
 
119
252
  test('SIGTERM waits for the app to drain', async () => {
120
253
  received.length = 0;
121
- const code = await runApp(DRAINING);
254
+ const {code} = await runApp(DRAINING);
122
255
  expect(received).toContainEqual({
123
256
  name: 'in flight at signal',
124
257
  finished: true,
@@ -128,7 +261,7 @@ describe('shutdown', () => {
128
261
 
129
262
  test('a host running the runtime runs the drains on SIGTERM', async () => {
130
263
  received.length = 0;
131
- const code = await runApp(HOSTED);
264
+ const {code} = await runApp(HOSTED);
132
265
  expect(received).toContainEqual({
133
266
  name: 'in flight at signal',
134
267
  finished: true,
@@ -136,9 +269,83 @@ describe('shutdown', () => {
136
269
  expect(code).toBe(0);
137
270
  }, 30_000);
138
271
 
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);
298
+
299
+ test('an app that exits itself keeps its exit code', async () => {
300
+ received.length = 0;
301
+ const {code, out} = await runApp(OWN_EXIT, 1, false);
302
+ expect(out).toContain('hooks done');
303
+ expect(code).toBe(3);
304
+ }, 30_000);
305
+
306
+ test('an app that closes everything keeps its exit code', async () => {
307
+ received.length = 0;
308
+ const {code, out} = await runApp(OWN_IDLE, 1, false);
309
+ expect(out).toContain('hooks done');
310
+ expect(code).toBe(4);
311
+ }, 30_000);
312
+
313
+ test('an app holding the shutdown is done once it releases it', async () => {
314
+ const {code, out, ms} = await runApp(OWN_HOLD, 1, false);
315
+ expect(out).toContain('hooks done');
316
+ expect(code).toBe(0);
317
+ // Its timer is left running: Encore exits, well before the deadline.
318
+ expect(ms).toBeLessThan(4000);
319
+ }, 30_000);
320
+
321
+ test('a hold taken with using is released at the end of its scope', async () => {
322
+ const {code, out} = await runApp(USING, 1, false);
323
+ expect(out).toContain('job done');
324
+ expect(code).toBe(0);
325
+ }, 30_000);
326
+
327
+ test('a shutdown callback is told when shutdown and cleanup begin', async () => {
328
+ const {code, out} = await runApp(CONTEXT, 1, false);
329
+ expect(out).toContain('began true true');
330
+ expect(out).toContain('cleanup');
331
+ expect(code).toBe(0);
332
+ }, 30_000);
333
+
334
+ test('a hold never released is cut off at the deadline', async () => {
335
+ const {code} = await runApp(STUCK, 1, false);
336
+ expect(code).toBe(1);
337
+ }, 30_000);
338
+
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
+
139
346
  test('a repeated signal does not cut shutdown short', async () => {
140
347
  received.length = 0;
141
- const code = await runApp(DRAINING, 2);
348
+ const {code} = await runApp(DRAINING, 2);
142
349
  expect(received).toContainEqual({
143
350
  name: 'in flight at signal',
144
351
  finished: true,
@@ -209,7 +416,9 @@ function fields(buf: Uint8Array, want: number): Uint8Array[] {
209
416
 
210
417
  /** A serialized `encore.runtime.v1.RuntimeConfig` exporting to `collector`,
211
418
  * base64-encoded. */
212
- function runtimeConfig(collector: string): string {
419
+ /** A runtime config hosting `svc`, exporting spans to `collector` if
420
+ * `telemetry`. */
421
+ function runtimeConfig(collector: string, telemetry: boolean): string {
213
422
  const varint = (n: number): number[] => {
214
423
  const out: number[] = [];
215
424
  for (;;) {
@@ -240,7 +449,7 @@ function runtimeConfig(collector: string): string {
240
449
  const destination = [...enumField(2, 1), ...msg(10, str(1, collector))];
241
450
  const deployment = [
242
451
  ...msg(5, str(1, 'svc')),
243
- ...msg(7, msg(4, msg(4, destination))),
452
+ ...(telemetry ? msg(7, msg(4, msg(4, destination))) : []),
244
453
  ];
245
454
  // RuntimeConfig{environment=1, deployment=3}
246
455
  const cfg = [...msg(1, environment), ...msg(3, deployment)];