@encore.dev/sdk 2.0.0-beta.15 → 2.0.0-beta.17

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 (235) hide show
  1. package/README.md +111 -101
  2. package/app_meta.ts +56 -54
  3. package/config/config.ts +60 -57
  4. package/config/secrets.ts +45 -52
  5. package/config/value.ts +23 -26
  6. package/cron/mod.ts +28 -29
  7. package/dist/app_meta.d.ts +52 -50
  8. package/dist/app_meta.d.ts.map +1 -1
  9. package/dist/app_meta.js +2 -2
  10. package/dist/app_meta.js.map +1 -1
  11. package/dist/config/config.d.ts +58 -55
  12. package/dist/config/config.d.ts.map +1 -1
  13. package/dist/config/config.js +8 -9
  14. package/dist/config/config.js.map +1 -1
  15. package/dist/config/secrets.d.ts +45 -52
  16. package/dist/config/secrets.d.ts.map +1 -1
  17. package/dist/config/secrets.js +8 -9
  18. package/dist/config/secrets.js.map +1 -1
  19. package/dist/config/value.d.ts +20 -23
  20. package/dist/config/value.d.ts.map +1 -1
  21. package/dist/config/value.js +20 -23
  22. package/dist/config/value.js.map +1 -1
  23. package/dist/cron/mod.d.ts +26 -27
  24. package/dist/cron/mod.d.ts.map +1 -1
  25. package/dist/cron/mod.js +13 -14
  26. package/dist/cron/mod.js.map +1 -1
  27. package/dist/frontends/mod.d.ts +20 -19
  28. package/dist/frontends/mod.d.ts.map +1 -1
  29. package/dist/frontends/mod.js +20 -19
  30. package/dist/frontends/mod.js.map +1 -1
  31. package/dist/gateway/errors.d.ts +28 -30
  32. package/dist/gateway/errors.d.ts.map +1 -1
  33. package/dist/gateway/errors.js +29 -31
  34. package/dist/gateway/errors.js.map +1 -1
  35. package/dist/gateway/match.d.ts +54 -54
  36. package/dist/gateway/match.d.ts.map +1 -1
  37. package/dist/gateway/match.js +56 -56
  38. package/dist/gateway/match.js.map +1 -1
  39. package/dist/gateway/middleware.d.ts +62 -64
  40. package/dist/gateway/middleware.d.ts.map +1 -1
  41. package/dist/gateway/middleware.js +1 -1
  42. package/dist/gateway/middleware.js.map +1 -1
  43. package/dist/gateway/mod.d.ts +64 -67
  44. package/dist/gateway/mod.d.ts.map +1 -1
  45. package/dist/gateway/mod.js +72 -76
  46. package/dist/gateway/mod.js.map +1 -1
  47. package/dist/gateway/request.d.ts +138 -134
  48. package/dist/gateway/request.d.ts.map +1 -1
  49. package/dist/gateway/request.js +117 -108
  50. package/dist/gateway/request.js.map +1 -1
  51. package/dist/gateway/serve.d.ts +29 -34
  52. package/dist/gateway/serve.d.ts.map +1 -1
  53. package/dist/gateway/serve.js +51 -56
  54. package/dist/gateway/serve.js.map +1 -1
  55. package/dist/gateways/mod.d.ts +23 -21
  56. package/dist/gateways/mod.d.ts.map +1 -1
  57. package/dist/gateways/mod.js +25 -23
  58. package/dist/gateways/mod.js.map +1 -1
  59. package/dist/internal/runtime/napi/napi.cjs +1 -1
  60. package/dist/internal/runtime/napi/napi.d.cts +10 -3
  61. package/dist/internal/runtime/shutdown.d.ts +75 -57
  62. package/dist/internal/runtime/shutdown.d.ts.map +1 -1
  63. package/dist/internal/runtime/shutdown.js +88 -84
  64. package/dist/internal/runtime/shutdown.js.map +1 -1
  65. package/dist/log/logger.d.ts +43 -37
  66. package/dist/log/logger.d.ts.map +1 -1
  67. package/dist/log/logger.js +26 -25
  68. package/dist/log/logger.js.map +1 -1
  69. package/dist/metrics/mod.d.ts +133 -114
  70. package/dist/metrics/mod.d.ts.map +1 -1
  71. package/dist/metrics/mod.js +109 -101
  72. package/dist/metrics/mod.js.map +1 -1
  73. package/dist/otel.d.ts +6 -3
  74. package/dist/otel.d.ts.map +1 -1
  75. package/dist/otel.js +6 -3
  76. package/dist/otel.js.map +1 -1
  77. package/dist/pubsub/subscription.d.ts +88 -116
  78. package/dist/pubsub/subscription.d.ts.map +1 -1
  79. package/dist/pubsub/subscription.js +14 -17
  80. package/dist/pubsub/subscription.js.map +1 -1
  81. package/dist/pubsub/topic.d.ts +86 -113
  82. package/dist/pubsub/topic.d.ts.map +1 -1
  83. package/dist/pubsub/topic.js +68 -82
  84. package/dist/pubsub/topic.js.map +1 -1
  85. package/dist/reqctx/mod.d.ts +83 -86
  86. package/dist/reqctx/mod.d.ts.map +1 -1
  87. package/dist/reqctx/mod.js +39 -41
  88. package/dist/reqctx/mod.js.map +1 -1
  89. package/dist/services/index.d.ts +76 -75
  90. package/dist/services/index.d.ts.map +1 -1
  91. package/dist/services/index.js +73 -71
  92. package/dist/services/index.js.map +1 -1
  93. package/dist/shutdown/mod.d.ts +26 -25
  94. package/dist/shutdown/mod.d.ts.map +1 -1
  95. package/dist/shutdown/mod.js +26 -25
  96. package/dist/shutdown/mod.js.map +1 -1
  97. package/dist/storage/clickhouse/database.d.ts +113 -115
  98. package/dist/storage/clickhouse/database.d.ts.map +1 -1
  99. package/dist/storage/clickhouse/database.js +65 -79
  100. package/dist/storage/clickhouse/database.js.map +1 -1
  101. package/dist/storage/clickhouse/errors.d.ts +25 -26
  102. package/dist/storage/clickhouse/errors.d.ts.map +1 -1
  103. package/dist/storage/clickhouse/errors.js +15 -17
  104. package/dist/storage/clickhouse/errors.js.map +1 -1
  105. package/dist/storage/clickhouse/mod.d.ts +10 -10
  106. package/dist/storage/clickhouse/mod.js +10 -10
  107. package/dist/storage/objects/bucket.d.ts +196 -225
  108. package/dist/storage/objects/bucket.d.ts.map +1 -1
  109. package/dist/storage/objects/bucket.js +71 -84
  110. package/dist/storage/objects/bucket.js.map +1 -1
  111. package/dist/storage/objects/error.d.ts +4 -4
  112. package/dist/storage/objects/error.js +4 -4
  113. package/dist/storage/postgres/database.d.ts +124 -149
  114. package/dist/storage/postgres/database.d.ts.map +1 -1
  115. package/dist/storage/postgres/database.js +98 -135
  116. package/dist/storage/postgres/database.js.map +1 -1
  117. package/dist/storage/postgres/errors.d.ts +42 -48
  118. package/dist/storage/postgres/errors.d.ts.map +1 -1
  119. package/dist/storage/postgres/errors.js +44 -51
  120. package/dist/storage/postgres/errors.js.map +1 -1
  121. package/dist/storage/postgres/interval.d.ts +19 -19
  122. package/dist/storage/postgres/interval.d.ts.map +1 -1
  123. package/dist/storage/postgres/interval.js +21 -21
  124. package/dist/storage/postgres/interval.js.map +1 -1
  125. package/dist/storage/redis/bitfield.d.ts +48 -23
  126. package/dist/storage/redis/bitfield.d.ts.map +1 -1
  127. package/dist/storage/redis/bitfield.js +38 -19
  128. package/dist/storage/redis/bitfield.js.map +1 -1
  129. package/dist/storage/redis/command.d.ts +16 -12
  130. package/dist/storage/redis/command.d.ts.map +1 -1
  131. package/dist/storage/redis/command.js +16 -12
  132. package/dist/storage/redis/command.js.map +1 -1
  133. package/dist/storage/redis/commands.d.ts +99 -100
  134. package/dist/storage/redis/commands.d.ts.map +1 -1
  135. package/dist/storage/redis/commands.js +84 -85
  136. package/dist/storage/redis/commands.js.map +1 -1
  137. package/dist/storage/redis/database.d.ts +138 -122
  138. package/dist/storage/redis/database.d.ts.map +1 -1
  139. package/dist/storage/redis/database.js +120 -101
  140. package/dist/storage/redis/database.js.map +1 -1
  141. package/dist/storage/redis/mod.d.ts +52 -48
  142. package/dist/storage/redis/mod.d.ts.map +1 -1
  143. package/dist/storage/redis/mod.js +52 -48
  144. package/dist/storage/redis/mod.js.map +1 -1
  145. package/dist/storage/redis/options.d.ts +26 -24
  146. package/dist/storage/redis/options.d.ts.map +1 -1
  147. package/dist/storage/redis/options.js.map +1 -1
  148. package/dist/storage/redis/pubsub.d.ts +16 -16
  149. package/dist/storage/redis/pubsub.d.ts.map +1 -1
  150. package/dist/storage/redis/pubsub.js +14 -14
  151. package/dist/storage/redis/pubsub.js.map +1 -1
  152. package/dist/storage/redis/reply.d.ts +80 -72
  153. package/dist/storage/redis/reply.d.ts.map +1 -1
  154. package/dist/storage/redis/reply.js +53 -46
  155. package/dist/storage/redis/reply.js.map +1 -1
  156. package/dist/storage/redis/scan.d.ts +4 -4
  157. package/dist/storage/redis/scan.d.ts.map +1 -1
  158. package/dist/storage/redis/scan.js +6 -6
  159. package/dist/storage/redis/scan.js.map +1 -1
  160. package/dist/storage/redis/script.d.ts +28 -21
  161. package/dist/storage/redis/script.d.ts.map +1 -1
  162. package/dist/storage/redis/script.js +29 -22
  163. package/dist/storage/redis/script.js.map +1 -1
  164. package/dist/storage/redis/target.d.ts +17 -1
  165. package/dist/storage/redis/target.d.ts.map +1 -1
  166. package/dist/storage/redis/target.js +30 -1
  167. package/dist/storage/redis/target.js.map +1 -1
  168. package/dist/storage/redis/wire.d.ts +6 -6
  169. package/dist/storage/redis/wire.d.ts.map +1 -1
  170. package/dist/storage/redis/wire.js +6 -6
  171. package/dist/storage/redis/wire.js.map +1 -1
  172. package/dist/testing/mod.d.ts +83 -88
  173. package/dist/testing/mod.d.ts.map +1 -1
  174. package/dist/testing/mod.js +75 -81
  175. package/dist/testing/mod.js.map +1 -1
  176. package/dist/testing/playwright.d.ts +28 -32
  177. package/dist/testing/playwright.d.ts.map +1 -1
  178. package/dist/testing/playwright.js +22 -27
  179. package/dist/testing/playwright.js.map +1 -1
  180. package/dist/testing/puppeteer.d.ts +11 -12
  181. package/dist/testing/puppeteer.d.ts.map +1 -1
  182. package/dist/testing/puppeteer.js +17 -18
  183. package/dist/testing/puppeteer.js.map +1 -1
  184. package/dist/testing/system.d.ts +72 -90
  185. package/dist/testing/system.d.ts.map +1 -1
  186. package/dist/testing/system.js +90 -107
  187. package/dist/testing/system.js.map +1 -1
  188. package/dist/tsconfig.build.tsbuildinfo +1 -1
  189. package/frontends/mod.test.ts +6 -2
  190. package/frontends/mod.ts +20 -19
  191. package/gateway/errors.ts +30 -32
  192. package/gateway/match.ts +61 -57
  193. package/gateway/middleware.ts +62 -64
  194. package/gateway/mod.ts +73 -76
  195. package/gateway/request.ts +143 -140
  196. package/gateway/serve.ts +58 -63
  197. package/gateways/mod.ts +25 -23
  198. package/internal/runtime/napi/napi.cjs +1 -1
  199. package/internal/runtime/napi/napi.d.cts +10 -3
  200. package/internal/runtime/shutdown.ts +113 -101
  201. package/log/logger.test.ts +8 -0
  202. package/log/logger.ts +48 -45
  203. package/metrics/mod.ts +138 -122
  204. package/otel.ts +6 -3
  205. package/package.json +1 -1
  206. package/pubsub/subscription.ts +93 -123
  207. package/pubsub/topic.ts +96 -130
  208. package/reqctx/mod.ts +83 -86
  209. package/services/index.ts +78 -78
  210. package/shutdown/mod.ts +26 -25
  211. package/storage/clickhouse/database.ts +115 -129
  212. package/storage/clickhouse/errors.ts +27 -29
  213. package/storage/clickhouse/mod.ts +10 -10
  214. package/storage/objects/bucket.ts +209 -239
  215. package/storage/objects/error.ts +4 -4
  216. package/storage/postgres/database.ts +131 -164
  217. package/storage/postgres/errors.ts +45 -52
  218. package/storage/postgres/interval.ts +21 -21
  219. package/storage/redis/bitfield.ts +51 -26
  220. package/storage/redis/command.ts +16 -12
  221. package/storage/redis/commands.ts +99 -100
  222. package/storage/redis/database.ts +145 -123
  223. package/storage/redis/mod.ts +52 -48
  224. package/storage/redis/options.ts +26 -24
  225. package/storage/redis/pubsub.ts +14 -14
  226. package/storage/redis/redis.test.ts +17 -2
  227. package/storage/redis/reply.ts +85 -77
  228. package/storage/redis/scan.ts +6 -6
  229. package/storage/redis/script.ts +29 -22
  230. package/storage/redis/target.ts +34 -1
  231. package/storage/redis/wire.ts +8 -8
  232. package/testing/mod.ts +99 -105
  233. package/testing/playwright.ts +32 -37
  234. package/testing/puppeteer.ts +22 -23
  235. package/testing/system.ts +117 -133
