@fuzdev/fuz_app 0.183.0 → 0.185.0

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 (223) hide show
  1. package/dist/actions/CLAUDE.md +538 -1223
  2. package/dist/actions/action_codegen.d.ts +1 -1
  3. package/dist/actions/action_codegen.d.ts.map +1 -1
  4. package/dist/actions/action_codegen.js +3 -2
  5. package/dist/actions/connection_closer.d.ts +11 -9
  6. package/dist/actions/connection_closer.d.ts.map +1 -1
  7. package/dist/actions/connection_closer.js +11 -9
  8. package/dist/actions/frontend_rpc_client.d.ts +1 -1
  9. package/dist/actions/register_action_ws.d.ts +21 -1
  10. package/dist/actions/register_action_ws.d.ts.map +1 -1
  11. package/dist/actions/register_action_ws.js +2 -1
  12. package/dist/actions/ws_socket_session.d.ts +25 -4
  13. package/dist/actions/ws_socket_session.d.ts.map +1 -1
  14. package/dist/actions/ws_socket_session.js +81 -25
  15. package/dist/auth/CLAUDE.md +433 -1048
  16. package/dist/auth/account_queries.d.ts +1 -1
  17. package/dist/auth/account_queries.js +1 -1
  18. package/dist/auth/account_routes.d.ts +4 -5
  19. package/dist/auth/account_routes.d.ts.map +1 -1
  20. package/dist/auth/account_routes.js +8 -10
  21. package/dist/auth/admin_actions.d.ts.map +1 -1
  22. package/dist/auth/admin_actions.js +10 -11
  23. package/dist/auth/api_token.d.ts +20 -3
  24. package/dist/auth/api_token.d.ts.map +1 -1
  25. package/dist/auth/api_token.js +28 -9
  26. package/dist/auth/api_token_queries.d.ts +2 -2
  27. package/dist/auth/api_token_queries.js +2 -2
  28. package/dist/auth/audit_log_routes.d.ts +1 -1
  29. package/dist/auth/audit_log_routes.d.ts.map +1 -1
  30. package/dist/auth/audit_log_routes.js +3 -2
  31. package/dist/auth/audit_log_schema.d.ts +15 -9
  32. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  33. package/dist/auth/audit_log_schema.js +1 -2
  34. package/dist/auth/auth_guard_resolver.d.ts +1 -1
  35. package/dist/auth/auth_guard_resolver.js +1 -1
  36. package/dist/auth/bearer_auth.d.ts +2 -5
  37. package/dist/auth/bearer_auth.d.ts.map +1 -1
  38. package/dist/auth/bearer_auth.js +4 -13
  39. package/dist/auth/bootstrap_account.d.ts +13 -15
  40. package/dist/auth/bootstrap_account.d.ts.map +1 -1
  41. package/dist/auth/bootstrap_account.js +9 -11
  42. package/dist/auth/bootstrap_routes.d.ts +20 -21
  43. package/dist/auth/bootstrap_routes.d.ts.map +1 -1
  44. package/dist/auth/bootstrap_routes.js +21 -19
  45. package/dist/auth/bootstrap_token_store.d.ts +3 -4
  46. package/dist/auth/bootstrap_token_store.d.ts.map +1 -1
  47. package/dist/auth/bootstrap_token_store.js +1 -1
  48. package/dist/auth/cleanup.d.ts +34 -3
  49. package/dist/auth/cleanup.d.ts.map +1 -1
  50. package/dist/auth/cleanup.js +11 -3
  51. package/dist/auth/daemon_token.d.ts +5 -1
  52. package/dist/auth/daemon_token.d.ts.map +1 -1
  53. package/dist/auth/daemon_token_middleware.d.ts +12 -8
  54. package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
  55. package/dist/auth/daemon_token_middleware.js +15 -21
  56. package/dist/auth/deps.d.ts +11 -0
  57. package/dist/auth/deps.d.ts.map +1 -1
  58. package/dist/auth/invite_queries.d.ts +51 -3
  59. package/dist/auth/invite_queries.d.ts.map +1 -1
  60. package/dist/auth/invite_queries.js +81 -6
  61. package/dist/auth/invite_schema.d.ts +2 -1
  62. package/dist/auth/invite_schema.d.ts.map +1 -1
  63. package/dist/auth/middleware.d.ts +2 -3
  64. package/dist/auth/middleware.d.ts.map +1 -1
  65. package/dist/auth/middleware.js +3 -3
  66. package/dist/auth/request_context.d.ts +3 -3
  67. package/dist/auth/request_context.js +3 -3
  68. package/dist/auth/role_grant_offer_actions.d.ts +2 -2
  69. package/dist/auth/role_grant_offer_actions.js +2 -2
  70. package/dist/auth/session_cookie.d.ts +82 -174
  71. package/dist/auth/session_cookie.d.ts.map +1 -1
  72. package/dist/auth/session_cookie.js +80 -130
  73. package/dist/auth/session_middleware.d.ts +8 -17
  74. package/dist/auth/session_middleware.d.ts.map +1 -1
  75. package/dist/auth/session_middleware.js +14 -23
  76. package/dist/auth/session_queries.d.ts +9 -14
  77. package/dist/auth/session_queries.d.ts.map +1 -1
  78. package/dist/auth/session_queries.js +8 -9
  79. package/dist/auth/signup_routes.d.ts.map +1 -1
  80. package/dist/auth/signup_routes.js +4 -6
  81. package/dist/db/CLAUDE.md +5 -3
  82. package/dist/dev/setup.d.ts +3 -1
  83. package/dist/dev/setup.d.ts.map +1 -1
  84. package/dist/dev/setup.js +3 -1
  85. package/dist/http/CLAUDE.md +315 -768
  86. package/dist/http/db_routes.d.ts +1 -1
  87. package/dist/http/db_routes.js +1 -1
  88. package/dist/http/origin.d.ts +7 -8
  89. package/dist/http/origin.d.ts.map +1 -1
  90. package/dist/http/origin.js +7 -8
  91. package/dist/http/pending_effects.d.ts +82 -4
  92. package/dist/http/pending_effects.d.ts.map +1 -1
  93. package/dist/http/pending_effects.js +82 -4
  94. package/dist/http/route_result.d.ts +1 -1
  95. package/dist/http/route_spec.d.ts +17 -14
  96. package/dist/http/route_spec.d.ts.map +1 -1
  97. package/dist/realtime/audit_log_sse.d.ts +1 -1
  98. package/dist/realtime/sse.d.ts +6 -25
  99. package/dist/realtime/sse.d.ts.map +1 -1
  100. package/dist/realtime/sse.js +4 -25
  101. package/dist/realtime/sse_constants.d.ts +1 -1
  102. package/dist/realtime/sse_constants.js +1 -1
  103. package/dist/server/app_backend.d.ts +4 -5
  104. package/dist/server/app_backend.d.ts.map +1 -1
  105. package/dist/server/app_backend.js +3 -1
  106. package/dist/server/app_server.d.ts +87 -76
  107. package/dist/server/app_server.d.ts.map +1 -1
  108. package/dist/server/app_server.js +111 -91
  109. package/dist/server/app_server_context.d.ts +1 -2
  110. package/dist/server/app_server_context.d.ts.map +1 -1
  111. package/dist/server/env.js +2 -2
  112. package/dist/server/shutdown_drain.d.ts +69 -0
  113. package/dist/server/shutdown_drain.d.ts.map +1 -0
  114. package/dist/server/shutdown_drain.js +77 -0
  115. package/dist/testing/CLAUDE.md +89 -57
  116. package/dist/testing/admin_integration.d.ts +4 -5
  117. package/dist/testing/admin_integration.d.ts.map +1 -1
  118. package/dist/testing/admin_integration.js +39 -23
  119. package/dist/testing/app_server.d.ts +3 -8
  120. package/dist/testing/app_server.d.ts.map +1 -1
  121. package/dist/testing/app_server.js +10 -9
  122. package/dist/testing/attack_surface.d.ts +1 -1
  123. package/dist/testing/attack_surface.d.ts.map +1 -1
  124. package/dist/testing/audit_completeness.d.ts +2 -3
  125. package/dist/testing/audit_completeness.d.ts.map +1 -1
  126. package/dist/testing/audit_completeness.js +1 -1
  127. package/dist/testing/cross_backend/bootstrap_backend.d.ts +3 -1
  128. package/dist/testing/cross_backend/bootstrap_backend.d.ts.map +1 -1
  129. package/dist/testing/cross_backend/bootstrap_backend.js +5 -1
  130. package/dist/testing/cross_backend/capability_mounts.d.ts.map +1 -1
  131. package/dist/testing/cross_backend/capability_mounts.js +16 -11
  132. package/dist/testing/cross_backend/conformance_table.d.ts +5 -6
  133. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  134. package/dist/testing/cross_backend/conformance_table.js +4 -4
  135. package/dist/testing/cross_backend/cookie_attributes.js +1 -1
  136. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts +10 -1
  137. package/dist/testing/cross_backend/create_dual_spawn_global_setup.d.ts.map +1 -1
  138. package/dist/testing/cross_backend/create_dual_spawn_global_setup.js +33 -7
  139. package/dist/testing/cross_backend/default_backend_configs.d.ts +3 -3
  140. package/dist/testing/cross_backend/default_spine_surface.d.ts +0 -6
  141. package/dist/testing/cross_backend/default_spine_surface.d.ts.map +1 -1
  142. package/dist/testing/cross_backend/default_spine_surface.js +4 -9
  143. package/dist/testing/cross_backend/differential.d.ts +2 -3
  144. package/dist/testing/cross_backend/differential.d.ts.map +1 -1
  145. package/dist/testing/cross_backend/differential.js +1 -1
  146. package/dist/testing/cross_backend/full_spine_mount.d.ts +1 -42
  147. package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
  148. package/dist/testing/cross_backend/full_spine_mount.js +45 -4
  149. package/dist/testing/cross_backend/in_process_setup.d.ts +7 -8
  150. package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
  151. package/dist/testing/cross_backend/in_process_setup.js +10 -13
  152. package/dist/testing/cross_backend/rpc_success_fixtures.d.ts.map +1 -1
  153. package/dist/testing/cross_backend/rpc_success_fixtures.js +2 -1
  154. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts +3 -4
  155. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
  156. package/dist/testing/cross_backend/rust_spine_consumer_surface.js +2 -2
  157. package/dist/testing/cross_backend/setup.d.ts +1 -1
  158. package/dist/testing/cross_backend/spawn_backend.d.ts +14 -0
  159. package/dist/testing/cross_backend/spawn_backend.d.ts.map +1 -1
  160. package/dist/testing/cross_backend/spawn_backend.js +56 -8
  161. package/dist/testing/cross_backend/spine_suites.d.ts +18 -16
  162. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  163. package/dist/testing/cross_backend/spine_suites.js +38 -18
  164. package/dist/testing/cross_backend/standard.d.ts +19 -84
  165. package/dist/testing/cross_backend/standard.d.ts.map +1 -1
  166. package/dist/testing/cross_backend/standard.js +8 -23
  167. package/dist/testing/cross_backend/standard_auth.d.ts +74 -0
  168. package/dist/testing/cross_backend/standard_auth.d.ts.map +1 -0
  169. package/dist/testing/cross_backend/standard_auth.js +28 -0
  170. package/dist/testing/cross_backend/standard_bundle.d.ts +48 -0
  171. package/dist/testing/cross_backend/standard_bundle.d.ts.map +1 -0
  172. package/dist/testing/cross_backend/standard_bundle.js +43 -0
  173. package/dist/testing/cross_backend/testing_credential_read.d.ts +10 -11
  174. package/dist/testing/cross_backend/testing_credential_read.d.ts.map +1 -1
  175. package/dist/testing/cross_backend/testing_credential_read.js +12 -12
  176. package/dist/testing/cross_backend/testing_reset_actions.d.ts +46 -30
  177. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  178. package/dist/testing/cross_backend/testing_reset_actions.js +52 -31
  179. package/dist/testing/cross_backend/testing_server_bun.d.ts.map +1 -1
  180. package/dist/testing/cross_backend/testing_server_bun.js +5 -4
  181. package/dist/testing/cross_backend/testing_server_core.d.ts +16 -3
  182. package/dist/testing/cross_backend/testing_server_core.d.ts.map +1 -1
  183. package/dist/testing/cross_backend/testing_server_core.js +22 -7
  184. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts +6 -2
  185. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts.map +1 -1
  186. package/dist/testing/cross_backend/ts_spine_backend_config.js +7 -3
  187. package/dist/testing/daemon_token_rotation.d.ts.map +1 -1
  188. package/dist/testing/daemon_token_rotation.js +2 -3
  189. package/dist/testing/error_coverage.d.ts +5 -0
  190. package/dist/testing/error_coverage.d.ts.map +1 -1
  191. package/dist/testing/error_coverage.js +2 -1
  192. package/dist/testing/integration.d.ts +6 -23
  193. package/dist/testing/integration.d.ts.map +1 -1
  194. package/dist/testing/integration.js +53 -83
  195. package/dist/testing/integration_helpers.d.ts +16 -0
  196. package/dist/testing/integration_helpers.d.ts.map +1 -1
  197. package/dist/testing/integration_helpers.js +29 -1
  198. package/dist/testing/middleware_gate_probes.d.ts +55 -1
  199. package/dist/testing/middleware_gate_probes.d.ts.map +1 -1
  200. package/dist/testing/middleware_gate_probes.js +69 -3
  201. package/dist/testing/rate_limiting.d.ts +2 -3
  202. package/dist/testing/rate_limiting.d.ts.map +1 -1
  203. package/dist/testing/rate_limiting.js +3 -3
  204. package/dist/testing/rpc_helpers.d.ts +1 -2
  205. package/dist/testing/rpc_helpers.d.ts.map +1 -1
  206. package/dist/testing/rpc_helpers.js +3 -3
  207. package/dist/testing/rpc_round_trip.d.ts +2 -3
  208. package/dist/testing/rpc_round_trip.d.ts.map +1 -1
  209. package/dist/testing/rpc_round_trip.js +1 -1
  210. package/dist/testing/sse_round_trip.d.ts +2 -3
  211. package/dist/testing/sse_round_trip.d.ts.map +1 -1
  212. package/dist/testing/sse_round_trip.js +2 -2
  213. package/dist/testing/stubs.d.ts +5 -6
  214. package/dist/testing/stubs.d.ts.map +1 -1
  215. package/dist/testing/stubs.js +10 -8
  216. package/dist/testing/test_app.d.ts +8 -5
  217. package/dist/testing/test_app.d.ts.map +1 -1
  218. package/dist/testing/test_app.js +7 -7
  219. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  220. package/dist/testing/ws_round_trip.js +3 -0
  221. package/dist/ui/ui_format.d.ts.map +1 -1
  222. package/dist/ui/ui_format.js +1 -2
  223. package/package.json +1 -1
