@wildo-ai/saas-workers-node-lib 1.1.3

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 (58) hide show
  1. package/LICENSE +34 -0
  2. package/dist/esm/index.d.ts +37 -0
  3. package/dist/esm/index.d.ts.map +1 -0
  4. package/dist/esm/index.js +37 -0
  5. package/dist/esm/index.js.map +1 -0
  6. package/dist/esm/inject/models/container.d.ts +7 -0
  7. package/dist/esm/inject/models/container.d.ts.map +1 -0
  8. package/dist/esm/inject/models/container.js +63 -0
  9. package/dist/esm/inject/models/container.js.map +1 -0
  10. package/dist/esm/inject/models/service-types.d.ts +6 -0
  11. package/dist/esm/inject/models/service-types.d.ts.map +1 -0
  12. package/dist/esm/inject/models/service-types.js +5 -0
  13. package/dist/esm/inject/models/service-types.js.map +1 -0
  14. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.d.ts +54 -0
  15. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.d.ts.map +1 -0
  16. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.js +61 -0
  17. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.js.map +1 -0
  18. package/dist/esm/runtime/middlewares/worker-request-context.middleware.d.ts +35 -0
  19. package/dist/esm/runtime/middlewares/worker-request-context.middleware.d.ts.map +1 -0
  20. package/dist/esm/runtime/middlewares/worker-request-context.middleware.js +30 -0
  21. package/dist/esm/runtime/middlewares/worker-request-context.middleware.js.map +1 -0
  22. package/dist/esm/runtime/services/define-worker-init.d.ts +85 -0
  23. package/dist/esm/runtime/services/define-worker-init.d.ts.map +1 -0
  24. package/dist/esm/runtime/services/define-worker-init.js +4 -0
  25. package/dist/esm/runtime/services/define-worker-init.js.map +1 -0
  26. package/dist/esm/runtime/services/read-worker-bootstrap-env.d.ts +47 -0
  27. package/dist/esm/runtime/services/read-worker-bootstrap-env.d.ts.map +1 -0
  28. package/dist/esm/runtime/services/read-worker-bootstrap-env.js +43 -0
  29. package/dist/esm/runtime/services/read-worker-bootstrap-env.js.map +1 -0
  30. package/dist/esm/runtime/services/read-worker-http-surface-env.d.ts +42 -0
  31. package/dist/esm/runtime/services/read-worker-http-surface-env.d.ts.map +1 -0
  32. package/dist/esm/runtime/services/read-worker-http-surface-env.js +49 -0
  33. package/dist/esm/runtime/services/read-worker-http-surface-env.js.map +1 -0
  34. package/dist/esm/runtime/services/start-worker-application.backend.service.d.ts +100 -0
  35. package/dist/esm/runtime/services/start-worker-application.backend.service.d.ts.map +1 -0
  36. package/dist/esm/runtime/services/start-worker-application.backend.service.js +297 -0
  37. package/dist/esm/runtime/services/start-worker-application.backend.service.js.map +1 -0
  38. package/dist/esm/runtime/services/worker-http-server.backend.service.d.ts +56 -0
  39. package/dist/esm/runtime/services/worker-http-server.backend.service.d.ts.map +1 -0
  40. package/dist/esm/runtime/services/worker-http-server.backend.service.js +128 -0
  41. package/dist/esm/runtime/services/worker-http-server.backend.service.js.map +1 -0
  42. package/dist/tsconfig.build.tsbuildinfo +1 -0
  43. package/package.json +61 -0
  44. package/src/index.ts +36 -0
  45. package/src/inject/models/container.ts +76 -0
  46. package/src/inject/models/service-types.ts +9 -0
  47. package/src/runtime/middlewares/__tests__/worker-jwt-verifier.rotation-cutoff.middleware.test.ts +62 -0
  48. package/src/runtime/middlewares/__tests__/worker-request-context.middleware.test.ts +85 -0
  49. package/src/runtime/middlewares/worker-jwt-verifier.middleware.ts +112 -0
  50. package/src/runtime/middlewares/worker-request-context.middleware.ts +47 -0
  51. package/src/runtime/services/__tests__/read-worker-http-surface-env.test.ts +66 -0
  52. package/src/runtime/services/__tests__/start-worker-application.backend.service.test.ts +315 -0
  53. package/src/runtime/services/__tests__/worker-http-server.backend.service.test.ts +69 -0
  54. package/src/runtime/services/define-worker-init.ts +92 -0
  55. package/src/runtime/services/read-worker-bootstrap-env.ts +86 -0
  56. package/src/runtime/services/read-worker-http-surface-env.ts +84 -0
  57. package/src/runtime/services/start-worker-application.backend.service.ts +346 -0
  58. package/src/runtime/services/worker-http-server.backend.service.ts +144 -0