@@ -1,70 +1,77 @@
1
1
  import type {Runtime} from './napi/napi.cjs';
2
2
 
3
- /** A phase of Encore's shutdown.
3
+ /**
4
+ * Current phase of Encore's graceful shutdown:
4
5
  *
5
6
  * - `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. */
7
+ * - `started`: Pub/Sub intake has stopped; Encore is waiting for in-flight
8
+ * message handlers and application holds to finish.
9
+ * - `cleanup`: Encore is closing managed resources and flushing telemetry.
10
+ * - `completed`: cleanup has finished (whether it succeeded or timed out).
11
+ */
10
12
  export type ShutdownPhase = 'not-started' | 'started' | 'cleanup' | 'completed';
11
13
 
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}. */
14
+ /**
15
+ * Outcome of a completed shutdown: `'success'` if cleanup finished within the
16
+ * shutdown deadline, or `'timeout'` if the deadline expired. A failed cleanup
17
+ * rejects with {@link ShutdownError}.
18
+ */
15
19
  export type ShutdownResult = 'success' | 'timeout';
16
20
 
17
- /** Encore's cleanup failed, or the shutdown was used before it began. */
21
+ /** Thrown when Encore's resource cleanup fails or a shutdown API is called invalidly. */
18
22
  export class ShutdownError extends Error {
19
23
  override name = 'ShutdownError';
20
24
  }