@@ -9,12 +9,12 @@
9
9
  */
10
10
  import { Hono } from 'hono';
11
11
  import { logger } from 'hono/logger';
12
- import { SESSION_AGE_MAX, create_session_cookie_value, format_session_set_cookie, is_cookie_name } from '../auth/session_cookie.js';
13
- import { generate_session_token } from '../auth/session_queries.js';
12
+ import { is_cookie_name } from '../auth/session_cookie.js';
14
13
  import { create_sse_stream } from '../realtime/sse.js';
15
14
  import { create_audit_log_sse, create_sse_connection_closer, audit_log_event_specs } from '../realtime/audit_log_sse.js';
16
15
  import { BaseServerEnv } from './env.js';
17
16
  import { RateLimiter, announce_rate_limiters_disabled, default_login_ip_rate_limit, default_login_account_rate_limit, default_action_account_rate_limit, default_action_ip_rate_limit } from '../rate_limiter.js';
17
+ import { resolve_keeper_account_id } from '../auth/daemon_token_middleware.js';
18
18
  // Side-effect import: augments Hono's ContextVariableMap so consumers
19
19
  // that import app_server get type-safe c.get('auth_session_id') etc.
20
20
  import '../hono_context.js';
@@ -28,9 +28,10 @@ import { create_app_surface_spec } from '../http/surface.js';
28
28
  import { create_dev_route_error_check } from '../http/dev_route_error_check.js';