@@ -0,0 +1,43 @@
1
+ import { ApplicationWorkerBootstrapEnvKey } from '@wildo-ai/platform-core-shared';
2
+ /**
3
+ * Read and validate the worker bootstrap-env-contract, failing closed with
4
+ * EVERY missing key named at once (not just the first) so a misconfigured
5
+ * `.env` surfaces in a single boot attempt.
6
+ *
7
+ * The worker entrypoint calls this once and threads the values into
8
+ * {@link StartWorkerApplicationBackendService.initialize}. Keeping the read
9
+ * here — rather than re-deriving `process.env['…']` literals in each worker's
10
+ * `index.ts` — is what prevents the name drift this helper exists to close.
11
+ *
12
+ * @param env Environment source; defaults to `process.env`. Overridable so
13
+ * tests can exercise the fail-closed path without mutating global state.
14
+ * @throws If any of the four contract keys is missing or empty.
15
+ */
16
+ export function readWorkerBootstrapEnv(env = process.env) {
17
+ const missingKeys = [];
18
+ const requireKey = (key) => {
19
+ const value = env[key];
20
+ if (!value) {
21
+ missingKeys.push(key);
22
+ return '';
23
+ }
24
+ return value;
25
+ };
26
+ const applicationId = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ID);
27
+ const platformApplicationPrimarySecret = requireKey(ApplicationWorkerBootstrapEnvKey.PLATFORM_APPLICATION_PRIMARY_SECRET);
28
+ const appsManagerUrl = requireKey(ApplicationWorkerBootstrapEnvKey.PLATFORM_APPS_MANAGER_URL);
29
+ const applicationEnv = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ENV);
30
+ if (missingKeys.length > 0) {
31
+ throw new Error('[saas-workers-node-lib] Worker booted without required bootstrap env '
32
+ + `var(s): ${missingKeys.join(', ')}. These are projected into the worker's `
33
+ + '`.env` by `wildo config sync` from `wildo.saas.config.ts`; re-run it (and '
34
+ + 'verify the `.env` is loaded into this process) before starting the worker.');
35
+ }
36
+ return {
37
+ applicationId,
38
+ platformApplicationPrimarySecret,
39
+ appsManagerUrl,
40
+ applicationEnv,
41
+ };
42
+ }
43
+ //# sourceMappingURL=read-worker-bootstrap-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-worker-bootstrap-env.js","sourceRoot":"","sources":["../../../../../src/runtime/services/read-worker-bootstrap-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAkClF;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAyB,OAAO,CAAC,GAAG;IAEpC,MAAM,WAAW,GAAa,EAAE,CAAC;IACjC,MAAM,UAAU,GAAG,CAAC,GAAqC,EAAU,EAAE;QACnE,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtB,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,UAAU,CAAC,gCAAgC,CAAC,cAAc,CAAC,CAAC;IAClF,MAAM,gCAAgC,GAAG,UAAU,CACjD,gCAAgC,CAAC,mCAAmC,CACrE,CAAC;IACF,MAAM,cAAc,GAAG,UAAU,CAC/B,gCAAgC,CAAC,yBAAyB,CAC3D,CAAC;IACF,MAAM,cAAc,GAAG,UAAU,CAAC,gCAAgC,CAAC,eAAe,CAAC,CAAC;IAEpF,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CACb,uEAAuE;cACrE,WAAW,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,0CAA0C;cAC3E,4EAA4E;cAC5E,4EAA4E,CAC/E,CAAC;IACJ,CAAC;IAED,OAAO;QACL,aAAa;QACb,gCAAgC;QAChC,cAAc;QACd,cAAc;KACf,CAAC;AACJ,CAAC","sourcesContent":["import { ApplicationWorkerBootstrapEnvKey } from '@wildo-ai/platform-core-shared';\n\n/**\n * The four-env bootstrap-env-contract a Node worker needs at boot, read from\n * the process environment and validated fail-closed.\n *\n * These keys are always projected into the worker's `.env` by\n * `wildo config sync` (from `wildo.saas.config.ts`), keyed off the canonical\n * {@link ApplicationWorkerBootstrapEnvKey} enum. Reading them back through the\n * SAME enum closes the loop the backend lane already has — its\n * `ApplicationEnvConfigurationSchema` is keyed off the sibling\n * `ApplicationBackendBootstrapEnvKey`, so an emit-side rename fails to compile\n * against the read side. Workers previously re-derived these names as string\n * literals in each `index.ts`, which is exactly how a worker drifted from the\n * emitter (`APPS_MANAGER_URL` vs the emitted `PLATFORM_APPS_MANAGER_URL`).\n */\nexport interface WorkerBootstrapEnv {\n /** `APPLICATION_ID` — the caller identity forwarded to apps-manager. */\n applicationId: string;\n /**\n * `PLATFORM_APPLICATION_PRIMARY_SECRET` — paired with the application id as\n * the `x-platform-secret` header so the worker-bootstrap fetch authenticates\n * as `APP_TO_PLATFORM`.\n */\n platformApplicationPrimarySecret: string;\n /**\n * `PLATFORM_APPS_MANAGER_URL` — base URL of the apps-manager the worker polls\n * for the trusted `APPLICATION_WORKER_REQUEST` public key.\n */\n appsManagerUrl: string;\n /** `APPLICATION_ENV` — the deployment environment (`development`, `staging`, …). */\n applicationEnv: string;\n}\n\n/**\n * Read and validate the worker bootstrap-env-contract, failing closed with\n * EVERY missing key named at once (not just the first) so a misconfigured\n * `.env` surfaces in a single boot attempt.\n *\n * The worker entrypoint calls this once and threads the values into\n * {@link StartWorkerApplicationBackendService.initialize}. Keeping the read\n * here — rather than re-deriving `process.env['…']` literals in each worker's\n * `index.ts` — is what prevents the name drift this helper exists to close.\n *\n * @param env Environment source; defaults to `process.env`. Overridable so\n * tests can exercise the fail-closed path without mutating global state.\n * @throws If any of the four contract keys is missing or empty.\n */\nexport function readWorkerBootstrapEnv(\n env: NodeJS.ProcessEnv = process.env,\n): WorkerBootstrapEnv {\n const missingKeys: string[] = [];\n const requireKey = (key: ApplicationWorkerBootstrapEnvKey): string => {\n const value = env[key];\n if (!value) {\n missingKeys.push(key);\n return '';\n }\n return value;\n };\n\n const applicationId = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ID);\n const platformApplicationPrimarySecret = requireKey(\n ApplicationWorkerBootstrapEnvKey.PLATFORM_APPLICATION_PRIMARY_SECRET,\n );\n const appsManagerUrl = requireKey(\n ApplicationWorkerBootstrapEnvKey.PLATFORM_APPS_MANAGER_URL,\n );\n const applicationEnv = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ENV);\n\n if (missingKeys.length > 0) {\n throw new Error(\n '[saas-workers-node-lib] Worker booted without required bootstrap env '\n + `var(s): ${missingKeys.join(', ')}. These are projected into the worker's `\n + '`.env` by `wildo config sync` from `wildo.saas.config.ts`; re-run it (and '\n + 'verify the `.env` is loaded into this process) before starting the worker.',\n );\n }\n\n return {\n applicationId,\n platformApplicationPrimarySecret,\n appsManagerUrl,\n applicationEnv,\n };\n}\n"]}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The worker's resolved inbound HTTP surface, read from the process
3
+ * environment and threaded into {@link WorkerInitializationConfig.http}.
4
+ *
5
+ * These keys are projected into the worker's `.env` by `wildo config sync`
6
+ * from the authored `wildo.worker.config.ts > http` block (`WorkerHttpSchema`
7
+ * in `@wildo-ai/platform-config-lib`), keyed off the canonical
8
+ * {@link ApplicationWorkerHttpSurfaceEnvKey} enum. Reading them back through
9
+ * the SAME enum closes the loop — an emit-side rename fails to compile against
10
+ * this read side — and stops a worker from re-deriving env-name literals
11
+ * (`process.env.PORT`) that drift from the emitter and from the sibling Rust
12
+ * worker (which reads `WORKER_HTTP_PORT` / `WORKER_HEALTH_PATH` /
13
+ * `WORKER_READY_PATH`).
14
+ */
15
+ export interface WorkerHttpSurfaceEnv {
16
+ /** `WORKER_HTTP_PORT` — the TCP port the worker's HTTP server binds. */
17
+ port: number;
18
+ /** `WORKER_HEALTH_PATH` — unauthenticated liveness route (K8s probe). */
19
+ healthPath: string;
20
+ /** `WORKER_READY_PATH` — unauthenticated readiness route (K8s probe). */
21
+ readyPath: string;
22
+ /** `WORKER_METRICS_PATH` — optional Prometheus scrape route; `undefined` when the author did not opt in. */
23
+ metricsPath?: string;
24
+ }
25
+ /**
26
+ * Read the worker HTTP-surface contract from the process environment.
27
+ *
28
+ * Unlike {@link readWorkerBootstrapEnv} — which fails closed on any missing
29
+ * REQUIRED identity key — the HTTP surface is DEFAULTED: a missing key falls
30
+ * back to the canonical default (`8080` / `/healthz` / `/readyz`), exactly as
31
+ * the Rust worker does. The one fail-closed case is a PRESENT-but-invalid
32
+ * `WORKER_HTTP_PORT` (non-numeric or non-positive): a bad port must surface at
33
+ * boot rather than silently binding a wrong/default port, mirroring the Rust
34
+ * worker's `WORKER_HTTP_PORT must parse to u16` error.
35
+ *
36
+ * @param env Environment source; defaults to `process.env`. Overridable so
37
+ * tests can exercise the default and fail-closed paths without mutating global
38
+ * state.
39
+ * @throws If `WORKER_HTTP_PORT` is set to a value that is not a positive integer.
40
+ */
41
+ export declare function readWorkerHttpSurfaceEnv(env?: NodeJS.ProcessEnv): WorkerHttpSurfaceEnv;
42
+ //# sourceMappingURL=read-worker-http-surface-env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-worker-http-surface-env.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/read-worker-http-surface-env.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,oBAAoB;IACnC,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,UAAU,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,SAAS,EAAE,MAAM,CAAC;IAClB,4GAA4G;IAC5G,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAcD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,oBAAoB,CA0BtB"}
@@ -0,0 +1,49 @@
1
+ import { ApplicationWorkerHttpSurfaceEnvKey } from '@wildo-ai/platform-core-shared';
2
+ /**
3
+ * Canonical HTTP-surface defaults. They mirror the `WorkerHttpSchema` field
4
+ * defaults in `@wildo-ai/platform-config-lib` AND the Rust reference worker's
5
+ * `std::env::var(...).unwrap_or_else(...)` fallbacks, so every worker runtime
6
+ * agrees on the same values when a key is absent. A generated `.env` always
7
+ * carries the authored values, so these only apply to a worker booted outside
8
+ * the generated env (e.g. an ad-hoc local run).
9
+ */
10
+ const DEFAULT_WORKER_HTTP_PORT = 8080;
11
+ const DEFAULT_WORKER_HEALTH_PATH = '/healthz';
12
+ const DEFAULT_WORKER_READY_PATH = '/readyz';
13
+ /**
14
+ * Read the worker HTTP-surface contract from the process environment.
15
+ *
16
+ * Unlike {@link readWorkerBootstrapEnv} — which fails closed on any missing
17
+ * REQUIRED identity key — the HTTP surface is DEFAULTED: a missing key falls
18
+ * back to the canonical default (`8080` / `/healthz` / `/readyz`), exactly as
19
+ * the Rust worker does. The one fail-closed case is a PRESENT-but-invalid
20
+ * `WORKER_HTTP_PORT` (non-numeric or non-positive): a bad port must surface at
21
+ * boot rather than silently binding a wrong/default port, mirroring the Rust
22
+ * worker's `WORKER_HTTP_PORT must parse to u16` error.
23
+ *
24
+ * @param env Environment source; defaults to `process.env`. Overridable so
25
+ * tests can exercise the default and fail-closed paths without mutating global
26
+ * state.
27
+ * @throws If `WORKER_HTTP_PORT` is set to a value that is not a positive integer.
28
+ */
29
+ export function readWorkerHttpSurfaceEnv(env = process.env) {
30
+ const rawPort = env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT];
31
+ let port = DEFAULT_WORKER_HTTP_PORT;
32
+ if (rawPort !== undefined && rawPort !== '') {
33
+ const parsedPort = Number(rawPort);
34
+ if (!Number.isInteger(parsedPort) || parsedPort <= 0) {
35
+ throw new Error(`[saas-workers-node-lib] ${ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT} must be a `
36
+ + `positive integer, received '${rawPort}'. It is projected into the worker's \`.env\` by `
37
+ + '`wildo config sync` from `wildo.worker.config.ts > http.port`; fix the authored value '
38
+ + '(or the running env) before starting the worker.');
39
+ }
40
+ port = parsedPort;
41
+ }
42
+ // A blank value falls back to the default too — an empty path is never a
43
+ // valid Express route, so treating '' as "unset" is safer than binding it.
44
+ const healthPath = env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HEALTH_PATH] || DEFAULT_WORKER_HEALTH_PATH;
45
+ const readyPath = env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_READY_PATH] || DEFAULT_WORKER_READY_PATH;
46
+ const metricsPath = env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_METRICS_PATH] || undefined;
47
+ return { port, healthPath, readyPath, metricsPath };
48
+ }
49
+ //# sourceMappingURL=read-worker-http-surface-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-worker-http-surface-env.js","sourceRoot":"","sources":["../../../../../src/runtime/services/read-worker-http-surface-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AA2BpF;;;;;;;GAOG;AACH,MAAM,wBAAwB,GAAG,IAAI,CAAC;AACtC,MAAM,0BAA0B,GAAG,UAAU,CAAC;AAC9C,MAAM,yBAAyB,GAAG,SAAS,CAAC;AAE5C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,wBAAwB,CACtC,MAAyB,OAAO,CAAC,GAAG;IAEpC,MAAM,OAAO,GAAG,GAAG,CAAC,kCAAkC,CAAC,gBAAgB,CAAC,CAAC;IACzE,IAAI,IAAI,GAAG,wBAAwB,CAAC;IACpC,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;QAC5C,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;YACrD,MAAM,IAAI,KAAK,CACb,2BAA2B,kCAAkC,CAAC,gBAAgB,aAAa;kBACzF,+BAA+B,OAAO,mDAAmD;kBACzF,wFAAwF;kBACxF,kDAAkD,CACrD,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,UAAU,CAAC;IACpB,CAAC;IAED,yEAAyE;IACzE,2EAA2E;IAC3E,MAAM,UAAU,GACd,GAAG,CAAC,kCAAkC,CAAC,kBAAkB,CAAC,IAAI,0BAA0B,CAAC;IAC3F,MAAM,SAAS,GACb,GAAG,CAAC,kCAAkC,CAAC,iBAAiB,CAAC,IAAI,yBAAyB,CAAC;IACzF,MAAM,WAAW,GACf,GAAG,CAAC,kCAAkC,CAAC,mBAAmB,CAAC,IAAI,SAAS,CAAC;IAE3E,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { ApplicationWorkerHttpSurfaceEnvKey } from '@wildo-ai/platform-core-shared';\n\n/**\n * The worker's resolved inbound HTTP surface, read from the process\n * environment and threaded into {@link WorkerInitializationConfig.http}.\n *\n * These keys are projected into the worker's `.env` by `wildo config sync`\n * from the authored `wildo.worker.config.ts > http` block (`WorkerHttpSchema`\n * in `@wildo-ai/platform-config-lib`), keyed off the canonical\n * {@link ApplicationWorkerHttpSurfaceEnvKey} enum. Reading them back through\n * the SAME enum closes the loop — an emit-side rename fails to compile against\n * this read side — and stops a worker from re-deriving env-name literals\n * (`process.env.PORT`) that drift from the emitter and from the sibling Rust\n * worker (which reads `WORKER_HTTP_PORT` / `WORKER_HEALTH_PATH` /\n * `WORKER_READY_PATH`).\n */\nexport interface WorkerHttpSurfaceEnv {\n /** `WORKER_HTTP_PORT` — the TCP port the worker's HTTP server binds. */\n port: number;\n /** `WORKER_HEALTH_PATH` — unauthenticated liveness route (K8s probe). */\n healthPath: string;\n /** `WORKER_READY_PATH` — unauthenticated readiness route (K8s probe). */\n readyPath: string;\n /** `WORKER_METRICS_PATH` — optional Prometheus scrape route; `undefined` when the author did not opt in. */\n metricsPath?: string;\n}\n\n/**\n * Canonical HTTP-surface defaults. They mirror the `WorkerHttpSchema` field\n * defaults in `@wildo-ai/platform-config-lib` AND the Rust reference worker's\n * `std::env::var(...).unwrap_or_else(...)` fallbacks, so every worker runtime\n * agrees on the same values when a key is absent. A generated `.env` always\n * carries the authored values, so these only apply to a worker booted outside\n * the generated env (e.g. an ad-hoc local run).\n */\nconst DEFAULT_WORKER_HTTP_PORT = 8080;\nconst DEFAULT_WORKER_HEALTH_PATH = '/healthz';\nconst DEFAULT_WORKER_READY_PATH = '/readyz';\n\n/**\n * Read the worker HTTP-surface contract from the process environment.\n *\n * Unlike {@link readWorkerBootstrapEnv} — which fails closed on any missing\n * REQUIRED identity key — the HTTP surface is DEFAULTED: a missing key falls\n * back to the canonical default (`8080` / `/healthz` / `/readyz`), exactly as\n * the Rust worker does. The one fail-closed case is a PRESENT-but-invalid\n * `WORKER_HTTP_PORT` (non-numeric or non-positive): a bad port must surface at\n * boot rather than silently binding a wrong/default port, mirroring the Rust\n * worker's `WORKER_HTTP_PORT must parse to u16` error.\n *\n * @param env Environment source; defaults to `process.env`. Overridable so\n * tests can exercise the default and fail-closed paths without mutating global\n * state.\n * @throws If `WORKER_HTTP_PORT` is set to a value that is not a positive integer.\n */\nexport function readWorkerHttpSurfaceEnv(\n env: NodeJS.ProcessEnv = process.env,\n): WorkerHttpSurfaceEnv {\n const rawPort = env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT];\n let port = DEFAULT_WORKER_HTTP_PORT;\n if (rawPort !== undefined && rawPort !== '') {\n const parsedPort = Number(rawPort);\n if (!Number.isInteger(parsedPort) || parsedPort <= 0) {\n throw new Error(\n `[saas-workers-node-lib] ${ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT} must be a `\n + `positive integer, received '${rawPort}'. It is projected into the worker's \\`.env\\` by `\n + '`wildo config sync` from `wildo.worker.config.ts > http.port`; fix the authored value '\n + '(or the running env) before starting the worker.',\n );\n }\n port = parsedPort;\n }\n\n // A blank value falls back to the default too — an empty path is never a\n // valid Express route, so treating '' as \"unset\" is safer than binding it.\n const healthPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HEALTH_PATH] || DEFAULT_WORKER_HEALTH_PATH;\n const readyPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_READY_PATH] || DEFAULT_WORKER_READY_PATH;\n const metricsPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_METRICS_PATH] || undefined;\n\n return { port, healthPath, readyPath, metricsPath };\n}\n"]}
@@ -0,0 +1,100 @@
1
+ import { type ProviderRuntimeArtifact, WildoWorkerBootstrapClientService } from '@wildo-ai/saas-backend-lib';
2
+ import { type AppWorkerBootstrapResponse } from '@wildo-ai/platform-config-lib';
3
+ import type { WorkerInitializationConfig } from './define-worker-init';
4
+ import { WorkerHttpServerBackendService } from './worker-http-server.backend.service';
5
+ /**
6
+ * Worker entrypoint per Q1 LOCKED of
7
+ * `.claude/plans/minions-and-workers-implementation.md`: a standalone
8
+ * runtime kernel that does NOT consume the backend-api's heavy bootstrap
9
+ * (no `AppConfigurationService`, no Mongo / Redis / RabbitMQ). Per the
10
+ * Phase 1.5 mapping doc Table A, the worker only inherits these
11
+ * `bootstrap-base` steps:
12
+ * - Env validation
13
+ * - Apps-manager handshake (limited to fetching the trusted
14
+ * `APPLICATION_WORKER_REQUEST` public key)
15
+ * - Final validation gate
16
+ * - SIGTERM handler (graceful shutdown per G-18 + KD-7)
17
+ *
18
+ * Plus the two worker-specific steps:
19
+ * - HTTP server + controllers (with JWT verifier middleware)
20
+ * - K8s liveness writer (HTTP `/healthz` per `WildoWorkerConfig.http.healthPath`)
21
+ *
22
+ * Shipped behaviour:
23
+ * 1. Initializes `WildoWorkerBootstrapClientService` and prefetches the
24
+ * trusted public key.
25
+ * 2. Schedules the JWKS-style refresh loop; the cached bootstrap response
26
+ * feeds the JWT verifier on every inbound request, so a rotation
27
+ * rolls in without restarting the server.
28
+ * 3. Installs the lightweight `WorkerHttpServerBackendService` (express +
29
+ * helmet, no CORS, no websockets), mounts liveness/readiness probes
30
+ * unauthenticated, and gates everything else behind the
31
+ * `APPLICATION_WORKER_REQUEST` JWT verifier middleware.
32
+ * 4. Marks the readiness probe ready once the bootstrap response is
33
+ * loaded.
34
+ */
35
+ export declare class StartWorkerApplicationBackendService {
36
+ private readonly workerBootstrapClient;
37
+ private readonly workerHttpServer;
38
+ private bootstrapResponse?;
39
+ private providerRuntime?;
40
+ private refreshTimer?;
41
+ private isInitialized;
42
+ private signalHandlersRegistered;
43
+ constructor(workerBootstrapClient: WildoWorkerBootstrapClientService, workerHttpServer: WorkerHttpServerBackendService);
44
+ initialize(input: {
45
+ config: WorkerInitializationConfig;
46
+ applicationId: string;
47
+ /**
48
+ * `PLATFORM_APPLICATION_PRIMARY_SECRET` from the four-env
49
+ * bootstrap-env-contract — required so the worker's
50
+ * `WildoWorkerBootstrapClientService` can authenticate against the
51
+ * apps-manager `apps-to-manager/workers/:workerName/bootstrap`
52
+ * endpoint as APP_TO_PLATFORM.
53
+ */
54
+ platformApplicationPrimarySecret: string;
55
+ }): Promise<void>;
56
+ /**
57
+ * Returns the trusted public key + rotation metadata. The HTTP server's
58
+ * verifier middleware already reads this on every request via the
59
+ * `getCurrentPublicKey` / `getRotatedPublicKeys` callbacks; this getter
60
+ * exists so test code and the worker's own route handlers can inspect
61
+ * the active rotation state.
62
+ */
63
+ getBootstrapResponse(): AppWorkerBootstrapResponse;
64
+ /**
65
+ * Returns the generated, backend-shaped provider runtime selected for the
66
+ * current worker. Undefined means the worker was started without a generated
67
+ * provider artifact (valid for provider-free workers).
68
+ */
69
+ getProviderRuntime(): ProviderRuntimeArtifact | undefined;
70
+ shutdown(gracePeriodMs?: number): Promise<void>;
71
+ /**
72
+ * Install the worker's SIGTERM/SIGINT graceful-shutdown handler — the JSDoc's "SIGTERM handler
73
+ * per G-18 + KD-7" that audit A-11 found was claimed but absent (a signal would hard-kill the
74
+ * worker, dropping any final telemetry). The worker is deliberately queue-free (KD-3), so it does
75
+ * NOT use the RabbitMQ-coupled `WorkerShutdownManager`; instead it runs its own cleanup
76
+ * (`shutdown()`) and flushes OTel telemetry before exit — the worker-local analogue of the
77
+ * platform hosts' note-6 flush. `process.once` keeps the host killable (the handler exits).
78
+ * Idempotent.
79
+ */
80
+ private registerGracefulShutdown;
81
+ private gracefulShutdown;
82
+ private requireBootstrap;
83
+ private scheduleRefresh;
84
+ /**
85
+ * Bridge the per-worker materialized provider runtime artifact into the
86
+ * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`.
87
+ *
88
+ * Three accepted input shapes — see `StartMinionApplicationBackendService`
89
+ * for the same pattern. Summary:
90
+ *
91
+ * 1. `{ artifactKind: 'backend', scope: ... }` — already projected.
92
+ * 2. `{ artifactKind: 'nodeWorkers', scope: ..., scopes: undefined }` —
93
+ * pre-scoped per-worker module emitted by `wildo config sync`.
94
+ * 3. `{ artifactKind: 'nodeWorkers', scopes: { [name]: ... } }` —
95
+ * multi-scope artifact (legacy / non-CLI hosts).
96
+ */
97
+ private normalizeProviderRuntime;
98
+ private selectWorkerProviderRuntimeScope;
99
+ }
100
+ //# sourceMappingURL=start-worker-application.backend.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-worker-application.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/start-worker-application.backend.service.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,uBAAuB,EAE5B,iCAAiC,EAClC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,KAAK,0BAA0B,EAChC,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EACV,0BAA0B,EAE3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,qBACa,oCAAoC;IAS7C,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IAEtC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAVnC,OAAO,CAAC,iBAAiB,CAAC,CAA6B;IACvD,OAAO,CAAC,eAAe,CAAC,CAA0B;IAClD,OAAO,CAAC,YAAY,CAAC,CAAiB;IACtC,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,wBAAwB,CAAS;gBAItB,qBAAqB,EAAE,iCAAiC,EAExD,gBAAgB,EAAE,8BAA8B;IAGtD,UAAU,CAAC,KAAK,EAAE;QAC7B,MAAM,EAAE,0BAA0B,CAAC;QACnC,aAAa,EAAE,MAAM,CAAC;QACtB;;;;;;WAMG;QACH,gCAAgC,EAAE,MAAM,CAAC;KAC1C,GAAG,OAAO,CAAC,IAAI,CAAC;IAiEjB;;;;;;OAMG;IACI,oBAAoB,IAAI,0BAA0B;IAIzD;;;;OAIG;IACI,kBAAkB,IAAI,uBAAuB,GAAG,SAAS;IAInD,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAY5D;;;;;;;;OAQG;IACH,OAAO,CAAC,wBAAwB;YASlB,gBAAgB;IAyB9B,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,eAAe;IAuBvB;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,wBAAwB;IAoBhC,OAAO,CAAC,gCAAgC;CAkEzC"}
@@ -0,0 +1,297 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { inject, injectable } from 'inversify';
14
+ import { getOtelSdkHandle, SAAS_SERVICE_TYPES, WildoWorkerBootstrapClientService, } from '@wildo-ai/saas-backend-lib';
15
+ import { assertProviderRuntimeEnvInSync, } from '@wildo-ai/platform-config-lib';
16
+ import { SAAS_WORKERS_NODE_SERVICE_TYPES } from '../../inject/models/service-types.js';
17
+ import { WorkerHttpServerBackendService } from './worker-http-server.backend.service.js';
18
+ /**
19
+ * Worker entrypoint per Q1 LOCKED of
20
+ * `.claude/plans/minions-and-workers-implementation.md`: a standalone
21
+ * runtime kernel that does NOT consume the backend-api's heavy bootstrap
22
+ * (no `AppConfigurationService`, no Mongo / Redis / RabbitMQ). Per the
23
+ * Phase 1.5 mapping doc Table A, the worker only inherits these
24
+ * `bootstrap-base` steps:
25
+ * - Env validation
26
+ * - Apps-manager handshake (limited to fetching the trusted
27
+ * `APPLICATION_WORKER_REQUEST` public key)
28
+ * - Final validation gate
29
+ * - SIGTERM handler (graceful shutdown per G-18 + KD-7)
30
+ *
31
+ * Plus the two worker-specific steps:
32
+ * - HTTP server + controllers (with JWT verifier middleware)
33
+ * - K8s liveness writer (HTTP `/healthz` per `WildoWorkerConfig.http.healthPath`)
34
+ *
35
+ * Shipped behaviour:
36
+ * 1. Initializes `WildoWorkerBootstrapClientService` and prefetches the
37
+ * trusted public key.
38
+ * 2. Schedules the JWKS-style refresh loop; the cached bootstrap response
39
+ * feeds the JWT verifier on every inbound request, so a rotation
40
+ * rolls in without restarting the server.
41
+ * 3. Installs the lightweight `WorkerHttpServerBackendService` (express +
42
+ * helmet, no CORS, no websockets), mounts liveness/readiness probes
43
+ * unauthenticated, and gates everything else behind the
44
+ * `APPLICATION_WORKER_REQUEST` JWT verifier middleware.
45
+ * 4. Marks the readiness probe ready once the bootstrap response is
46
+ * loaded.
47
+ */
48
+ let StartWorkerApplicationBackendService = class StartWorkerApplicationBackendService {
49
+ workerBootstrapClient;
50
+ workerHttpServer;
51
+ bootstrapResponse;
52
+ providerRuntime;
53
+ refreshTimer;
54
+ isInitialized = false;
55
+ signalHandlersRegistered = false;
56
+ constructor(workerBootstrapClient, workerHttpServer) {
57
+ this.workerBootstrapClient = workerBootstrapClient;
58
+ this.workerHttpServer = workerHttpServer;
59
+ }
60
+ async initialize(input) {
61
+ const { config, applicationId, platformApplicationPrimarySecret } = input;
62
+ this.providerRuntime = this.normalizeProviderRuntime(config.providerRuntime, config.workerName);
63
+ // Boot-time fail-closed reconciliation between the typed
64
+ // `wildo-provider-runtime.generated.ts` artifact and the
65
+ // `.wildo-providers.env` file mounted into this process. Catches
66
+ // stale-sync drift before the registry filter would silently boot
67
+ // with mismatched topology.
68
+ //
69
+ // Skipped when:
70
+ // - the artifact is absent (worker authored zero providers AND no
71
+ // scope block in `wildo.saas.config.ts`); or
72
+ // - the artifact has zero `providerRefs` (worker authored an
73
+ // explicit empty scope `providers: {}`). The CLI emitter
74
+ // deliberately does NOT write `.wildo-providers.env` in that
75
+ // case, so the env-vars are absent — running the assertion
76
+ // would raise a false-positive fail-closed.
77
+ // Defensive `?? []` — the schema marks `providerRefs` optional, so
78
+ // a hand-crafted artifact (test fixture / future format drift)
79
+ // could omit it. Without the fallback `.length` would TypeError
80
+ // before fail-closed produced its actionable message. Production
81
+ // CLI emit always defaults to `[]`, so this is hardening only.
82
+ const projectedProviderRefs = this.providerRuntime?.providerRefs ?? [];
83
+ if (this.providerRuntime && projectedProviderRefs.length > 0) {
84
+ assertProviderRuntimeEnvInSync({
85
+ artifactProviderRefs: projectedProviderRefs,
86
+ artifactSourceDigest: this.providerRuntime.sourceDigest,
87
+ hostKind: 'node-worker',
88
+ hostKey: config.workerName,
89
+ });
90
+ }
91
+ this.workerBootstrapClient.initialize({
92
+ appsManagerBaseUrl: config.appsManagerBootstrapUrl,
93
+ applicationId,
94
+ workerName: config.workerName,
95
+ platformApplicationPrimarySecret,
96
+ refreshIntervalMs: config.publicKeyRefreshIntervalMs,
97
+ });
98
+ this.bootstrapResponse = await this.workerBootstrapClient.getBootstrap();
99
+ this.scheduleRefresh(config.publicKeyRefreshIntervalMs);
100
+ await this.workerHttpServer.initialize({
101
+ config,
102
+ providerRuntime: this.providerRuntime,
103
+ getCurrentPublicKey: () => this.requireBootstrap().jwt.publicKey,
104
+ getRotatedPublicKeys: () => (this.requireBootstrap().jwt.rotatedPublicKeys ?? []).map((entry) => ({
105
+ kid: entry.kid,
106
+ publicKey: entry.publicKey,
107
+ ...(entry.notAfter ? { notAfter: entry.notAfter } : {}),
108
+ })),
109
+ });
110
+ this.workerHttpServer.markReady();
111
+ this.isInitialized = true;
112
+ // Audit A-11 + A-3: install the worker's own graceful-shutdown handler (the JSDoc's "SIGTERM
113
+ // handler per G-18 + KD-7", previously claimed but absent). See `registerGracefulShutdown`.
114
+ this.registerGracefulShutdown();
115
+ }
116
+ /**
117
+ * Returns the trusted public key + rotation metadata. The HTTP server's
118
+ * verifier middleware already reads this on every request via the
119
+ * `getCurrentPublicKey` / `getRotatedPublicKeys` callbacks; this getter
120
+ * exists so test code and the worker's own route handlers can inspect
121
+ * the active rotation state.
122
+ */
123
+ getBootstrapResponse() {
124
+ return this.requireBootstrap();
125
+ }
126
+ /**
127
+ * Returns the generated, backend-shaped provider runtime selected for the
128
+ * current worker. Undefined means the worker was started without a generated
129
+ * provider artifact (valid for provider-free workers).
130
+ */
131
+ getProviderRuntime() {
132
+ return this.providerRuntime;
133
+ }
134
+ async shutdown(gracePeriodMs) {
135
+ this.workerHttpServer.markNotReady();
136
+ await this.workerHttpServer.shutdown(gracePeriodMs);
137
+ if (this.refreshTimer) {
138
+ clearInterval(this.refreshTimer);
139
+ this.refreshTimer = undefined;
140
+ }
141
+ this.bootstrapResponse = undefined;
142
+ this.providerRuntime = undefined;
143
+ this.isInitialized = false;
144
+ }
145
+ /**
146
+ * Install the worker's SIGTERM/SIGINT graceful-shutdown handler — the JSDoc's "SIGTERM handler
147
+ * per G-18 + KD-7" that audit A-11 found was claimed but absent (a signal would hard-kill the
148
+ * worker, dropping any final telemetry). The worker is deliberately queue-free (KD-3), so it does
149
+ * NOT use the RabbitMQ-coupled `WorkerShutdownManager`; instead it runs its own cleanup
150
+ * (`shutdown()`) and flushes OTel telemetry before exit — the worker-local analogue of the
151
+ * platform hosts' note-6 flush. `process.once` keeps the host killable (the handler exits).
152
+ * Idempotent.
153
+ */
154
+ registerGracefulShutdown() {
155
+ if (this.signalHandlersRegistered) {
156
+ return;
157
+ }
158
+ this.signalHandlersRegistered = true;
159
+ process.once('SIGTERM', () => void this.gracefulShutdown('SIGTERM'));
160
+ process.once('SIGINT', () => void this.gracefulShutdown('SIGINT'));
161
+ }
162
+ async gracefulShutdown(signal) {
163
+ // `console` is intentional — this runtime kernel injects no LoggerService.
164
+ // eslint-disable-next-line no-console
165
+ console.log(`[worker] received ${signal}, shutting down gracefully…`);
166
+ // Bounded force-exit so a stuck drain/flush can never wedge the process (mirrors the platform
167
+ // hosts' 5s budget). `unref()` keeps the timer from holding the loop open on its own.
168
+ const forceExit = setTimeout(() => process.exit(1), 5_000);
169
+ forceExit.unref();
170
+ try {
171
+ await this.shutdown();
172
+ // Audit A-3: flush the final OTel trace/log batch before exit. `process.exit` skips the
173
+ // preload's `beforeExit` backstop, so without this the worker's last batch is lost on a
174
+ // signal. No-op when telemetry is off (the global handle is undefined). Fail-open — a flush
175
+ // error must never turn a clean shutdown into a non-zero exit.
176
+ await getOtelSdkHandle()
177
+ ?.shutdown()
178
+ .catch(() => {
179
+ // best-effort flush
180
+ });
181
+ process.exit(0);
182
+ }
183
+ catch {
184
+ process.exit(1);
185
+ }
186
+ }
187
+ requireBootstrap() {
188
+ if (!this.isInitialized || !this.bootstrapResponse) {
189
+ throw new Error('StartWorkerApplicationBackendService.getBootstrapResponse() called before initialize() resolved.');
190
+ }
191
+ return this.bootstrapResponse;
192
+ }
193
+ scheduleRefresh(intervalMs) {
194
+ if (this.refreshTimer) {
195
+ clearInterval(this.refreshTimer);
196
+ }
197
+ if (intervalMs === undefined || intervalMs <= 0) {
198
+ return;
199
+ }
200
+ this.refreshTimer = setInterval(() => {
201
+ void this.workerBootstrapClient
202
+ .getBootstrap({ force: true })
203
+ .then((response) => {
204
+ this.bootstrapResponse = response;
205
+ })
206
+ .catch(() => {
207
+ // Refresh failures keep the previously-cached key live so the
208
+ // verifier does not flap; the next interval re-attempts.
209
+ });
210
+ }, intervalMs);
211
+ if (typeof this.refreshTimer.unref === 'function') {
212
+ this.refreshTimer.unref();
213
+ }
214
+ }
215
+ /**
216
+ * Bridge the per-worker materialized provider runtime artifact into the
217
+ * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`.
218
+ *
219
+ * Three accepted input shapes — see `StartMinionApplicationBackendService`
220
+ * for the same pattern. Summary:
221
+ *
222
+ * 1. `{ artifactKind: 'backend', scope: ... }` — already projected.
223
+ * 2. `{ artifactKind: 'nodeWorkers', scope: ..., scopes: undefined }` —
224
+ * pre-scoped per-worker module emitted by `wildo config sync`.
225
+ * 3. `{ artifactKind: 'nodeWorkers', scopes: { [name]: ... } }` —
226
+ * multi-scope artifact (legacy / non-CLI hosts).
227
+ */
228
+ normalizeProviderRuntime(providerRuntime, workerName) {
229
+ if (!providerRuntime) {
230
+ return undefined;
231
+ }
232
+ if (providerRuntime.artifactKind === 'backend') {
233
+ return providerRuntime;
234
+ }
235
+ const artifactKind = providerRuntime.artifactKind;
236
+ if (artifactKind !== 'nodeWorkers') {
237
+ throw new Error(`Unsupported provider runtime artifactKind '${artifactKind}' for worker '${workerName}'.`);
238
+ }
239
+ return this.selectWorkerProviderRuntimeScope(providerRuntime, workerName);
240
+ }
241
+ selectWorkerProviderRuntimeScope(providerRuntime, workerName) {
242
+ const preScopedScope = providerRuntime.scope;
243
+ const scopes = providerRuntime.scopes;
244
+ let scope;
245
+ if (preScopedScope && (!scopes || Object.keys(scopes).length === 0)) {
246
+ scope = preScopedScope;
247
+ }
248
+ else if (scopes) {
249
+ scope = scopes[workerName];
250
+ if (!scope) {
251
+ throw new Error(`Provider runtime artifact does not contain a scope for worker '${workerName}'. `
252
+ + `Re-run \`wildo config sync\` and verify the worker is declared in `
253
+ + `wildo.saas.config.ts \`providers.scopes.workers\`.`);
254
+ }
255
+ }
256
+ if (!scope) {
257
+ throw new Error(`Provider runtime artifact for worker '${workerName}' is missing both a `
258
+ + `pre-scoped \`scope\` and a multi-scope \`scopes\` map. The artifact is malformed.`);
259
+ }
260
+ // Recompute `providerRefs` from the projected per-host scope, NOT
261
+ // from the multi-scope union the parent artifact carries. The
262
+ // `buildMultiScopeArtifactMetadata` upstream computes
263
+ // `providerRefs` as the union across all hosts; preserving that
264
+ // here would make the boot-time `assertProviderRuntimeEnvInSync`
265
+ // guard treat sibling-scope refs as "this host has providers" and
266
+ // mistakenly run reconciliation on hosts whose own scope is empty.
267
+ // Mirrors `selectScopedProviderRuntimeArtifact` in
268
+ // `provider-runtime-artifacts.ts`.
269
+ const projectedProviderRefs = Object.keys(scope.providers ?? {}).sort();
270
+ // Narrowed with the refs, for the same reason (#330): the import map on a multi-scope artifact
271
+ // is the union across every host, and handing this host a sibling's package specifiers would
272
+ // tell it that it may load something it never declared.
273
+ const projectedProviderRuntimeImports = Object.fromEntries(Object.entries(providerRuntime.providerRuntimeImports ?? {}).filter(([providerRef]) => projectedProviderRefs.includes(providerRef)));
274
+ return {
275
+ __AUTOGENERATED__: providerRuntime.__AUTOGENERATED__,
276
+ generatedBy: providerRuntime.generatedBy,
277
+ generatedAt: providerRuntime.generatedAt,
278
+ sourceDigest: providerRuntime.sourceDigest,
279
+ providerRefs: projectedProviderRefs,
280
+ providerRuntimeImports: projectedProviderRuntimeImports,
281
+ providerGraphDigest: providerRuntime.providerGraphDigest,
282
+ lockfileSectionDigest: providerRuntime.lockfileSectionDigest,
283
+ artifactKind: 'backend',
284
+ modules: providerRuntime.modules,
285
+ scope,
286
+ };
287
+ }
288
+ };
289
+ StartWorkerApplicationBackendService = __decorate([
290
+ injectable(),
291
+ __param(0, inject(SAAS_SERVICE_TYPES.WildoWorkerBootstrapClientService)),
292
+ __param(1, inject(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)),
293
+ __metadata("design:paramtypes", [WildoWorkerBootstrapClientService,
294
+ WorkerHttpServerBackendService])
295
+ ], StartWorkerApplicationBackendService);
296
+ export { StartWorkerApplicationBackendService };
297
+ //# sourceMappingURL=start-worker-application.backend.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-worker-application.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/services/start-worker-application.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EACL,gBAAgB,EAEhB,kBAAkB,EAClB,iCAAiC,GAClC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,8BAA8B,GAE/B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAKpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEI,IAAM,oCAAoC,GAA1C,MAAM,oCAAoC;IAS5B;IAEA;IAVX,iBAAiB,CAA8B;IAC/C,eAAe,CAA2B;IAC1C,YAAY,CAAkB;IAC9B,aAAa,GAAG,KAAK,CAAC;IACtB,wBAAwB,GAAG,KAAK,CAAC;IAEzC,YAEmB,qBAAwD,EAExD,gBAAgD;QAFhD,0BAAqB,GAArB,qBAAqB,CAAmC;QAExD,qBAAgB,GAAhB,gBAAgB,CAAgC;IAChE,CAAC;IAEG,KAAK,CAAC,UAAU,CAAC,KAWvB;QACC,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,gC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EAAE,EAAE,CAAC,qBAAqB,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CACzE,CAAC;QAEF,OAAO;YACL,iBAAiB,EAAE,eAAe,CAAC,iBAAiB;YACpD,WAAW,EAAE,eAAe,CAAC,WAAW;YACxC,WAAW,EAAE,eAAe,CAAC,WAAW;YACxC,YAAY,EAAE,eAAe,CAAC,YAAY;YAC1C,YAAY,EAAE,qBAAqB;YACnC,sBAAsB,EAAE,+BAA+B;YACvD,mBAAmB,EAAE,eAAe,CAAC,mBAAmB;YACxD,qBAAqB,EAAE,eAAe,CAAC,qBAAqB;YAC5D,YAAY,EAAE,SAAS;YACvB,OAAO,EAAE,eAAe,CAAC,OAAO;YAChC,KAAK;SACN,CAAC;IACJ,CAAC;CACF,CAAA;AAxSY,oCAAoC;IADhD,UAAU,EAAE;IASR,WAAA,MAAM,CAAC,kBAAkB,CAAC,iCAAiC,CAAC,CAAA;IAE5D,WAAA,MAAM,CAAC,+BAA+B,CAAC,uBAAuB,CAAC,CAAA;qCADxB,iCAAiC;QAEtC,8BAA8B;GAXxD,oCAAoC,CAwShD","sourcesContent":["import { inject, injectable } from 'inversify';\nimport {\n getOtelSdkHandle,\n type ProviderRuntimeArtifact,\n SAAS_SERVICE_TYPES,\n WildoWorkerBootstrapClientService,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n assertProviderRuntimeEnvInSync,\n type AppWorkerBootstrapResponse,\n} from '@wildo-ai/platform-config-lib';\nimport { SAAS_WORKERS_NODE_SERVICE_TYPES } from '../../inject/models/service-types';\nimport type {\n WorkerInitializationConfig,\n WorkerProviderRuntimeArtifact,\n} from './define-worker-init';\nimport { WorkerHttpServerBackendService } from './worker-http-server.backend.service';\n\n/**\n * Worker entrypoint per Q1 LOCKED of\n * `.claude/plans/minions-and-workers-implementation.md`: a standalone\n * runtime kernel that does NOT consume the backend-api's heavy bootstrap\n * (no `AppConfigurationService`, no Mongo / Redis / RabbitMQ). Per the\n * Phase 1.5 mapping doc Table A, the worker only inherits these\n * `bootstrap-base` steps:\n * - Env validation\n * - Apps-manager handshake (limited to fetching the trusted\n * `APPLICATION_WORKER_REQUEST` public key)\n * - Final validation gate\n * - SIGTERM handler (graceful shutdown per G-18 + KD-7)\n *\n * Plus the two worker-specific steps:\n * - HTTP server + controllers (with JWT verifier middleware)\n * - K8s liveness writer (HTTP `/healthz` per `WildoWorkerConfig.http.healthPath`)\n *\n * Shipped behaviour:\n * 1. Initializes `WildoWorkerBootstrapClientService` and prefetches the\n * trusted public key.\n * 2. Schedules the JWKS-style refresh loop; the cached bootstrap response\n * feeds the JWT verifier on every inbound request, so a rotation\n * rolls in without restarting the server.\n * 3. Installs the lightweight `WorkerHttpServerBackendService` (express +\n * helmet, no CORS, no websockets), mounts liveness/readiness probes\n * unauthenticated, and gates everything else behind the\n * `APPLICATION_WORKER_REQUEST` JWT verifier middleware.\n * 4. Marks the readiness probe ready once the bootstrap response is\n * loaded.\n */\n@injectable()\nexport class StartWorkerApplicationBackendService {\n private bootstrapResponse?: AppWorkerBootstrapResponse;\n private providerRuntime?: ProviderRuntimeArtifact;\n private refreshTimer?: NodeJS.Timeout;\n private isInitialized = false;\n private signalHandlersRegistered = false;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.WildoWorkerBootstrapClientService)\n private readonly workerBootstrapClient: WildoWorkerBootstrapClientService,\n @inject(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)\n private readonly workerHttpServer: WorkerHttpServerBackendService,\n ) {}\n\n public async initialize(input: {\n config: WorkerInitializationConfig;\n applicationId: string;\n /**\n * `PLATFORM_APPLICATION_PRIMARY_SECRET` from the four-env\n * bootstrap-env-contract — required so the worker's\n * `WildoWorkerBootstrapClientService` can authenticate against the\n * apps-manager `apps-to-manager/workers/:workerName/bootstrap`\n * endpoint as APP_TO_PLATFORM.\n */\n platformApplicationPrimarySecret: string;\n }): Promise<void> {\n const { config, applicationId, platformApplicationPrimarySecret } = input;\n this.providerRuntime = this.normalizeProviderRuntime(\n config.providerRuntime,\n config.workerName,\n );\n\n // Boot-time fail-closed reconciliation between the typed\n // `wildo-provider-runtime.generated.ts` artifact and the\n // `.wildo-providers.env` file mounted into this process. Catches\n // stale-sync drift before the registry filter would silently boot\n // with mismatched topology.\n //\n // Skipped when:\n // - the artifact is absent (worker authored zero providers AND no\n // scope block in `wildo.saas.config.ts`); or\n // - the artifact has zero `providerRefs` (worker authored an\n // explicit empty scope `providers: {}`). The CLI emitter\n // deliberately does NOT write `.wildo-providers.env` in that\n // case, so the env-vars are absent — running the assertion\n // would raise a false-positive fail-closed.\n // Defensive `?? []` — the schema marks `providerRefs` optional, so\n // a hand-crafted artifact (test fixture / future format drift)\n // could omit it. Without the fallback `.length` would TypeError\n // before fail-closed produced its actionable message. Production\n // CLI emit always defaults to `[]`, so this is hardening only.\n const projectedProviderRefs = this.providerRuntime?.providerRefs ?? [];\n if (this.providerRuntime && projectedProviderRefs.length > 0) {\n assertProviderRuntimeEnvInSync({\n artifactProviderRefs: projectedProviderRefs,\n artifactSourceDigest: this.providerRuntime.sourceDigest,\n hostKind: 'node-worker',\n hostKey: config.workerName,\n });\n }\n\n this.workerBootstrapClient.initialize({\n appsManagerBaseUrl: config.appsManagerBootstrapUrl,\n applicationId,\n workerName: config.workerName,\n platformApplicationPrimarySecret,\n refreshIntervalMs: config.publicKeyRefreshIntervalMs,\n });\n this.bootstrapResponse = await this.workerBootstrapClient.getBootstrap();\n this.scheduleRefresh(config.publicKeyRefreshIntervalMs);\n\n await this.workerHttpServer.initialize({\n config,\n providerRuntime: this.providerRuntime,\n getCurrentPublicKey: () => this.requireBootstrap().jwt.publicKey,\n getRotatedPublicKeys: () =>\n (this.requireBootstrap().jwt.rotatedPublicKeys ?? []).map((entry) => ({\n kid: entry.kid,\n publicKey: entry.publicKey,\n ...(entry.notAfter ? { notAfter: entry.notAfter } : {}),\n })),\n });\n this.workerHttpServer.markReady();\n this.isInitialized = true;\n\n // Audit A-11 + A-3: install the worker's own graceful-shutdown handler (the JSDoc's \"SIGTERM\n // handler per G-18 + KD-7\", previously claimed but absent). See `registerGracefulShutdown`.\n this.registerGracefulShutdown();\n }\n\n /**\n * Returns the trusted public key + rotation metadata. The HTTP server's\n * verifier middleware already reads this on every request via the\n * `getCurrentPublicKey` / `getRotatedPublicKeys` callbacks; this getter\n * exists so test code and the worker's own route handlers can inspect\n * the active rotation state.\n */\n public getBootstrapResponse(): AppWorkerBootstrapResponse {\n return this.requireBootstrap();\n }\n\n /**\n * Returns the generated, backend-shaped provider runtime selected for the\n * current worker. Undefined means the worker was started without a generated\n * provider artifact (valid for provider-free workers).\n */\n public getProviderRuntime(): ProviderRuntimeArtifact | undefined {\n return this.providerRuntime;\n }\n\n public async shutdown(gracePeriodMs?: number): Promise<void> {\n this.workerHttpServer.markNotReady();\n await this.workerHttpServer.shutdown(gracePeriodMs);\n if (this.refreshTimer) {\n clearInterval(this.refreshTimer);\n this.refreshTimer = undefined;\n }\n this.bootstrapResponse = undefined;\n this.providerRuntime = undefined;\n this.isInitialized = false;\n }\n\n /**\n * Install the worker's SIGTERM/SIGINT graceful-shutdown handler — the JSDoc's \"SIGTERM handler\n * per G-18 + KD-7\" that audit A-11 found was claimed but absent (a signal would hard-kill the\n * worker, dropping any final telemetry). The worker is deliberately queue-free (KD-3), so it does\n * NOT use the RabbitMQ-coupled `WorkerShutdownManager`; instead it runs its own cleanup\n * (`shutdown()`) and flushes OTel telemetry before exit — the worker-local analogue of the\n * platform hosts' note-6 flush. `process.once` keeps the host killable (the handler exits).\n * Idempotent.\n */\n private registerGracefulShutdown(): void {\n if (this.signalHandlersRegistered) {\n return;\n }\n this.signalHandlersRegistered = true;\n process.once('SIGTERM', () => void this.gracefulShutdown('SIGTERM'));\n process.once('SIGINT', () => void this.gracefulShutdown('SIGINT'));\n }\n\n private async gracefulShutdown(signal: string): Promise<void> {\n // `console` is intentional — this runtime kernel injects no LoggerService.\n // eslint-disable-next-line no-console\n console.log(`[worker] received ${signal}, shutting down gracefully…`);\n // Bounded force-exit so a stuck drain/flush can never wedge the process (mirrors the platform\n // hosts' 5s budget). `unref()` keeps the timer from holding the loop open on its own.\n const forceExit = setTimeout(() => process.exit(1), 5_000);\n forceExit.unref();\n try {\n await this.shutdown();\n // Audit A-3: flush the final OTel trace/log batch before exit. `process.exit` skips the\n // preload's `beforeExit` backstop, so without this the worker's last batch is lost on a\n // signal. No-op when telemetry is off (the global handle is undefined). Fail-open — a flush\n // error must never turn a clean shutdown into a non-zero exit.\n await getOtelSdkHandle()\n ?.shutdown()\n .catch(() => {\n // best-effort flush\n });\n process.exit(0);\n } catch {\n process.exit(1);\n }\n }\n\n private requireBootstrap(): AppWorkerBootstrapResponse {\n if (!this.isInitialized || !this.bootstrapResponse) {\n throw new Error(\n 'StartWorkerApplicationBackendService.getBootstrapResponse() called before initialize() resolved.',\n );\n }\n return this.bootstrapResponse;\n }\n\n private scheduleRefresh(intervalMs?: number): void {\n if (this.refreshTimer) {\n clearInterval(this.refreshTimer);\n }\n if (intervalMs === undefined || intervalMs <= 0) {\n return;\n }\n this.refreshTimer = setInterval(() => {\n void this.workerBootstrapClient\n .getBootstrap({ force: true })\n .then((response) => {\n this.bootstrapResponse = response;\n })\n .catch(() => {\n // Refresh failures keep the previously-cached key live so the\n // verifier does not flap; the next interval re-attempts.\n });\n }, intervalMs);\n if (typeof this.refreshTimer.unref === 'function') {\n this.refreshTimer.unref();\n }\n }\n\n /**\n * Bridge the per-worker materialized provider runtime artifact into the\n * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`.\n *\n * Three accepted input shapes — see `StartMinionApplicationBackendService`\n * for the same pattern. Summary:\n *\n * 1. `{ artifactKind: 'backend', scope: ... }` — already projected.\n * 2. `{ artifactKind: 'nodeWorkers', scope: ..., scopes: undefined }` —\n * pre-scoped per-worker module emitted by `wildo config sync`.\n * 3. `{ artifactKind: 'nodeWorkers', scopes: { [name]: ... } }` —\n * multi-scope artifact (legacy / non-CLI hosts).\n */\n private normalizeProviderRuntime(\n providerRuntime: WorkerInitializationConfig['providerRuntime'],\n workerName: string,\n ): ProviderRuntimeArtifact | undefined {\n if (!providerRuntime) {\n return undefined;\n }\n if (providerRuntime.artifactKind === 'backend') {\n return providerRuntime;\n }\n const artifactKind = providerRuntime.artifactKind;\n if (artifactKind !== 'nodeWorkers') {\n throw new Error(\n `Unsupported provider runtime artifactKind '${artifactKind}' for worker '${workerName}'.`,\n );\n }\n\n return this.selectWorkerProviderRuntimeScope(providerRuntime, workerName);\n }\n\n private selectWorkerProviderRuntimeScope(\n providerRuntime: WorkerProviderRuntimeArtifact,\n workerName: string,\n ): ProviderRuntimeArtifact {\n const preScopedScope = (providerRuntime as WorkerProviderRuntimeArtifact & {\n scope?: ProviderRuntimeArtifact['scope'];\n }).scope;\n const scopes = providerRuntime.scopes as\n | Record<string, ProviderRuntimeArtifact['scope']>\n | undefined;\n\n let scope: ProviderRuntimeArtifact['scope'] | undefined;\n\n if (preScopedScope && (!scopes || Object.keys(scopes).length === 0)) {\n scope = preScopedScope;\n } else if (scopes) {\n scope = scopes[workerName];\n if (!scope) {\n throw new Error(\n `Provider runtime artifact does not contain a scope for worker '${workerName}'. `\n + `Re-run \\`wildo config sync\\` and verify the worker is declared in `\n + `wildo.saas.config.ts \\`providers.scopes.workers\\`.`,\n );\n }\n }\n\n if (!scope) {\n throw new Error(\n `Provider runtime artifact for worker '${workerName}' is missing both a `\n + `pre-scoped \\`scope\\` and a multi-scope \\`scopes\\` map. The artifact is malformed.`,\n );\n }\n\n // Recompute `providerRefs` from the projected per-host scope, NOT\n // from the multi-scope union the parent artifact carries. The\n // `buildMultiScopeArtifactMetadata` upstream computes\n // `providerRefs` as the union across all hosts; preserving that\n // here would make the boot-time `assertProviderRuntimeEnvInSync`\n // guard treat sibling-scope refs as \"this host has providers\" and\n // mistakenly run reconciliation on hosts whose own scope is empty.\n // Mirrors `selectScopedProviderRuntimeArtifact` in\n // `provider-runtime-artifacts.ts`.\n const projectedProviderRefs = Object.keys(scope.providers ?? {}).sort();\n // Narrowed with the refs, for the same reason (#330): the import map on a multi-scope artifact\n // is the union across every host, and handing this host a sibling's package specifiers would\n // tell it that it may load something it never declared.\n const projectedProviderRuntimeImports = Object.fromEntries(\n Object.entries(\n providerRuntime.providerRuntimeImports ?? {},\n ).filter(([providerRef]) => projectedProviderRefs.includes(providerRef)),\n );\n\n return {\n __AUTOGENERATED__: providerRuntime.__AUTOGENERATED__,\n generatedBy: providerRuntime.generatedBy,\n generatedAt: providerRuntime.generatedAt,\n sourceDigest: providerRuntime.sourceDigest,\n providerRefs: projectedProviderRefs,\n providerRuntimeImports: projectedProviderRuntimeImports,\n providerGraphDigest: providerRuntime.providerGraphDigest,\n lockfileSectionDigest: providerRuntime.lockfileSectionDigest,\n artifactKind: 'backend',\n modules: providerRuntime.modules,\n scope,\n };\n }\n}\n"]}