21
25
 
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. */
26
+ /**
27
+ * A hold that delays Encore resource cleanup until {@link release} is called
28
+ * or the shutdown deadline expires. Calling `release()` more than once is a
29
+ * no-op. Implements `Disposable` so `using` releases it automatically at the
30
+ * end of a scope.
31
+ */
25
32
  export interface ShutdownHold extends Disposable {
26
33
  release(): void;
27
34
  }
28
35
 
29
- /** What a shutdown callback is told. */
36
+ /** Context passed to an {@link onShutdown} callback. */
30
37
  export interface ShutdownContext {
31
- /** Aborts when cleanup begins, the callback done or not: the shutdown
32
- * deadline passed, or cleanup was forced. */
38
+ /** Aborts when resource cleanup begins (either because the shutdown deadline
39
+ * expired or because cleanup was forced), even if the callback is still running. */
33
40
  signal: AbortSignal;
34
- /** When the shutdown deadline passes, in milliseconds since the epoch, as
35
- * `Date.now()` counts them. */
41
+ /** Timestamp when the shutdown deadline expires, in milliseconds since the
42
+ * Unix epoch (matching `Date.now()`). */
36
43
  deadline: number;
37
44
  }
38
45
 
39
- /** Called when shutdown begins. Cleanup waits for what it returns to settle. */
46
+ /** Callback invoked when shutdown begins. Resource cleanup waits for any
47
+ * returned promise to settle (up to the shutdown deadline). */
40
48
  export type ShutdownCallback = (ctx: ShutdownContext) => void | Promise<void>;