29
29
  import { create_dev_set_cookie_check } from '../http/dev_set_cookie_check.js';
30
30
  import { apply_middleware_specs, apply_route_specs, prefix_route_specs } from '../http/route_spec.js';
31
- import { check_bootstrap_status, create_bootstrap_route_specs } from '../auth/bootstrap_routes.js';
31
+ import { is_bootstrap_available, create_bootstrap_route_specs } from '../auth/bootstrap_routes.js';
32
32
  import { create_surface_route_spec } from './surface_route.js';
33
- import { flush_request_effects } from '../http/pending_effects.js';
33
+ import { ERROR_SERVICE_UNAVAILABLE } from '../http/error_schemas.js';
34
+ import { create_request_tracker_view, flush_request_effects } from '../http/pending_effects.js';
34
35
  import { assert_credential_routes_in_auth_scope, assert_endpoint_in_auth_scope, assert_middleware_stack_mounted, create_auth_middleware_specs } from '../auth/middleware.js';
35
36
  import { fuz_auth_guard_resolver } from '../auth/auth_guard_resolver.js';
36
37
  import { create_fuz_authorization_handler } from '../auth/request_context.js';
@@ -42,6 +43,8 @@ import { register_action_ws } from '../actions/register_action_ws.js';
42
43
  import { resolve_ws_endpoints } from '../actions/ws_endpoint_spec.js';
43
44
  import { create_revocation_guard } from '../actions/connection_closer.js';
44
45
  import { start_auth_cleanup } from '../auth/cleanup.js';
46
+ import { PERIODIC_INTERVAL_MS_MAX } from '../periodic.js';
47
+ import { DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS, drain_effects_on_shutdown } from './shutdown_drain.js';
45
48
  /**
46
49
  * Assert that `audit_sse` was wired by `create_app_server` and return it
47
50
  * as a non-null `AuditLogSse`. Throws a labelled error when the
@@ -70,12 +73,6 @@ export const require_audit_sse = (source) => {
70
73
  * `fuz_http` `DEFAULT_BODY_LIMIT_BYTES`.
71
74
  */
