@powerhousedao/switchboard 6.2.3-dev.85 → 6.2.3-dev.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.tsbuild/test/ai-gateway.test.d.ts +2 -0
  2. package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
  3. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  4. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  5. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  6. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  7. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  8. package/CHANGELOG.md +34 -0
  9. package/README.md +33 -0
  10. package/dist/boot.d.mts +1 -1
  11. package/dist/boot.mjs +1 -1
  12. package/dist/config/from-env.d.mts +1 -1
  13. package/dist/config/from-env.d.mts.map +1 -1
  14. package/dist/config/from-env.mjs +3 -3
  15. package/dist/config/schema.d.mts +1 -1
  16. package/dist/config/schema.mjs +3 -3
  17. package/dist/{from-env-BO0n9R02.mjs → from-env-DuUwngOC.mjs} +80 -8
  18. package/dist/from-env-DuUwngOC.mjs.map +1 -0
  19. package/dist/index.mjs +3 -3
  20. package/dist/{plugin-host-C1sYEm8g.d.mts → plugin-host-C0bSz1Oe.d.mts} +2 -2
  21. package/dist/{plugin-host-C1sYEm8g.d.mts.map → plugin-host-C0bSz1Oe.d.mts.map} +1 -1
  22. package/dist/plugins/ai.d.mts +37 -0
  23. package/dist/plugins/ai.d.mts.map +1 -0
  24. package/dist/plugins/ai.mjs +352 -0
  25. package/dist/plugins/ai.mjs.map +1 -0
  26. package/dist/plugins/attachments.d.mts +1 -1
  27. package/dist/plugins/attachments.mjs +3 -3
  28. package/dist/plugins/mcp.d.mts +1 -1
  29. package/dist/plugins/privacy.d.mts +1 -1
  30. package/dist/plugins/workflows.d.mts +2 -2
  31. package/dist/plugins/workflows.mjs +3 -3
  32. package/dist/{schema-ivUWPQOn.d.mts → schema-DhempFjb.d.mts} +41 -1
  33. package/dist/schema-DhempFjb.d.mts.map +1 -0
  34. package/dist/{schema-0g_QdOWn.mjs → schema-XEZrdmag.mjs} +55 -6
  35. package/dist/schema-XEZrdmag.mjs.map +1 -0
  36. package/dist/{server-YNY3Qw9a.mjs → server-BqiCmeR0.mjs} +102 -14
  37. package/dist/server-BqiCmeR0.mjs.map +1 -0
  38. package/dist/server.d.mts +8 -7
  39. package/dist/server.d.mts.map +1 -1
  40. package/dist/server.mjs +5 -5
  41. package/dist/{workflow-runtime-7GaJ13c9.d.mts → workflow-runtime-CF5pc8mt.d.mts} +5 -2
  42. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  43. package/dist/{workflows-DkIrfmdn.mjs → workflows-C_pWcP2u.mjs} +4 -3
  44. package/dist/{workflows-DkIrfmdn.mjs.map → workflows-C_pWcP2u.mjs.map} +1 -1
  45. package/package.json +22 -16
  46. package/test/ai-gateway.test.ts +555 -0
  47. package/test/config-from-env.test.ts +184 -0
  48. package/test/config-schema.test.ts +28 -0
  49. package/test/goldens/supergraph.graphql +132 -0
  50. package/test/keyframe-reclaim-store.test.ts +156 -0
  51. package/test/processor-timing-log.test.ts +109 -0
  52. package/tsdown.config.ts +1 -0
  53. package/dist/from-env-BO0n9R02.mjs.map +0 -1
  54. package/dist/schema-0g_QdOWn.mjs.map +0 -1
  55. package/dist/schema-ivUWPQOn.d.mts.map +0 -1
  56. package/dist/server-YNY3Qw9a.mjs.map +0 -1
  57. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-XEZrdmag.mjs","sources":["../src/config/merge.ts","../src/config/schema.ts"],"sourcesContent":["import type { SwitchboardConfigInput } from \"./schema.js\";\n\ntype Layer = SwitchboardConfigInput;\ntype Section = Record<string, unknown>;\n\n// A union, not a section: its variants do not share keys.\nconst REPLACED_WHOLE = new Set([\"attachments.storage\", \"storage.keyframes\"]);\n\n// The reactor-api auth keys whose env vars override a caller's option.\nconst ENV_WINS_AUTH = [\n \"enabled\",\n \"admins\",\n \"resolveIdentity\",\n \"requireAuthenticatedCaller\",\n \"requireAuthenticatedCallerExemptPaths\",\n \"attachmentReadsFollowDocumentPolicy\",\n] as const;\n\nfunction isPlainObject(value: unknown): value is Section {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction mergeSection(base: Section, over: Section, path: string): Section {\n const result: Section = { ...base };\n for (const [key, value] of Object.entries(over)) {\n if (value === undefined) continue;\n const at = path ? `${path}.${key}` : key;\n const current = result[key];\n result[key] =\n isPlainObject(value) && isPlainObject(current) && !REPLACED_WHOLE.has(at)\n ? mergeSection(current, value, at)\n : value;\n }\n return result;\n}\n\n/** Later layers win per key; arrays, maps and unions are replaced whole. */\nexport function mergeSwitchboardConfig(...layers: Layer[]): Layer {\n let merged: Section = {};\n for (const layer of layers) merged = mergeSection(merged, layer, \"\");\n return merged as Layer;\n}\n\n/** A caller's layer over the env's, keeping each key's pre-config precedence. */\nexport function callerOverEnv(env: Layer, caller: Layer): Layer {\n const merged = mergeSwitchboardConfig(env, caller);\n const features: Section = { ...merged.features };\n const inspection: Section = { ...merged.inspection };\n const auth: Section = { ...merged.auth };\n\n const envAuth: Section = env.auth ?? {};\n for (const key of ENV_WINS_AUTH) {\n if (envAuth[key] !== undefined) auth[key] = envAuth[key];\n }\n if (env.features?.documentModelSubgraphs !== undefined) {\n features.documentModelSubgraphs = env.features.documentModelSubgraphs;\n }\n if (env.features?.mcp === false || caller.features?.mcp === false) {\n features.mcp = false;\n }\n if (\n env.inspection?.enabled === false ||\n caller.inspection?.enabled === false\n ) {\n inspection.enabled = false;\n }\n // Under the plugin host a plugin's presence decides these, not their env vars.\n if (features.pluginHost === true) {\n features.mcp = caller.features?.mcp;\n features.workflows = caller.features?.workflows;\n }\n\n return { ...merged, features, inspection, auth } as Layer;\n}\n","import type { ReactorApiConfig } from \"@powerhousedao/reactor-api\";\nimport type { AttachmentStorageConfig } from \"@powerhousedao/reactor-attachments\";\nimport { z } from \"zod\";\n\n// Zod at runtime only: the monitor, workers and host validation load this without the server.\n\nexport const SWITCHBOARD_LOG_LEVELS = [\n \"verbose\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n] as const;\n\nexport const SWITCHBOARD_DRIVE_DOCUMENT_TYPES = [\n \"powerhouse/document-drive\",\n \"powerhouse/reactor-drive\",\n] as const;\n\nconst port = z.number().int().min(0).max(65535);\nconst nonNegativeInt = z.number().int().min(0);\nconst positiveInt = z.number().int().min(1);\nconst nonNegative = z.number().min(0);\nconst positive = z.number().positive();\n\nconst serverSchema = z.object({\n port: port.default(4001),\n strictPort: z.boolean().default(false),\n basePath: z.string().default(\"/\"),\n /** Origin advertised in webhook URLs; a bare domain gets a scheme at use. */\n publicUrl: z.string().optional(),\n gatewayAdapter: z\n .enum([\"apollo\", \"mercurius\", \"stitching\"])\n .default(\"apollo\"),\n https: z\n .union([\n z.boolean(),\n z.object({ keyPath: z.string(), certPath: z.string() }),\n ])\n .optional(),\n dev: z.boolean().default(false),\n});\n\nconst vacuumFullSchema = z.object({\n mode: z.enum([\"off\", \"quiet\", \"forced\"]).default(\"off\"),\n aboveMb: nonNegative.optional(),\n quietMs: nonNegative.optional(),\n maxDeferMs: nonNegative.optional(),\n});\n\nconst keyframeRuleSchema = z.strictObject({\n interval: positiveInt.optional(),\n /** Null keeps every keyframe. */\n keep: positiveInt.nullable().optional(),\n});\n\n/** See `KeyframeSettings` in the reactor. */\nconst keyframesSchema = z.strictObject({\n default: keyframeRuleSchema.optional(),\n types: z.record(z.string(), keyframeRuleSchema).optional(),\n});\n\nconst storageSchema = z.object({\n /** Postgres URL or PGlite data dir; unset uses the default dir. */\n reactor: z.object({ url: z.string().min(1).optional() }).prefault({}),\n /** Postgres URL or PGlite data dir; unset uses the default dir. */\n readModel: z.object({ url: z.string().min(1).optional() }).prefault({}),\n inMemory: z.boolean().default(false),\n /** Relocates the `.ph` tree (stores, identity) under this root. */\n userDataDir: z.string().min(1).optional(),\n pglite: z\n .object({\n fsync: z.boolean().default(true),\n workers: z.boolean().default(true),\n workerMemoryMb: positiveInt.optional(),\n vacuumFull: vacuumFullSchema.prefault({}),\n })\n .prefault({}),\n migratePglite: z.boolean().default(false),\n forcePgVersion: z.union([z.literal(16), z.literal(17)]).optional(),\n /** Unset: `reactor.keyframes` of the project config, then the built-in rule. */\n keyframes: keyframesSchema.optional(),\n});\n\nconst protocolSchema = z.object({\n featureFlags: z\n .object({\n documentDecisions: z.boolean().default(false),\n authEnforcement: z.boolean().default(false),\n authGroups: z.boolean().default(false),\n authConditions: z.boolean().default(false),\n })\n .prefault({}),\n /** Requested policy; without a signer the boot still falls back to legacy. */\n createSignaturePolicy: z\n .enum([\"legacy\", \"v2-required\"])\n .default(\"v2-required\"),\n unsupportedStoredDocuments: z.enum([\"refuse\", \"read-only\"]).default(\"refuse\"),\n legacyProcessorIds: z.boolean().default(true),\n maxSkipThreshold: positiveInt.optional(),\n catchUpPriority: z\n .union([z.literal(\"dynamic\"), z.number().int().min(0).max(7)])\n .default(\"dynamic\"),\n /** What processors record about their time. */\n processorTiming: z.enum([\"off\", \"basic\", \"detailed\"]).default(\"basic\"),\n processorTimingWindowMs: positiveInt.default(60_000),\n /** At `detailed`: an `onOperations` call over this logs a warning. */\n processorSlowBatchMs: positiveInt.default(1_000),\n /** Above 0: logs the slowest processors this often while catching up. */\n processorTimingLogMs: nonNegativeInt.default(0),\n});\n\nconst memoryTelemetrySchema = z.object({\n enabled: z.boolean().default(false),\n intervalMs: z.number().int().min(1000).default(30_000),\n /** `memory`, the ring, is always on while telemetry runs. */\n outputs: z\n .array(z.enum([\"memory\", \"file\", \"console\"]))\n .default([\"memory\", \"file\"]),\n file: z\n .object({\n path: z.string().min(1).optional(),\n maxMb: positiveInt.default(10),\n keep: positiveInt.default(5),\n })\n .prefault({}),\n ringSize: positiveInt.default(720),\n consoleIntervalMs: positiveInt.default(300_000),\n workers: z.boolean().default(true),\n windowMin: positiveInt.default(30),\n});\n\nconst telemetrySchema = z.object({\n memory: memoryTelemetrySchema.prefault({}),\n /** Under it go the JSONL files and heap snapshots; unset: `<phDir>/telemetry`. */\n dir: z.string().min(1).optional(),\n heapSnapshotDir: z.string().min(1).optional(),\n});\n\nconst authSchema = z.object({\n enabled: z.boolean().default(false),\n /** Unset follows `enabled`. */\n resolveIdentity: z.boolean().optional(),\n requireAuthenticatedCaller: z.boolean().default(false),\n requireAuthenticatedCallerExemptPaths: z.array(z.string()).default([]),\n admins: z.array(z.string()).default([]),\n defaultProtection: z.boolean().default(false),\n attachmentReadsFollowDocumentPolicy: z.boolean().default(false),\n documentPermissions: z\n .object({\n enabled: z.boolean().default(false),\n cacheTtlMs: nonNegativeInt.optional(),\n })\n .prefault({}),\n skipCredentialVerification: z.boolean().default(false),\n /** Unset: 0 with a \"self\" renown source, else the AuthService default. */\n credentialCacheTtlMs: nonNegative.optional(),\n wsRecheckMs: nonNegative.optional(),\n renown: z\n .object({\n source: z.enum([\"self\", \"remote\"]).optional(),\n url: z.string().min(1).optional(),\n switchboardUrl: z.string().min(1).optional(),\n })\n .prefault({}),\n});\n\nconst inspectionSchema = z.object({\n enabled: z.boolean().default(true),\n admin: z.boolean().default(false),\n callsPerMinute: positiveInt.optional(),\n});\n\nconst workersSchema = z.object({\n executor: z\n .object({\n count: z.union([nonNegativeInt, z.literal(\"auto\")]).default(0),\n poolSize: nonNegativeInt.default(2),\n acquireTimeoutMs: nonNegativeInt.default(5000),\n })\n .prefault({}),\n hostPoolSize: positiveInt.default(16),\n projection: z\n .object({\n enabled: z.boolean().default(false),\n poolSize: positiveInt.default(8),\n })\n .prefault({}),\n});\n\nconst packagesSchema = z.object({\n registryUrl: z.string().optional(),\n registryPackages: z.array(z.string()).default([]),\n dynamic: z.boolean().default(false),\n list: z.array(z.string()).default([]),\n disableLocal: z.boolean().default(false),\n});\n\nconst privacySchema = z.object({\n enabled: z.boolean().default(false),\n deploymentSecret: z.string().optional(),\n intervalMs: positive.optional(),\n deadlineMs: positive.optional(),\n markerGraceMs: positive.optional(),\n purgeTimeoutMs: positive.optional(),\n});\n\nconst featuresSchema = z.object({\n /** Unset: on unless a plugin composition leaves it out. */\n mcp: z.boolean().optional(),\n /** Unset: the config file's `workflows.enabled`, then off. */\n workflows: z.boolean().optional(),\n documentModelSubgraphs: z.boolean().default(true),\n pluginHost: z.boolean().default(false),\n privacy: privacySchema.prefault({}),\n});\n\nconst s3Schema = z.object({\n endpoint: z.string(),\n region: z.string(),\n bucket: z.string(),\n accessKeyId: z.string(),\n secretAccessKey: z.string(),\n prefix: z.string(),\n forcePathStyle: z.boolean(),\n uploadTtlSeconds: positiveInt,\n downloadTtlSeconds: positiveInt,\n});\n\nconst attachmentsSchema = z.object({\n storage: z\n .discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"filesystem\") }),\n z.object({ kind: z.literal(\"s3\"), s3: s3Schema }),\n ])\n .default({ kind: \"filesystem\" }),\n /** Unset: production refuses signed downloads, elsewhere a per-process secret. */\n urlSigningSecret: z.string().optional(),\n downloadTargetMaxTtlSeconds: positiveInt.optional(),\n /** Unset: `http(s)://localhost:<port>`. */\n serviceUrl: z.string().optional(),\n});\n\nconst identitySchema = z.object({\n keypairPath: z.string().optional(),\n requireExisting: z.boolean().optional(),\n baseUrl: z.string().optional(),\n});\n\nconst driveSchema = z.looseObject({\n id: z.string().optional(),\n slug: z.string().optional(),\n documentType: z.enum(SWITCHBOARD_DRIVE_DOCUMENT_TYPES).optional(),\n});\n\n/** Every field is optional on input, so `z.input` is one configuration layer. */\nexport const switchboardConfigSchema = z.object({\n logLevel: z.enum(SWITCHBOARD_LOG_LEVELS).default(\"info\"),\n server: serverSchema.prefault({}),\n storage: storageSchema.prefault({}),\n protocol: protocolSchema.prefault({}),\n telemetry: telemetrySchema.prefault({}),\n auth: authSchema.prefault({}),\n inspection: inspectionSchema.prefault({}),\n workers: workersSchema.prefault({}),\n packages: packagesSchema.prefault({}),\n features: featuresSchema.prefault({}),\n attachments: attachmentsSchema.prefault({}),\n identity: identitySchema.optional(),\n drive: driveSchema.optional(),\n remoteDrives: z.array(z.string()).default([]),\n configFile: z.string().optional(),\n processorConfig: z.map(z.string(), z.unknown()).optional(),\n});\n\n/**\n * One layer's own schema: every key optional, no defaults (they would\n * override the layers below), unknown keys refused. `omit` drops dotted\n * paths the caller sets elsewhere.\n */\nexport function switchboardConfigLayerSchema(\n omit: readonly string[] = [],\n): z.ZodType<SwitchboardConfigInput, SwitchboardConfigInput> {\n return layerOf(switchboardConfigSchema, \"\", new Set(omit)) as z.ZodType<\n SwitchboardConfigInput,\n SwitchboardConfigInput\n >;\n}\n\nfunction layerOf(\n schema: z.ZodType,\n path: string,\n omit: Set<string>,\n): z.ZodType {\n const def = schema.def as { type: string; innerType?: z.ZodType };\n if (\n (def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"optional\") &&\n def.innerType\n ) {\n return layerOf(def.innerType, path, omit);\n }\n if (!(schema instanceof z.ZodObject)) return schema;\n const shape: Record<string, z.ZodType> = {};\n for (const [key, field] of Object.entries(\n schema.shape as Record<string, z.ZodType>,\n )) {\n const at = path ? `${path}.${key}` : key;\n if (omit.has(at)) continue;\n shape[key] = layerOf(field, at, omit).optional();\n }\n const catchall = schema.def.catchall as z.ZodType | undefined;\n return catchall && catchall.def.type !== \"never\"\n ? z.looseObject(shape)\n : z.strictObject(shape);\n}\n\nexport type SwitchboardConfig = z.output<typeof switchboardConfigSchema>;\n\n/** One configuration layer: any subset of {@link SwitchboardConfig}. */\nexport type SwitchboardConfigInput = z.input<typeof switchboardConfigSchema>;\n\n// The sections reactor-api reads are ReactorApiConfig's, under its names.\ntype Section<T> = NonNullable<T>;\ntype MissingKeys<Api, Ours> = Exclude<keyof Section<Api>, keyof Ours>;\ntype Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype Assert<T extends true> = T;\nexport type ReactorApiSectionsMatch = [\n Assert<\n Same<\n MissingKeys<ReactorApiConfig[\"server\"], SwitchboardConfig[\"server\"]>,\n never\n >\n >,\n Assert<\n Same<\n MissingKeys<ReactorApiConfig[\"auth\"], SwitchboardConfig[\"auth\"]>,\n never\n >\n >,\n Assert<\n Same<\n MissingKeys<\n Section<ReactorApiConfig[\"auth\"]>[\"documentPermissions\"],\n SwitchboardConfig[\"auth\"][\"documentPermissions\"]\n >,\n never\n >\n >,\n Assert<\n Same<\n MissingKeys<\n ReactorApiConfig[\"inspection\"],\n SwitchboardConfig[\"inspection\"]\n >,\n never\n >\n >,\n Assert<\n Same<\n MissingKeys<\n ReactorApiConfig[\"attachments\"],\n SwitchboardConfig[\"attachments\"]\n >,\n never\n >\n >,\n Assert<ReactorApiConfig extends SwitchboardConfigInput ? true : false>,\n Assert<\n Pick<\n SwitchboardConfig,\n \"server\" | \"auth\" | \"inspection\" | \"attachments\"\n > extends ReactorApiConfig\n ? true\n : false\n >,\n Assert<\n Same<\n SwitchboardConfig[\"server\"][\"gatewayAdapter\"],\n NonNullable<Section<ReactorApiConfig[\"server\"]>[\"gatewayAdapter\"]>\n >\n >,\n Assert<\n Same<SwitchboardConfig[\"attachments\"][\"storage\"], AttachmentStorageConfig>\n >,\n];\n\nexport { callerOverEnv, mergeSwitchboardConfig } from \"./merge.js\";\n"],"names":[],"mappings":";;;;AAMA,MAAM,iCAAiB,IAAI,IAAI,CAAC,uBAAuB,mBAAmB,CAAC;AAG3E,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,cAAc,OAAkC;CACvD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAO,eAAe,KAAK,MAAM,OAAO;AAE5C;AAEA,SAAS,aAAa,MAAe,MAAe,MAAuB;CACzE,MAAM,SAAkB,EAAE,GAAG,KAAK;CAClC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;EAC/C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C5B,OAAO,YAAY,SAAS,IAAI,SAAS,UACrC,EAAE,YAAY,KAAK,IACnB,EAAE,aAAa,KAAK;AAC1B","debug_id":"4cfd484a-11e3-5f7d-a891-5b7293484d62"}