41
49
 
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. */
50
+ /** Signals that initiate graceful shutdown. On Windows under Node.js, includes
51
+ * `SIGBREAK` (sent by the daemon when a process does not handle stop requests);
52
+ * Bun terminates immediately on `SIGBREAK` regardless of listeners. */
45
53
  const SIGNALS: readonly NodeJS.Signals[] =
46
54
  process.platform === 'win32' && !process.versions.bun
47
55
  ? ['SIGTERM', 'SIGINT', 'SIGBREAK']
48
56
  : ['SIGTERM', 'SIGINT'];
49
- /** How long after the first signal the same one again is a new one, not the
50
- * first delivered twice: a process group's runner may forward the signal its
51
- * members already received. */
57
+ /** Minimum interval after the first signal before the same signal is treated
58
+ * as a deliberate repeat rather than a duplicate forwarded by a process group. */
52
59
  const REPEAT_MS = 1000;
53
60
 
54
61
  let runtime: Runtime | undefined;
55
- /** Whether the runtime runs the process ({@link runUntilShutdown}): it
56
- * handles the signals natively, and its caller exits. */
62
+ /** Whether the native runtime owns the event loop ({@link runUntilShutdown}),
63
+ * handling signals natively and letting its caller exit. */
57
64
  let hosted = false;
