@powerhousedao/reactor 6.2.2-dev.3 → 6.2.2-dev.31

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/entry.js CHANGED
@@ -1,6 +1,6 @@
1
- import { o as instrumentPgPool } from "./drive-container-types-DpJp2AmE.js";
1
+ import { o as instrumentPgPool } from "./drive-container-types-BNwEHEXP.js";
2
2
  import { n as errorToInfo, t as createForwardingLogger } from "./forwarding-logger-BBkMSxuJ.js";
3
- import { n as defaultLoadFactory, t as buildWorkerExecutor } from "./build-worker-executor-BDrPlCJl.js";
3
+ import { n as defaultLoadFactory, t as buildWorkerExecutor } from "./build-worker-executor-CO2_-cnA.js";
4
4
  import { ConsoleLogger } from "document-model";
5
5
  import { isMainThread, parentPort } from "node:worker_threads";
6
6
  //#region src/executor/worker/run-worker.ts
@@ -120,6 +120,7 @@ function runWorker(parentPort, overrides = {}) {
120
120
  init: msg,
121
121
  database: database.kysely,
122
122
  logger: new ConsoleLogger([`reactor-worker:${msg.workerId}`]),
123
+ executorConfig: msg.executorConfig,
123
124
  loadFactory: activeLoadFactory
124
125
  });
125
126
  if (database.poolInstrumentation) startPoolReporter(database.poolInstrumentation);
