@rebasepro/server 0.23.0 → 0.24.0
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/README.md +1 -1
- package/bin/rebase-server.js +4 -2
- package/dist/{GCSStorageController-CjrA4PMo.js → GCSStorageController-BSiP1c-f.js} +22 -8
- package/dist/GCSStorageController-BSiP1c-f.js.map +1 -0
- package/dist/{S3StorageController-B6pKDNVj.js → S3StorageController-CAwFRgjV.js} +19 -7
- package/dist/S3StorageController-CAwFRgjV.js.map +1 -0
- package/dist/api/ast-schema-editor.d.ts +92 -1
- package/dist/api/errors.d.ts +9 -0
- package/dist/api/live-schema-routes.d.ts +38 -8
- package/dist/api/logs-routes.d.ts +39 -1
- package/dist/api/openapi-generator.d.ts +17 -0
- package/dist/api/rest/api-generator.d.ts +44 -10
- package/dist/api/rest/write-validation.d.ts +2 -2
- package/dist/api/types.d.ts +17 -1
- package/dist/{ast-schema-editor-Mvr50v_S.js → ast-schema-editor-CWqS_sLJ.js} +309 -11
- package/dist/ast-schema-editor-CWqS_sLJ.js.map +1 -0
- package/dist/auth/access.d.ts +105 -0
- package/dist/auth/adapter-middleware.d.ts +2 -1
- package/dist/auth/address-ownership.d.ts +16 -1
- package/dist/auth/admin-roles-route.d.ts +4 -2
- package/dist/auth/admin-roles.d.ts +17 -20
- package/dist/auth/admin-users-route.d.ts +1 -0
- package/dist/auth/api-keys/api-key-middleware.d.ts +56 -55
- package/dist/auth/api-keys/api-key-routes.d.ts +41 -11
- package/dist/auth/api-keys/api-key-store.d.ts +31 -8
- package/dist/auth/api-keys/api-key-types.d.ts +14 -16
- package/dist/auth/api-keys/http-operation.d.ts +19 -0
- package/dist/auth/api-keys/index.d.ts +11 -11
- package/dist/auth/api-keys/key-grant.d.ts +41 -0
- package/dist/auth/api-keys/legacy-permissions.d.ts +33 -0
- package/dist/auth/auth-hooks.d.ts +46 -7
- package/dist/auth/builtin-auth-adapter.d.ts +8 -0
- package/dist/auth/cookie-utils.d.ts +7 -0
- package/dist/auth/deliverable-address.d.ts +6 -0
- package/dist/auth/email-change-routes.d.ts +41 -0
- package/dist/auth/expired-token-sweep.d.ts +67 -0
- package/dist/auth/impersonation.d.ts +110 -0
- package/dist/auth/index.d.ts +4 -2
- package/dist/auth/interfaces.d.ts +110 -59
- package/dist/auth/jwt.d.ts +49 -3
- package/dist/auth/magic-link-routes.d.ts +2 -6
- package/dist/auth/mfa-routes.d.ts +2 -9
- package/dist/auth/middleware.d.ts +17 -5
- package/dist/auth/otp-routes.d.ts +2 -6
- package/dist/auth/passwordless-signup.d.ts +27 -0
- package/dist/auth/platform-token.d.ts +122 -0
- package/dist/auth/rate-limiter.d.ts +41 -0
- package/dist/auth/routes.d.ts +45 -0
- package/dist/auth/scope-routes.d.ts +22 -0
- package/dist/auth/session-routes.d.ts +11 -6
- package/dist/auth/token-revocation.d.ts +50 -1
- package/dist/auth/verify-credential.d.ts +28 -0
- package/dist/{auth-B-GIMpDG.js → auth-DMLngxn_.js} +2159 -569
- package/dist/auth-DMLngxn_.js.map +1 -0
- package/dist/backend-DTAOsLQc.js.map +1 -1
- package/dist/backup/backup-common.d.ts +10 -0
- package/dist/backup/backup-routes.d.ts +24 -4
- package/dist/backup/backup-schedule.d.ts +33 -0
- package/dist/backup/backup-storage.d.ts +14 -0
- package/dist/backup/index.d.ts +2 -0
- package/dist/backup-CN0s50D2.js +444 -0
- package/dist/backup-CN0s50D2.js.map +1 -0
- package/dist/boot/bundle.d.ts +19 -0
- package/dist/boot/env.d.ts +49 -4
- package/dist/boot/security-headers.d.ts +26 -0
- package/dist/boot/static-routing.d.ts +56 -0
- package/dist/collection_patch-BRu-BvDv.js +472 -0
- package/dist/collection_patch-BRu-BvDv.js.map +1 -0
- package/dist/{contract-routes-CbFjuBwa.js → contract-routes-fz8i4pxs.js} +17 -4
- package/dist/contract-routes-fz8i4pxs.js.map +1 -0
- package/dist/cron/cron-scheduler.d.ts +25 -20
- package/dist/cron/cron-store.d.ts +6 -2
- package/dist/{cron-loader-DfTj2Hbi.js → cron-loader-CwaANlOG.js} +4 -4
- package/dist/cron-loader-CwaANlOG.js.map +1 -0
- package/dist/{cron-routes-eE8nif_b.js → cron-routes-Bc-SB0Se.js} +10 -7
- package/dist/cron-routes-Bc-SB0Se.js.map +1 -0
- package/dist/{cron-scheduler-B0pLfAix.js → cron-scheduler-CYQgco86.js} +52 -34
- package/dist/cron-scheduler-CYQgco86.js.map +1 -0
- package/dist/{cron-store-TcoGz-xS.js → cron-store-D2Q9-Aco.js} +10 -15
- package/dist/cron-store-D2Q9-Aco.js.map +1 -0
- package/dist/{ddl-bootstrap-C6mo0Kmz.js → ddl-bootstrap-BaqMSa4Y.js} +2 -2
- package/dist/{ddl-bootstrap-C6mo0Kmz.js.map → ddl-bootstrap-BaqMSa4Y.js.map} +1 -1
- package/dist/email/index.d.ts +2 -2
- package/dist/email/templates.d.ts +22 -0
- package/dist/email/types.d.ts +26 -0
- package/dist/env.d.ts +1 -2
- package/dist/{errors-DWsX4yTd.js → errors-D6_y86c5.js} +102 -8
- package/dist/errors-D6_y86c5.js.map +1 -0
- package/dist/{function-loader-xnbDAPfa.js → function-loader-D7o5Epjj.js} +2 -2
- package/dist/{function-loader-xnbDAPfa.js.map → function-loader-D7o5Epjj.js.map} +1 -1
- package/dist/{function-routes-Chet4-lB.js → function-routes-CaNG4waN.js} +24 -12
- package/dist/function-routes-CaNG4waN.js.map +1 -0
- package/dist/functions/context.d.ts +17 -6
- package/dist/functions/guards.d.ts +22 -5
- package/dist/functions/index.d.ts +2 -2
- package/dist/functions/index.js +90 -36
- package/dist/functions/index.js.map +1 -1
- package/dist/{history-recorder-B4MpJfJK.js → history-recorder-Nr8zLvoU.js} +4 -4
- package/dist/{history-recorder-B4MpJfJK.js.map → history-recorder-Nr8zLvoU.js.map} +1 -1
- package/dist/{history-store-BhxWOuz9.js → history-store-rcAm_xFR.js} +2 -2
- package/dist/{history-store-BhxWOuz9.js.map → history-store-rcAm_xFR.js.map} +1 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.es.js +3084 -753
- package/dist/index.es.js.map +1 -1
- package/dist/init/health.d.ts +17 -2
- package/dist/init/shutdown.d.ts +10 -0
- package/dist/init.d.ts +54 -0
- package/dist/{jobs-CazMYhyy.js → jobs-DqYNfquG.js} +5 -5
- package/dist/{jobs-CazMYhyy.js.map → jobs-DqYNfquG.js.map} +1 -1
- package/dist/{jwt-DnQHNFCl.js → jwt-R6bSPMjk.js} +39 -15
- package/dist/{jwt-DnQHNFCl.js.map → jwt-R6bSPMjk.js.map} +1 -1
- package/dist/{keys-CogCQpxG.js → keys-GAVZqbqx.js} +3 -17
- package/dist/{keys-CogCQpxG.js.map → keys-GAVZqbqx.js.map} +1 -1
- package/dist/{logger-DO2PZc4i.js → logger-D-S-hO5e.js} +26 -3
- package/dist/logger-D-S-hO5e.js.map +1 -0
- package/dist/{logs-routes-Bj4TYYUl.js → logs-routes-DAdv37GI.js} +48 -8
- package/dist/logs-routes-DAdv37GI.js.map +1 -0
- package/dist/mcp/consent-page.d.ts +1 -1
- package/dist/mcp/mcp-routes.d.ts +7 -0
- package/dist/mcp/mcp-tools.d.ts +15 -9
- package/dist/mcp/oauth-metadata.d.ts +21 -16
- package/dist/mcp/oauth-routes.d.ts +7 -1
- package/dist/{openapi-generator-O_O24MAT.js → openapi-generator-DAq_XVDu.js} +104 -13
- package/dist/openapi-generator-DAq_XVDu.js.map +1 -0
- package/dist/{proxy-Czngl3p9.js → proxy-qRlqeUmO.js} +2 -2
- package/dist/{proxy-Czngl3p9.js.map → proxy-qRlqeUmO.js.map} +1 -1
- package/dist/{query-parser-DGRVFNM3.js → query-parser-BgiKJKvc.js} +6 -56
- package/dist/query-parser-BgiKJKvc.js.map +1 -0
- package/dist/{request-timeout-C_4C2BeR.js → request-timeout-DgH7j8qO.js} +3 -3
- package/dist/{request-timeout-C_4C2BeR.js.map → request-timeout-DgH7j8qO.js.map} +1 -1
- package/dist/schema-edit/apply-schema-change.d.ts +63 -3
- package/dist/schema-edit/project-root.d.ts +3 -2
- package/dist/schema-edit/remote-source.d.ts +9 -4
- package/dist/{schema-editor-routes-C5-lh_jO.js → schema-editor-routes-oIyuWl3L.js} +12 -7
- package/dist/schema-editor-routes-oIyuWl3L.js.map +1 -0
- package/dist/serve-spa.d.ts +58 -0
- package/dist/services/routed-realtime-service.d.ts +11 -0
- package/dist/soft-delete-params-BWPilMPF.js +59 -0
- package/dist/soft-delete-params-BWPilMPF.js.map +1 -0
- package/dist/{src-vkcwKXbT.js → src-CatHFUym.js} +439 -20
- package/dist/src-CatHFUym.js.map +1 -0
- package/dist/{src-pmvW7BFx.js → src-I3aG1PcY.js} +252 -70
- package/dist/src-I3aG1PcY.js.map +1 -0
- package/dist/storage/GCSStorageController.d.ts +2 -0
- package/dist/storage/LocalStorageController.d.ts +2 -0
- package/dist/storage/S3StorageController.d.ts +2 -0
- package/dist/storage/index.d.ts +2 -2
- package/dist/storage/property-limits.d.ts +41 -6
- package/dist/storage/request-keys.d.ts +15 -0
- package/dist/storage/requested-object.d.ts +74 -0
- package/dist/storage/routes.d.ts +36 -18
- package/dist/storage/tus-handler.d.ts +30 -5
- package/dist/storage/types.d.ts +19 -0
- package/dist/types-BfKcm9do.js.map +1 -1
- package/dist/utils/logger.d.ts +12 -0
- package/package.json +5 -5
- package/dist/GCSStorageController-CjrA4PMo.js.map +0 -1
- package/dist/S3StorageController-B6pKDNVj.js.map +0 -1
- package/dist/admin-roles-vYdp_Pil.js +0 -36
- package/dist/admin-roles-vYdp_Pil.js.map +0 -1
- package/dist/admin_block-DxKLmdiv.js +0 -206
- package/dist/admin_block-DxKLmdiv.js.map +0 -1
- package/dist/ast-schema-editor-Mvr50v_S.js.map +0 -1
- package/dist/auth/api-keys/api-key-permission-guard.d.ts +0 -65
- package/dist/auth-B-GIMpDG.js.map +0 -1
- package/dist/backup-D7YR94N3.js +0 -253
- package/dist/backup-D7YR94N3.js.map +0 -1
- package/dist/contract-routes-CbFjuBwa.js.map +0 -1
- package/dist/cron-loader-DfTj2Hbi.js.map +0 -1
- package/dist/cron-routes-eE8nif_b.js.map +0 -1
- package/dist/cron-scheduler-B0pLfAix.js.map +0 -1
- package/dist/cron-store-TcoGz-xS.js.map +0 -1
- package/dist/errors-DWsX4yTd.js.map +0 -1
- package/dist/function-routes-Chet4-lB.js.map +0 -1
- package/dist/logger-DO2PZc4i.js.map +0 -1
- package/dist/logs-routes-Bj4TYYUl.js.map +0 -1
- package/dist/openapi-generator-O_O24MAT.js.map +0 -1
- package/dist/query-parser-DGRVFNM3.js.map +0 -1
- package/dist/schema-editor-routes-C5-lh_jO.js.map +0 -1
- package/dist/src-pmvW7BFx.js.map +0 -1
- package/dist/src-vkcwKXbT.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cron-scheduler-CYQgco86.js","names":[],"sources":["../../types/src/types/env_boolean.ts","../src/cron/scale-to-zero.ts","../src/cron/cron-scheduler.ts"],"sourcesContent":["const YES = new Set([\"true\", \"1\", \"yes\", \"on\"]);\nconst NO = new Set([\"false\", \"0\", \"no\", \"off\"]);\n\n/**\n * Read a boolean environment variable — one spelling rule for every reader.\n *\n * `true`, `1`, `yes` and `on` are true; `false`, `0`, `no` and `off` are\n * false. Case and surrounding whitespace are ignored. Anything else — unset,\n * blank, or a value that spells neither — is `undefined`, so the caller's\n * default decides and a typo lands on the side the caller chose:\n *\n * ```ts\n * parseEnvBoolean(env.FORCE_LOCAL_STORAGE) === true // off unless said\n * parseEnvBoolean(env.REBASE_MCP_OPEN_REGISTRATION) !== false // on unless said\n * ```\n *\n * It exists because every reader used to spell this itself, and they\n * disagreed. The reader that mattered tested the raw string for truthiness —\n * `!process.env.FORCE_LOCAL_STORAGE` — and every non-empty string is truthy,\n * so `FORCE_LOCAL_STORAGE=false`, written to say \"there is no durable volume\n * here\", switched the production storage guard off and sent uploads to a\n * container filesystem the next redeploy erased. Beside it, `=== \"true\"` made\n * `DISABLE_DB_ROLE_SWITCHING=1` do nothing and `!== \"false\"` made\n * `REBASE_MCP_OPEN_REGISTRATION=0` leave registration open.\n *\n * The boot schemas in `@rebasepro/server` (`loadEnv`, `loadBootEnv`) accept a\n * strict subset — `true`, `false` and blank — and refuse any other value\n * before the server starts. On that subset they read exactly what this reads,\n * so a variable a schema declares and something else reads lazily cannot mean\n * two different things.\n *\n * It lives in this package, with no dependencies, for the reason\n * {@link storageEnvSuffix} does: the runtime, its drivers and the CLI all read\n * these variables, and a second parser is a second chance to disagree.\n *\n * @group Models\n */\nexport function parseEnvBoolean(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined;\n const spelled = value.trim().toLowerCase();\n if (YES.has(spelled)) return true;\n if (NO.has(spelled)) return false;\n return undefined;\n}\n","/**\n * Scale-to-zero detection for the cron scheduler.\n *\n * The scheduler drives jobs with in-process `setTimeout`. That works on any\n * always-running instance, but on a platform that freezes or evicts the\n * container between requests (Cloud Run with `--min-instances=0`, AWS Lambda,\n * Vercel functions) the timers simply never fire — the process boots, logs the\n * jobs as registered, and silently runs nothing.\n *\n * None of these platforms expose their scaling floor to the container, so this\n * detection is a heuristic: it identifies the *platform*, not the setting. It\n * is a warning only — it must never influence boot.\n *\n * Environment variables used here were verified against vendor documentation:\n * - `K_SERVICE` / `K_REVISION` / `K_CONFIGURATION` — Cloud Run services\n * (Cloud Run container contract; no variable exposes min-instances).\n * - `CLOUD_RUN_JOB` — Cloud Run jobs (same contract).\n * - `AWS_LAMBDA_FUNCTION_NAME` — reserved AWS Lambda runtime variable.\n * - `VERCEL=1` — Vercel system environment variable, available at runtime.\n * - `KUBERNETES_SERVICE_HOST` — injected into every pod by the kubelet. Used\n * as an *exclusion*: a Deployment pod runs continuously, and Knative on\n * Kubernetes also sets `K_SERVICE`, so a pod is never warned about.\n */\n\nimport { parseEnvBoolean } from \"@rebasepro/types\";\n\n/** Environment variable that permanently silences the scale-to-zero warning. */\nexport const CRON_ALWAYS_ON_ENV = \"REBASE_CRON_ALWAYS_ON\";\n\n/** The subset of `process.env` this module reads. */\nexport type EnvLike = Record<string, string | undefined>;\n\nexport interface FreezableRuntime {\n /** Human-readable platform name, used verbatim in the warning. */\n platform: string;\n /** Names of the environment variables that identified the platform. */\n signals: string[];\n}\n\n/** Minimal shape of a registered job needed to build the warning. */\nexport interface WarnableJob {\n id: string;\n enabled: boolean;\n}\n\nexport interface ScaleToZeroWarning {\n message: string;\n data: Record<string, unknown>;\n}\n\n/**\n * Identify a runtime whose instances can be frozen or torn down between\n * requests. Returns `undefined` when the platform is unknown or known to run\n * continuously.\n */\nexport function detectFreezableRuntime(env: EnvLike = process.env): FreezableRuntime | undefined {\n // A Kubernetes pod (GKE, EKS, self-hosted) runs continuously. Knative and\n // Cloud Run for Anthos set K_SERVICE *inside* a pod, so this exclusion has\n // to come first or every Knative pod would be a false positive.\n if (env.KUBERNETES_SERVICE_HOST) return undefined;\n\n if (env.K_SERVICE) {\n const signals = [\"K_SERVICE\"];\n if (env.K_REVISION) signals.push(\"K_REVISION\");\n if (env.K_CONFIGURATION) signals.push(\"K_CONFIGURATION\");\n return { platform: \"Cloud Run\", signals };\n }\n\n if (env.CLOUD_RUN_JOB) {\n return { platform: \"Cloud Run Jobs\", signals: [\"CLOUD_RUN_JOB\"] };\n }\n\n if (env.AWS_LAMBDA_FUNCTION_NAME) {\n return { platform: \"AWS Lambda\", signals: [\"AWS_LAMBDA_FUNCTION_NAME\"] };\n }\n\n if (parseEnvBoolean(env.VERCEL) === true) {\n return { platform: \"Vercel\", signals: [\"VERCEL\"] };\n }\n\n return undefined;\n}\n\n/** How many job ids to name before collapsing the rest into \"+N more\". */\nconst MAX_NAMED_JOBS = 10;\n\n/**\n * Build the boot-time warning, or `undefined` when it does not apply.\n *\n * Fires only when all of the following hold:\n * 1. `NODE_ENV=production` — a laptop or CI run is not at risk.\n * 2. At least one *enabled* job is registered — nothing to lose otherwise.\n * 3. The environment looks like a freezable platform (see above).\n * 4. `REBASE_CRON_ALWAYS_ON` is not set to a truthy value.\n */\nexport function buildScaleToZeroWarning(\n jobs: WarnableJob[],\n env: EnvLike = process.env\n): ScaleToZeroWarning | undefined {\n if (env.NODE_ENV !== \"production\") return undefined;\n if (parseEnvBoolean(env[CRON_ALWAYS_ON_ENV]) === true) return undefined;\n\n const enabled = jobs.filter((job) => job.enabled).map((job) => job.id);\n if (enabled.length === 0) return undefined;\n\n const runtime = detectFreezableRuntime(env);\n if (!runtime) return undefined;\n\n const named = enabled.slice(0, MAX_NAMED_JOBS);\n const list = enabled.length > named.length\n ? `${named.join(\", \")} (+${enabled.length - named.length} more)`\n : named.join(\", \");\n\n const message = `[cron] ${runtime.platform} detected — in-process timers do not fire while an instance is frozen or scaled to zero, so ${enabled.length} enabled job(s) may never run: ${list}; drive them from an external scheduler instead (POST /api/cron/:id/trigger, e.g. Cloud Scheduler). ${runtime.platform} does not expose its scaling floor to the container, so an always-warm deployment cannot be confirmed from inside the process — set ${CRON_ALWAYS_ON_ENV}=1 to silence this if at least one instance is pinned warm.`;\n\n return {\n message,\n data: {\n platform: runtime.platform,\n signals: runtime.signals,\n jobs: enabled\n }\n };\n}\n","import type {\n CronJobDefinition,\n CronJobStatus,\n CronJobLogEntry,\n CronJobRunState,\n CronJobContext,\n RejectedCronJob\n} from \"@rebasepro/types\";\nimport type { RebaseServerClient } from \"@rebasepro/types\";\nimport { hostname } from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\nimport type { LoadedCronJob } from \"./cron-loader\";\nimport type { CronJobRunSummary, CronStore } from \"./cron-store\";\nimport { logger, redactSensitiveText, stringifyForLog } from \"../utils/logger.js\";\nimport { buildScaleToZeroWarning } from \"./scale-to-zero.js\";\n\n// ─── Cron expression parser (minimal, no external dependency) ────────\n// Supports standard 5-field cron (minute hour dom month dow).\n// Returns the next Date after `after` that matches the expression.\n\n/**\n * Expand a single cron field into an ordered array of allowed values.\n * Supports: `*`, `N`, `N-M`, `N/S`, `N-M/S`, `*\\/S`, and comma-separated combinations.\n */\nfunction expandCronField(field: string, min: number, max: number): number[] {\n const results = new Set<number>();\n for (const segment of field.split(\",\")) {\n const trimmed = segment.trim();\n if (trimmed === \"*\") {\n for (let i = min; i <= max; i++) results.add(i);\n } else if (trimmed.includes(\"/\")) {\n const [rangeStr, stepStr] = trimmed.split(\"/\");\n const step = parseInt(stepStr, 10);\n if (isNaN(step) || step <= 0) {\n throw new Error(`Invalid step value \"${stepStr}\" in cron field \"${field}\"`);\n }\n let start = min;\n let end = max;\n if (rangeStr !== \"*\") {\n if (rangeStr.includes(\"-\")) {\n const [a, b] = rangeStr.split(\"-\").map(Number);\n start = a;\n end = b;\n } else {\n start = parseInt(rangeStr, 10);\n }\n }\n for (let i = start; i <= end; i += step) results.add(i);\n } else if (trimmed.includes(\"-\")) {\n const [a, b] = trimmed.split(\"-\").map(Number);\n for (let i = a; i <= b; i++) results.add(i);\n } else {\n const val = parseInt(trimmed, 10);\n if (isNaN(val)) {\n throw new Error(`Invalid value \"${trimmed}\" in cron field \"${field}\"`);\n }\n results.add(val);\n }\n }\n return [...results].sort((a, b) => a - b);\n}\n\n/**\n * Validates a standard 5-field cron expression structurally and semantically.\n * Returns `{ valid: true }` or `{ valid: false, reason: string }`.\n */\nexport function validateCronExpression(schedule: string): { valid: true } | { valid: false; reason: string } {\n if (!schedule || typeof schedule !== \"string\") {\n return { valid: false,\nreason: \"Schedule must be a non-empty string\" };\n }\n const parts = schedule.trim().split(/\\s+/);\n if (parts.length !== 5) {\n return { valid: false,\nreason: `Expected 5 fields, got ${parts.length}` };\n }\n const fieldRanges: [string, number, number][] = [\n [\"minute\", 0, 59],\n [\"hour\", 0, 23],\n [\"day of month\", 1, 31],\n [\"month\", 1, 12],\n [\"day of week\", 0, 6]\n ];\n for (let i = 0; i < 5; i++) {\n const [name, min, max] = fieldRanges[i];\n try {\n const values = expandCronField(parts[i], min, max);\n if (values.length === 0) {\n return { valid: false,\nreason: `${name} field \"${parts[i]}\" produces no values` };\n }\n for (const v of values) {\n if (v < min || v > max) {\n return { valid: false,\nreason: `${name} field value ${v} out of range [${min}–${max}]` };\n }\n }\n } catch (err) {\n return { valid: false,\nreason: `${name} field: ${err instanceof Error ? err.message : String(err)}` };\n }\n }\n return { valid: true };\n}\n\n/** The five cron fields, pre-expanded into the values each one allows. */\ninterface CronFields {\n minutes: number[];\n hours: number[];\n doms: number[];\n months: number[];\n dows: number[];\n}\n\n/** Expand all five fields of an expression. Throws on invalid expressions. */\nfunction parseCronFields(expression: string): CronFields {\n const parts = expression.trim().split(/\\s+/);\n if (parts.length < 5) {\n throw new Error(`Invalid cron expression: \"${expression}\". Expected 5 fields.`);\n }\n const [minField, hourField, domField, monField, dowField] = parts;\n return {\n minutes: expandCronField(minField, 0, 59),\n hours: expandCronField(hourField, 0, 23),\n doms: expandCronField(domField, 1, 31),\n months: expandCronField(monField, 1, 12),\n dows: expandCronField(dowField, 0, 6) // 0=Sunday\n };\n}\n\n/**\n * Whether an IANA zone name is one this runtime can read a schedule in.\n *\n * `Intl` is the authority: it throws a RangeError on a name it does not know,\n * which is the only check that tracks the tz database the process actually\n * ships. A misspelled zone must fail when the job loads, not silently read\n * the schedule as local time.\n */\nexport function isValidTimeZone(zone: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone });\n return true;\n } catch {\n return false;\n }\n}\n\n/** Wall-clock parts of an instant, in a zone, as the cron fields see them. */\ninterface WallClock {\n minute: number;\n hour: number;\n dom: number;\n month: number;\n dow: number;\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>();\nconst DOW: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };\n\nfunction wallClockIn(candidate: Date, zone: string): WallClock {\n let formatter = formatters.get(zone);\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n hourCycle: \"h23\",\n weekday: \"short\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\"\n });\n formatters.set(zone, formatter);\n }\n const parts: Record<string, string> = {};\n for (const part of formatter.formatToParts(candidate)) parts[part.type] = part.value;\n return {\n minute: Number(parts.minute),\n hour: Number(parts.hour),\n dom: Number(parts.day),\n month: Number(parts.month),\n dow: DOW[parts.weekday] ?? candidate.getDay()\n };\n}\n\n/**\n * Whether a minute-precision instant matches every field of the expression.\n *\n * Read in `zone` when one is named, else in the process's own zone — which is\n * whatever the host is set to, UTC in nearly every container. A schedule that\n * names its zone means the same wall-clock hour on every host it runs on.\n */\nfunction matchesCronFields(candidate: Date, fields: CronFields, zone?: string): boolean {\n const wall: WallClock = zone\n ? wallClockIn(candidate, zone)\n : {\n minute: candidate.getMinutes(),\n hour: candidate.getHours(),\n dom: candidate.getDate(),\n month: candidate.getMonth() + 1, // getMonth is 0-11\n dow: candidate.getDay()\n };\n return fields.months.includes(wall.month)\n && fields.doms.includes(wall.dom)\n && fields.dows.includes(wall.dow)\n && fields.hours.includes(wall.hour)\n && fields.minutes.includes(wall.minute);\n}\n\n/**\n * How far forward to look for the next matching slot.\n *\n * Four years and a day, not one year. `0 0 29 2 *` — run on 29 February — is a\n * legitimate expression whose slot can be almost four years out, and a one-year\n * search never found it.\n */\nconst MAX_SLOT_SEARCH_MINUTES = 4 * 525960 + 1440;\n\nconst MINUTE_MS = 60_000;\n\n/**\n * Calculate the next Date after `after` that matches the cron expression.\n * Throws on invalid expressions.\n */\nexport function parseCronExpression(expression: string, after: Date, timezone?: string): Date {\n const fields = parseCronFields(expression);\n\n // Forward-search from `after + 1 minute`, stepping real minutes. The local\n // setters step wall-clock minutes, and across a daylight-saving change\n // those are not the same: falling back, `setMinutes(+1)` from 02:59 summer\n // time lands on 03:00 winter time, skipping the repeated hour, and inside\n // it the result can be an hour in the past. Only the matching reads the\n // wall clock.\n const candidate = new Date(after);\n candidate.setUTCSeconds(0, 0);\n candidate.setTime(candidate.getTime() + MINUTE_MS);\n\n for (let i = 0; i < MAX_SLOT_SEARCH_MINUTES; i++) {\n if (matchesCronFields(candidate, fields, timezone)) {\n return candidate;\n }\n candidate.setTime(candidate.getTime() + MINUTE_MS);\n }\n\n // No slot inside the window. Refuse rather than invent one.\n //\n // This used to return `after + 1 minute`, which is indistinguishable from a\n // schedule that really does fire every minute — so an expression with no\n // reachable slot ran sixty times an hour, forever. `0 0 29 2 *` was caught\n // by it while the search window was a single year: a job meant to run once\n // every four years became the busiest job on the deployment.\n //\n // The caller schedules inside a `try` and reports a job it could not\n // schedule, which is the correct outcome for an expression that names no\n // time. Genuinely impossible dates (`0 0 31 2 *`) land here too, and should.\n throw new Error(\n `Cron expression \"${expression}\" has no matching time within ` +\n `${Math.round(MAX_SLOT_SEARCH_MINUTES / 525960)} years of ${after.toISOString()}. ` +\n \"Check the day-of-month and month fields — a date such as 31 February never occurs.\"\n );\n}\n\n/**\n * The latest slot matching `expression` within the inclusive window\n * `[from, to]`, or `undefined` when the expression has no slot in it.\n *\n * Walks backwards a minute at a time from `to`, so the first hit is already\n * the answer — in the common case (a job that ran normally moments ago) that\n * is a handful of iterations, not a scan of the whole window.\n *\n * `to`'s own minute is included: an instance booting at 06:00:30 has *not* run\n * the 06:00 slot — `parseCronExpression` already skipped past it to tomorrow —\n * so that slot is genuinely missed and must be a candidate.\n *\n * Seconds and milliseconds are zeroed to match how `parseCronExpression`\n * builds a slot, so the same wall-clock slot serialises to a byte-identical\n * ISO string down either path. The claim key depends on that.\n */\nexport function findMostRecentSlot(expression: string, from: Date, to: Date, timezone?: string): Date | undefined {\n const fields = parseCronFields(expression);\n\n // Real minutes, as in `parseCronExpression`: a local-time step back from\n // 02:00 winter time lands on 01:59 summer time and walks over the repeated\n // hour.\n const candidate = new Date(to);\n candidate.setUTCSeconds(0, 0);\n\n for (let i = 0; i < MAX_SLOT_SEARCH_MINUTES && candidate.getTime() >= from.getTime(); i++) {\n if (matchesCronFields(candidate, fields, timezone)) {\n return candidate;\n }\n candidate.setTime(candidate.getTime() - MINUTE_MS);\n }\n\n return undefined;\n}\n\n// ─── In-memory ring buffer for logs ──────────────────────────────────\n\nconst MAX_LOGS_PER_JOB = 50;\n\n/**\n * Minimum milliseconds between scheduled executions of the same job.\n * Prevents tight re-execution loops caused by jitter or clock drift.\n */\nconst MIN_SCHEDULE_INTERVAL_MS = 5_000; // 5 seconds\n\n/**\n * Largest delay setTimeout can hold. Node stores it in a 32-bit signed int;\n * anything larger silently clamps to 1ms and fires immediately, so a slot\n * further out than this must be reached in hops rather than one timer.\n */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647; // 2^31 - 1, ~24.8 days\n\n/**\n * `setTimeout` for a delay that may exceed {@link MAX_TIMER_DELAY_MS}: armed in\n * hops no longer than the ceiling, re-measured against the deadline on each\n * wake. Returns the function that cancels it.\n */\nfunction setLongTimeout(callback: () => void, delayMs: number): () => void {\n const deadline = Date.now() + delayMs;\n let handle: ReturnType<typeof setTimeout>;\n const arm = () => {\n handle = setTimeout(() => {\n if (Date.now() < deadline) arm();\n else callback();\n }, Math.min(Math.max(deadline - Date.now(), 0), MAX_TIMER_DELAY_MS));\n };\n arm();\n return () => clearTimeout(handle);\n}\n\n/** A run's timeout when its definition names none. */\nconst DEFAULT_TIMEOUT_SECONDS = 300;\n\n/**\n * How long a run lease outlasts the run's own timeout.\n *\n * The lease is timed on the database's clock from the moment it is taken, the\n * timeout on this process's from a moment later; without a margin a lease\n * could lapse a beat before its run is aborted and released, and another\n * process start the job alongside it.\n */\nconst LEASE_GRACE_SECONDS = 30;\n\n/**\n * The lease a run with no timeout (`timeoutSeconds: Infinity`) holds.\n *\n * A lease is released when its run ends, so this only matters in two cases.\n * The holder crashed: the job is blocked — every trigger answered \"already\n * executing\", every slot skipped — until the lease lapses, so it must lapse\n * within an hour rather than never. The run is still going after an hour:\n * from then on another process may start the job beside it. A job that\n * legitimately runs for hours should say so with a finite `timeoutSeconds`,\n * which its lease then follows.\n */\nconst MAX_UNBOUNDED_LEASE_SECONDS = 3600;\n\n/**\n * Whether a log entry records a run that did not happen because one was\n * already executing — on this process, or on another that holds the job's run\n * lease. The shape is the documented marker of a skip, the one the Studio\n * panel reads.\n */\nexport function isAlreadyExecutingSkip(entry: CronJobLogEntry): boolean {\n const result = entry.result;\n return typeof result === \"object\" && result !== null\n && \"skipped\" in result && result.skipped === true\n && \"reason\" in result && result.reason === \"already_executing\";\n}\n\n/**\n * Why `timeoutSeconds` cannot be used, or `undefined` when it can. Infinity is\n * a timeout that never fires; zero, a negative number or NaN would fail every\n * run the moment it started.\n */\nfunction invalidTimeoutReason(timeoutSeconds: number | undefined): string | undefined {\n if (timeoutSeconds === undefined || timeoutSeconds === Infinity) return undefined;\n if (typeof timeoutSeconds === \"number\" && Number.isFinite(timeoutSeconds) && timeoutSeconds > 0) return undefined;\n return `timeoutSeconds must be a positive number of seconds, or Infinity for none — got ${String(timeoutSeconds)}`;\n}\n\n// ─── CronScheduler ───────────────────────────────────────────────────\n\ninterface RegisteredJob {\n id: string;\n definition: CronJobDefinition;\n enabled: boolean;\n state: CronJobRunState;\n lastRunAt?: Date;\n nextRunAt?: Date;\n lastDurationMs?: number;\n lastError?: string;\n totalRuns: number;\n totalFailures: number;\n timerId?: ReturnType<typeof setTimeout>;\n logs: CronJobLogEntry[];\n /** True while a handler is actively executing (prevents concurrent runs). */\n executing: boolean;\n}\n\n/**\n * What this process learned from the store about a job, for a listing: another\n * process running it, and — on a process whose scheduler is not started — its\n * run history and the slot the scheduler will fire next.\n */\ninterface FleetView {\n runningElsewhere?: boolean;\n summary?: CronJobRunSummary;\n nextRunAt?: Date;\n}\n\n/**\n * Whether a run may go ahead. `token` is the lease to release when it ends —\n * absent when no lease was taken, because the store has none or could not\n * answer.\n */\ntype LeaseOutcome =\n | { acquired: true; token?: string }\n | { acquired: false; holder?: string };\n\n/** A job the scheduler refused, with the definition it was refused from. */\ninterface RefusedJob {\n job: RejectedCronJob;\n definition: CronJobDefinition;\n}\n\nexport class CronScheduler {\n private jobs = new Map<string, RegisteredJob>();\n private rejected = new Map<string, RefusedJob>();\n private started = false;\n private store?: CronStore;\n private client?: RebaseServerClient;\n /**\n * Work `stop()` has to wait for: every run executing right now, and every\n * run's log write still on its way to the store.\n */\n private inFlight = new Set<Promise<unknown>>();\n /** The controller that ends each executing run — what `stop()` aborts. */\n private runControllers = new Set<AbortController>();\n /**\n * This process, as a run lease names it: what \"already executing on …\"\n * tells an operator. Each run adds its own suffix, so a release can only\n * ever clear the lease that run took.\n */\n private readonly instanceLabel = `${hostname()}:${process.pid}`;\n\n /**\n * Set the server singleton to make it available to cron job handlers.\n *\n * `RebaseServerClient`, not `RebaseClient`: the object `init.ts` passes is\n * the same one it registers as the singleton, so this was always the true\n * type — and the wider annotation is what let `ctx.client.data` look like a\n * user-scoped plane inside a cron, when it is the admin-scoped one.\n */\n setClient(client: RebaseServerClient): void {\n this.client = client;\n }\n\n /**\n * Attach a persistence store for cron logs.\n * When set, execution logs are written to the database after each run,\n * and counters are seeded from the database on start.\n */\n setStore(store: CronStore): void {\n this.store = store;\n }\n\n /**\n * Register a batch of loaded cron jobs.\n *\n * If the scheduler is already started, newly registered jobs are\n * automatically scheduled (so late-registered jobs don't sit idle).\n *\n * Validates the cron schedule on registration — invalid schedules\n * are rejected with a warning and the job is NOT registered.\n */\n registerJobs(loadedJobs: LoadedCronJob[]): void {\n for (const loaded of loadedJobs) {\n // Validate schedule up-front — reject invalid schedules\n const validation = validateCronExpression(loaded.definition.schedule);\n if (!validation.valid) {\n logger.error(`[cron] Rejecting job \"${loaded.id}\": invalid schedule \"${loaded.definition.schedule}\" — ${validation.reason}`);\n // Kept, not just logged. A rejected job is absent from\n // `listJobs()`, so from the Studio panel it is indistinguishable\n // from a file that was never written — and the commonest reason\n // to land here is a 6-field expression copied from a tool that\n // supports seconds, which is a one-character fix nobody could\n // see without boot-log access.\n this.refuse(loaded, validation.reason);\n continue;\n }\n // Rejected, not read as local time: a misspelled zone that fell\n // back silently would fire at the wrong hour on every host and\n // look like a scheduler bug. Kept in `rejected` for the same reason\n // a bad schedule is — otherwise the panel cannot tell it from a\n // file nobody wrote.\n if (loaded.definition.timezone !== undefined && !isValidTimeZone(loaded.definition.timezone)) {\n const reason =\n `unknown timezone \"${loaded.definition.timezone}\" — ` +\n 'use an IANA name such as \"Europe/Madrid\" or \"UTC\"';\n logger.error(`[cron] Rejecting job \"${loaded.id}\": ${reason}.`);\n this.refuse(loaded, reason);\n continue;\n }\n // Same treatment: a timeout that fails every run the moment it\n // starts is a configuration error, not a run-time one.\n const timeoutProblem = invalidTimeoutReason(loaded.definition.timeoutSeconds);\n if (timeoutProblem) {\n logger.error(`[cron] Rejecting job \"${loaded.id}\": ${timeoutProblem}.`);\n this.refuse(loaded, timeoutProblem);\n continue;\n }\n // A re-register that now validates clears the earlier complaint.\n this.rejected.delete(loaded.id);\n\n const existing = this.jobs.get(loaded.id);\n if (existing) {\n logger.warn(`[cron] Duplicate cron job id: \"${loaded.id}\". Overwriting.`);\n this.stopJob(loaded.id);\n }\n\n const enabled = loaded.definition.enabled !== false;\n\n const job: RegisteredJob = {\n id: loaded.id,\n definition: loaded.definition,\n enabled,\n state: enabled ? \"idle\" : \"disabled\",\n totalRuns: 0,\n totalFailures: 0,\n logs: [],\n executing: false\n };\n this.jobs.set(loaded.id, job);\n\n // If the scheduler is already running, auto-schedule new jobs\n if (this.started && this.shouldArm(job)) {\n this.scheduleNext(loaded.id);\n }\n }\n }\n\n /**\n * Start the scheduler — begins ticking all enabled jobs.\n */\n start(): void {\n if (this.started) return;\n this.started = true;\n\n // Seed counters from DB (non-blocking — scheduler starts immediately)\n if (this.store) {\n this.store.fetchJobStats().then((stats) => {\n for (const [jobId, data] of stats) {\n const job = this.jobs.get(jobId);\n if (job) {\n job.totalRuns = data.totalRuns;\n job.totalFailures = data.totalFailures;\n if (data.lastRunAt) {\n job.lastRunAt = new Date(data.lastRunAt);\n }\n }\n }\n }).catch((err) => {\n logger.warn(\"[cron] Failed to seed job stats from database\", { error: err });\n });\n }\n\n for (const [id, job] of this.jobs) {\n if (this.shouldArm(job)) {\n this.scheduleNext(id);\n }\n }\n if (!this.store) {\n logger.warn(\"[cron] No cron store attached — runs are uncoordinated; with multiple app instances every instance will execute every job\");\n }\n this.warnIfScaleToZero();\n\n // Recover slots that elapsed while nothing was ticking. Deliberately\n // not awaited: catch-up reaches the database and runs handlers, and\n // boot must not wait on either. Its own errors are contained inside.\n void this.catchUpMissedSlots();\n\n logger.info(`⏰ Cron scheduler started with ${this.jobs.size} job(s)`);\n }\n\n /**\n * Stop the scheduler: clear every timer, then wait for the runs executing\n * right now — for at most `timeoutMs` when given.\n *\n * A run still going when the budget runs out has its `ctx.signal` aborted\n * and ends there, recorded as a failure that says why. Its slot stays\n * claimed, so no other instance re-runs it; a handler that must not be cut\n * short should watch its signal and leave its work resumable.\n *\n * Nothing is scheduled after `stop()`, whether or not the returned promise\n * is awaited: the timers are cleared before it first yields.\n */\n async stop(timeoutMs?: number): Promise<void> {\n this.started = false;\n for (const [id] of this.jobs) {\n this.stopJob(id);\n }\n if (this.inFlight.size === 0) return;\n\n const settled = Promise.allSettled([...this.inFlight]).then(() => true);\n if (timeoutMs === undefined) {\n await settled;\n return;\n }\n let budget: ReturnType<typeof setTimeout> | undefined;\n const finished = await Promise.race([\n settled,\n new Promise<false>((resolve) => {\n budget = setTimeout(() => resolve(false), timeoutMs);\n if (budget && typeof budget === \"object\" && \"unref\" in budget) {\n budget.unref();\n }\n })\n ]);\n clearTimeout(budget);\n if (finished || this.runControllers.size === 0) return;\n\n logger.warn(`[cron] ${this.runControllers.size} run(s) still executing after ${timeoutMs}ms — aborting them`);\n for (const controller of this.runControllers) {\n controller.abort(new Error(\"The server is shutting down; the run was stopped before it finished\"));\n }\n }\n\n /**\n * List all registered jobs with their current status.\n */\n listJobs(): CronJobStatus[] {\n return [...this.jobs.values()].map((job) => this.toStatus(job));\n }\n\n /** Keep a refused job, so the admin surface can say why it never runs. */\n private refuse(loaded: LoadedCronJob, reason: string): void {\n this.rejected.set(loaded.id, {\n job: {\n id: loaded.id,\n name: loaded.definition.name ?? loaded.id,\n schedule: loaded.definition.schedule,\n reason\n },\n definition: loaded.definition\n });\n }\n\n /**\n * Jobs that loaded but whose schedule the scheduler refused.\n *\n * Kept apart from {@link listJobs} because they are not jobs — nothing will\n * run them — but they must be reachable, or \"my cron is missing\" and \"my\n * cron will never fire\" look identical from the admin panel.\n */\n listRejectedJobs(): RejectedCronJob[] {\n return [...this.rejected.values()].map(refused => refused.job);\n }\n\n /**\n * {@link listRejectedJobs}, those whose definition matches — how a surface\n * finds a refused job by what it is, as {@link jobIdsWhere} does for the\n * registered ones.\n */\n rejectedJobsWhere(predicate: (definition: CronJobDefinition) => boolean): RejectedCronJob[] {\n return [...this.rejected.values()].filter(refused => predicate(refused.definition)).map(refused => refused.job);\n }\n\n /**\n * The ids of the registered jobs whose definition matches — how a surface\n * finds a job by what it is rather than by the file it happens to live in.\n */\n jobIdsWhere(predicate: (definition: CronJobDefinition) => boolean): string[] {\n return [...this.jobs.values()].filter(job => predicate(job.definition)).map(job => job.id);\n }\n\n /**\n * Get a single job status by ID.\n */\n getJob(id: string): CronJobStatus | undefined {\n const job = this.jobs.get(id);\n return job ? this.toStatus(job) : undefined;\n }\n\n /**\n * {@link listJobs}, as the fleet sees it rather than this process alone.\n *\n * Reads the store: every job's enabled state — a pause another replica\n * made — whether another process holds its run lease, and each job's run\n * count and last run from `cron_logs`. The counters in this process's\n * memory count only the runs it made: the `api` role runs nothing and\n * would say 0 runs for a job the worker has run a thousand times, and one\n * of two scheduling replicas never sees the slots the other one claimed.\n *\n * A store that cannot answer leaves this process's own view, with a\n * warning: a listing is not worth failing.\n */\n async fetchJobs(): Promise<CronJobStatus[]> {\n const jobs = [...this.jobs.values()];\n const views = await this.readFleet(jobs);\n return jobs.map(job => this.toStatus(job, views.get(job.id)));\n }\n\n /** {@link getJob}, as {@link fetchJobs} reads it. */\n async fetchJob(id: string): Promise<CronJobStatus | undefined> {\n const job = this.jobs.get(id);\n if (!job) return undefined;\n const views = await this.readFleet([job]);\n return this.toStatus(job, views.get(id));\n }\n\n /**\n * Get log entries for a job.\n */\n getJobLogs(id: string, limit?: number): CronJobLogEntry[] {\n const job = this.jobs.get(id);\n if (!job) return [];\n const logs = [...job.logs].reverse(); // newest first\n return limit ? logs.slice(0, limit) : logs;\n }\n\n /**\n * Get log entries for a job from the database (if store is available).\n * Falls back to in-memory logs if no store is configured, or if the store\n * has none — a run whose row is still being written.\n *\n * Throws when the store cannot read the history. This process's memory is\n * not a stand-in for it: it is empty on the `api` role and after a\n * restart, and holds one replica's runs at most.\n */\n async getJobLogsFromDb(id: string, limit?: number): Promise<CronJobLogEntry[]> {\n if (this.store) {\n const dbLogs = await this.store.fetchLogs(id, limit);\n if (dbLogs.length > 0) return dbLogs;\n }\n // Fallback to in-memory\n return this.getJobLogs(id, limit);\n }\n\n /**\n * Enable or disable a job in this process only. `null` returns it to what\n * its code declares.\n *\n * {@link persistJobEnabled} is what the admin API calls: this alone is\n * forgotten on restart and reaches no other replica.\n */\n setJobEnabled(id: string, enabled: boolean | null): CronJobStatus | undefined {\n const job = this.jobs.get(id);\n if (!job) return undefined;\n\n const effective = enabled ?? this.codeEnabled(job);\n this.applyEnabled(job, effective);\n\n if (effective && this.started) {\n this.scheduleNext(id);\n } else if (!this.shouldArm(job)) {\n this.stopJob(id);\n }\n\n return this.toStatus(job);\n }\n\n /**\n * Enable or disable a job for every process that runs it, and keep it that\n * way across restarts and redeploys: `true` or `false` overrides the code's\n * `enabled`, `null` hands the decision back to it.\n *\n * The override is written to the store first, and only then applied here,\n * so a write that fails throws and changes nothing — a pause that only the\n * replica serving the request would honour is the failure this exists to\n * end. Every scheduler reads the override when a slot comes due, before it\n * claims the slot.\n *\n * Without a store that keeps the state (a driver with no SQL, persistence\n * switched off, a custom store) this is {@link setJobEnabled}: local, and\n * gone on restart.\n */\n async persistJobEnabled(id: string, enabled: boolean | null, updatedBy?: string): Promise<CronJobStatus | undefined> {\n if (!this.jobs.has(id)) return undefined;\n if (this.store?.saveEnabledOverride) {\n await this.store.saveEnabledOverride(id, enabled, updatedBy);\n }\n return this.setJobEnabled(id, enabled);\n }\n\n /**\n * Manually trigger a job execution immediately.\n *\n * Returns `undefined` if the job doesn't exist.\n * If the job is currently executing — here, or on another process that\n * holds its run lease — returns the log entry with a `skipped: true`\n * result rather than running concurrently; {@link isAlreadyExecutingSkip}\n * recognises it.\n */\n async triggerJob(id: string): Promise<CronJobLogEntry | undefined> {\n const job = this.jobs.get(id);\n if (!job) return undefined;\n\n // Concurrency guard — don't run two instances simultaneously\n if (job.executing) {\n logger.warn(`[cron] Skipping manual trigger of \"${id}\" — already executing`);\n return this.recordSkip(job, \"already_executing\", true);\n }\n\n return this.executeJob(job, true);\n }\n\n /**\n * Record a run that did not happen because the previous one had not\n * finished.\n *\n * Written to `cron_logs`, not only to the in-memory ring. An overlap is the\n * signature of a job that has outgrown its schedule — the one thing you want\n * to see in the history rather than infer from a gap in it — and until now\n * the scheduled path left no trace at all beyond a warning in the process\n * log, which is gone by the time anyone asks. The manual path wrote a ring\n * entry that vanished on restart.\n *\n * `success: true` is deliberate: nothing failed. The `result.skipped` flag\n * and the reason are what distinguishes it, and the Studio panel reads them.\n */\n private recordSkip(job: RegisteredJob, reason: string, manual: boolean, runningOn?: string): CronJobLogEntry {\n const now = new Date().toISOString();\n const why = reason === \"already_executing\" ? \"the previous run has not finished\" : reason;\n const logEntry: CronJobLogEntry = {\n jobId: job.id,\n startedAt: now,\n finishedAt: now,\n durationMs: 0,\n success: true,\n result: { skipped: true, reason },\n logs: [`Skipped: ${why}${runningOn ? ` — it is running on ${runningOn}` : \"\"}`],\n manual\n };\n\n job.logs.push(logEntry);\n if (job.logs.length > MAX_LOGS_PER_JOB) job.logs.shift();\n\n // Tracked like a run's own write, so a shutdown does not close the pool\n // under it.\n if (this.store) {\n this.track(this.store.insertLog(logEntry).catch((persistErr) => {\n logger.error(`[cron] Failed to persist skip for \"${job.id}\"`, { error: persistErr });\n }));\n }\n\n return logEntry;\n }\n\n // ─── Internal ────────────────────────────────────────────────────\n\n /** What the job's own definition says, before any override. */\n private codeEnabled(job: RegisteredJob): boolean {\n return job.definition.enabled !== false;\n }\n\n /**\n * Whether the enabled state lives in the store, where every process reads\n * it, rather than in this process alone.\n */\n private sharesEnabledState(): boolean {\n return Boolean(this.store?.fetchJobStates && this.store.saveEnabledOverride);\n }\n\n /**\n * Whether a job gets a timer here. A job paused in this process's memory\n * needs none — nothing but this process can resume it. A job whose state\n * the store keeps does, paused or not: another replica may resume it, and\n * reading the state when its slot comes due is how this one finds out.\n */\n private shouldArm(job: RegisteredJob): boolean {\n return job.enabled || this.sharesEnabledState();\n }\n\n /** Set a job's enabled flag, and its state with it unless a run is in progress. */\n private applyEnabled(job: RegisteredJob, enabled: boolean): void {\n job.enabled = enabled;\n if (job.executing) return;\n if (!enabled) job.state = \"disabled\";\n else if (job.state === \"disabled\") job.state = \"idle\";\n }\n\n /**\n * Whether a job may run now: the store's override when it keeps one, else\n * the code's `enabled`.\n *\n * One query per fire, before the slot is claimed — a paused job does not\n * spend its slot. A store that cannot answer falls back to the code's\n * `enabled`, with a warning: a scheduled run fails open, as it does when\n * the claims table cannot answer, because a broken state table must not\n * silently stop every job.\n */\n private async isEnabledNow(job: RegisteredJob): Promise<boolean> {\n if (!this.store?.fetchJobStates || !this.sharesEnabledState()) return job.enabled;\n try {\n const state = (await this.store.fetchJobStates([job.id])).get(job.id);\n const enabled = state?.enabled ?? this.codeEnabled(job);\n this.applyEnabled(job, enabled);\n return enabled;\n } catch (err) {\n const enabled = this.codeEnabled(job);\n logger.warn(\n `[cron] Could not read the enabled state of \"${job.id}\" — falling back to the code's ` +\n `enabled (${enabled}); a pause made from the admin API is not being honoured`,\n { error: err }\n );\n return enabled;\n }\n }\n\n /**\n * How long a run's lease lasts: the run's timeout and a grace, so that a\n * crashed holder frees the job once its run would have been aborted\n * anyway. No timeout gets {@link MAX_UNBOUNDED_LEASE_SECONDS}.\n */\n private leaseSeconds(job: RegisteredJob): number {\n const timeout = job.definition.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n return Number.isFinite(timeout) ? timeout + LEASE_GRACE_SECONDS : MAX_UNBOUNDED_LEASE_SECONDS;\n }\n\n /**\n * Take the job's run lease, the cross-process half of \"already\n * executing\". A store without leases, or one that cannot answer, lets the\n * run go ahead unleased — with a warning in the second case — the same way\n * a claim that cannot answer does.\n */\n private async acquireLease(job: RegisteredJob): Promise<LeaseOutcome> {\n if (!this.store?.tryAcquireRunLease) return { acquired: true };\n const token = `${this.instanceLabel}#${randomUUID().slice(0, 8)}`;\n try {\n const lease = await this.store.tryAcquireRunLease(job.id, token, this.leaseSeconds(job));\n return lease.acquired ? { acquired: true, token } : lease;\n } catch (err) {\n logger.warn(\n `[cron] Could not take the run lease for \"${job.id}\" — running without it, ` +\n \"so another process may run it at the same time\",\n { error: err }\n );\n return { acquired: true };\n }\n }\n\n /** Release a lease this run took. A release that fails leaves it to lapse. */\n private async releaseLease(job: RegisteredJob, token: string): Promise<void> {\n try {\n await this.store?.releaseRunLease?.(job.id, token);\n } catch (err) {\n logger.warn(\n `[cron] Could not release the run lease for \"${job.id}\" — it lapses on its own ` +\n `within ${this.leaseSeconds(job)}s`,\n { error: err }\n );\n }\n }\n\n /**\n * What the store says about `jobs` beyond this process — see\n * {@link fetchJobs}. Applies the enabled state it reads, and returns the\n * rest as a view for {@link toStatus}. Never throws.\n */\n private async readFleet(jobs: RegisteredJob[]): Promise<Map<string, FleetView>> {\n const views = new Map<string, FleetView>();\n const viewOf = (id: string): FleetView => {\n let view = views.get(id);\n if (!view) {\n view = {};\n views.set(id, view);\n }\n return view;\n };\n const store = this.store;\n const ids = jobs.map(job => job.id);\n\n if (store?.fetchJobStates && this.sharesEnabledState() && ids.length > 0) {\n try {\n const states = await store.fetchJobStates(ids);\n for (const job of jobs) {\n const state = states.get(job.id);\n this.applyEnabled(job, state?.enabled ?? this.codeEnabled(job));\n if (state?.runningBy && !job.executing) viewOf(job.id).runningElsewhere = true;\n }\n } catch (err) {\n logger.warn(\"[cron] Could not read the jobs' shared state — listing what this process knows\", { error: err });\n }\n }\n\n // Only where nothing is scheduled: a started scheduler has its own next\n // slots.\n if (!this.started) {\n const now = new Date();\n for (const job of jobs) {\n try {\n viewOf(job.id).nextRunAt = parseCronExpression(job.definition.schedule, now, job.definition.timezone);\n } catch {\n // A schedule with no reachable slot has no next run to show.\n }\n }\n }\n // Wherever this process stands. Its own counters are seeded from\n // `cron_logs` once, at start, and after that count only its own runs:\n // with two replicas scheduling, a slot the other one claimed never\n // reached them, and the card said \"idle, 0 runs\" over a history that\n // listed the failure.\n if (store?.fetchRunSummaries && ids.length > 0) {\n try {\n const summaries = await store.fetchRunSummaries(ids);\n for (const [id, summary] of summaries) viewOf(id).summary = summary;\n } catch (err) {\n logger.warn(\"[cron] Could not read the jobs' run history — listing what this process knows\", { error: err });\n }\n }\n return views;\n }\n\n /**\n * Warn once at start when the process looks like it is running on a\n * platform that freezes or evicts instances between requests, where the\n * in-process timers this scheduler relies on never fire.\n *\n * Advisory only: any failure here is swallowed so a detection bug can\n * never take a production boot down.\n */\n private warnIfScaleToZero(): void {\n try {\n const warning = buildScaleToZeroWarning(\n [...this.jobs.values()].map((job) => ({ id: job.id, enabled: job.enabled }))\n );\n if (warning) {\n logger.warn(warning.message, warning.data);\n }\n } catch {\n // Never let the advisory check affect startup.\n }\n }\n\n /**\n * Schedule the next execution for a job.\n *\n * Safety guarantees:\n * 1. Clears any existing timer first (prevents leaked/duplicate timers)\n * 2. Enforces a minimum delay to prevent tight loops from jitter\n * 3. Unref's the timer so it doesn't prevent process exit\n * 4. Re-checks enabled & started state before executing\n * 5. Concurrency guard prevents overlapping handler executions\n */\n private scheduleNext(id: string): void {\n const job = this.jobs.get(id);\n if (!job || !this.started || !this.shouldArm(job)) return;\n\n // Clear any previously scheduled timer to prevent double-firing\n this.stopJob(id);\n\n try {\n const now = new Date();\n const nextRun = parseCronExpression(job.definition.schedule, now, job.definition.timezone);\n job.nextRunAt = nextRun;\n\n const rawDelay = nextRun.getTime() - now.getTime();\n // Enforce a minimum delay to prevent tight re-execution loops\n // from event loop jitter or near-zero setTimeout drift\n const delay = Math.max(rawDelay, MIN_SCHEDULE_INTERVAL_MS);\n\n // A slot past the 32-bit timer ceiling cannot be armed directly:\n // setTimeout would clamp it to 1ms and fire at once, and since the\n // slot is already claimed by then, every wake re-schedules the same\n // overflowing delay — a permanent hot loop, not a late job. Sleep\n // to the ceiling and re-derive the delay on waking instead; the\n // cron expression stays the source of truth across the hops.\n if (delay > MAX_TIMER_DELAY_MS) {\n const hop = setTimeout(() => {\n if (this.started && this.shouldArm(job)) this.scheduleNext(id);\n }, MAX_TIMER_DELAY_MS);\n if (hop && typeof hop === \"object\" && \"unref\" in hop) {\n hop.unref();\n }\n job.timerId = hop;\n return;\n }\n\n const timer = setTimeout(async () => {\n // Re-check state: the scheduler may have been stopped between\n // when we scheduled and when we fire\n if (!this.started) return;\n\n // A timer can wake before its slot: a delay past the 32-bit\n // ceiling, a clock stepped backwards by NTP, a VM resuming from\n // suspend. Claiming on an early wake is unrecoverable — claims\n // are permanent, so the slot would be burned and the real run\n // silently skipped when it came due. Re-derive from the wall\n // clock and re-arm instead; only the fire that is genuinely due\n // may claim.\n if (Date.now() < nextRun.getTime()) {\n this.scheduleNext(id);\n return;\n }\n\n // Paused or resumed — perhaps by another replica, perhaps\n // before this process started. Asked of the store at every\n // fire, and before the claim, so a paused job leaves its slot\n // unspent.\n if (!(await this.isEnabledNow(job))) {\n if (this.started && this.shouldArm(job)) this.scheduleNext(id);\n return;\n }\n if (!this.started) return;\n\n // Concurrency guard: if somehow we're already executing, skip\n if (job.executing) {\n logger.warn(`[cron] Skipping scheduled run of \"${id}\" — still executing from previous run`);\n // Recorded as well as logged: a job that keeps overlapping\n // has outgrown its schedule, and that is visible in the run\n // history or nowhere.\n this.recordSkip(job, \"already_executing\", false);\n // Re-schedule to try again later\n this.scheduleNext(id);\n return;\n }\n\n // Cross-instance guard: claim the scheduled slot in the store.\n // The slot is the scheduled fire time — deterministic across\n // instances — so exactly one instance wins each (job, slot) pair.\n // A store without tryClaimRun (pre-claims custom implementation)\n // runs uncoordinated; a throwing store fails open — either way\n // this callback must never reject, or the job would silently\n // stop rescheduling.\n if (this.store?.tryClaimRun) {\n let claimed = true;\n try {\n claimed = await this.store.tryClaimRun(id, nextRun.toISOString());\n } catch (err) {\n logger.warn(`[cron] Claim check threw for \"${id}\" — running uncoordinated`, { error: err });\n }\n if (!claimed) {\n logger.info(`[cron] Slot ${nextRun.toISOString()} for \"${id}\" claimed by another instance — skipping`);\n if (this.started && this.shouldArm(job)) {\n this.scheduleNext(id);\n }\n return;\n }\n }\n\n // Takes the run lease: a manual trigger in progress on another\n // process — the api role's, say — turns this slot into a\n // recorded skip rather than a second run beside it.\n await this.executeJob(job, false);\n\n // Schedule the next tick (only if still started + armed)\n if (this.started && this.shouldArm(job)) {\n this.scheduleNext(id);\n }\n }, delay);\n\n // Unref the timer so it doesn't prevent Node.js from exiting\n // during graceful shutdown\n if (timer && typeof timer === \"object\" && \"unref\" in timer) {\n timer.unref();\n }\n\n job.timerId = timer;\n } catch (err: unknown) {\n logger.error(`[cron] Failed to schedule \"${id}\"`, { error: err });\n job.state = \"error\";\n job.lastError = err instanceof Error ? err.message : String(err);\n }\n }\n\n /**\n * Run any slot that elapsed while no instance was holding a timer for it.\n *\n * Only jobs that opted in via `catchUpWindowSeconds` are considered, and\n * only their single most recent missed slot — see the field's docs for why\n * both limits are deliberate.\n *\n * The claim is what makes this safe. In the ordinary case — an instance\n * restarting minutes after a slot ran normally — the most recent slot is\n * already claimed, so this costs one `tryClaimRun` per job per boot and\n * does nothing. A slot is only executed when no instance, past or present,\n * ever claimed it.\n *\n * Never throws: a failure here must not take down a scheduler that is\n * otherwise ticking correctly.\n */\n private async catchUpMissedSlots(): Promise<void> {\n // Every job with a window whose state the store may override, not only\n // the ones enabled here: a job the code disables can be resumed from\n // the admin API, and one it enables can be paused there. Each is asked\n // below, before its claim.\n const candidates = [...this.jobs.values()].filter(\n job => this.shouldArm(job) && (job.definition.catchUpWindowSeconds ?? 0) > 0\n );\n if (candidates.length === 0) return;\n\n // A claims-capable store is the whole safety mechanism. Without one,\n // every boot would look like \"this slot never ran\" and an instance\n // recycled twice an hour would re-run the same hourly job twice an\n // hour. Refusing to catch up is the correct degradation.\n if (!this.store?.tryClaimRun) {\n logger.warn(\n `[cron] Catch-up is configured on ${candidates.length} job(s) but no claims-capable store is attached — skipping. ` +\n \"Without claims a restart cannot tell an unrun slot from one the previous instance already ran.\"\n );\n return;\n }\n\n for (const job of candidates) {\n try {\n if (!this.started || job.executing) continue;\n // The persisted pause outlives the deploy that is catching up.\n if (!(await this.isEnabledNow(job))) continue;\n if (!this.started || job.executing) continue;\n\n // Read per job, not once for the pass: the jobs ahead of this\n // one ran their catch-ups first, and this job's own timer may\n // have fired newer slots meanwhile. Its most recent slot is the\n // one as of now, or a stale one runs after newer ones already did.\n const now = new Date();\n const windowSeconds = job.definition.catchUpWindowSeconds!;\n const from = new Date(now.getTime() - windowSeconds * 1000);\n const slot = findMostRecentSlot(job.definition.schedule, from, now, job.definition.timezone);\n if (!slot) continue;\n\n const slotIso = slot.toISOString();\n\n // Same key the scheduled path claims with, so a slot that fired\n // normally is already taken and this is a no-op.\n let claimed: boolean;\n try {\n claimed = await this.store.tryClaimRun(job.id, slotIso);\n } catch (err) {\n // Fail closed, unlike the scheduled path. A missed slot is\n // a recovery, not an obligation — running it against a\n // store that cannot tell us whether it already ran risks a\n // duplicate on every boot.\n logger.warn(`[cron] Catch-up claim threw for \"${job.id}\" — skipping catch-up`, { error: err });\n continue;\n }\n\n if (!claimed) continue;\n\n const lateBy = Math.round((now.getTime() - slot.getTime()) / 1000);\n logger.info(`[cron] Catching up missed slot ${slotIso} for \"${job.id}\" (${lateBy}s late)`);\n\n await this.executeJob(job, false, `⏰ Catch-up run for missed slot ${slotIso} (${lateBy}s late)`);\n } catch (err) {\n logger.error(`[cron] Catch-up failed for \"${job.id}\"`, { error: err });\n }\n }\n }\n\n /**\n * Stop a single job's timer and clear its next run state.\n */\n private stopJob(id: string): void {\n const job = this.jobs.get(id);\n if (job?.timerId) {\n clearTimeout(job.timerId);\n job.timerId = undefined;\n job.nextRunAt = undefined;\n }\n }\n\n /**\n * Execute a job's handler with full isolation and safety.\n *\n * - Sets a concurrency flag to prevent overlapping runs\n * - Wraps handler in a timeout race\n * - Captures all logs, errors, and results\n * - Persists to store (non-blocking) if available\n * - Always restores state even on catastrophic errors\n */\n private executeJob(\n job: RegisteredJob,\n manual: boolean,\n seedLog?: string\n ): Promise<CronJobLogEntry> {\n // Aborted when the run is over before its handler is: the timeout\n // below, or `stop()` giving up on it. Without it the timeout only\n // stopped the scheduler waiting: the handler's `fetch` kept its socket,\n // so a job whose timeout matches its interval leaked one abandoned\n // request per tick while every run was already marked failed.\n const abort = new AbortController();\n this.runControllers.add(abort);\n const run = this.runJob(job, manual, abort, seedLog);\n this.track(run);\n return run.finally(() => {\n this.runControllers.delete(abort);\n });\n }\n\n /** Hold `stop()` until `work` settles. */\n private track(work: Promise<unknown>): void {\n this.inFlight.add(work);\n const release = () => { this.inFlight.delete(work); };\n work.then(release, release);\n }\n\n private async runJob(\n job: RegisteredJob,\n manual: boolean,\n abort: AbortController,\n seedLog?: string\n ): Promise<CronJobLogEntry> {\n // Checked here as well as by each caller, because each caller awaits\n // something (a claim, a state read) between its own check and this.\n if (job.executing) {\n return this.recordSkip(job, \"already_executing\", manual);\n }\n // Set executing flag — prevents concurrent runs. Taken before the lease\n // is awaited, so a second trigger on this process cannot slip in.\n job.executing = true;\n\n // The lease is what keeps the other processes off: the worker's\n // scheduled run and the api role's manual trigger never saw each\n // other's in-process flag.\n const lease = await this.acquireLease(job);\n if (!lease.acquired) {\n job.executing = false;\n logger.warn(`[cron] Skipping ${manual ? \"manual trigger\" : \"scheduled run\"} of \"${job.id}\" — it is running on ${lease.holder ?? \"another process\"}`);\n return this.recordSkip(job, \"already_executing\", manual, lease.holder ?? \"another process\");\n }\n\n const startedAt = new Date();\n // A caller-supplied first line, stored with the run's own output. A\n // catch-up uses it to say so in the persisted log, where an operator\n // reading `cron_logs` will actually see it — `manual` is the only other\n // provenance the entry carries, and a catch-up is not manual.\n const capturedLogs: string[] = seedLog ? [seedLog] : [];\n\n const ctx: CronJobContext = {\n jobId: job.id,\n scheduledAt: startedAt,\n signal: abort.signal,\n log: (...args: unknown[]) => {\n const line = args.map((a) =>\n typeof a === \"string\" ? a : JSON.stringify(a)\n ).join(\" \");\n capturedLogs.push(line);\n // Also to the process log. `cron_logs` is behind the admin\n // API, so a line that went only there was missing from the\n // platform's logs, which is where an operator looks when a\n // run goes wrong. The values are redacted on the way: a\n // stringified object reaches the logger as text, and the\n // logger's own pass over the message only removes `Failed\n // query:` spans from it.\n logger.info(\n args.map((a) => typeof a === \"string\" ? a : stringifyForLog(a)).join(\" \"),\n { cron: job.id }\n );\n },\n // `rebase`, and only `rebase`: it matches the singleton import and\n // `defineFunction`'s context. The old `client` alias re-exposed\n // `client.data`, the name `RebaseServerClient` deliberately omits so\n // that the RLS-bypassing plane is spelled `dataAsAdmin` everywhere.\n rebase: this.client!\n };\n\n job.state = \"running\";\n job.lastRunAt = startedAt;\n job.totalRuns++;\n\n let success = true;\n let error: string | undefined;\n let result: unknown;\n\n // The run ends when the handler settles or when `abort` fires,\n // whichever is first — so an abort ends the run even for a handler\n // that ignores its signal, and the run is recorded rather than left\n // \"running\" forever.\n const aborted = new Promise<never>((_, reject) => {\n const end = () => reject(abort.signal.reason);\n if (abort.signal.aborted) end();\n else abort.signal.addEventListener(\"abort\", end, { once: true });\n });\n // Handled here as well as by the race: a handler that throws before\n // the race is entered leaves nothing else listening.\n aborted.catch(() => undefined);\n\n try {\n // Race with timeout. Past the 32-bit timer ceiling a plain\n // setTimeout fires after 1ms, so a month-long timeout would fail\n // every run at once; Infinity is no timeout at all.\n const timeout = (job.definition.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n const cancelTimeout = Number.isFinite(timeout)\n ? setLongTimeout(\n () => abort.abort(new Error(`Cron job \"${job.id}\" timed out after ${timeout}ms`)),\n timeout\n )\n : undefined;\n\n try {\n result = await Promise.race([Promise.resolve(job.definition.handler(ctx)), aborted]);\n } finally {\n cancelTimeout?.();\n }\n } catch (err: unknown) {\n success = false;\n // Redacted at the point of capture, not just on the way to the log:\n // this string is persisted into `cron_logs` and rendered in the\n // Studio cron panel, and a job that fails on a query would\n // otherwise store `Failed query: <sql>\\nparams: <values>` — the\n // statement and every bound value — in a table, indefinitely.\n error = redactSensitiveText(err instanceof Error ? err.message : String(err));\n job.totalFailures++;\n } finally {\n // The lease before the flag: in between, a trigger on this process\n // would pass the flag and then find its own process's lease held.\n if (lease.token) await this.releaseLease(job, lease.token);\n // Always clear executing flag — even on catastrophic errors\n job.executing = false;\n }\n\n const finishedAt = new Date();\n const durationMs = finishedAt.getTime() - startedAt.getTime();\n\n job.state = success ? (job.enabled ? \"idle\" : \"disabled\") : \"error\";\n job.lastDurationMs = durationMs;\n job.lastError = error;\n\n const logEntry: CronJobLogEntry = {\n jobId: job.id,\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n durationMs,\n success,\n error,\n result: result !== undefined ? result : undefined,\n logs: capturedLogs,\n manual\n };\n\n // Push to ring buffer\n job.logs.push(logEntry);\n if (job.logs.length > MAX_LOGS_PER_JOB) {\n job.logs.shift();\n }\n\n // Persist to database (non-blocking for the run, but tracked, so a\n // shutdown does not close the pool under the write)\n if (this.store) {\n this.track(this.store.insertLog(logEntry).catch((persistErr) => {\n logger.error(`[cron] Failed to persist log for \"${job.id}\"`, { error: persistErr });\n }));\n }\n\n if (success) {\n logger.info(`✅ [cron] \"${job.id}\" completed in ${durationMs}ms`);\n } else {\n logger.error(`❌ [cron] \"${job.id}\" failed in ${durationMs}ms: ${error}`);\n }\n\n return logEntry;\n }\n\n /**\n * A job's status: this process's own record, overlaid with what `view`\n * read from the store. A paused job shows no next run, even where its\n * timer stays armed to read the state again at that slot.\n */\n private toStatus(job: RegisteredJob, view: FleetView = {}): CronJobStatus {\n const summary = view.summary;\n const nextRunAt = job.enabled ? (job.nextRunAt ?? view.nextRunAt) : undefined;\n let state = job.state;\n if (!job.executing) {\n if (view.runningElsewhere) state = \"running\";\n else if (summary && job.enabled) state = summary.lastSuccess === false ? \"error\" : \"idle\";\n }\n return {\n id: job.id,\n // Same fallback the two `listJobs` paths already applied: `name` is\n // optional and the id is the file's own name.\n name: job.definition.name ?? job.id,\n description: job.definition.description,\n schedule: job.definition.schedule,\n enabled: job.enabled,\n state,\n lastRunAt: summary ? summary.lastRunAt : job.lastRunAt?.toISOString(),\n nextRunAt: nextRunAt?.toISOString(),\n lastDurationMs: summary ? summary.lastDurationMs : job.lastDurationMs,\n lastError: summary ? (summary.lastSuccess === false ? summary.lastError : undefined) : job.lastError,\n totalRuns: summary ? summary.totalRuns : job.totalRuns,\n totalFailures: summary ? summary.totalFailures : job.totalFailures\n };\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAM,sBAAM,IAAI,IAAI;CAAC;CAAQ;CAAK;CAAO;AAAI,CAAC;AAC9C,IAAM,qBAAK,IAAI,IAAI;CAAC;CAAS;CAAK;CAAM;AAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC9C,SAAgB,gBAAgB,OAAgD;CAC5E,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY;CACzC,IAAI,IAAI,IAAI,OAAO,GAAG,OAAO;CAC7B,IAAI,GAAG,IAAI,OAAO,GAAG,OAAO;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;AChBA,IAAa,qBAAqB;;;;;;AA4BlC,SAAgB,uBAAuB,MAAe,QAAQ,KAAmC;CAI7F,IAAI,IAAI,yBAAyB,OAAO,KAAA;CAExC,IAAI,IAAI,WAAW;EACf,MAAM,UAAU,CAAC,WAAW;EAC5B,IAAI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MAAM,UAAU,KAAK;EACrB,MAAM,YAAY,IAAI,UAAW,IAAI,aAAa,KAAK,YAAa,KAAA;EACpE,IAAI,QAAQ,IAAI;EAChB,IAAI,CAAC,IAAI;OACD,KAAK,kBAAkB,QAAQ;QAC9B,IAAI,WAAW,IAAI,SAAS,QAAQ,QAAQ,gBAAgB,QAAQ,UAAU;EAAA;EAEvF,OAAO;GACH,IAAI,IAAI;GAGR,MAAM,IAAI,WAAW,QAAQ,IAAI;GACjC,aAAa,IAAI,WAAW;GAC5B,UAAU,IAAI,WAAW;GACzB,SAAS,IAAI;GACb;GACA,WAAW,UAAU,QAAQ,YAAY,IAAI,WAAW,YAAY;GACpE,WAAW,WAAW,YAAY;GAClC,gBAAgB,UAAU,QAAQ,iBAAiB,IAAI;GACvD,WAAW,UAAW,QAAQ,gBAAgB,QAAQ,QAAQ,YAAY,KAAA,IAAa,IAAI;GAC3F,WAAW,UAAU,QAAQ,YAAY,IAAI;GAC7C,eAAe,UAAU,QAAQ,gBAAgB,IAAI;EACzD;CACJ;AACJ"}
|
|
@@ -3,11 +3,11 @@ import __rebaseProcess from "process";
|
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
5
|
import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
|
|
6
|
-
import {
|
|
7
|
-
import "./src-
|
|
6
|
+
import { P as revokeInternalTableSql } from "./src-I3aG1PcY.js";
|
|
7
|
+
import "./src-CatHFUym.js";
|
|
8
8
|
import { t as isSQLAdmin } from "./backend-DTAOsLQc.js";
|
|
9
|
-
import { r as logger } from "./logger-
|
|
10
|
-
import { n as createDdlBootstrapper, r as hasInCauseChain } from "./ddl-bootstrap-
|
|
9
|
+
import { r as logger } from "./logger-D-S-hO5e.js";
|
|
10
|
+
import { n as createDdlBootstrapper, r as hasInCauseChain } from "./ddl-bootstrap-BaqMSa4Y.js";
|
|
11
11
|
//#region src/cron/cron-store.ts
|
|
12
12
|
var cron_store_exports = /* @__PURE__ */ __exportAll({ createCronStore: () => createCronStore });
|
|
13
13
|
var TABLE = "rebase.cron_logs";
|
|
@@ -147,16 +147,11 @@ function createCronStore(driver) {
|
|
|
147
147
|
}
|
|
148
148
|
},
|
|
149
149
|
async fetchLogs(jobId, limit = 50) {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
LIMIT $2`, { params: [jobId, limit] })).map(rowToLogEntry);
|
|
156
|
-
} catch (err) {
|
|
157
|
-
logger.error(`[cron-store] Failed to fetch logs for "${jobId}"`, { error: err });
|
|
158
|
-
return [];
|
|
159
|
-
}
|
|
150
|
+
return (await exec(`SELECT job_id, started_at, finished_at, duration_ms, success, error, result, logs, manual
|
|
151
|
+
FROM ${TABLE}
|
|
152
|
+
WHERE job_id = $1
|
|
153
|
+
ORDER BY started_at DESC
|
|
154
|
+
LIMIT $2`, { params: [jobId, limit] })).map(rowToLogEntry);
|
|
160
155
|
},
|
|
161
156
|
async fetchJobStats() {
|
|
162
157
|
const stats = /* @__PURE__ */ new Map();
|
|
@@ -302,4 +297,4 @@ function rowToLogEntry(row) {
|
|
|
302
297
|
//#endregion
|
|
303
298
|
export { cron_store_exports as n, createCronStore as t };
|
|
304
299
|
|
|
305
|
-
//# sourceMappingURL=cron-store-
|
|
300
|
+
//# sourceMappingURL=cron-store-D2Q9-Aco.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cron-store-D2Q9-Aco.js","names":[],"sources":["../src/cron/cron-store.ts"],"sourcesContent":["import type { CronJobLogEntry } from \"@rebasepro/types\";\nimport type { DataDriver } from \"@rebasepro/types\";\nimport { isSQLAdmin } from \"@rebasepro/types\";\nimport { revokeInternalTableSql } from \"@rebasepro/common\";\nimport { logger } from \"../utils/logger.js\";\nimport { createDdlBootstrapper, hasInCauseChain } from \"../boot/ddl-bootstrap.js\";\n\n/**\n * Persistence layer for cron: the run history (`rebase.cron_logs`), the slot\n * claims that keep replicas from running the same slot twice\n * (`rebase.cron_claims`), and each job's shared state — the enabled override\n * and the run lease — in `rebase.cron_job_state`.\n *\n * Uses the DataDriver's `admin.executeSql` capability. Falls back gracefully if\n * the driver doesn't support SQL (e.g. MongoDB) — in that case, no persistence\n * occurs, and a pause or a trigger's \"already executing\" is per process.\n */\nexport interface CronStore {\n /** Ensure the backing table exists. Called once on startup. */\n ensureTable(): Promise<void>;\n\n /** Persist a single log entry after execution. */\n insertLog(entry: CronJobLogEntry): Promise<void>;\n\n /**\n * Fetch the most recent logs for a job.\n *\n * Throws when the history cannot be read. An empty array is a claim — the\n * job has no recorded runs — and a caller shows it as \"never ran\".\n *\n * @param jobId The job identifier\n * @param limit Max entries to return (default 50)\n * @returns Logs sorted newest-first\n */\n fetchLogs(jobId: string, limit?: number): Promise<CronJobLogEntry[]>;\n\n /**\n * Fetch aggregate stats for all jobs (totalRuns, totalFailures, lastRunAt).\n * Used to seed in-memory counters on startup.\n */\n fetchJobStats(): Promise<Map<string, { totalRuns: number; totalFailures: number; lastRunAt?: string }>>;\n\n /**\n * Atomically claim a scheduled run slot for a job.\n *\n * `slot` is the *scheduled* fire time (ISO string) derived from the cron\n * expression — deterministic across instances regardless of timer drift,\n * so all instances contend on the same (jobId, slot) key. Exactly one\n * caller wins the insert against the unique constraint and executes;\n * the rest skip.\n *\n * Throws when the store cannot tell — a missing or unreadable claims\n * table, a dropped connection. What that means is the caller's decision,\n * and the scheduler's two callers decide differently: a scheduled run\n * fails open, so a broken claims table degrades to uncoordinated execution\n * rather than silently never running jobs; a catch-up fails closed, so it\n * does not re-run the last slot on every boot of every replica.\n *\n * Optional so custom stores written against the pre-claims interface\n * keep working — the scheduler treats a missing implementation as\n * uncoordinated (always run).\n */\n tryClaimRun?(jobId: string, slot: string): Promise<boolean>;\n\n // ─── Fleet-wide job state ────────────────────────────────────────\n //\n // Everything below lives in `rebase.cron_job_state`, one row per job that\n // has ever been paused, resumed or run under a lease. It exists because the\n // alternative — each process's memory — is per process: a pause served by\n // one replica stopped only that replica, and on a split deployment the\n // process serving the admin API is not the one whose timers fire, so a\n // pause there stopped nothing at all.\n //\n // Optional, like `tryClaimRun`, so a custom store written against the\n // older interface keeps working: without them a pause is local to the\n // process that served it and a manual trigger is guarded only in-process.\n\n /**\n * Persist a job's enabled override: `true` or `false`, or `null` to hand the\n * decision back to the code's own `enabled`. Survives restarts and\n * redeploys — that is the point. Throws when the write fails.\n */\n saveEnabledOverride?(jobId: string, enabled: boolean | null, updatedBy?: string): Promise<void>;\n\n /**\n * The persisted state of the jobs asked about. A job with no row has no\n * override. `runningBy` is set only while a lease is live.\n *\n * Throws when the store cannot tell. The scheduler falls back to the code's\n * `enabled` then — a scheduled run fails open — and a listing falls back to\n * what this process knows.\n */\n fetchJobStates?(jobIds: readonly string[]): Promise<Map<string, CronJobPersistedState>>;\n\n /**\n * Take the job's run lease unless another process holds a live one.\n *\n * The cross-process half of \"already executing\": a manual trigger, a\n * scheduled run and a catch-up all take it, so none of them overlaps a run\n * another replica — or the worker, from the api role — is making. The lease\n * expires on its own after `ttlSeconds`, which is what frees a job whose\n * holder crashed.\n *\n * Throws when the store cannot tell.\n */\n tryAcquireRunLease?(jobId: string, holder: string, ttlSeconds: number): Promise<CronRunLease>;\n\n /** Release a lease taken with {@link tryAcquireRunLease} — only if `holder` still holds it. */\n releaseRunLease?(jobId: string, holder: string): Promise<void>;\n\n /**\n * Run count, failure count and last run of each job, read from\n * `cron_logs` — every process's runs, where the scheduler's own counters\n * hold only the ones it made.\n */\n fetchRunSummaries?(jobIds: readonly string[]): Promise<Map<string, CronJobRunSummary>>;\n}\n\n/** One job's row in `rebase.cron_job_state`, as the scheduler reads it. */\nexport interface CronJobPersistedState {\n /** The override, or `null` to follow the code's `enabled`. */\n enabled: boolean | null;\n /** Who holds the run lease, when a live one is held. */\n runningBy?: string;\n}\n\n/** The outcome of {@link CronStore.tryAcquireRunLease}. */\nexport type CronRunLease =\n | { acquired: true }\n | { acquired: false; holder?: string };\n\n/** A job's run history in brief, read from `cron_logs`. */\nexport interface CronJobRunSummary {\n totalRuns: number;\n totalFailures: number;\n lastRunAt?: string;\n lastDurationMs?: number;\n lastSuccess?: boolean;\n lastError?: string;\n}\n\n// ─── SQL-based implementation ────────────────────────────────────────\n\nconst TABLE = \"rebase.cron_logs\";\nconst CLAIMS_TABLE = \"rebase.cron_claims\";\nconst STATE_TABLE = \"rebase.cron_job_state\";\n\n/** `$1, $2, …` for `count` values, starting at `$first`. */\nfunction placeholders(count: number, first = 1): string {\n return Array.from({ length: count }, (_, i) => `$${first + i}`).join(\", \");\n}\n\n/**\n * Claims older than this are garbage-collected on startup — all but each\n * job's most recent one, which is kept however old it is; see the sweep in\n * `ensureTable`.\n */\nconst CLAIM_RETENTION_DAYS = 7;\n\n/**\n * How far ahead a claim may legitimately sit. Slots are claimed as they fire,\n * so anything beyond this is a clock-skewed peer at best and a stranded claim\n * at worst; see the sweep in `ensureTable`.\n */\nconst FUTURE_CLAIM_SKEW_MINUTES = 2;\n\n/**\n * Detect a unique-constraint violation anywhere in an error's cause chain.\n * Match the SQLSTATE code, never message text. Also covers SQLite\n * (\"UNIQUE constraint failed\") and MySQL (ER_DUP_ENTRY 1062) for future SQL\n * drivers.\n *\n * Distinct from `isConcurrentDdlRace` in `boot/ddl-bootstrap.ts`, which shares\n * the 23505 code but asks a different question — that one is about a losing\n * `CREATE`, this one is about a losing claim, and only the latter means\n * \"another instance already has this slot\".\n */\nfunction isUniqueViolation(err: unknown): boolean {\n return hasInCauseChain(err, (e) =>\n e.code === \"23505\" ||\n e.errno === 1062 ||\n (typeof e.message === \"string\" && e.message.includes(\"UNIQUE constraint failed\"))\n );\n}\n\nexport function createCronStore(driver: DataDriver): Required<CronStore> | undefined {\n const admin = driver.admin;\n if (!isSQLAdmin(admin)) {\n logger.warn(\"⚠️ [cron-store] DataDriver does not support SQL admin — cron logs will not be persisted.\");\n return undefined;\n }\n\n const exec = (sqlText: string, options?: { params?: unknown[] }) =>\n admin.executeSql(sqlText, options?.params ? { params: options.params } : undefined);\n\n const ddl = createDdlBootstrapper(exec, \"cron-store\");\n\n return {\n async ensureTable(): Promise<void> {\n // Creation. Every statement here is idempotent, so losing the race\n // to a peer that booted at the same moment is survivable — but only\n // if the loser retries rather than abandoning everything below it.\n // One step each, so a hard failure on any one of them does not take\n // the others with it. The claims table in particular must not be\n // lost because an index on the *logs* table could not be built.\n await ddl.ensureObject(\"Creating schema rebase\", \"CREATE SCHEMA IF NOT EXISTS rebase\");\n\n await ddl.ensureObject(`Creating ${TABLE}`, `\n CREATE TABLE IF NOT EXISTS ${TABLE} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n job_id TEXT NOT NULL,\n started_at TIMESTAMPTZ NOT NULL,\n finished_at TIMESTAMPTZ NOT NULL,\n duration_ms INTEGER NOT NULL,\n success BOOLEAN NOT NULL DEFAULT true,\n error TEXT,\n result JSONB,\n logs JSONB,\n manual BOOLEAN NOT NULL DEFAULT false\n )\n `);\n\n await ddl.ensureObject(\"Creating idx_cron_logs_job\", `\n CREATE INDEX IF NOT EXISTS idx_cron_logs_job\n ON ${TABLE}(job_id, started_at DESC)\n `);\n\n // What a process whose scheduler is not started reads to show a\n // job's failure count. Partial, so it holds only the failed runs:\n // the count reads those and nothing else, and a healthy job's\n // inserts never touch it.\n await ddl.ensureObject(\"Creating idx_cron_logs_job_failures\", `\n CREATE INDEX IF NOT EXISTS idx_cron_logs_job_failures\n ON ${TABLE}(job_id) WHERE NOT success\n `);\n\n await ddl.ensureObject(`Creating ${CLAIMS_TABLE}`, `\n CREATE TABLE IF NOT EXISTS ${CLAIMS_TABLE} (\n job_id TEXT NOT NULL,\n slot TIMESTAMPTZ NOT NULL,\n claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n PRIMARY KEY (job_id, slot)\n )\n `);\n\n // One row per job that has been paused, resumed or run under a\n // lease. `enabled` NULL means \"follow the code\"; `updated_at` and\n // `updated_by` say who last set it, and stay NULL on a row that has\n // only ever held a lease. Created here rather than by a migration,\n // so a database that predates it gains it on its next boot.\n await ddl.ensureObject(`Creating ${STATE_TABLE}`, `\n CREATE TABLE IF NOT EXISTS ${STATE_TABLE} (\n job_id TEXT PRIMARY KEY,\n enabled BOOLEAN,\n updated_at TIMESTAMPTZ,\n updated_by TEXT,\n running_until TIMESTAMPTZ,\n running_by TEXT\n )\n `);\n\n // Everything from here is keyed on what actually exists, not on\n // whether *this* instance is the one that created it. A single\n // failure above used to abandon the rest of this method, which meant\n // the loser of a boot race skipped the sweeps and — far worse — the\n // privilege revocation, leaving the claims table writable by end\n // users on an instance that reported nothing but a warning about\n // log persistence.\n const [logsReady, claimsReady, stateReady] = await Promise.all([\n ddl.isReadable(TABLE),\n ddl.isReadable(CLAIMS_TABLE),\n ddl.isReadable(STATE_TABLE)\n ]);\n\n if (claimsReady) {\n // Drop claims for slots that have not happened yet. A slot is\n // claimed at the moment it fires, so a future one can only come\n // from a timer that woke early — and because claims are\n // permanent, that claim would silently skip the real run when it\n // finally came due. The margin keeps a legitimate claim made\n // moments early by a clock-skewed peer.\n await ddl.step(\"Future-slot claim sweep\", async () => {\n const stranded = await exec(\n `DELETE FROM ${CLAIMS_TABLE}\n WHERE slot > now() + make_interval(mins => $1)\n RETURNING job_id, slot`,\n { params: [FUTURE_CLAIM_SKEW_MINUTES] }\n );\n // A driver that does not honour RETURNING gives back\n // nothing; the rows are only used to report, so treat that\n // as \"none\".\n for (const row of (stranded ?? []) as { job_id: string; slot: string }[]) {\n logger.warn(\n `[cron-store] Released a claim on the future slot ${new Date(row.slot).toISOString()} ` +\n `for \"${row.job_id}\" — it was claimed by a timer that fired early, and would ` +\n \"otherwise have skipped that run\"\n );\n }\n });\n\n // Garbage-collect old claims — except each job's most recent\n // one. A claim is also the record that a slot already ran, and\n // the catch-up at boot asks exactly that about the job's latest\n // slot, as far back as its `catchUpWindowSeconds` reaches —\n // which can be a month. Sweeping that claim after seven days\n // would make the boot that swept it re-run the slot. A claim\n // behind the latest answers for a slot no catch-up looks at,\n // since a catch-up considers only the most recent one.\n //\n // After the future-slot sweep, not before: a stranded future\n // claim would otherwise count as the job's latest, and the real\n // one behind it would be swept here and then released there.\n await ddl.step(\"Claim retention sweep\", async () => {\n await exec(\n `DELETE FROM ${CLAIMS_TABLE} AS c\n WHERE c.claimed_at < now() - make_interval(days => $1)\n AND c.slot < (\n SELECT max(latest.slot) FROM ${CLAIMS_TABLE} AS latest\n WHERE latest.job_id = c.job_id\n )`,\n { params: [CLAIM_RETENTION_DAYS] }\n );\n });\n }\n\n // Neither table is a collection, so neither carries RLS, while the\n // Postgres driver's schema-wide grant reaches both. Cron logs hold\n // job output — arbitrary application data — and a writable\n // `cron_claims` lets any signed-in user suppress a scheduled run by\n // claiming its slot. This is a security control, so it is re-applied\n // by every instance on every boot, whatever else went wrong.\n if (logsReady) {\n await ddl.step(\"Revoking end-user access to cron_logs\", () =>\n exec(revokeInternalTableSql(\"rebase\", \"cron_logs\")));\n }\n if (claimsReady) {\n await ddl.step(\"Revoking end-user access to cron_claims\", () =>\n exec(revokeInternalTableSql(\"rebase\", \"cron_claims\")));\n }\n // A writable `cron_job_state` would let any signed-in user pause a\n // job for the whole fleet, or hold its run lease so that nothing\n // runs it.\n if (stateReady) {\n await ddl.step(\"Revoking end-user access to cron_job_state\", () =>\n exec(revokeInternalTableSql(\"rebase\", \"cron_job_state\")));\n }\n\n if (logsReady && claimsReady && stateReady) {\n logger.info(\"✅ Cron logs table ready\");\n return;\n }\n // Say which capability is gone, and what it costs. \"Continuing\n // without cron log persistence\" undersold this: the claims table is\n // the only thing stopping every instance from running every job.\n if (!claimsReady) {\n logger.error(\n `❌ [cron-store] ${CLAIMS_TABLE} is unavailable — scheduled runs cannot be coordinated. ` +\n \"With more than one app instance, every instance will now run every job on every tick.\"\n );\n }\n if (!logsReady) {\n logger.warn(`⚠️ [cron-store] ${TABLE} is unavailable — cron run history will not be persisted.`);\n }\n if (!stateReady) {\n logger.warn(\n `⚠️ [cron-store] ${STATE_TABLE} is unavailable — pausing a job reaches only the process ` +\n \"that served the request, and jobs run as their code declares on every other one. \" +\n \"A manual trigger is not kept off a run another process is making.\"\n );\n }\n },\n\n async insertLog(entry: CronJobLogEntry): Promise<void> {\n try {\n const resultJson = entry.result !== undefined ? JSON.stringify(entry.result) : null;\n const logsJson = entry.logs.length > 0 ? JSON.stringify(entry.logs) : null;\n\n await exec(\n `INSERT INTO ${TABLE} (job_id, started_at, finished_at, duration_ms, success, error, result, logs, manual)\n VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9)`,\n { params: [\n entry.jobId,\n entry.startedAt,\n entry.finishedAt,\n entry.durationMs,\n entry.success,\n entry.error || null,\n resultJson,\n logsJson,\n entry.manual\n ]}\n );\n } catch (err) {\n // Non-blocking — log persistence should never crash the scheduler\n logger.error(`[cron-store] Failed to persist log for \"${entry.jobId}\"`, { error: err });\n }\n },\n\n async fetchLogs(jobId: string, limit = 50): Promise<CronJobLogEntry[]> {\n const rows = await exec(\n `SELECT job_id, started_at, finished_at, duration_ms, success, error, result, logs, manual\n FROM ${TABLE}\n WHERE job_id = $1\n ORDER BY started_at DESC\n LIMIT $2`,\n { params: [jobId, limit] }\n );\n\n return rows.map(rowToLogEntry);\n },\n\n async fetchJobStats(): Promise<Map<string, { totalRuns: number; totalFailures: number; lastRunAt?: string }>> {\n const stats = new Map<string, { totalRuns: number; totalFailures: number; lastRunAt?: string }>();\n try {\n const rows = await exec(`\n SELECT\n job_id,\n COUNT(*)::int AS total_runs,\n COUNT(*) FILTER (WHERE NOT success)::int AS total_failures,\n MAX(started_at) AS last_run_at\n FROM ${TABLE}\n GROUP BY job_id\n `);\n\n for (const row of rows) {\n stats.set(row.job_id as string, {\n totalRuns: row.total_runs as number,\n totalFailures: row.total_failures as number,\n lastRunAt: row.last_run_at ? new Date(row.last_run_at as string).toISOString() : undefined\n });\n }\n } catch (err) {\n logger.error(\"[cron-store] Failed to fetch job stats\", { error: err });\n }\n return stats;\n },\n\n async tryClaimRun(jobId: string, slot: string): Promise<boolean> {\n try {\n const rows = await exec(\n `INSERT INTO ${CLAIMS_TABLE} (job_id, slot)\n VALUES ($1, $2)\n ON CONFLICT (job_id, slot) DO NOTHING\n RETURNING job_id`,\n { params: [jobId, slot] }\n );\n return rows.length > 0;\n } catch (err) {\n if (isUniqueViolation(err)) {\n // Another instance won the race for this slot\n return false;\n }\n // Neither won nor lost: the store does not know, and says so.\n // Answering `true` here would decide \"fail open\" for every\n // caller, including the catch-up, whose whole safety rests on\n // failing closed.\n throw err;\n }\n },\n\n async saveEnabledOverride(jobId: string, enabled: boolean | null, updatedBy?: string): Promise<void> {\n await exec(\n `INSERT INTO ${STATE_TABLE} (job_id, enabled, updated_at, updated_by)\n VALUES ($1, $2::boolean, now(), $3)\n ON CONFLICT (job_id) DO UPDATE\n SET enabled = EXCLUDED.enabled, updated_at = now(), updated_by = EXCLUDED.updated_by`,\n { params: [jobId, enabled, updatedBy ?? null] }\n );\n },\n\n async fetchJobStates(jobIds: readonly string[]): Promise<Map<string, CronJobPersistedState>> {\n const states = new Map<string, CronJobPersistedState>();\n if (jobIds.length === 0) return states;\n const rows = await exec(\n `SELECT job_id, enabled,\n CASE WHEN running_until > now() THEN running_by END AS running_by\n FROM ${STATE_TABLE}\n WHERE job_id IN (${placeholders(jobIds.length)})`,\n { params: [...jobIds] }\n );\n for (const row of rows ?? []) {\n states.set(String(row.job_id), {\n enabled: typeof row.enabled === \"boolean\" ? row.enabled : null,\n runningBy: typeof row.running_by === \"string\" ? row.running_by : undefined\n });\n }\n return states;\n },\n\n async tryAcquireRunLease(jobId: string, holder: string, ttlSeconds: number): Promise<CronRunLease> {\n // One statement, always one row. The insert covers a job that has\n // no row yet; the conditional update covers one whose lease is\n // absent or expired, and does nothing over a live one — so of two\n // processes racing, the second waits on the first's row and then\n // finds it held. The outer SELECT sees the table as it was before\n // this statement, which is exactly the holder that refused us.\n const rows = await exec(\n `WITH attempt AS (\n INSERT INTO ${STATE_TABLE} AS s (job_id, running_until, running_by)\n VALUES ($1, now() + make_interval(secs => $2::double precision), $3)\n ON CONFLICT (job_id) DO UPDATE\n SET running_until = EXCLUDED.running_until, running_by = EXCLUDED.running_by\n WHERE s.running_until IS NULL OR s.running_until <= now()\n RETURNING s.job_id\n )\n SELECT EXISTS (SELECT 1 FROM attempt) AS acquired,\n (SELECT running_by FROM ${STATE_TABLE}\n WHERE job_id = $1 AND running_until > now()) AS holder`,\n { params: [jobId, ttlSeconds, holder] }\n );\n const row = rows?.[0];\n if (!row) {\n throw new Error(`The run lease for \"${jobId}\" got no answer from the database`);\n }\n if (row.acquired === true) return { acquired: true };\n return {\n acquired: false,\n holder: typeof row.holder === \"string\" ? row.holder : undefined\n };\n },\n\n async releaseRunLease(jobId: string, holder: string): Promise<void> {\n await exec(\n `UPDATE ${STATE_TABLE}\n SET running_until = NULL, running_by = NULL\n WHERE job_id = $1 AND running_by = $2`,\n { params: [jobId, holder] }\n );\n },\n\n async fetchRunSummaries(jobIds: readonly string[]): Promise<Map<string, CronJobRunSummary>> {\n const summaries = new Map<string, CronJobRunSummary>();\n if (jobIds.length === 0) return summaries;\n // Per job, never a GROUP BY over the whole table: each subquery\n // reads one job's range of `idx_cron_logs_job` (the failures, the\n // partial `idx_cron_logs_job_failures`), and the last run is one\n // index probe. Jobs no longer registered are never read at all.\n const rows = await exec(\n `SELECT j.job_id,\n (SELECT count(*)::int FROM ${TABLE} l WHERE l.job_id = j.job_id) AS total_runs,\n (SELECT count(*)::int FROM ${TABLE} l WHERE l.job_id = j.job_id AND NOT l.success) AS total_failures,\n last.started_at, last.duration_ms, last.success, last.error\n FROM (VALUES ${jobIds.map((_, i) => `($${i + 1}::text)`).join(\", \")}) AS j(job_id)\n LEFT JOIN LATERAL (\n SELECT l.started_at, l.duration_ms, l.success, l.error\n FROM ${TABLE} l\n WHERE l.job_id = j.job_id\n ORDER BY l.started_at DESC\n LIMIT 1\n ) AS last ON true`,\n { params: [...jobIds] }\n );\n for (const row of rows ?? []) {\n const summary: CronJobRunSummary = {\n totalRuns: Number(row.total_runs ?? 0),\n totalFailures: Number(row.total_failures ?? 0)\n };\n const lastRunAt = toIsoString(row.started_at);\n if (lastRunAt) {\n summary.lastRunAt = lastRunAt;\n summary.lastDurationMs = Number(row.duration_ms);\n summary.lastSuccess = row.success === true;\n if (typeof row.error === \"string\") summary.lastError = row.error;\n }\n summaries.set(String(row.job_id), summary);\n }\n return summaries;\n }\n };\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\n/** A TIMESTAMPTZ as the driver returned it — a `Date` or a string — in ISO form. */\nfunction toIsoString(value: unknown): string | undefined {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"string\" || typeof value === \"number\") return new Date(value).toISOString();\n return undefined;\n}\n\nfunction rowToLogEntry(row: Record<string, unknown>): CronJobLogEntry {\n return {\n jobId: row.job_id as string,\n startedAt: new Date(row.started_at as string).toISOString(),\n finishedAt: new Date(row.finished_at as string).toISOString(),\n durationMs: row.duration_ms as number,\n success: row.success as boolean,\n error: (row.error as string) ?? undefined,\n result: row.result ?? undefined,\n logs: Array.isArray(row.logs) ? row.logs : (row.logs ? (() => { try { return JSON.parse(row.logs as string); } catch { return []; } })() : []),\n manual: row.manual as boolean\n };\n}\n"],"mappings":";;;;;;;;;;;;AA+IA,IAAM,QAAQ;AACd,IAAM,eAAe;AACrB,IAAM,cAAc;;AAGpB,SAAS,aAAa,OAAe,QAAQ,GAAW;CACpD,OAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,IAAI,GAAG,MAAM,IAAI,QAAQ,GAAG,CAAC,CAAC,KAAK,IAAI;AAC7E;;;;;;AAOA,IAAM,uBAAuB;;;;;;AAO7B,IAAM,4BAA4B;;;;;;;;;;;;AAalC,SAAS,kBAAkB,KAAuB;CAC9C,OAAO,gBAAgB,MAAM,MACzB,EAAE,SAAS,WACX,EAAE,UAAU,QACX,OAAO,EAAE,YAAY,YAAY,EAAE,QAAQ,SA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O,IAAI,KAAK,KAAK,CAAC,CAAC,YAAY;AAEnG;AAEA,SAAS,cAAc,KAA+C;CAClE,OAAO;EACH,OAAO,IAAI;EACX,WAAW,IAAI,KAAK,IAAI,UAAoB,CAAC,CAAC,YAAY;EAC1D,YAAY,IAAI,KAAK,IAAI,WAAqB,CAAC,CAAC,YAAY;EAC5D,YAAY,IAAI;EAChB,SAAS,IAAI;EACb,OAAQ,IAAI,SAAoB,KAAA;EAChC,QAAQ,IAAI,UAAU,KAAA;EACtB,MAAM,MAAM,QAAQ,IAAI,IAAI,IAAI,IAAI,OAAQ,IAAI,cAAc;GAAE,IAAI;IAAE,OAAO,KAAK,MAAM,IAAI,IAAc;GAAG,QAAQ;IAAE,OAAO,CAAC;GAAG;EAAE,EAAA,CAAG,IAAI,CAAC;EAC5I,QAAQ,IAAI;CAChB;AACJ"}
|
|
@@ -2,7 +2,7 @@ import { createRequire as __rebaseCreateRequire } from "module";
|
|
|
2
2
|
import __rebaseProcess from "process";
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
|
-
import { r as logger } from "./logger-
|
|
5
|
+
import { r as logger } from "./logger-D-S-hO5e.js";
|
|
6
6
|
//#region src/boot/ddl-bootstrap.ts
|
|
7
7
|
/**
|
|
8
8
|
* SQLSTATEs a *simultaneous boot* can raise from statements that are otherwise
|
|
@@ -144,4 +144,4 @@ function createDdlBootstrapper(exec, scope) {
|
|
|
144
144
|
//#endregion
|
|
145
145
|
export { isDuplicateObjectRace as a, isConcurrentDdlRace as i, createDdlBootstrapper as n, hasInCauseChain as r, CONCURRENT_DDL_SQLSTATES as t };
|
|
146
146
|
|
|
147
|
-
//# sourceMappingURL=ddl-bootstrap-
|
|
147
|
+
//# sourceMappingURL=ddl-bootstrap-BaqMSa4Y.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ddl-bootstrap-C6mo0Kmz.js","names":[],"sources":["../src/boot/ddl-bootstrap.ts"],"sourcesContent":["import { logger } from \"../utils/logger.js\";\n\n/**\n * Helpers for the \"create my internal table if it isn't there yet\" bootstrap\n * that several stores run at boot.\n *\n * These all look trivially safe — every statement is `IF NOT EXISTS` — and they\n * are not, for two reasons that only show up with more than one app instance:\n *\n * 1. `CREATE … IF NOT EXISTS` reads the catalog and then writes to it, and\n * those two steps are not one atomic operation. Instances starting together\n * — a rolling deploy, a replica count going from 1 to N, a crash loop\n * restarting the fleet — can both see \"absent\" and both try to create. The\n * loser gets a duplicate key on a *catalog* index instead of the silent\n * no-op the syntax appears to promise. Measured against Postgres 18: with\n * five instances booting at once, 8 of 10 `ensureTable` calls hit it.\n *\n * 2. A bootstrap written as one long `try` block therefore abandons everything\n * after the losing statement — including, in every store that has one, the\n * `REVOKE` that takes the table back off the end-user role. That revoke is\n * a security control and must not be collateral damage from a race.\n *\n * So: retry the race, contain each statement separately, and decide what to do\n * next from what actually exists rather than from who won.\n */\n\n/** A driver's `executeSql`, narrowed to what a bootstrap needs. */\nexport type SqlExec = (sqlText: string, options?: { params?: unknown[] }) => Promise<Record<string, unknown>[]>;\n\n\n/**\n * SQLSTATEs a *simultaneous boot* can raise from statements that are otherwise\n * idempotent. Retrying is always the right answer for these: the second attempt\n * finds the object present and does nothing.\n */\nexport const CONCURRENT_DDL_SQLSTATES = new Set([\n \"23505\", // unique_violation on pg_type / pg_class / pg_namespace\n \"42P06\", // duplicate_schema\n \"42P07\", // duplicate_table\n \"42710\", // duplicate_object — an index or a constraint\n \"40P01\" // deadlock_detected — two boots taking catalog locks in step\n]);\n\n/** Attempts per idempotent DDL statement, including the first. */\nexport const DDL_ATTEMPTS = 4;\nconst DDL_RETRY_BASE_MS = 40;\n\n/**\n * Walk an error's `cause` chain, stopping at the first link `visit` accepts.\n * Drizzle wraps the driver error, so nothing useful is ever on the top level.\n */\nexport function hasInCauseChain(err: unknown, visit: (e: Record<string, unknown>) => boolean): boolean {\n let current: unknown = err;\n for (let depth = 0; depth < 10 && current; depth++) {\n if (typeof current !== \"object\") break;\n const e = current as Record<string, unknown>;\n if (visit(e)) return true;\n current = e.cause;\n }\n return false;\n}\n\n/**\n * Is this the loser of a race to create something that already exists?\n *\n * Deliberately narrow. A permission failure, an unreachable database or a typo\n * in the DDL must surface on the first attempt rather than being retried four\n * times and then reported as a race that never was.\n */\nexport function isConcurrentDdlRace(err: unknown): boolean {\n return hasInCauseChain(err, (e) =>\n (typeof e.code === \"string\" && CONCURRENT_DDL_SQLSTATES.has(e.code)) ||\n // SQLite and MySQL say it in words rather than in a shared SQLSTATE.\n (typeof e.message === \"string\" && /already exists/i.test(e.message))\n );\n}\n\n/**\n * SQLSTATEs that mean, unambiguously, *the object is already there*.\n *\n * A subset of {@link CONCURRENT_DDL_SQLSTATES} and a stricter question. The\n * broad set answers \"should this be retried\"; this one answers \"is it safe to\n * carry on as though the statement had succeeded\", which is a claim about the\n * end state rather than about the attempt. Deadlock is not in it — a deadlocked\n * statement did nothing and must be retried, not skipped.\n */\nconst DUPLICATE_OBJECT_SQLSTATES = new Set([\n \"42P06\", // duplicate_schema\n \"42P07\", // duplicate_table\n \"42710\" // duplicate_object — a type, an index, a constraint\n]);\n\n/**\n * Did this statement fail *because a peer already created the same object*?\n *\n * The narrow companion to {@link isConcurrentDdlRace}, for the one caller that\n * needs to tell \"someone beat me to it\" from \"this genuinely failed\": a loop\n * applying a schema plan, where treating every `23505` as a harmless race would\n * silently swallow the one that matters — a unique constraint that cannot be\n * added because the customer's existing rows violate it.\n *\n * `23505` is therefore only accepted when it names a `pg_catalog` index. That is\n * what a lost `CREATE TYPE`/`CREATE TABLE` race raises (`pg_type_typname_nsp_index`\n * is the one seen in practice); a unique violation on user data names the user's\n * own constraint and is left to the caller.\n *\n * With one exception, in {@link NOT_A_RACE_PG_INDEXES}.\n */\nexport function isDuplicateObjectRace(err: unknown): boolean {\n return hasInCauseChain(err, (e) => {\n if (typeof e.code !== \"string\") return false;\n if (DUPLICATE_OBJECT_SQLSTATES.has(e.code)) return true;\n if (e.code !== \"23505\") return false;\n // node-postgres puts the violated index in `constraint`; some paths only\n // carry it in the detail text, so check both rather than miss the race.\n const constraint = typeof e.constraint === \"string\" ? e.constraint : \"\";\n const detail = typeof e.detail === \"string\" ? e.detail : \"\";\n for (const index of NOT_A_RACE_PG_INDEXES) {\n if (constraint === index || detail.includes(index)) return false;\n }\n return constraint.startsWith(\"pg_\") || /\\bpg_[a-z_]+_index\\b/.test(detail);\n });\n}\n\n/**\n * `pg_catalog` indexes whose `23505` is never a race.\n *\n * `pg_enum_typid_label_index` is unique on (type, label), and one statement\n * violates it on its own: `CREATE TYPE t AS ENUM ('draft', 'draft')` — which is\n * what a collection with two enum entries carrying the same `id` generates.\n * Under the `pg_` prefix rule that read as \"a peer created it first\", so the\n * type was never created, boot carried on, and the column fell back to `TEXT`\n * with no enum behind it. Verified against PGlite: the duplicate `CREATE TYPE`\n * raises exactly this.\n *\n * The concurrent-boot case this rule exists for does not come through here at\n * all. Two pods adding the same label race on `ALTER TYPE … ADD VALUE`, which\n * raises `42710` (already in {@link DUPLICATE_OBJECT_SQLSTATES}) — and the\n * generator writes `ADD VALUE IF NOT EXISTS`, so it usually raises nothing.\n *\n * The duplicate `id` is rejected earlier now, by `validate-config`, which names\n * the property. This is the second line: a config that reaches the database with\n * one fails loudly instead of degrading.\n */\nconst NOT_A_RACE_PG_INDEXES = [\"pg_enum_typid_label_index\"];\n\nexport interface DdlBootstrapper {\n /**\n * Run one idempotent statement — `CREATE … IF NOT EXISTS`, `ALTER TABLE …\n * ADD COLUMN IF NOT EXISTS` — retrying the catalog race a simultaneous boot\n * produces. Never throws: a statement that cannot be made to work is logged\n * and the caller carries on to the next one.\n */\n ensureObject(label: string, sqlText: string): Promise<void>;\n\n /** Contain one step's failure so that the steps after it still run. */\n step(label: string, run: () => Promise<unknown>): Promise<void>;\n\n /**\n * Is this table there and readable? Asked with a query any SQL dialect\n * answers, rather than `to_regclass`, so a future non-Postgres SQL driver\n * gets a real answer instead of a syntax error read as \"missing\".\n */\n isReadable(table: string): Promise<boolean>;\n}\n\n/**\n * @param exec the driver's SQL escape hatch\n * @param scope log prefix identifying the caller, e.g. `\"cron-store\"`\n */\nexport function createDdlBootstrapper(exec: SqlExec, scope: string): DdlBootstrapper {\n /** Jittered, so peers that collided once do not collide again in lockstep. */\n const backoff = (attempt: number) =>\n new Promise(resolve => setTimeout(resolve, DDL_RETRY_BASE_MS * attempt * (1 + Math.random())));\n\n const step: DdlBootstrapper[\"step\"] = async (label, run) => {\n try {\n await run();\n } catch (err) {\n logger.error(`[${scope}] ${label} failed`, { error: err });\n }\n };\n\n return {\n step,\n\n ensureObject(label, sqlText) {\n return step(label, async () => {\n for (let attempt = 1; ; attempt++) {\n try {\n await exec(sqlText);\n return;\n } catch (err) {\n if (!isConcurrentDdlRace(err) || attempt >= DDL_ATTEMPTS) throw err;\n logger.debug(\n `[${scope}] Lost a create race for ${label} with another instance ` +\n `(attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`\n );\n await backoff(attempt);\n }\n }\n });\n },\n\n async isReadable(table) {\n try {\n await exec(`SELECT 1 FROM ${table} WHERE false`);\n return true;\n } catch {\n return false;\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAmCA,IAAa,2CAA2B,IAAI,IAAI;CAC5C;CACA;CACA;CACA;CACA;AACJ,CAAC;AAID,IAAM,oBAAoB;;;;;AAM1B,SAAgB,gBAAgB,KAAc,OAAyD;CACnG,IAAI,UAAmB;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,SAAS,SAAS;EAChD,IAAI,OAAO,YAAY,UAAU;EACjC,MAAM,IAAI;EACV,IAAI,MAAM,CAAC,GAAG,OAAO;EACrB,UAAU,EAAE;CAChB;CACA,OAAO;AACX;;;;;;;;AASA,SAAgB,oBAAoB,KAAuB;CACvD,OAAO,gBAAgB,MAAM,MACxB,OAAO,EAAE,SAAS,YAAY,yBAAyB,IAAI,EAAE,IAAI,KAEjE,OAAO,EAAE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,kCAC/B,QAAQ,eACxB;KACA,MAAM,QAAQ,OAAO;IACzB;GAER,CAAC;EACL;EAEA,MAAM,WAAW,OAAO;GACpB,IAAI;IACA,MAAM,KAAK,iBAAiB,MAAM,aAAa;IAC/C,OAAO;GACX,QAAQ;IACJ,OAAO;GACX;EACJ;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"ddl-bootstrap-BaqMSa4Y.js","names":[],"sources":["../src/boot/ddl-bootstrap.ts"],"sourcesContent":["import { logger } from \"../utils/logger.js\";\n\n/**\n * Helpers for the \"create my internal table if it isn't there yet\" bootstrap\n * that several stores run at boot.\n *\n * These all look trivially safe — every statement is `IF NOT EXISTS` — and they\n * are not, for two reasons that only show up with more than one app instance:\n *\n * 1. `CREATE … IF NOT EXISTS` reads the catalog and then writes to it, and\n * those two steps are not one atomic operation. Instances starting together\n * — a rolling deploy, a replica count going from 1 to N, a crash loop\n * restarting the fleet — can both see \"absent\" and both try to create. The\n * loser gets a duplicate key on a *catalog* index instead of the silent\n * no-op the syntax appears to promise. Measured against Postgres 18: with\n * five instances booting at once, 8 of 10 `ensureTable` calls hit it.\n *\n * 2. A bootstrap written as one long `try` block therefore abandons everything\n * after the losing statement — including, in every store that has one, the\n * `REVOKE` that takes the table back off the end-user role. That revoke is\n * a security control and must not be collateral damage from a race.\n *\n * So: retry the race, contain each statement separately, and decide what to do\n * next from what actually exists rather than from who won.\n */\n\n/** A driver's `executeSql`, narrowed to what a bootstrap needs. */\nexport type SqlExec = (sqlText: string, options?: { params?: unknown[] }) => Promise<Record<string, unknown>[]>;\n\n\n/**\n * SQLSTATEs a *simultaneous boot* can raise from statements that are otherwise\n * idempotent. Retrying is always the right answer for these: the second attempt\n * finds the object present and does nothing.\n */\nexport const CONCURRENT_DDL_SQLSTATES = new Set([\n \"23505\", // unique_violation on pg_type / pg_class / pg_namespace\n \"42P06\", // duplicate_schema\n \"42P07\", // duplicate_table\n \"42710\", // duplicate_object — an index or a constraint\n \"40P01\" // deadlock_detected — two boots taking catalog locks in step\n]);\n\n/** Attempts per idempotent DDL statement, including the first. */\nexport const DDL_ATTEMPTS = 4;\nconst DDL_RETRY_BASE_MS = 40;\n\n/**\n * Walk an error's `cause` chain, stopping at the first link `visit` accepts.\n * Drizzle wraps the driver error, so nothing useful is ever on the top level.\n */\nexport function hasInCauseChain(err: unknown, visit: (e: Record<string, unknown>) => boolean): boolean {\n let current: unknown = err;\n for (let depth = 0; depth < 10 && current; depth++) {\n if (typeof current !== \"object\") break;\n const e = current as Record<string, unknown>;\n if (visit(e)) return true;\n current = e.cause;\n }\n return false;\n}\n\n/**\n * Is this the loser of a race to create something that already exists?\n *\n * Deliberately narrow. A permission failure, an unreachable database or a typo\n * in the DDL must surface on the first attempt rather than being retried four\n * times and then reported as a race that never was.\n */\nexport function isConcurrentDdlRace(err: unknown): boolean {\n return hasInCauseChain(err, (e) =>\n (typeof e.code === \"string\" && CONCURRENT_DDL_SQLSTATES.has(e.code)) ||\n // SQLite and MySQL say it in words rather than in a shared SQLSTATE.\n (typeof e.message === \"string\" && /already exists/i.test(e.message))\n );\n}\n\n/**\n * SQLSTATEs that mean, unambiguously, *the object is already there*.\n *\n * A subset of {@link CONCURRENT_DDL_SQLSTATES} and a stricter question. The\n * broad set answers \"should this be retried\"; this one answers \"is it safe to\n * carry on as though the statement had succeeded\", which is a claim about the\n * end state rather than about the attempt. Deadlock is not in it — a deadlocked\n * statement did nothing and must be retried, not skipped.\n */\nconst DUPLICATE_OBJECT_SQLSTATES = new Set([\n \"42P06\", // duplicate_schema\n \"42P07\", // duplicate_table\n \"42710\" // duplicate_object — a type, an index, a constraint\n]);\n\n/**\n * Did this statement fail *because a peer already created the same object*?\n *\n * The narrow companion to {@link isConcurrentDdlRace}, for the one caller that\n * needs to tell \"someone beat me to it\" from \"this genuinely failed\": a loop\n * applying a schema plan, where treating every `23505` as a harmless race would\n * silently swallow the one that matters — a unique constraint that cannot be\n * added because the customer's existing rows violate it.\n *\n * `23505` is therefore only accepted when it names a `pg_catalog` index. That is\n * what a lost `CREATE TYPE`/`CREATE TABLE` race raises (`pg_type_typname_nsp_index`\n * is the one seen in practice); a unique violation on user data names the user's\n * own constraint and is left to the caller.\n *\n * With one exception, in {@link NOT_A_RACE_PG_INDEXES}.\n */\nexport function isDuplicateObjectRace(err: unknown): boolean {\n return hasInCauseChain(err, (e) => {\n if (typeof e.code !== \"string\") return false;\n if (DUPLICATE_OBJECT_SQLSTATES.has(e.code)) return true;\n if (e.code !== \"23505\") return false;\n // node-postgres puts the violated index in `constraint`; some paths only\n // carry it in the detail text, so check both rather than miss the race.\n const constraint = typeof e.constraint === \"string\" ? e.constraint : \"\";\n const detail = typeof e.detail === \"string\" ? e.detail : \"\";\n for (const index of NOT_A_RACE_PG_INDEXES) {\n if (constraint === index || detail.includes(index)) return false;\n }\n return constraint.startsWith(\"pg_\") || /\\bpg_[a-z_]+_index\\b/.test(detail);\n });\n}\n\n/**\n * `pg_catalog` indexes whose `23505` is never a race.\n *\n * `pg_enum_typid_label_index` is unique on (type, label), and one statement\n * violates it on its own: `CREATE TYPE t AS ENUM ('draft', 'draft')` — which is\n * what a collection with two enum entries carrying the same `id` generates.\n * Under the `pg_` prefix rule that read as \"a peer created it first\", so the\n * type was never created, boot carried on, and the column fell back to `TEXT`\n * with no enum behind it. Verified against PGlite: the duplicate `CREATE TYPE`\n * raises exactly this.\n *\n * The concurrent-boot case this rule exists for does not come through here at\n * all. Two pods adding the same label race on `ALTER TYPE … ADD VALUE`, which\n * raises `42710` (already in {@link DUPLICATE_OBJECT_SQLSTATES}) — and the\n * generator writes `ADD VALUE IF NOT EXISTS`, so it usually raises nothing.\n *\n * The duplicate `id` is rejected earlier now, by `validate-config`, which names\n * the property. This is the second line: a config that reaches the database with\n * one fails loudly instead of degrading.\n */\nconst NOT_A_RACE_PG_INDEXES = [\"pg_enum_typid_label_index\"];\n\nexport interface DdlBootstrapper {\n /**\n * Run one idempotent statement — `CREATE … IF NOT EXISTS`, `ALTER TABLE …\n * ADD COLUMN IF NOT EXISTS` — retrying the catalog race a simultaneous boot\n * produces. Never throws: a statement that cannot be made to work is logged\n * and the caller carries on to the next one.\n */\n ensureObject(label: string, sqlText: string): Promise<void>;\n\n /** Contain one step's failure so that the steps after it still run. */\n step(label: string, run: () => Promise<unknown>): Promise<void>;\n\n /**\n * Is this table there and readable? Asked with a query any SQL dialect\n * answers, rather than `to_regclass`, so a future non-Postgres SQL driver\n * gets a real answer instead of a syntax error read as \"missing\".\n */\n isReadable(table: string): Promise<boolean>;\n}\n\n/**\n * @param exec the driver's SQL escape hatch\n * @param scope log prefix identifying the caller, e.g. `\"cron-store\"`\n */\nexport function createDdlBootstrapper(exec: SqlExec, scope: string): DdlBootstrapper {\n /** Jittered, so peers that collided once do not collide again in lockstep. */\n const backoff = (attempt: number) =>\n new Promise(resolve => setTimeout(resolve, DDL_RETRY_BASE_MS * attempt * (1 + Math.random())));\n\n const step: DdlBootstrapper[\"step\"] = async (label, run) => {\n try {\n await run();\n } catch (err) {\n logger.error(`[${scope}] ${label} failed`, { error: err });\n }\n };\n\n return {\n step,\n\n ensureObject(label, sqlText) {\n return step(label, async () => {\n for (let attempt = 1; ; attempt++) {\n try {\n await exec(sqlText);\n return;\n } catch (err) {\n if (!isConcurrentDdlRace(err) || attempt >= DDL_ATTEMPTS) throw err;\n logger.debug(\n `[${scope}] Lost a create race for ${label} with another instance ` +\n `(attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`\n );\n await backoff(attempt);\n }\n }\n });\n },\n\n async isReadable(table) {\n try {\n await exec(`SELECT 1 FROM ${table} WHERE false`);\n return true;\n } catch {\n return false;\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAmCA,IAAa,2CAA2B,IAAI,IAAI;CAC5C;CACA;CACA;CACA;CACA;AACJ,CAAC;AAID,IAAM,oBAAoB;;;;;AAM1B,SAAgB,gBAAgB,KAAc,OAAyD;CACnG,IAAI,UAAmB;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,M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AC;EAC7D;CACJ;CAEA,OAAO;EACH;EAEA,aAAa,OAAO,SAAS;GACzB,OAAO,KAAK,OAAO,YAAY;IAC3B,KAAK,IAAI,UAAU,IAAK,WACpB,IAAI;KACA,MAAM,KAAK,OAAO;KAClB;IACJ,SAAS,KAAK;KACV,IAAI,CAAC,oBAAoB,GAAG,KAAK,WAAA,GAAyB,MAAM;KAChE,OAAO,MACH,IAAI,MAAM,2BAA2B,MAAM,kCAC/B,QAAQ,eACxB;KACA,MAAM,QAAQ,OAAO;IACzB;GAER,CAAC;EACL;EAEA,MAAM,WAAW,OAAO;GACpB,IAAI;IACA,MAAM,KAAK,iBAAiB,MAAM,aAAa;IAC/C,OAAO;GACX,QAAQ;IACJ,OAAO;GACX;EACJ;CACJ;AACJ"}
|
package/dist/email/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Email module exports
|
|
3
3
|
*/
|
|
4
|
-
export type { EmailService, EmailSendOptions, EmailSendResult, SMTPConfig, EmailConfig, PasswordResetTemplateFunction, EmailVerificationTemplateFunction, UserInvitationTemplateFunction, WelcomeEmailTemplateFunction, MagicLinkTemplateFunction } from "./types.js";
|
|
4
|
+
export type { EmailService, EmailSendOptions, EmailSendResult, SMTPConfig, EmailConfig, PasswordResetTemplateFunction, EmailVerificationTemplateFunction, UserInvitationTemplateFunction, WelcomeEmailTemplateFunction, MagicLinkTemplateFunction, EmailOtpTemplateFunction, EmailChangeTemplateFunction, EmailChangeNoticeTemplateFunction } from "./types.js";
|
|
5
5
|
export { SMTPEmailService, createEmailService } from "./smtp-email-service.js";
|
|
6
6
|
export { createUnconfiguredEmailService } from "./unconfigured.js";
|
|
7
7
|
export { html, raw, escapeHtml, RawHtml } from "./html.js";
|
|
@@ -9,5 +9,5 @@ export { createDevEmailSink, extractLinks, registerDevEmailSink, activeDevEmailS
|
|
|
9
9
|
export type { DevEmailSink, CapturedEmail } from "./dev-sink.js";
|
|
10
10
|
export { resolveEmailLinkBase, assertEmailLinkBases } from "./link-base.js";
|
|
11
11
|
export type { EmailLinkKind } from "./link-base.js";
|
|
12
|
-
export { getPasswordResetTemplate, getEmailVerificationTemplate, getUserInvitationTemplate, getWelcomeEmailTemplate, getMagicLinkTemplate, getEmailOtpTemplate } from "./templates.js";
|
|
12
|
+
export { getPasswordResetTemplate, getEmailVerificationTemplate, getUserInvitationTemplate, getWelcomeEmailTemplate, getMagicLinkTemplate, getEmailOtpTemplate, getEmailChangeTemplate, getEmailChangeNoticeTemplate } from "./templates.js";
|
|
13
13
|
export { resolveEmailBranding } from "./templates.js";
|
|
@@ -92,4 +92,26 @@ export declare function getMagicLinkTemplate(magicLinkUrl: string, user: Templat
|
|
|
92
92
|
html: string;
|
|
93
93
|
text: string;
|
|
94
94
|
};
|
|
95
|
+
/**
|
|
96
|
+
* Default address-change confirmation, mailed to the NEW address.
|
|
97
|
+
*
|
|
98
|
+
* Names the account being moved — its current address — because the link
|
|
99
|
+
* makes the address the account's: whoever follows it hands their inbox to
|
|
100
|
+
* that account, and must be able to tell whether it is theirs.
|
|
101
|
+
*/
|
|
102
|
+
export declare function getEmailChangeTemplate(confirmUrl: string, user: TemplateUser, newEmail: string, appName?: string, logoUrl?: string): {
|
|
103
|
+
subject: string;
|
|
104
|
+
html: string;
|
|
105
|
+
text: string;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Default notice to the OLD address that a change was asked for. It carries
|
|
109
|
+
* no link: the old inbox can do nothing about the change except know of it,
|
|
110
|
+
* and a link here would be a second way to make it.
|
|
111
|
+
*/
|
|
112
|
+
export declare function getEmailChangeNoticeTemplate(user: TemplateUser, newEmail: string, appName?: string, logoUrl?: string): {
|
|
113
|
+
subject: string;
|
|
114
|
+
html: string;
|
|
115
|
+
text: string;
|
|
116
|
+
};
|
|
95
117
|
export {};
|
package/dist/email/types.d.ts
CHANGED
|
@@ -87,6 +87,30 @@ export type EmailOtpTemplateFunction = (code: string, user: {
|
|
|
87
87
|
html: string;
|
|
88
88
|
text?: string;
|
|
89
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* Template function for the address-change confirmation, mailed to the new
|
|
92
|
+
* address. `user.email` is the account's current address.
|
|
93
|
+
*/
|
|
94
|
+
export type EmailChangeTemplateFunction = (confirmUrl: string, user: {
|
|
95
|
+
email: string;
|
|
96
|
+
displayName?: string | null;
|
|
97
|
+
}, newEmail: string) => {
|
|
98
|
+
subject: string;
|
|
99
|
+
html: string;
|
|
100
|
+
text?: string;
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* Template function for the notice mailed to the old address when an address
|
|
104
|
+
* change is asked for. Carries no link.
|
|
105
|
+
*/
|
|
106
|
+
export type EmailChangeNoticeTemplateFunction = (user: {
|
|
107
|
+
email: string;
|
|
108
|
+
displayName?: string | null;
|
|
109
|
+
}, newEmail: string) => {
|
|
110
|
+
subject: string;
|
|
111
|
+
html: string;
|
|
112
|
+
text?: string;
|
|
113
|
+
};
|
|
90
114
|
/**
|
|
91
115
|
* Complete email configuration
|
|
92
116
|
*/
|
|
@@ -159,5 +183,7 @@ export interface EmailConfig {
|
|
|
159
183
|
welcomeEmail?: WelcomeEmailTemplateFunction;
|
|
160
184
|
magicLink?: MagicLinkTemplateFunction;
|
|
161
185
|
emailOtp?: EmailOtpTemplateFunction;
|
|
186
|
+
emailChange?: EmailChangeTemplateFunction;
|
|
187
|
+
emailChangeNotice?: EmailChangeNoticeTemplateFunction;
|
|
162
188
|
};
|
|
163
189
|
}
|
package/dist/env.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export declare function optionalNumericEnvVar<T extends z.ZodType<number | undef
|
|
|
22
22
|
/**
|
|
23
23
|
* The full set of environment variables recognized by a Rebase backend.
|
|
24
24
|
*/
|
|
25
|
-
declare const rebaseEnvSchema: z.ZodObject<{
|
|
25
|
+
export declare const rebaseEnvSchema: z.ZodObject<{
|
|
26
26
|
NODE_ENV: z.ZodDefault<z.ZodEnum<{
|
|
27
27
|
production: "production";
|
|
28
28
|
test: "test";
|
|
@@ -159,4 +159,3 @@ export declare function loadEnv(): RebaseEnv;
|
|
|
159
159
|
export declare function loadEnv<E extends z.ZodObject<z.ZodRawShape>>(options: {
|
|
160
160
|
extend: E;
|
|
161
161
|
}): RebaseEnv & z.infer<E>;
|
|
162
|
-
export {};
|