58
65
  const callbacks = new Set<ShutdownCallback>();
59
- /** The callbacks Encore registered itself, as its API framework's server
60
- * does: they don't say the app tells Encore of its shutdown. */
66
+ /** Callbacks registered internally by Encore (such as the API framework's
67
+ * server), which do not count as application-managed shutdown hooks. */
61
68
  const ownCallbacks = new WeakSet<ShutdownCallback>();
62
69
  let holds = 0;
63
70
  let begun = false;
64
71
  let markBegun!: () => void;
65
72
  const begunAt = new Promise<void>(resolve => (markBegun = resolve));
66
73
  let deadline = 0;
67
- /** Whether Encore was told the app has drained: holds count no longer. */
74
+ /** Whether the application has already been marked drained (new holds no longer delay cleanup). */
68
75
  let drained = false;
69
76
  let cleaningUp = false;
70
77
  const startAbort = new AbortController();
@@ -75,29 +82,27 @@ let markCleanup!: () => void;
75
82
  const cleanupAt = new Promise<void>(resolve => (markCleanup = resolve));
76
83
  let completion: Promise<ShutdownResult> | undefined;
77
84
 
78
- /** The signals that force cleanup when they come again: a second Ctrl-C, and
79
- * for a gateway program a second SIGTERM, which is how the supervisor stops
80
- * waiting for its drain. */
85
+ /** Signals that force immediate cleanup when received a second time (a second
86
+ * Ctrl-C, or for gateway processes a second `SIGTERM` from the supervisor). */
81
87
  const forcing = new Set<NodeJS.Signals>(['SIGINT']);
82
88
 
83
- /** The signal that began the shutdown: Encore then exits once it completes. */
89
+ /** Signal that initiated shutdown; when set, Encore exits the process once cleanup finishes. */
84
90
  let signalled: NodeJS.Signals | undefined;
85
91
  let signalledAt = 0;
86
- /** Held for an app that handles the signal itself without telling Encore of
87
- * its shutdown, until it is done. */
92
+ /** Automatic hold kept while an application handles the shutdown signal itself. */
88
93
  let appHold: ShutdownHold | undefined;
89
- /** The signal the app raised again, to die of once Encore has cleaned up. */
94
+ /** Signal re-raised by the application after removing its own listener, re-sent after cleanup. */
90
95
  let reraised: NodeJS.Signals | undefined;
91
- /** Whether Encore waits for cleanup to complete, to exit. */
96
+ /** Whether Encore is currently waiting on cleanup to exit the process. */
92
97
  let exiting = false;
93
- /** Whether the process is on its way out, cleanup completed. */
98
+ /** Whether the process exit path has already started. */
94
99
  let finished = false;
95
100
 
96
- /** Aborts when shutdown begins: Encore takes no new Pub/Sub messages, and the
97
- * app should stop taking work too. */
101
+ /** Aborts as soon as shutdown begins: Encore stops accepting new Pub/Sub
102
+ * messages, and your application should stop accepting new work as well. */
98
103
  export const signal: AbortSignal = startAbort.signal;
99
104
 
100
- /** Sets the runtime the shutdown runs on. */
105
+ /** Sets the native runtime instance used to coordinate shutdown. */
101
106
  export function setShutdownRuntime(rt: Runtime): void {
102
107
  runtime = rt;
103
108
  }
@@ -107,13 +112,16 @@ function rt(): Runtime {
107
112
  return runtime;
108
113
  }
109
114
 