package/dist/entry.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"entry.js","names":[],"sources":["../src/executor/worker/run-worker.ts","../src/executor/worker/entry.ts"],"sourcesContent":["import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { ConsoleLogger } from \"document-model\";\nimport type { Kysely } from \"kysely\";\nimport type { MessagePort } from \"node:worker_threads\";\nimport type { Database } from \"../../core/types.js\";\nimport type { Job } from \"../../queue/types.js\";\nimport {\n instrumentPgPool,\n type PoolInstrumentation,\n} from \"../../storage/pool-instrumentation.js\";\nimport {\n buildWorkerExecutor,\n defaultLoadFactory,\n type BuildWorkerExecutorOptions,\n type WorkerExecutorStack,\n} from \"./build-worker-executor.js\";\nimport { createForwardingLogger } from \"./forwarding-logger.js\";\nimport type {\n DbConfig,\n FactorySpec,\n InitMessage,\n LoadModelMessage,\n ParentMessage,\n WorkerMessage,\n} from \"./protocol.js\";\nimport { errorToInfo } from \"./sanitize.js\";\n\nconst POOL_SAMPLE_INTERVAL_MS = 1_000;\n\n/**\n * Closeable handle around the parent's Postgres pool the worker owns.\n * Decoupled so tests can substitute a PGlite-backed Kysely.\n *\n * When the worker owns a real pg.Pool, the handle exposes a\n * {@link PoolInstrumentation} so the run-loop can subscribe to acquire-wait\n * samples and forward them to the host. Tests that swap in PGlite leave\n * this undefined; pool metrics simply do not emit in that path.\n */\nexport type WorkerDatabaseHandle = {\n kysely: Kysely<Database>;\n poolInstrumentation?: PoolInstrumentation;\n shutdown(): Promise<void>;\n};\n\nexport type RunWorkerOverrides = {\n /**\n * Builds the worker's Kysely instance from the init's DbConfig. Defaults\n * to a real Postgres pool. Tests typically swap this for PGlite.\n */\n createDatabase?: (\n config: DbConfig,\n workerId: string,\n ) => Promise<WorkerDatabaseHandle>;\n /**\n * Overrides the dynamic-import factory loader used for the signature\n * verifier and document model manifest. Tests usually inject this so\n * they don't need real packages.\n */\n loadFactory?: BuildWorkerExecutorOptions[\"loadFactory\"];\n /**\n * Called after the database is created but before the executor stack\n * is built. Lets tests run reactor migrations against PGlite, since\n * the production parent runs them once against shared Postgres.\n */\n beforeBuildExecutor?: (db: Kysely<Database>) => Promise<void>;\n};\n\nasync function defaultCreateDatabase(\n config: DbConfig,\n workerId: string,\n): Promise<WorkerDatabaseHandle> {\n const { Kysely, PostgresDialect } = await import(\"kysely\");\n const pgModule = await import(\"pg\");\n const Pool = pgModule.default.Pool;\n const pool = new Pool({\n host: config.host,\n port: config.port,\n database: config.database,\n user: config.user,\n password: config.password,\n ssl: config.ssl ? { rejectUnauthorized: false } : undefined,\n application_name: config.applicationName ?? workerId,\n max: config.poolSize,\n connectionTimeoutMillis: config.connectionTimeoutMillis,\n idleTimeoutMillis: config.idleTimeoutMillis,\n });\n const poolInstrumentation = instrumentPgPool(pool, workerId);\n const kysely = new Kysely<Database>({\n dialect: new PostgresDialect({ pool }),\n });\n return {\n kysely,\n poolInstrumentation,\n async shutdown(): Promise<void> {\n try {\n await kysely.destroy();\n } catch {\n // best-effort\n }\n try {\n await pool.end();\n } catch {\n // best-effort\n }\n },\n };\n}\n\n/**\n * Drives the worker's message loop. Owns lifecycle of the database handle\n * and executor stack. The default factories build a real Postgres pool and\n * use dynamic `import()` for model/verifier specs; tests inject overrides\n * for an in-process PGlite path.\n */\nexport function runWorker(\n parentPort: MessagePort,\n overrides: RunWorkerOverrides = {},\n): void {\n let workerId = \"\";\n let initCompleted = false;\n let initConfig: InitMessage | null = null;\n let executorStack: WorkerExecutorStack | null = null;\n let database: WorkerDatabaseHandle | null = null;\n let poolSampleTimer: NodeJS.Timeout | null = null;\n let pendingPoolSamples: number[] = [];\n let detachPoolListener: (() => void) | null = null;\n const activeLoadFactory: NonNullable<\n BuildWorkerExecutorOptions[\"loadFactory\"]\n > = overrides.loadFactory ?? defaultLoadFactory;\n\n function post(msg: WorkerMessage): void {\n parentPort.postMessage(msg);\n }\n\n const logger = createForwardingLogger(post);\n\n function startPoolReporter(instrumentation: PoolInstrumentation): void {\n detachPoolListener = instrumentation.onAcquire((durationMs) => {\n pendingPoolSamples.push(durationMs);\n });\n poolSampleTimer = setInterval(() => {\n if (pendingPoolSamples.length === 0) {\n return;\n }\n const durations = pendingPoolSamples;\n pendingPoolSamples = [];\n const stats = instrumentation.getStats();\n post({\n type: \"pool-acquire-samples\",\n workerId,\n poolName: instrumentation.name,\n timestamp: Date.now(),\n durations,\n size: stats.size,\n idle: stats.idle,\n waiting: stats.waiting,\n });\n }, POOL_SAMPLE_INTERVAL_MS);\n poolSampleTimer.unref();\n }\n\n function stopPoolReporter(): void {\n if (detachPoolListener) {\n detachPoolListener();\n detachPoolListener = null;\n }\n if (poolSampleTimer) {\n clearInterval(poolSampleTimer);\n poolSampleTimer = null;\n }\n pendingPoolSamples = [];\n }\n\n process.on(\"uncaughtException\", (err: unknown) => {\n try {\n post({\n type: \"log\",\n level: \"error\",\n message: \"worker uncaughtException\",\n args: [errorToInfo(err)],\n timestamp: Date.now(),\n });\n } catch {\n // nothing left to do\n }\n throw err;\n });\n\n process.on(\"unhandledRejection\", (reason: unknown) => {\n try {\n post({\n type: \"log\",\n level: \"error\",\n message: \"worker unhandledRejection\",\n args: [errorToInfo(reason)],\n timestamp: Date.now(),\n });\n } catch {\n // nothing left to do\n }\n });\n\n async function handleInit(msg: InitMessage): Promise<void> {\n workerId = msg.workerId;\n initConfig = msg;\n const createDb = overrides.createDatabase ?? defaultCreateDatabase;\n database = await createDb(msg.db, msg.workerId);\n if (overrides.beforeBuildExecutor) {\n await overrides.beforeBuildExecutor(database.kysely);\n }\n executorStack = await buildWorkerExecutor({\n init: msg,\n database: database.kysely,\n logger: new ConsoleLogger([`reactor-worker:${msg.workerId}`]),\n loadFactory: activeLoadFactory,\n });\n if (database.poolInstrumentation) {\n startPoolReporter(database.poolInstrumentation);\n }\n initCompleted = true;\n logger.info(\"worker initialized: @workerId\", msg.workerId);\n post({\n type: \"ready\",\n correlationId: msg.correlationId,\n workerId: msg.workerId,\n });\n }\n\n async function handleExecute(correlationId: string, job: Job): Promise<void> {\n if (!executorStack) {\n post({\n type: \"result\",\n correlationId,\n result: { job, success: false },\n error: errorToInfo(new Error(\"execute received before init\")),\n });\n return;\n }\n try {\n const result = await executorStack.executor.executeJob(job);\n const writeReady = executorStack.takeLastWriteReady();\n post({\n type: \"result\",\n correlationId,\n result,\n writeReady: writeReady ?? undefined,\n });\n } catch (error) {\n post({\n type: \"result\",\n correlationId,\n result: { job, success: false },\n error: errorToInfo(error),\n });\n }\n }\n\n async function handleLoadModel(msg: LoadModelMessage): Promise<void> {\n const stack = executorStack;\n if (!stack) {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(new Error(\"load-model received before init\")),\n });\n return;\n }\n let module: DocumentModelModule;\n try {\n module = (await activeLoadFactory(msg.model.spec)) as DocumentModelModule;\n } catch (error) {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(error),\n });\n return;\n }\n const [result] = stack.registry.registerModules(module);\n if (result.status === \"error\") {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(result.error),\n });\n return;\n }\n post({\n type: \"model-loaded\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n });\n }\n\n async function shutdownDatabase(): Promise<void> {\n stopPoolReporter();\n if (database) {\n await database.shutdown();\n }\n }\n\n function handleParentMessage(msg: ParentMessage): void {\n switch (msg.type) {\n case \"init\": {\n handleInit(msg).catch((err: unknown) => {\n post({\n type: \"log\",\n level: \"error\",\n message: \"worker init failed\",\n args: [errorToInfo(err)],\n timestamp: Date.now(),\n });\n });\n break;\n }\n\n case \"execute\": {\n if (!initCompleted) {\n logger.warn(\"received execute before init\");\n post({\n type: \"result\",\n correlationId: msg.correlationId,\n result: { job: msg.job, success: false },\n error: errorToInfo(new Error(\"execute received before init\")),\n });\n break;\n }\n handleExecute(msg.correlationId, msg.job).catch((err: unknown) => {\n post({\n type: \"result\",\n correlationId: msg.correlationId,\n result: { job: msg.job, success: false },\n error: errorToInfo(err),\n });\n });\n break;\n }\n\n case \"shutdown\": {\n logger.info(\"worker shutting down: @workerId\", workerId);\n void shutdownDatabase().finally(() => {\n post({\n type: \"log\",\n level: \"info\",\n message: \"worker shutdown\",\n args: [],\n timestamp: Date.now(),\n });\n process.exit(0);\n });\n break;\n }\n\n case \"abort\": {\n logger.warn(\n \"abort received (no-op stub): @correlationId\",\n msg.correlationId,\n );\n break;\n }\n\n case \"load-model\": {\n handleLoadModel(msg).catch((err: unknown) => {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(err),\n });\n });\n break;\n }\n\n default: {\n const raw = msg as Record<string, unknown>;\n if (raw[\"type\"] === \"__test_throw\") {\n const rawReason = raw[\"reason\"];\n const reason =\n typeof rawReason === \"string\"\n ? rawReason\n : \"synthetic uncaughtException\";\n setTimeout(() => {\n throw new Error(reason);\n }, 0);\n return;\n }\n const _exhaustive: never = msg;\n void _exhaustive;\n break;\n }\n }\n }\n\n parentPort.on(\"message\", handleParentMessage);\n\n // Test-only exports surfaced on a side-channel for unit tests that drive\n // the message loop directly without a real worker_threads parent.\n const harness = {\n handleParentMessage,\n get initCompleted(): boolean {\n return initCompleted;\n },\n get initConfig(): InitMessage | null {\n return initConfig;\n },\n get workerId(): string {\n return workerId;\n },\n };\n (\n parentPort as unknown as { __reactorWorkerHarness?: unknown }\n ).__reactorWorkerHarness = harness;\n}\n\nexport type FactorySpecForTesting = FactorySpec;\n","import { isMainThread, parentPort } from \"node:worker_threads\";\nimport { runWorker } from \"./run-worker.js\";\n\nif (isMainThread || parentPort === null) {\n throw new Error(\"entry.ts must be run as a worker thread\");\n}\n\nrunWorker(parentPort);\n"],"mappings":";;;;;;AA2BA,MAAM,0BAA0B;AAwChC,eAAe,sBACb,QACA,UAC+B;CAC/B,MAAM,EAAE,QAAQ,oBAAoB,MAAM,OAAO;CAEjD,MAAM,QADW,MAAM,OAAO,OACR,QAAQ;CAC9B,MAAM,OAAO,IAAI,KAAK;EACpB,MAAM,OAAO;EACb,MAAM,OAAO;EACb,UAAU,OAAO;EACjB,MAAM,OAAO;EACb,UAAU,OAAO;EACjB,KAAK,OAAO,MAAM,EAAE,oBAAoB,OAAO,GAAG,KAAA;EAClD,kBAAkB,OAAO,mBAAmB;EAC5C,KAAK,OAAO;EACZ,yBAAyB,OAAO;EAChC,mBAAmB,OAAO;EAC3B,CAAC;CACF,MAAM,sBAAsB,iBAAiB,MAAM,SAAS;CAC5D,MAAM,SAAS,IAAI,OAAiB,EAClC,SAAS,IAAI,gBA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AI;MACnB,QAAQ;OAAE,KAAK,IAAI;OAAK,SAAS;OAAO;MACxC,OAAO,YAAY,IAAI;MACxB,CAAC;MACF;AACF;GAGF,KAAK;AACH,WAAO,KAAK,mCAAmC,SAAS;AACnD,sBAAkB,CAAC,cAAc;AACpC,UAAK;MACH,MAAM;MACN,OAAO;MACP,SAAS;MACT,MAAM,EAAE;MACR,WAAW,KAAK,KAAK;MACtB,CAAC;AACF,aAAQ,KAAK,EAAE;MACf;AACF;GAGF,KAAK;AACH,WAAO,KACL,+CACA,IAAI,cACL;AACD;GAGF,KAAK;AACH,oBAAgB,IAAI,CAAC,OAAO,QAAiB;AAC3C,UAAK;MACH,MAAM;MACN,eAAe,IAAI;MACnB,cAAc,IAAI,MAAM;MACxB,SAAS,IAAI,MAAM;MACnB,OAAO,YAAY,IAAI;MACxB,CAAC;MACF;AACF;GAGF,SAAS;IACP,MAAM,MAAM;AACZ,QAAI,IAAI,YAAY,gBAAgB;KAClC,MAAM,YAAY,IAAI;KACtB,MAAM,SACJ,OAAO,cAAc,WACjB,YACA;AACN,sBAAiB;AACf,YAAM,IAAI,MAAM,OAAO;QACtB,EAAE;AACL;;AAIF;;;;AAKN,YAAW,GAAG,WAAW,oBAAoB;AAiB3C,YACA,yBAdc;EACd;EACA,IAAI,gBAAyB;AAC3B,UAAO;;EAET,IAAI,aAAiC;AACnC,UAAO;;EAET,IAAI,WAAmB;AACrB,UAAO;;EAEV;;;;AC7ZH,IAAI,gBAAgB,eAAe,KACjC,OAAM,IAAI,MAAM,0CAA0C;AAG5D,UAAU,WAAW"}
1
+ {"version":3,"file":"entry.js","names":[],"sources":["../src/executor/worker/run-worker.ts","../src/executor/worker/entry.ts"],"sourcesContent":["import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { ConsoleLogger } from \"document-model\";\nimport type { Kysely } from \"kysely\";\nimport type { MessagePort } from \"node:worker_threads\";\nimport type { Database } from \"../../core/types.js\";\nimport type { Job } from \"../../queue/types.js\";\nimport {\n instrumentPgPool,\n type PoolInstrumentation,\n} from \"../../storage/pool-instrumentation.js\";\nimport {\n buildWorkerExecutor,\n defaultLoadFactory,\n type BuildWorkerExecutorOptions,\n type WorkerExecutorStack,\n} from \"./build-worker-executor.js\";\nimport { createForwardingLogger } from \"./forwarding-logger.js\";\nimport type {\n DbConfig,\n FactorySpec,\n InitMessage,\n LoadModelMessage,\n ParentMessage,\n WorkerMessage,\n} from \"./protocol.js\";\nimport { errorToInfo } from \"./sanitize.js\";\n\nconst POOL_SAMPLE_INTERVAL_MS = 1_000;\n\n/**\n * Closeable handle around the parent's Postgres pool the worker owns.\n * Decoupled so tests can substitute a PGlite-backed Kysely.\n *\n * When the worker owns a real pg.Pool, the handle exposes a\n * {@link PoolInstrumentation} so the run-loop can subscribe to acquire-wait\n * samples and forward them to the host. Tests that swap in PGlite leave\n * this undefined; pool metrics simply do not emit in that path.\n */\nexport type WorkerDatabaseHandle = {\n kysely: Kysely<Database>;\n poolInstrumentation?: PoolInstrumentation;\n shutdown(): Promise<void>;\n};\n\nexport type RunWorkerOverrides = {\n /**\n * Builds the worker's Kysely instance from the init's DbConfig. Defaults\n * to a real Postgres pool. Tests typically swap this for PGlite.\n */\n createDatabase?: (\n config: DbConfig,\n workerId: string,\n ) => Promise<WorkerDatabaseHandle>;\n /**\n * Overrides the dynamic-import factory loader used for the signature\n * verifier and document model manifest. Tests usually inject this so\n * they don't need real packages.\n */\n loadFactory?: BuildWorkerExecutorOptions[\"loadFactory\"];\n /**\n * Called after the database is created but before the executor stack\n * is built. Lets tests run reactor migrations against PGlite, since\n * the production parent runs them once against shared Postgres.\n */\n beforeBuildExecutor?: (db: Kysely<Database>) => Promise<void>;\n};\n\nasync function defaultCreateDatabase(\n config: DbConfig,\n workerId: string,\n): Promise<WorkerDatabaseHandle> {\n const { Kysely, PostgresDialect } = await import(\"kysely\");\n const pgModule = await import(\"pg\");\n const Pool = pgModule.default.Pool;\n const pool = new Pool({\n host: config.host,\n port: config.port,\n database: config.database,\n user: config.user,\n password: config.password,\n ssl: config.ssl ? { rejectUnauthorized: false } : undefined,\n application_name: config.applicationName ?? workerId,\n max: config.poolSize,\n connectionTimeoutMillis: config.connectionTimeoutMillis,\n idleTimeoutMillis: config.idleTimeoutMillis,\n });\n const poolInstrumentation = instrumentPgPool(pool, workerId);\n const kysely = new Kysely<Database>({\n dialect: new PostgresDialect({ pool }),\n });\n return {\n kysely,\n poolInstrumentation,\n async shutdown(): Promise<void> {\n try {\n await kysely.destroy();\n } catch {\n // best-effort\n }\n try {\n await pool.end();\n } catch {\n // best-effort\n }\n },\n };\n}\n\n/**\n * Drives the worker's message loop. Owns lifecycle of the database handle\n * and executor stack. The default factories build a real Postgres pool and\n * use dynamic `import()` for model/verifier specs; tests inject overrides\n * for an in-process PGlite path.\n */\nexport function runWorker(\n parentPort: MessagePort,\n overrides: RunWorkerOverrides = {},\n): void {\n let workerId = \"\";\n let initCompleted = false;\n let initConfig: InitMessage | null = null;\n let executorStack: WorkerExecutorStack | null = null;\n let database: WorkerDatabaseHandle | null = null;\n let poolSampleTimer: NodeJS.Timeout | null = null;\n let pendingPoolSamples: number[] = [];\n let detachPoolListener: (() => void) | null = null;\n const activeLoadFactory: NonNullable<\n BuildWorkerExecutorOptions[\"loadFactory\"]\n > = overrides.loadFactory ?? defaultLoadFactory;\n\n function post(msg: WorkerMessage): void {\n parentPort.postMessage(msg);\n }\n\n const logger = createForwardingLogger(post);\n\n function startPoolReporter(instrumentation: PoolInstrumentation): void {\n detachPoolListener = instrumentation.onAcquire((durationMs) => {\n pendingPoolSamples.push(durationMs);\n });\n poolSampleTimer = setInterval(() => {\n if (pendingPoolSamples.length === 0) {\n return;\n }\n const durations = pendingPoolSamples;\n pendingPoolSamples = [];\n const stats = instrumentation.getStats();\n post({\n type: \"pool-acquire-samples\",\n workerId,\n poolName: instrumentation.name,\n timestamp: Date.now(),\n durations,\n size: stats.size,\n idle: stats.idle,\n waiting: stats.waiting,\n });\n }, POOL_SAMPLE_INTERVAL_MS);\n poolSampleTimer.unref();\n }\n\n function stopPoolReporter(): void {\n if (detachPoolListener) {\n detachPoolListener();\n detachPoolListener = null;\n }\n if (poolSampleTimer) {\n clearInterval(poolSampleTimer);\n poolSampleTimer = null;\n }\n pendingPoolSamples = [];\n }\n\n process.on(\"uncaughtException\", (err: unknown) => {\n try {\n post({\n type: \"log\",\n level: \"error\",\n message: \"worker uncaughtException\",\n args: [errorToInfo(err)],\n timestamp: Date.now(),\n });\n } catch {\n // nothing left to do\n }\n throw err;\n });\n\n process.on(\"unhandledRejection\", (reason: unknown) => {\n try {\n post({\n type: \"log\",\n level: \"error\",\n message: \"worker unhandledRejection\",\n args: [errorToInfo(reason)],\n timestamp: Date.now(),\n });\n } catch {\n // nothing left to do\n }\n });\n\n async function handleInit(msg: InitMessage): Promise<void> {\n workerId = msg.workerId;\n initConfig = msg;\n const createDb = overrides.createDatabase ?? defaultCreateDatabase;\n database = await createDb(msg.db, msg.workerId);\n if (overrides.beforeBuildExecutor) {\n await overrides.beforeBuildExecutor(database.kysely);\n }\n executorStack = await buildWorkerExecutor({\n init: msg,\n database: database.kysely,\n logger: new ConsoleLogger([`reactor-worker:${msg.workerId}`]),\n executorConfig: msg.executorConfig,\n loadFactory: activeLoadFactory,\n });\n if (database.poolInstrumentation) {\n startPoolReporter(database.poolInstrumentation);\n }\n initCompleted = true;\n logger.info(\"worker initialized: @workerId\", msg.workerId);\n post({\n type: \"ready\",\n correlationId: msg.correlationId,\n workerId: msg.workerId,\n });\n }\n\n async function handleExecute(correlationId: string, job: Job): Promise<void> {\n if (!executorStack) {\n post({\n type: \"result\",\n correlationId,\n result: { job, success: false },\n error: errorToInfo(new Error(\"execute received before init\")),\n });\n return;\n }\n try {\n const result = await executorStack.executor.executeJob(job);\n const writeReady = executorStack.takeLastWriteReady();\n post({\n type: \"result\",\n correlationId,\n result,\n writeReady: writeReady ?? undefined,\n });\n } catch (error) {\n post({\n type: \"result\",\n correlationId,\n result: { job, success: false },\n error: errorToInfo(error),\n });\n }\n }\n\n async function handleLoadModel(msg: LoadModelMessage): Promise<void> {\n const stack = executorStack;\n if (!stack) {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(new Error(\"load-model received before init\")),\n });\n return;\n }\n let module: DocumentModelModule;\n try {\n module = (await activeLoadFactory(msg.model.spec)) as DocumentModelModule;\n } catch (error) {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(error),\n });\n return;\n }\n const [result] = stack.registry.registerModules(module);\n if (result.status === \"error\") {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(result.error),\n });\n return;\n }\n post({\n type: \"model-loaded\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n });\n }\n\n async function shutdownDatabase(): Promise<void> {\n stopPoolReporter();\n if (database) {\n await database.shutdown();\n }\n }\n\n function handleParentMessage(msg: ParentMessage): void {\n switch (msg.type) {\n case \"init\": {\n handleInit(msg).catch((err: unknown) => {\n post({\n type: \"log\",\n level: \"error\",\n message: \"worker init failed\",\n args: [errorToInfo(err)],\n timestamp: Date.now(),\n });\n });\n break;\n }\n\n case \"execute\": {\n if (!initCompleted) {\n logger.warn(\"received execute before init\");\n post({\n type: \"result\",\n correlationId: msg.correlationId,\n result: { job: msg.job, success: false },\n error: errorToInfo(new Error(\"execute received before init\")),\n });\n break;\n }\n handleExecute(msg.correlationId, msg.job).catch((err: unknown) => {\n post({\n type: \"result\",\n correlationId: msg.correlationId,\n result: { job: msg.job, success: false },\n error: errorToInfo(err),\n });\n });\n break;\n }\n\n case \"shutdown\": {\n logger.info(\"worker shutting down: @workerId\", workerId);\n void shutdownDatabase().finally(() => {\n post({\n type: \"log\",\n level: \"info\",\n message: \"worker shutdown\",\n args: [],\n timestamp: Date.now(),\n });\n process.exit(0);\n });\n break;\n }\n\n case \"abort\": {\n logger.warn(\n \"abort received (no-op stub): @correlationId\",\n msg.correlationId,\n );\n break;\n }\n\n case \"load-model\": {\n handleLoadModel(msg).catch((err: unknown) => {\n post({\n type: \"model-load-failed\",\n correlationId: msg.correlationId,\n documentType: msg.model.documentType,\n version: msg.model.version,\n error: errorToInfo(err),\n });\n });\n break;\n }\n\n default: {\n const raw = msg as Record<string, unknown>;\n if (raw[\"type\"] === \"__test_throw\") {\n const rawReason = raw[\"reason\"];\n const reason =\n typeof rawReason === \"string\"\n ? rawReason\n : \"synthetic uncaughtException\";\n setTimeout(() => {\n throw new Error(reason);\n }, 0);\n return;\n }\n const _exhaustive: never = msg;\n void _exhaustive;\n break;\n }\n }\n }\n\n parentPort.on(\"message\", handleParentMessage);\n\n // Test-only exports surfaced on a side-channel for unit tests that drive\n // the message loop directly without a real worker_threads parent.\n const harness = {\n handleParentMessage,\n get initCompleted(): boolean {\n return initCompleted;\n },\n get initConfig(): InitMessage | null {\n return initConfig;\n },\n get workerId(): string {\n return workerId;\n },\n };\n (\n parentPort as unknown as { __reactorWorkerHarness?: unknown }\n ).__reactorWorkerHarness = harness;\n}\n\nexport type FactorySpecForTesting = FactorySpec;\n","import { isMainThread, parentPort } from \"node:worker_threads\";\nimport { runWorker } from \"./run-worker.js\";\n\nif (isMainThread || parentPort === null) {\n throw new Error(\"entry.ts must be run as a worker thread\");\n}\n\nrunWorker(parentPort);\n"],"mappings":";;;;;;AA2BA,MAAM,0BAA0B;AAwChC,eAAe,sBACb,QACA,UAC+B;CAC/B,MAAM,EAAE,QAAQ,oBAAoB,MAAM,OAAO;CAEjD,MAAM,QADW,MAAM,OAAO,OACR,QAAQ;CAC9B,MAAM,OAAO,IAAI,KAAK;EACpB,MAAM,OAAO;EACb,MAAM,OAAO;EACb,UAAU,OAAO;EACjB,MAAM,OAAO;EACb,UAAU,OAAO;EACjB,KAAK,OAAO,MAAM,EAAE,oBAAoB,OAAO,GAAG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