72
75
  export const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024;
73
- /**
74
- * Default bound on `AppServer.close`'s wait for the effects still in flight
75
- * (`AppServerOptions.shutdown_drain_timeout_ms`). Twin of the Rust spine's
76
- * `DEFAULT_DRAIN_TIMEOUT`.
77
- */
78
- export const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS = 10_000;
79
76
  /**
80
77
  * Each `AppServerOptions` rate-limiter field, with the defaults an omitted one
81
78
  * is built from under `rate_limiters: 'enforced'` and the name its
@@ -219,13 +216,14 @@ export const collect_config_diagnostics = (input) => {
219
216
  * so far runs, last acquired first (one that throws is logged and the rest
220
217
  * still run), and the original error is rethrown: a failed assembly leaves
221
218
  * the backend's emitter, closer and notification sender as it found them and
222
- * no limiter timer running. When `auth_cleanup` is set, the
219
+ * no limiter timer running. When `auth_cleanup` is `{every_ms}`, the
223
220
  * auth cleanup schedule starts as the last step of assembly — nothing after
224
221
  * it can throw, so an assembly that throws leaves no schedule running.
225
222
  *
226
223
  * The returned `close` owns shutdown: it stops that schedule, closes every
227
- * live connection on the backend's closer, runs the same releases, and
228
- * closes the database (`AppServer.close`).
224
+ * live connection on the backend's closer, waits for the work in flight
225
+ * within its bound, runs the same releases, closes the database, and
226
+ * resolves what the wait gave up on (`AppServer.close`).
229
227
  *
230
228
  * @returns the assembled Hono app with its surface, bootstrap status, migration results,
231
229
  * audit SSE, mounted WS registries, and `close`
@@ -242,37 +240,28 @@ export const create_app_server = async (options) => {
242
240
  }
243
241
  };
244
242
  /**
245
- * Wait for the request flushes in flight and then the audit emitter's pool
246
- * writes, until none is left or `timeout_ms` passes — then log an error naming
247
- * what was given up on. Never rejects.
243
+ * Read `auth_cleanup`: `null` for `'off'`, else its `every_ms`.
248
244
  *
249
- * @returns what was given up on, both counts `0` when everything settled
245
+ * @throws Error unless it is `'off'` or `{every_ms}` with a positive finite
246
+ * number no greater than `PERIODIC_INTERVAL_MS_MAX`
250
247
  */