110
- /** Holds the shutdown back: Encore cleans up once every hold is released, or
111
- * the shutdown deadline passes. A hold taken once the app has drained, or
112
- * cleanup has begun, comes released: cleanup does not wait for it. */
115
+ /**
116
+ * Delays Encore's resource cleanup until the returned hold is released or the
117
+ * shutdown deadline expires. If called after the application has already
118
+ * drained or cleanup has begun, returns an already-released hold and logs a
119
+ * warning.
120
+ */
113
121
  export function hold(): ShutdownHold {
114
122
  if (drained || cleaningUp) {
115
123
  console.warn(
116
- 'encore: a shutdown hold was taken after the app drained; cleanup does not wait for it',
124
+ 'encore: shutdown hold acquired after the app drained; cleanup will not wait for it',
117
125
  );
118
126
  const release = () => {};
119
127
  return {release, [Symbol.dispose]: release};
@@ -129,7 +137,7 @@ export function hold(): ShutdownHold {
129
137
  return {release, [Symbol.dispose]: release};
130
138
  }
131
139
 
132
- /** Holds the shutdown back until `work` settles. A rejection is logged. */
140
+ /** Delays resource cleanup until `work` settles. Any rejection is logged. */
133
141
  export function waitUntil(work: PromiseLike<unknown>): void {
134
142
  const held = hold();
135
143
  Promise.resolve(work)
@@ -137,26 +145,31 @@ export function waitUntil(work: PromiseLike<unknown>): void {
137
145
  .finally(() => held.release());
138
146
  }
139
147
 
140
- /** Calls `callback` when shutdown begins, or at once if it has, holding
141
- * cleanup back until it settles. Disposing of the returned value
142
- * unregisters it. */
148
+ /**
149
+ * Registers `callback` to run when shutdown begins (or immediately if shutdown
150
+ * has already begun), delaying resource cleanup until it settles. Disposing
151
+ * the returned handle unregisters the callback.
152
+ */
143
153
  export function onShutdown(callback: ShutdownCallback): Disposable {
144
154
  callbacks.add(callback);
145
155
  if (begun) run(callback);
146
156
  return {[Symbol.dispose]: () => void callbacks.delete(callback)};
147
157
  }
148
158
 
149
- /** Registers `callback` as {@link onShutdown} does, as Encore's own: it
150
- * doesn't stop Encore from waiting for an app that handles the signal itself. */
159
+ /** Registers an Encore-internal shutdown callback without disabling automatic
160
+ * detection of application-owned signal handlers. */
151
161
  export function onShutdownInternal(callback: ShutdownCallback): Disposable {
152
162
  ownCallbacks.add(callback);
153
163
  return onShutdown(callback);
154
164
  }
155
165
 
156
- /** Begins the shutdown, once: Encore stops taking Pub/Sub messages,
157
- * {@link signal} aborts, and the {@link onShutdown} callbacks run. Encore
158
- * cleans up once every hold is released, or the shutdown deadline passes.
159
- * SIGTERM and SIGINT begin it, outside tests. */
166
+ /**
167
+ * Initiates graceful shutdown (idempotent): stops Pub/Sub intake, aborts
168
+ * {@link signal}, and invokes all registered {@link onShutdown} callbacks.
169
+ * Encore cleans up resources once every hold is released or the shutdown
170
+ * deadline expires. Outside tests, `SIGTERM` and `SIGINT` call this
171
+ * automatically.
172
+ */
160
173
  export function begin(): void {
161
174
  if (begun) return;
162
175
  const r = rt();
@@ -171,26 +184,27 @@ export function begin(): void {
171
184
  settle();
172
185
  }
173
186
 
174
- /** The shutdown's phase now. */
187
+ /** Returns the current shutdown phase. */
175
188
  export function phase(): ShutdownPhase {
176
189
  return (runtime?.shutdownPhase() ?? 'not-started') as ShutdownPhase;
177
190
  }
178
191
 
179
- /** Resolves once the shutdown has begun and Pub/Sub intake has stopped.
180
- * Waiting does not keep the process alive. */
192
+ /** Resolves once shutdown has begun and Pub/Sub intake has stopped. Awaiting
193
+ * this promise does not keep the event loop alive. */
181
194
  export function started(): Promise<void> {
182
195
  return startedAt;
183
196
  }
184
197
 
185
- /** Resolves once cleanup begins: the app drained, the shutdown deadline
186
- * passed, or cleanup was forced. Waiting does not keep the process alive. */
198
+ /** Resolves once resource cleanup begins (because the app drained, the
199
+ * shutdown deadline expired, or cleanup was forced). Awaiting this promise
200
+ * does not keep the event loop alive. */
187
201
  export function cleanup(): Promise<void> {
188
202
  return cleanupAt;
189
203
  }
190
204
 
191
- /** Resolves with the shutdown's result once cleanup has completed, after the
192
- * deadline too; rejects with a {@link ShutdownError} if cleanup failed.
193
- * Waiting keeps the process alive once the shutdown has begun. */
205
+ /** Resolves with the shutdown result once cleanup completes (even after the
206
+ * deadline), or rejects with {@link ShutdownError} if cleanup failed. Once
207
+ * shutdown has begun, awaiting this keeps the event loop alive. */
194
208
  export function completed(): Promise<ShutdownResult> {
195
209
  return (completion ??= begunAt
196
210
  .then(() => rt().shutdownCompleted())
@@ -202,40 +216,41 @@ export function completed(): Promise<ShutdownResult> {
202
216
  }));
203
217
  }
204
218
 
205
- /** Begins cleanup without waiting for the app's holds or the Pub/Sub
206
- * handlers in flight. Work still running may find its resources closed. */
219
+ /** Starts resource cleanup immediately without waiting for application holds
220
+ * or in-flight Pub/Sub handlers. Work still running may encounter closed
221
+ * resources. */
207
222
  export function forceCleanup(): void {
208
223
  if (!begun) throw new ShutdownError('shutdown has not begun');
209
224
  rt().forceShutdownCleanup();
210
225
  }
211
226
 
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:
214
- * with `process.exitCode` (0 unless the app set it) if cleanup finished
215
- * within the shutdown deadline, else 1. A second SIGINT, a second Ctrl-C,
216
- * forces cleanup.
227
+ /**
228
+ * Installs signal listeners for `SIGTERM` and `SIGINT` (and daemon stop
229
+ * requests on Windows) to drive graceful shutdown and exit once cleanup
230
+ * completes. Exits with `process.exitCode` (0 unless set) if cleanup succeeds
231
+ * within the deadline, or 1 otherwise. A second `SIGINT` forces cleanup.
217
232
  *
218
- * An app that listens for the signal itself and holds nothing is waited for
219
- * until it raises the signal again, exits, or has closed everything it had
220
- * open. */
233
+ * If the application registers its own signal listener without using Encore's
234
+ * shutdown hooks, Encore waits until the application re-raises the signal,
235
+ * exits, or drains its event loop.
236
+ */
221
237
  export function watchShutdownSignals(): void {
222
238
  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.
239
+ // Windows has no SIGTERM: the daemon signals a named event instead, which we
240
+ // surface as SIGTERM so application listeners see it too.
225
241
  rt().watchStopRequest(() => void process.emit('SIGTERM', 'SIGTERM'));
226
242
  }
227
243
 
228
- /** Runs `rt` until its shutdown completes, returning the exit code. The
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. */
244
+ /** Runs `r` until shutdown completes and returns the exit code. The native
245
+ * runtime handles `SIGTERM`, `SIGINT`, and Windows console close events,
246
+ * triggers JS shutdown here, and waits for application holds before cleanup. */
232
247
  export function runUntilShutdown(r: Runtime): Promise<number> {
233
248
  runtime = r;
234
249
  hosted = true;
235
250
  return r.runForever(true, begin);
236
251
  }
237
252
 
238
- /** Has `sig` force cleanup when it comes again, as a second SIGINT does. */
253
+ /** Configures `sig` to force immediate cleanup when received a second time. */
239
254
  export function forceCleanupOnRepeat(sig: NodeJS.Signals): void {
240
255
  forcing.add(sig);
241
256
  }
@@ -246,18 +261,18 @@ function onSignal(sig: NodeJS.Signals): void {
246
261
  signalled = sig;
247
262
  signalledAt = Date.now();
248
263
  if (!appTellsShutdown() && process.listenerCount(sig) > 1) {
249
- // The app's own listeners run after this one, and may take their time.
264
+ // The app's own listeners run after this one and may take time to drain.
250
265
  appHold = hold();
251
266
  console.warn(
252
- `encore: the app handles ${sig} itself; Encore cleans up once it is done. ` +
253
- 'Register its shutdown with onShutdown() from @encore.dev/sdk/shutdown to say when.',
267
+ `encore: detected custom ${sig} handler; Encore will clean up after it finishes. ` +
268
+ 'Use onShutdown() from @encore.dev/sdk/shutdown to coordinate shutdown explicitly.',
254
269
  );
255
270
  }
256
271
  process.on('beforeExit', onIdle);
257
272
  begin();
258
273
  }
259
274
 
260
- /** Whether the app holds the shutdown back, or has callbacks of its own. */
275
+ /** Returns whether the application has any active holds or user-registered callbacks. */
261
276
  function appTellsShutdown(): boolean {
262
277
  if (holds > 0) return true;
263
278
  for (const callback of callbacks) {
@@ -269,8 +284,7 @@ function appTellsShutdown(): boolean {
269
284
  function repeated(sig: NodeJS.Signals): void {
270
285
  if (!signalled) return;
271
286
  if (appHold && sig === signalled && process.listenerCount(sig) === 1) {
272
- // The app raised the signal again, having removed its own listener. Only
273
- // the signal it handled counts: another may arrive while it still runs.
287
+ // The app removed its own listener and re-raised the original signal.
274
288
  reraised = sig;
275
289
  appHold.release();
276
290
  return;
@@ -280,12 +294,11 @@ function repeated(sig: NodeJS.Signals): void {
280
294
  }
281
295
  }
282
296
 
283
- /** The event loop emptied. An app handling the signal itself is done; other
284
- * holds are still waited for, until the deadline, as work that holds nothing
285
- * open on the event loop may yet release them. */
297
+ /** Called when the event loop empties: releases any automatic app-signal hold
298
+ * while still honoring explicit holds until the deadline. */
286
299
  function onIdle(): void {
287
- // A turn later, as a signal the app raised as it closed its last handle is
288
- // read in that turn: it says how the app meant to end.
300
+ // Defer one turn so a signal re-raised while closing the last handle is
301
+ // observed first.
289
302
  setImmediate(() => {
290
303
  appHold?.release();
291
304
  if (!finished) exitOnCompletion();
@@ -299,11 +312,11 @@ function settle(): void {
299
312
  function markDrained(): void {
300
313
  drained = true;
301
314
  rt().markApplicationDrained();
302
- // Now the app is done, the wait may hold the event loop open.
315
+ // Once the app is drained, keep the event loop alive while cleanup finishes.
303
316
  if (signalled) exitOnCompletion();
304
317
  }
305
318
 
306
- /** Exits once cleanup completes, holding the event loop open till then. */
319
+ /** Waits for cleanup to complete (keeping the event loop alive) and exits. */
307
320
  function exitOnCompletion(): void {
308
321
  if (exiting) return;
309
322
  exiting = true;
@@ -315,12 +328,11 @@ function exitOnCompletion(): void {
315
328
 
316
329
  function onPhase(phase: string, result?: string): void {
317
330
  reached(phase);
318
- // Cleanup also completes once the shutdown deadline passes, the app done
319
- // or not; the exit code then says it was cut short.
331
+ // Cleanup also completes if the deadline expires before the app finishes.
320
332
  if (phase === 'completed' && signalled) exit(result ?? 'failed');
321
333
  }
322
334
 
323
- /** Settles what waits for `phase`, and for the phases before it. */
335
+ /** Resolves promises waiting on `phase` and any earlier phases. */
324
336
  function reached(phase: string): void {
325
337
  if (phase === 'cleanup' || phase === 'completed') {
326
338
  cleaningUp = true;
@@ -330,12 +342,12 @@ function reached(phase: string): void {
330
342
  markStarted();
331
343
  }
332
344
 
333
- /** Exits with 1 if cleanup failed or timed out, else as the app meant to:
334
- * dying of the signal it raised again, or with its own exit code. */
345
+ /** Exits with 1 if cleanup failed or timed out; otherwise re-raises any signal
346
+ * the application re-raised, or exits with `process.exitCode`. */
335
347
  function exit(result: string): void {
336
348
  if (finished) return;
337
349
  finished = true;
338
- // Completion may be heard of before the phases leading to it.
350
+ // Completion may arrive before intermediate phase callbacks.
339
351
  reached('completed');
340
352
  if (result !== 'success') process.exit(1);
341
353
  if (reraised) {
@@ -346,8 +358,8 @@ function exit(result: string): void {
346
358
  process.exit();
347
359
  }
348
360
 
349
- /** An app that exits itself leaves no turn of the event loop to wait in:
350
- * cleanup finishes here, blocking, and a failure overrides its exit code. */
361
+ /** Handles synchronous process exit initiated by the application: finishes
362
+ * cleanup synchronously and overrides the exit code if cleanup fails. */
351
363
  function finishOnExit(): void {
352
364
  if (finished) return;
353
365
  finished = true;
@@ -126,6 +126,14 @@ describe('Logger', () => {
126
126
  expect(fatal).toMatchObject(exception);
127
127
  });
128
128
 
129
+ test('an empty message is distinct from an omitted message', () => {
130
+ const {log, records} = setup();
131
+ const err = new Error('boom');
132
+ log.error(err, '');
133
+ log.error(err);
134
+ expect(records().map(r => r.message)).toEqual(['', undefined]);
135
+ });
136
+
129
137
  test('a message is not an error; a non-error is wrapped', () => {
130
138
  const {log, records} = setup();
131
139
  log.warn('plain failure', {id: 1});