@rebasepro/server 0.19.2-canary.gef769df → 0.20.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.
@@ -4,7 +4,7 @@ globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
6
  import { n as errorHandler, t as ApiError } from "./errors-DMImyqyR.js";
7
- import { a as resolveListLimitParam } from "./query-parser-0EB_LGgY.js";
7
+ import { a as resolveListLimitParam } from "./query-parser-BQiPZrM-.js";
8
8
  import { Hono } from "hono";
9
9
  //#region src/cron/cron-routes.ts
10
10
  var cron_routes_exports = /* @__PURE__ */ __exportAll({ createCronRoutes: () => createCronRoutes });
@@ -69,4 +69,4 @@ function createCronRoutes(scheduler, skipped = 0) {
69
69
  //#endregion
70
70
  export { cron_routes_exports as n, createCronRoutes as t };
71
71
 
72
- //# sourceMappingURL=cron-routes-B0hgbL0a.js.map
72
+ //# sourceMappingURL=cron-routes-Bfwni8Zg.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cron-routes-B0hgbL0a.js","names":[],"sources":["../src/cron/cron-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { HonoEnv } from \"../api/types\";\nimport type { CronScheduler } from \"./cron-scheduler\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { resolveListLimitParam } from \"../api/rest/query-parser\";\n\n/**\n * Create admin REST routes for managing cron jobs.\n *\n * Routes:\n * GET / → list all cron jobs\n * GET /:id → get a single job's status\n * POST /:id/trigger → manually trigger a job\n * GET /:id/logs → get execution logs for a job\n * PUT /:id → update job (enable/disable)\n */\nexport function createCronRoutes(scheduler: CronScheduler, skipped = 0): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n // Hono's onError does NOT propagate from parent to child routers, so this\n // child router registers its own handler to format thrown ApiErrors.\n router.onError(errorHandler);\n\n // List all jobs\n router.get(\"/\", (c) => {\n const jobs = scheduler.listJobs();\n // A file that failed to load is not a job, so it appears nowhere in\n // this list — and \"my job is missing\" and \"my job is not scheduled\"\n // look identical from here. Say how many were dropped, as the\n // functions listing does, so the Studio panel and anyone with curl can\n // see it without boot-log access.\n //\n // Two ways to be dropped, counted together and reported apart. A file\n // the loader could not read has only a count: the failure happened\n // before there was a job to name. A schedule the scheduler refused has a\n // name and a reason — most often \"Expected 5 fields, got 6\", from an\n // expression copied out of a tool that supports seconds — and quoting it\n // here turns a job that silently never fires into a one-line fix.\n const rejected = scheduler.listRejectedJobs();\n const total = skipped + rejected.length;\n return c.json({\n jobs,\n ...(total > 0 && {\n skipped: total,\n ...(rejected.length > 0 && { rejected }),\n note: [\n skipped > 0 ? `${skipped} cron file(s) failed to load` : undefined,\n rejected.length > 0 ? `${rejected.length} job(s) have an invalid schedule` : undefined\n ].filter(Boolean).join(\" and \") +\n \" — NOT scheduled. \" +\n (rejected.length > 0\n ? \"See `rejected` for the reason; \"\n : \"\") +\n \"the server log has the rest.\"\n })\n });\n });\n\n // Get single job\n router.get(\"/:id\", (c) => {\n const id = c.req.param(\"id\");\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n return c.json({ job });\n });\n\n // Trigger a job manually\n router.post(\"/:id/trigger\", async (c) => {\n const id = c.req.param(\"id\");\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const log = await scheduler.triggerJob(id);\n return c.json({ log,\njob: scheduler.getJob(id) });\n });\n\n // Get job logs\n router.get(\"/:id/logs\", async (c) => {\n const id = c.req.param(\"id\");\n // Validated, not `parseInt`-ed. `?limit=abc` used to reach the store as\n // `NaN`, where Postgres refused `LIMIT NaN`, the store swallowed the\n // error and returned `[]` — a 200 with an empty list, which reads as\n // \"this job has never run\". The data plane answers 400 for the same\n // input; so does this now.\n const limit = resolveListLimitParam(c.req.query(\"limit\") ?? null, { defaultLimit: 50 });\n\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const logs = await scheduler.getJobLogsFromDb(id, limit);\n return c.json({ logs });\n });\n\n // Enable/disable a job\n router.put(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const body = await c.req.json().catch(() => ({})) as { enabled: boolean };\n\n if (typeof body.enabled !== \"boolean\") {\n throw ApiError.badRequest(\"Missing 'enabled' boolean in body\");\n }\n\n const job = scheduler.setJobEnabled(id, body.enabled);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n return c.json({ job });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,WAA0B,UAAU,GAAkB;CACnF,MAAM,SAAS,IAAI,KAAc;CAGjC,OAAO,QAAQ,YAAY;CAG3B,OAAO,IAAI,MAAM,MAAM;EACnB,MAAM,OAAO,UAAU,SAAS;EAahC,MAAM,WAAW,UAAU,iBAAiB;EAC5C,MAAM,QAAQ,UAAU,SAAS;EACjC,OAAO,EAAE,KAAK;GACV;GACA,GAAI,QAAQ,KAAK;IACb,SAAS;IACT,GAAI,SAAS,SAAS,KAAK,EAAE,SAAS;IACtC,MAAM,CACF,UAAU,IAAI,GAAG,QAAQ,gCAAgC,KAAA,GACzD,SAAS,SAAS,IAAI,GAAG,SAAS,OAAO,oCAAoC,KAAA,CACjF,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,OAAO,IAC1B,wBACC,SAAS,SAAS,IACb,oCACA,MACN;GACR;EACJ,CAAC;CACL,CAAC;CAGD,OAAO,IAAI,SAAS,MAAM;EACtB,MAAM,KAAK,EAAE,IAAI,MAAM,IAAI;EAC3B,MAAM,MAAM,UAAU,OAAO,EAAE;EAC/B,IAAI,CAAC,KACD,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAExD,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;CACzB,CAAC;CAGD,OAAO,KAAK,gBAAgB,OAAO,MAAM;EACrC,MAAM,KAAK,EAAE,IAAI,MAAM,IAAI;EAE3B,IAAI,CADQ,UAAU,OAAO,EACxB,GACD,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,MAAM,MAAM,MAAM,UAAU,WAAW,EAAE;EACzC,OAAO,EAAE,KAAK;GAAE;GACxB,KAAK,UAAU,OAAO,EAAE;EAAE,CAAC;CACvB,CAAC;CAGD,OAAO,IAAI,aAAa,OAAO,MAAM;EACjC,MAAM,KAAK,EAAE,IAAI,MAAM,IAAI;EAM3B,MAAM,QAAQ,sBAAsB,EAAE,IAAI,MAAM,OAAO,KAAK,MAAM,EAAE,cAAc,GAAG,CAAC;EAGtF,IAAI,CADQ,UAAU,OAAO,EACxB,GACD,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,MAAM,OAAO,MAAM,UAAU,iBAAiB,IAAI,KAAK;EACvD,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC;CAC1B,CAAC;CAGD,OAAO,IAAI,QAAQ,OAAO,MAAM;EAC5B,MAAM,KAAK,EAAE,IAAI,MAAM,IAAI;EAC3B,MAAM,OAAO,MAAM,EAAE,IAAI,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE;EAEhD,IAAI,OAAO,KAAK,YAAY,WACxB,MAAM,SAAS,WAAW,mCAAmC;EAGjE,MAAM,MAAM,UAAU,cAAc,IAAI,KAAK,OAAO;EACpD,IAAI,CAAC,KACD,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;CACzB,CAAC;CAED,OAAO;AACX"}
1
+ {"version":3,"file":"cron-routes-Bfwni8Zg.js","names":[],"sources":["../src/cron/cron-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { HonoEnv } from \"../api/types\";\nimport type { CronScheduler } from \"./cron-scheduler\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { resolveListLimitParam } from \"../api/rest/query-parser\";\n\n/**\n * Create admin REST routes for managing cron jobs.\n *\n * Routes:\n * GET / → list all cron jobs\n * GET /:id → get a single job's status\n * POST /:id/trigger → manually trigger a job\n * GET /:id/logs → get execution logs for a job\n * PUT /:id → update job (enable/disable)\n */\nexport function createCronRoutes(scheduler: CronScheduler, skipped = 0): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n // Hono's onError does NOT propagate from parent to child routers, so this\n // child router registers its own handler to format thrown ApiErrors.\n router.onError(errorHandler);\n\n // List all jobs\n router.get(\"/\", (c) => {\n const jobs = scheduler.listJobs();\n // A file that failed to load is not a job, so it appears nowhere in\n // this list — and \"my job is missing\" and \"my job is not scheduled\"\n // look identical from here. Say how many were dropped, as the\n // functions listing does, so the Studio panel and anyone with curl can\n // see it without boot-log access.\n //\n // Two ways to be dropped, counted together and reported apart. A file\n // the loader could not read has only a count: the failure happened\n // before there was a job to name. A schedule the scheduler refused has a\n // name and a reason — most often \"Expected 5 fields, got 6\", from an\n // expression copied out of a tool that supports seconds — and quoting it\n // here turns a job that silently never fires into a one-line fix.\n const rejected = scheduler.listRejectedJobs();\n const total = skipped + rejected.length;\n return c.json({\n jobs,\n ...(total > 0 && {\n skipped: total,\n ...(rejected.length > 0 && { rejected }),\n note: [\n skipped > 0 ? `${skipped} cron file(s) failed to load` : undefined,\n rejected.length > 0 ? `${rejected.length} job(s) have an invalid schedule` : undefined\n ].filter(Boolean).join(\" and \") +\n \" — NOT scheduled. \" +\n (rejected.length > 0\n ? \"See `rejected` for the reason; \"\n : \"\") +\n \"the server log has the rest.\"\n })\n });\n });\n\n // Get single job\n router.get(\"/:id\", (c) => {\n const id = c.req.param(\"id\");\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n return c.json({ job });\n });\n\n // Trigger a job manually\n router.post(\"/:id/trigger\", async (c) => {\n const id = c.req.param(\"id\");\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const log = await scheduler.triggerJob(id);\n return c.json({ log,\njob: scheduler.getJob(id) });\n });\n\n // Get job logs\n router.get(\"/:id/logs\", async (c) => {\n const id = c.req.param(\"id\");\n // Validated, not `parseInt`-ed. `?limit=abc` used to reach the store as\n // `NaN`, where Postgres refused `LIMIT NaN`, the store swallowed the\n // error and returned `[]` — a 200 with an empty list, which reads as\n // \"this job has never run\". The data plane answers 400 for the same\n // input; so does this now.\n const limit = resolveListLimitParam(c.req.query(\"limit\") ?? null, { defaultLimit: 50 });\n\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const logs = await scheduler.getJobLogsFromDb(id, limit);\n return c.json({ logs });\n });\n\n // Enable/disable a job\n router.put(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const body = await c.req.json().catch(() => ({})) as { enabled: boolean };\n\n if (typeof body.enabled !== \"boolean\") {\n throw ApiError.badRequest(\"Missing 'enabled' boolean in body\");\n }\n\n const job = scheduler.setJobEnabled(id, body.enabled);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n return c.json({ job });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,WAA0B,UAAU,GAAkB;CACnF,MAAM,SAAS,IAAI,KAAc;CAGjC,OAAO,QAAQ,YAAY;CAG3B,OAAO,IAAI,MAAM,MAAM;EACnB,MAAM,OAAO,UAAU,SAAS;EAahC,MAAM,WAAW,UAAU,iBAAiB;EAC5C,MAAM,QAAQ,UAAU,SAAS;EACjC,OAAO,EAAE,KAAK;GACV;GACA,GAAI,QAAQ,KAAK;IACb,SAAS;IACT,GAAI,SAAS,SAAS,KAAK,EAAE,SAAS;IACtC,MAAM,CACF,UAAU,IAAI,GAAG,QAAQ,gCAAgC,KAAA,GACzD,SAAS,SAAS,IAAI,GAAG,SAAS,OAAO,oCAAoC,KA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cAAc,IAAI,KAAK,OAAO;EACpD,IAAI,CAAC,KACD,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;CACzB,CAAC;CAED,OAAO;AACX"}
@@ -3,7 +3,7 @@ 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 "./src-Dgk200Dh.js";
6
+ import "./src-DqZ9YiGA.js";
7
7
  import "./src-Br6ARbs6.js";
8
8
  import { n as createDdlBootstrapper, o as isSQLAdmin, r as hasInCauseChain } from "./ddl-bootstrap-CfNvxMuK.js";
9
9
  import { t as revokeInternalTableSql } from "./internal-tables-DYVcFFSv.js";
@@ -182,4 +182,4 @@ function rowToLogEntry(row) {
182
182
  //#endregion
183
183
  export { cron_store_exports as n, createCronStore as t };
184
184
 
185
- //# sourceMappingURL=cron-store-DuZMJvSh.js.map
185
+ //# sourceMappingURL=cron-store-Bsiw4Q6u.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cron-store-DuZMJvSh.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 job execution logs.\n *\n * Uses the DataDriver's `admin.executeSql` capability to store logs in a\n * `rebase.cron_logs` table. Falls back gracefully if the driver doesn't\n * support SQL (e.g. MongoDB) — in that case, no persistence occurs.\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 * @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 * Fails open (returns true) on unexpected store errors, so a broken\n * claims table degrades to uncoordinated execution rather than silently\n * never running jobs.\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\n// ─── SQL-based implementation ────────────────────────────────────────\n\nconst TABLE = \"rebase.cron_logs\";\nconst CLAIMS_TABLE = \"rebase.cron_claims\";\n\n/** Claims older than this are garbage-collected on startup. */\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): 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 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 // 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] = await Promise.all([\n ddl.isReadable(TABLE),\n ddl.isReadable(CLAIMS_TABLE)\n ]);\n\n if (claimsReady) {\n // Garbage-collect old claims — they are only needed while\n // instances could still contend on the same slot.\n await ddl.step(\"Claim retention sweep\", async () => {\n await exec(\n `DELETE FROM ${CLAIMS_TABLE} WHERE claimed_at < now() - make_interval(days => $1)`,\n { params: [CLAIM_RETENTION_DAYS] }\n );\n });\n\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\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\n if (logsReady && claimsReady) {\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 },\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 try {\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 } catch (err) {\n logger.error(`[cron-store] Failed to fetch logs for \"${jobId}\"`, { error: err });\n return [];\n }\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 // Fail open: better to risk a duplicate run than to have a\n // broken claims table silently stop all cron execution.\n logger.warn(`[cron-store] Claim check failed for \"${jobId}\" — running uncoordinated`, { error: err });\n return true;\n }\n }\n };\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\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":";;;;;;;;;;;;AAyDA,IAAM,QAAQ;AACd,IAAM,eAAe;;AAGrB,IAAM,uBAAuB;;;;;;AAO7B,IAAM,4BAA4B;;;;;;;;;;;;AAalC,SAAS,k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B,WAAW,IAAI;KACf,eAAe,IAAI;KACnB,WAAW,IAAI,cAAc,IAAI,KAAK,IAAI,WAAqB,CAAC,CAAC,YAAY,IAAI,KAAA;IACrF,CAAC;GAET,SAAS,KAAK;IACV,OAAO,MAAM,0CAA0C,EAAE,OAAO,IAAI,CAAC;GACzE;GACA,OAAO;EACX;EAEA,MAAM,YAAY,OAAe,MAAgC;GAC7D,IAAI;IAQA,QAAO,MAPY,KACf,eAAe,aAAa;;;wCAI5B,EAAE,QAAQ,CAAC,OAAO,IAAI,EAAE,CAC5B,EAAA,CACY,SAAS;GACzB,SAAS,KAAK;IACV,IAAI,kBAAkB,GAAG,GAErB,OAAO;IAIX,OAAO,KAAK,wCAAwC,MAAM,4BAA4B,EAAE,OAAO,IAAI,CAAC;IACpG,OAAO;GACX;EACJ;CACJ;AACJ;AAIA,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"}
1
+ {"version":3,"file":"cron-store-Bsiw4Q6u.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 job execution logs.\n *\n * Uses the DataDriver's `admin.executeSql` capability to store logs in a\n * `rebase.cron_logs` table. Falls back gracefully if the driver doesn't\n * support SQL (e.g. MongoDB) — in that case, no persistence occurs.\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 * @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 * Fails open (returns true) on unexpected store errors, so a broken\n * claims table degrades to uncoordinated execution rather than silently\n * never running jobs.\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\n// ─── SQL-based implementation ────────────────────────────────────────\n\nconst TABLE = \"rebase.cron_logs\";\nconst CLAIMS_TABLE = \"rebase.cron_claims\";\n\n/** Claims older than this are garbage-collected on startup. */\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): 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 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 // 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] = await Promise.all([\n ddl.isReadable(TABLE),\n ddl.isReadable(CLAIMS_TABLE)\n ]);\n\n if (claimsReady) {\n // Garbage-collect old claims — they are only needed while\n // instances could still contend on the same slot.\n await ddl.step(\"Claim retention sweep\", async () => {\n await exec(\n `DELETE FROM ${CLAIMS_TABLE} WHERE claimed_at < now() - make_interval(days => $1)`,\n { params: [CLAIM_RETENTION_DAYS] }\n );\n });\n\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\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\n if (logsReady && claimsReady) {\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 },\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 try {\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 } catch (err) {\n logger.error(`[cron-store] Failed to fetch logs for \"${jobId}\"`, { error: err });\n return [];\n }\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 // Fail open: better to risk a duplicate run than to have a\n // broken claims table silently stop all cron execution.\n logger.warn(`[cron-store] Claim check failed for \"${jobId}\" — running uncoordinated`, { error: err });\n return true;\n }\n }\n };\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\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":";;;;;;;;;;;;AAyDA,IAAM,QAAQ;AACd,IAAM,eAAe;;AAGrB,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,SAAS,0BAA0B,CACnF;AACJ;AAEA,SAAgB,gBAAgB,QAA2C;CACvE,MAAM,QAAQ,OAAO;CACrB,IAAI,CAAC,WAAW,KAAK,GAAG;EACpB,OAAO,KAAK,0FAA0F;EACtG;CACJ;CAEA,MAAM,QAAQ,SAAiB,YAC3B,MAAM,WAAW,SAAS,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,KAAA,CAAS;CAEtF,MAAM,MAAM,sBAAsB,MAAM,YAAY;CAEpD,OAAO;EACH,MAAM,cAA6B;GAO/B,MAAM,IAAI,aAAa,0BAA0B,oCAAoC;GAErF,MAAM,IAAI,aAAa,YAAY,SAAS;6CACX,MAAM;;;;;;;;;;;;aAYtC;GAED,MAAM,IAAI,aAAa,8BAA8B;;qBAE5C,MAAM;aACd;GAED,MAAM,IAAI,aAAa,YAAY,gBAAgB;6CAClB,aAAa;;;;;;aAM7C;GASD,MAAM,CAAC,WAAW,eAAe,MAAM,QAAQ,IAAI,CAC/C,IAAI,WAAW,KAAK,GACpB,IAAI,WAAW,YAAY,CAC/B,CAAC;GAED,IAAI,aAAa;IAGb,MAAM,IAAI,KAAK,yBAAyB,YAAY;KAChD,MAAM,KACF,eAAe,aAAa,wDAC5B,EAAE,QAAQ,CAAC,oBAAoB,EAAE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E,OAAO,CAAC;GAAG;EAAE,EAAA,CAAG,IAAI,CAAC;EAC5I,QAAQ,IAAI;CAChB;AACJ"}
@@ -3,7 +3,7 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { r as logger } from "./logger-DO2PZc4i.js";
6
- import { a as recordSamples, i as readSeries, n as SAMPLE_INTERVAL_MS, o as sampleSelf, r as ensureMetricsHistory } from "./history-store-BPErMNQq.js";
6
+ import { a as recordSamples, i as readSeries, n as SAMPLE_INTERVAL_MS, o as sampleSelf, r as ensureMetricsHistory } from "./history-store-D4RVK-uZ.js";
7
7
  import { monitorEventLoopDelay } from "node:perf_hooks";
8
8
  //#region src/metrics/history-recorder.ts
9
9
  /**
@@ -73,4 +73,4 @@ function createMetricsHistory(driver) {
73
73
  //#endregion
74
74
  export { createMetricsHistory };
75
75
 
76
- //# sourceMappingURL=history-recorder-oJZctx5W.js.map
76
+ //# sourceMappingURL=history-recorder-r5_IzSHK.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"history-recorder-oJZctx5W.js","names":[],"sources":["../src/metrics/history-recorder.ts"],"sourcesContent":["/**\n * Wiring the history store to a driver and a timer.\n *\n * Split from `history-store.ts` so the store stays pure — every rule in it is\n * testable with a fake executor, and nothing there knows what a DataDriver is.\n * This half is the part that cannot be unit-tested meaningfully: it opens a\n * connection and starts an interval.\n */\nimport { monitorEventLoopDelay } from \"node:perf_hooks\";\nimport { logger } from \"../utils/logger.js\";\nimport type { DataDriver } from \"@rebasepro/types\";\nimport {\n ensureMetricsHistory,\n recordSamples,\n readSeries,\n sampleSelf,\n SAMPLE_INTERVAL_MS,\n type Exec,\n type MetricSeries,\n type SeriesPoint\n} from \"./history-store.js\";\n\nexport interface MetricsHistory {\n /** Create the table and sweep what has aged out. */\n ensure(): Promise<void>;\n /** Begin sampling this process. Returns a stop. */\n start(): () => void;\n /** Read one series, for the route and for anything else that asks. */\n read(series: MetricSeries, sinceMinutes: number): Promise<SeriesPoint[]>;\n}\n\n/** Narrow structural check, matching how the job store decides the same thing. */\nfunction sqlExecutorOf(driver: DataDriver): Exec | undefined {\n const admin = (driver as { admin?: { executeSql?: unknown } }).admin;\n if (!admin || typeof admin.executeSql !== \"function\") return undefined;\n const executeSql = admin.executeSql as (sql: string, opts?: { params?: unknown[] }) => Promise<unknown>;\n return (sql, params) => executeSql(sql, params ? { params } : undefined);\n}\n\n/**\n * History for this deployment, or `undefined` when it cannot have any.\n *\n * Undefined rather than a no-op: the route turns it into a named 501, because a\n * chart that renders empty is indistinguishable from a quiet period and this is\n * exactly the class of silence the panel it feeds exists to remove.\n */\nexport function createMetricsHistory(driver: DataDriver): MetricsHistory | undefined {\n const exec = sqlExecutorOf(driver);\n if (!exec) {\n logger.debug(\"[metrics] driver has no SQL admin — no metrics history will be kept.\");\n return undefined;\n }\n\n return {\n ensure: () => ensureMetricsHistory(exec),\n read: (series, sinceMinutes) => readSeries(exec, series, sinceMinutes),\n start(): () => void {\n // Which process this is. A tenant's replicas share one database and\n // each records its own numbers, so a row needs to say whose they\n // are — without it they overwrite each other and a scaled-out app\n // charts one arbitrary pod.\n //\n // HOSTNAME is the pod name on Kubernetes and the container id under\n // Docker; the pid fallback keeps two local processes distinct.\n const instance = process.env.HOSTNAME?.trim() || `pid-${process.pid}`;\n let cursor: { cpu: NodeJS.CpuUsage; at: number } | null = null;\n let stopped = false;\n\n // Event-loop delay: how long a callback waited past its schedule.\n // The one number here that says whether this process is *healthy*\n // rather than how much it is consuming — a pod can sit at 20% CPU\n // and still be unable to answer, and nothing else recorded would\n // show it.\n //\n // `monitorEventLoopDelay` samples in libuv at a fixed resolution and\n // costs effectively nothing; `.enable()` is required, and the\n // histogram is reset each tick so every sample describes its own\n // minute rather than the process's whole life.\n interface LoopHistogram { mean: number; enable(): void; reset(): void }\n let loop: LoopHistogram | null = null;\n try {\n loop = monitorEventLoopDelay({ resolution: 20 }) as unknown as LoopHistogram;\n loop.enable();\n } catch {\n // A runtime without it still records the other two.\n loop = null;\n }\n\n const tick = async () => {\n if (stopped) return;\n // Nanoseconds from the histogram, milliseconds on the wire.\n const delayMs = loop ? loop.mean / 1e6 : undefined;\n loop?.reset();\n const { samples, cursor: next } = sampleSelf(cursor, Date.now(), delayMs);\n cursor = next;\n try {\n await recordSamples(exec, samples, instance);\n } catch (err) {\n // Never fatal, and never noisy: a sampler that crash-loops a\n // pod over a chart would be a far worse trade than a gap in\n // one. The gap is visible in the data; a restart loop is not.\n logger.debug(\"[metrics] could not record a sample\", { err });\n }\n };\n\n // The first tick establishes the CPU cursor and publishes memory;\n // the rate needs a second reading, which is why nothing claims a CPU\n // figure until one interval has passed.\n void tick();\n const timer = setInterval(() => void tick(), SAMPLE_INTERVAL_MS);\n // Not the reason this process should stay alive.\n timer.unref?.();\n\n return () => { stopped = true; clearInterval(timer); };\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,SAAS,cAAc,QAAsC;CACzD,MAAM,QAAS,OAAgD;CAC/D,IAAI,CAAC,SAAS,OAAO,MAAM,eAAe,YAAY,OAAO,KAAA;CAC7D,MAAM,aAAa,MAAM;CACzB,QAAQ,KAAK,WAAW,WAAW,KAAK,SAAS,EAAE,OAAO,IAAI,KAAA,CAAS;AAC3E;;;;;;;;AASA,SAAgB,qBAAqB,QAAgD;CACjF,MAAM,OAAO,cAAc,MAAM;CACjC,IAAI,CAAC,MAAM;EACP,OAAO,MAAM,sEAAsE;EACnF;CACJ;CAEA,OAAO;EACH,cAAc,qBAAqB,IAAI;EACvC,OAAO,QAAQ,iBAAiB,WAAW,MAAM,QAAQ,YAAY;EACrE,QAAoB;GAQhB,MAAM,WAAW,QAAQ,IAAI,UAAU,KAAK,KAAK,OAAO,QAAQ;GAChE,IAAI,SAAsD;GAC1D,IAAI,UAAU;GAad,IAAI,OAA6B;GACjC,IAAI;IACA,OAAO,sBAAsB,EAAE,YAAY,GAAG,CAAC;IAC/C,KAAK,OAAO;GAChB,QAAQ;IAEJ,OAAO;GACX;GAEA,MAAM,OAAO,YAAY;IACrB,IAAI,SAAS;IAEb,MAAM,UAAU,OAAO,KAAK,OAAO,MAAM,KAAA;IACzC,MAAM,MAAM;IACZ,MAAM,EAAE,SAAS,QAAQ,SAAS,WAAW,QAAQ,KAAK,IAAI,GAAG,OAAO;IACxE,SAAS;IACT,IAAI;KACA,MAAM,cAAc,MAAM,SAAS,QAAQ;IAC/C,SAAS,KAAK;KAIV,OAAO,MAAM,uCAAuC,EAAE,IAAI,CAAC;IAC/D;GACJ;GAKA,KAAU;GACV,MAAM,QAAQ,kBAAkB,KAAK,KAAK,GAAG,kBAAkB;GAE/D,MAAM,QAAQ;GAEd,aAAa;IAAE,UAAU;IAAM,cAAc,KAAK;GAAG;EACzD;CACJ;AACJ"}
1
+ {"version":3,"file":"history-recorder-r5_IzSHK.js","names":[],"sources":["../src/metrics/history-recorder.ts"],"sourcesContent":["/**\n * Wiring the history store to a driver and a timer.\n *\n * Split from `history-store.ts` so the store stays pure — every rule in it is\n * testable with a fake executor, and nothing there knows what a DataDriver is.\n * This half is the part that cannot be unit-tested meaningfully: it opens a\n * connection and starts an interval.\n */\nimport { monitorEventLoopDelay } from \"node:perf_hooks\";\nimport { logger } from \"../utils/logger.js\";\nimport type { DataDriver } from \"@rebasepro/types\";\nimport {\n ensureMetricsHistory,\n recordSamples,\n readSeries,\n sampleSelf,\n SAMPLE_INTERVAL_MS,\n type Exec,\n type MetricSeries,\n type SeriesPoint\n} from \"./history-store.js\";\n\nexport interface MetricsHistory {\n /** Create the table and sweep what has aged out. */\n ensure(): Promise<void>;\n /** Begin sampling this process. Returns a stop. */\n start(): () => void;\n /** Read one series, for the route and for anything else that asks. */\n read(series: MetricSeries, sinceMinutes: number): Promise<SeriesPoint[]>;\n}\n\n/** Narrow structural check, matching how the job store decides the same thing. */\nfunction sqlExecutorOf(driver: DataDriver): Exec | undefined {\n const admin = (driver as { admin?: { executeSql?: unknown } }).admin;\n if (!admin || typeof admin.executeSql !== \"function\") return undefined;\n const executeSql = admin.executeSql as (sql: string, opts?: { params?: unknown[] }) => Promise<unknown>;\n return (sql, params) => executeSql(sql, params ? { params } : undefined);\n}\n\n/**\n * History for this deployment, or `undefined` when it cannot have any.\n *\n * Undefined rather than a no-op: the route turns it into a named 501, because a\n * chart that renders empty is indistinguishable from a quiet period and this is\n * exactly the class of silence the panel it feeds exists to remove.\n */\nexport function createMetricsHistory(driver: DataDriver): MetricsHistory | undefined {\n const exec = sqlExecutorOf(driver);\n if (!exec) {\n logger.debug(\"[metrics] driver has no SQL admin — no metrics history will be kept.\");\n return undefined;\n }\n\n return {\n ensure: () => ensureMetricsHistory(exec),\n read: (series, sinceMinutes) => readSeries(exec, series, sinceMinutes),\n start(): () => void {\n // Which process this is. A tenant's replicas share one database and\n // each records its own numbers, so a row needs to say whose they\n // are — without it they overwrite each other and a scaled-out app\n // charts one arbitrary pod.\n //\n // HOSTNAME is the pod name on Kubernetes and the container id under\n // Docker; the pid fallback keeps two local processes distinct.\n const instance = process.env.HOSTNAME?.trim() || `pid-${process.pid}`;\n let cursor: { cpu: NodeJS.CpuUsage; at: number } | null = null;\n let stopped = false;\n\n // Event-loop delay: how long a callback waited past its schedule.\n // The one number here that says whether this process is *healthy*\n // rather than how much it is consuming — a pod can sit at 20% CPU\n // and still be unable to answer, and nothing else recorded would\n // show it.\n //\n // `monitorEventLoopDelay` samples in libuv at a fixed resolution and\n // costs effectively nothing; `.enable()` is required, and the\n // histogram is reset each tick so every sample describes its own\n // minute rather than the process's whole life.\n interface LoopHistogram { mean: number; enable(): void; reset(): void }\n let loop: LoopHistogram | null = null;\n try {\n loop = monitorEventLoopDelay({ resolution: 20 }) as unknown as LoopHistogram;\n loop.enable();\n } catch {\n // A runtime without it still records the other two.\n loop = null;\n }\n\n const tick = async () => {\n if (stopped) return;\n // Nanoseconds from the histogram, milliseconds on the wire.\n const delayMs = loop ? loop.mean / 1e6 : undefined;\n loop?.reset();\n const { samples, cursor: next } = sampleSelf(cursor, Date.now(), delayMs);\n cursor = next;\n try {\n await recordSamples(exec, samples, instance);\n } catch (err) {\n // Never fatal, and never noisy: a sampler that crash-loops a\n // pod over a chart would be a far worse trade than a gap in\n // one. The gap is visible in the data; a restart loop is not.\n logger.debug(\"[metrics] could not record a sample\", { err });\n }\n };\n\n // The first tick establishes the CPU cursor and publishes memory;\n // the rate needs a second reading, which is why nothing claims a CPU\n // figure until one interval has passed.\n void tick();\n const timer = setInterval(() => void tick(), SAMPLE_INTERVAL_MS);\n // Not the reason this process should stay alive.\n timer.unref?.();\n\n return () => { stopped = true; clearInterval(timer); };\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,SAAS,cAAc,QAAsC;CACzD,MAAM,QAAS,OAAgD;CAC/D,IAAI,CAAC,SAAS,OAAO,MAAM,eAAe,YAAY,OAAO,KAAA;CAC7D,MAAM,aAAa,MAAM;CACzB,QAAQ,KAAK,WAAW,WAAW,KAAK,SAAS,EAAE,OAAO,IAAI,KAAA,CAAS;AAC3E;;;;;;;;AASA,SAAgB,qBAAqB,QAAgD;CACjF,MAAM,OAAO,cAAc,MAAM;CACjC,IAAI,CAAC,MAAM;EACP,OAAO,MAAM,sEAAsE;EACnF;CACJ;CAEA,OAAO;EACH,cAAc,qBAAqB,IAAI;EACvC,OAAO,QAAQ,iBAAiB,WAAW,MAAM,QAAQ,YAAY;EACrE,QAAoB;GAQhB,MAAM,WAAW,QAAQ,IAAI,UAAU,KAAK,KAAK,OAAO,QAAQ;GAChE,IAAI,SAAsD;GAC1D,IAAI,UAAU;GAad,IAAI,OAA6B;GACjC,IAAI;IACA,OAAO,sBAAsB,EAAE,YAAY,GAAG,CAAC;IAC/C,KAAK,OAAO;GAChB,QAAQ;IAEJ,OAAO;GACX;GAEA,MAAM,OAAO,YAAY;IACrB,IAAI,SAAS;IAEb,MAAM,UAAU,OAAO,KAAK,OAAO,MAAM,KAAA;IACzC,MAAM,MAAM;IACZ,MAAM,EAAE,SAAS,QAAQ,SAAS,WAAW,QAAQ,KAAK,IAAI,GAAG,OAAO;IACxE,SAAS;IACT,IAAI;KACA,MAAM,cAAc,MAAM,SAAS,QAAQ;IAC/C,SAAS,KAAK;KAIV,OAAO,MAAM,uCAAuC,EAAE,IAAI,CAAC;IAC/D;GACJ;GAKA,KAAU;GACV,MAAM,QAAQ,kBAAkB,KAAK,KAAK,GAAG,kBAAkB;GAE/D,MAAM,QAAQ;GAEd,aAAa;IAAE,UAAU;IAAM,cAAc,KAAK;GAAG;EACzD;CACJ;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 "./src-Dgk200Dh.js";
5
+ import "./src-DqZ9YiGA.js";
6
6
  import { t as revokeInternalTableSql } from "./internal-tables-DYVcFFSv.js";
7
7
  //#region src/metrics/history-store.ts
8
8
  /**
@@ -207,4 +207,4 @@ async function readSeries(exec, series, sinceMinutes) {
207
207
  //#endregion
208
208
  export { recordSamples as a, readSeries as i, SAMPLE_INTERVAL_MS as n, sampleSelf as o, ensureMetricsHistory as r, METRIC_SERIES as t };
209
209
 
210
- //# sourceMappingURL=history-store-BPErMNQq.js.map
210
+ //# sourceMappingURL=history-store-D4RVK-uZ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"history-store-BPErMNQq.js","names":[],"sources":["../src/metrics/history-store.ts"],"sourcesContent":["/**\n * A little history for the metrics this process already keeps.\n *\n * ## Why this is in the framework and not in the cloud console\n *\n * The console wants to draw \"CPU over the last hour\". The obvious way to get it\n * on GKE is Cloud Monitoring, which already collects exactly this — and which\n * would make the panel unportable the day the platform moves, for a feature\n * every self-hoster also wants. So the history lives where the runtime lives:\n * the process samples ITSELF, into its OWN database, and anything that can read\n * the database can draw the chart. No cluster, no metrics-server, no vendor.\n *\n * That is the same rule the binder follows — the cloud is a better\n * implementation behind the same interface, never a different one.\n *\n * ## Why it stays cheap\n *\n * One row per series per instance per minute. Three series across two replicas\n * is 8,640 rows a day, and the sweep below bounds the window, so the table settles\n * at a size measured in megabytes. It is deliberately NOT a general time-series\n * store: no labels, no cardinality to explode, no per-request rows.\n *\n * A minute is the resolution because that is what the question needs — \"was it\n * slow at 15:40\", \"did my deploy cause that\" — and because a finer grain buys\n * nothing a reader can see on a chart of an hour.\n */\n/**\n * The positional-parameter shape every store in this package settles on.\n *\n * The bootstrapper's own `SqlExec` takes an options object; each store wraps it\n * once and reads better for it. Same two shapes, same reason, as `job-store`.\n */\nimport { revokeInternalTableSql } from \"@rebasepro/common\";\n\nexport type Exec = (sql: string, params?: unknown[]) => Promise<unknown>;\n\n/** Where the samples live. Framework-owned, like `rebase.jobs`. */\nexport const METRICS_HISTORY_TABLE = \"rebase.metric_samples\";\n\n/**\n * How long a sample is kept.\n *\n * Two weeks answers \"is this worse than last week\" and stops well short of\n * being an archive. Anything that needs to outlive it — billing, capacity\n * planning — is a rollup somebody else owns, not a longer retention here.\n *\n * Read it as \"14 days, or since this process started, whichever is longer\": the\n * sweep runs at boot and nowhere else, so a pod up for 90 days holds 90 days.\n * That is a deliberate trade rather than an oversight — a cron for it would be\n * machinery for a table that stays trivial either way, and reads are bounded by\n * the index regardless — but the table does not \"reach a steady size and stay\n * there\" on a long-lived pod, which an earlier version of this comment claimed.\n */\nexport const RETENTION_DAYS = 14;\n\n/** How often the process samples itself. Matched to the resolution it stores. */\nexport const SAMPLE_INTERVAL_MS = 60_000;\n\n/**\n * The series this records. A closed set on purpose — see the cardinality note.\n *\n * A list rather than only a union, because the route validates against it: an\n * unknown `?series=` must be a named 400 rather than an empty chart, which\n * reads exactly like a quiet period.\n *\n * **It lists what `sampleSelf` actually writes, and nothing else.** It used to\n * also name `requests_total`, `errors_total` and `event_loop_delay_ms`, none of\n * which anything ever recorded — so those three were *valid* parameters that\n * returned `points: []`, which is precisely the empty chart the 400 two\n * paragraphs up exists to prevent. A declared-but-unwritten series is worse\n * than an absent one: the 400 tells you the name is wrong, and the empty array\n * tells you the app was quiet.\n *\n * `event_loop_delay_ms` kept its place by gaining a sampler, because it is the\n * one signal here that says whether the process is *healthy* rather than how\n * much it is using, and it has no counter semantics to get wrong.\n *\n * `requests_total` and `errors_total` were dropped rather than wired up. The\n * registry does hold them, but they reset on restart, and a resetting counter\n * summed across replicas is not monotonic — a rolling deploy would draw a\n * cliff that looks like traffic collapsing. That needs a deliberate decision\n * about deltas and resets, not a line added at 2am. Adding either back means\n * adding its sampler in the same commit.\n */\nexport const METRIC_SERIES = [\n \"cpu_millicores\",\n \"memory_bytes\",\n \"event_loop_delay_ms\"\n] as const;\n\nexport type MetricSeries = (typeof METRIC_SERIES)[number];\n\nexport interface MetricSample {\n at: Date;\n series: MetricSeries;\n value: number;\n}\n\n/**\n * Create the table and sweep what has aged out.\n *\n * Called at boot, beside the job and cron stores, and for the same reason they\n * do it there: the only moment the schema is guaranteed to be reachable and\n * nobody is mid-request.\n */\nexport async function ensureMetricsHistory(exec: Exec): Promise<void> {\n await exec(`\n CREATE TABLE IF NOT EXISTS ${METRICS_HISTORY_TABLE} (\n at timestamptz NOT NULL,\n series text NOT NULL,\n instance text NOT NULL,\n value double precision NOT NULL,\n PRIMARY KEY (series, instance, at)\n )\n `, []);\n\n // (series, at DESC) rather than the primary key's order: every read is\n // \"this series across all instances, bounded by time\", and the PK leads with\n // instance, which is the wrong first column for that scan.\n await exec(`\n CREATE INDEX IF NOT EXISTS metric_samples_series_recent\n ON ${METRICS_HISTORY_TABLE} (series, at DESC)\n `, []);\n\n // Framework-internal, so the end-user role must not be able to address it.\n //\n // The driver grants `rebase_user` full DML across the schemas a project\n // uses, plus `ALTER DEFAULT PRIVILEGES` so tables created later inherit it —\n // and this one is created later, at boot. Without the revoke, an\n // authenticated request could read and write another deployment's process\n // metrics, and `pnpm rls:check` correctly called that `[critical]\n // rls-disabled` the first time CI saw the table.\n //\n // REVOKE rather than `ENABLE ROW LEVEL SECURITY`, matching every other table\n // in `REBASE_INTERNAL_TABLES`: RLS with no policy denies the same rows but\n // is the weaker statement, because the grant survives and a later policy\n // reopens it. There is no row here any end user should reach, so \"this role\n // has no privilege at all\" is the honest encoding. The owner connection the\n // recorder runs on is unaffected.\n await exec(revokeInternalTableSql(\"rebase\", \"metric_samples\"), []);\n\n // Swept here rather than by a cron, so a deployment that runs no scheduler\n // still stays bounded. A DELETE is the right tool at this size — a few\n // thousand rows a day — and partitioning would be machinery for a table\n // that never gets big.\n await exec(\n `DELETE FROM ${METRICS_HISTORY_TABLE} WHERE at < now() - make_interval(days => $1)`,\n [RETENTION_DAYS]\n );\n}\n\n/**\n * What this process is using right now.\n *\n * `process.cpuUsage()` is cumulative, so a rate needs two readings and the gap\n * between them — which is why the previous one is threaded through rather than\n * held in a module global: a module global is shared by every test in a file\n * and makes the first assertion depend on whatever ran before it.\n */\nexport function sampleSelf(\n previous: { cpu: NodeJS.CpuUsage; at: number } | null,\n now = Date.now(),\n /**\n * Mean event-loop delay over the last window, in milliseconds, or undefined\n * where it cannot be measured. Passed in rather than read here so this\n * function stays pure: the histogram is a stateful handle the recorder owns.\n */\n eventLoopDelayMs?: number\n): { samples: Omit<MetricSample, \"at\">[]; cursor: { cpu: NodeJS.CpuUsage; at: number } } {\n const cpu = process.cpuUsage();\n const memory = process.memoryUsage();\n const samples: Omit<MetricSample, \"at\">[] = [\n { series: \"memory_bytes\", value: memory.rss }\n ];\n\n // Only when it was actually measured. Zero is a real and common reading for\n // an idle process, so a `?? 0` here would be indistinguishable from a\n // healthy one — the same substitution this module rejects everywhere else.\n if (typeof eventLoopDelayMs === \"number\" && Number.isFinite(eventLoopDelayMs)) {\n samples.push({ series: \"event_loop_delay_ms\", value: eventLoopDelayMs });\n }\n\n if (previous) {\n const elapsedMs = now - previous.at;\n if (elapsedMs > 0) {\n // Microseconds of CPU over milliseconds of wall clock, as\n // millicores: 1000m is one core saturated for the whole window.\n const usedMicros = (cpu.user - previous.cpu.user) + (cpu.system - previous.cpu.system);\n samples.push({ series: \"cpu_millicores\", value: (usedMicros / 1000 / elapsedMs) * 1000 });\n }\n }\n\n return { samples, cursor: { cpu, at: now } };\n}\n\n/**\n * Write one tick's samples, for one instance.\n *\n * ## Why `instance` is part of the key\n *\n * A tenant's replicas share one database, and each records its OWN process. Key\n * a row by `(series, minute)` alone and the pods overwrite each other every\n * tick: one pod at 5m and another at 500m leave whichever wrote last, so a\n * scaled-out tenant charts one arbitrary replica and calls it the app. Adding\n * the instance makes each pod its own row, and lets the read decide whether the\n * question is \"the whole deployment\" or \"which pod is hot\".\n *\n * Cardinality stays bounded: rows are series × replicas × minutes, and replicas\n * are capped by the autoscaling ceiling. Six pods is ~43k rows a day and a\n * fortnight of them is well under a million.\n */\nexport async function recordSamples(\n exec: Exec,\n samples: Omit<MetricSample, \"at\">[],\n instance: string,\n at: Date = new Date()\n): Promise<void> {\n if (samples.length === 0) return;\n // Truncated to the minute, so a pod restarting mid-minute overwrites its own\n // earlier row rather than adding a second one for the same instant.\n const bucket = new Date(Math.floor(at.getTime() / 60_000) * 60_000);\n for (const s of samples) {\n if (!Number.isFinite(s.value)) continue;\n await exec(\n `INSERT INTO ${METRICS_HISTORY_TABLE} (at, series, instance, value)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (series, instance, at) DO UPDATE SET value = EXCLUDED.value`,\n [bucket, s.series, instance, s.value]\n );\n }\n}\n\n/**\n * How a series combines across the replicas that reported it.\n *\n * Not one answer for everything, because the right one differs by what the\n * number means. CPU and memory are consumption: the deployment's figure is the\n * sum, and a mean would make scaling out look like it reduced usage. A queue\n * depth or an event-loop delay is a condition each process is independently in,\n * and summing those produces a number no single pod ever experienced.\n */\nconst COMBINE: Record<MetricSeries, \"sum\" | \"avg\"> = {\n cpu_millicores: \"sum\",\n memory_bytes: \"sum\",\n event_loop_delay_ms: \"avg\"\n};\n\nexport interface SeriesPoint {\n at: string;\n /** The deployment's figure, combined per `COMBINE`. */\n value: number;\n /** How many instances reported in this bucket. */\n instances: number;\n}\n\n/**\n * Read one series over a window, oldest first — the order a chart draws in.\n *\n * Combined across instances rather than returned per-pod. A chart of \"this\n * app's CPU\" is the question people ask; \"which pod is hot\" is answered by the\n * live panel, which already lists instances individually and does not need\n * history to do it.\n *\n * `instances` rides along because a sum whose contributor count changed is not\n * comparable with itself: CPU doubling because the app got busy and CPU\n * doubling because it scaled from one replica to two are different events, and\n * a line chart alone cannot tell them apart.\n */\nexport async function readSeries(\n exec: Exec,\n series: MetricSeries,\n sinceMinutes: number\n): Promise<SeriesPoint[]> {\n const combine = COMBINE[series] === \"avg\" ? \"avg\" : \"sum\";\n // The current minute is EXCLUDED, and that is not tidiness.\n //\n // Each replica samples on its own phase — `setInterval` from whenever that\n // pod booted — so at 10:45:20 the bucket for 10:45 holds rows from whichever\n // pods have ticked so far, typically one of three. The chart takes the last\n // point as its headline figure, so a three-replica app displayed one\n // replica's CPU as the deployment's, the line ended in a cliff, and the\n // instance step dropped underneath it — which the chart's own caption\n // explains to the reader as a scale-down that never happened.\n //\n // Every live pod has written bucket M-1 before the clock enters M, so the\n // newest bucket returned is complete and its `instances` is the true\n // contributor count. `date_trunc` rather than arithmetic because it matches\n // the recorder's `floor(t / 60_000) * 60_000` exactly, and is\n // timezone-independent on a timestamptz.\n const rows = await exec(\n `SELECT at, ${combine}(value) AS value, count(*) AS instances\n FROM ${METRICS_HISTORY_TABLE}\n WHERE series = $1\n AND at >= now() - make_interval(mins => $2)\n AND at < date_trunc('minute', now())\n GROUP BY at\n ORDER BY at ASC`,\n [series, sinceMinutes]\n ) as unknown as { rows?: RawPoint[] } | RawPoint[];\n\n const list = Array.isArray(rows) ? rows : (rows?.rows ?? []);\n return list.map(r => ({\n at: r.at instanceof Date ? r.at.toISOString() : String(r.at),\n value: Number(r.value),\n instances: Number(r.instances ?? 1)\n }));\n}\n\ninterface RawPoint { at: Date | string; value: number; instances?: number | string }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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CAAC,OAAO,SAAS,EAAE,KAAK,GAAG;EAC/B,MAAM,KACF,eAAe,sBAAsB;;uFAGrC;GAAC;GAAQ,EAAE;GAAQ;GAAU,EAAE;EAAK,CACxC;CACJ;AACJ;;;;;;;;;;AAWA,IAAM,UAA+C;CACjD,gBAAgB;CAChB,cAAc;CACd,qBAAqB;AACzB;;;;;;;;;;;;;;AAuBA,eAAsB,WAClB,MACA,QACA,cACsB;CAiBtB,MAAM,OAAO,MAAM,KACf,cAjBY,QAAQ,YAAY,QAAQ,QAAQ,MAiB1B;kBACZ,sBAAsB;;;;;4BAMhC,CAAC,QAAQ,YAAY,CACzB;CAGA,QADa,MAAM,QAAQ,IAAI,IAAI,OAAQ,MAAM,QAAQ,CAAC,EAAA,CAC9C,KAAI,OAAM;EAClB,IAAI,EAAE,cAAc,OAAO,EAAE,GAAG,YAAY,IAAI,OAAO,EAAE,EAAE;EAC3D,OAAO,OAAO,EAAE,KAAK;EACrB,WAAW,OAAO,EAAE,aAAa,CAAC;CACtC,EAAE;AACN"}
1
+ {"version":3,"file":"history-store-D4RVK-uZ.js","names":[],"sources":["../src/metrics/history-store.ts"],"sourcesContent":["/**\n * A little history for the metrics this process already keeps.\n *\n * ## Why this is in the framework and not in the cloud console\n *\n * The console wants to draw \"CPU over the last hour\". The obvious way to get it\n * on GKE is Cloud Monitoring, which already collects exactly this — and which\n * would make the panel unportable the day the platform moves, for a feature\n * every self-hoster also wants. So the history lives where the runtime lives:\n * the process samples ITSELF, into its OWN database, and anything that can read\n * the database can draw the chart. No cluster, no metrics-server, no vendor.\n *\n * That is the same rule the binder follows — the cloud is a better\n * implementation behind the same interface, never a different one.\n *\n * ## Why it stays cheap\n *\n * One row per series per instance per minute. Three series across two replicas\n * is 8,640 rows a day, and the sweep below bounds the window, so the table settles\n * at a size measured in megabytes. It is deliberately NOT a general time-series\n * store: no labels, no cardinality to explode, no per-request rows.\n *\n * A minute is the resolution because that is what the question needs — \"was it\n * slow at 15:40\", \"did my deploy cause that\" — and because a finer grain buys\n * nothing a reader can see on a chart of an hour.\n */\n/**\n * The positional-parameter shape every store in this package settles on.\n *\n * The bootstrapper's own `SqlExec` takes an options object; each store wraps it\n * once and reads better for it. Same two shapes, same reason, as `job-store`.\n */\nimport { revokeInternalTableSql } from \"@rebasepro/common\";\n\nexport type Exec = (sql: string, params?: unknown[]) => Promise<unknown>;\n\n/** Where the samples live. Framework-owned, like `rebase.jobs`. */\nexport const METRICS_HISTORY_TABLE = \"rebase.metric_samples\";\n\n/**\n * How long a sample is kept.\n *\n * Two weeks answers \"is this worse than last week\" and stops well short of\n * being an archive. Anything that needs to outlive it — billing, capacity\n * planning — is a rollup somebody else owns, not a longer retention here.\n *\n * Read it as \"14 days, or since this process started, whichever is longer\": the\n * sweep runs at boot and nowhere else, so a pod up for 90 days holds 90 days.\n * That is a deliberate trade rather than an oversight — a cron for it would be\n * machinery for a table that stays trivial either way, and reads are bounded by\n * the index regardless — but the table does not \"reach a steady size and stay\n * there\" on a long-lived pod, which an earlier version of this comment claimed.\n */\nexport const RETENTION_DAYS = 14;\n\n/** How often the process samples itself. Matched to the resolution it stores. */\nexport const SAMPLE_INTERVAL_MS = 60_000;\n\n/**\n * The series this records. A closed set on purpose — see the cardinality note.\n *\n * A list rather than only a union, because the route validates against it: an\n * unknown `?series=` must be a named 400 rather than an empty chart, which\n * reads exactly like a quiet period.\n *\n * **It lists what `sampleSelf` actually writes, and nothing else.** It used to\n * also name `requests_total`, `errors_total` and `event_loop_delay_ms`, none of\n * which anything ever recorded — so those three were *valid* parameters that\n * returned `points: []`, which is precisely the empty chart the 400 two\n * paragraphs up exists to prevent. A declared-but-unwritten series is worse\n * than an absent one: the 400 tells you the name is wrong, and the empty array\n * tells you the app was quiet.\n *\n * `event_loop_delay_ms` kept its place by gaining a sampler, because it is the\n * one signal here that says whether the process is *healthy* rather than how\n * much it is using, and it has no counter semantics to get wrong.\n *\n * `requests_total` and `errors_total` were dropped rather than wired up. The\n * registry does hold them, but they reset on restart, and a resetting counter\n * summed across replicas is not monotonic — a rolling deploy would draw a\n * cliff that looks like traffic collapsing. That needs a deliberate decision\n * about deltas and resets, not a line added at 2am. Adding either back means\n * adding its sampler in the same commit.\n */\nexport const METRIC_SERIES = [\n \"cpu_millicores\",\n \"memory_bytes\",\n \"event_loop_delay_ms\"\n] as const;\n\nexport type MetricSeries = (typeof METRIC_SERIES)[number];\n\nexport interface MetricSample {\n at: Date;\n series: MetricSeries;\n value: number;\n}\n\n/**\n * Create the table and sweep what has aged out.\n *\n * Called at boot, beside the job and cron stores, and for the same reason they\n * do it there: the only moment the schema is guaranteed to be reachable and\n * nobody is mid-request.\n */\nexport async function ensureMetricsHistory(exec: Exec): Promise<void> {\n await exec(`\n CREATE TABLE IF NOT EXISTS ${METRICS_HISTORY_TABLE} (\n at timestamptz NOT NULL,\n series text NOT NULL,\n instance text NOT NULL,\n value double precision NOT NULL,\n PRIMARY KEY (series, instance, at)\n )\n `, []);\n\n // (series, at DESC) rather than the primary key's order: every read is\n // \"this series across all instances, bounded by time\", and the PK leads with\n // instance, which is the wrong first column for that scan.\n await exec(`\n CREATE INDEX IF NOT EXISTS metric_samples_series_recent\n ON ${METRICS_HISTORY_TABLE} (series, at DESC)\n `, []);\n\n // Framework-internal, so the end-user role must not be able to address it.\n //\n // The driver grants `rebase_user` full DML across the schemas a project\n // uses, plus `ALTER DEFAULT PRIVILEGES` so tables created later inherit it —\n // and this one is created later, at boot. Without the revoke, an\n // authenticated request could read and write another deployment's process\n // metrics, and `pnpm rls:check` correctly called that `[critical]\n // rls-disabled` the first time CI saw the table.\n //\n // REVOKE rather than `ENABLE ROW LEVEL SECURITY`, matching every other table\n // in `REBASE_INTERNAL_TABLES`: RLS with no policy denies the same rows but\n // is the weaker statement, because the grant survives and a later policy\n // reopens it. There is no row here any end user should reach, so \"this role\n // has no privilege at all\" is the honest encoding. The owner connection the\n // recorder runs on is unaffected.\n await exec(revokeInternalTableSql(\"rebase\", \"metric_samples\"), []);\n\n // Swept here rather than by a cron, so a deployment that runs no scheduler\n // still stays bounded. A DELETE is the right tool at this size — a few\n // thousand rows a day — and partitioning would be machinery for a table\n // that never gets big.\n await exec(\n `DELETE FROM ${METRICS_HISTORY_TABLE} WHERE at < now() - make_interval(days => $1)`,\n [RETENTION_DAYS]\n );\n}\n\n/**\n * What this process is using right now.\n *\n * `process.cpuUsage()` is cumulative, so a rate needs two readings and the gap\n * between them — which is why the previous one is threaded through rather than\n * held in a module global: a module global is shared by every test in a file\n * and makes the first assertion depend on whatever ran before it.\n */\nexport function sampleSelf(\n previous: { cpu: NodeJS.CpuUsage; at: number } | null,\n now = Date.now(),\n /**\n * Mean event-loop delay over the last window, in milliseconds, or undefined\n * where it cannot be measured. Passed in rather than read here so this\n * function stays pure: the histogram is a stateful handle the recorder owns.\n */\n eventLoopDelayMs?: number\n): { samples: Omit<MetricSample, \"at\">[]; cursor: { cpu: NodeJS.CpuUsage; at: number } } {\n const cpu = process.cpuUsage();\n const memory = process.memoryUsage();\n const samples: Omit<MetricSample, \"at\">[] = [\n { series: \"memory_bytes\", value: memory.rss }\n ];\n\n // Only when it was actually measured. Zero is a real and common reading for\n // an idle process, so a `?? 0` here would be indistinguishable from a\n // healthy one — the same substitution this module rejects everywhere else.\n if (typeof eventLoopDelayMs === \"number\" && Number.isFinite(eventLoopDelayMs)) {\n samples.push({ series: \"event_loop_delay_ms\", value: eventLoopDelayMs });\n }\n\n if (previous) {\n const elapsedMs = now - previous.at;\n if (elapsedMs > 0) {\n // Microseconds of CPU over milliseconds of wall clock, as\n // millicores: 1000m is one core saturated for the whole window.\n const usedMicros = (cpu.user - previous.cpu.user) + (cpu.system - previous.cpu.system);\n samples.push({ series: \"cpu_millicores\", value: (usedMicros / 1000 / elapsedMs) * 1000 });\n }\n }\n\n return { samples, cursor: { cpu, at: now } };\n}\n\n/**\n * Write one tick's samples, for one instance.\n *\n * ## Why `instance` is part of the key\n *\n * A tenant's replicas share one database, and each records its OWN process. Key\n * a row by `(series, minute)` alone and the pods overwrite each other every\n * tick: one pod at 5m and another at 500m leave whichever wrote last, so a\n * scaled-out tenant charts one arbitrary replica and calls it the app. Adding\n * the instance makes each pod its own row, and lets the read decide whether the\n * question is \"the whole deployment\" or \"which pod is hot\".\n *\n * Cardinality stays bounded: rows are series × replicas × minutes, and replicas\n * are capped by the autoscaling ceiling. Six pods is ~43k rows a day and a\n * fortnight of them is well under a million.\n */\nexport async function recordSamples(\n exec: Exec,\n samples: Omit<MetricSample, \"at\">[],\n instance: string,\n at: Date = new Date()\n): Promise<void> {\n if (samples.length === 0) return;\n // Truncated to the minute, so a pod restarting mid-minute overwrites its own\n // earlier row rather than adding a second one for the same instant.\n const bucket = new Date(Math.floor(at.getTime() / 60_000) * 60_000);\n for (const s of samples) {\n if (!Number.isFinite(s.value)) continue;\n await exec(\n `INSERT INTO ${METRICS_HISTORY_TABLE} (at, series, instance, value)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (series, instance, at) DO UPDATE SET value = EXCLUDED.value`,\n [bucket, s.series, instance, s.value]\n );\n }\n}\n\n/**\n * How a series combines across the replicas that reported it.\n *\n * Not one answer for everything, because the right one differs by what the\n * number means. CPU and memory are consumption: the deployment's figure is the\n * sum, and a mean would make scaling out look like it reduced usage. A queue\n * depth or an event-loop delay is a condition each process is independently in,\n * and summing those produces a number no single pod ever experienced.\n */\nconst COMBINE: Record<MetricSeries, \"sum\" | \"avg\"> = {\n cpu_millicores: \"sum\",\n memory_bytes: \"sum\",\n event_loop_delay_ms: \"avg\"\n};\n\nexport interface SeriesPoint {\n at: string;\n /** The deployment's figure, combined per `COMBINE`. */\n value: number;\n /** How many instances reported in this bucket. */\n instances: number;\n}\n\n/**\n * Read one series over a window, oldest first — the order a chart draws in.\n *\n * Combined across instances rather than returned per-pod. A chart of \"this\n * app's CPU\" is the question people ask; \"which pod is hot\" is answered by the\n * live panel, which already lists instances individually and does not need\n * history to do it.\n *\n * `instances` rides along because a sum whose contributor count changed is not\n * comparable with itself: CPU doubling because the app got busy and CPU\n * doubling because it scaled from one replica to two are different events, and\n * a line chart alone cannot tell them apart.\n */\nexport async function readSeries(\n exec: Exec,\n series: MetricSeries,\n sinceMinutes: number\n): Promise<SeriesPoint[]> {\n const combine = COMBINE[series] === \"avg\" ? \"avg\" : \"sum\";\n // The current minute is EXCLUDED, and that is not tidiness.\n //\n // Each replica samples on its own phase — `setInterval` from whenever that\n // pod booted — so at 10:45:20 the bucket for 10:45 holds rows from whichever\n // pods have ticked so far, typically one of three. The chart takes the last\n // point as its headline figure, so a three-replica app displayed one\n // replica's CPU as the deployment's, the line ended in a cliff, and the\n // instance step dropped underneath it — which the chart's own caption\n // explains to the reader as a scale-down that never happened.\n //\n // Every live pod has written bucket M-1 before the clock enters M, so the\n // newest bucket returned is complete and its `instances` is the true\n // contributor count. `date_trunc` rather than arithmetic because it matches\n // the recorder's `floor(t / 60_000) * 60_000` exactly, and is\n // timezone-independent on a timestamptz.\n const rows = await exec(\n `SELECT at, ${combine}(value) AS value, count(*) AS instances\n FROM ${METRICS_HISTORY_TABLE}\n WHERE series = $1\n AND at >= now() - make_interval(mins => $2)\n AND at < date_trunc('minute', now())\n GROUP BY at\n ORDER BY at ASC`,\n [series, sinceMinutes]\n ) as unknown as { rows?: RawPoint[] } | RawPoint[];\n\n const list = Array.isArray(rows) ? rows : (rows?.rows ?? []);\n return list.map(r => ({\n at: r.at instanceof Date ? r.at.toISOString() : String(r.at),\n value: Number(r.value),\n instances: Number(r.instances ?? 1)\n }));\n}\n\ninterface RawPoint { at: Date | string; value: number; instances?: number | string }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,wBAAwB;;AAmBrC,IAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BlC,IAAa,gBAAgB;CACzB;CACA;CACA;AACJ;;;;;;;;AAiBA,eAAsB,qBAAqB,MAA2B;CAClE,MAAM,KAAK;qCACsB,sBAAsB;;;;;;;OAOpD,C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;AACzB;;;;;;;;;;;;;;AAuBA,eAAsB,WAClB,MACA,QACA,cACsB;CAiBtB,MAAM,OAAO,MAAM,KACf,cAjBY,QAAQ,YAAY,QAAQ,QAAQ,MAiB1B;kBACZ,sBAAsB;;;;;4BAMhC,CAAC,QAAQ,YAAY,CACzB;CAGA,QADa,MAAM,QAAQ,IAAI,IAAI,OAAQ,MAAM,QAAQ,CAAC,EAAA,CAC9C,KAAI,OAAM;EAClB,IAAI,EAAE,cAAc,OAAO,EAAE,GAAG,YAAY,IAAI,OAAO,EAAE,EAAE;EAC3D,OAAO,OAAO,EAAE,KAAK;EACrB,WAAW,OAAO,EAAE,aAAa,CAAC;CACtC,EAAE;AACN"}
package/dist/index.es.js CHANGED
@@ -2,16 +2,16 @@ 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 { $ as isFieldOperation, A as createDataSourceRegistry, B as resolveCollectionRelations, D as restrictedFieldNames, E as effectiveAccess, F as securityRuleToConditions, G as suggestNearMiss, H as buildCompositeId, I as fieldKeyForColumn, K as toSnakeCase, L as findRelation, M as resolveDataSource, N as getEffectiveSecurityRules, O as defaultUsersCollection, Q as hasFieldOperation, R as getTableName, S as cursorToStartAfter, T as canWriteField, U as resolvePrimaryKeys, V as enumToObjectEntries, W as hydrateRegExp, X as BATCH_REF_KEY, Z as FIELD_OPERATORS, at as Vector, c as collectAllPages, ct as isUnsupported, g as topLevelIncludeNames, h as serializeInclude, it as GeoPoint, j as isRelationalCollection, k as CollectionRegistry, l as paginateFind, lt as unsupportedMethod, n as buildSdkData, nt as EntityReference, o as serializeFilter, ot as RebaseApiError, p as mergeIncludeSpecs, rt as EntityRelation, s as serializeLogicalCondition, st as RebaseClientError, t as buildRoutedRebaseData, u as resolveFindWindow, v as normalizeOrderBy, y as serializeOrderBy } from "./src-Dgk200Dh.js";
5
+ import { $ as isFieldOperation, A as createDataSourceRegistry, B as resolveCollectionRelations, D as restrictedFieldNames, E as effectiveAccess, F as securityRuleToConditions, G as suggestNearMiss, H as buildCompositeId, I as fieldKeyForColumn, K as toSnakeCase, L as findRelation, M as resolveDataSource, N as getEffectiveSecurityRules, O as defaultUsersCollection, Q as hasFieldOperation, R as getTableName, S as cursorToStartAfter, T as canWriteField, U as resolvePrimaryKeys, V as enumToObjectEntries, W as hydrateRegExp, X as BATCH_REF_KEY, Z as FIELD_OPERATORS, at as Vector, c as collectAllPages, ct as isUnsupported, g as topLevelIncludeNames, h as serializeInclude, it as GeoPoint, j as isRelationalCollection, k as CollectionRegistry, l as paginateFind, lt as unsupportedMethod, n as buildSdkData, nt as EntityReference, o as serializeFilter, ot as RebaseApiError, p as mergeIncludeSpecs, rt as EntityRelation, s as serializeLogicalCondition, st as RebaseClientError, t as buildRoutedRebaseData, u as resolveFindWindow, v as normalizeOrderBy, y as serializeOrderBy } from "./src-DqZ9YiGA.js";
6
6
  import { E as DEFAULT_DATA_SOURCE_KEY, F as sortKeyToString, I as toCanonicalOp, P as parseRelationAggregateSort, S as getCollectionDataPath, _ as resourceKinds, a as resourceToStorageSource, b as RLS_UID_SQL, c as DEFAULT_STORAGE_SOURCE_KEY, d as DEFAULT_RESOURCE_KEY, f as buildResourceGraph, g as resourceKind, h as resourceKeyOf, i as resourceToDataSource, l as findStorageSuffixCollision, m as resourceEnvSuffix, n as declaredQueueConsumers, o as setQueueRuntime, p as resolveResourceRefs, r as declaredSubscriptions, s as setTopicRuntime, u as storageEnvSuffix, v as RLS_JWT_SQL, w as isPostgresCollectionConfig, y as RLS_ROLES_SQL } from "./src-Br6ARbs6.js";
7
7
  import { n as ADMIN_PROPERTY_KEYS, t as ADMIN_COLLECTION_KEYS } from "./admin_block-0Xu0r6eZ.js";
8
8
  import { a as isDuplicateObjectRace, i as isConcurrentDdlRace, n as createDdlBootstrapper, o as isSQLAdmin, s as isSchemaEditingAdmin, t as CONCURRENT_DDL_SQLSTATES } from "./ddl-bootstrap-CfNvxMuK.js";
9
9
  import { i as SCHEMA_VERSION_HEADER, n as createContractRoutes, r as computeSchemaVersion } from "./contract-routes-eLxV0le1.js";
10
- import { $ as escapeHtml, A as MemoryRateLimitStore, B as resolveAuthHooks, C as providerVerifiedEmail, Ct as PUBLIC_STORAGE_PREFIX, D as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, E as isBootstrapWindowOpen, F as registerDevEmailSink, G as getEmailOtpTemplate, H as validatePasswordStrength, I as SMTPEmailService, J as getPasswordResetTemplate, K as getEmailVerificationTemplate, L as createEmailService, M as clearActiveDevEmailSink, N as createDevEmailSink, O as createDataRateLimiter, P as extractLinks, Q as RawHtml, R as assertEmailLinkBases, S as pkceTokenParams, St as isOperationAllowed, T as createBuiltinAuthAdapter, U as verifyPassword, V as hashPassword, W as generateSecurePassword, X as getWelcomeEmailTemplate, Y as getUserInvitationTemplate, Z as resolveEmailBranding, _ as verifyOidcIdToken, _t as extractBearerToken, a as resolveRateLimitStoreKind, at as extractUserFromToken, b as createGoogleProvider, bt as scopeDataDriver, c as createSlackProvider, ct as publicObjectAuth, d as createDiscordProvider, dt as requireAuth, et as html, f as createTwitterProvider, ft as createApiKeyPreAuth, g as tryVerifyOidcIdToken, gt as validateApiKey, h as createMicrosoftProvider, ht as isApiKeyToken, i as createApiKeyStore, it as createRequireAuth, j as activeDevEmailSink, k as defaultAuthLimiter, l as createBitbucketProvider, lt as queryTokenAuth, m as createAppleProvider, mt as createStorageApiKeyGuard, n as createCustomAuthAdapter, nt as createAdapterAuthMiddleware, o as createSqlRateLimitStore, ot as fileTokenAuth, p as createFacebookProvider, pt as createFunctionApiKeyGuard, q as getMagicLinkTemplate, r as createApiKeyRoutes, rt as createAuthMiddleware, s as createSpotifyProvider, st as optionalAuth, tt as raw, u as createGitLabProvider, ut as requireAdmin, v as createGitHubProvider, vt as safeCompare, w as createJwksRoutes, wt as isPublicStoragePath, x as oauthCodeFlowSchema, xt as httpMethodToOperation, y as createLinkedinProvider, yt as SERVICE_IDENTITY, z as resolveEmailLinkBase } from "./auth-BLD80igz.js";
10
+ import { $ as escapeHtml, A as MemoryRateLimitStore, B as resolveAuthHooks, C as providerVerifiedEmail, Ct as PUBLIC_STORAGE_PREFIX, D as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, E as isBootstrapWindowOpen, F as registerDevEmailSink, G as getEmailOtpTemplate, H as validatePasswordStrength, I as SMTPEmailService, J as getPasswordResetTemplate, K as getEmailVerificationTemplate, L as createEmailService, M as clearActiveDevEmailSink, N as createDevEmailSink, O as createDataRateLimiter, P as extractLinks, Q as RawHtml, R as assertEmailLinkBases, S as pkceTokenParams, St as isOperationAllowed, T as createBuiltinAuthAdapter, U as verifyPassword, V as hashPassword, W as generateSecurePassword, X as getWelcomeEmailTemplate, Y as getUserInvitationTemplate, Z as resolveEmailBranding, _ as verifyOidcIdToken, _t as extractBearerToken, a as resolveRateLimitStoreKind, at as extractUserFromToken, b as createGoogleProvider, bt as scopeDataDriver, c as createSlackProvider, ct as publicObjectAuth, d as createDiscordProvider, dt as requireAuth, et as html, f as createTwitterProvider, ft as createApiKeyPreAuth, g as tryVerifyOidcIdToken, gt as validateApiKey, h as createMicrosoftProvider, ht as isApiKeyToken, i as createApiKeyStore, it as createRequireAuth, j as activeDevEmailSink, k as defaultAuthLimiter, l as createBitbucketProvider, lt as queryTokenAuth, m as createAppleProvider, mt as createStorageApiKeyGuard, n as createCustomAuthAdapter, nt as createAdapterAuthMiddleware, o as createSqlRateLimitStore, ot as fileTokenAuth, p as createFacebookProvider, pt as createFunctionApiKeyGuard, q as getMagicLinkTemplate, r as createApiKeyRoutes, rt as createAuthMiddleware, s as createSpotifyProvider, st as optionalAuth, tt as raw, u as createGitLabProvider, ut as requireAdmin, v as createGitHubProvider, vt as safeCompare, w as createJwksRoutes, wt as isPublicStoragePath, x as oauthCodeFlowSchema, xt as httpMethodToOperation, y as createLinkedinProvider, yt as SERVICE_IDENTITY, z as resolveEmailLinkBase } from "./auth-DJsLXsCR.js";
11
11
  import { t as revokeInternalTableSql } from "./internal-tables-DYVcFFSv.js";
12
12
  import { i as rawQueryLoggingEnabled, n as describeCauseChain, o as setLogLevel, r as logger, s as hostEnv } from "./logger-DO2PZc4i.js";
13
13
  import { n as errorHandler, r as schemaDriftRemedy, t as ApiError } from "./errors-DMImyqyR.js";
14
- import { a as resolveListLimitParam, c as HARD_DELETE_QUERY_PARAM, i as parseQueryOptions, l as parseHardDelete, n as parseAggregateSelect, o as assertReadableFields, r as parseGroupBy, s as requestViewer, t as orderByEntriesToTuples } from "./query-parser-0EB_LGgY.js";
14
+ import { a as resolveListLimitParam, c as HARD_DELETE_QUERY_PARAM, i as parseQueryOptions, l as parseHardDelete, n as parseAggregateSelect, o as assertReadableFields, r as parseGroupBy, s as requestViewer, t as orderByEntriesToTuples } from "./query-parser-BQiPZrM-.js";
15
15
  import { S as sha256Hex, c as getJwks, d as hasAsymmetricSigningKey, i as generateDownloadToken, n as configureJwt, p as isJwtConfigured, v as normalizePemFromEnv } from "./jwt-DATvkKB_.js";
16
16
  import { a as canonicalStorageKey, i as canonicalStorageId, n as InvalidStorageKeyError, r as canonicalStorageBucket, t as InvalidStorageBucketError } from "./keys-Qfc4XieN.js";
17
17
  import { t as logMiddleware } from "./logs-routes-DnJINsMu.js";
@@ -25,11 +25,11 @@ import "./request-timeout-BR-OBwES.js";
25
25
  import { t as FunctionSelectionError } from "./selection-CRpqKUbt.js";
26
26
  import { n as loadCronJobsFromDirectory, r as loadCronJobsWithDiagnostics } from "./cron-loader-CQjvjpEw.js";
27
27
  import { r as validateCronExpression, t as CronScheduler } from "./cron-scheduler-D47tdB9T.js";
28
- import { t as createCronRoutes } from "./cron-routes-B0hgbL0a.js";
29
- import { t as createCronStore } from "./cron-store-DuZMJvSh.js";
28
+ import { t as createCronRoutes } from "./cron-routes-Bfwni8Zg.js";
29
+ import { t as createCronStore } from "./cron-store-Bsiw4Q6u.js";
30
30
  import { a as parseBackupTimestamp, i as parseBackupDestination, n as createBackupRoutes, o as readBackupBytes, r as listBackupObjects } from "./backup-DGu0v9Ku.js";
31
- import { i as createJobStore, n as createJobQueue, r as defaultBackoff } from "./jobs-2oLrObSd.js";
32
- import { t as METRIC_SERIES } from "./history-store-BPErMNQq.js";
31
+ import { i as createJobStore, n as createJobQueue, r as defaultBackoff } from "./jobs-CW5lm_Ix.js";
32
+ import { t as METRIC_SERIES } from "./history-store-D4RVK-uZ.js";
33
33
  import { createHash, createSign, randomBytes } from "node:crypto";
34
34
  import * as fs$3 from "fs";
35
35
  import fs, { existsSync } from "fs";
@@ -3949,10 +3949,12 @@ var RestApiGenerator = class {
3949
3949
  const id = c.req.param("id");
3950
3950
  const driver = this.getScopedDriver(c);
3951
3951
  return this.runIdempotent(c, { id: String(id) }, async () => {
3952
+ const hardDelete = parseHardDelete(c.req.query(HARD_DELETE_QUERY_PARAM));
3952
3953
  const existingEntity = await driver.fetchOne({
3953
3954
  path: getCollectionDataPath(collection),
3954
3955
  id: String(id),
3955
- collection: resolvedCollection
3956
+ collection: resolvedCollection,
3957
+ withDeleted: hardDelete ? true : void 0
3956
3958
  });
3957
3959
  if (!existingEntity) throw this.entityNotFound(collection.slug, String(id));
3958
3960
  const ifMatch = c.req.header(IF_MATCH_HEADER);
@@ -4115,13 +4117,15 @@ var RestApiGenerator = class {
4115
4117
  if (!parsed || !parsed.id) return next();
4116
4118
  const driver = this.getScopedDriver(c);
4117
4119
  this.enforceSubcollectionApiKeyPermission(c, parsed.collectionPath);
4120
+ const hardDelete = parseHardDelete(c.req.query(HARD_DELETE_QUERY_PARAM));
4118
4121
  const existingEntity = await driver.fetchOne({
4119
4122
  path: parsed.collectionPath,
4120
- id: parsed.id
4123
+ id: parsed.id,
4124
+ withDeleted: hardDelete ? true : void 0
4121
4125
  });
4122
4126
  if (!existingEntity) throw this.entityNotFound(parsed.collectionPath, parsed.id);
4123
4127
  await driver.delete({
4124
- hard: parseHardDelete(c.req.query(HARD_DELETE_QUERY_PARAM)),
4128
+ hard: hardDelete,
4125
4129
  row: {
4126
4130
  id: parsed.id,
4127
4131
  path: parsed.collectionPath,
@@ -7038,7 +7042,7 @@ async function mountOpenApiDocs(app, basePath, enableSwagger, serverCollections,
7038
7042
  basePath,
7039
7043
  requireAuth
7040
7044
  }));
7041
- const { generateOpenApiSpec } = await import("./openapi-generator-CaA6xKaL.js");
7045
+ const { generateOpenApiSpec } = await import("./openapi-generator-DGyLbISS.js");
7042
7046
  generateOpenApiSpecFn = generateOpenApiSpec;
7043
7047
  if (isPublic) app.get(`${basePath}/docs`, (c) => spec(c));
7044
7048
  else app.get(`${basePath}/docs`, createRequireAuth({}), requireAdmin, (c) => spec(c));
@@ -16627,6 +16631,7 @@ async function _initializeRebaseBackend(config) {
16627
16631
  dir: config.collectionsDir
16628
16632
  });
16629
16633
  }
16634
+ enforceAuthSecretExclusion(activeCollections);
16630
16635
  const introspectCollections = activeCollections.length === 0;
16631
16636
  if (introspectCollections) logger.info("No collections declared — deriving them from the database schema");
16632
16637
  else logger.debug("Serving declared collections");
@@ -16942,7 +16947,7 @@ async function _initializeRebaseBackend(config) {
16942
16947
  ]) {
16943
16948
  const providerConfig = safeAuthConfig[key];
16944
16949
  if (providerConfig && requiredFields.every((f) => Boolean(providerConfig[f]))) {
16945
- const createFn = (await import("./auth-BLD80igz.js").then((n) => n.t))[factory];
16950
+ const createFn = (await import("./auth-DJsLXsCR.js").then((n) => n.t))[factory];
16946
16951
  oauthProviders.push(createFn(providerConfig));
16947
16952
  }
16948
16953
  }
@@ -17401,8 +17406,8 @@ async function _initializeRebaseBackend(config) {
17401
17406
  if (surfaces.cron || config.cronsDir && ownership.cronScheduler) {
17402
17407
  const { loadCronJobsWithDiagnostics } = await import("./cron-loader-CQjvjpEw.js").then((n) => n.t);
17403
17408
  const { CronScheduler } = await import("./cron-scheduler-D47tdB9T.js").then((n) => n.n);
17404
- const { createCronRoutes } = await import("./cron-routes-B0hgbL0a.js").then((n) => n.n);
17405
- const { createCronStore } = await import("./cron-store-DuZMJvSh.js").then((n) => n.n);
17409
+ const { createCronRoutes } = await import("./cron-routes-Bfwni8Zg.js").then((n) => n.n);
17410
+ const { createCronStore } = await import("./cron-store-Bsiw4Q6u.js").then((n) => n.n);
17406
17411
  const { jobs: loadedCronJobs, problems: cronProblems } = config.cronsDir ? await loadCronJobsWithDiagnostics(config.cronsDir) : {
17407
17412
  jobs: [],
17408
17413
  problems: []
@@ -17459,7 +17464,7 @@ async function _initializeRebaseBackend(config) {
17459
17464
  }
17460
17465
  let metricsHistory;
17461
17466
  try {
17462
- const { createMetricsHistory } = await import("./history-recorder-oJZctx5W.js");
17467
+ const { createMetricsHistory } = await import("./history-recorder-r5_IzSHK.js");
17463
17468
  metricsHistory = createMetricsHistory(defaultDriver);
17464
17469
  if (metricsHistory) {
17465
17470
  await metricsHistory.ensure();
@@ -17471,7 +17476,7 @@ async function _initializeRebaseBackend(config) {
17471
17476
  }
17472
17477
  let jobQueue;
17473
17478
  if (config.jobs?.enabled) {
17474
- const { createJobStore, createJobQueue } = await import("./jobs-2oLrObSd.js").then((n) => n.t);
17479
+ const { createJobStore, createJobQueue } = await import("./jobs-CW5lm_Ix.js").then((n) => n.t);
17475
17480
  const store = createJobStore(defaultDriver);
17476
17481
  if (store) {
17477
17482
  await store.ensureTable();