@wildo-ai/saas-workers-node-lib 1.1.6 → 1.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/inject/models/container.d.ts.map +1 -1
- package/dist/esm/inject/models/container.js.map +1 -1
- package/dist/esm/inject/models/service-types.d.ts.map +1 -1
- package/dist/esm/inject/models/service-types.js.map +1 -1
- package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.d.ts.map +1 -1
- package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.js.map +1 -1
- package/dist/esm/runtime/middlewares/worker-request-context.middleware.d.ts.map +1 -1
- package/dist/esm/runtime/middlewares/worker-request-context.middleware.js.map +1 -1
- package/dist/esm/runtime/services/define-worker-init.d.ts.map +1 -1
- package/dist/esm/runtime/services/define-worker-init.js.map +1 -1
- package/dist/esm/runtime/services/read-worker-bootstrap-env.d.ts.map +1 -1
- package/dist/esm/runtime/services/read-worker-bootstrap-env.js.map +1 -1
- package/dist/esm/runtime/services/read-worker-http-surface-env.d.ts.map +1 -1
- package/dist/esm/runtime/services/read-worker-http-surface-env.js.map +1 -1
- package/dist/esm/runtime/services/start-worker-application.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/services/start-worker-application.backend.service.js.map +1 -1
- package/dist/esm/runtime/services/worker-http-server.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/services/worker-http-server.backend.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +5 -5
package/dist/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,iDAAiD,CAAC;AAChE,cAAc,6DAA6D,CAAC;AAC5E,cAAc,uDAAuD,CAAC;AACtE,cAAc,sDAAsD,CAAC"}
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,iDAAiD,CAAC;AAChE,cAAc,6DAA6D,CAAC;AAC5E,cAAc,uDAAuD,CAAC;AACtE,cAAc,sDAAsD,CAAC","sourcesContent":["/**\n * Node worker runtime-host boundary.\n *\n * Owns the worker-side surface that intentionally lives OUTSIDE\n * `saas-backend-lib` per KD-3 of\n * `.claude/plans/minions-and-workers-implementation.md`: the worker is a\n * stateless HTTP-only runtime with no backing-service access (Mongo /\n * Redis / RabbitMQ MUST NOT bleed in).\n *\n * Current shipped surface:\n * - `defineWorkerInit` — typed config helper for the worker entrypoint\n * including the generated provider-runtime seam for Node workers\n * - `setupSaasWorkerInjection` — composes the worker DI graph on top of\n * the saas-backend bindings (JWT signer family, logger, error builder,\n * `WildoWorkerBootstrapClientService`) without auto-connecting backing\n * services\n * - `StartWorkerApplicationBackendService` — wires the dynamic public-key\n * resolver (Q3 LOCKED), prefetches the trusted public key, and\n * schedules the JWKS-style refresh loop while selecting the current\n * worker's generated provider scope\n * - `WorkerHttpServerBackendService` — installs the authenticated route\n * surface and threads the selected provider runtime into\n * `registerRoutes(...)`\n *\n * Non-Node workers remain on the deferred env/bootstrap delivery track;\n * this package only owns executable provider delivery for Node/JS/TS\n * worker runtimes.\n */\nexport * from './inject/models/service-types';\nexport * from './inject/models/container';\nexport * from './runtime/services/define-worker-init';\nexport * from './runtime/services/read-worker-bootstrap-env';\nexport * from './runtime/services/read-worker-http-surface-env';\nexport * from './runtime/services/start-worker-application.backend.service';\nexport * from './runtime/services/worker-http-server.backend.service';\nexport * from './runtime/middlewares/worker-jwt-verifier.middleware';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"container.d.ts","sourceRoot":"","sources":["../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EAIxB,MAAM,4BAA4B,CAAC;AAKpC,KAAK,SAAS,GAAG,kBAAkB,CAAC;AA4CpC,wBAAgB,wBAAwB,CAAC,QAAQ,CAAC,EAAE,SAAS,GAAG,SAAS,CAYxE;AAED,wBAAgB,yBAAyB,IAAI,SAAS,CAErD;AAED,wBAAgB,2BAA2B,IAAI,IAAI,CAGlD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"container.js","sourceRoot":"","sources":["../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oCAAoC,EAAE,MAAM,iEAAiE,CAAC;AACvH,OAAO,EAAE,8BAA8B,EAAE,MAAM,2DAA2D,CAAC;AAC3G,OAAO,EAAE,+BAA+B,EAAE,MAAM,iBAAiB,CAAC;AAIlE,IAAI,sBAA6C,CAAC;AAElD;;;;;;;;;;;;;;GAcG;AACH,MAAM,wBAAwB;IACC;IAA7B,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;QAC/C,IAAI,CAAC,mBAAmB,EAAE,CAAC;IA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AAE,CAAC;AACzB,CAAC","sourcesContent":["import {\n type InversifyContainer,\n resetGlobalContainer,\n SAAS_SERVICE_TYPES,\n setupSaasBackendInjection,\n} from '@wildo-ai/saas-backend-lib';\nimport { StartWorkerApplicationBackendService } from '../../runtime/services/start-worker-application.backend.service';\nimport { WorkerHttpServerBackendService } from '../../runtime/services/worker-http-server.backend.service';\nimport { SAAS_WORKERS_NODE_SERVICE_TYPES } from './service-types';\n\ntype Container = InversifyContainer;\n\nlet globalWorkersContainer: Container | undefined;\n\n/**\n * Composes the worker DI graph on top of `setupSaasBackendInjection()`.\n *\n * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the\n * worker boundary deliberately does NOT consume backing-service bindings\n * (Mongo / Redis / RabbitMQ) at runtime. The shared backend container is\n * still composed underneath because it carries the JWT signer family,\n * the logger, the error builder, and `WildoWorkerBootstrapClientService`\n * — all stateless services the worker host needs. Subsequent slices may\n * shrink this composition further (e.g. by introducing a smaller\n * \"stateless-services-only\" base) once the contract stabilises; today\n * the saas-backend bindings do not auto-connect to backing services\n * unless their `initialize()` is called, so wiring them in the container\n * is safe at the worker boundary.\n */\nclass SaasWorkersNodeContainer {\n constructor(private readonly container: Container) {\n this.bindRuntimeServices();\n }\n\n public getContainer(): Container {\n return this.container;\n }\n\n private bindRuntimeServices(): void {\n if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)) {\n this.container\n .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)\n .to(StartWorkerApplicationBackendService)\n .inSingletonScope();\n }\n if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)) {\n this.container\n .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)\n .to(WorkerHttpServerBackendService)\n .inSingletonScope();\n }\n }\n}\n\nexport function setupSaasWorkerInjection(existing?: Container): Container {\n const container = existing ?? globalWorkersContainer ?? setupSaasBackendInjection();\n if (existing && !container.isBound(SAAS_SERVICE_TYPES.WildoWorkerBootstrapClientService)) {\n throw new Error(\n 'setupSaasWorkerInjection(existing) requires a container that already includes saas-backend-lib bindings.',\n );\n }\n const workersContainer = new SaasWorkersNodeContainer(container);\n if (!existing) {\n globalWorkersContainer = workersContainer.getContainer();\n }\n return workersContainer.getContainer();\n}\n\nexport function getGlobalWorkersContainer(): Container {\n return globalWorkersContainer ?? setupSaasWorkerInjection();\n}\n\nexport function resetGlobalWorkersContainer(): void {\n globalWorkersContainer = undefined;\n resetGlobalContainer();\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,CAAC,6BAA6B,EAAE,MAAM,CAAC;IAC/C,QAAQ,CAAC,uBAAuB,EAAE,MAAM,CAAC;CAC1C;AAED,eAAO,MAAM,+BAA+B,EAAE,2BAG7C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-types.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,+BAA+B,GAAgC;IAC1E,6BAA6B,EAAE,MAAM,CAAC,GAAG,CAAC,gDAAgD,CAAC;IAC3F,uBAAuB,EAAE,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC;CAChF,CAAC","sourcesContent":["export interface SaasWorkersNodeServiceTypes {\n readonly StartWorkerApplicationService: symbol;\n readonly WorkerHttpServerService: symbol;\n}\n\nexport const SAAS_WORKERS_NODE_SERVICE_TYPES: SaasWorkersNodeServiceTypes = {\n StartWorkerApplicationService: Symbol.for('SaaS.WorkersNode.StartWorkerApplicationService'),\n WorkerHttpServerService: Symbol.for('SaaS.WorkersNode.WorkerHttpServerService'),\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-jwt-verifier.middleware.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"worker-jwt-verifier.middleware.d.ts","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-jwt-verifier.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAW,cAAc,EAA0B,MAAM,SAAS,CAAC;AAC/E,OAAO,GAAG,MAAM,cAAc,CAAC;AAG/B;;;;;;;;;GASG;AACH,MAAM,WAAW,wBAAyB,SAAQ,GAAG,CAAC,UAAU;IAC9D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf,SAAS,CAAC,EAAE,wBAAwB,CAAC;SACtC;KACF;CACF;AAED,MAAM,WAAW,6BAA6B;IAC5C;;;;;OAKG;IACH,mBAAmB,EAAE,MAAM,MAAM,CAAC;IAClC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,KAAK,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;KAAE,CAAC,CAAC;CAClG;AAED;;;;;;;;GAQG;AACH,wBAAgB,iCAAiC,CAC/C,KAAK,EAAE,6BAA6B,GACnC,cAAc,CAmChB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-jwt-verifier.middleware.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"worker-jwt-verifier.middleware.js","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-jwt-verifier.middleware.ts"],"names":[],"mappings":"AACA,OAAO,GAAG,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C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Request, RequestHandler, Response, NextFunction } from 'express';\nimport jwt from 'jsonwebtoken';\nimport { JwtPrivateKeys, JwtVerifyOptions } from '@wildo-ai/saas-backend-lib';\n\n/**\n * Per-request claims attached to the express `Request` object after the\n * `APPLICATION_WORKER_REQUEST` JWT has been verified. The shape mirrors\n * what `jsonwebtoken.verify` decodes: framework `iat`/`exp`/`iss`/`aud`\n * fields plus whatever the backend-api stamped onto the payload.\n *\n * Worker route handlers read this via `req.workerJwt` to authorize a\n * specific call, e.g. confirming the source applicationId or correlation\n * id that the backend-api signed.\n */\nexport interface WorkerVerifiedJwtPayload extends jwt.JwtPayload {\n applicationId?: string;\n correlationId?: string;\n workerName?: string;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n workerJwt?: WorkerVerifiedJwtPayload;\n }\n }\n}\n\nexport interface WorkerJwtVerifierFactoryInput {\n /**\n * Returns the trusted `APPLICATION_WORKER_REQUEST` public key. Called\n * on every request so the JWKS-style refresh loop (managed by\n * `StartWorkerApplicationBackendService`) takes effect without\n * restarting the server.\n */\n getCurrentPublicKey: () => string;\n /**\n * Optional set of rotation public keys that are still trusted during\n * a rotation window. Each entry is tried after the current key fails.\n * Provided by the bootstrap response payload.\n */\n getRotatedPublicKeys?: () => Array<{ kid: string; publicKey: string; notAfter?: Date | string }>;\n}\n\n/**\n * Factory for the worker JWT verifier middleware. Verifies inbound\n * `Authorization: Bearer <jwt>` headers against the trusted\n * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver).\n *\n * Independent of any DI container: takes plain functions returning the\n * current trusted key(s). The host wires those functions to the\n * bootstrap response managed by `StartWorkerApplicationBackendService`.\n */\nexport function createWorkerJwtVerifierMiddleware(\n input: WorkerJwtVerifierFactoryInput,\n): RequestHandler {\n const verifyOptions = JwtVerifyOptions[JwtPrivateKeys.APPLICATION_WORKER_REQUEST];\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const authHeader = req.headers.authorization ?? req.headers.Authorization;\n const headerValue = Array.isArray(authHeader) ? authHeader[0] : authHeader;\n if (!headerValue || typeof headerValue !== 'string' || !headerValue.startsWith('Bearer ')) {\n res.status(401).json({ error: 'missing_authorization' });\n return;\n }\n const token = headerValue.slice('Bearer '.length).trim();\n if (!token) {\n res.status(401).json({ error: 'empty_authorization_token' });\n return;\n }\n\n const candidates: Array<{ kid: string; publicKey: string }> = [\n { kid: 'current', publicKey: input.getCurrentPublicKey() },\n ...(input.getRotatedPublicKeys?.() ?? [])\n .filter((candidate) => !candidate.notAfter || new Date(candidate.notAfter).getTime() > Date.now())\n .map(({ kid, publicKey }) => ({ kid, publicKey })),\n ];\n\n for (const candidate of candidates) {\n try {\n const decoded = await verifyOnce(token, candidate.publicKey, verifyOptions);\n req.workerJwt = decoded;\n next();\n return;\n } catch {\n // try the next candidate; only emit 401 once all keys have failed\n }\n }\n res.status(401).json({ error: 'invalid_jwt' });\n };\n}\n\nfunction verifyOnce(\n token: string,\n publicKey: string,\n verifyOptions: jwt.VerifyOptions,\n): Promise<WorkerVerifiedJwtPayload> {\n return new Promise((resolve, reject) => {\n jwt.verify(token, publicKey, verifyOptions, (err, decoded) => {\n if (err) {\n reject(err);\n return;\n }\n if (!decoded || typeof decoded === 'string') {\n reject(new Error('jwt_payload_not_object'));\n return;\n }\n resolve(decoded as WorkerVerifiedJwtPayload);\n });\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-request-context.middleware.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"worker-request-context.middleware.d.ts","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-request-context.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAyB,cAAc,EAAY,MAAM,SAAS,CAAC;AAI/E,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf;;;;;;eAMG;YACH,aAAa,CAAC,EAAE,MAAM,CAAC;SACxB;KACF;CACF;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,oCAAoC,IAAI,cAAc,CAQrE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-request-context.middleware.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"worker-request-context.middleware.js","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-request-context.middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAkB7F;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,oCAAoC;IAClD,OAAO,CAAC,GAAY,EAAE,IAAc,EAAE,IAAkB,EAAQ,EAAE;QAChE,MAAM,KAAK,GAAG,wBAAwB,CAAC;YACrC,oBAAoB,EAAE,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,cAAc,CAAC;SAC9D,CAAC,CAAC;QACH,GAAG,CAAC,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC;QACxC,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { WildoHeaderKeys } from '@wildo-ai/saas-models';\nimport { buildRequestContextFrame, runWithRequestContext } from '@wildo-ai/saas-backend-lib';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n /**\n * The correlation id for THIS worker dispatch, read from the `x-correlation-id` header (SD7 — the\n * header the backend interceptor stamps, NEVER the `APPLICATION_WORKER_REQUEST` JWT `correlationId`\n * claim). Set by {@link createWorkerRequestContextMiddleware}. The same value is carried in the\n * ambient request-context ALS frame, so backend-lib code invoked during the dispatch logs it via\n * the pino mixin; worker route handlers that log directly can read `req.correlationId`.\n */\n correlationId?: string;\n }\n }\n}\n\n/**\n * Establish the request-scoped correlation frame for an inbound worker dispatch.\n *\n * The backend's `RemoteClientBaseBackendService` interceptor stamps the canonical `x-correlation-id`\n * header on every backend → worker call (Phase 6). This middleware ingests it into the request-context\n * ALS frame — the SAME `@wildo-ai/saas-backend-lib` primitive the backend HTTP server uses in\n * `setupRequestContext()` — so the worker's dispatch shares the DISPATCHING request's correlationId:\n * every log line emitted by backend-lib code invoked within the dispatch (via the pino ALS mixin)\n * carries it, and the value is mirrored onto `req.correlationId` for handlers that log directly. A fresh\n * id is minted when the header is absent or unsafe, so an un-correlated call stays independently traceable.\n *\n * Per SD7 the id comes from the HEADER, not the JWT: correlation is a uniform transport concern (the same\n * `x-correlation-id` channel used service → service), deliberately decoupled from worker authentication.\n * The pattern — wrapping the whole downstream continuation in `runWithRequestContext(frame, () => next())`\n * so route handlers AND the error path share one ambient frame — is pinned by the backend HTTP-seam\n * integration test (`request-context.als.http-seam.integration.test.ts`); this worker seam is structurally\n * identical (minus `x-frontend-service-name`, which a backend-originated dispatch never carries).\n */\nexport function createWorkerRequestContextMiddleware(): RequestHandler {\n return (req: Request, _res: Response, next: NextFunction): void => {\n const frame = buildRequestContextFrame({\n inboundCorrelationId: req.get(WildoHeaderKeys.CORRELATION_ID),\n });\n req.correlationId = frame.correlationId;\n runWithRequestContext(frame, () => next());\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-worker-init.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"define-worker-init.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/define-worker-init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CA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C1E;;;;OAIG;IACH,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,uBAAuB,KAAK,IAAI,CAAC;CAC1E;AAED,MAAM,WAAW,uBAAuB;IACtC,SAAS,EAAE,cAAc,CAAC;IAC1B,eAAe,CAAC,EAAE,uBAAuB,CAAC;CAC3C;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,0BAA0B,GACjC,0BAA0B,CAE5B;;AACD,+DAA+D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-worker-init.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"define-worker-init.js","sourceRoot":"","sources":["../../../../src/runtime/services/define-worker-init.ts"],"names":[],"mappings":"AA0FA,MAAM,UAAU,gBAAgB,CAC9B,MAAkC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,+DAA+D","sourcesContent":["import type { Router, RequestHandler } from 'express';\nimport type { BackgroundRuntimeType } from '@wildo-ai/saas-models';\nimport type { ProviderRuntimeArtifact } from '@wildo-ai/saas-backend-lib';\n\ntype ProviderRuntimeScope = ProviderRuntimeArtifact['scope'];\ntype ProviderRuntimeModules = ProviderRuntimeArtifact['modules'];\n\nexport interface WorkerProviderRuntimeArtifact {\n __AUTOGENERATED__: string;\n generatedBy: ProviderRuntimeArtifact['generatedBy'];\n generatedAt: string;\n sourceDigest: string;\n providerRefs?: ProviderRuntimeArtifact['providerRefs'];\n /**\n * Mirrored from the engine artifact so the per-host projection can FORWARD it (#330).\n *\n * This interface is a hand-written mirror of the CLI's multi-scope artifact, so a field the\n * CLI emits and this shape omits is a field the projection can only reach through a cast —\n * which would assert, across a package boundary, the very thing nobody checked.\n */\n providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];\n /** Mirrored for the same reason: the projection narrows and forwards it (#1672). */\n providerRuntimeAugmentations?: ProviderRuntimeArtifact['providerRuntimeAugmentations'];\n providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];\n lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];\n artifactKind: 'nodeWorkers';\n modules: ProviderRuntimeModules;\n scopes: Record<string, ProviderRuntimeScope>;\n}\n\n/**\n * Inputs the worker host needs to bootstrap. Intentionally minimal per KD-3\n * of `.claude/plans/minions-and-workers-implementation.md`: the worker has\n * no backing-service access (no Mongo / Redis / RabbitMQ), only:\n * - the four-env bootstrap-env-contract\n * (`APPLICATION_ID`, `PLATFORM_APPLICATION_PRIMARY_SECRET`,\n * `PLATFORM_APPS_MANAGER_URL`, `APPLICATION_ENV`), read via\n * `readWorkerBootstrapEnv()`,\n * - the worker's HTTP surface descriptor (port + paths),\n * - the apps-manager `worker-bootstrap` URL it polls for the trusted\n * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver),\n * - the worker's identity (`workerName`, paired with\n * `APP_OWNED_SERVICE_KIND === BackgroundRuntimeType.WORKER`).\n *\n * The wider DI graph used by backend-api and minions is deliberately NOT\n * imported here — pulling it in would drag Mongo / Redis / RabbitMQ\n * services into the worker boundary and defeat the language-pluggable\n * isolation the worker kind exists to provide.\n */\n/** @wildo_source:part:start workers.node.worker-init-contract facet:layer:backend facet:family:worker facet:audience:app-developer */\nexport interface WorkerInitializationConfig {\n workerName: string;\n serviceKind: BackgroundRuntimeType.WORKER;\n http: {\n port: number;\n healthPath: string;\n readyPath: string;\n metricsPath?: string;\n };\n appsManagerBootstrapUrl: string;\n /**\n * Generated provider topology imported from the worker package's local\n * `src/generated/wildo-provider-runtime.generated.ts` module.\n *\n * Node workers receive only their own pre-scoped provider graph. Non-Node\n * workers stay on the deferred env/bootstrap delivery path and therefore do\n * not use this seam.\n */\n providerRuntime?: ProviderRuntimeArtifact | WorkerProviderRuntimeArtifact;\n /**\n * Cadence (ms) at which the worker re-polls apps-manager for the\n * trusted `APPLICATION_WORKER_REQUEST` public key. JWKS-style refresh\n * per Q3 LOCKED.\n */\n publicKeyRefreshIntervalMs?: number;\n /**\n * Worker route registration. Called once during HTTP server install\n * with an authenticated `Router` (the JWT verifier middleware is\n * already mounted by the host) plus the verifier handle as `verifyJwt`\n * for routes that need to opt out of the default authenticated\n * pipeline.\n */\n registerRoutes?: (router: Router, deps: WorkerRouteDependencies) => void;\n}\n\nexport interface WorkerRouteDependencies {\n verifyJwt: RequestHandler;\n providerRuntime?: ProviderRuntimeArtifact;\n}\n\nexport function defineWorkerInit(\n config: WorkerInitializationConfig,\n): WorkerInitializationConfig {\n return config;\n}\n/** @wildo_source:part:end workers.node.worker-init-contract */\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read-worker-bootstrap-env.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"read-worker-bootstrap-env.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/read-worker-bootstrap-env.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,aAAa,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,gCAAgC,EAAE,MAAM,CAAC;IACzC;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,oFAAoF;IACpF,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,kBAAkB,CAmCpB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read-worker-bootstrap-env.js","sourceRoot":"","sources":["
|
|
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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read-worker-http-surface-env.d.ts","sourceRoot":"","sources":["
|
|
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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read-worker-http-surface-env.js","sourceRoot":"","sources":["
|
|
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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-worker-application.backend.service.d.ts","sourceRoot":"","sources":["
|
|
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;IAkEjB;;;;;;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;CAuEzC"}
|
|
@@ -1 +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,iCA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AAC,EAAE,CAAC,CAAC,CAAC,EAAE,4BAA4B,EAAE,MAAM,CAAC,WAAW,CAAC,sBAAsB,CAAC,EAAE,CAAC;YAC5H,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;AA9SY,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,CA8ShD","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 // The startup read tolerates apps-manager restarting; the refresh loop below keeps a single attempt.\n this.bootstrapResponse = await this.workerBootstrapClient.getBootstrapAtStartup();\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 // Narrowed with the refs as well (#1672): a host applies augmentations only to providers it declares, and a\n // sibling's opt-in must not load a package into this process.\n const projectedAugmentations = Object.entries(providerRuntime.providerRuntimeAugmentations ?? {})\n .filter(([providerRef]) => projectedProviderRefs.includes(providerRef));\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 ...(projectedAugmentations.length === 0 ? {} : { providerRuntimeAugmentations: Object.fromEntries(projectedAugmentations) }),\n providerGraphDigest: providerRuntime.providerGraphDigest,\n lockfileSectionDigest: providerRuntime.lockfileSectionDigest,\n artifactKind: 'backend',\n modules: providerRuntime.modules,\n scope,\n };\n }\n}\n"]}
|
|
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;IACt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A,MAAM,CAAC,+BAA+B,CAAC,uBAAuB,CAAC,CAAA;qCADxB,iCAAiC;QAEtC,8BAA8B;GAXxD,oCAAoC,CA8ShD","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 // The startup read tolerates apps-manager restarting; the refresh loop below keeps a single attempt.\n this.bootstrapResponse = await this.workerBootstrapClient.getBootstrapAtStartup();\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 // Narrowed with the refs as well (#1672): a host applies augmentations only to providers it declares, and a\n // sibling's opt-in must not load a package into this process.\n const projectedAugmentations = Object.entries(providerRuntime.providerRuntimeAugmentations ?? {})\n .filter(([providerRef]) => projectedProviderRefs.includes(providerRef));\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 ...(projectedAugmentations.length === 0 ? {} : { providerRuntimeAugmentations: Object.fromEntries(projectedAugmentations) }),\n providerGraphDigest: providerRuntime.providerGraphDigest,\n lockfileSectionDigest: providerRuntime.lockfileSectionDigest,\n artifactKind: 'backend',\n modules: providerRuntime.modules,\n scope,\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-http-server.backend.service.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"worker-http-server.backend.service.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/worker-http-server.backend.service.ts"],"names":[],"mappings":"AACA,OAAgB,EAAgB,KAAK,cAAc,EAAU,MAAM,SAAS,CAAC;AAG7E,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAIvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBACa,8BAA8B;IACzC,OAAO,CAAC,GAAG,CAAC,CAAU;IACtB,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;IAEjB,UAAU,CAAC,KAAK,EAAE;QACvB,MAAM,EAAE,0BAA0B,CAAC;QACnC,eAAe,CAAC,EAAE,uBAAuB,CAAC;QAC1C,mBAAmB,EAAE,MAAM,MAAM,CAAC;QAClC,oBAAoB,CAAC,EAAE,MAAM,KAAK,CAAC;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,SAAS,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;SAAE,CAAC,CAAC;QACjG,cAAc,CAAC,EAAE,cAAc,CAAC;KACjC,GAAG,OAAO,CAAC,IAAI,CAAC;IAgEV,SAAS,IAAI,IAAI;IAIjB,YAAY,IAAI,IAAI;IAId,QAAQ,CAAC,aAAa,GAAE,MAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAiBrE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-http-server.backend.service.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"worker-http-server.backend.service.js","sourceRoot":"","sources":["../../../../src/runtime/services/worker-http-server.backend.service.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,OAAO,EAAE,EAAqC,MAAM,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,MAAM,MAAM,QAAQ,CAAC;AAI5B,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAAE,oCAAoC,EAAE,MAAM,kDAAkD,CAAC;AAExG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEI,IAAM,8BAA8B,GAApC,MAAM,8BAA8B;IACjC,GAAG,CAAW;IACd,MAAM,CAAU;IAChB,OAAO,GAAG,KAAK,CAAC;IAEjB,UAAU,CAAC,KAMjB;QACC,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;QAC7E,CAAC;QAED,MAAM,EACJ,MAAM,EACN,eAAe,EACf,mBAAmB,EACnB,oBAAoB,EACpB,cAAc,GACf,GAAG,KAAK,CAAC;QACV,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;QACtB,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAC5B,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;QAClB,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QAExC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE;YAC5C,GAAG,CAA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GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC;IACvB,CAAC;CACF,CAAA;AApGY,8BAA8B;IAD1C,UAAU,EAAE;GACA,8BAA8B,CAoG1C","sourcesContent":["import { injectable } from 'inversify';\nimport express, { type Express, type RequestHandler, Router } from 'express';\nimport helmet from 'helmet';\nimport type { Server } from 'http';\nimport type { ProviderRuntimeArtifact } from '@wildo-ai/saas-backend-lib';\nimport type { WorkerInitializationConfig } from './define-worker-init';\nimport { createWorkerJwtVerifierMiddleware } from '../middlewares/worker-jwt-verifier.middleware';\nimport { createWorkerRequestContextMiddleware } from '../middlewares/worker-request-context.middleware';\n\n/**\n * Lightweight HTTP server install for the Wildo worker runtime.\n *\n * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the\n * worker is a stateless HTTP-only runtime. The server here intentionally\n * does NOT pull `HttpServerBackendService` from `saas-backend-lib` — that\n * service depends on `AppConfigurationService`, `RedisService`,\n * `WebSocketService`, `ControllersRegistryHandlerBackendService`, etc.,\n * none of which exist (or should exist) at the worker boundary.\n *\n * Surface:\n * - `helmet` security headers (no CORS — workers are ClusterIP-only,\n * never reached by browsers, never granted ingress).\n * - `express.json()` body parser with a tight default limit.\n * - Liveness / readiness probes mounted on the authored\n * `WildoWorkerConfig.http.{healthPath,readyPath}` (no JWT required —\n * K8s probe traffic is unauthenticated by design).\n * - Optional `metricsPath` mounted unauthenticated for in-cluster\n * prom-client scraping (KD-3: no public ingress, so this is fine).\n * - All other routes are gated by the\n * `APPLICATION_WORKER_REQUEST`-keyed JWT verifier; worker code\n * registers them via `WorkerInitializationConfig.registerRoutes`.\n *\n * Correlation-id propagation (CC-8 / Phase 6) is wired: an early\n * `createWorkerRequestContextMiddleware()` ingests the backend-stamped\n * `x-correlation-id` into the request-context ALS frame, so a dispatch's\n * backend-lib logs share the dispatching request's id and `req.correlationId`\n * is available to handlers. The kernel itself still logs via `console` by\n * design (it injects no `LoggerService`). Subsequent slices may layer in\n * prom-client metrics scaffolding and graceful-shutdown drain (KD-7\n * `gracePeriodSec`); the surface above is otherwise the minimum needed to\n * verify a backend-api → worker round-trip end-to-end.\n */\n@injectable()\nexport class WorkerHttpServerBackendService {\n private app?: Express;\n private server?: Server;\n private isReady = false;\n\n public initialize(input: {\n config: WorkerInitializationConfig;\n providerRuntime?: ProviderRuntimeArtifact;\n getCurrentPublicKey: () => string;\n getRotatedPublicKeys?: () => Array<{ kid: string; publicKey: string; notAfter?: Date | string }>;\n metricsHandler?: RequestHandler;\n }): Promise<void> {\n if (this.app) {\n throw new Error('WorkerHttpServerBackendService.initialize called twice.');\n }\n\n const {\n config,\n providerRuntime,\n getCurrentPublicKey,\n getRotatedPublicKeys,\n metricsHandler,\n } = input;\n const app = express();\n app.disable('x-powered-by');\n app.use(helmet());\n app.use(express.json({ limit: '1mb' }));\n\n app.get(config.http.healthPath, (_req, res) => {\n res.status(200).json({ status: 'ok' });\n });\n app.get(config.http.readyPath, (_req, res) => {\n if (this.isReady) {\n res.status(200).json({ status: 'ready' });\n } else {\n res.status(503).json({ status: 'not_ready' });\n }\n });\n\n if (config.http.metricsPath && metricsHandler) {\n app.get(config.http.metricsPath, metricsHandler);\n }\n\n // Phase 6 — establish the correlation frame for dispatch traffic. Mounted AFTER the health / ready /\n // metrics probes (they are registered above and short-circuit first, keeping high-frequency K8s probe\n // traffic out of a frame) and BEFORE the authenticated router, so every worker dispatch — and the 404\n // fallthrough — runs inside a frame carrying the backend-stamped `x-correlation-id`.\n app.use(createWorkerRequestContextMiddleware());\n\n const verifyJwt = createWorkerJwtVerifierMiddleware({\n getCurrentPublicKey,\n getRotatedPublicKeys,\n });\n\n if (config.registerRoutes) {\n const authenticatedRouter = Router();\n authenticatedRouter.use(verifyJwt);\n config.registerRoutes(authenticatedRouter, { verifyJwt, providerRuntime });\n app.use(authenticatedRouter);\n }\n\n app.use((_req, res) => {\n res.status(404).json({ error: 'not_found' });\n });\n\n return new Promise((resolve, reject) => {\n const server = app.listen(config.http.port, () => {\n this.app = app;\n this.server = server;\n resolve();\n });\n server.on('error', reject);\n });\n }\n\n public markReady(): void {\n this.isReady = true;\n }\n\n public markNotReady(): void {\n this.isReady = false;\n }\n\n public async shutdown(gracePeriodMs: number = 10_000): Promise<void> {\n this.isReady = false;\n if (!this.server) return;\n const server = this.server;\n await new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n server.closeAllConnections?.();\n resolve();\n }, gracePeriodMs);\n server.close(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n this.server = undefined;\n this.app = undefined;\n }\n}\n"]}
|