251
- export const drain_effects_on_shutdown = async (inflight_flushes, audit, timeout_ms, log) => {
252
- const drain = async () => {
253
- // wait for zero: a flush's post-commit thunk can start another write
254
- while (inflight_flushes.size > 0)
255
- await Promise.allSettled(inflight_flushes);
256
- await audit.drain_inflight();
257
- };
258
- let timer;
259
- const timed_out = new Promise((resolve) => {
260
- timer = setTimeout(resolve, timeout_ms);
261
- });
262
- try {
263
- await Promise.race([drain(), timed_out]);
264
- }
265
- finally {
266
- clearTimeout(timer);
267
- }
268
- const given_up = {
269
- request_flushes: inflight_flushes.size,
270
- audit_writes: audit.inflight_count()
271
- };
272
- if (given_up.request_flushes === 0 && given_up.audit_writes === 0)
273
- return given_up;
274
- log.error(`create_app_server: shutdown gave up after ${timeout_ms}ms on effects still running — ${given_up.request_flushes} request flush(es), ${given_up.audit_writes} audit row write(s)`);
275
- return given_up;
248
+ const parse_auth_cleanup = (auth_cleanup) => {
249
+ if (auth_cleanup === 'off')
250
+ return null;
251
+ const every_ms = typeof auth_cleanup === 'object' &&
252
+ auth_cleanup !== null &&
253
+ Object.hasOwn(auth_cleanup, 'every_ms')
254
+ ? auth_cleanup.every_ms
255
+ : undefined;
256
+ if (typeof every_ms === 'number' &&
257
+ Number.isFinite(every_ms) &&
258
+ every_ms > 0 &&
259
+ every_ms <= PERIODIC_INTERVAL_MS_MAX) {
260
+ return every_ms;
261
+ }
262
+ throw new Error(`create_app_server: auth_cleanup must be 'off' or {every_ms} with a positive finite number of ms no greater than ${PERIODIC_INTERVAL_MS_MAX}, got ${typeof auth_cleanup === 'object' && auth_cleanup !== null
263
+ ? JSON.stringify(auth_cleanup, (_key, value) => typeof value === 'number' && !Number.isFinite(value) ? String(value) : value)
264
+ : String(auth_cleanup)}`);
276
265
  };
277
266
  /**
278
267
  * Run `releases` last-first and empty it. Each runs in its own `try`, so one
@@ -298,22 +287,11 @@ const assemble_app_server = async (options, releases) => {
298
287
  const { deps } = backend;
299
288
  const { log } = deps;
300
289
  // option checks first, before anything is acquired
301
- if (!is_cookie_name(options.session_options.cookie_name)) {
290
+ if (!is_cookie_name(options.session_cookie_name)) {
302
291
  // a name the `Cookie` grammar cannot carry would be written as a header
303
- // that reads back differently — refused here rather than at the first login
304
- throw new Error(`create_app_server: session cookie name ${JSON.stringify(options.session_options.cookie_name)} is not an RFC 6265 cookie-name`);
305
- }
306
- // Mint a sample cookie the way a login does. Options that cannot write one
307
- // — an `encode_identity` emitting a character outside the cookie grammar, a
308
- // `max_age` that is no whole number of seconds — would otherwise throw at
309
- // the first mint, which for bootstrap comes after its one-shot token is
310
- // spent.
311
- try {
312
- format_session_set_cookie(options.session_options.cookie_name, await create_session_cookie_value(deps.keyring, generate_session_token(), options.session_options), options.session_options.max_age ?? SESSION_AGE_MAX);
313
- }
314
- catch (error) {
315
- throw new Error('create_app_server: session_options cannot mint a session cookie — ' +
316
- (error instanceof Error ? error.message : String(error)), { cause: error });
292
+ // that reads back differently — refused here rather than at the first
293
+ // mint, which for bootstrap comes after its one-shot token is spent
294
+ throw new Error(`create_app_server: session cookie name ${JSON.stringify(options.session_cookie_name)} is not an RFC 6265 cookie-name`);
317
295
  }
318
296
  if (options.allowed_origins.length === 0) {
319
297
  throw new Error('create_app_server: allowed_origins is empty — list at least one origin pattern ' +
@@ -336,6 +314,11 @@ const assemble_app_server = async (options, releases) => {
336
314
  if (!(shutdown_drain_timeout_ms > 0 && Number.isFinite(shutdown_drain_timeout_ms))) {
337
315
  throw new Error(`create_app_server: shutdown_drain_timeout_ms must be a positive number of ms, got ${shutdown_drain_timeout_ms}`);
338
316
  }
317
+ // the schedule starts last, so its interval is refused here, before
318
+ // anything is acquired — as the Rust backend build refuses a zero `Every`
319
+ // first. A caller of the old option shape (`true`, `{interval_ms}`) lands
320
+ // here too, rather than on a schedule it didn't name.
321
+ const auth_cleanup_every_ms = parse_auth_cleanup(options.auth_cleanup);
339
322
  // Rate limiters — the ones built here are the server's to dispose, on
340
323
  // close or when assembly fails.
341
324
  const { mode: rate_limiter_mode, limiters: rate_limiters, built: built_rate_limiters } = resolve_rate_limiters(options);
@@ -371,7 +354,7 @@ const assemble_app_server = async (options, releases) => {
371
354
  // Auth middleware
372
355
  const auth_middleware = await create_auth_middleware_specs(deps, {
373
356
  allowed_origins: options.allowed_origins,
374
- session_options: options.session_options,
357
+ session_cookie_name: options.session_cookie_name,
375
358
  daemon_token_state: options.daemon_token_state,
376
359
  origin_carve_outs: options.origin_carve_outs
377
360
  });
@@ -387,12 +370,35 @@ const assemble_app_server = async (options, releases) => {
387
370
  middleware_specs = options.transform_middleware(stack_specs.map((spec) => ({ ...spec })));
388
371
  assert_middleware_stack_mounted(stack_specs, middleware_specs);
389
372
  }
373
+ // The daemon-token keeper, after the migrations and before the bootstrap
374
+ // check, as the Rust spine's boot runs `resolve_keeper_into`: a live
375
+ // bootstrap sets it on a fresh database once it commits, and this covers
376
+ // one already bootstrapped. Best-effort, as there: a failed read warns
377
+ // (the same message as the Rust twin's) and leaves it unset, and a
378
+ // keeper-less state authenticates no daemon token.
379
+ const daemon_token_state = options.daemon_token_state;
380
+ if (daemon_token_state && daemon_token_state.keeper_account_id === null) {
381
+ try {
382
+ const keeper_account_id = await resolve_keeper_account_id(deps);
383
+ if (keeper_account_id !== null) {
384
+ daemon_token_state.keeper_account_id = keeper_account_id;
385
+ log.info('daemon token: keeper account resolved', { account_id: keeper_account_id });
386
+ }
387
+ }
388
+ catch (error) {
389
+ log.warn('daemon token: resolving the keeper account failed', error);
390
+ }
391
+ }
390
392
  // Bootstrap status
391
393
  // - undefined / 'disabled': no route mounted; placeholder status.
392
394
  // - 'surface_only': route mounted but permanently unavailable; status placeholder.
393
- // - 'live': real disk + lock check via `check_bootstrap_status`.
395
+ // - 'live': real disk + lock check via `is_bootstrap_available`.
394
396
  const bootstrap_status = options.bootstrap?.mode === 'live'
395
- ? await check_bootstrap_status(deps, { token_store: options.bootstrap.token_store })
397
+ ? {
398
+ available: await is_bootstrap_available(deps, {
399
+ token_store: options.bootstrap.token_store
400
+ })
401
+ }
396
402
  : { available: false };
397
403
  // Surface route ref — factory manages the circular ref
398
404
  const surface_ref = {
@@ -411,7 +417,7 @@ const assemble_app_server = async (options, releases) => {
411
417
  deps,
412
418
  backend,
413
419
  bootstrap_status,
414
- session_options: options.session_options,
420
+ session_cookie_name: options.session_cookie_name,
415
421
  ...rate_limiters,
416
422
  audit_sse
417
423
  };
@@ -424,10 +430,11 @@ const assemble_app_server = async (options, releases) => {
424
430
  // 'surface_only' and the post-bootstrap state for 'live'.
425
431
  if (options.bootstrap && options.bootstrap.mode !== 'disabled') {
426
432
  const bootstrap_routes = create_bootstrap_route_specs(deps, {
427
- session_options: options.session_options,
433
+ session_cookie_name: options.session_cookie_name,
428
434
  bootstrap_status,
429
435
  token_store: options.bootstrap.mode === 'live' ? options.bootstrap.token_store : null,
430
- on_bootstrap: options.bootstrap.mode === 'live' ? options.bootstrap.on_bootstrap : undefined,
436
+ // a successful bootstrap sets its keeper here, after its commit
437
+ daemon_token_state: options.daemon_token_state ?? null,
431
438
  bootstrap_ip_rate_limiter
432
439
  });
433
440
  const prefix = options.bootstrap.route_prefix ?? '/api/account';
@@ -602,13 +609,22 @@ const assemble_app_server = async (options, releases) => {
602
609
  // writes to settle — a revocation's connection close must not sit behind
603
610
  // a slow audit INSERT.
604
611
  const on_effect_error = options.on_effect_error;
605
- // The flushes production leaves running past the response — what
606
- // shutdown waits on before the database closes. Each removes itself as it
607
- // settles; none rejects.
608
- const inflight_flushes = new Set();
612
+ // Every request, HTTP and WS, is held on the backend's tracker from
613
+ // acceptance until its handler has returned and its flush settled — what
614
+ // shutdown waits on before the database closes. The WS endpoints mounted
615
+ // below hold their messages there too. Through this server's own view, so
616
+ // its shutdown refuses what arrives after it starts draining and leaves
617
+ // the backend's tracker open for a later server.
618
+ const request_tracker = create_request_tracker_view(deps.request_tracker);
609
619
  app.use('*', async (c, next) => {
620
+ const accepted = request_tracker.accept();
621
+ // the server is shutting down: refused, never run against a closing
622
+ // database — the shape of a failed pool checkout (`app_error_handler.ts`)
623
+ if (!accepted)
624
+ return c.json({ error: ERROR_SERVICE_UNAVAILABLE }, 503);
610
625
  c.set('pending_effects', []);
611
626
  c.set('post_commit_effects', []);
627
+ let flushed = null;
612
628
  try {
613
629
  await next();
614
630
  }
@@ -621,16 +637,13 @@ const assemble_app_server = async (options, releases) => {
621
637
  method: c.req.method,
622
638
  path: c.req.path
623
639
  };
624
- const flushed = flush_request_effects(eager, deferred, log, on_effect_error ? (reason) => on_effect_error(reason, error_ctx) : undefined);
625
- if (options.await_pending_effects) {
626
- await flushed;
627
- }
628
- else {
629
- inflight_flushes.add(flushed);
630
- void flushed.then(() => inflight_flushes.delete(flushed));
631
- }
640
+ flushed = flush_request_effects(eager, deferred, log, on_effect_error ? (reason) => on_effect_error(reason, error_ctx) : undefined);
632
641
  }
642
+ accepted.finish(flushed);
643
+ if (flushed && options.await_pending_effects)
644
+ await flushed;
633
645
  }
646
+ return;
634
647
  });
635
648
  if (log.level !== 'off') {
636
649
  app.use(logger((msg) => log.info(msg)));
@@ -676,7 +689,8 @@ const assemble_app_server = async (options, releases) => {
676
689
  action_ip_rate_limiter,
677
690
  action_account_rate_limiter,
678
691
  notification_sender: deps.notification_sender,
679
- on_effect_error
692
+ on_effect_error,
693
+ request_tracker
680
694
  });
681
695
  mounted_ws_endpoints[endpoint.path] = endpoint_registry;
682
696
  // every revocation's close — the handlers' and the guard's — reaches
@@ -703,20 +717,19 @@ const assemble_app_server = async (options, releases) => {
703
717
  // the 404 — read from the app's own router, so every route registered on
704
718
  // it counts, one added after assembly included
705
719
  app.notFound(create_unmatched_route_handler(app.router));
706
- // Auth cleanup — opt-in, and last: nothing after it can throw, so a failed
707
- // assembly never leaves a schedule running. Its own throw (an invalid
708
- // `interval_ms`) comes before any pass starts, and unwinds `releases` like
709
- // any other. Its closes go through `deps.connection_closer`, which the
710
- // mounts above have filled.
711
- const auth_cleanup = options.auth_cleanup
712
- ? start_auth_cleanup(deps, options.auth_cleanup === true ? undefined : options.auth_cleanup)
713
- : null;
720
+ // Auth cleanup — last: nothing after it can throw, so a failed assembly
721
+ // never leaves a schedule running, and its interval was checked with the
722
+ // other options, so it cannot throw either. Its closes go through
723
+ // `deps.connection_closer`, which the mounts above have filled.
724
+ const auth_cleanup = auth_cleanup_every_ms === null
725
+ ? null
726
+ : start_auth_cleanup(deps, { interval_ms: auth_cleanup_every_ms });
714
727
  // One shutdown, shared by every call — see `AppServer.close` for the order.
715
728
  let closing = null;
716
729
  const shutdown = async () => {
717
- // the schedule first, so a pass in progress finishes on a live pool
718
- if (auth_cleanup)
719
- await auth_cleanup.stop();
730
+ // the schedule first: no pass starts from here, and the one in progress
731
+ // is waited for in the drain below, under its bound
732
+ const upkeep = auth_cleanup ? [auth_cleanup.stop()] : [];
720
733
  // then the connections, so none outlives the server — a failure here
721
734
  // must not keep the database open
722
735
  try {
@@ -725,14 +738,21 @@ const assemble_app_server = async (options, releases) => {
725
738
  catch (error) {
726
739
  log.error('create_app_server: closing live connections on shutdown failed:', error);
727
740
  }
728
- // then the effects still in flight, so a failure row or a session touch
729
- // a request already answered started is not lost to the closing pool —
730
- // bounded, as the Rust spine's shutdown drain is
731
- await drain_effects_on_shutdown(inflight_flushes, deps.audit, shutdown_drain_timeout_ms, log);
741
+ // then the work still in flight, refusing any request that arrives from
742
+ // here, so the cleanup pass, a handler still running, a WS upgrade's
743
+ // admission re-read,
744
+ // and the failure row, token-usage touch or post-commit thunk a request
745
+ // or WS message started, is not cut off by the closing pool — bounded.
746
+ // The Rust spine's drain waits for an HTTP request already dispatched
747
+ // too, but drops a WS message's dispatch still in its handler
748
+ // (`http/CLAUDE.md` §Pending Effects)
749
+ request_tracker.close();
750
+ const given_up = await drain_effects_on_shutdown(request_tracker, deps.audit, upkeep, shutdown_drain_timeout_ms, log);
732
751
  // then what assembly acquired — the audit listeners and closer members
733
752
  // this server added, and the limiters it built
734
753
  run_releases(releases, log, 'shutdown');
735
754
  await backend.close();
755
+ return given_up;
736
756
  };
737
757
  return {
738
758
  app,
@@ -16,7 +16,6 @@
16
16
  import type { AppDeps } from '../auth/deps.js';
17
17
  import type { AppBackend } from './app_backend.js';
18
18
  import type { BootstrapStatus } from '../auth/bootstrap_routes.js';
19
- import type { SessionOptions } from '../auth/session_cookie.js';
20
19
  import type { RateLimiter } from '../rate_limiter.js';
21
20
  import type { AuditLogSse } from '../realtime/audit_log_sse.js';
22
21
  /** Context passed to `create_route_specs`. */
@@ -24,7 +23,7 @@ export interface AppServerContext {
24
23
  deps: AppDeps;
25
24
  backend: AppBackend;
26
25
  bootstrap_status: BootstrapStatus;
27
- session_options: SessionOptions<string>;
26
+ session_cookie_name: string;
28
27
  /**
29
28
  * Per-IP login + password-change rate limiter. One instance per auth
30
29
  * surface — see `AppServerOptions.login_ip_rate_limiter` for why these
@@ -1 +1 @@
1
- {"version":3,"file":"app_server_context.d.ts","sourceRoot":"","sources":["../../src/lib/server/app_server_context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEhE,8CAA8C;AAC9C,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,UAAU,CAAC;IACpB,gBAAgB,EAAE,eAAe,CAAC;IAClC,eAAe,EAAE,cAAc,CAAC,MAAM,CAAC,CAAC;IACxC;;;;;;;;;OASG;IACH,qBAAqB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC1C,wDAAwD;IACxD,sBAAsB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3C,2DAA2D;IAC3D,yBAAyB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC9C,4DAA4D;IAC5D,0BAA0B,EAAE,WAAW,GAAG,IAAI,CAAC;IAC/C,6DAA6D;IAC7D,2BAA2B,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD,iGAAiG;IACjG,sBAAsB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3C;;;OAGG;IACH,2BAA2B,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD;;;;OAIG;IACH,SAAS,EAAE,WAAW,GAAG,IAAI,CAAC;CAC9B"}
1
+ {"version":3,"file":"app_server_context.d.ts","sourceRoot":"","sources":["../../src/lib/server/app_server_context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEhE,8CAA8C;AAC9C,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,UAAU,CAAC;IACpB,gBAAgB,EAAE,eAAe,CAAC;IAClC,mBAAmB,EAAE,MAAM,CAAC;IAC5B;;;;;;;;;OASG;IACH,qBAAqB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC1C,wDAAwD;IACxD,sBAAsB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3C,2DAA2D;IAC3D,yBAAyB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC9C,4DAA4D;IAC5D,0BAA0B,EAAE,WAAW,GAAG,IAAI,CAAC;IAC/C,6DAA6D;IAC7D,2BAA2B,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD,iGAAiG;IACjG,sBAAsB,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3C;;;OAGG;IACH,2BAA2B,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD;;;;OAIG;IACH,SAAS,EAAE,WAAW,GAAG,IAAI,CAAC;CAC9B"}
@@ -61,10 +61,10 @@ export const BaseServerEnv = object({
61
61
  sensitivity: 'secret'
62
62
  }),
63
63
  FUZ_DB_CHECKOUT_TIMEOUT_MS: meta(optional(env_integer({ min: 1, max: DB_CHECKOUT_TIMEOUT_MAX_MS })), {
64
- description: 'Bound on the pool checkouts a request makes, in ms (default 5000); a failed checkout answers 503. Audit writes use FUZ_DB_AUDIT_CHECKOUT_TIMEOUT_MS instead, including the failed-login row a request waits on. Postgres only — PGlite and pglet have no pool'
64
+ description: 'Bound on the pool checkouts a request makes, in ms (default 5000); a failed checkout answers 503. Audit pool writes (failure rows) use FUZ_DB_AUDIT_CHECKOUT_TIMEOUT_MS instead. Postgres only — PGlite and pglet have no pool'
65
65
  }),
66
66
  FUZ_DB_AUDIT_CHECKOUT_TIMEOUT_MS: meta(optional(env_integer({ min: 1, max: DB_CHECKOUT_TIMEOUT_MAX_MS })), {
67
- description: 'Bound on the checkout behind each audit pool write, in ms (default 30000); a failed login waits on its row, so up to this bound. Postgres only'
67
+ description: 'Bound on the checkout behind each audit pool write (a failure row), in ms (default 30000); no response waits on one, and shutdown drains them within its own bound. Postgres only'
68
68
  })
69
69
  });
70
70
  /**
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The bounded wait `AppServer.close` makes for the work still in flight, and
3
+ * the report of what it gave up on.
4
+ *
5
+ * Its own module, free of any server framework, so a process that serves the
6
+ * app (`testing/cross_backend/testing_server_core.ts`) reads the report
7
+ * without loading the server. Twin of the Rust spine's shutdown drain
8
+ * (`fuz_http::serve_with_shutdown` and its `ServeShutdown`).
9
+ *
10
+ * @module
11
+ */
12
+ import type { Logger } from '@fuzdev/fuz_util/log.ts';
13
+ import type { RequestTracker } from '../http/pending_effects.js';
14
+ import type { AuditEmitter } from '../auth/audit_emitter.js';
15
+ /**
16
+ * Default bound on `AppServer.close`'s wait for the effects still in flight
17
+ * (`AppServerOptions.shutdown_drain_timeout_ms`). Twin of the Rust spine's
18
+ * `DEFAULT_DRAIN_TIMEOUT`.
19
+ */
20
+ export declare const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS = 10000;
21
+ /**
22
+ * What `AppServer.close` gave up on at its drain bound
23
+ * (`drain_effects_on_shutdown`), each counted on its own: a request still
24
+ * waiting on its audit writes has those writes counted in `audit_writes` too,
25
+ * so the counts are not summed. Every count `0` is a shutdown that drained
26
+ * everything. Twin of the Rust spine's `fuz_http::ServeShutdown`.
27
+ */
28
+ export interface ShutdownDrainGivenUp {
29
+ /**
30
+ * Requests still held — HTTP requests and WS messages alike, each with its
31
+ * handler or its effect flush still running, and WS upgrades still opening.
32
+ */
33
+ requests: number;
34
+ /** Pool writes of the audit emitter still in flight. */
35
+ audit_writes: number;
36
+ /**
37
+ * Upkeep tasks still running — the auth cleanup pass in progress when
38
+ * `auth_cleanup` scheduled one. Twin of `ServeShutdown`'s
39
+ * `upkeep_given_up`; here the pass is left to finish rather than aborted.
40
+ */
41
+ upkeep: number;
42
+ }
43
+ /**
44
+ * Whether a shutdown gave up on anything — its drain bound ran out before
45
+ * every wait finished. A process reports it as a failed exit. Twin of the
46
+ * Rust `ServeShutdown::gave_up`.
47
+ *
48
+ * @param report - what `AppServer.close` resolved
49
+ */
50
+ export declare const shutdown_gave_up: (report: ShutdownDrainGivenUp) => boolean;
51
+ /**
52
+ * Wait for the upkeep stops (the auth cleanup's pass in progress), then the
53
+ * requests held (HTTP requests, WS messages and WS upgrades still opening,
54
+ * one tracker — each until its handler has returned and its flush settled)
55
+ * and then the audit emitter's pool writes, until none is left or
56
+ * `timeout_ms` passes — then log an error naming what was given up on. One
57
+ * bound for all of it. Never rejects. The Rust shutdown joins its upkeep after
58
+ * the request drain; both wait concurrently against one deadline, so only the
59
+ * wait order differs.
60
+ *
61
+ * @param requests - the request tracker
62
+ * @param audit - the audit emitter
63
+ * @param upkeep - each upkeep task's stop, already requested; one still pending at the bound is counted
64
+ * @param timeout_ms - the bound
65
+ * @param log - where a give-up is logged
66
+ * @returns what was given up on, every count `0` when everything settled
67
+ */
68
+ export declare const drain_effects_on_shutdown: (requests: Pick<RequestTracker, "drain_inflight" | "inflight_count">, audit: Pick<AuditEmitter, "drain_inflight" | "inflight_count">, upkeep: ReadonlyArray<Promise<void>>, timeout_ms: number, log: Logger) => Promise<ShutdownDrainGivenUp>;
69
+ //# sourceMappingURL=shutdown_drain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shutdown_drain.d.ts","sourceRoot":"","sources":["../../src/lib/server/shutdown_drain.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAEtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAE7D;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,QAAS,CAAC;AAExD;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACpC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,wDAAwD;IACxD,YAAY,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;CACf;AAED;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,GAAI,QAAQ,oBAAoB,KAAG,OACI,CAAC;AAErE;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,yBAAyB,GACrC,UAAU,IAAI,CAAC,cAAc,EAAE,gBAAgB,GAAG,gBAAgB,CAAC,EACnE,OAAO,IAAI,CAAC,YAAY,EAAE,gBAAgB,GAAG,gBAAgB,CAAC,EAC9D,QAAQ,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,EACpC,YAAY,MAAM,EAClB,KAAK,MAAM,KACT,OAAO,CAAC,oBAAoB,CAoC9B,CAAC"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The bounded wait `AppServer.close` makes for the work still in flight, and
3
+ * the report of what it gave up on.
4
+ *
5
+ * Its own module, free of any server framework, so a process that serves the
6
+ * app (`testing/cross_backend/testing_server_core.ts`) reads the report
7
+ * without loading the server. Twin of the Rust spine's shutdown drain
8
+ * (`fuz_http::serve_with_shutdown` and its `ServeShutdown`).
9
+ *
10
+ * @module
11
+ */
12
+ /**
13
+ * Default bound on `AppServer.close`'s wait for the effects still in flight
14
+ * (`AppServerOptions.shutdown_drain_timeout_ms`). Twin of the Rust spine's
15
+ * `DEFAULT_DRAIN_TIMEOUT`.
16
+ */
17
+ export const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS = 10_000;
18
+ /**
19
+ * Whether a shutdown gave up on anything — its drain bound ran out before
20
+ * every wait finished. A process reports it as a failed exit. Twin of the
21
+ * Rust `ServeShutdown::gave_up`.
22
+ *
23
+ * @param report - what `AppServer.close` resolved
24
+ */
25
+ export const shutdown_gave_up = (report) => report.requests > 0 || report.audit_writes > 0 || report.upkeep > 0;
26
+ /**
27
+ * Wait for the upkeep stops (the auth cleanup's pass in progress), then the
28
+ * requests held (HTTP requests, WS messages and WS upgrades still opening,
29
+ * one tracker — each until its handler has returned and its flush settled)
30
+ * and then the audit emitter's pool writes, until none is left or
31
+ * `timeout_ms` passes — then log an error naming what was given up on. One
32
+ * bound for all of it. Never rejects. The Rust shutdown joins its upkeep after
33
+ * the request drain; both wait concurrently against one deadline, so only the
34
+ * wait order differs.
35
+ *
36
+ * @param requests - the request tracker
37
+ * @param audit - the audit emitter
38
+ * @param upkeep - each upkeep task's stop, already requested; one still pending at the bound is counted
39
+ * @param timeout_ms - the bound
40
+ * @param log - where a give-up is logged
41
+ * @returns what was given up on, every count `0` when everything settled
42
+ */
43
+ export const drain_effects_on_shutdown = async (requests, audit, upkeep, timeout_ms, log) => {
44
+ let upkeep_pending = upkeep.length;
45
+ const drain = async () => {
46
+ // the upkeep first, so a write a pass started is in the loop below
47
+ await Promise.all(upkeep.map(async (stopped) => {
48
+ await stopped;
49
+ upkeep_pending--;
50
+ }));
51
+ // until both are empty: a flush's post-commit thunk can start an audit
52
+ // write, and a request accepted meanwhile is held too
53
+ do {
54
+ await requests.drain_inflight();
55
+ await audit.drain_inflight();
56
+ } while (requests.inflight_count() > 0 || audit.inflight_count() > 0);
57
+ };
58
+ let timer;
59
+ const timed_out = new Promise((resolve) => {
60
+ timer = setTimeout(resolve, timeout_ms);
61
+ });
62
+ try {
63
+ await Promise.race([drain(), timed_out]);
64
+ }
65
+ finally {
66
+ clearTimeout(timer);
67
+ }
68
+ const given_up = {
69
+ requests: requests.inflight_count(),
70
+ audit_writes: audit.inflight_count(),
71
+ upkeep: upkeep_pending
72
+ };
73
+ if (!shutdown_gave_up(given_up))
74
+ return given_up;
75
+ log.error(`create_app_server: shutdown gave up after ${timeout_ms}ms on work still running — ${given_up.requests} request(s) (handler, effect flush, or WS open), ${given_up.audit_writes} audit row write(s), ${given_up.upkeep} upkeep task(s)`);
76
+ return given_up;
77
+ };