@encore.dev/sdk 2.0.0-beta.4 → 2.0.0-beta.6

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,64 +1,340 @@
1
1
  import type {Runtime} from './napi/napi.cjs';
2
2
 
3
- type Drain = () => void | Promise<void>;
3
+ /** A phase of Encore's shutdown.
4
+ *
5
+ * - `not-started`: shutdown has not begun.
6
+ * - `started`: Pub/Sub intake has stopped; Encore waits for the message
7
+ * handlers in flight, and for the app's holds.
8
+ * - `cleanup`: Encore is closing its resources and flushing telemetry.
9
+ * - `completed`: cleanup has finished, whatever its result. */
10
+ export type ShutdownPhase = 'not-started' | 'started' | 'cleanup' | 'completed';
11
+
12
+ /** How a completed shutdown went: `success` if cleanup finished within the
13
+ * shutdown deadline, else `timeout`. A failed cleanup is a
14
+ * {@link ShutdownError}. */
15
+ export type ShutdownResult = 'success' | 'timeout';
16
+
17
+ /** Encore's cleanup failed, or the shutdown was used before it began. */
18
+ export class ShutdownError extends Error {
19
+ override name = 'ShutdownError';
20
+ }
21
+
22
+ /** Work the shutdown waits for before Encore cleans up: until it is
23
+ * released, or the shutdown deadline passes. Releasing it twice is harmless.
24
+ * As a `Disposable`, `using` releases it at the end of its scope. */
25
+ export interface ShutdownHold extends Disposable {
26
+ release(): void;
27
+ }
28
+
29
+ /** What a shutdown callback is told. */
30
+ export interface ShutdownContext {
31
+ /** Aborts when cleanup begins, the callback done or not: the shutdown
32
+ * deadline passed, or cleanup was forced. */
33
+ signal: AbortSignal;
34
+ /** When the shutdown deadline passes, in milliseconds since the epoch, as
35
+ * `Date.now()` counts them. */
36
+ deadline: number;
37
+ }
38
+
39
+ /** Called when shutdown begins. Cleanup waits for what it returns to settle. */
40
+ export type ShutdownCallback = (ctx: ShutdownContext) => void | Promise<void>;
4
41
 
5
42
  const SIGNALS = ['SIGTERM', 'SIGINT'] as const;
6
- const drains: Drain[] = [];
43
+ /** How long after the first signal the same one again is a new one, not the
44
+ * first delivered twice: a process group's runner may forward the signal its
45
+ * members already received. */
46
+ const REPEAT_MS = 1000;
47
+
7
48
  let runtime: Runtime | undefined;
8
- let signalled = false;
49
+ /** Whether the runtime runs the process ({@link runUntilShutdown}): it
50
+ * handles the signals natively, and its caller exits. */
51
+ let hosted = false;
52
+ const callbacks = new Set<ShutdownCallback>();
53
+ /** The callbacks Encore registered itself, as its API framework's server
54
+ * does: they don't say the app tells Encore of its shutdown. */
55
+ const ownCallbacks = new WeakSet<ShutdownCallback>();
56
+ let holds = 0;
57
+ let begun = false;
58
+ let markBegun!: () => void;
59
+ const begunAt = new Promise<void>(resolve => (markBegun = resolve));
60
+ let deadline = 0;
61
+ /** Whether Encore was told the app has drained: holds count no longer. */
62
+ let drained = false;
63
+ let cleaningUp = false;
64
+ const startAbort = new AbortController();
65
+ const cleanupAbort = new AbortController();
66
+ let markStarted!: () => void;
67
+ const startedAt = new Promise<void>(resolve => (markStarted = resolve));
68
+ let markCleanup!: () => void;
69
+ const cleanupAt = new Promise<void>(resolve => (markCleanup = resolve));
70
+ let completion: Promise<ShutdownResult> | undefined;
9
71
 
10
- /** Registers `drain` to run on SIGTERM or SIGINT, before Encore cleans up. */
11
- export function onShutdown(drain: Drain): void {
12
- drains.push(drain);
13
- }
72
+ /** The signal that began the shutdown: Encore then exits once it completes. */
73
+ let signalled: NodeJS.Signals | undefined;
74
+ let signalledAt = 0;
75
+ /** Held for an app that handles the signal itself without telling Encore of
76
+ * its shutdown, until it is done. */
77
+ let appHold: ShutdownHold | undefined;
78
+ /** The signal the app raised again, to die of once Encore has cleaned up. */
79
+ let reraised: NodeJS.Signals | undefined;
80
+ /** Whether Encore waits for cleanup to complete, to exit. */
81
+ let exiting = false;
82
+ /** Whether the process is on its way out, cleanup completed. */
83
+ let finished = false;
84
+
85
+ /** Aborts when shutdown begins: Encore takes no new Pub/Sub messages, and the
86
+ * app should stop taking work too. */
87
+ export const signal: AbortSignal = startAbort.signal;
14
88
 
