@wildo-ai/saas-minions-lib 1.1.11 → 1.1.13
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/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.js.map +1 -1
- 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/queue/minion-tick-consumer.backend.service.d.ts +10 -1
- package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js +12 -1
- package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js.map +1 -1
- package/dist/esm/runtime/services/define-minion-init.d.ts +6 -3
- package/dist/esm/runtime/services/define-minion-init.d.ts.map +1 -1
- package/dist/esm/runtime/services/define-minion-init.js.map +1 -1
- package/dist/esm/runtime/services/minion-liveness-heartbeat.d.ts +57 -0
- package/dist/esm/runtime/services/minion-liveness-heartbeat.d.ts.map +1 -0
- package/dist/esm/runtime/services/minion-liveness-heartbeat.js +125 -0
- package/dist/esm/runtime/services/minion-liveness-heartbeat.js.map +1 -0
- package/dist/esm/runtime/services/own-schedule-reader.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/services/own-schedule-reader.backend.service.js.map +1 -1
- package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts +14 -0
- package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/services/start-minion-application.backend.service.js +58 -8
- package/dist/esm/runtime/services/start-minion-application.backend.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +6 -6
- package/src/runtime/queue/__tests__/minion-tick-consumer.backend.service.test.ts +16 -1
- package/src/runtime/queue/minion-tick-consumer.backend.service.ts +13 -1
- package/src/runtime/services/__tests__/minion-liveness-heartbeat.test.ts +116 -0
- package/src/runtime/services/__tests__/start-minion-application.backend.service.test.ts +149 -2
- package/src/runtime/services/define-minion-init.ts +6 -3
- package/src/runtime/services/minion-liveness-heartbeat.ts +126 -0
- package/src/runtime/services/start-minion-application.backend.service.ts +63 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"minion-liveness-heartbeat.js","sourceRoot":"","sources":["../../../../src/runtime/services/minion-liveness-heartbeat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAsB,MAAM,4BAA4B,CAAC;AACrF,OAAO,EAAE,6BAA6B,EAAwC,MAAM,+BAA+B,CAAC;AAEpH;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,OAAO,uBAAuB;IAOf;IACA;IACA;IACA;IATX,KAAK,CAA6C;IAClD,QAAQ,CAA4B;IAC5C,gGAAgG;IACxF,gBAAgB,GAAG,KAAK,CAAC;IAEjC,YACmB,QAAyC,EACzC,eAA8B,EAC9B,MAAsD,EACtD,MAAoB,IAAI,CAAC,GAAG;QAH5B,aAAQ,GAAR,QAAQ,CAAiC;QACzC,oBAAe,GAAf,eAAe,CAAe;QAC9B,WAAM,GAAN,MAAM,CAAgD;QACtD,QAAG,GAAH,GAAG,CAAyB;IAC5C,CAAC;IAEJ;;;OAGG;IACI,MAAM,CAAC,KAAK,CAAC,KAAK,CACvB,QAAyC,EACzC,MAAmC;QAEnC,IAAI,CAAC;YACH,MAAM,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAClC,CAAC;QAAC,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E,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC9I,CAAC;IACH,CAAC;CACF","sourcesContent":["import { mkdir, rename, unlink, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { describeCaughtError, type LoggerService } from '@wildo-ai/saas-backend-lib';\nimport { encodeMinionLivenessHeartbeat, type MinionLivenessHeartbeatSettings } from '@wildo-ai/platform-config-lib';\n\n/**\n * The producer half of a minion's file liveness contract (#1859).\n *\n * The probe half — the `exec` command the k8s `livenessProbe`/`startupProbe` and the compose `healthcheck`\n * run, and their cadence — is rendered from the same parsed `wildo.minion.config.ts > liveness` by\n * `minion-liveness.contracts.ts` in `@wildo-ai/platform-config-lib`, which also renders the env this\n * writer is configured from. Read that module's header for how `heartbeat.intervalSec`, `staleAfterSec`,\n * `periodSeconds` and `failureThreshold` relate.\n *\n * ## What a heartbeat asserts\n *\n * Not that the process exists: a process whose broker connection has closed is alive and useless, because\n * the RabbitMQ adapter does not reconnect and the minion will never receive another tick. So every beat asks\n * `isWorkLoopAlive()` first — wired by minion startup to \"the tick consumer is subscribed and the broker\n * connection is up\" — and writes nothing when the answer is no. The file then goes stale, the probe fails,\n * and the kubelet restarts the minion into a fresh connection, which is the only recovery there is.\n *\n * A long-running tick does not stop the beats. Ticks run detached from receipt and the beat is a timer, so\n * the heartbeat stays fresh for as long as the handler awaits I/O; only a handler that blocks the event loop\n * for longer than the stale window is restarted.\n *\n * ## The write is atomic\n *\n * Each beat writes a sibling temporary file and renames it over the heartbeat, so the probe never reads a\n * half-written number. A torn read would fail the probe's numeric check, and a few of those in a row would\n * restart a healthy minion.\n */\nexport class MinionLivenessHeartbeat {\n private timer: ReturnType<typeof setInterval> | undefined;\n private inFlight: Promise<void> | undefined;\n /** Logged on the transition only, so a stopped loop does not write one warning per interval. */\n private reportedNotAlive = false;\n\n constructor(\n private readonly settings: MinionLivenessHeartbeatSettings,\n private readonly isWorkLoopAlive: () => boolean,\n private readonly logger: Pick<LoggerService, 'info' | 'warn' | 'error'>,\n private readonly now: () => number = Date.now,\n ) {}\n\n /**\n * Remove a heartbeat left by an earlier process, so nothing can read as alive before this one has beaten.\n * Missing is the normal case.\n */\n public static async clear(\n settings: MinionLivenessHeartbeatSettings,\n logger: Pick<LoggerService, 'warn'>,\n ): Promise<void> {\n try {\n await unlink(settings.filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n logger.warn('Could not remove the minion liveness heartbeat', { filePath: settings.filePath, error: describeCaughtError(error) });\n }\n }\n }\n\n /** Writes the first beat now, then one every `intervalSec`. Idempotent. */\n public async start(): Promise<void> {\n if (this.timer) return;\n this.timer = setInterval(() => {\n void this.beat();\n }, this.settings.intervalSec * 1000);\n // The heartbeat must never be what keeps a process up: a minion with nothing else holding its event loop\n // open has stopped working, and exiting is the honest outcome.\n this.timer.unref();\n await this.beat();\n this.logger.info('Minion liveness heartbeat started', {\n filePath: this.settings.filePath,\n intervalSec: this.settings.intervalSec,\n });\n }\n\n /**\n * Stops beating and removes the heartbeat, so a stopping minion reads as not alive at once rather than\n * one stale window later.\n */\n public async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.inFlight;\n await MinionLivenessHeartbeat.clear(this.settings, this.logger);\n }\n\n public isRunning(): boolean {\n return this.timer !== undefined;\n }\n\n /** One beat. Exposed for tests; the timer calls it. Never overlaps itself. */\n public async beat(): Promise<void> {\n if (this.inFlight) return this.inFlight;\n this.inFlight = this.writeIfAlive().finally(() => {\n this.inFlight = undefined;\n });\n return this.inFlight;\n }\n\n private async writeIfAlive(): Promise<void> {\n if (!this.isWorkLoopAlive()) {\n if (!this.reportedNotAlive) {\n this.reportedNotAlive = true;\n this.logger.warn('Minion work loop is not receiving ticks; the liveness heartbeat is withheld so the probe fails', {\n filePath: this.settings.filePath,\n });\n }\n return;\n }\n this.reportedNotAlive = false;\n const temporaryPath = `${this.settings.filePath}.${process.pid}.tmp`;\n try {\n // The schema keeps the file inside a writable mount; a sub-directory of one may not exist yet.\n await mkdir(dirname(this.settings.filePath), { recursive: true });\n await writeFile(temporaryPath, encodeMinionLivenessHeartbeat(this.now()), 'utf8');\n await rename(temporaryPath, this.settings.filePath);\n } catch (error) {\n // Nothing to retry here: an unwritable heartbeat (a read-only rootfs without its `/tmp` mount) fails the\n // probe, and the restart that follows is the correct outcome for a minion that cannot prove it is alive.\n this.logger.error('Could not write the minion liveness heartbeat', { filePath: this.settings.filePath, error: describeCaughtError(error) });\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"own-schedule-reader.backend.service.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"own-schedule-reader.backend.service.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/own-schedule-reader.backend.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,kBAAkB,CAAC;AAK1B,OAAO,EACL,uBAAuB,EAEvB,yCAAyC,EAEzC,KAAK,0BAA0B,EAC/B,KAAK,aAAa,EACnB,MAAM,4BAA4B,CAAC;AAEpC;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE;QACH,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,OAAO,CAAA;SAAE,CAAC;QAClE,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;KAC1B,CAAC;IACF,gBAAgB,EAAE,KAAK,CAAC;QACtB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;KAC1B,CAAC,CAAC;CACJ;AAcD,qBACa,+BAA+B;IAIL,OAAO,CAAC,QAAQ,CAAC,MAAM;IACV,OAAO,CAAC,QAAQ,CAAC,YAAY;IAChC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAE9E,OAAO,CAAC,QAAQ,CAAC,YAAY;IAP/B,OAAO,CAAC,OAAO,CAAuB;gBAGgB,MAAM,EAAE,aAAa,EACR,YAAY,EAAE,0BAA0B,EAC3C,gBAAgB,EAAE,uBAAuB,EAEtF,YAAY,EAAE,yCAAyC;IAG1E;;;;;;OAMG;IACU,IAAI,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAqChD,OAAO,CAAC,cAAc;CAqBvB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"own-schedule-reader.backend.service.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"own-schedule-reader.backend.service.js","sourceRoot":"","sources":["../../../../src/runtime/services/own-schedule-reader.backend.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;;;;;;;;;;;;;AAEH,OAAO,kBAAkB,CAAC;AAE1B,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAChG,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,yCAAyC,EACzC,kBAAkB,GAGnB,MAAM,4BAA4B,CAAC;AA0BpC,MAAM,iBAAiB,GAAG,gCAAgC,CAAC;AAE3D;;;;;;;GAOG;AACH,MAAM,+BAA+B,GAAG,MAAM,CAAC;AAGxC,IAAM,+BAA+B,GAArC,MAAM,+BAA+B;IAIY;IACa;IACH;IAE7C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,CAAC;QAC7E,OAAO,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC;IAC1B,CAAC;IAEO,cAAc;QACpB,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,CAAC,OAAO,CAAC;QAEtC,MAAM,OAAO,GACX,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,uBAAuB,CAAC,iCAAiC,CAAC;YACvG,EAAE,WAAW,CAAC;QAElB,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,yEAAyE;YACzE,wEAAwE;YACxE,wEAAwE;YACxE,MAAM,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,SAAS,CAAC,aAAa,EAAE,SAAS,EAAE;gBACrE,sBAAsB,EAAE,2BAA2B,CAAC,aAAa;gBACjE,OAAO,EAAE,EAAE,OAAO,EAAE,kEAAkE,EAAE;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,oDAAoD,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;QACrG,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF,CAAA;AA5EY,+BAA+B;IAD3C,UAAU,EAAE;IAKR,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;IACjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAA;IAC9C,WAAA,MAAM,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAA;IAC3C,WAAA,MAAM,CAAC,kBAAkB,CAAC,kCAAkC,CAAC,CAAA;yDADkB,uBAAuB;QAExE,yCAAyC;GAR/D,+BAA+B,CA4E3C","sourcesContent":["/**\n * A minion reading its OWN cron records from the platform (R4).\n *\n * ## The client is as selector-free as the route\n *\n * `read()` takes no arguments. Not a minion name, not an application id, not a\n * job id — there is nothing to pass, so there is nothing an author could pass\n * wrongly and nothing a later caller could parameterise. The route it calls\n * derives its subject from the attestation, and this client's shape mirrors that\n * rather than merely respecting it.\n *\n * That symmetry is deliberate. A client with a `minionName` argument that always\n * happens to be filled with the caller's own name is one refactor away from being\n * filled with something else, and the server would still be correct while every\n * reader of this file had been taught the wrong mental model.\n *\n * ## Authority, and where it is decided\n *\n * Nothing here checks `platformAccess`. Two other places do, and both are better\n * placed: apps-manager refuses to mint an attestation for a minion whose\n * application declared no scope, and crontabs re-checks the scope before it\n * queries. A third check here would be a client-side guess about a server-side\n * decision — it would drift, and the day it drifted it would either refuse work\n * the platform allows or promise work the platform refuses.\n *\n * So a minion without the scope gets a refusal from the platform, which is the\n * party that knows.\n */\n\nimport 'reflect-metadata';\n\nimport { inject, injectable } from 'inversify';\n\nimport { ErrorCustomMessageReference, ErrorType, WildoHeaderKeys } from '@wildo-ai/saas-models';\nimport {\n AppConfigurationService,\n PlatformApplicationType,\n RuntimePrincipalAttestationBackendService,\n SAAS_SERVICE_TYPES,\n type ErrorBuilderBackendService,\n type LoggerService,\n} from '@wildo-ai/saas-backend-lib';\n\n/**\n * One cron job that ticks this minion, with its recent runs.\n *\n * Typed structurally rather than importing the platform's `CronJob` — a minion\n * runtime has no dependency on `platform-shared-lib` and giving it one to name a\n * response body would be a package boundary crossed for a type alias.\n */\nexport interface OwnScheduleEntry {\n job: {\n jobId: string;\n name?: string;\n schedule?: { cron: string; timezone?: string; enabled?: boolean };\n status?: string;\n [field: string]: unknown;\n };\n recentExecutions: Array<{\n status?: string;\n startTime?: string;\n endTime?: string;\n error?: string;\n [field: string]: unknown;\n }>;\n}\n\nconst OWN_SCHEDULE_PATH = '/api/v1/runtime-self/cron-jobs';\n\n/**\n * Hard deadline for the own-schedule read.\n *\n * The crontabs manager is ours rather than a vendor's, which changes who is at fault and not what\n * happens: a peer that accepts the connection and never answers holds this call open indefinitely,\n * and Node's `fetch` supplies no bound of its own. 10s, because the response is a small JSON list\n * of this minion's jobs — nothing legitimate here spends time moving bytes.\n */\nconst OWN_SCHEDULE_REQUEST_TIMEOUT_MS = 10_000;\n\n@injectable()\nexport class OwnScheduleReaderBackendService {\n private baseUrl: string | null = null;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_SERVICE_TYPES.RuntimePrincipalAttestationService)\n private readonly attestations: RuntimePrincipalAttestationBackendService,\n ) {}\n\n /**\n * This minion's cron job definitions and their recent runs.\n *\n * The attestation is fetched per call rather than held: the exchange caches it,\n * so this costs nothing, and a client that cached it itself would eventually\n * present an expired one.\n */\n public async read(): Promise<OwnScheduleEntry[]> {\n const baseUrl = this.resolveBaseUrl();\n const attestation = await this.attestations.getAttestation(\n PlatformApplicationType.PLATFORM_CRONTABS_BATCHES_MANAGER,\n );\n\n const response = await fetch(`${baseUrl}${OWN_SCHEDULE_PATH}`, {\n method: 'GET',\n headers: {\n [WildoHeaderKeys.CONTENT_TYPE]: 'application/json',\n // Deliberately the ONLY credential. A minion is not a platform service,\n // so no `X-Service-Id`; and an application JWT would carry an identity\n // meaning \"some runtime of this app\" — attaching one as well would only\n // invite the server to read the weaker of the two.\n [WildoHeaderKeys.RUNTIME_PRINCIPAL_TOKEN]: attestation,\n },\n signal: AbortSignal.timeout(OWN_SCHEDULE_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n // Surfaced rather than swallowed into an empty schedule. A refusal and \"you\n // have no jobs\" are different answers, and returning `[]` for both would\n // make a missing `platformAccess` declaration look like a correctly-empty\n // schedule — the one failure an author cannot debug from the result.\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATION,\n context: {\n message: 'The platform refused this runtime\\'s own-schedule read',\n status: response.status,\n },\n });\n }\n\n const body = (await response.json()) as { jobs?: OwnScheduleEntry[] } | null;\n return body?.jobs ?? [];\n }\n\n private resolveBaseUrl(): string {\n if (this.baseUrl) return this.baseUrl;\n\n const baseUrl =\n this.appConfigService.config.runtime.endPoints[PlatformApplicationType.PLATFORM_CRONTABS_BATCHES_MANAGER]\n ?.internalUrl;\n\n if (!baseUrl) {\n // A CONFIGURATION failure, not an authorization one. Blurring them would\n // send an operator to inspect the minion's `platformAccess` declaration\n // over what is really a missing endpoint in this deployment's topology.\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: 'The crontabs-manager endpoint is not configured for this runtime' },\n });\n }\n\n this.baseUrl = baseUrl.replace(/\\/+$/, '');\n this.logger.debug?.('Own-schedule reader bound to the crontabs endpoint', { baseUrl: this.baseUrl });\n return this.baseUrl;\n }\n}\n"]}
|
|
@@ -11,11 +11,25 @@ export declare class StartMinionApplicationBackendService {
|
|
|
11
11
|
private readonly systemAccess;
|
|
12
12
|
private readonly ownScheduleReader;
|
|
13
13
|
private tickConsumerStarted;
|
|
14
|
+
private livenessHeartbeat;
|
|
14
15
|
constructor(startApplicationService: StartApplicationBackendService, appConfigService: AppConfigurationService, tickConsumer: MinionTickConsumerBackendService, logger: LoggerService, runtimePrincipal: RuntimePrincipalBackendService, systemAccess: SystemAccessBackendService, ownScheduleReader: OwnScheduleReaderBackendService);
|
|
15
16
|
initialize(config: MinionInitializationConfig): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* For a host that shuts the minion down itself. A container's SIGTERM does not come through here: it reaches
|
|
19
|
+
* `WorkerShutdownManager`, whose stop handler stops the tick consumer, and the heartbeat then stops beating on
|
|
20
|
+
* its own because `isReceiving()` turns false. The leftover file is cleared by the next container's
|
|
21
|
+
* `initialize()`.
|
|
22
|
+
*/
|
|
16
23
|
shutdown(): Promise<void>;
|
|
17
24
|
isApplicationInitialized(): boolean;
|
|
18
25
|
private startTickConsumer;
|
|
26
|
+
/**
|
|
27
|
+
* The producer half of the file liveness probe (#1859). Started only AFTER the tick consumer subscribed, so
|
|
28
|
+
* the first heartbeat means "able to receive work", which is what the `startupProbe` waits for. The settings
|
|
29
|
+
* come from the env the container renderers stamp from `wildo.minion.config.ts > liveness`, the same parsed
|
|
30
|
+
* value the probe itself is rendered from; a host process gets no such env and writes nothing.
|
|
31
|
+
*/
|
|
32
|
+
private startLivenessHeartbeat;
|
|
19
33
|
private getMinionRuntimeConfig;
|
|
20
34
|
/**
|
|
21
35
|
* Bridge the per-minion materialized provider runtime artifact into the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-minion-application.backend.service.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"start-minion-application.backend.service.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,uBAAuB,EAI5B,KAAK,aAAa,EAElB,KAAK,8BAA8B,EACnC,KAAK,0BAA0B,EAE/B,KAAK,8BAA8B,EAAuB,MAAM,4BAA4B,CAAC;AAM/F,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAC7F,OAAO,EACL,gCAAgC,EAEjC,MAAM,+CAA+C,CAAC;AACvD,OAAO,KAAK,EACV,0BAA0B,EAK3B,MAAM,sBAAsB,CAAC;AAQ9B,qBACa,oCAAoC;IAM7C,OAAO,CAAC,QAAQ,CAAC,uBAAuB;IAExC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IAEvB,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAjBpC,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,iBAAiB,CAAsC;gBAI5C,uBAAuB,EAAE,8BAA8B,EAEvD,gBAAgB,EAAE,uBAAuB,EAEzC,YAAY,EAAE,gCAAgC,EAE9C,MAAM,EAAE,aAAa,EAErB,gBAAgB,EAAE,8BAA8B,EAEhD,YAAY,EAAE,0BAA0B,EAExC,iBAAiB,EAAE,+BAA+B;IAGxD,UAAU,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO,CAAC,IAAI,CAAC;IA8I1E;;;;;OAKG;IACU,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAyB/B,wBAAwB,IAAI,OAAO;YAI5B,iBAAiB;IA8C/B;;;;;OAKG;YACW,sBAAsB;IAepC,OAAO,CAAC,sBAAsB;IAkC9B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,OAAO,CAAC,wBAAwB;IAoBhC,OAAO,CAAC,gCAAgC;CAkFzC"}
|
|
@@ -11,8 +11,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
import { ApplicationRuntimeProfile, inject, injectable, SAAS_SERVICE_TYPES, describeCaughtError } from '@wildo-ai/saas-backend-lib';
|
|
14
|
-
import { ErrorCustomMessageReference, ErrorType } from '@wildo-ai/saas-models';
|
|
15
|
-
import { assertProviderRuntimeEnvInSync } from '@wildo-ai/platform-config-lib';
|
|
14
|
+
import { ErrorCustomMessageReference, ErrorType, narrowRuntimeProviderDataResidency } from '@wildo-ai/saas-models';
|
|
15
|
+
import { assertProviderRuntimeEnvInSync, readMinionLivenessHeartbeatEnv } from '@wildo-ai/platform-config-lib';
|
|
16
|
+
import { MinionLivenessHeartbeat } from './minion-liveness-heartbeat.js';
|
|
16
17
|
import { MinionScopedServicesRegistryHandlerBackendService } from '../../base-classes/services/services/minion-scoped-services-registry-handler.backend.service.js';
|
|
17
18
|
import { SAAS_MINIONS_SERVICE_TYPES } from '../../inject/models/service-types.js';
|
|
18
19
|
import { MinionTickConsumerBackendService, } from '../queue/minion-tick-consumer.backend.service.js';
|
|
@@ -25,6 +26,7 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
25
26
|
systemAccess;
|
|
26
27
|
ownScheduleReader;
|
|
27
28
|
tickConsumerStarted = false;
|
|
29
|
+
livenessHeartbeat;
|
|
28
30
|
constructor(startApplicationService, appConfigService, tickConsumer, logger, runtimePrincipal, systemAccess, ownScheduleReader) {
|
|
29
31
|
this.startApplicationService = startApplicationService;
|
|
30
32
|
this.appConfigService = appConfigService;
|
|
@@ -35,6 +37,14 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
35
37
|
this.ownScheduleReader = ownScheduleReader;
|
|
36
38
|
}
|
|
37
39
|
async initialize(config) {
|
|
40
|
+
// Read (and so validate) the heartbeat settings before anything connects, and clear any heartbeat a PREVIOUS
|
|
41
|
+
// container left behind. In k8s `/tmp` is an `emptyDir`, which outlives a container restart inside the pod: a
|
|
42
|
+
// minion that crashed without removing its file would hand the next container a fresh-looking heartbeat, the
|
|
43
|
+
// startupProbe would pass at once, and the livenessProbe would then kill a slow boot. Cleared here, the
|
|
44
|
+
// startupProbe waits for THIS process's first beat (#1859).
|
|
45
|
+
const livenessHeartbeatSettings = readMinionLivenessHeartbeatEnv(process.env);
|
|
46
|
+
if (livenessHeartbeatSettings)
|
|
47
|
+
await MinionLivenessHeartbeat.clear(livenessHeartbeatSettings, this.logger);
|
|
38
48
|
const { minionName, serviceIdentifier, onTick, tickRecovery, reconcileTick, ...startupConfig } = config;
|
|
39
49
|
// Declare WHO this process is before anything can perform a privileged access.
|
|
40
50
|
//
|
|
@@ -45,7 +55,7 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
45
55
|
//
|
|
46
56
|
// Attribution only: this grants nothing. A minion's operations are governed by its
|
|
47
57
|
// role and its `resourceAccess` whitelist; its cross-tenant reach comes from the
|
|
48
|
-
// system-access door.
|
|
58
|
+
// system-access door.
|
|
49
59
|
//
|
|
50
60
|
// assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged access by a non-human
|
|
51
61
|
// background runtime is attributable to that runtime.
|
|
@@ -129,8 +139,27 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
129
139
|
// operation but the subscription is harmless (no message ⇒ no
|
|
130
140
|
// dispatch) and keeps the runtime contract symmetric across modes.
|
|
131
141
|
await this.startTickConsumer(minionName, onTick, tickRecovery, reconcileTick);
|
|
142
|
+
await this.startLivenessHeartbeat(minionName, livenessHeartbeatSettings);
|
|
132
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* For a host that shuts the minion down itself. A container's SIGTERM does not come through here: it reaches
|
|
146
|
+
* `WorkerShutdownManager`, whose stop handler stops the tick consumer, and the heartbeat then stops beating on
|
|
147
|
+
* its own because `isReceiving()` turns false. The leftover file is cleared by the next container's
|
|
148
|
+
* `initialize()`.
|
|
149
|
+
*/
|
|
133
150
|
async shutdown() {
|
|
151
|
+
// First, so a stopping minion stops claiming to be alive before its consumer is torn down.
|
|
152
|
+
if (this.livenessHeartbeat) {
|
|
153
|
+
try {
|
|
154
|
+
await this.livenessHeartbeat.stop();
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
this.logger.warn('Failed to stop the minion liveness heartbeat cleanly', { error: describeCaughtError(error) });
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
this.livenessHeartbeat = undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
134
163
|
if (this.tickConsumerStarted) {
|
|
135
164
|
try {
|
|
136
165
|
await this.tickConsumer.stop();
|
|
@@ -171,12 +200,10 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
171
200
|
const handler = onTick
|
|
172
201
|
? async (token, scheduledAttempt) => onTick(token, { ...context, scheduledAttempt })
|
|
173
202
|
: undefined;
|
|
203
|
+
// Only this minion's own policy is read here. Whether a policy names an undeclared minion is the backend's diagnosis
|
|
204
|
+
// (`JobConsumerBackendService`): a minion is answered its OWN declaration only (#2954), so every sibling would read
|
|
205
|
+
// as undeclared from here.
|
|
174
206
|
const evidencePolicies = this.appConfigService.config?.scheduledEvidence?.minions;
|
|
175
|
-
for (const configuredName of Object.keys(evidencePolicies ?? {})) {
|
|
176
|
-
if (!Object.hasOwn(this.appConfigService.config.minions ?? {}, configuredName)) {
|
|
177
|
-
this.logger.warn('Scheduled evidence policy names an undeclared minion; no evidence will be collected for this key', { minionName: configuredName });
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
207
|
await this.tickConsumer.start({
|
|
181
208
|
applicationId: this.appConfigService.applicationId,
|
|
182
209
|
minionName,
|
|
@@ -189,6 +216,20 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
189
216
|
});
|
|
190
217
|
this.tickConsumerStarted = true;
|
|
191
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* The producer half of the file liveness probe (#1859). Started only AFTER the tick consumer subscribed, so
|
|
221
|
+
* the first heartbeat means "able to receive work", which is what the `startupProbe` waits for. The settings
|
|
222
|
+
* come from the env the container renderers stamp from `wildo.minion.config.ts > liveness`, the same parsed
|
|
223
|
+
* value the probe itself is rendered from; a host process gets no such env and writes nothing.
|
|
224
|
+
*/
|
|
225
|
+
async startLivenessHeartbeat(minionName, settings) {
|
|
226
|
+
if (!settings)
|
|
227
|
+
return;
|
|
228
|
+
const heartbeat = new MinionLivenessHeartbeat(settings, () => this.startApplicationService.isApplicationInitialized() && this.tickConsumer.isReceiving(), this.logger);
|
|
229
|
+
await heartbeat.start();
|
|
230
|
+
this.livenessHeartbeat = heartbeat;
|
|
231
|
+
this.logger.info('Minion liveness heartbeat wired to the tick consumer', { minionName });
|
|
232
|
+
}
|
|
192
233
|
getMinionRuntimeConfig(appConfig, minionName, errorBuilder) {
|
|
193
234
|
const minionConfig = appConfig.minions?.[minionName];
|
|
194
235
|
if (minionConfig) {
|
|
@@ -283,6 +324,9 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
283
324
|
// sibling's opt-in must not load a package into this process.
|
|
284
325
|
const projectedAugmentations = Object.entries(providerRuntime.providerRuntimeAugmentations ?? {})
|
|
285
326
|
.filter(([providerRef]) => projectedProviderRefs.includes(providerRef));
|
|
327
|
+
// Narrowed with the refs too (#3513): the region a sibling's provider is bound to is not this host's to apply.
|
|
328
|
+
const projectedProcessingRegions = Object.entries(providerRuntime.providerProcessingRegions ?? {})
|
|
329
|
+
.filter(([providerRef]) => projectedProviderRefs.includes(providerRef));
|
|
286
330
|
return {
|
|
287
331
|
__AUTOGENERATED__: providerRuntime.__AUTOGENERATED__,
|
|
288
332
|
generatedBy: providerRuntime.generatedBy,
|
|
@@ -291,6 +335,12 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
|
|
|
291
335
|
providerRefs: projectedProviderRefs,
|
|
292
336
|
providerRuntimeImports: projectedProviderRuntimeImports,
|
|
293
337
|
...(projectedAugmentations.length === 0 ? {} : { providerRuntimeAugmentations: Object.fromEntries(projectedAugmentations) }),
|
|
338
|
+
...(projectedProcessingRegions.length === 0 ? {} : { providerProcessingRegions: Object.fromEntries(projectedProcessingRegions) }),
|
|
339
|
+
// Narrowed with the refs too (#2294), and never dropped: a projection that lost it would load this host's providers
|
|
340
|
+
// without the residency the application declared, which is the one thing the loader's re-check exists to prevent.
|
|
341
|
+
...(providerRuntime.providerDataResidency === undefined
|
|
342
|
+
? {}
|
|
343
|
+
: { providerDataResidency: narrowRuntimeProviderDataResidency(providerRuntime.providerDataResidency, projectedProviderRefs) }),
|
|
294
344
|
providerGraphDigest: providerRuntime.providerGraphDigest,
|
|
295
345
|
lockfileSectionDigest: providerRuntime.lockfileSectionDigest,
|
|
296
346
|
artifactKind: 'backend',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-minion-application.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAGL,yBAAyB,EACzB,MAAM,EACN,UAAU,EAKV,kBAAkB,EACmB,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAgC,MAAM,uBAAuB,CAAC;AAC7G,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,iDAAiD,EAAE,MAAM,8FAA8F,CAAC;AACjK,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAE/E,OAAO,EACL,gCAAgC,GAEjC,MAAM,+CAA+C,CAAC;AAgBhD,IAAM,oCAAoC,GAA1C,MAAM,oCAAoC;IAK5B;IAEA;IAEA;IAEA;IAEA;IAEA;IAEA;IAhBX,mBAAmB,GAAG,KAAK,CAAC;IAEpC,YAEmB,uBAAuD,EAEvD,gBAAyC,EAEzC,YAA8C,EAE9C,MAAqB,EAErB,gBAAgD,EAEhD,YAAwC,EAExC,iBAAkD;QAZlD,4BAAuB,GAAvB,uBAAuB,CAAgC;QAEvD,qBAAgB,GAAhB,gBAAgB,CAAyB;QAEzC,iBAAY,GAAZ,YAAY,CAAkC;QAE9C,WAAM,GAAN,MAAM,CAAe;QAErB,qBAAgB,GAAhB,gBAAgB,CAAgC;QAEhD,iBAAY,GAAZ,YAAY,CAA4B;QAExC,sBAAiB,GAAjB,iBAAiB,CAAiC;IAClE,CAAC;IAEG,KAAK,CAAC,UAAU,CAAC,MAAkC;QACxD,MAAM,EACJ,UAAU,EACV,iBAAiB,EACjB,MAAM,EACN,YAAY,EACZ,aAAa,EACb,GAAG,aAAa,EACjB,GAAG,MAAM,CAAC;QACX,+EAA+E;QAC/E,EAAE;QACF,gFAAgF;QAChF,iFAAiF;QACjF,kFAAkF;QAClF,sDAAsD;QACtD,EAAE;QACF,mFAAmF;QACnF,iFAA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,CAAC,WAAW,CAAC,CAAC,CAAC;QAE1E,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,GAAG,CAAC,sBAAsB,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,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;AApXY,oCAAoC;IADhD,UAAU,EAAE;IAKR,WAAA,MAAM,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,CAAA;IAElD,WAAA,MAAM,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAA;IAE3C,WAAA,MAAM,CAAC,0BAA0B,CAAC,yBAAyB,CAAC,CAAA;IAE5D,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;IAEjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,CAAA;IAElD,WAAA,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAA;IAE9C,WAAA,MAAM,CAAC,0BAA0B,CAAC,wBAAwB,CAAC,CAAA;yDAP7B,gCAAgC;GATtD,oCAAoC,CAoXhD","sourcesContent":["import {\n type AppConfiguration,\n type AppConfigurationService,\n ApplicationRuntimeProfile,\n inject,\n injectable,\n type LoggerService,\n type ProviderRuntimeArtifact,\n type RuntimePrincipalBackendService,\n type SystemAccessBackendService,\n SAAS_SERVICE_TYPES,\n type StartApplicationBackendService, describeCaughtError } from '@wildo-ai/saas-backend-lib';\nimport { ErrorCustomMessageReference, ErrorType, type ScheduledRecoveryPolicy } from '@wildo-ai/saas-models';\nimport { assertProviderRuntimeEnvInSync } from '@wildo-ai/platform-config-lib';\nimport { MinionScopedServicesRegistryHandlerBackendService } from '../../base-classes/services/services/minion-scoped-services-registry-handler.backend.service';\nimport { SAAS_MINIONS_SERVICE_TYPES } from '../../inject/models/service-types';\nimport type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';\nimport {\n MinionTickConsumerBackendService,\n type MinionTickHandler,\n} from '../queue/minion-tick-consumer.backend.service';\nimport type {\n MinionInitializationConfig,\n MinionProviderRuntimeArtifact,\n MinionTickAuthorHandler,\n MinionTickContext,\n MinionTickReconciliationHandler,\n} from './define-minion-init';\n\ntype MinionAwareAppConfiguration = AppConfiguration & {\n minions?: Record<string, MinionRuntimeConfig>;\n};\n\ntype MinionRuntimeConfig = NonNullable<NonNullable<AppConfiguration['minions']>[string]>;\n\n@injectable()\nexport class StartMinionApplicationBackendService {\n private tickConsumerStarted = false;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.StartApplicationService)\n private readonly startApplicationService: StartApplicationBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService)\n private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)\n private readonly tickConsumer: MinionTickConsumerBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.RuntimePrincipalService)\n private readonly runtimePrincipal: RuntimePrincipalBackendService,\n @inject(SAAS_SERVICE_TYPES.SystemAccessService)\n private readonly systemAccess: SystemAccessBackendService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)\n private readonly ownScheduleReader: OwnScheduleReaderBackendService,\n ) {}\n\n public async initialize(config: MinionInitializationConfig): Promise<void> {\n const {\n minionName,\n serviceIdentifier,\n onTick,\n tickRecovery,\n reconcileTick,\n ...startupConfig\n } = config;\n // Declare WHO this process is before anything can perform a privileged access.\n //\n // Established here, in framework-owned minion startup, rather than left to each\n // minion author — attribution that an author can forget is attribution that will\n // be missing exactly when an auditor needs it. Every minion therefore carries its\n // identity structurally, by virtue of being a minion.\n //\n // Attribution only: this grants nothing. A minion's operations are governed by its\n // role and its `resourceAccess` whitelist; its cross-tenant reach comes from the\n // system-access door. See `.claude/plans/minion-runtime-scope.md` (D9).\n //\n // assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged access by a non-human\n // background runtime is attributable to that runtime.\n this.runtimePrincipal.initialize({\n runtimeProfile: ApplicationRuntimeProfile.MINION,\n runtimeKey: minionName,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n });\n\n const normalizedProviderRuntime = this.normalizeProviderRuntime(\n startupConfig.providerRuntime,\n minionName,\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 (operator regenerated one surface but not the\n // other) BEFORE the registry filter would silently boot with\n // mismatched topology.\n //\n // Skipped when:\n // - the artifact is absent (host authored zero providers AND no\n // scope block in `wildo.saas.config.ts`); or\n // - the artifact has zero `providerRefs` (host 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 = normalizedProviderRuntime?.providerRefs ?? [];\n if (normalizedProviderRuntime && projectedProviderRefs.length > 0) {\n assertProviderRuntimeEnvInSync({\n artifactProviderRefs: projectedProviderRefs,\n artifactSourceDigest: normalizedProviderRuntime.sourceDigest,\n hostKind: 'minion',\n hostKey: minionName,\n });\n }\n\n await this.startApplicationService.initialize({\n ...startupConfig,\n providerRuntime: normalizedProviderRuntime,\n headlessMode: true,\n skipCronSync: true,\n // A minion reuses the full backend startup lifecycle but is NOT a job\n // worker for the shared application queues — it consumes ONLY its own\n // `minion-tick.<name>` queue (subscribed below via `startTickConsumer`).\n // Skipping the shared job consumers keeps RabbitMQ from round-robining\n // scheduled-cron ticks onto this process (which would dead-letter every\n // tick it can't interpret). The broker connection itself is still made,\n // because the tick consumer depends on it.\n skipJobConsumers: true,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n afterResourcesRegistryInitialized: async ({\n appConfig,\n resourcesRegistryService,\n errorBuilder,\n }) => {\n const minionConfig = this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n );\n const resourceAccess = minionConfig.resourceAccess;\n const knownResourceTypes = new Set(resourcesRegistryService.getResourceTypes());\n const unknownResourceTypes = [\n ...(resourceAccess?.read ?? []),\n ...(resourceAccess?.write ?? []),\n ].filter((resourceType, index, all) => (\n resourceType !== '*'\n && !knownResourceTypes.has(resourceType)\n && all.indexOf(resourceType) === index\n ));\n\n if (unknownResourceTypes.length > 0) {\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' references unknown resources in resourceAccess: `\n + `[${unknownResourceTypes.join(', ')}].`,\n minionName,\n unknownResourceTypes,\n },\n });\n }\n },\n servicesRegistryDecoratorFactory: (registry, { appConfig, errorBuilder }) => (\n new MinionScopedServicesRegistryHandlerBackendService(\n registry as any,\n minionName,\n this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n ).resourceAccess,\n ).asDecoratedRegistry()\n ),\n });\n\n // KD-12 auto-wiring: every minion subscribes to its dedicated tick\n // queue (`wildo.queue.<appId>.minion-tick.<minionName>`). Cron-mode\n // minions receive ticks from `platform-crontabs-batches-manager`;\n // always-up minions receive nothing on this queue under normal\n // operation but the subscription is harmless (no message ⇒ no\n // dispatch) and keeps the runtime contract symmetric across modes.\n await this.startTickConsumer(minionName, onTick, tickRecovery, reconcileTick);\n }\n\n public async shutdown(): Promise<void> {\n if (this.tickConsumerStarted) {\n try {\n await this.tickConsumer.stop();\n } catch (error) {\n this.logger.warn('Failed to stop minion tick consumer cleanly', {\n error: describeCaughtError(error),\n });\n } finally {\n this.tickConsumerStarted = false;\n }\n }\n await this.startApplicationService.shutdown();\n }\n\n public isApplicationInitialized(): boolean {\n return this.startApplicationService.isApplicationInitialized();\n }\n\n private async startTickConsumer(\n minionName: string,\n onTick: MinionTickAuthorHandler | undefined,\n tickRecovery: Partial<ScheduledRecoveryPolicy> | undefined,\n reconcileTick: MinionTickReconciliationHandler | undefined,\n ): Promise<void> {\n // The surface the handler is ALLOWED to work with, assembled once at the tick\n // boundary. Handed to the author rather than left for them to resolve from the\n // container: `systemAccess` here is already contained by this minion's\n // `resourceAccess` ACL, because startup rebinds the services registry to the\n // scoped decorator before any tick can be delivered. An author who resolved the\n // door themselves could bypass that; an author handed this one cannot.\n const context: Omit<MinionTickContext, 'scheduledAttempt'> = {\n systemAccess: this.systemAccess,\n minionName,\n // Same reasoning as `systemAccess`: handed to the author rather than left\n // to be resolved from the container. A reader an author constructs is a\n // reader an author could construct with a different identity; this one is\n // bound to the process's own attested principal and cannot be pointed\n // elsewhere.\n ownSchedule: this.ownScheduleReader,\n };\n\n // Missing handlers stay absent: the durable coordinator records REVIEW instead of\n // treating an unimplemented tick as successful work.\n const handler: MinionTickHandler | undefined = onTick\n ? async (token, scheduledAttempt) => onTick(token, { ...context, scheduledAttempt })\n : undefined;\n\n const evidencePolicies = this.appConfigService.config?.scheduledEvidence?.minions;\n for (const configuredName of Object.keys(evidencePolicies ?? {})) {\n if (!Object.hasOwn(this.appConfigService.config.minions ?? {}, configuredName)) {\n this.logger.warn('Scheduled evidence policy names an undeclared minion; no evidence will be collected for this key', { minionName: configuredName });\n }\n }\n await this.tickConsumer.start({\n applicationId: this.appConfigService.applicationId,\n minionName,\n handler,\n recoveryPolicy: tickRecovery,\n evidencePolicy: evidencePolicies && Object.hasOwn(evidencePolicies, minionName) ? evidencePolicies[minionName] : undefined,\n reconcile: reconcileTick\n ? async (token, scheduledAttempt) => reconcileTick(token, { ...context, scheduledAttempt })\n : undefined,\n });\n this.tickConsumerStarted = true;\n }\n\n private getMinionRuntimeConfig(\n appConfig: MinionAwareAppConfiguration,\n minionName: string,\n errorBuilder?: {\n buildError: (\n errorType: ErrorType,\n executionContext: undefined,\n options: {\n customMessageReference?: ErrorCustomMessageReference;\n context?: Record<string, unknown>;\n },\n ) => unknown;\n },\n ): MinionRuntimeConfig {\n const minionConfig = appConfig.minions?.[minionName];\n if (minionConfig) {\n return minionConfig;\n }\n\n if (!errorBuilder) {\n throw new Error(`Minion '${minionName}' is missing from appConfig.minions.`);\n }\n\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' is not declared in the managed runtime config. `\n + 'Re-sync the application bootstrap material before starting the minion.',\n minionName,\n },\n });\n }\n\n /**\n * Bridge the per-minion materialized provider runtime artifact into the\n * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`\n * (and ultimately filtered by `BackendProviderRegistryBackendService`).\n *\n * Three accepted input shapes:\n *\n * 1. `{ artifactKind: 'backend', scope: ... }` — already projected to a\n * backend-shaped single-scope artifact (e.g. produced by an\n * embedding host that pre-selected the scope).\n * 2. `{ artifactKind: 'minions', scope: ..., scopes: undefined }` —\n * what `wildo config sync` writes to each minion's\n * `src/generated/wildo-provider-runtime.generated.ts`. The CLI calls\n * `selectScopedProviderRuntimeArtifact(artifacts.minions, minionKey)`\n * so the file already carries only this minion's scope. We unwrap\n * it here to the canonical backend-shaped artifact.\n * 3. `{ artifactKind: 'minions', scopes: { [name]: ... } }` —\n * multi-scope minion artifact (legacy / non-CLI-driven hosts that\n * pass the unscoped artifact). We resolve `scopes[minionName]`.\n *\n * Anything else fails fast with a clear locator. Each minion process\n * must only see its own scope — there is no fallback to other scopes,\n * no merging across minions, and no silent recovery from a missing\n * scope.\n */\n private normalizeProviderRuntime(\n providerRuntime: MinionInitializationConfig['providerRuntime'],\n minionName: 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 !== 'minions') {\n throw new Error(\n `Unsupported provider runtime artifactKind '${artifactKind}' for minion '${minionName}'.`,\n );\n }\n\n return this.selectMinionProviderRuntimeScope(providerRuntime, minionName);\n }\n\n private selectMinionProviderRuntimeScope(\n providerRuntime: MinionProviderRuntimeArtifact,\n minionName: string,\n ): ProviderRuntimeArtifact {\n const preScopedScope = (providerRuntime as MinionProviderRuntimeArtifact & {\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 // Shape 2 — the CLI-emitted per-minion module.\n scope = preScopedScope;\n } else if (scopes) {\n // Shape 3 — unscoped multi-scope artifact.\n scope = scopes[minionName];\n if (!scope) {\n throw new Error(\n `Provider runtime artifact does not contain a scope for minion '${minionName}'. `\n + `Re-run \\`wildo config sync\\` and verify the minion is declared in `\n + `wildo.saas.config.ts \\`providers.scopes.minions\\`.`,\n );\n }\n }\n\n if (!scope) {\n throw new Error(\n `Provider runtime artifact for minion '${minionName}' 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-minion-application.backend.service.js","sourceRoot":"","sources":["../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAGL,yBAAyB,EACzB,MAAM,EACN,UAAU,EAKV,kBAAkB,EACmB,mBAAmB,EAAE,MAAM,4BAA4B,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CAAC,wBAAwB,CAAC,CAAA;yDAP7B,gCAAgC;GAVtD,oCAAoC,CA0ahD","sourcesContent":["import {\n type AppConfiguration,\n type AppConfigurationService,\n ApplicationRuntimeProfile,\n inject,\n injectable,\n type LoggerService,\n type ProviderRuntimeArtifact,\n type RuntimePrincipalBackendService,\n type SystemAccessBackendService,\n SAAS_SERVICE_TYPES,\n type StartApplicationBackendService, describeCaughtError } from '@wildo-ai/saas-backend-lib';\nimport { ErrorCustomMessageReference, ErrorType, narrowRuntimeProviderDataResidency, type ScheduledRecoveryPolicy } from '@wildo-ai/saas-models';\nimport { assertProviderRuntimeEnvInSync, readMinionLivenessHeartbeatEnv } from '@wildo-ai/platform-config-lib';\nimport { MinionLivenessHeartbeat } from './minion-liveness-heartbeat';\nimport { MinionScopedServicesRegistryHandlerBackendService } from '../../base-classes/services/services/minion-scoped-services-registry-handler.backend.service';\nimport { SAAS_MINIONS_SERVICE_TYPES } from '../../inject/models/service-types';\nimport type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';\nimport {\n MinionTickConsumerBackendService,\n type MinionTickHandler,\n} from '../queue/minion-tick-consumer.backend.service';\nimport type {\n MinionInitializationConfig,\n MinionProviderRuntimeArtifact,\n MinionTickAuthorHandler,\n MinionTickContext,\n MinionTickReconciliationHandler,\n} from './define-minion-init';\n\ntype MinionAwareAppConfiguration = AppConfiguration & {\n minions?: Record<string, MinionRuntimeConfig>;\n};\n\ntype MinionRuntimeConfig = NonNullable<NonNullable<AppConfiguration['minions']>[string]>;\n\n@injectable()\nexport class StartMinionApplicationBackendService {\n private tickConsumerStarted = false;\n private livenessHeartbeat: MinionLivenessHeartbeat | undefined;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.StartApplicationService)\n private readonly startApplicationService: StartApplicationBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService)\n private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)\n private readonly tickConsumer: MinionTickConsumerBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.RuntimePrincipalService)\n private readonly runtimePrincipal: RuntimePrincipalBackendService,\n @inject(SAAS_SERVICE_TYPES.SystemAccessService)\n private readonly systemAccess: SystemAccessBackendService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)\n private readonly ownScheduleReader: OwnScheduleReaderBackendService,\n ) {}\n\n public async initialize(config: MinionInitializationConfig): Promise<void> {\n // Read (and so validate) the heartbeat settings before anything connects, and clear any heartbeat a PREVIOUS\n // container left behind. In k8s `/tmp` is an `emptyDir`, which outlives a container restart inside the pod: a\n // minion that crashed without removing its file would hand the next container a fresh-looking heartbeat, the\n // startupProbe would pass at once, and the livenessProbe would then kill a slow boot. Cleared here, the\n // startupProbe waits for THIS process's first beat (#1859).\n const livenessHeartbeatSettings = readMinionLivenessHeartbeatEnv(process.env);\n if (livenessHeartbeatSettings) await MinionLivenessHeartbeat.clear(livenessHeartbeatSettings, this.logger);\n\n const {\n minionName,\n serviceIdentifier,\n onTick,\n tickRecovery,\n reconcileTick,\n ...startupConfig\n } = config;\n // Declare WHO this process is before anything can perform a privileged access.\n //\n // Established here, in framework-owned minion startup, rather than left to each\n // minion author — attribution that an author can forget is attribution that will\n // be missing exactly when an auditor needs it. Every minion therefore carries its\n // identity structurally, by virtue of being a minion.\n //\n // Attribution only: this grants nothing. A minion's operations are governed by its\n // role and its `resourceAccess` whitelist; its cross-tenant reach comes from the\n // system-access door.\n //\n // assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged access by a non-human\n // background runtime is attributable to that runtime.\n this.runtimePrincipal.initialize({\n runtimeProfile: ApplicationRuntimeProfile.MINION,\n runtimeKey: minionName,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n });\n\n const normalizedProviderRuntime = this.normalizeProviderRuntime(\n startupConfig.providerRuntime,\n minionName,\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 (operator regenerated one surface but not the\n // other) BEFORE the registry filter would silently boot with\n // mismatched topology.\n //\n // Skipped when:\n // - the artifact is absent (host authored zero providers AND no\n // scope block in `wildo.saas.config.ts`); or\n // - the artifact has zero `providerRefs` (host 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 = normalizedProviderRuntime?.providerRefs ?? [];\n if (normalizedProviderRuntime && projectedProviderRefs.length > 0) {\n assertProviderRuntimeEnvInSync({\n artifactProviderRefs: projectedProviderRefs,\n artifactSourceDigest: normalizedProviderRuntime.sourceDigest,\n hostKind: 'minion',\n hostKey: minionName,\n });\n }\n\n await this.startApplicationService.initialize({\n ...startupConfig,\n providerRuntime: normalizedProviderRuntime,\n headlessMode: true,\n skipCronSync: true,\n // A minion reuses the full backend startup lifecycle but is NOT a job\n // worker for the shared application queues — it consumes ONLY its own\n // `minion-tick.<name>` queue (subscribed below via `startTickConsumer`).\n // Skipping the shared job consumers keeps RabbitMQ from round-robining\n // scheduled-cron ticks onto this process (which would dead-letter every\n // tick it can't interpret). The broker connection itself is still made,\n // because the tick consumer depends on it.\n skipJobConsumers: true,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n afterResourcesRegistryInitialized: async ({\n appConfig,\n resourcesRegistryService,\n errorBuilder,\n }) => {\n const minionConfig = this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n );\n const resourceAccess = minionConfig.resourceAccess;\n const knownResourceTypes = new Set(resourcesRegistryService.getResourceTypes());\n const unknownResourceTypes = [\n ...(resourceAccess?.read ?? []),\n ...(resourceAccess?.write ?? []),\n ].filter((resourceType, index, all) => (\n resourceType !== '*'\n && !knownResourceTypes.has(resourceType)\n && all.indexOf(resourceType) === index\n ));\n\n if (unknownResourceTypes.length > 0) {\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' references unknown resources in resourceAccess: `\n + `[${unknownResourceTypes.join(', ')}].`,\n minionName,\n unknownResourceTypes,\n },\n });\n }\n },\n servicesRegistryDecoratorFactory: (registry, { appConfig, errorBuilder }) => (\n new MinionScopedServicesRegistryHandlerBackendService(\n registry as any,\n minionName,\n this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n ).resourceAccess,\n ).asDecoratedRegistry()\n ),\n });\n\n // KD-12 auto-wiring: every minion subscribes to its dedicated tick\n // queue (`wildo.queue.<appId>.minion-tick.<minionName>`). Cron-mode\n // minions receive ticks from `platform-crontabs-batches-manager`;\n // always-up minions receive nothing on this queue under normal\n // operation but the subscription is harmless (no message ⇒ no\n // dispatch) and keeps the runtime contract symmetric across modes.\n await this.startTickConsumer(minionName, onTick, tickRecovery, reconcileTick);\n await this.startLivenessHeartbeat(minionName, livenessHeartbeatSettings);\n }\n\n /**\n * For a host that shuts the minion down itself. A container's SIGTERM does not come through here: it reaches\n * `WorkerShutdownManager`, whose stop handler stops the tick consumer, and the heartbeat then stops beating on\n * its own because `isReceiving()` turns false. The leftover file is cleared by the next container's\n * `initialize()`.\n */\n public async shutdown(): Promise<void> {\n // First, so a stopping minion stops claiming to be alive before its consumer is torn down.\n if (this.livenessHeartbeat) {\n try {\n await this.livenessHeartbeat.stop();\n } catch (error) {\n this.logger.warn('Failed to stop the minion liveness heartbeat cleanly', { error: describeCaughtError(error) });\n } finally {\n this.livenessHeartbeat = undefined;\n }\n }\n if (this.tickConsumerStarted) {\n try {\n await this.tickConsumer.stop();\n } catch (error) {\n this.logger.warn('Failed to stop minion tick consumer cleanly', {\n error: describeCaughtError(error),\n });\n } finally {\n this.tickConsumerStarted = false;\n }\n }\n await this.startApplicationService.shutdown();\n }\n\n public isApplicationInitialized(): boolean {\n return this.startApplicationService.isApplicationInitialized();\n }\n\n private async startTickConsumer(\n minionName: string,\n onTick: MinionTickAuthorHandler | undefined,\n tickRecovery: Partial<ScheduledRecoveryPolicy> | undefined,\n reconcileTick: MinionTickReconciliationHandler | undefined,\n ): Promise<void> {\n // The surface the handler is ALLOWED to work with, assembled once at the tick\n // boundary. Handed to the author rather than left for them to resolve from the\n // container: `systemAccess` here is already contained by this minion's\n // `resourceAccess` ACL, because startup rebinds the services registry to the\n // scoped decorator before any tick can be delivered. An author who resolved the\n // door themselves could bypass that; an author handed this one cannot.\n const context: Omit<MinionTickContext, 'scheduledAttempt'> = {\n systemAccess: this.systemAccess,\n minionName,\n // Same reasoning as `systemAccess`: handed to the author rather than left\n // to be resolved from the container. A reader an author constructs is a\n // reader an author could construct with a different identity; this one is\n // bound to the process's own attested principal and cannot be pointed\n // elsewhere.\n ownSchedule: this.ownScheduleReader,\n };\n\n // Missing handlers stay absent: the durable coordinator records REVIEW instead of\n // treating an unimplemented tick as successful work.\n const handler: MinionTickHandler | undefined = onTick\n ? async (token, scheduledAttempt) => onTick(token, { ...context, scheduledAttempt })\n : undefined;\n\n // Only this minion's own policy is read here. Whether a policy names an undeclared minion is the backend's diagnosis\n // (`JobConsumerBackendService`): a minion is answered its OWN declaration only (#2954), so every sibling would read\n // as undeclared from here.\n const evidencePolicies = this.appConfigService.config?.scheduledEvidence?.minions;\n await this.tickConsumer.start({\n applicationId: this.appConfigService.applicationId,\n minionName,\n handler,\n recoveryPolicy: tickRecovery,\n evidencePolicy: evidencePolicies && Object.hasOwn(evidencePolicies, minionName) ? evidencePolicies[minionName] : undefined,\n reconcile: reconcileTick\n ? async (token, scheduledAttempt) => reconcileTick(token, { ...context, scheduledAttempt })\n : undefined,\n });\n this.tickConsumerStarted = true;\n }\n\n /**\n * The producer half of the file liveness probe (#1859). Started only AFTER the tick consumer subscribed, so\n * the first heartbeat means \"able to receive work\", which is what the `startupProbe` waits for. The settings\n * come from the env the container renderers stamp from `wildo.minion.config.ts > liveness`, the same parsed\n * value the probe itself is rendered from; a host process gets no such env and writes nothing.\n */\n private async startLivenessHeartbeat(\n minionName: string,\n settings: ReturnType<typeof readMinionLivenessHeartbeatEnv>,\n ): Promise<void> {\n if (!settings) return;\n const heartbeat = new MinionLivenessHeartbeat(\n settings,\n () => this.startApplicationService.isApplicationInitialized() && this.tickConsumer.isReceiving(),\n this.logger,\n );\n await heartbeat.start();\n this.livenessHeartbeat = heartbeat;\n this.logger.info('Minion liveness heartbeat wired to the tick consumer', { minionName });\n }\n\n private getMinionRuntimeConfig(\n appConfig: MinionAwareAppConfiguration,\n minionName: string,\n errorBuilder?: {\n buildError: (\n errorType: ErrorType,\n executionContext: undefined,\n options: {\n customMessageReference?: ErrorCustomMessageReference;\n context?: Record<string, unknown>;\n },\n ) => unknown;\n },\n ): MinionRuntimeConfig {\n const minionConfig = appConfig.minions?.[minionName];\n if (minionConfig) {\n return minionConfig;\n }\n\n if (!errorBuilder) {\n throw new Error(`Minion '${minionName}' is missing from appConfig.minions.`);\n }\n\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' is not declared in the managed runtime config. `\n + 'Re-sync the application bootstrap material before starting the minion.',\n minionName,\n },\n });\n }\n\n /**\n * Bridge the per-minion materialized provider runtime artifact into the\n * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`\n * (and ultimately filtered by `BackendProviderRegistryBackendService`).\n *\n * Three accepted input shapes:\n *\n * 1. `{ artifactKind: 'backend', scope: ... }` — already projected to a\n * backend-shaped single-scope artifact (e.g. produced by an\n * embedding host that pre-selected the scope).\n * 2. `{ artifactKind: 'minions', scope: ..., scopes: undefined }` —\n * what `wildo config sync` writes to each minion's\n * `src/generated/wildo-provider-runtime.generated.ts`. The CLI calls\n * `selectScopedProviderRuntimeArtifact(artifacts.minions, minionKey)`\n * so the file already carries only this minion's scope. We unwrap\n * it here to the canonical backend-shaped artifact.\n * 3. `{ artifactKind: 'minions', scopes: { [name]: ... } }` —\n * multi-scope minion artifact (legacy / non-CLI-driven hosts that\n * pass the unscoped artifact). We resolve `scopes[minionName]`.\n *\n * Anything else fails fast with a clear locator. Each minion process\n * must only see its own scope — there is no fallback to other scopes,\n * no merging across minions, and no silent recovery from a missing\n * scope.\n */\n private normalizeProviderRuntime(\n providerRuntime: MinionInitializationConfig['providerRuntime'],\n minionName: 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 !== 'minions') {\n throw new Error(\n `Unsupported provider runtime artifactKind '${artifactKind}' for minion '${minionName}'.`,\n );\n }\n\n return this.selectMinionProviderRuntimeScope(providerRuntime, minionName);\n }\n\n private selectMinionProviderRuntimeScope(\n providerRuntime: MinionProviderRuntimeArtifact,\n minionName: string,\n ): ProviderRuntimeArtifact {\n const preScopedScope = (providerRuntime as MinionProviderRuntimeArtifact & {\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 // Shape 2 — the CLI-emitted per-minion module.\n scope = preScopedScope;\n } else if (scopes) {\n // Shape 3 — unscoped multi-scope artifact.\n scope = scopes[minionName];\n if (!scope) {\n throw new Error(\n `Provider runtime artifact does not contain a scope for minion '${minionName}'. `\n + `Re-run \\`wildo config sync\\` and verify the minion is declared in `\n + `wildo.saas.config.ts \\`providers.scopes.minions\\`.`,\n );\n }\n }\n\n if (!scope) {\n throw new Error(\n `Provider runtime artifact for minion '${minionName}' 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 // Narrowed with the refs too (#3513): the region a sibling's provider is bound to is not this host's to apply.\n const projectedProcessingRegions = Object.entries(providerRuntime.providerProcessingRegions ?? {})\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 ...(projectedProcessingRegions.length === 0 ? {} : { providerProcessingRegions: Object.fromEntries(projectedProcessingRegions) }),\n // Narrowed with the refs too (#2294), and never dropped: a projection that lost it would load this host's providers\n // without the residency the application declared, which is the one thing the loader's re-check exists to prevent.\n ...(providerRuntime.providerDataResidency === undefined\n ? {}\n : { providerDataResidency: narrowRuntimeProviderDataResidency(providerRuntime.providerDataResidency, projectedProviderRefs) }),\n providerGraphDigest: providerRuntime.providerGraphDigest,\n lockfileSectionDigest: providerRuntime.lockfileSectionDigest,\n artifactKind: 'backend',\n modules: providerRuntime.modules,\n scope,\n };\n }\n}\n"]}
|