@@ -1,11 +1,11 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c2e7566d-7533-5c06-9c0d-cb162985a7ed")}catch(e){}}();
3
- import { a as loadNodeFsClass, c as openForVerify, d as ATTACHMENT_URL_SIGNING_SECRET_ENV, f as resolveAttachmentUrlSigning, i as isSupportedMajor, l as pgliteModuleSpec, n as StoredDocumentsRefusedError, o as loadPGliteModule, r as resolveUnsupportedStoredDocuments, s as loadPgDump, t as switchboardConfigFromEnv, u as readPgVersionFile } from "./from-env-BO0n9R02.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2a63a8d5-698a-52e9-b920-886ea25ac8f6")}catch(e){}}();
3
+ import { a as loadNodeFsClass, c as openForVerify, d as ATTACHMENT_URL_SIGNING_SECRET_ENV, f as resolveAttachmentUrlSigning, i as isSupportedMajor, l as pgliteModuleSpec, n as StoredDocumentsRefusedError, o as loadPGliteModule, r as resolveUnsupportedStoredDocuments, s as loadPgDump, t as switchboardConfigFromEnv, u as readPgVersionFile } from "./from-env-DuUwngOC.mjs";
4
4
  import { a as resolveWorkerModelSources, l as resolveProjectionWorkerOptions, n as keepImportableSources, o as resolveWorkerPoolOptions, p as workerPoolIssues, s as assertProjectionWorkerSupported, t as buildWorkerDbConfig } from "./worker-pool-BWHBLBJd.mjs";