15
- /** Shuts down on SIGTERM or SIGINT: runs the drains, waits for the runtime's
16
- * cleanup, and exits. Later signals are ignored: a process group's runner may
17
- * forward the one its members already received. */
18
- export function watchShutdownSignals(rt: Runtime): void {
89
+ /** Sets the runtime the shutdown runs on. */
90
+ export function setShutdownRuntime(rt: Runtime): void {
19
91
  runtime = rt;
20
- for (const signal of SIGNALS) process.on(signal, shutdown);
21
92
  }
22
93
 
23
- /** Runs `rt` until its shutdown completes, returning the exit code. The
24
- * runtime handles SIGTERM and SIGINT; on them the drains run, and cleanup
25
- * waits for them to settle. */
26
- export function runUntilShutdown(rt: Runtime): Promise<number> {
27
- runtime = rt;
28
- for (const signal of SIGNALS) {
29
- process.off(signal, shutdown);
30
- process.on(signal, drainOnce);
94
+ function rt(): Runtime {
95
+ if (!runtime) throw new ShutdownError('the Encore runtime is not loaded');
96
+ return runtime;
97
+ }
98
+
99
+ /** Holds the shutdown back: Encore cleans up once every hold is released, or
100
+ * the shutdown deadline passes. A hold taken once the app has drained, or
101
+ * cleanup has begun, comes released: cleanup does not wait for it. */
102
+ export function hold(): ShutdownHold {
103
+ if (drained || cleaningUp) {
104
+ console.warn(
105
+ 'encore: a shutdown hold was taken after the app drained; cleanup does not wait for it',
106
+ );
107
+ const release = () => {};
108
+ return {release, [Symbol.dispose]: release};
31
109
  }
32
- return rt.runForever(true);
33
- }
34
-
35
- function shutdown(): void {
36
- if (signalled) return;
37
- signalled = true;
38
- const rt = runtime!;
39
- const cooperative = drains.length > 0;
40
- rt.beginShutdown(cooperative);
41
- if (cooperative) drain(rt);
42
- rt.shutdownCompleted().then(
43
- code => process.exit(code),
44
- () => process.exit(1),
45
- );
110
+ holds++;
111
+ let held = true;
112
+ const release = () => {
113
+ if (!held) return;
114
+ held = false;
115
+ holds--;
116
+ settle();
117
+ };
118
+ return {release, [Symbol.dispose]: release};
46
119
  }
47
120
 
48
- function drainOnce(): void {
49
- if (signalled) return;
50
- signalled = true;
51
- drain(runtime!);
121
+ /** Holds the shutdown back until `work` settles. A rejection is logged. */
122
+ export function waitUntil(work: PromiseLike<unknown>): void {
123
+ const held = hold();
124
+ Promise.resolve(work)
125
+ .then(undefined, err => console.error('encore: shutdown work failed:', err))
126
+ .finally(() => held.release());
52
127
  }
53
128
 
54
- /** Runs the drains, then tells `rt` the app has drained. */
55
- function drain(rt: Runtime): void {
56
- void Promise.allSettled(drains.map(async drain => drain())).then(results => {
57
- for (const r of results) {
58
- if (r.status === 'rejected') {
59
- console.error('encore: shutdown drain failed:', r.reason);
129
+ /** Calls `callback` when shutdown begins, or at once if it has, holding
130
+ * cleanup back until it settles. Disposing of the returned value
131
+ * unregisters it. */
132
+ export function onShutdown(callback: ShutdownCallback): Disposable {
133
+ callbacks.add(callback);
134
+ if (begun) run(callback);
135
+ return {[Symbol.dispose]: () => void callbacks.delete(callback)};
136
+ }
137
+
138
+ /** Registers `callback` as {@link onShutdown} does, as Encore's own: it
139
+ * doesn't stop Encore from waiting for an app that handles the signal itself. */
140
+ export function onShutdownInternal(callback: ShutdownCallback): Disposable {
141
+ ownCallbacks.add(callback);
142
+ return onShutdown(callback);
143
+ }
144
+
145
+ /** Begins the shutdown, once: Encore stops taking Pub/Sub messages,
146
+ * {@link signal} aborts, and the {@link onShutdown} callbacks run. Encore
147
+ * cleans up once every hold is released, or the shutdown deadline passes.
148
+ * SIGTERM and SIGINT begin it, outside tests. */
149
+ export function begin(): void {
150
+ if (begun) return;
151
+ const r = rt();
152
+ begun = true;
153
+ r.beginShutdown(true);
154
+ deadline = Date.now() + r.shutdownTimeoutMs();
155
+ r.watchShutdown(onPhase);
156
+ if (!hosted) process.once('exit', finishOnExit);
157
+ markBegun();
158
+ startAbort.abort();
159
+ for (const callback of callbacks) run(callback);
160
+ settle();
161
+ }
162
+
163
+ /** The shutdown's phase now. */
164
+ export function phase(): ShutdownPhase {
165
+ return (runtime?.shutdownPhase() ?? 'not-started') as ShutdownPhase;
166
+ }
167
+
168
+ /** Resolves once the shutdown has begun and Pub/Sub intake has stopped.
169
+ * Waiting does not keep the process alive. */
170
+ export function started(): Promise<void> {
171
+ return startedAt;
172
+ }
173
+
174
+ /** Resolves once cleanup begins: the app drained, the shutdown deadline
175
+ * passed, or cleanup was forced. Waiting does not keep the process alive. */
176
+ export function cleanup(): Promise<void> {
177
+ return cleanupAt;
178
+ }
179
+
180
+ /** Resolves with the shutdown's result once cleanup has completed, after the
181
+ * deadline too; rejects with a {@link ShutdownError} if cleanup failed.
182
+ * Waiting keeps the process alive once the shutdown has begun. */
183
+ export function completed(): Promise<ShutdownResult> {
184
+ return (completion ??= begunAt
185
+ .then(() => rt().shutdownCompleted())
186
+ .then(result => {
187
+ if (result === 'failed') {
188
+ throw new ShutdownError('Encore resource cleanup failed');
60
189
  }
61
- }
62
- rt.markApplicationDrained();
190
+ return result as ShutdownResult;
191
+ }));
192
+ }
193
+
194
+ /** Begins cleanup without waiting for the app's holds or the Pub/Sub
195
+ * handlers in flight. Work still running may find its resources closed. */
196
+ export function forceCleanup(): void {
197
+ if (!begun) throw new ShutdownError('shutdown has not begun');
198
+ rt().forceShutdownCleanup();
199
+ }
200
+
201
+ /** Begins the shutdown on SIGTERM or SIGINT, and exits once it completes:
202
+ * with `process.exitCode` (0 unless the app set it) if cleanup finished
203
+ * within the shutdown deadline, else 1. A second SIGINT, a second Ctrl-C,
204
+ * forces cleanup.
205
+ *
206
+ * An app that listens for the signal itself and holds nothing is waited for
207
+ * until it raises the signal again, exits, or has closed everything it had
208
+ * open. */
209
+ export function watchShutdownSignals(): void {
210
+ for (const s of SIGNALS) process.on(s, onSignal);
211
+ }
212
+
213
+ /** Runs `rt` until its shutdown completes, returning the exit code. The
214
+ * runtime handles SIGTERM and SIGINT; on them the shutdown begins here too,
215
+ * and cleanup waits for the app's holds. */
216
+ export function runUntilShutdown(r: Runtime): Promise<number> {
217
+ runtime = r;
218
+ hosted = true;
219
+ return r.runForever(true);
220
+ }
221
+
222
+ function onSignal(sig: NodeJS.Signals): void {
223
+ if (hosted) return begin();
224
+ if (signalled || begun) return repeated(sig);
225
+ signalled = sig;
226
+ signalledAt = Date.now();
227
+ if (!appTellsShutdown() && process.listenerCount(sig) > 1) {
228
+ // The app's own listeners run after this one, and may take their time.
229
+ appHold = hold();
230
+ console.warn(
231
+ `encore: the app handles ${sig} itself; Encore cleans up once it is done. ` +
232
+ 'Register its shutdown with onShutdown() from @encore.dev/sdk/shutdown to say when.',
233
+ );
234
+ }
235
+ process.on('beforeExit', onIdle);
236
+ begin();
237
+ }
238
+
239
+ /** Whether the app holds the shutdown back, or has callbacks of its own. */
240
+ function appTellsShutdown(): boolean {
241
+ if (holds > 0) return true;
242
+ for (const callback of callbacks) {
243
+ if (!ownCallbacks.has(callback)) return true;
244
+ }
245
+ return false;
246
+ }
247
+
248
+ function repeated(sig: NodeJS.Signals): void {
249
+ if (!signalled) return;
250
+ if (appHold && sig === signalled && process.listenerCount(sig) === 1) {
251
+ // The app raised the signal again, having removed its own listener. Only
252
+ // the signal it handled counts: another may arrive while it still runs.
253
+ reraised = sig;
254
+ appHold.release();
255
+ return;
256
+ }
257
+ if (sig === 'SIGINT' && Date.now() - signalledAt > REPEAT_MS) {
258
+ rt().forceShutdownCleanup();
259
+ }
260
+ }
261
+
262
+ /** The event loop emptied. An app handling the signal itself is done; other
263
+ * holds are still waited for, until the deadline, as work that holds nothing
264
+ * open on the event loop may yet release them. */
265
+ function onIdle(): void {
266
+ // A turn later, as a signal the app raised as it closed its last handle is
267
+ // read in that turn: it says how the app meant to end.
268
+ setImmediate(() => {
269
+ appHold?.release();
270
+ if (!finished) exitOnCompletion();
63
271
  });
64
272
  }
273
+
274
+ function settle(): void {
275
+ if (begun && !drained && holds === 0) markDrained();
276
+ }
277
+
278
+ function markDrained(): void {
279
+ drained = true;
280
+ rt().markApplicationDrained();
281
+ // Now the app is done, the wait may hold the event loop open.
282
+ if (signalled) exitOnCompletion();
283
+ }
284
+
285
+ /** Exits once cleanup completes, holding the event loop open till then. */
286
+ function exitOnCompletion(): void {
287
+ if (exiting) return;
288
+ exiting = true;
289
+ completed().then(
290
+ result => exit(result),
291
+ () => exit('failed'),
292
+ );
293
+ }
294
+
295
+ function onPhase(phase: string, result?: string): void {
296
+ reached(phase);
297
+ // Cleanup also completes once the shutdown deadline passes, the app done
298
+ // or not; the exit code then says it was cut short.
299
+ if (phase === 'completed' && signalled) exit(result ?? 'failed');
300
+ }
301
+
302
+ /** Settles what waits for `phase`, and for the phases before it. */
303
+ function reached(phase: string): void {
304
+ if (phase === 'cleanup' || phase === 'completed') {
305
+ cleaningUp = true;
306
+ cleanupAbort.abort();
307
+ markCleanup();
308
+ }
309
+ markStarted();
310
+ }
311
+
312
+ /** Exits with 1 if cleanup failed or timed out, else as the app meant to:
313
+ * dying of the signal it raised again, or with its own exit code. */
314
+ function exit(result: string): void {
315
+ if (finished) return;
316
+ finished = true;
317
+ // Completion may be heard of before the phases leading to it.
318
+ reached('completed');
319
+ if (result !== 'success') process.exit(1);
320
+ if (reraised) {
321
+ for (const s of SIGNALS) process.off(s, onSignal);
322
+ process.kill(process.pid, reraised);
323
+ return;
324
+ }
325
+ process.exit();
326
+ }
327
+
328
+ /** An app that exits itself leaves no turn of the event loop to wait in:
329
+ * cleanup finishes here, blocking, and a failure overrides its exit code. */
330
+ function finishOnExit(): void {
331
+ if (finished) return;
332
+ finished = true;
333
+ const code = rt().finishShutdownSync();
334
+ if (code !== 0) process.exitCode = code;
335
+ }
336
+
337
+ function run(callback: ShutdownCallback): void {
338
+ const ctx = {signal: cleanupAbort.signal, deadline};
339
+ waitUntil((async () => callback(ctx))());
340
+ }
package/package.json CHANGED
@@ -119,5 +119,5 @@
119
119
  },
120
120
  "sideEffects": false,
121
121
  "type": "module",
122
- "version": "2.0.0-beta.4"
122
+ "version": "2.0.0-beta.6"
123
123
  }
package/services/index.ts CHANGED
@@ -4,6 +4,11 @@ import {runtimeConfig} from '../internal/runtime/mod';
4
4
  * The base URL of `service`, ending in `/`. Resolve relative paths against
5
5
  * it: `new URL("orders/1", serviceUrl("orders"))`. Throws if the service is
6
6
  * unknown to this process.
7
+ *
8
+ * No service runs under `encore test`. Every service still has a base URL
9
+ * there, but a call to it is answered with `501 Not Implemented` and an error
10
+ * saying which service and path the test called: mock the call in the test
11
+ * instead.
7
12
  */
8
13
  export function serviceUrl(service: string): URL {
9
14
  const base = runtimeConfig().services[service];
package/shutdown/mod.ts CHANGED
@@ -2,10 +2,13 @@
2
2
  * Graceful shutdown on SIGTERM or SIGINT.
3
3
  *
4
4
  * On the signal Encore stops Pub/Sub intake, waits for in-flight message
5
- * handlers, flushes metrics and telemetry, and exits: 0 when this finished
6
- * within the shutdown deadline, else 1.
5
+ * handlers and for the app's own work, closes its resources, flushes metrics
6
+ * and telemetry, and exits: with `process.exitCode` (0 unless the app set it)
7
+ * when this finished within the shutdown deadline, else 1. A second SIGINT,
8
+ * a second Ctrl-C, stops waiting for the app.
7
9
  *
8
- * An app serving requests drains them first by registering a drain:
10
+ * The app tells Encore what to wait for. A server drains its requests in an
11
+ * {@link onShutdown} callback:
9
12
  *
10
13
  * ```typescript
11
14
  * import { onShutdown } from "@encore.dev/sdk/shutdown";
@@ -14,11 +17,62 @@
14
17
  * onShutdown(() => new Promise((resolve) => server.close(() => resolve())));
15
18
  * ```
16
19
  *
17
- * Encore cleans up once every drain settles or the shutdown deadline passes,
18
- * whichever comes first.
20
+ * A framework that runs shutdown hooks of its own closes in one, rather than
21
+ * on a signal listener of its own; with NestJS, instead of
22
+ * `enableShutdownHooks()`:
23
+ *
24
+ * ```typescript
25
+ * onShutdown(() => app.close());
26
+ * ```
27
+ *
28
+ * Work that isn't a callback holds the shutdown back with {@link hold}, or
29
+ * {@link waitUntil} for a promise. `using` releases a hold at the end of its
30
+ * scope, a job's for example:
31
+ *
32
+ * ```typescript
33
+ * import * as shutdown from "@encore.dev/sdk/shutdown";
34
+ *
35
+ * async function processJob(job: Job) {
36
+ * using _ = shutdown.hold();
37
+ * await handle(job);
38
+ * }
39
+ * ```
40
+ *
41
+ * Encore cleans up once every hold is released, or the shutdown deadline
42
+ * passes, whichever comes first. {@link signal} aborts when the shutdown
43
+ * begins; a callback's own signal aborts when cleanup does.
44
+ *
45
+ * An app that listens for the signal itself and holds nothing, as NestJS's
46
+ * `enableShutdownHooks()` does, is waited for: Encore stops taking work at
47
+ * once and cleans up once the app raises the signal again, exits, or has
48
+ * closed everything it had open. The process then ends as the app meant it
49
+ * to, with its own exit code, unless the shutdown deadline passed first:
50
+ * then the exit code is 1.
51
+ *
52
+ * Connections the app's own database pools hold, as `pg` and Drizzle's do,
53
+ * stay open until the app closes them or the process exits.
19
54
  *
20
55
  * @module
21
56
  */
22
57
  import '../internal/runtime/mod';
23
58
 
24
- export {onShutdown} from '../internal/runtime/shutdown';
59
+ export {
60
+ begin,
61
+ cleanup,
62
+ completed,
63
+ forceCleanup,
64
+ hold,
65
+ onShutdown,
66
+ phase,
67
+ signal,
68
+ started,
69
+ waitUntil,
70
+ ShutdownError,
71
+ } from '../internal/runtime/shutdown';
72
+ export type {
73
+ ShutdownCallback,
74
+ ShutdownContext,
75
+ ShutdownHold,
76
+ ShutdownPhase,
77
+ ShutdownResult,
78
+ } from '../internal/runtime/shutdown';
@@ -292,6 +292,10 @@ export class DatabaseRef extends Queryable {
292
292
  return this.impl.connString();
293
293
  }
294
294
 
295
+ /**
296
+ * Acquires a database connection from the pool, with this handle's access.
297
+ * See {@link Database.acquire}.
298
+ */
295
299
  async acquire(): Promise<Connection> {
296
300
  return new Connection(await this.impl.acquire());
297
301
  }
@@ -365,6 +369,12 @@ export class Database extends BaseQueryExecutor {
365
369
  * Acquires a database connection from the database pool.
366
370
  *
367
371
  * When the connection is closed or is garbage-collected, it is returned to the pool.
372
+ * Settings and the role its session was given (`SET`, `set_config`,
373
+ * `SET ROLE`) are reset before the pool lends it again, when a statement
374
+ * sent on it did so: one a function or procedure changes is not noticed,
375
+ * and stays for the next borrower. To scope a setting to a unit of work,
376
+ * such as a tenant id for row-level security, set it in a transaction with
377
+ * `set_config(name, value, true)`, which ends with it.
368
378
  * @returns a new connection to the database
369
379
  */
370
380
  async acquire(): Promise<Connection> {