5
5
  import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
6
6
  import { n as resolvePrivacy, r as startPrivacy } from "./privacy-DxIJGH4P.mjs";
7
- import { i as switchboardConfigSchema, o as mergeSwitchboardConfig } from "./schema-0g_QdOWn.mjs";
8
- import { a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as triggerFatalShutdown, h as installFatalErrorShutdown, l as assertWorkflowPackageLoadable, m as workflowSingletonLossHandler, p as retryWorkflowSingleton, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-DkIrfmdn.mjs";
7
+ import { i as switchboardConfigSchema, o as mergeSwitchboardConfig } from "./schema-XEZrdmag.mjs";
8
+ import { a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as triggerFatalShutdown, h as installFatalErrorShutdown, l as assertWorkflowPackageLoadable, m as workflowSingletonLossHandler, p as retryWorkflowSingleton, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-C_pWcP2u.mjs";
9
9
  import { t as privacyPlugin } from "./privacy-BO8Q25xI.mjs";
10
10
  import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
11
11
  import { n as reactorFeatureFlagsOf, t as renownLayers } from "./renown-layers-COZsrGQT.mjs";
@@ -16,9 +16,9 @@ import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumenta
16
16
  import * as Sentry from "@sentry/node";
17
17
  import { childLogger, setLogLevel } from "document-model";
18
18
  import { getConfig } from "@powerhousedao/config/node";
19
- import { CatchUpPriority, ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, startProgressHeartbeat, supportsLiveReadModelRegistration, withProgressHeartbeat } from "@powerhousedao/reactor";
20
- import { HttpPackageLoader, ImportPackageLoader, NodeEventLoopDelay, PackageManagementService, PackagesSubgraph, RequestLoadRecorder, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
21
- import { DEFAULT_PGLITE_WORKER_MEMORY_MB, PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, disableWasmWrapperTiering, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteMaintenance, syncTree } from "@powerhousedao/reactor-api/pglite-node";
19
+ import { CatchUpPriority, ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, MemoryTelemetry, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, ProcessorTimingSettings, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, computeProcessorTiming, createHybridProjectionCoordinatorFactory, instrumentPgPool, isCatchingUp, parseDriveUrl, parseKeyframeSettings, rankSlowest, renderDoneSummary, renderSlowLine, startProgressHeartbeat, supportsLiveReadModelRegistration, withProgressHeartbeat } from "@powerhousedao/reactor";
20
+ import { HttpPackageLoader, ImportPackageLoader, NodeEventLoopDelay, NodeMemorySampler, PackageManagementService, PackagesSubgraph, RequestLoadRecorder, baseDocumentModels, createHeapSnapshotWriter, getUniqueDocumentModels, initializeAndStartAPI, memoryFileSink, reportFailure, resolveRenownConfig, runDetached, telemetryDir } from "@powerhousedao/reactor-api";
21
+ import { DEFAULT_PGLITE_WORKER_MEMORY_MB, PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, disableWasmWrapperTiering, maintenanceOf, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteMaintenance, syncTree } from "@powerhousedao/reactor-api/pglite-node";
22
22
  import "@powerhousedao/shared/document-model";
23
23
  import fs, { promises } from "node:fs";
24
24
  import path, { join, resolve } from "node:path";
@@ -1080,6 +1080,35 @@ function createSwitchboardPluginHost(ctx, resolved) {
1080
1080
  };
1081
1081
  }
1082
1082
  //#endregion
1083
+ //#region src/processor-timing-log.mts
1084
+ const TOP = 5;
1085
+ /**
1086
+ * The console's `catch-up slowest` line for a host without the ph-cli display:
1087
+ * one every interval while catching up, and one summary when it ends. Silent
1088
+ * while timing is off or nothing is catching up. Returns the stop.
1089
+ */
1090
+ function startProcessorTimingLog(options) {
1091
+ const now = options.now ?? (() => Date.now());
1092
+ let busySince;
1093
+ const tick = () => {
1094
+ const report = options.read();
1095
+ if (report.level === "off") return;
1096
+ if (isCatchingUp(report)) {
1097
+ busySince ??= now();
1098
+ const rows = rankSlowest(report, TOP, "window");
1099
+ if (rows.length > 0) options.log(renderSlowLine(rows, report.windowMs));
1100
+ return;
1101
+ }
1102
+ if (busySince === void 0) return;
1103
+ const wallMs = now() - busySince;
1104
+ busySince = void 0;
1105
+ options.log(renderDoneSummary(rankSlowest(report, TOP, "total"), wallMs));
1106
+ };
1107
+ const timer = setInterval(tick, options.intervalMs);
1108
+ timer.unref();
1109
+ return () => clearInterval(timer);
1110
+ }
1111
+ //#endregion
1083
1112
  //#region src/pglite-dialect.ts
1084
1113
  /** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
1085
1114
  function reactorPgliteDialectOptions(logger, proc) {
@@ -1649,6 +1678,11 @@ function readConfigOAuthApps(configPath, logger) {
1649
1678
  }
1650
1679
  return parseOAuthApps(raw, path$1.dirname(path$1.resolve(configPath)), (id, relay) => logger.warn(`workflows.oauthApps "${id}": relay ${JSON.stringify(relay)} is not an object with clientId, redirectUri and tokenUrl; ignored`));
1651
1680
  }
1681
+ /** `PH_KEYFRAMES` (or a caller's layer) wins whole over the project config. */
1682
+ function resolveKeyframes(configured, fromFile, configPath) {
1683
+ if (configured) return configured;
1684
+ return fromFile === void 0 ? void 0 : parseKeyframeSettings(fromFile, `${configPath} reactor.keyframes`);
1685
+ }
1652
1686
  function readConfigWorkflowsEnabled(configPath) {
1653
1687
  try {
1654
1688
  return getConfig(configPath).workflows?.enabled ?? false;
@@ -1698,7 +1732,8 @@ async function createReactorKysely(opts) {
1698
1732
  return {
1699
1733
  kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, dialectOptions) }),
1700
1734
  poolInstrumentation: void 0,
1701
- storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS
1735
+ storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS,
1736
+ storeMaintenance: pglite instanceof ThreadedPGlite ? pglite : maintenanceOf(pglite)
1702
1737
  };
1703
1738
  }
1704
1739
  /**
@@ -1854,6 +1889,12 @@ async function initServer(requestedPort, options, config, renown, renownConfig,
1854
1889
  mode: "fixed",
1855
1890
  level: config.protocol.catchUpPriority
1856
1891
  });
1892
+ const processorTiming = new ProcessorTimingSettings({
1893
+ level: config.protocol.processorTiming,
1894
+ windowMs: config.protocol.processorTimingWindowMs,
1895
+ slowBatchMs: config.protocol.processorSlowBatchMs
1896
+ });
1897
+ const memoryTelemetry = createMemoryTelemetry(config, reactorLogger);
1857
1898
  let workerModels;
1858
1899
  let localRenownRequest;
1859
1900
  const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests, readModelDb }) => {
@@ -1868,7 +1909,7 @@ async function initServer(requestedPort, options, config, renown, renownConfig,
1868
1909
  attachmentReferenceProjection
1869
1910
  };
1870
1911
  }
1871
- const { kysely: baseKysely, poolInstrumentation, storageFacts } = await createReactorKysely({
1912
+ const { kysely: baseKysely, poolInstrumentation, storageFacts, storeMaintenance } = await createReactorKysely({
1872
1913
  reactorDbUrl,
1873
1914
  reactorPgliteDir,
1874
1915
  reactorPgliteMajor,
@@ -1883,7 +1924,13 @@ async function initServer(requestedPort, options, config, renown, renownConfig,
1883
1924
  if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
1884
1925
  const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = reactorFeatureFlagsOf(config.protocol.featureFlags);
1885
1926
  if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
1886
- const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: config.protocol.legacyProcessorIds }).withUnsupportedStoredDocuments(unsupportedStoredDocuments).withCatchUpPriority(catchUpPriority);
1927
+ const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: config.protocol.legacyProcessorIds }).withUnsupportedStoredDocuments(unsupportedStoredDocuments).withCatchUpPriority(catchUpPriority).withProcessorTiming(processorTiming).withMemoryTelemetry(memoryTelemetry);
1928
+ const keyframes = resolveKeyframes(config.storage.keyframes, fileConfig.reactor?.keyframes, configPath);
1929
+ if (keyframes) {
1930
+ logger.info(`Keyframes: default ${JSON.stringify(keyframes.default ?? {})}, ${Object.keys(keyframes.types ?? {}).length} document type(s) with their own rule`);
1931
+ reactorBuilder.withKeyframes(keyframes);
1932
+ }
1933
+ if (storeMaintenance) reactorBuilder.withStoreMaintenance(storeMaintenance);
1887
1934
  if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
1888
1935
  const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
1889
1936
  const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
@@ -1973,8 +2020,10 @@ async function initServer(requestedPort, options, config, renown, renownConfig,
1973
2020
  throw error;
1974
2021
  }
1975
2022
  if (module.reactorModule) {
1976
- new ReactorInstrumentation(module.reactorModule).start();
2023
+ const instrumentation = new ReactorInstrumentation(module.reactorModule);
2024
+ instrumentation.start();
1977
2025
  reactorLogger.info("Reactor metrics instrumentation started");
2026
+ memoryTelemetry.addGauge("otel", () => instrumentation.stats());
1978
2027
  }
1979
2028
  const reactorDriveClient = new ReactorDriveClient({
1980
2029
  read: module.read,
@@ -2255,9 +2304,13 @@ async function initServer(requestedPort, options, config, renown, renownConfig,
2255
2304
  }
2256
2305
  }
2257
2306
  const stopCatchUpLoad = ownedReactorModule ? feedCatchUpPriority(catchUpPriority, api.httpServer) : () => {};
2307
+ const stopTimingLog = startOwnedTimingLog(ownedReactorModule?.reactorModule, processorTiming, config.protocol.processorTimingLogMs, reactorLogger);
2308
+ if (ownedReactorModule?.reactorModule && config.telemetry.memory.enabled) memoryTelemetry.start();
2258
2309
  let apiDrained;
2259
2310
  const drainApi = () => apiDrained ??= (async () => {
2260
2311
  stopCatchUpLoad();
2312
+ stopTimingLog();
2313
+ memoryTelemetry.stop();
2261
2314
  if (pluginHost) await pluginHost.observe("onShutdown");
2262
2315
  await privacy?.stop();
2263
2316
  await workflowsRetry?.stop();
@@ -2520,6 +2573,41 @@ if (import.meta.main) {
2520
2573
  initSwitchboardProcess(config);
2521
2574
  await startSwitchboard(config, { fatalErrorShutdown: true });
2522
2575
  }
2576
+ /** Off in config, no timers or observers exist; a lever can still start it. */
2577
+ function createMemoryTelemetry(config, logger) {
2578
+ const { memory, dir, heapSnapshotDir } = config.telemetry;
2579
+ const directory = dir ?? telemetryDir();
2580
+ return new MemoryTelemetry({
2581
+ sampler: new NodeMemorySampler(),
2582
+ config: {
2583
+ enabled: memory.enabled,
2584
+ intervalMs: memory.intervalMs,
2585
+ outputs: memory.outputs,
2586
+ filePath: memory.file.path,
2587
+ fileMaxMb: memory.file.maxMb,
2588
+ fileKeep: memory.file.keep,
2589
+ ringSize: memory.ringSize,
2590
+ consoleIntervalMs: memory.consoleIntervalMs,
2591
+ workers: memory.workers,
2592
+ windowMin: memory.windowMin
2593
+ },
2594
+ fileSink: (settings) => memoryFileSink(settings, {
2595
+ dir: directory,
2596
+ logger
2597
+ }),
2598
+ heapSnapshot: createHeapSnapshotWriter({ dir: heapSnapshotDir ?? directory }),
2599
+ logger
2600
+ });
2601
+ }
2602
+ /** For a host with no ph-cli display: the slowest processors, through the log. */
2603
+ function startOwnedTimingLog(module, settings, intervalMs, logger) {
2604
+ if (!module || intervalMs <= 0) return () => {};
2605
+ return startProcessorTimingLog({
2606
+ intervalMs,
2607
+ read: () => computeProcessorTiming(module.processorManager.getAll(), module.catchUp.status(), settings.level, settings.windowMs),
2608
+ log: (line) => logger.info("@Line", line)
2609
+ });
2610
+ }
2523
2611
  /**
2524
2612
  * Feeds the priority this server's request load and main-thread event-loop
2525
2613
  * delay, and ticks its controller every second. Returns the stop.
@@ -2536,7 +2624,7 @@ function feedCatchUpPriority(priority, server) {
2536
2624
  };
2537
2625
  }
2538
2626
  //#endregion
2539
- export { resolvePgliteStorageDirs as a, attachmentsPluginConfigSchema as c, isPortAvailable as i, applySwitchboardReactorDefaults as l, deriveAttachmentServiceConfig as n, startSwitchboard as o, initSwitchboardProcess as r, attachmentsPlugin as s, createReactorKysely as t, initProfilerFromEnv as u };
2627
+ export { resolveKeyframes as a, attachmentsPlugin as c, initProfilerFromEnv as d, isPortAvailable as i, attachmentsPluginConfigSchema as l, deriveAttachmentServiceConfig as n, resolvePgliteStorageDirs as o, initSwitchboardProcess as r, startSwitchboard as s, createReactorKysely as t, applySwitchboardReactorDefaults as u };
2540
2628
 
2541
- //# sourceMappingURL=server-YNY3Qw9a.mjs.map
2542
- //# debugId=c2e7566d-7533-5c06-9c0d-cb162985a7ed
2629
+ //# sourceMappingURL=server-BqiCmeR0.mjs.map
2630
+ //# debugId=2a63a8d5-698a-52e9-b920-886ea25ac8f6