@rebasepro/server 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
- package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
- package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
- package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
- package/dist/{access-Dtu87BMj.js → access-BxkEYQh1.js} +5 -5
- package/dist/{access-Dtu87BMj.js.map → access-BxkEYQh1.js.map} +1 -1
- package/dist/api/errors.d.ts +4 -0
- package/dist/api/rest/api-generator.d.ts +8 -0
- package/dist/{auth-BOz84vIr.js → auth-Bfwjg4Bg.js} +37 -13
- package/dist/auth-Bfwjg4Bg.js.map +1 -0
- package/dist/backend/create-backend.d.ts +6 -0
- package/dist/backend/options.d.ts +10 -0
- package/dist/backend/services.d.ts +9 -0
- package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
- package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
- package/dist/boot/bundle.d.ts +11 -1
- package/dist/boot/env.d.ts +5 -0
- package/dist/boot/security-headers.d.ts +15 -5
- package/dist/boot/static-routing.d.ts +58 -0
- package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
- package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
- package/dist/{contract-routes-o5oqNhfc.js → contract-routes-CZTlAP7p.js} +3 -3
- package/dist/{contract-routes-o5oqNhfc.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
- package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
- package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
- package/dist/{cron-routes-BOu-bY7I.js → cron-routes-Du03uJ7K.js} +5 -5
- package/dist/{cron-routes-BOu-bY7I.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
- package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
- package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
- package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
- package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
- package/dist/dist-C1vNURUy.js +19354 -0
- package/dist/dist-C1vNURUy.js.map +1 -0
- package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
- package/dist/errors-NVbAQU25.js.map +1 -0
- package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
- package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
- package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
- package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
- package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
- package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
- package/dist/functions/index.d.ts +2 -0
- package/dist/functions/index.js +162 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/rate-limit.d.ts +71 -0
- package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
- package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
- package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
- package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.es.js +1241 -213
- package/dist/index.es.js.map +1 -1
- package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
- package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
- package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
- package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
- package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
- package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
- package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
- package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
- package/dist/{load-schema-Cv5XLVjW.js → load-schema-CSEXeduP.js} +36 -5
- package/dist/{load-schema-Cv5XLVjW.js.map → load-schema-CSEXeduP.js.map} +1 -1
- package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
- package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
- package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
- package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
- package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
- package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
- package/dist/{openapi-generator-CoAFACMx.js → openapi-generator-CAhJiwBm.js} +3 -3
- package/dist/{openapi-generator-CoAFACMx.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
- package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
- package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
- package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
- package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
- package/dist/push/push-options.d.ts +26 -0
- package/dist/push/push-routes.d.ts +30 -0
- package/dist/push/push-service.d.ts +13 -0
- package/dist/push/push-store.d.ts +45 -0
- package/dist/push/set-up.d.ts +25 -0
- package/dist/push/subscription-input.d.ts +26 -0
- package/dist/push/vapid-config.d.ts +35 -0
- package/dist/push/web-push-crypto.d.ts +44 -0
- package/dist/push/web-push-sender.d.ts +10 -0
- package/dist/{query-parser-D9Uf8aha.js → query-parser-Cd70kZO8.js} +5 -5
- package/dist/{query-parser-D9Uf8aha.js.map → query-parser-Cd70kZO8.js.map} +1 -1
- package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
- package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
- package/dist/{rls-simulator-routes-BvH6wI64.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
- package/dist/{rls-simulator-routes-BvH6wI64.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
- package/dist/{schema-editor-routes-CzITcAgt.js → schema-editor-routes-BxN0Q85n.js} +5 -5
- package/dist/{schema-editor-routes-CzITcAgt.js.map → schema-editor-routes-BxN0Q85n.js.map} +1 -1
- package/dist/{schema-tables-lJHnyqj4.js → schema-tables-DKFg6vMV.js} +3 -3
- package/dist/{schema-tables-lJHnyqj4.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
- package/dist/{schema-tables-routes-Uss-ljon.js → schema-tables-routes-BfsNG4c4.js} +5 -5
- package/dist/{schema-tables-routes-Uss-ljon.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
- package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
- package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
- package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
- package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
- package/dist/serve-spa.d.ts +12 -0
- package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
- package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
- package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
- package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
- package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
- package/dist/src-CNZB3fuE.js.map +1 -0
- package/dist/{table-source-editor-qmyi5vxX.js → table-source-editor-DCJgZEz9.js} +3 -3
- package/dist/{table-source-editor-qmyi5vxX.js.map → table-source-editor-DCJgZEz9.js.map} +1 -1
- package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
- package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-BOz84vIr.js.map +0 -1
- package/dist/dist-fBcYxf4h.js +0 -19354
- package/dist/dist-fBcYxf4h.js.map +0 -1
- package/dist/errors-DpTMfX77.js.map +0 -1
- package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
- package/dist/src-DLIb1O9l.js.map +0 -1
|
@@ -249,6 +249,6 @@ function grantExecuteToRequestRolesSql(signature) {
|
|
|
249
249
|
`.trim();
|
|
250
250
|
}
|
|
251
251
|
//#endregion
|
|
252
|
-
export { revokeInternalTableSql as i,
|
|
252
|
+
export { revokeInternalTableSql as a, grantExecuteToRequestRolesSql as i, REBASE_INTERNAL_TABLES as n, REQUEST_ROLE_CANDIDATES_SQL as r, LOAD_REQUEST_ROLES_PLPGSQL as t };
|
|
253
253
|
|
|
254
|
-
//# sourceMappingURL=internal-tables-
|
|
254
|
+
//# sourceMappingURL=internal-tables-XxM_NdR_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-tables-CHFJHH7N.js","names":[],"sources":["../../common/src/util/internal-tables.ts"],"sourcesContent":["/**\n * The tables Rebase creates for its own bookkeeping, and the SQL that keeps the\n * end-user role away from them.\n *\n * ## Why this exists\n *\n * Authenticated requests run as {@link REBASE_USER_ROLE}, and the boot-time role\n * provisioning grants that role `SELECT, INSERT, UPDATE, DELETE` on every table\n * in the schemas a project uses — including `rebase`, because a project's own\n * collections are allowed to live there (the scaffold puts `users` there). It\n * also sets `ALTER DEFAULT PRIVILEGES`, so a table created *later* by the\n * migrating role inherits the same grant.\n *\n * Every framework-internal table is created later: auth's tables come up during\n * `initializeAuth`, `api_keys` during route mounting, `cron_logs` when the first\n * job registers, `idempotency_keys` on the first request that carries a key. So\n * they all inherited full DML for the end-user role — and none of them enables\n * row-level security, because none of them is a collection with\n * `securityRules`. Measured on a freshly provisioned database, `SET ROLE\n * rebase_user` could read `rebase.refresh_tokens` (session token hashes),\n * `rebase.mfa_factors` (`secret_encrypted`), `rebase.recovery_codes`, and\n * `rebase.api_keys` (including its `admin` flag), and insert into\n * `rebase.app_config`.\n *\n * Nothing routes a user-context query at those tables today, so this was not\n * reachable over the API. That is the wrong thing to depend on: the documented\n * model is that RLS is the authorization boundary, and these tables sat outside\n * it. The boundary is now a privilege boundary instead — the role simply cannot\n * address them.\n *\n * ## Why REVOKE rather than ENABLE ROW LEVEL SECURITY\n *\n * RLS with no policy denies every row, which is the same outcome, but it is the\n * *weaker* statement: it leaves the grant in place, so a later policy — or a\n * `FORCE` flag cleared by some future migration — reopens the table. There is no\n * row of `refresh_tokens` any end user should ever reach, so the honest encoding\n * is \"this role has no privilege here at all\". It also keeps the owner\n * connection (which auth actually runs on) completely unaffected.\n *\n * ## Keeping it true\n *\n * `packages/rls-check` scans the `rebase` schema — it used to skip it as a\n * \"platform\" schema — and its `rls-disabled` check fires on exactly the\n * condition this module removes: RLS off *and* a DML grant to a reachable role.\n * So a table added here without a revoke is caught by `pnpm rls:check`, not by\n * someone re-reading this file.\n */\n\n/**\n * The Postgres role authenticated requests run as.\n *\n * Defined here rather than in the Postgres driver because both the driver (which\n * provisions the role) and this module (which revokes on its behalf) need it,\n * and a second spelling of a role name is a silent no-op waiting to happen.\n */\nexport const REBASE_USER_ROLE = \"rebase_user\";\n\n/**\n * Framework-internal table names, unqualified.\n *\n * Deliberately NOT including `users`: the auth user table is also a collection,\n * with `securityRules`, RLS enabled and policies applied. Users read their own\n * row through it — revoking there would break sign-in. `revokeInternalTableSql`\n * now skips any table with RLS enabled, so that exception is enforced rather\n * than merely remembered — and so is the same hazard for every other name here,\n * any of which a project may legitimately use for a collection of its own.\n * Without that collection it is not guarded at all, so the request roles are\n * kept off it by {@link withheldTablesIn} instead.\n *\n * `atlas_schema_revisions` is Atlas's migration ledger, which lands in `rebase`\n * because `db migrate apply` passes `--revisions-schema rebase`.\n *\n * Every entry here must also be revoked by whatever creates it, and vice versa:\n * the creation-time revoke fires once, on the boot that first makes the table,\n * so it cannot help a database provisioned before that revoke existed. This\n * list is what the boot-time sweep in `ensureAppRole` iterates, and the sweep\n * is the only thing that can repair an already-granted table. A table revoked\n * at creation but missing here is therefore permanently stranded on any\n * database that predates its revoke.\n *\n * These names are unqualified, and the boot-time sweep applies them to every\n * schema a project uses — so an entry here is a claim on that name in `public`\n * as much as in `rebase`. `jobs` is Rebase's queue at `rebase.jobs` AND a\n * perfectly ordinary collection name, and revoking `public.jobs` from a project\n * that owns it leaves every read failing 42501 with correct policies applied\n * and nothing in the RLS logs to explain it. The `relrowsecurity` guard in\n * `revokeInternalTableSql` is what makes a common noun safe here — it is not a\n * licence to claim more of them.\n */\nexport const REBASE_INTERNAL_TABLES: readonly string[] = [\n // auth\n \"user_identities\",\n \"refresh_tokens\",\n \"password_reset_tokens\",\n \"magic_link_tokens\",\n \"mfa_factors\",\n \"mfa_challenges\",\n \"recovery_codes\",\n \"app_config\",\n \"schema_meta\",\n // platform services\n \"api_keys\",\n \"cron_logs\",\n \"cron_claims\",\n \"cron_job_state\",\n \"jobs\",\n \"rate_limit_hits\",\n \"idempotency_keys\",\n \"entity_history\",\n \"branches\",\n \"metric_samples\",\n // how the panel presents each table, per workspace and per user — read and\n // written by the server on the caller's behalf\n \"ui_preferences\",\n // realtime channels — authorization for these lives in the channel rules the\n // server evaluates before it reads or writes, never in a row policy\n \"channel_messages\",\n \"channel_cursors\",\n \"channel_presence\",\n // migration bookkeeping\n \"atlas_schema_revisions\"\n];\n\n/**\n * The auth user table, by schema and name: `rebase.users`.\n *\n * Kept off {@link REBASE_INTERNAL_TABLES}, which also says what Studio and a\n * branch diff treat as Rebase's plumbing, and the users are the project's\n * data. But its privileges follow the same rule. With the users collection\n * registered it has RLS and admin-only policies, and the revoke skips it.\n * Without it, it had RLS off, the schema-wide grant gave the request role\n * every row, and SQL run as a caller (`getSql`) read every account's address\n * and password hash, an anonymous caller's included.\n */\nexport const AUTH_USERS_TABLE = { schema: \"rebase\", table: \"users\" } as const;\n\n/**\n * The tables in `schema` the request roles are kept off whenever RLS is off on\n * them: {@link REBASE_INTERNAL_TABLES}, and in `rebase` the auth user table.\n */\nexport function withheldTablesIn(schema: string): readonly string[] {\n return schema === AUTH_USERS_TABLE.schema ? [...REBASE_INTERNAL_TABLES, AUTH_USERS_TABLE.table] : REBASE_INTERNAL_TABLES;\n}\n\n/**\n * PL/pgSQL that fills a `request_roles text[]` variable with the roles this\n * database's requests run as: what a provisioning boot recorded in\n * `rebase.schema_meta` (`request_roles`), or `rebase_user` where nothing was\n * recorded — every database from before the role became a setting.\n *\n * Read from the database, not passed in, so every store that revokes or grants\n * on its own objects agrees with the server about the role without being handed\n * it, whatever order the boot runs them in. Dynamic, because the table may not\n * exist yet and a static reference to it would fail the whole block.\n */\nexport const LOAD_REQUEST_ROLES_PLPGSQL = `\n IF to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE $request_roles$SELECT string_to_array(value, ',') FROM \"rebase\".\"schema_meta\" WHERE key = 'request_roles'$request_roles$\n INTO request_roles;\n END IF;\n request_roles := COALESCE(request_roles, ARRAY['${REBASE_USER_ROLE}']);`.trim();\n\n/**\n * SQL: the oids of every role that could be a request role from this\n * connection — roles it may become that cannot log in, Postgres's own `pg_*`\n * roles aside. For a plain catalogue read that decides whether a store has a\n * revoke to run, where the recorded list in `rebase.schema_meta` may not exist\n * yet and so cannot be named.\n *\n * Always a superset of the real request roles, since the connection must be\n * able to switch to them. A role in it that is not one only makes the store run\n * {@link revokeInternalTableSql}, whose own test is exact and finds nothing to do.\n */\nexport const REQUEST_ROLE_CANDIDATES_SQL =\n \"ARRAY(SELECT r.oid FROM pg_roles r WHERE NOT r.rolcanlogin AND r.rolname NOT LIKE 'pg\\\\_%' \" +\n \"AND r.rolname <> current_user AND pg_has_role(current_user, r.oid, 'MEMBER'))\";\n\n/** Postgres identifiers this module is willing to interpolate. */\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * A single statement that takes every privilege on `schema.table` away from the\n * end-user role.\n *\n * Wrapped in a `DO` block guarded on `pg_roles` for two reasons, both of which\n * happen in practice:\n *\n * - the role does not exist when the connection is unprivileged (Rebase then\n * relies on native RLS rather than a role switch), and a bare `REVOKE` on a\n * missing role is an error, not a no-op;\n * - the table may not exist yet — `cron_logs` never appears in a project with\n * no cron jobs — and `to_regclass` returning NULL has to be tolerated too.\n *\n * The third guard is the one that decides whether the *right* table is being\n * revoked. The names in {@link REBASE_INTERNAL_TABLES} are unqualified, and the\n * boot-time sweep in `ensureAppRole` applies all of them to every schema a\n * project uses — including the schema its own collections live in. A project is\n * free to call a collection `jobs`, `branches` or `api_keys`, and when it does,\n * the sweep was revoking `rebase_user`'s DML on the project's table on every\n * single boot. That is not a subtle degradation: the collection's whole API\n * answers 500 `permission denied for table …` from then on, which is what\n * happened to a public job board whose vacancies live in `public.jobs`.\n *\n * `relrowsecurity` separates the two cleanly, and it is the same fact this\n * module already relies on. Framework-internal tables carry no RLS — that is the\n * premise stated at the top of this file, and the reason a revoke is needed at\n * all. Every collection table has it enabled, because that is how Rebase\n * enforces `securityRules`. So \"RLS is off\" is exactly \"this is not somebody's\n * collection\", and the guard also subsumes the hand-carved `users` exception:\n * the auth user table is a collection, has RLS, and would now be skipped on its\n * own merits rather than by being kept off a list.\n *\n * The fourth guard is about cost, and leaves the end state exactly as it was:\n * the `REVOKE` runs only when it would change something. A `REVOKE` rewrites the\n * table's `pg_class` row whether or not anything was granted, which invalidates\n * every cached plan that touches the table on every connection. Every store\n * that owns an internal table runs this on every boot. So it is skipped when the\n * end-user role holds nothing on the table — no entry in its ACL or in any\n * column's ACL — and the ACL has been written. A table whose ACL has never been\n * written (`relacl` NULL) is still revoked once: the `REVOKE` writes the owner's\n * default ACL out, exactly as before, and from then on it is skipped.\n *\n * One command, so it is safe on handles that speak the extended query protocol\n * and reject multi-statement strings.\n */\nexport function revokeInternalTableSql(schema: string, table: string): string {\n if (!SAFE_IDENTIFIER.test(schema)) {\n throw new Error(`Refusing to build SQL with an unsafe schema name: ${JSON.stringify(schema)}`);\n }\n if (!SAFE_IDENTIFIER.test(table)) {\n throw new Error(`Refusing to build SQL with an unsafe table name: ${JSON.stringify(table)}`);\n }\n const qualified = `\"${schema}\".\"${table}\"`;\n const role = \"(SELECT oid FROM pg_roles WHERE rolname = request_role)\";\n return `\n DO $rebase_revoke$\n DECLARE\n request_roles text[];\n request_role text;\n BEGIN\n ${LOAD_REQUEST_ROLES_PLPGSQL}\n IF to_regclass('${qualified}') IS NULL\n OR (SELECT relrowsecurity FROM pg_class WHERE oid = to_regclass('${qualified}')) THEN\n RETURN;\n END IF;\n FOREACH request_role IN ARRAY request_roles LOOP\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role)\n AND (\n (SELECT relacl IS NULL FROM pg_class WHERE oid = to_regclass('${qualified}'))\n OR EXISTS (SELECT 1 FROM pg_class c, aclexplode(c.relacl) a\n WHERE c.oid = to_regclass('${qualified}') AND a.grantee = ${role})\n OR EXISTS (SELECT 1 FROM pg_attribute att, aclexplode(att.attacl) a\n WHERE att.attrelid = to_regclass('${qualified}') AND att.attacl IS NOT NULL\n AND a.grantee = ${role})\n ) THEN\n EXECUTE format('REVOKE ALL ON ${qualified} FROM %I', request_role);\n END IF;\n END LOOP;\n END\n $rebase_revoke$;\n `.trim();\n}\n\n/**\n * One statement granting `EXECUTE` on a function to every request role, for\n * the `SECURITY DEFINER` functions a request calls (the job queue's enqueue,\n * the history writer). Guarded per role, so a database whose request role does\n * not exist (an unprivileged connection) finds it a no-op.\n */\nexport function grantExecuteToRequestRolesSql(signature: string): string {\n return `\n DO $rebase_grant_execute$\n DECLARE\n request_roles text[];\n request_role text;\n BEGIN\n ${LOAD_REQUEST_ROLES_PLPGSQL}\n FOREACH request_role IN ARRAY request_roles LOOP\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role) THEN\n EXECUTE format('GRANT EXECUTE ON FUNCTION ${signature.replace(/'/g, \"''\")} TO %I', request_role);\n END IF;\n END LOOP;\n END\n $rebase_grant_execute$\n `.trim();\n}\n\n/**\n * Revoke on every internal table in `schema`, one statement at a time.\n *\n * Best-effort per table: a connection that does not own one of them (a\n * pre-provisioned database, a platform-managed ledger) cannot revoke on it, and\n * that must not take down a boot. The caller decides how loud to be — `onError`\n * exists so the driver can warn without this module importing a logger.\n */\nexport async function revokeInternalTableAccess(\n execute: (sql: string) => Promise<unknown>,\n schema: string,\n options?: { tables?: readonly string[]; onError?: (table: string, error: unknown) => void }\n): Promise<void> {\n for (const table of options?.tables ?? withheldTablesIn(schema)) {\n try {\n await execute(revokeInternalTableSql(schema, table));\n } catch (error) {\n options?.onError?.(table, error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkChC,IAAa,yBAA4C;CAErD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CAGA;CACA;CACA;CAEA;AACJ;;;;;;;;;;;;AAkCA,IAAa,6BAA6B;;;;;8DAKoB,iBAAiB,MAAM,KAAK;;;;;;;;;;;;AAa1F,IAAa,8BACT;;AAIJ,IAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CxB,SAAgB,uBAAuB,QAAgB,OAAuB;CAC1E,IAAI,CAAC,gBAAgB,KAAK,MAAM,GAC5B,MAAM,IAAI,MAAM,qDAAqD,KAAK,UAAU,MAAM,GAAG;CAEjG,IAAI,CAAC,gBAAgB,KAAK,KAAK,GAC3B,MAAM,IAAI,MAAM,oDAAoD,KAAK,UAAU,KAAK,GAAG;CAE/F,MAAM,YAAY,IAAI,OAAO,KAAK,MAAM;CACxC,MAAM,OAAO;CACb,OAAO;;;;;;cAMG,2BAA2B;8BACX,UAAU;kFAC0C,UAAU;;;;;;uFAML,UAAU;;+DAElC,UAAU,qBAAqB,KAAK;;sEAE7B,UAAU;sDAC1B,KAAK;;oDAEP,UAAU;;;;;MAKxD,KAAK;AACX;;;;;;;AAQA,SAAgB,8BAA8B,WAA2B;CACrE,OAAO;;;;;;cAMG,2BAA2B;;;gEAGuB,UAAU,QAAQ,MAAM,IAAI,EAAE;;;;;MAKxF,KAAK;AACX"}
|
|
1
|
+
{"version":3,"file":"internal-tables-XxM_NdR_.js","names":[],"sources":["../../common/src/util/internal-tables.ts"],"sourcesContent":["/**\n * The tables Rebase creates for its own bookkeeping, and the SQL that keeps the\n * end-user role away from them.\n *\n * ## Why this exists\n *\n * Authenticated requests run as {@link REBASE_USER_ROLE}, and the boot-time role\n * provisioning grants that role `SELECT, INSERT, UPDATE, DELETE` on every table\n * in the schemas a project uses — including `rebase`, because a project's own\n * collections are allowed to live there (the scaffold puts `users` there). It\n * also sets `ALTER DEFAULT PRIVILEGES`, so a table created *later* by the\n * migrating role inherits the same grant.\n *\n * Every framework-internal table is created later: auth's tables come up during\n * `initializeAuth`, `api_keys` during route mounting, `cron_logs` when the first\n * job registers, `idempotency_keys` on the first request that carries a key. So\n * they all inherited full DML for the end-user role — and none of them enables\n * row-level security, because none of them is a collection with\n * `securityRules`. Measured on a freshly provisioned database, `SET ROLE\n * rebase_user` could read `rebase.refresh_tokens` (session token hashes),\n * `rebase.mfa_factors` (`secret_encrypted`), `rebase.recovery_codes`, and\n * `rebase.api_keys` (including its `admin` flag), and insert into\n * `rebase.app_config`.\n *\n * Nothing routes a user-context query at those tables today, so this was not\n * reachable over the API. That is the wrong thing to depend on: the documented\n * model is that RLS is the authorization boundary, and these tables sat outside\n * it. The boundary is now a privilege boundary instead — the role simply cannot\n * address them.\n *\n * ## Why REVOKE rather than ENABLE ROW LEVEL SECURITY\n *\n * RLS with no policy denies every row, which is the same outcome, but it is the\n * *weaker* statement: it leaves the grant in place, so a later policy — or a\n * `FORCE` flag cleared by some future migration — reopens the table. There is no\n * row of `refresh_tokens` any end user should ever reach, so the honest encoding\n * is \"this role has no privilege here at all\". It also keeps the owner\n * connection (which auth actually runs on) completely unaffected.\n *\n * ## Keeping it true\n *\n * `packages/rls-check` scans the `rebase` schema — it used to skip it as a\n * \"platform\" schema — and its `rls-disabled` check fires on exactly the\n * condition this module removes: RLS off *and* a DML grant to a reachable role.\n * So a table added here without a revoke is caught by `pnpm rls:check`, not by\n * someone re-reading this file.\n */\n\n/**\n * The Postgres role authenticated requests run as.\n *\n * Defined here rather than in the Postgres driver because both the driver (which\n * provisions the role) and this module (which revokes on its behalf) need it,\n * and a second spelling of a role name is a silent no-op waiting to happen.\n */\nexport const REBASE_USER_ROLE = \"rebase_user\";\n\n/**\n * Framework-internal table names, unqualified.\n *\n * Deliberately NOT including `users`: the auth user table is also a collection,\n * with `securityRules`, RLS enabled and policies applied. Users read their own\n * row through it — revoking there would break sign-in. `revokeInternalTableSql`\n * now skips any table with RLS enabled, so that exception is enforced rather\n * than merely remembered — and so is the same hazard for every other name here,\n * any of which a project may legitimately use for a collection of its own.\n * Without that collection it is not guarded at all, so the request roles are\n * kept off it by {@link withheldTablesIn} instead.\n *\n * `atlas_schema_revisions` is Atlas's migration ledger, which lands in `rebase`\n * because `db migrate apply` passes `--revisions-schema rebase`.\n *\n * Every entry here must also be revoked by whatever creates it, and vice versa:\n * the creation-time revoke fires once, on the boot that first makes the table,\n * so it cannot help a database provisioned before that revoke existed. This\n * list is what the boot-time sweep in `ensureAppRole` iterates, and the sweep\n * is the only thing that can repair an already-granted table. A table revoked\n * at creation but missing here is therefore permanently stranded on any\n * database that predates its revoke.\n *\n * These names are unqualified, and the boot-time sweep applies them to every\n * schema a project uses — so an entry here is a claim on that name in `public`\n * as much as in `rebase`. `jobs` is Rebase's queue at `rebase.jobs` AND a\n * perfectly ordinary collection name, and revoking `public.jobs` from a project\n * that owns it leaves every read failing 42501 with correct policies applied\n * and nothing in the RLS logs to explain it. The `relrowsecurity` guard in\n * `revokeInternalTableSql` is what makes a common noun safe here — it is not a\n * licence to claim more of them.\n */\nexport const REBASE_INTERNAL_TABLES: readonly string[] = [\n // auth\n \"user_identities\",\n \"refresh_tokens\",\n \"password_reset_tokens\",\n \"magic_link_tokens\",\n \"mfa_factors\",\n \"mfa_challenges\",\n \"recovery_codes\",\n \"app_config\",\n \"schema_meta\",\n // platform services\n \"api_keys\",\n \"cron_logs\",\n \"cron_claims\",\n \"cron_job_state\",\n \"jobs\",\n \"rate_limit_hits\",\n \"idempotency_keys\",\n \"entity_history\",\n \"branches\",\n \"metric_samples\",\n // how the panel presents each table, per workspace and per user — read and\n // written by the server on the caller's behalf\n \"ui_preferences\",\n // realtime channels — authorization for these lives in the channel rules the\n // server evaluates before it reads or writes, never in a row policy\n \"channel_messages\",\n \"channel_cursors\",\n \"channel_presence\",\n // migration bookkeeping\n \"atlas_schema_revisions\"\n];\n\n/**\n * The auth user table, by schema and name: `rebase.users`.\n *\n * Kept off {@link REBASE_INTERNAL_TABLES}, which also says what Studio and a\n * branch diff treat as Rebase's plumbing, and the users are the project's\n * data. But its privileges follow the same rule. With the users collection\n * registered it has RLS and admin-only policies, and the revoke skips it.\n * Without it, it had RLS off, the schema-wide grant gave the request role\n * every row, and SQL run as a caller (`getSql`) read every account's address\n * and password hash, an anonymous caller's included.\n */\nexport const AUTH_USERS_TABLE = { schema: \"rebase\", table: \"users\" } as const;\n\n/**\n * The tables in `schema` the request roles are kept off whenever RLS is off on\n * them: {@link REBASE_INTERNAL_TABLES}, and in `rebase` the auth user table.\n */\nexport function withheldTablesIn(schema: string): readonly string[] {\n return schema === AUTH_USERS_TABLE.schema ? [...REBASE_INTERNAL_TABLES, AUTH_USERS_TABLE.table] : REBASE_INTERNAL_TABLES;\n}\n\n/**\n * PL/pgSQL that fills a `request_roles text[]` variable with the roles this\n * database's requests run as: what a provisioning boot recorded in\n * `rebase.schema_meta` (`request_roles`), or `rebase_user` where nothing was\n * recorded — every database from before the role became a setting.\n *\n * Read from the database, not passed in, so every store that revokes or grants\n * on its own objects agrees with the server about the role without being handed\n * it, whatever order the boot runs them in. Dynamic, because the table may not\n * exist yet and a static reference to it would fail the whole block.\n */\nexport const LOAD_REQUEST_ROLES_PLPGSQL = `\n IF to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE $request_roles$SELECT string_to_array(value, ',') FROM \"rebase\".\"schema_meta\" WHERE key = 'request_roles'$request_roles$\n INTO request_roles;\n END IF;\n request_roles := COALESCE(request_roles, ARRAY['${REBASE_USER_ROLE}']);`.trim();\n\n/**\n * SQL: the oids of every role that could be a request role from this\n * connection — roles it may become that cannot log in, Postgres's own `pg_*`\n * roles aside. For a plain catalogue read that decides whether a store has a\n * revoke to run, where the recorded list in `rebase.schema_meta` may not exist\n * yet and so cannot be named.\n *\n * Always a superset of the real request roles, since the connection must be\n * able to switch to them. A role in it that is not one only makes the store run\n * {@link revokeInternalTableSql}, whose own test is exact and finds nothing to do.\n */\nexport const REQUEST_ROLE_CANDIDATES_SQL =\n \"ARRAY(SELECT r.oid FROM pg_roles r WHERE NOT r.rolcanlogin AND r.rolname NOT LIKE 'pg\\\\_%' \" +\n \"AND r.rolname <> current_user AND pg_has_role(current_user, r.oid, 'MEMBER'))\";\n\n/** Postgres identifiers this module is willing to interpolate. */\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * A single statement that takes every privilege on `schema.table` away from the\n * end-user role.\n *\n * Wrapped in a `DO` block guarded on `pg_roles` for two reasons, both of which\n * happen in practice:\n *\n * - the role does not exist when the connection is unprivileged (Rebase then\n * relies on native RLS rather than a role switch), and a bare `REVOKE` on a\n * missing role is an error, not a no-op;\n * - the table may not exist yet — `cron_logs` never appears in a project with\n * no cron jobs — and `to_regclass` returning NULL has to be tolerated too.\n *\n * The third guard is the one that decides whether the *right* table is being\n * revoked. The names in {@link REBASE_INTERNAL_TABLES} are unqualified, and the\n * boot-time sweep in `ensureAppRole` applies all of them to every schema a\n * project uses — including the schema its own collections live in. A project is\n * free to call a collection `jobs`, `branches` or `api_keys`, and when it does,\n * the sweep was revoking `rebase_user`'s DML on the project's table on every\n * single boot. That is not a subtle degradation: the collection's whole API\n * answers 500 `permission denied for table …` from then on, which is what\n * happened to a public job board whose vacancies live in `public.jobs`.\n *\n * `relrowsecurity` separates the two cleanly, and it is the same fact this\n * module already relies on. Framework-internal tables carry no RLS — that is the\n * premise stated at the top of this file, and the reason a revoke is needed at\n * all. Every collection table has it enabled, because that is how Rebase\n * enforces `securityRules`. So \"RLS is off\" is exactly \"this is not somebody's\n * collection\", and the guard also subsumes the hand-carved `users` exception:\n * the auth user table is a collection, has RLS, and would now be skipped on its\n * own merits rather than by being kept off a list.\n *\n * The fourth guard is about cost, and leaves the end state exactly as it was:\n * the `REVOKE` runs only when it would change something. A `REVOKE` rewrites the\n * table's `pg_class` row whether or not anything was granted, which invalidates\n * every cached plan that touches the table on every connection. Every store\n * that owns an internal table runs this on every boot. So it is skipped when the\n * end-user role holds nothing on the table — no entry in its ACL or in any\n * column's ACL — and the ACL has been written. A table whose ACL has never been\n * written (`relacl` NULL) is still revoked once: the `REVOKE` writes the owner's\n * default ACL out, exactly as before, and from then on it is skipped.\n *\n * One command, so it is safe on handles that speak the extended query protocol\n * and reject multi-statement strings.\n */\nexport function revokeInternalTableSql(schema: string, table: string): string {\n if (!SAFE_IDENTIFIER.test(schema)) {\n throw new Error(`Refusing to build SQL with an unsafe schema name: ${JSON.stringify(schema)}`);\n }\n if (!SAFE_IDENTIFIER.test(table)) {\n throw new Error(`Refusing to build SQL with an unsafe table name: ${JSON.stringify(table)}`);\n }\n const qualified = `\"${schema}\".\"${table}\"`;\n const role = \"(SELECT oid FROM pg_roles WHERE rolname = request_role)\";\n return `\n DO $rebase_revoke$\n DECLARE\n request_roles text[];\n request_role text;\n BEGIN\n ${LOAD_REQUEST_ROLES_PLPGSQL}\n IF to_regclass('${qualified}') IS NULL\n OR (SELECT relrowsecurity FROM pg_class WHERE oid = to_regclass('${qualified}')) THEN\n RETURN;\n END IF;\n FOREACH request_role IN ARRAY request_roles LOOP\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role)\n AND (\n (SELECT relacl IS NULL FROM pg_class WHERE oid = to_regclass('${qualified}'))\n OR EXISTS (SELECT 1 FROM pg_class c, aclexplode(c.relacl) a\n WHERE c.oid = to_regclass('${qualified}') AND a.grantee = ${role})\n OR EXISTS (SELECT 1 FROM pg_attribute att, aclexplode(att.attacl) a\n WHERE att.attrelid = to_regclass('${qualified}') AND att.attacl IS NOT NULL\n AND a.grantee = ${role})\n ) THEN\n EXECUTE format('REVOKE ALL ON ${qualified} FROM %I', request_role);\n END IF;\n END LOOP;\n END\n $rebase_revoke$;\n `.trim();\n}\n\n/**\n * One statement granting `EXECUTE` on a function to every request role, for\n * the `SECURITY DEFINER` functions a request calls (the job queue's enqueue,\n * the history writer). Guarded per role, so a database whose request role does\n * not exist (an unprivileged connection) finds it a no-op.\n */\nexport function grantExecuteToRequestRolesSql(signature: string): string {\n return `\n DO $rebase_grant_execute$\n DECLARE\n request_roles text[];\n request_role text;\n BEGIN\n ${LOAD_REQUEST_ROLES_PLPGSQL}\n FOREACH request_role IN ARRAY request_roles LOOP\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role) THEN\n EXECUTE format('GRANT EXECUTE ON FUNCTION ${signature.replace(/'/g, \"''\")} TO %I', request_role);\n END IF;\n END LOOP;\n END\n $rebase_grant_execute$\n `.trim();\n}\n\n/**\n * Revoke on every internal table in `schema`, one statement at a time.\n *\n * Best-effort per table: a connection that does not own one of them (a\n * pre-provisioned database, a platform-managed ledger) cannot revoke on it, and\n * that must not take down a boot. The caller decides how loud to be — `onError`\n * exists so the driver can warn without this module importing a logger.\n */\nexport async function revokeInternalTableAccess(\n execute: (sql: string) => Promise<unknown>,\n schema: string,\n options?: { tables?: readonly string[]; onError?: (table: string, error: unknown) => void }\n): Promise<void> {\n for (const table of options?.tables ?? withheldTablesIn(schema)) {\n try {\n await execute(revokeInternalTableSql(schema, table));\n } catch (error) {\n options?.onError?.(table, error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkChC,IAAa,yBAA4C;CAErD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CAGA;CACA;CACA;CAEA;AACJ;;;;;;;;;;;;AAkCA,IAAa,6BAA6B;;;;;8DAKoB,iBAAiB,MAAM,KAAK;;;;;;;;;;;;AAa1F,IAAa,8BACT;;AAIJ,IAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CxB,SAAgB,uBAAuB,QAAgB,OAAuB;CAC1E,IAAI,CAAC,gBAAgB,KAAK,MAAM,GAC5B,MAAM,IAAI,MAAM,qDAAqD,KAAK,UAAU,MAAM,GAAG;CAEjG,IAAI,CAAC,gBAAgB,KAAK,KAAK,GAC3B,MAAM,IAAI,MAAM,oDAAoD,KAAK,UAAU,KAAK,GAAG;CAE/F,MAAM,YAAY,IAAI,OAAO,KAAK,MAAM;CACxC,MAAM,OAAO;CACb,OAAO;;;;;;cAMG,2BAA2B;8BACX,UAAU;kFAC0C,UAAU;;;;;;uFAML,UAAU;;+DAElC,UAAU,qBAAqB,KAAK;;sEAE7B,UAAU;sDAC1B,KAAK;;oDAEP,UAAU;;;;;MAKxD,KAAK;AACX;;;;;;;AAQA,SAAgB,8BAA8B,WAA2B;CACrE,OAAO;;;;;;cAMG,2BAA2B;;;gEAGuB,UAAU,QAAQ,MAAM,IAAI,EAAE;;;;;MAKxF,KAAK;AACX"}
|
|
@@ -2,9 +2,9 @@ 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 {
|
|
5
|
+
import { Rn as __exportAll, nn as isSQLAdmin } from "./src-CNZB3fuE.js";
|
|
6
6
|
import { a as logger } from "./logger-SigQ2oZJ.js";
|
|
7
|
-
import {
|
|
7
|
+
import { a as revokeInternalTableSql, i as grantExecuteToRequestRolesSql } from "./internal-tables-XxM_NdR_.js";
|
|
8
8
|
import { n as sqlRows, t as firstSqlRow } from "./sql-rows-CIThkmuF.js";
|
|
9
9
|
import { c as provisioningExec, i as hasInCauseChain, r as createDdlBootstrapper } from "./ddl-bootstrap-DhCuwhHM.js";
|
|
10
10
|
import { randomUUID } from "crypto";
|
|
@@ -736,4 +736,4 @@ var jobs_exports = /* @__PURE__ */ __exportAll({
|
|
|
736
736
|
//#endregion
|
|
737
737
|
export { defaultBackoff as a, createJobQueue as i, createJobStore as n, currentAmbientTransaction as o, PermanentJobError as r, jobs_exports as t };
|
|
738
738
|
|
|
739
|
-
//# sourceMappingURL=jobs-
|
|
739
|
+
//# sourceMappingURL=jobs-CFUwQTao.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jobs-WCyKVsUf.js","names":[],"sources":["../src/db/ambient-transaction.ts","../src/jobs/job-queue.ts","../src/jobs/job-store.ts","../src/jobs/index.ts"],"sourcesContent":["/**\n * The write transaction the current code is running inside, when there is one.\n *\n * A collection callback runs inside the transaction that carries its write.\n * Work it hands off — a job, a queue message, a topic event, a webhook\n * delivery — has to share that write's fate: queued when it commits, never\n * queued when it rolls back, and invisible to a worker until the commit. The\n * code that queues it lives in this package and knows no driver; the\n * transaction belongs to the driver. So the driver publishes the transaction it\n * opened for a write, and the queueing code asks for it here.\n *\n * Until this existed the job store wrote through the default driver's own\n * connection, in autocommit, whatever called it. A job enqueued from an\n * `afterSave` that then threw stayed queued for a row that was never written,\n * and a worker could claim it before the row it was about committed.\n *\n * The resolver lives on `globalThis` under a registered symbol, like the\n * `rebase` singleton: a managed runtime can load two copies of this package,\n * and the copy a driver registers with must be the one the job store reads.\n * No Node imports — the store is reachable from code that has to stay portable.\n *\n * **The symbol's key is a contract between packages, and frozen.** The\n * Postgres driver writes the slot itself rather than importing a setter from\n * here: the managed runtime supplies this package from the image while a\n * bundle brings its own driver, and a driver importing a function an older\n * image does not export would fail to link and take the boot down. Written\n * through the slot, any pairing of versions degrades to the old behaviour —\n * jobs committing on their own — instead.\n */\nexport interface AmbientTransaction {\n /**\n * Run one statement on the transaction, `$1…` placeholders as\n * `executeSql` takes them. It runs as the transaction's current role — on\n * Postgres the request's restricted one — so a statement that needs more\n * goes through a function granted to that role.\n */\n exec(sqlText: string, params?: unknown[]): Promise<Record<string, unknown>[]>;\n /** Run `fn` after the transaction commits. Never runs if it rolls back. */\n afterCommit(fn: () => void): void;\n}\n\n/** Frozen — see above. `server-postgres/src/services/write-transaction-scope.ts` writes it. */\nconst RESOLVER_SLOT = Symbol.for(\"rebase.server.ambientTransactionResolver\");\n\ntype ResolverSlot = { [RESOLVER_SLOT]?: () => AmbientTransaction | undefined };\n\n/**\n * Register how to find the write transaction the caller is inside; pass\n * `undefined` to unregister. For tests and for drivers in this repository's\n * lockstep — a driver shipped separately writes the slot, as above.\n */\nexport function setAmbientTransactionResolver(resolve: (() => AmbientTransaction | undefined) | undefined): void {\n (globalThis as ResolverSlot)[RESOLVER_SLOT] = resolve;\n}\n\n/** The write transaction the caller is inside, or `undefined` outside one. */\nexport function currentAmbientTransaction(): AmbientTransaction | undefined {\n return (globalThis as ResolverSlot)[RESOLVER_SLOT]?.();\n}\n","import { randomUUID } from \"crypto\";\nimport { logger } from \"../utils/logger.js\";\nimport { currentAmbientTransaction } from \"../db/ambient-transaction.js\";\nimport type { JobClaim, JobStore } from \"./job-store.js\";\nimport type { EnqueueOptions, JobHandler, JobQueueClient, JobQueueOptions, JobRecord } from \"./types.js\";\n\n/**\n * The worker: claim, run, record, repeat.\n *\n * Everything difficult about running jobs concurrently is in `job-store.ts`,\n * where one `UPDATE … FOR UPDATE SKIP LOCKED` does the arbitration. What is\n * left here is a loop and the decisions around a handler that throws.\n */\n\nconst DEFAULT_CONCURRENCY = 5;\nconst DEFAULT_POLL_INTERVAL_MS = 2_000;\nconst DEFAULT_VISIBILITY_TIMEOUT_MS = 5 * 60_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\n/**\n * How long one attempt may run when `jobs.timeoutMs` is left out. Without a\n * bound, a handler awaiting a socket that never answers held its worker slot\n * and its claim for the life of the process, with `/health` green. Fifteen\n * minutes is far past any job that is merely slow, and a job meant to run\n * longer says so with its own `timeoutMs` — or `0`, for no limit.\n */\nexport const DEFAULT_JOB_TIMEOUT_MS = 15 * 60_000;\n\n/**\n * The longest an idle worker goes without looking for work.\n *\n * An idle worker used to claim every 2 seconds, forever: about 45,000 round\n * trips a day per pod, each with a pool checkout, and a database that could\n * never suspend. Now it is woken instead — by `NOTIFY` when another process\n * enqueues, by its own enqueues, retries and delayed jobs — and this is the\n * safety poll behind that. Where the database cannot notify it, it backs off\n * from `pollIntervalMs` to this, doubling after each look that found nothing.\n */\nconst IDLE_POLL_MAX_MS = 30_000;\n\n/** 1s, 5s, 25s, 125s … capped at an hour. */\nexport function defaultBackoff(attempt: number): number {\n return Math.min(1_000 * Math.pow(5, Math.max(0, attempt - 1)), 60 * 60_000);\n}\n\n/**\n * How often the reaper runs, relative to the visibility timeout.\n *\n * A quarter of it, so a stranded job waits at most 1.25× the timeout rather\n * than 2× — and so the sweep is not itself a per-poll query against a table\n * whose interesting rows are, almost always, none.\n */\nconst REAP_INTERVAL_FACTOR = 0.25;\n\n/**\n * How long after a job's `run_at` a timed wake claims. A timer can fire a few\n * milliseconds early by the wall clock — libuv measures from its cached loop\n * time — and the claim compares `run_at <= now()` in the database. A claim that\n * lands before the row is due finds nothing, and with a `LISTEN` the worker\n * then sleeps until its safety poll: a job delayed by 1.5 s started a minute\n * late. Waking a little after the due time costs that much latency and nothing\n * else.\n */\nexport const DUE_GRACE_MS = 50;\n\n/**\n * How often a worker deletes finished jobs past retention. Hourly keeps the\n * table near its retention size on a pod that is never redeployed; each sweep\n * reads only the finished rows, through `idx_jobs_finished`.\n */\nconst RETENTION_SWEEP_INTERVAL_MS = 60 * 60_000;\n\n/**\n * Thrown by a handler for a failure no retry can change — a destination that\n * is refused, a receiver that redirects. The job is dead-lettered on this\n * attempt, with the message as its `last_error`, instead of spending its\n * remaining attempts proving the same thing. Returning normally is not the\n * alternative: that records the job as succeeded.\n */\nexport class PermanentJobError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"PermanentJobError\";\n }\n}\n\nexport interface JobQueue extends JobQueueClient {\n start(): void;\n /**\n * Stop claiming, and wait for the jobs in flight — for at most `timeoutMs`\n * when given. A job still running when the budget runs out keeps its claim\n * and is recovered by the visibility timeout; waiting on it without a bound\n * would let one handler that never settles hold the whole shutdown.\n */\n stop(timeoutMs?: number): Promise<void>;\n /**\n * Claim what fits in the free slots, run it, and resolve with how many jobs\n * ran. For tests and for `/jobs/drain`; not meant to run beside `start()`.\n */\n runOnce(): Promise<number>;\n /** Registered after construction — how `tasks` from config and internal producers meet. */\n register<P = unknown>(task: string, handler: JobHandler<P>): void;\n isRunning(): boolean;\n}\n\nexport function createJobQueue(store: JobStore, options: JobQueueOptions = {}): JobQueue {\n const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const visibilityTimeoutMs = options.visibilityTimeoutMs ?? DEFAULT_VISIBILITY_TIMEOUT_MS;\n const defaultMaxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const backoff = options.backoff ?? defaultBackoff;\n const configuredTimeoutMs = options.timeoutMs;\n if (configuredTimeoutMs !== undefined && !(Number.isFinite(configuredTimeoutMs) && configuredTimeoutMs >= 0)) {\n // NaN is what a mistyped env var parses to; it would fail every\n // attempt at once.\n throw new Error(`jobs.timeoutMs must be a number of milliseconds, or 0 for no limit (got ${String(configuredTimeoutMs)}).`);\n }\n /** `undefined` means no limit: only an explicit `0` asks for that. */\n const timeoutMs = configuredTimeoutMs === undefined\n ? DEFAULT_JOB_TIMEOUT_MS\n : configuredTimeoutMs === 0 ? undefined : configuredTimeoutMs;\n\n // A task's payload is whatever was enqueued under its name, so the map erases\n // each handler's `P`: the one place a stored handler is widened to `unknown`.\n const handlers = new Map<string, JobHandler<unknown>>();\n for (const [task, handler] of Object.entries(options.tasks ?? {})) {\n handlers.set(task, handler as JobHandler<unknown>);\n }\n\n // Identifies this process in `locked_by`: \"which pod had it when it\n // stopped\" is the first question anyone asks of a stuck job, and with the\n // attempt it is the claim an outcome is written under (see `JobClaim`).\n const workerId = `${process.pid}-${randomUUID().slice(0, 8)}`;\n\n let timer: NodeJS.Timeout | null = null;\n /** When {@link timer} fires (epoch ms), so a later wake never postpones an earlier one. */\n let timerDue = Infinity;\n /**\n * The wait after a look that found nothing. Doubles to {@link idleCeilingMs}\n * while the worker polls on its own; back to `pollIntervalMs` whenever\n * there is work or a wake. Fixed at the ceiling while notifications wake it.\n */\n const idleCeilingMs = Math.max(IDLE_POLL_MAX_MS, pollIntervalMs);\n let idleIntervalMs = pollIntervalMs;\n /** Notifications from the database wake this worker — see `JobStore.subscribe`. */\n let listening = false;\n let unsubscribe: (() => Promise<void>) | null = null;\n /** A wake arrived while a claim was in flight: claim again once it is done. */\n let rerun = false;\n let reapTimer: NodeJS.Timeout | null = null;\n let sweepTimer: NodeJS.Timeout | null = null;\n let sweeping = false;\n let running = false;\n /**\n * Every job this worker is running, tracked one by one rather than per\n * claimed batch: a batch would let its slowest job decide when the next\n * claim happens, so one handler that never settled would idle every other\n * slot — and hold `stop()` with it.\n */\n const active = new Set<Promise<void>>();\n /** The claim in progress, so `stop()` also waits for jobs it is about to hand out. */\n let claiming: Promise<unknown> | null = null;\n /** The last claim filled every free slot, so more work is probably waiting. */\n let backlog = false;\n let reaping = false;\n let draining: Promise<void> | null = null;\n\n /**\n * Renew `claim` while its handler runs, at a third of the visibility\n * timeout, so the reaper only ever takes a job from a worker that stopped\n * renewing — a dead one — and never from one that is merely slow. Returns\n * the stop.\n */\n function keepClaim(job: JobRecord, claim: JobClaim): () => void {\n if (!store.heartbeat) return () => undefined;\n const renew = store.heartbeat.bind(store);\n const interval = setInterval(() => {\n renew(job.id, claim).then((held) => {\n if (held) return;\n clearInterval(interval);\n logger.warn(\n `[jobs] \"${job.task}\" lost its claim on attempt ${claim.attempt} while running; ` +\n \"its outcome will not be recorded\", { jobId: job.id }\n );\n }).catch((error: unknown) => {\n logger.warn(`[jobs] Could not renew the claim on \"${job.task}\"`, { jobId: job.id, error });\n });\n }, Math.max(1, Math.floor(visibilityTimeoutMs / 3)));\n interval.unref?.();\n return () => clearInterval(interval);\n }\n\n async function runJob(job: JobRecord): Promise<void> {\n const handler = handlers.get(job.task);\n const claim: JobClaim = { workerId, attempt: job.attempts };\n\n if (!handler) {\n // Only reachable through a store that ignores the `tasks` filter on\n // `claim` — the one that ships never hands this worker a task it\n // has no handler for. Give the row back for a peer that has one.\n // The attempt the claim spent is not undone, so a task nobody in\n // the fleet implements dead-letters with an error naming it rather\n // than cycling through such a store forever.\n logger.warn(`[jobs] No handler registered for task \"${job.task}\" — returning the job to the queue`);\n const retryAt = job.attempts < job.maxAttempts ? new Date(Date.now() + backoff(job.attempts)) : null;\n await store.fail(job.id, `No handler registered for task \"${job.task}\"`, retryAt, claim);\n if (retryAt) wake(retryAt.getTime());\n return;\n }\n\n const releaseClaim = keepClaim(job, claim);\n const controller = new AbortController();\n let deadline: NodeJS.Timeout | undefined;\n try {\n try {\n const run = Promise.resolve().then(() => handler({\n id: job.id,\n task: job.task,\n payload: job.payload,\n attempt: job.attempts,\n maxAttempts: job.maxAttempts,\n signal: controller.signal\n }));\n if (timeoutMs === undefined) {\n await run;\n } else {\n // A handler that ignores the signal outlives its attempt;\n // what it does after is not this attempt's outcome.\n run.catch(() => undefined);\n await Promise.race([run, new Promise<never>((_, reject) => {\n deadline = setTimeout(() => {\n const error = new Error(`\"${job.task}\" timed out after ${timeoutMs}ms (jobs.timeoutMs)`);\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n // A deadline is not work: it must not hold a process\n // open that is otherwise done.\n deadline.unref?.();\n })]);\n }\n } finally {\n clearTimeout(deadline);\n releaseClaim();\n }\n await store.complete(job.id, claim);\n } catch (error) {\n const message = error instanceof Error ? (error.stack ?? error.message) : String(error);\n const permanent = error instanceof PermanentJobError;\n const willRetry = !permanent && job.attempts < job.maxAttempts;\n\n // Truncated, because `last_error` holds a stack and a queue that\n // accumulates megabytes of them is its own outage.\n const retryAt = willRetry ? new Date(Date.now() + backoff(job.attempts)) : null;\n await store.fail(job.id, message.slice(0, 4_000), retryAt, claim);\n // This worker knows when the retry is due; nobody will notify it.\n if (retryAt) wake(retryAt.getTime());\n\n if (willRetry) {\n logger.warn(`[jobs] \"${job.task}\" failed on attempt ${job.attempts}/${job.maxAttempts}; retrying`, { jobId: job.id });\n } else if (permanent) {\n logger.error(`[jobs] \"${job.task}\" failed permanently on attempt ${job.attempts}; not retrying`, { jobId: job.id, error: message });\n } else {\n // The last attempt is an error, not a warning: nothing else will\n // touch this job, and if nobody looks at the table it is simply\n // lost work.\n logger.error(`[jobs] \"${job.task}\" failed permanently after ${job.attempts} attempts`, { jobId: job.id, error: message });\n }\n }\n }\n\n /**\n * Return jobs stranded by a dead worker. On its own timer, not inside the\n * poll: a poll can be skipped for as long as every slot is busy, and that\n * is exactly when a stranded job most needs a peer to take it back.\n */\n async function reap(): Promise<void> {\n if (reaping) return;\n reaping = true;\n try {\n // Revived jobs are runnable now, and nothing notified anyone.\n if (await store.reapExpired(visibilityTimeoutMs) > 0) wake();\n } catch (error) {\n logger.error(\"[jobs] Failed to reclaim expired jobs\", { error });\n } finally {\n reaping = false;\n }\n }\n\n /**\n * Delete finished jobs past retention. On the worker, on its own timer:\n * the sweep used to run only in the boot path, awaited before the server\n * served, so a pod that lived for weeks never pruned and the next boot\n * paid for all of it at once.\n */\n async function sweep(): Promise<void> {\n if (sweeping || !store.sweepExpired) return;\n sweeping = true;\n try {\n const deleted = await store.sweepExpired();\n if (deleted > 0) logger.info(`[jobs] Removed ${deleted} finished job(s) past retention`);\n } catch (error) {\n logger.warn(\"[jobs] The retention sweep failed; it runs again within the hour\", { error });\n } finally {\n sweeping = false;\n }\n }\n\n /** Claim as many jobs as there are free slots and start each one on its own. */\n async function claimAndStart(): Promise<Promise<void>[]> {\n const free = concurrency - active.size;\n if (free <= 0) return [];\n\n // Only the tasks this worker can run. During a rolling deploy an\n // instance on older code shares the table with jobs whose task only\n // the newer code implements, and a claim spends an attempt: claiming\n // them here would dead-letter them before an updated peer got to them.\n // A handler registered after `start()` joins the next claim.\n if (handlers.size === 0) return [];\n const jobs = await store.claim(free, workerId, [...handlers.keys()]);\n backlog = jobs.length >= free;\n // Found work: look again soon if it runs out. Found none: wait longer.\n if (jobs.length > 0) idleIntervalMs = pollIntervalMs;\n\n return jobs.map((job) => {\n const run: Promise<void> = runJob(job)\n .catch((error) => {\n // `runJob` handles a throwing handler; this is a store\n // write failing after it. The job keeps its claim, so the\n // visibility timeout recovers it.\n logger.error(`[jobs] Could not record the outcome of \"${job.task}\"`, { jobId: job.id, error });\n })\n .finally(() => {\n active.delete(run);\n // A slot just came free and there is work waiting: take the\n // next job now, not a poll interval from now.\n if (backlog) schedule(0);\n });\n active.add(run);\n return run;\n });\n }\n\n /** Look for work in `delayMs` — unless a look is already due sooner. */\n function schedule(delayMs: number): void {\n if (!running) return;\n const due = Date.now() + delayMs;\n if (timer && timerDue <= due) return;\n if (timer) clearTimeout(timer);\n timerDue = due;\n timer = setTimeout(() => {\n timer = null;\n timerDue = Infinity;\n void tick();\n }, delayMs);\n // Never hold the process open. A queue with nothing to do should not be\n // the reason `rebase dev` will not exit.\n timer.unref?.();\n }\n\n /**\n * Work may be runnable at `runAtMs` (now, when absent): a job was enqueued\n * — here, or in another process that notified — or a retry or a reclaimed\n * job came due. Resets the back-off.\n */\n function wake(runAtMs?: number): void {\n if (!running) return;\n idleIntervalMs = pollIntervalMs;\n const now = Date.now();\n const delay = runAtMs === undefined || runAtMs <= now ? 0 : runAtMs + DUE_GRACE_MS - now;\n if (delay === 0 && active.size >= concurrency) {\n // Every slot is busy: the next one to free claims at once.\n backlog = true;\n return;\n }\n schedule(delay);\n }\n\n async function tick(): Promise<void> {\n if (!running) return;\n // A claim already in progress looks again when it finishes — the wake\n // may be for a row its snapshot did not see.\n if (claiming) {\n rerun = true;\n return;\n }\n const work = claimAndStart().catch((error) => {\n logger.error(\"[jobs] Poll failed\", { error });\n backlog = false;\n });\n claiming = work;\n await work;\n claiming = null;\n\n // A full claim with a slot still free — a job already finished — means\n // go straight back, and so does a wake that came in mid-claim.\n // Otherwise sleep; a job finishing during a backlog wakes the loop\n // early, and so does anything that calls `wake`.\n if ((backlog && active.size < concurrency) || rerun) {\n rerun = false;\n schedule(0);\n return;\n }\n if (listening) {\n schedule(idleCeilingMs);\n return;\n }\n schedule(idleIntervalMs);\n idleIntervalMs = Math.min(idleIntervalMs * 2, idleCeilingMs);\n }\n\n /** Be woken by the database when another process enqueues — where it can. */\n function listen(): void {\n if (!store.subscribe) return;\n store.subscribe(\n (runAtMs) => wake(runAtMs),\n // Notifications sent while the connection was down are gone.\n () => wake()\n ).then((stop) => {\n if (!running) {\n void stop().catch(() => undefined);\n return;\n }\n unsubscribe = stop;\n listening = true;\n logger.info(`[jobs] Woken by the database on enqueue; looking every ${idleCeilingMs / 1000}s besides`);\n }).catch((error: unknown) => {\n logger.info(\n `[jobs] Not woken by the database (${error instanceof Error ? error.message : String(error)}); ` +\n `polling instead, from every ${pollIntervalMs}ms up to every ${idleCeilingMs / 1000}s while idle`\n );\n });\n }\n\n async function drain(): Promise<void> {\n await claiming;\n await Promise.allSettled([...active]);\n }\n\n return {\n start(): void {\n if (running) return;\n running = true;\n idleIntervalMs = pollIntervalMs;\n logger.info(`[jobs] Worker started (concurrency ${concurrency}, poll ${pollIntervalMs}ms, up to ${idleCeilingMs}ms while idle)`);\n if (configuredTimeoutMs === undefined) {\n logger.info(\n `[jobs] Each attempt is limited to ${DEFAULT_JOB_TIMEOUT_MS / 60_000} minutes, the default jobs.timeoutMs. ` +\n \"Set jobs.timeoutMs to change it, or 0 for no limit.\"\n );\n }\n void reap();\n reapTimer = setInterval(() => { void reap(); }, visibilityTimeoutMs * REAP_INTERVAL_FACTOR);\n reapTimer.unref?.();\n void sweep();\n sweepTimer = setInterval(() => { void sweep(); }, RETENTION_SWEEP_INTERVAL_MS);\n sweepTimer.unref?.();\n listen();\n schedule(0);\n },\n\n async stop(timeoutMs?: number): Promise<void> {\n running = false;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n timerDue = Infinity;\n }\n listening = false;\n const stopListening = unsubscribe;\n unsubscribe = null;\n if (stopListening) {\n await stopListening().catch((error: unknown) => {\n logger.warn(\"[jobs] Could not close the notification connection\", { error });\n });\n }\n if (reapTimer) {\n clearInterval(reapTimer);\n reapTimer = null;\n }\n if (sweepTimer) {\n clearInterval(sweepTimer);\n sweepTimer = null;\n }\n // Jobs in flight keep their claim until they finish or the\n // visibility timeout expires, so waiting here is what turns a\n // graceful shutdown into \"no job runs twice\".\n draining ??= drain().finally(() => { draining = null; });\n if (timeoutMs === undefined) {\n await draining;\n return;\n }\n let budget: NodeJS.Timeout | undefined;\n const finished = await Promise.race([\n draining.then(() => true),\n new Promise<false>((resolve) => {\n budget = setTimeout(() => resolve(false), timeoutMs);\n budget.unref?.();\n })\n ]);\n clearTimeout(budget);\n if (!finished) {\n logger.warn(\n `[jobs] ${active.size} job(s) still running after ${timeoutMs}ms; stopping without them. ` +\n \"They keep their claim and are retried once the visibility timeout reclaims it.\"\n );\n }\n },\n\n async runOnce(): Promise<number> {\n const started = await claimAndStart();\n await Promise.allSettled(started);\n return started.length;\n },\n\n register<P = unknown>(task: string, handler: JobHandler<P>): void {\n if (handlers.has(task)) {\n logger.warn(`[jobs] Task \"${task}\" was already registered; the later handler wins`);\n }\n handlers.set(task, handler as JobHandler<unknown>);\n },\n\n isRunning(): boolean {\n return running;\n },\n\n async enqueue<P = unknown>(task: string, payload?: P, enqueueOptions: EnqueueOptions = {}): Promise<string | null> {\n const runAt = new Date(Date.now() + (enqueueOptions.delayMs ?? 0));\n // Read before the insert, which may await: inside a write the row\n // is invisible until that write commits, so that is when to look.\n const ambient = currentAmbientTransaction();\n const id = await store.insert({\n task,\n payload: payload ?? null,\n runAt,\n maxAttempts: enqueueOptions.maxAttempts ?? defaultMaxAttempts,\n idempotencyKey: enqueueOptions.idempotencyKey\n });\n // This process's own worker needs no notification to hear about it.\n if (id !== null && running) {\n if (ambient) ambient.afterCommit(() => wake(runAt.getTime()));\n else wake(runAt.getTime());\n }\n return id;\n }\n };\n}\n","import type { DataDriver } from \"@rebasepro/types\";\nimport { isSQLAdmin } from \"@rebasepro/types\";\nimport { grantExecuteToRequestRolesSql, revokeInternalTableSql, sqlRows, firstSqlRow } from \"@rebasepro/common\";\nimport { logger } from \"../utils/logger.js\";\nimport { createDdlBootstrapper, hasInCauseChain, provisioningExec, type SqlExec } from \"../boot/ddl-bootstrap.js\";\nimport { currentAmbientTransaction } from \"../db/ambient-transaction.js\";\nimport type { JobRecord } from \"./types.js\";\n\n/**\n * The queue's storage, as SQL against `rebase.jobs`.\n *\n * Split from the worker for the same reason `cron-store` is split from\n * `cron-scheduler`: the interesting parts here are three statements that have\n * to be exactly right under concurrency, and they are much easier to reason\n * about — and to test — away from a polling loop.\n */\n\nconst TABLE = \"rebase.jobs\";\n\n/** How long finished jobs are kept before the retention sweep removes them. */\nconst SUCCEEDED_RETENTION_DAYS = 3;\n/**\n * Failures outlive successes by a lot. A dead-lettered job is evidence, and the\n * person who needs it is usually looking on Monday for something that happened\n * on Friday night.\n */\nconst FAILED_RETENTION_DAYS = 30;\n\n/**\n * Rows one retention statement deletes. A sweep repeats it until a batch\n * comes back short, so a backlog — the first sweep on a table a long-lived\n * pod let grow to millions of rows — is many short transactions rather than\n * one that holds locks and writes a burst of WAL for seconds.\n */\nconst RETENTION_BATCH = 5_000;\n\n/** A row as Postgres returns it. */\ninterface JobRow {\n id: string;\n task: string;\n payload: unknown;\n status: string;\n run_at: string;\n attempts: number;\n max_attempts: number;\n last_error: string | null;\n created_at: string;\n updated_at: string;\n}\n\nfunction toRecord(row: JobRow): JobRecord {\n return {\n id: row.id,\n task: row.task,\n payload: row.payload,\n status: row.status as JobRecord[\"status\"],\n runAt: new Date(row.run_at).toISOString(),\n attempts: Number(row.attempts),\n maxAttempts: Number(row.max_attempts),\n lastError: row.last_error,\n createdAt: new Date(row.created_at).toISOString(),\n updatedAt: new Date(row.updated_at).toISOString()\n };\n}\n\n/** Same rule as `cron-store`: match the SQLSTATE, never the message. */\nfunction isUniqueViolation(err: unknown): boolean {\n return hasInCauseChain(err, (e) => e.code === \"23505\");\n}\n\n/**\n * How a job gets into `rebase.jobs` from inside somebody else's transaction.\n *\n * An enqueue from a collection callback has to ride the write's transaction —\n * committed with it, discarded with it, invisible to workers until then — and\n * that transaction runs as the request's restricted role, which has no access\n * to `rebase.jobs` at all (see the revoke in `ensureTable`). This function is\n * the one door: `SECURITY DEFINER`, so the insert runs with the owner's rights\n * for that one statement and the transaction's role never changes. Switching\n * the role for the insert instead would elevate the whole connection for as\n * long as the insert took, and a callback's un-awaited statement would run\n * in that window as the owner.\n *\n * The door is narrow on purpose. It takes the five columns an enqueue sets and\n * nothing else, so it cannot claim, complete or rewrite a job — and only the\n * request role is granted it, not PUBLIC. That role runs statements the server\n * writes; nobody outside gets SQL as it.\n *\n * `ON CONFLICT DO NOTHING` rather than a caught unique violation: an error\n * inside a transaction aborts the whole transaction, so an idempotency clash\n * would have failed the customer's write. A clash returns no row, hence NULL.\n */\nconst ENQUEUE_FUNCTION = \"rebase.enqueue_job\";\nconst ENQUEUE_SIGNATURE = `${ENQUEUE_FUNCTION}(text, jsonb, timestamptz, integer, text)`;\n\n/**\n * The `NOTIFY` channel an insert announces itself on, with the job's `run_at`\n * in epoch milliseconds as the payload. Workers listening on it are woken\n * instead of polling; Postgres delivers it when the insert commits, and not at\n * all if it rolls back. Frozen: workers of the previous release listen on it\n * during a rolling deploy.\n */\nexport const JOBS_NOTIFY_CHANNEL = \"rebase_jobs\";\n\n/** `run_at` as the notification's payload: epoch milliseconds, as text. */\nconst NOTIFY_PAYLOAD = (runAt: string) => `(extract(epoch FROM ${runAt}) * 1000)::bigint::text`;\n\n/**\n * Which claim an outcome belongs to: the worker holding the job, and the\n * attempt that claim spent.\n *\n * The visibility timeout hands a job to a second worker when the first stops\n * renewing its claim, and the first may still be running — slow, not dead. Its\n * outcome is then about an attempt the table has moved past, and writing it\n * would mark a running job `succeeded`, or send a finished one back to\n * `pending` for another run. Both writes therefore apply only while the claim\n * they name still holds the row. The attempt is part of the identity because a\n * worker's own reaper can hand a job back to the same worker in another slot.\n */\nexport interface JobClaim {\n workerId: string;\n attempt: number;\n}\n\nexport interface JobStore {\n ensureTable(): Promise<void>;\n /** Returns the new job's id, or `null` if an idempotency key matched unfinished work. */\n insert(job: {\n task: string;\n payload: unknown;\n runAt: Date;\n maxAttempts: number;\n idempotencyKey?: string;\n }): Promise<string | null>;\n /**\n * Atomically take up to `limit` runnable jobs for this worker — only jobs\n * whose task is in `tasks`, when it is given. A worker never claims work it\n * cannot run: a claim spends an attempt, so an instance running older code\n * during a rollout would otherwise dead-letter the newer code's jobs.\n */\n claim(limit: number, workerId: string, tasks?: readonly string[]): Promise<JobRecord[]>;\n /** Mark the job `succeeded` — a no-op once `claim` no longer holds it. */\n complete(id: string, claim: JobClaim): Promise<void>;\n /**\n * Back to `pending` with a later `runAt`, or `failed` when out of attempts —\n * a no-op once `claim` no longer holds it.\n */\n fail(id: string, error: string, retryAt: Date | null, claim: JobClaim): Promise<void>;\n /**\n * Renew `claim` on a job whose handler is still running, so the visibility\n * timeout only ever reclaims a job from a worker that stopped renewing.\n * Resolves with whether the claim still held. A store without it leaves a\n * handler that outlives the timeout to be run a second time beside itself.\n */\n heartbeat?(id: string, claim: JobClaim): Promise<boolean>;\n /** Return jobs stranded by a worker that died holding them. Resolves with how many. */\n reapExpired(visibilityTimeoutMs: number): Promise<number>;\n /**\n * Call `onWake` whenever any process inserts a job, with the job's `run_at`\n * in epoch milliseconds. Resolves, once listening, with the stop; rejects\n * when this database cannot notify this process — no session connection\n * to hold a `LISTEN` on — and the worker polls instead. `onReconnect` is\n * called after a dropped connection is back: what was sent meanwhile is\n * lost. A store without it leaves the worker polling.\n */\n subscribe?(onWake: (runAtMs?: number) => void, onReconnect: () => void): Promise<() => Promise<void>>;\n /**\n * Delete finished jobs past retention — succeeded ones after\n * {@link SUCCEEDED_RETENTION_DAYS} days, failed ones after\n * {@link FAILED_RETENTION_DAYS} — in batches. Resolves with how many went.\n * The worker runs it on a timer; a store without it keeps every row.\n */\n sweepExpired?(): Promise<number>;\n fetch(id: string): Promise<JobRecord | null>;\n}\n\n/** The rows a claim's writes may touch: `$1` the job, `$2` the worker, `$3` the attempt. */\nconst HELD_BY_CLAIM = \"id = $1 AND status = 'running' AND locked_by = $2 AND attempts = $3\";\n\nfunction warnStaleOutcome(id: string, claim: JobClaim, outcome: \"success\" | \"failure\"): void {\n logger.warn(\n `[jobs] Ignored the ${outcome} of attempt ${claim.attempt} of job ${id}: the job was reclaimed ` +\n \"from this worker while it ran, so that attempt's outcome is no longer the job's.\"\n );\n}\n\nexport function createJobStore(\n /** Only its SQL escape hatch is read. */\n driver: Pick<DataDriver, \"admin\">,\n options: {\n /**\n * Default `true`. `false` is a backend that changes nothing in its\n * database: `ensureTable` uses the queue and its enqueue function if\n * they are there, and creates, grants and revokes nothing.\n */\n provision?: boolean;\n } = {}\n): JobStore | undefined {\n const admin = driver.admin;\n if (!isSQLAdmin(admin)) {\n logger.warn(\n \"⚠️ [jobs] DataDriver does not support SQL admin — the durable job queue is unavailable. \" +\n \"Work that would have been queued runs inline instead.\"\n );\n return undefined;\n }\n\n // Two shapes of the same call: the bootstrapper's `SqlExec` takes an\n // options object, while everything below reads better with a positional\n // parameter array.\n const execRaw: SqlExec = provisioningExec(\n (sqlText, execOptions) =>\n admin.executeSql(sqlText, execOptions?.params ? { params: execOptions.params } : undefined),\n options.provision\n );\n const exec = (sqlText: string, params?: unknown[]) =>\n execRaw(sqlText, params ? { params } : undefined);\n\n const ddl = createDdlBootstrapper(execRaw, \"jobs\");\n\n /**\n * Whether {@link ENQUEUE_FUNCTION} exists, so an enqueue inside a write can\n * ride its transaction. Decided at boot rather than assumed: a database\n * that refused the function would otherwise fail every write whose callback\n * enqueues, where falling back to the old behaviour only loses atomicity.\n */\n let enqueueInTransaction = false;\n\n return {\n async ensureTable(): Promise<void> {\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 task TEXT NOT NULL,\n payload JSONB,\n status TEXT NOT NULL DEFAULT 'pending',\n run_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n attempts INTEGER NOT NULL DEFAULT 0,\n max_attempts INTEGER NOT NULL DEFAULT 3,\n locked_at TIMESTAMPTZ,\n locked_by TEXT,\n idempotency_key TEXT,\n last_error TEXT,\n created_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n updated_at TIMESTAMPTZ NOT NULL DEFAULT now()\n )\n `);\n\n // The claim query's index. Partial, because the rows it has to find\n // fast are a shrinking minority of a table that also holds every\n // success and every dead letter.\n await ddl.ensureObject(\"Creating idx_jobs_runnable\", `\n CREATE INDEX IF NOT EXISTS idx_jobs_runnable\n ON ${TABLE}(run_at, created_at)\n WHERE status = 'pending'\n `);\n\n // Finds jobs stranded by a dead worker.\n await ddl.ensureObject(\"Creating idx_jobs_running\", `\n CREATE INDEX IF NOT EXISTS idx_jobs_running\n ON ${TABLE}(locked_at)\n WHERE status = 'running'\n `);\n\n // What makes `idempotencyKey` a guarantee rather than a\n // check-then-act race: two instances reacting to one event both\n // reach the INSERT, and the index decides. Partial on unfinished\n // work — see `EnqueueOptions.idempotencyKey` for why a key must be\n // reusable once its job is done.\n await ddl.ensureObject(\"Creating idx_jobs_idempotency\", `\n CREATE UNIQUE INDEX IF NOT EXISTS idx_jobs_idempotency\n ON ${TABLE}(idempotency_key)\n WHERE idempotency_key IS NOT NULL AND status IN ('pending', 'running')\n `);\n\n // The retention sweep's index. Partial on the finished rows — the\n // only ones it deletes — so a sweep reads what it removes instead\n // of the whole table; without it every sweep was a sequential scan,\n // six seconds over two million rows.\n await ddl.ensureObject(\"Creating idx_jobs_finished\", `\n CREATE INDEX IF NOT EXISTS idx_jobs_finished\n ON ${TABLE}(status, updated_at)\n WHERE status IN ('succeeded', 'failed')\n `);\n\n const ready = await ddl.isReadable(TABLE);\n\n if (ready) {\n // No retention sweep here. It used to run at boot and only at\n // boot: awaited before the server served, a sequential scan of\n // the whole table, and never again for as long as the pod lived\n // — a worker up for three weeks held seven times the rows\n // retention meant to keep. The worker runs `sweepExpired` on a\n // timer instead.\n\n // Payloads are arbitrary application data — a webhook body, a\n // user id, whatever was passed — and a writable queue lets any\n // signed-in user schedule work of their choosing under the\n // server's own authority. Same reasoning, and the same\n // unconditional re-application, as `cron_claims`.\n await ddl.step(\"Revoking end-user access to jobs\", () =>\n exec(revokeInternalTableSql(\"rebase\", \"jobs\")));\n\n await ddl.ensureObject(`Creating ${ENQUEUE_FUNCTION}`, `\n CREATE OR REPLACE FUNCTION ${ENQUEUE_FUNCTION}(\n p_task text, p_payload jsonb, p_run_at timestamptz,\n p_max_attempts integer, p_idempotency_key text\n ) RETURNS text\n LANGUAGE sql\n SECURITY DEFINER\n SET search_path = pg_catalog, pg_temp\n AS $fn$\n SELECT pg_notify('${JOBS_NOTIFY_CHANNEL}', ${NOTIFY_PAYLOAD(\"p_run_at\")});\n INSERT INTO ${TABLE} (task, payload, run_at, max_attempts, idempotency_key)\n VALUES (p_task, p_payload, p_run_at, p_max_attempts, p_idempotency_key)\n ON CONFLICT DO NOTHING\n RETURNING id\n $fn$\n `);\n // Re-applied every boot: a new function is executable by PUBLIC\n // until told otherwise, and the request role may be provisioned\n // after the function was first made.\n await ddl.step(`Granting ${ENQUEUE_FUNCTION} to the request role`, async () => {\n await exec(`REVOKE ALL ON FUNCTION ${ENQUEUE_SIGNATURE} FROM PUBLIC`);\n await exec(grantExecuteToRequestRolesSql(ENQUEUE_SIGNATURE));\n });\n enqueueInTransaction = firstSqlRow<{ present: boolean }>(await exec(\n `SELECT to_regprocedure('${ENQUEUE_SIGNATURE}') IS NOT NULL AS present`\n ))?.present === true;\n if (!enqueueInTransaction) {\n logger.warn(\n `⚠️ [jobs] ${ENQUEUE_FUNCTION} could not be created, so a job enqueued inside a write ` +\n \"commits on its own: it stays queued if the write rolls back.\"\n );\n }\n\n logger.info(\"✅ Job queue table ready\");\n } else {\n logger.error(\n `❌ [jobs] ${TABLE} is unavailable — nothing can be queued and nothing queued earlier ` +\n \"will run. Callers fall back to running the work inline.\"\n );\n }\n },\n\n async insert(job): Promise<string | null> {\n const params = [\n job.task,\n JSON.stringify(job.payload ?? null),\n job.runAt.toISOString(),\n job.maxAttempts,\n job.idempotencyKey ?? null\n ];\n // Inside a write: on its transaction, through the definer function\n // — see `ENQUEUE_FUNCTION`. Checked and used with no `await`\n // between, so the transaction cannot close in the gap.\n const ambient = enqueueInTransaction ? currentAmbientTransaction() : undefined;\n if (ambient) {\n const rows = await ambient.exec(\n `SELECT ${ENQUEUE_FUNCTION}($1::text, $2::jsonb, $3::timestamptz, $4::integer, $5::text) AS id`,\n params\n );\n return (rows?.[0]?.id as string | null | undefined) ?? null;\n }\n try {\n // The notification rides the insert's own statement, so it\n // is sent exactly when the row commits.\n const rows = await exec(\n `WITH inserted AS (\n INSERT INTO ${TABLE} (task, payload, run_at, max_attempts, idempotency_key)\n VALUES ($1, $2::jsonb, $3, $4, $5)\n RETURNING id, run_at\n )\n SELECT id, pg_notify('${JOBS_NOTIFY_CHANNEL}', ${NOTIFY_PAYLOAD(\"run_at\")}) AS notified\n FROM inserted`,\n params\n );\n return (rows?.[0]?.id as string) ?? null;\n } catch (error) {\n // The losing side of an idempotency race. Not an error: the\n // work the caller wanted is already queued, which is the\n // outcome they asked for.\n if (isUniqueViolation(error)) return null;\n throw error;\n }\n },\n\n async claim(limit: number, workerId: string, tasks?: readonly string[]): Promise<JobRecord[]> {\n if (tasks && tasks.length === 0) return [];\n // One placeholder per task rather than an array parameter: every\n // driver binds a string, and not every driver binds an array.\n const taskFilter = tasks\n ? `AND task IN (${tasks.map((_, i) => `$${i + 3}`).join(\", \")})`\n : \"\";\n // `FOR UPDATE SKIP LOCKED` is the whole design. The inner select\n // takes row locks on the jobs it picks and *skips* any a concurrent\n // worker already holds, so N workers polling the same table divide\n // the work instead of contending for the head of it — and no job is\n // ever handed to two of them.\n //\n // `attempts` is incremented here, on claim, rather than on failure.\n // A worker that is killed mid-job never reports anything, so\n // counting on failure would let a job that crashes the process be\n // retried forever, once per restart, taking the process down each\n // time.\n const rows = await exec(\n `UPDATE ${TABLE} SET\n status = 'running',\n attempts = attempts + 1,\n locked_at = now(),\n locked_by = $2,\n updated_at = now()\n WHERE id IN (\n SELECT id FROM ${TABLE}\n WHERE status = 'pending' AND run_at <= now() ${taskFilter}\n ORDER BY run_at, created_at\n LIMIT $1\n FOR UPDATE SKIP LOCKED\n )\n RETURNING *`,\n [limit, workerId, ...(tasks ?? [])]\n );\n return sqlRows<JobRow>(rows).map(toRecord);\n },\n\n async complete(id: string, claim: JobClaim): Promise<void> {\n const rows = await exec(\n `UPDATE ${TABLE} SET status = 'succeeded', locked_at = NULL, locked_by = NULL,\n last_error = NULL, updated_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt]\n );\n if (sqlRows(rows).length === 0) warnStaleOutcome(id, claim, \"success\");\n },\n\n async fail(id: string, error: string, retryAt: Date | null, claim: JobClaim): Promise<void> {\n const rows = retryAt\n ? await exec(\n `UPDATE ${TABLE} SET status = 'pending', run_at = $4, locked_at = NULL,\n locked_by = NULL, last_error = $5, updated_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt, retryAt.toISOString(), error]\n )\n : await exec(\n `UPDATE ${TABLE} SET status = 'failed', locked_at = NULL, locked_by = NULL,\n last_error = $4, updated_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt, error]\n );\n if (sqlRows(rows).length === 0) warnStaleOutcome(id, claim, \"failure\");\n },\n\n async heartbeat(id: string, claim: JobClaim): Promise<boolean> {\n const rows = await exec(\n `UPDATE ${TABLE} SET locked_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt]\n );\n return sqlRows(rows).length > 0;\n },\n\n async reapExpired(visibilityTimeoutMs: number): Promise<number> {\n // A worker killed while holding a job cannot release it, so nothing\n // but a timeout will ever free the row. Jobs that still have\n // attempts left go back to `pending`; the rest are dead-lettered\n // with an error that says what happened, because \"attempts: 3,\n // lastError: null\" is otherwise a genuinely baffling row to find.\n const seconds = Math.max(1, Math.round(visibilityTimeoutMs / 1000));\n\n const revived = await exec(\n `UPDATE ${TABLE} SET status = 'pending', locked_at = NULL, locked_by = NULL,\n last_error = 'Worker stopped responding; the job was reclaimed', updated_at = now()\n WHERE status = 'running'\n AND locked_at < now() - make_interval(secs => $1)\n AND attempts < max_attempts\n RETURNING id`,\n [seconds]\n );\n\n const buried = await exec(\n `UPDATE ${TABLE} SET status = 'failed', locked_at = NULL, locked_by = NULL,\n last_error = 'Worker stopped responding on the final attempt', updated_at = now()\n WHERE status = 'running'\n AND locked_at < now() - make_interval(secs => $1)\n AND attempts >= max_attempts\n RETURNING id`,\n [seconds]\n );\n\n const count = (revived?.length ?? 0) + (buried?.length ?? 0);\n if (count > 0) {\n logger.warn(\n `[jobs] Reclaimed ${count} job(s) from a worker that stopped responding ` +\n `(${revived?.length ?? 0} retryable, ${buried?.length ?? 0} dead-lettered)`\n );\n }\n return count;\n },\n\n async sweepExpired(): Promise<number> {\n // `SKIP LOCKED`, so replicas sweeping at once divide the rows\n // rather than queue behind each other's batch. The count comes back\n // as one row, not one id per deleted job.\n let total = 0;\n for (;;) {\n const rows = await exec(\n `WITH swept AS (\n DELETE FROM ${TABLE}\n WHERE id IN (\n SELECT id FROM ${TABLE}\n WHERE (status = 'succeeded' AND updated_at < now() - make_interval(days => $1))\n OR (status = 'failed' AND updated_at < now() - make_interval(days => $2))\n LIMIT $3\n FOR UPDATE SKIP LOCKED\n )\n RETURNING 1\n )\n SELECT count(*)::int AS deleted FROM swept`,\n [SUCCEEDED_RETENTION_DAYS, FAILED_RETENTION_DAYS, RETENTION_BATCH]\n );\n const deleted = Number(firstSqlRow<{ deleted: number }>(rows)?.deleted ?? 0);\n total += deleted;\n if (deleted < RETENTION_BATCH) return total;\n }\n },\n\n async subscribe(onWake: (runAtMs?: number) => void, onReconnect: () => void): Promise<() => Promise<void>> {\n if (!admin.listen) {\n throw new Error(\"this database driver has no notifications\");\n }\n return admin.listen(JOBS_NOTIFY_CHANNEL, (payload) => {\n const runAtMs = Number(payload);\n onWake(Number.isFinite(runAtMs) && runAtMs > 0 ? runAtMs : undefined);\n }, { onReconnect });\n },\n\n async fetch(id: string): Promise<JobRecord | null> {\n const rows = await exec(`SELECT * FROM ${TABLE} WHERE id = $1`, [id]);\n const row = firstSqlRow<JobRow>(rows);\n return row ? toRecord(row) : null;\n }\n };\n}\n","export { createJobStore } from \"./job-store\";\nexport type { JobClaim, JobStore } from \"./job-store\";\nexport { createJobQueue, defaultBackoff, PermanentJobError } from \"./job-queue\";\nexport type { JobQueue } from \"./job-queue\";\nexport type {\n EnqueueOptions,\n JobContext,\n JobHandler,\n JobQueueClient,\n JobQueueOptions,\n JobRecord,\n JobStatus\n} from \"./types\";\n"],"mappings":";;;;;;;;;;;;AA0CA,IAAM,gBAAgB,OAAO,IAAI,0CAA0C;;AAc3E,SAAgB,4BAA4D;CACxE,OAAQ,WAA4B,cAAc,GAAG;AACzD;;;;;;;;;;AC5CA,IAAM,sBAAsB;AAC5B,IAAM,2BAA2B;AACjC,IAAM,gCAAgC,IAAI;AAC1C,IAAM,uBAAuB;;;;;;;;AAS7B,IAAa,yBAAyB,KAAK;;;;;;;;;;;AAY3C,IAAM,mBAAmB;;AAGzB,SAAgB,eAAe,SAAyB;CACpD,OAAO,KAAK,IAAI,MAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,UAAU,CAAC,CAAC,GAAG,KAAK,GAAM;AAC9E;;;;;;;;AASA,IAAM,uBAAuB;;;;;;AAkB7B,IAAM,8BAA8B,KAAK;;;;;;;;AASzC,IAAa,oBAAb,cAAuC,MAAM;CACzC,YAAY,SAAiB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AS;IACL,MAAM,OAAO,MAAM,KACf;uCACmB,MAAM;;8CAEC,MAAM;;;;;;;;kEAShC;KAAC;KAA0B;KAAuB;IAAe,CACrE;IACA,MAAM,UAAU,OAAO,YAAiC,IAAI,CAAC,EAAE,WAAW,CAAC;IAC3E,SAAS;IACT,IAAI,UAAU,iBAAiB,OAAO;GAC1C;EACJ;EAEA,MAAM,UAAU,QAAoC,aAAuD;GACvG,IAAI,CAAC,MAAM,QACP,MAAM,IAAI,MAAM,2CAA2C;GAE/D,OAAO,MAAM,OAAO,sBAAsB,YAAY;IAClD,MAAM,UAAU,OAAO,OAAO;IAC9B,OAAO,OAAO,SAAS,OAAO,KAAK,UAAU,IAAI,UAAU,KAAA,CAAS;GACxE,GAAG,EAAE,YAAY,CAAC;EACtB;EAEA,MAAM,MAAM,IAAuC;GAE/C,MAAM,MAAM,YAAoB,MADb,KAAK,iBAAiB,MAAM,iBAAiB,CAAC,EAAE,CAAC,CAChC;GACpC,OAAO,MAAM,SAAS,GAAG,IAAI;EACjC;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"jobs-CFUwQTao.js","names":[],"sources":["../src/db/ambient-transaction.ts","../src/jobs/job-queue.ts","../src/jobs/job-store.ts","../src/jobs/index.ts"],"sourcesContent":["/**\n * The write transaction the current code is running inside, when there is one.\n *\n * A collection callback runs inside the transaction that carries its write.\n * Work it hands off — a job, a queue message, a topic event, a webhook\n * delivery — has to share that write's fate: queued when it commits, never\n * queued when it rolls back, and invisible to a worker until the commit. The\n * code that queues it lives in this package and knows no driver; the\n * transaction belongs to the driver. So the driver publishes the transaction it\n * opened for a write, and the queueing code asks for it here.\n *\n * Until this existed the job store wrote through the default driver's own\n * connection, in autocommit, whatever called it. A job enqueued from an\n * `afterSave` that then threw stayed queued for a row that was never written,\n * and a worker could claim it before the row it was about committed.\n *\n * The resolver lives on `globalThis` under a registered symbol, like the\n * `rebase` singleton: a managed runtime can load two copies of this package,\n * and the copy a driver registers with must be the one the job store reads.\n * No Node imports — the store is reachable from code that has to stay portable.\n *\n * **The symbol's key is a contract between packages, and frozen.** The\n * Postgres driver writes the slot itself rather than importing a setter from\n * here: the managed runtime supplies this package from the image while a\n * bundle brings its own driver, and a driver importing a function an older\n * image does not export would fail to link and take the boot down. Written\n * through the slot, any pairing of versions degrades to the old behaviour —\n * jobs committing on their own — instead.\n */\nexport interface AmbientTransaction {\n /**\n * Run one statement on the transaction, `$1…` placeholders as\n * `executeSql` takes them. It runs as the transaction's current role — on\n * Postgres the request's restricted one — so a statement that needs more\n * goes through a function granted to that role.\n */\n exec(sqlText: string, params?: unknown[]): Promise<Record<string, unknown>[]>;\n /** Run `fn` after the transaction commits. Never runs if it rolls back. */\n afterCommit(fn: () => void): void;\n}\n\n/** Frozen — see above. `server-postgres/src/services/write-transaction-scope.ts` writes it. */\nconst RESOLVER_SLOT = Symbol.for(\"rebase.server.ambientTransactionResolver\");\n\ntype ResolverSlot = { [RESOLVER_SLOT]?: () => AmbientTransaction | undefined };\n\n/**\n * Register how to find the write transaction the caller is inside; pass\n * `undefined` to unregister. For tests and for drivers in this repository's\n * lockstep — a driver shipped separately writes the slot, as above.\n */\nexport function setAmbientTransactionResolver(resolve: (() => AmbientTransaction | undefined) | undefined): void {\n (globalThis as ResolverSlot)[RESOLVER_SLOT] = resolve;\n}\n\n/** The write transaction the caller is inside, or `undefined` outside one. */\nexport function currentAmbientTransaction(): AmbientTransaction | undefined {\n return (globalThis as ResolverSlot)[RESOLVER_SLOT]?.();\n}\n","import { randomUUID } from \"crypto\";\nimport { logger } from \"../utils/logger.js\";\nimport { currentAmbientTransaction } from \"../db/ambient-transaction.js\";\nimport type { JobClaim, JobStore } from \"./job-store.js\";\nimport type { EnqueueOptions, JobHandler, JobQueueClient, JobQueueOptions, JobRecord } from \"./types.js\";\n\n/**\n * The worker: claim, run, record, repeat.\n *\n * Everything difficult about running jobs concurrently is in `job-store.ts`,\n * where one `UPDATE … FOR UPDATE SKIP LOCKED` does the arbitration. What is\n * left here is a loop and the decisions around a handler that throws.\n */\n\nconst DEFAULT_CONCURRENCY = 5;\nconst DEFAULT_POLL_INTERVAL_MS = 2_000;\nconst DEFAULT_VISIBILITY_TIMEOUT_MS = 5 * 60_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\n/**\n * How long one attempt may run when `jobs.timeoutMs` is left out. Without a\n * bound, a handler awaiting a socket that never answers held its worker slot\n * and its claim for the life of the process, with `/health` green. Fifteen\n * minutes is far past any job that is merely slow, and a job meant to run\n * longer says so with its own `timeoutMs` — or `0`, for no limit.\n */\nexport const DEFAULT_JOB_TIMEOUT_MS = 15 * 60_000;\n\n/**\n * The longest an idle worker goes without looking for work.\n *\n * An idle worker used to claim every 2 seconds, forever: about 45,000 round\n * trips a day per pod, each with a pool checkout, and a database that could\n * never suspend. Now it is woken instead — by `NOTIFY` when another process\n * enqueues, by its own enqueues, retries and delayed jobs — and this is the\n * safety poll behind that. Where the database cannot notify it, it backs off\n * from `pollIntervalMs` to this, doubling after each look that found nothing.\n */\nconst IDLE_POLL_MAX_MS = 30_000;\n\n/** 1s, 5s, 25s, 125s … capped at an hour. */\nexport function defaultBackoff(attempt: number): number {\n return Math.min(1_000 * Math.pow(5, Math.max(0, attempt - 1)), 60 * 60_000);\n}\n\n/**\n * How often the reaper runs, relative to the visibility timeout.\n *\n * A quarter of it, so a stranded job waits at most 1.25× the timeout rather\n * than 2× — and so the sweep is not itself a per-poll query against a table\n * whose interesting rows are, almost always, none.\n */\nconst REAP_INTERVAL_FACTOR = 0.25;\n\n/**\n * How long after a job's `run_at` a timed wake claims. A timer can fire a few\n * milliseconds early by the wall clock — libuv measures from its cached loop\n * time — and the claim compares `run_at <= now()` in the database. A claim that\n * lands before the row is due finds nothing, and with a `LISTEN` the worker\n * then sleeps until its safety poll: a job delayed by 1.5 s started a minute\n * late. Waking a little after the due time costs that much latency and nothing\n * else.\n */\nexport const DUE_GRACE_MS = 50;\n\n/**\n * How often a worker deletes finished jobs past retention. Hourly keeps the\n * table near its retention size on a pod that is never redeployed; each sweep\n * reads only the finished rows, through `idx_jobs_finished`.\n */\nconst RETENTION_SWEEP_INTERVAL_MS = 60 * 60_000;\n\n/**\n * Thrown by a handler for a failure no retry can change — a destination that\n * is refused, a receiver that redirects. The job is dead-lettered on this\n * attempt, with the message as its `last_error`, instead of spending its\n * remaining attempts proving the same thing. Returning normally is not the\n * alternative: that records the job as succeeded.\n */\nexport class PermanentJobError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"PermanentJobError\";\n }\n}\n\nexport interface JobQueue extends JobQueueClient {\n start(): void;\n /**\n * Stop claiming, and wait for the jobs in flight — for at most `timeoutMs`\n * when given. A job still running when the budget runs out keeps its claim\n * and is recovered by the visibility timeout; waiting on it without a bound\n * would let one handler that never settles hold the whole shutdown.\n */\n stop(timeoutMs?: number): Promise<void>;\n /**\n * Claim what fits in the free slots, run it, and resolve with how many jobs\n * ran. For tests and for `/jobs/drain`; not meant to run beside `start()`.\n */\n runOnce(): Promise<number>;\n /** Registered after construction — how `tasks` from config and internal producers meet. */\n register<P = unknown>(task: string, handler: JobHandler<P>): void;\n isRunning(): boolean;\n}\n\nexport function createJobQueue(store: JobStore, options: JobQueueOptions = {}): JobQueue {\n const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const visibilityTimeoutMs = options.visibilityTimeoutMs ?? DEFAULT_VISIBILITY_TIMEOUT_MS;\n const defaultMaxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const backoff = options.backoff ?? defaultBackoff;\n const configuredTimeoutMs = options.timeoutMs;\n if (configuredTimeoutMs !== undefined && !(Number.isFinite(configuredTimeoutMs) && configuredTimeoutMs >= 0)) {\n // NaN is what a mistyped env var parses to; it would fail every\n // attempt at once.\n throw new Error(`jobs.timeoutMs must be a number of milliseconds, or 0 for no limit (got ${String(configuredTimeoutMs)}).`);\n }\n /** `undefined` means no limit: only an explicit `0` asks for that. */\n const timeoutMs = configuredTimeoutMs === undefined\n ? DEFAULT_JOB_TIMEOUT_MS\n : configuredTimeoutMs === 0 ? undefined : configuredTimeoutMs;\n\n // A task's payload is whatever was enqueued under its name, so the map erases\n // each handler's `P`: the one place a stored handler is widened to `unknown`.\n const handlers = new Map<string, JobHandler<unknown>>();\n for (const [task, handler] of Object.entries(options.tasks ?? {})) {\n handlers.set(task, handler as JobHandler<unknown>);\n }\n\n // Identifies this process in `locked_by`: \"which pod had it when it\n // stopped\" is the first question anyone asks of a stuck job, and with the\n // attempt it is the claim an outcome is written under (see `JobClaim`).\n const workerId = `${process.pid}-${randomUUID().slice(0, 8)}`;\n\n let timer: NodeJS.Timeout | null = null;\n /** When {@link timer} fires (epoch ms), so a later wake never postpones an earlier one. */\n let timerDue = Infinity;\n /**\n * The wait after a look that found nothing. Doubles to {@link idleCeilingMs}\n * while the worker polls on its own; back to `pollIntervalMs` whenever\n * there is work or a wake. Fixed at the ceiling while notifications wake it.\n */\n const idleCeilingMs = Math.max(IDLE_POLL_MAX_MS, pollIntervalMs);\n let idleIntervalMs = pollIntervalMs;\n /** Notifications from the database wake this worker — see `JobStore.subscribe`. */\n let listening = false;\n let unsubscribe: (() => Promise<void>) | null = null;\n /** A wake arrived while a claim was in flight: claim again once it is done. */\n let rerun = false;\n let reapTimer: NodeJS.Timeout | null = null;\n let sweepTimer: NodeJS.Timeout | null = null;\n let sweeping = false;\n let running = false;\n /**\n * Every job this worker is running, tracked one by one rather than per\n * claimed batch: a batch would let its slowest job decide when the next\n * claim happens, so one handler that never settled would idle every other\n * slot — and hold `stop()` with it.\n */\n const active = new Set<Promise<void>>();\n /** The claim in progress, so `stop()` also waits for jobs it is about to hand out. */\n let claiming: Promise<unknown> | null = null;\n /** The last claim filled every free slot, so more work is probably waiting. */\n let backlog = false;\n let reaping = false;\n let draining: Promise<void> | null = null;\n\n /**\n * Renew `claim` while its handler runs, at a third of the visibility\n * timeout, so the reaper only ever takes a job from a worker that stopped\n * renewing — a dead one — and never from one that is merely slow. Returns\n * the stop.\n */\n function keepClaim(job: JobRecord, claim: JobClaim): () => void {\n if (!store.heartbeat) return () => undefined;\n const renew = store.heartbeat.bind(store);\n const interval = setInterval(() => {\n renew(job.id, claim).then((held) => {\n if (held) return;\n clearInterval(interval);\n logger.warn(\n `[jobs] \"${job.task}\" lost its claim on attempt ${claim.attempt} while running; ` +\n \"its outcome will not be recorded\", { jobId: job.id }\n );\n }).catch((error: unknown) => {\n logger.warn(`[jobs] Could not renew the claim on \"${job.task}\"`, { jobId: job.id, error });\n });\n }, Math.max(1, Math.floor(visibilityTimeoutMs / 3)));\n interval.unref?.();\n return () => clearInterval(interval);\n }\n\n async function runJob(job: JobRecord): Promise<void> {\n const handler = handlers.get(job.task);\n const claim: JobClaim = { workerId, attempt: job.attempts };\n\n if (!handler) {\n // Only reachable through a store that ignores the `tasks` filter on\n // `claim` — the one that ships never hands this worker a task it\n // has no handler for. Give the row back for a peer that has one.\n // The attempt the claim spent is not undone, so a task nobody in\n // the fleet implements dead-letters with an error naming it rather\n // than cycling through such a store forever.\n logger.warn(`[jobs] No handler registered for task \"${job.task}\" — returning the job to the queue`);\n const retryAt = job.attempts < job.maxAttempts ? new Date(Date.now() + backoff(job.attempts)) : null;\n await store.fail(job.id, `No handler registered for task \"${job.task}\"`, retryAt, claim);\n if (retryAt) wake(retryAt.getTime());\n return;\n }\n\n const releaseClaim = keepClaim(job, claim);\n const controller = new AbortController();\n let deadline: NodeJS.Timeout | undefined;\n try {\n try {\n const run = Promise.resolve().then(() => handler({\n id: job.id,\n task: job.task,\n payload: job.payload,\n attempt: job.attempts,\n maxAttempts: job.maxAttempts,\n signal: controller.signal\n }));\n if (timeoutMs === undefined) {\n await run;\n } else {\n // A handler that ignores the signal outlives its attempt;\n // what it does after is not this attempt's outcome.\n run.catch(() => undefined);\n await Promise.race([run, new Promise<never>((_, reject) => {\n deadline = setTimeout(() => {\n const error = new Error(`\"${job.task}\" timed out after ${timeoutMs}ms (jobs.timeoutMs)`);\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n // A deadline is not work: it must not hold a process\n // open that is otherwise done.\n deadline.unref?.();\n })]);\n }\n } finally {\n clearTimeout(deadline);\n releaseClaim();\n }\n await store.complete(job.id, claim);\n } catch (error) {\n const message = error instanceof Error ? (error.stack ?? error.message) : String(error);\n const permanent = error instanceof PermanentJobError;\n const willRetry = !permanent && job.attempts < job.maxAttempts;\n\n // Truncated, because `last_error` holds a stack and a queue that\n // accumulates megabytes of them is its own outage.\n const retryAt = willRetry ? new Date(Date.now() + backoff(job.attempts)) : null;\n await store.fail(job.id, message.slice(0, 4_000), retryAt, claim);\n // This worker knows when the retry is due; nobody will notify it.\n if (retryAt) wake(retryAt.getTime());\n\n if (willRetry) {\n logger.warn(`[jobs] \"${job.task}\" failed on attempt ${job.attempts}/${job.maxAttempts}; retrying`, { jobId: job.id });\n } else if (permanent) {\n logger.error(`[jobs] \"${job.task}\" failed permanently on attempt ${job.attempts}; not retrying`, { jobId: job.id, error: message });\n } else {\n // The last attempt is an error, not a warning: nothing else will\n // touch this job, and if nobody looks at the table it is simply\n // lost work.\n logger.error(`[jobs] \"${job.task}\" failed permanently after ${job.attempts} attempts`, { jobId: job.id, error: message });\n }\n }\n }\n\n /**\n * Return jobs stranded by a dead worker. On its own timer, not inside the\n * poll: a poll can be skipped for as long as every slot is busy, and that\n * is exactly when a stranded job most needs a peer to take it back.\n */\n async function reap(): Promise<void> {\n if (reaping) return;\n reaping = true;\n try {\n // Revived jobs are runnable now, and nothing notified anyone.\n if (await store.reapExpired(visibilityTimeoutMs) > 0) wake();\n } catch (error) {\n logger.error(\"[jobs] Failed to reclaim expired jobs\", { error });\n } finally {\n reaping = false;\n }\n }\n\n /**\n * Delete finished jobs past retention. On the worker, on its own timer:\n * the sweep used to run only in the boot path, awaited before the server\n * served, so a pod that lived for weeks never pruned and the next boot\n * paid for all of it at once.\n */\n async function sweep(): Promise<void> {\n if (sweeping || !store.sweepExpired) return;\n sweeping = true;\n try {\n const deleted = await store.sweepExpired();\n if (deleted > 0) logger.info(`[jobs] Removed ${deleted} finished job(s) past retention`);\n } catch (error) {\n logger.warn(\"[jobs] The retention sweep failed; it runs again within the hour\", { error });\n } finally {\n sweeping = false;\n }\n }\n\n /** Claim as many jobs as there are free slots and start each one on its own. */\n async function claimAndStart(): Promise<Promise<void>[]> {\n const free = concurrency - active.size;\n if (free <= 0) return [];\n\n // Only the tasks this worker can run. During a rolling deploy an\n // instance on older code shares the table with jobs whose task only\n // the newer code implements, and a claim spends an attempt: claiming\n // them here would dead-letter them before an updated peer got to them.\n // A handler registered after `start()` joins the next claim.\n if (handlers.size === 0) return [];\n const jobs = await store.claim(free, workerId, [...handlers.keys()]);\n backlog = jobs.length >= free;\n // Found work: look again soon if it runs out. Found none: wait longer.\n if (jobs.length > 0) idleIntervalMs = pollIntervalMs;\n\n return jobs.map((job) => {\n const run: Promise<void> = runJob(job)\n .catch((error) => {\n // `runJob` handles a throwing handler; this is a store\n // write failing after it. The job keeps its claim, so the\n // visibility timeout recovers it.\n logger.error(`[jobs] Could not record the outcome of \"${job.task}\"`, { jobId: job.id, error });\n })\n .finally(() => {\n active.delete(run);\n // A slot just came free and there is work waiting: take the\n // next job now, not a poll interval from now.\n if (backlog) schedule(0);\n });\n active.add(run);\n return run;\n });\n }\n\n /** Look for work in `delayMs` — unless a look is already due sooner. */\n function schedule(delayMs: number): void {\n if (!running) return;\n const due = Date.now() + delayMs;\n if (timer && timerDue <= due) return;\n if (timer) clearTimeout(timer);\n timerDue = due;\n timer = setTimeout(() => {\n timer = null;\n timerDue = Infinity;\n void tick();\n }, delayMs);\n // Never hold the process open. A queue with nothing to do should not be\n // the reason `rebase dev` will not exit.\n timer.unref?.();\n }\n\n /**\n * Work may be runnable at `runAtMs` (now, when absent): a job was enqueued\n * — here, or in another process that notified — or a retry or a reclaimed\n * job came due. Resets the back-off.\n */\n function wake(runAtMs?: number): void {\n if (!running) return;\n idleIntervalMs = pollIntervalMs;\n const now = Date.now();\n const delay = runAtMs === undefined || runAtMs <= now ? 0 : runAtMs + DUE_GRACE_MS - now;\n if (delay === 0 && active.size >= concurrency) {\n // Every slot is busy: the next one to free claims at once.\n backlog = true;\n return;\n }\n schedule(delay);\n }\n\n async function tick(): Promise<void> {\n if (!running) return;\n // A claim already in progress looks again when it finishes — the wake\n // may be for a row its snapshot did not see.\n if (claiming) {\n rerun = true;\n return;\n }\n const work = claimAndStart().catch((error) => {\n logger.error(\"[jobs] Poll failed\", { error });\n backlog = false;\n });\n claiming = work;\n await work;\n claiming = null;\n\n // A full claim with a slot still free — a job already finished — means\n // go straight back, and so does a wake that came in mid-claim.\n // Otherwise sleep; a job finishing during a backlog wakes the loop\n // early, and so does anything that calls `wake`.\n if ((backlog && active.size < concurrency) || rerun) {\n rerun = false;\n schedule(0);\n return;\n }\n if (listening) {\n schedule(idleCeilingMs);\n return;\n }\n schedule(idleIntervalMs);\n idleIntervalMs = Math.min(idleIntervalMs * 2, idleCeilingMs);\n }\n\n /** Be woken by the database when another process enqueues — where it can. */\n function listen(): void {\n if (!store.subscribe) return;\n store.subscribe(\n (runAtMs) => wake(runAtMs),\n // Notifications sent while the connection was down are gone.\n () => wake()\n ).then((stop) => {\n if (!running) {\n void stop().catch(() => undefined);\n return;\n }\n unsubscribe = stop;\n listening = true;\n logger.info(`[jobs] Woken by the database on enqueue; looking every ${idleCeilingMs / 1000}s besides`);\n }).catch((error: unknown) => {\n logger.info(\n `[jobs] Not woken by the database (${error instanceof Error ? error.message : String(error)}); ` +\n `polling instead, from every ${pollIntervalMs}ms up to every ${idleCeilingMs / 1000}s while idle`\n );\n });\n }\n\n async function drain(): Promise<void> {\n await claiming;\n await Promise.allSettled([...active]);\n }\n\n return {\n start(): void {\n if (running) return;\n running = true;\n idleIntervalMs = pollIntervalMs;\n logger.info(`[jobs] Worker started (concurrency ${concurrency}, poll ${pollIntervalMs}ms, up to ${idleCeilingMs}ms while idle)`);\n if (configuredTimeoutMs === undefined) {\n logger.info(\n `[jobs] Each attempt is limited to ${DEFAULT_JOB_TIMEOUT_MS / 60_000} minutes, the default jobs.timeoutMs. ` +\n \"Set jobs.timeoutMs to change it, or 0 for no limit.\"\n );\n }\n void reap();\n reapTimer = setInterval(() => { void reap(); }, visibilityTimeoutMs * REAP_INTERVAL_FACTOR);\n reapTimer.unref?.();\n void sweep();\n sweepTimer = setInterval(() => { void sweep(); }, RETENTION_SWEEP_INTERVAL_MS);\n sweepTimer.unref?.();\n listen();\n schedule(0);\n },\n\n async stop(timeoutMs?: number): Promise<void> {\n running = false;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n timerDue = Infinity;\n }\n listening = false;\n const stopListening = unsubscribe;\n unsubscribe = null;\n if (stopListening) {\n await stopListening().catch((error: unknown) => {\n logger.warn(\"[jobs] Could not close the notification connection\", { error });\n });\n }\n if (reapTimer) {\n clearInterval(reapTimer);\n reapTimer = null;\n }\n if (sweepTimer) {\n clearInterval(sweepTimer);\n sweepTimer = null;\n }\n // Jobs in flight keep their claim until they finish or the\n // visibility timeout expires, so waiting here is what turns a\n // graceful shutdown into \"no job runs twice\".\n draining ??= drain().finally(() => { draining = null; });\n if (timeoutMs === undefined) {\n await draining;\n return;\n }\n let budget: NodeJS.Timeout | undefined;\n const finished = await Promise.race([\n draining.then(() => true),\n new Promise<false>((resolve) => {\n budget = setTimeout(() => resolve(false), timeoutMs);\n budget.unref?.();\n })\n ]);\n clearTimeout(budget);\n if (!finished) {\n logger.warn(\n `[jobs] ${active.size} job(s) still running after ${timeoutMs}ms; stopping without them. ` +\n \"They keep their claim and are retried once the visibility timeout reclaims it.\"\n );\n }\n },\n\n async runOnce(): Promise<number> {\n const started = await claimAndStart();\n await Promise.allSettled(started);\n return started.length;\n },\n\n register<P = unknown>(task: string, handler: JobHandler<P>): void {\n if (handlers.has(task)) {\n logger.warn(`[jobs] Task \"${task}\" was already registered; the later handler wins`);\n }\n handlers.set(task, handler as JobHandler<unknown>);\n },\n\n isRunning(): boolean {\n return running;\n },\n\n async enqueue<P = unknown>(task: string, payload?: P, enqueueOptions: EnqueueOptions = {}): Promise<string | null> {\n const runAt = new Date(Date.now() + (enqueueOptions.delayMs ?? 0));\n // Read before the insert, which may await: inside a write the row\n // is invisible until that write commits, so that is when to look.\n const ambient = currentAmbientTransaction();\n const id = await store.insert({\n task,\n payload: payload ?? null,\n runAt,\n maxAttempts: enqueueOptions.maxAttempts ?? defaultMaxAttempts,\n idempotencyKey: enqueueOptions.idempotencyKey\n });\n // This process's own worker needs no notification to hear about it.\n if (id !== null && running) {\n if (ambient) ambient.afterCommit(() => wake(runAt.getTime()));\n else wake(runAt.getTime());\n }\n return id;\n }\n };\n}\n","import type { DataDriver } from \"@rebasepro/types\";\nimport { isSQLAdmin } from \"@rebasepro/types\";\nimport { grantExecuteToRequestRolesSql, revokeInternalTableSql, sqlRows, firstSqlRow } from \"@rebasepro/common\";\nimport { logger } from \"../utils/logger.js\";\nimport { createDdlBootstrapper, hasInCauseChain, provisioningExec, type SqlExec } from \"../boot/ddl-bootstrap.js\";\nimport { currentAmbientTransaction } from \"../db/ambient-transaction.js\";\nimport type { JobRecord } from \"./types.js\";\n\n/**\n * The queue's storage, as SQL against `rebase.jobs`.\n *\n * Split from the worker for the same reason `cron-store` is split from\n * `cron-scheduler`: the interesting parts here are three statements that have\n * to be exactly right under concurrency, and they are much easier to reason\n * about — and to test — away from a polling loop.\n */\n\nconst TABLE = \"rebase.jobs\";\n\n/** How long finished jobs are kept before the retention sweep removes them. */\nconst SUCCEEDED_RETENTION_DAYS = 3;\n/**\n * Failures outlive successes by a lot. A dead-lettered job is evidence, and the\n * person who needs it is usually looking on Monday for something that happened\n * on Friday night.\n */\nconst FAILED_RETENTION_DAYS = 30;\n\n/**\n * Rows one retention statement deletes. A sweep repeats it until a batch\n * comes back short, so a backlog — the first sweep on a table a long-lived\n * pod let grow to millions of rows — is many short transactions rather than\n * one that holds locks and writes a burst of WAL for seconds.\n */\nconst RETENTION_BATCH = 5_000;\n\n/** A row as Postgres returns it. */\ninterface JobRow {\n id: string;\n task: string;\n payload: unknown;\n status: string;\n run_at: string;\n attempts: number;\n max_attempts: number;\n last_error: string | null;\n created_at: string;\n updated_at: string;\n}\n\nfunction toRecord(row: JobRow): JobRecord {\n return {\n id: row.id,\n task: row.task,\n payload: row.payload,\n status: row.status as JobRecord[\"status\"],\n runAt: new Date(row.run_at).toISOString(),\n attempts: Number(row.attempts),\n maxAttempts: Number(row.max_attempts),\n lastError: row.last_error,\n createdAt: new Date(row.created_at).toISOString(),\n updatedAt: new Date(row.updated_at).toISOString()\n };\n}\n\n/** Same rule as `cron-store`: match the SQLSTATE, never the message. */\nfunction isUniqueViolation(err: unknown): boolean {\n return hasInCauseChain(err, (e) => e.code === \"23505\");\n}\n\n/**\n * How a job gets into `rebase.jobs` from inside somebody else's transaction.\n *\n * An enqueue from a collection callback has to ride the write's transaction —\n * committed with it, discarded with it, invisible to workers until then — and\n * that transaction runs as the request's restricted role, which has no access\n * to `rebase.jobs` at all (see the revoke in `ensureTable`). This function is\n * the one door: `SECURITY DEFINER`, so the insert runs with the owner's rights\n * for that one statement and the transaction's role never changes. Switching\n * the role for the insert instead would elevate the whole connection for as\n * long as the insert took, and a callback's un-awaited statement would run\n * in that window as the owner.\n *\n * The door is narrow on purpose. It takes the five columns an enqueue sets and\n * nothing else, so it cannot claim, complete or rewrite a job — and only the\n * request role is granted it, not PUBLIC. That role runs statements the server\n * writes; nobody outside gets SQL as it.\n *\n * `ON CONFLICT DO NOTHING` rather than a caught unique violation: an error\n * inside a transaction aborts the whole transaction, so an idempotency clash\n * would have failed the customer's write. A clash returns no row, hence NULL.\n */\nconst ENQUEUE_FUNCTION = \"rebase.enqueue_job\";\nconst ENQUEUE_SIGNATURE = `${ENQUEUE_FUNCTION}(text, jsonb, timestamptz, integer, text)`;\n\n/**\n * The `NOTIFY` channel an insert announces itself on, with the job's `run_at`\n * in epoch milliseconds as the payload. Workers listening on it are woken\n * instead of polling; Postgres delivers it when the insert commits, and not at\n * all if it rolls back. Frozen: workers of the previous release listen on it\n * during a rolling deploy.\n */\nexport const JOBS_NOTIFY_CHANNEL = \"rebase_jobs\";\n\n/** `run_at` as the notification's payload: epoch milliseconds, as text. */\nconst NOTIFY_PAYLOAD = (runAt: string) => `(extract(epoch FROM ${runAt}) * 1000)::bigint::text`;\n\n/**\n * Which claim an outcome belongs to: the worker holding the job, and the\n * attempt that claim spent.\n *\n * The visibility timeout hands a job to a second worker when the first stops\n * renewing its claim, and the first may still be running — slow, not dead. Its\n * outcome is then about an attempt the table has moved past, and writing it\n * would mark a running job `succeeded`, or send a finished one back to\n * `pending` for another run. Both writes therefore apply only while the claim\n * they name still holds the row. The attempt is part of the identity because a\n * worker's own reaper can hand a job back to the same worker in another slot.\n */\nexport interface JobClaim {\n workerId: string;\n attempt: number;\n}\n\nexport interface JobStore {\n ensureTable(): Promise<void>;\n /** Returns the new job's id, or `null` if an idempotency key matched unfinished work. */\n insert(job: {\n task: string;\n payload: unknown;\n runAt: Date;\n maxAttempts: number;\n idempotencyKey?: string;\n }): Promise<string | null>;\n /**\n * Atomically take up to `limit` runnable jobs for this worker — only jobs\n * whose task is in `tasks`, when it is given. A worker never claims work it\n * cannot run: a claim spends an attempt, so an instance running older code\n * during a rollout would otherwise dead-letter the newer code's jobs.\n */\n claim(limit: number, workerId: string, tasks?: readonly string[]): Promise<JobRecord[]>;\n /** Mark the job `succeeded` — a no-op once `claim` no longer holds it. */\n complete(id: string, claim: JobClaim): Promise<void>;\n /**\n * Back to `pending` with a later `runAt`, or `failed` when out of attempts —\n * a no-op once `claim` no longer holds it.\n */\n fail(id: string, error: string, retryAt: Date | null, claim: JobClaim): Promise<void>;\n /**\n * Renew `claim` on a job whose handler is still running, so the visibility\n * timeout only ever reclaims a job from a worker that stopped renewing.\n * Resolves with whether the claim still held. A store without it leaves a\n * handler that outlives the timeout to be run a second time beside itself.\n */\n heartbeat?(id: string, claim: JobClaim): Promise<boolean>;\n /** Return jobs stranded by a worker that died holding them. Resolves with how many. */\n reapExpired(visibilityTimeoutMs: number): Promise<number>;\n /**\n * Call `onWake` whenever any process inserts a job, with the job's `run_at`\n * in epoch milliseconds. Resolves, once listening, with the stop; rejects\n * when this database cannot notify this process — no session connection\n * to hold a `LISTEN` on — and the worker polls instead. `onReconnect` is\n * called after a dropped connection is back: what was sent meanwhile is\n * lost. A store without it leaves the worker polling.\n */\n subscribe?(onWake: (runAtMs?: number) => void, onReconnect: () => void): Promise<() => Promise<void>>;\n /**\n * Delete finished jobs past retention — succeeded ones after\n * {@link SUCCEEDED_RETENTION_DAYS} days, failed ones after\n * {@link FAILED_RETENTION_DAYS} — in batches. Resolves with how many went.\n * The worker runs it on a timer; a store without it keeps every row.\n */\n sweepExpired?(): Promise<number>;\n fetch(id: string): Promise<JobRecord | null>;\n}\n\n/** The rows a claim's writes may touch: `$1` the job, `$2` the worker, `$3` the attempt. */\nconst HELD_BY_CLAIM = \"id = $1 AND status = 'running' AND locked_by = $2 AND attempts = $3\";\n\nfunction warnStaleOutcome(id: string, claim: JobClaim, outcome: \"success\" | \"failure\"): void {\n logger.warn(\n `[jobs] Ignored the ${outcome} of attempt ${claim.attempt} of job ${id}: the job was reclaimed ` +\n \"from this worker while it ran, so that attempt's outcome is no longer the job's.\"\n );\n}\n\nexport function createJobStore(\n /** Only its SQL escape hatch is read. */\n driver: Pick<DataDriver, \"admin\">,\n options: {\n /**\n * Default `true`. `false` is a backend that changes nothing in its\n * database: `ensureTable` uses the queue and its enqueue function if\n * they are there, and creates, grants and revokes nothing.\n */\n provision?: boolean;\n } = {}\n): JobStore | undefined {\n const admin = driver.admin;\n if (!isSQLAdmin(admin)) {\n logger.warn(\n \"⚠️ [jobs] DataDriver does not support SQL admin — the durable job queue is unavailable. \" +\n \"Work that would have been queued runs inline instead.\"\n );\n return undefined;\n }\n\n // Two shapes of the same call: the bootstrapper's `SqlExec` takes an\n // options object, while everything below reads better with a positional\n // parameter array.\n const execRaw: SqlExec = provisioningExec(\n (sqlText, execOptions) =>\n admin.executeSql(sqlText, execOptions?.params ? { params: execOptions.params } : undefined),\n options.provision\n );\n const exec = (sqlText: string, params?: unknown[]) =>\n execRaw(sqlText, params ? { params } : undefined);\n\n const ddl = createDdlBootstrapper(execRaw, \"jobs\");\n\n /**\n * Whether {@link ENQUEUE_FUNCTION} exists, so an enqueue inside a write can\n * ride its transaction. Decided at boot rather than assumed: a database\n * that refused the function would otherwise fail every write whose callback\n * enqueues, where falling back to the old behaviour only loses atomicity.\n */\n let enqueueInTransaction = false;\n\n return {\n async ensureTable(): Promise<void> {\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 task TEXT NOT NULL,\n payload JSONB,\n status TEXT NOT NULL DEFAULT 'pending',\n run_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n attempts INTEGER NOT NULL DEFAULT 0,\n max_attempts INTEGER NOT NULL DEFAULT 3,\n locked_at TIMESTAMPTZ,\n locked_by TEXT,\n idempotency_key TEXT,\n last_error TEXT,\n created_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n updated_at TIMESTAMPTZ NOT NULL DEFAULT now()\n )\n `);\n\n // The claim query's index. Partial, because the rows it has to find\n // fast are a shrinking minority of a table that also holds every\n // success and every dead letter.\n await ddl.ensureObject(\"Creating idx_jobs_runnable\", `\n CREATE INDEX IF NOT EXISTS idx_jobs_runnable\n ON ${TABLE}(run_at, created_at)\n WHERE status = 'pending'\n `);\n\n // Finds jobs stranded by a dead worker.\n await ddl.ensureObject(\"Creating idx_jobs_running\", `\n CREATE INDEX IF NOT EXISTS idx_jobs_running\n ON ${TABLE}(locked_at)\n WHERE status = 'running'\n `);\n\n // What makes `idempotencyKey` a guarantee rather than a\n // check-then-act race: two instances reacting to one event both\n // reach the INSERT, and the index decides. Partial on unfinished\n // work — see `EnqueueOptions.idempotencyKey` for why a key must be\n // reusable once its job is done.\n await ddl.ensureObject(\"Creating idx_jobs_idempotency\", `\n CREATE UNIQUE INDEX IF NOT EXISTS idx_jobs_idempotency\n ON ${TABLE}(idempotency_key)\n WHERE idempotency_key IS NOT NULL AND status IN ('pending', 'running')\n `);\n\n // The retention sweep's index. Partial on the finished rows — the\n // only ones it deletes — so a sweep reads what it removes instead\n // of the whole table; without it every sweep was a sequential scan,\n // six seconds over two million rows.\n await ddl.ensureObject(\"Creating idx_jobs_finished\", `\n CREATE INDEX IF NOT EXISTS idx_jobs_finished\n ON ${TABLE}(status, updated_at)\n WHERE status IN ('succeeded', 'failed')\n `);\n\n const ready = await ddl.isReadable(TABLE);\n\n if (ready) {\n // No retention sweep here. It used to run at boot and only at\n // boot: awaited before the server served, a sequential scan of\n // the whole table, and never again for as long as the pod lived\n // — a worker up for three weeks held seven times the rows\n // retention meant to keep. The worker runs `sweepExpired` on a\n // timer instead.\n\n // Payloads are arbitrary application data — a webhook body, a\n // user id, whatever was passed — and a writable queue lets any\n // signed-in user schedule work of their choosing under the\n // server's own authority. Same reasoning, and the same\n // unconditional re-application, as `cron_claims`.\n await ddl.step(\"Revoking end-user access to jobs\", () =>\n exec(revokeInternalTableSql(\"rebase\", \"jobs\")));\n\n await ddl.ensureObject(`Creating ${ENQUEUE_FUNCTION}`, `\n CREATE OR REPLACE FUNCTION ${ENQUEUE_FUNCTION}(\n p_task text, p_payload jsonb, p_run_at timestamptz,\n p_max_attempts integer, p_idempotency_key text\n ) RETURNS text\n LANGUAGE sql\n SECURITY DEFINER\n SET search_path = pg_catalog, pg_temp\n AS $fn$\n SELECT pg_notify('${JOBS_NOTIFY_CHANNEL}', ${NOTIFY_PAYLOAD(\"p_run_at\")});\n INSERT INTO ${TABLE} (task, payload, run_at, max_attempts, idempotency_key)\n VALUES (p_task, p_payload, p_run_at, p_max_attempts, p_idempotency_key)\n ON CONFLICT DO NOTHING\n RETURNING id\n $fn$\n `);\n // Re-applied every boot: a new function is executable by PUBLIC\n // until told otherwise, and the request role may be provisioned\n // after the function was first made.\n await ddl.step(`Granting ${ENQUEUE_FUNCTION} to the request role`, async () => {\n await exec(`REVOKE ALL ON FUNCTION ${ENQUEUE_SIGNATURE} FROM PUBLIC`);\n await exec(grantExecuteToRequestRolesSql(ENQUEUE_SIGNATURE));\n });\n enqueueInTransaction = firstSqlRow<{ present: boolean }>(await exec(\n `SELECT to_regprocedure('${ENQUEUE_SIGNATURE}') IS NOT NULL AS present`\n ))?.present === true;\n if (!enqueueInTransaction) {\n logger.warn(\n `⚠️ [jobs] ${ENQUEUE_FUNCTION} could not be created, so a job enqueued inside a write ` +\n \"commits on its own: it stays queued if the write rolls back.\"\n );\n }\n\n logger.info(\"✅ Job queue table ready\");\n } else {\n logger.error(\n `❌ [jobs] ${TABLE} is unavailable — nothing can be queued and nothing queued earlier ` +\n \"will run. Callers fall back to running the work inline.\"\n );\n }\n },\n\n async insert(job): Promise<string | null> {\n const params = [\n job.task,\n JSON.stringify(job.payload ?? null),\n job.runAt.toISOString(),\n job.maxAttempts,\n job.idempotencyKey ?? null\n ];\n // Inside a write: on its transaction, through the definer function\n // — see `ENQUEUE_FUNCTION`. Checked and used with no `await`\n // between, so the transaction cannot close in the gap.\n const ambient = enqueueInTransaction ? currentAmbientTransaction() : undefined;\n if (ambient) {\n const rows = await ambient.exec(\n `SELECT ${ENQUEUE_FUNCTION}($1::text, $2::jsonb, $3::timestamptz, $4::integer, $5::text) AS id`,\n params\n );\n return (rows?.[0]?.id as string | null | undefined) ?? null;\n }\n try {\n // The notification rides the insert's own statement, so it\n // is sent exactly when the row commits.\n const rows = await exec(\n `WITH inserted AS (\n INSERT INTO ${TABLE} (task, payload, run_at, max_attempts, idempotency_key)\n VALUES ($1, $2::jsonb, $3, $4, $5)\n RETURNING id, run_at\n )\n SELECT id, pg_notify('${JOBS_NOTIFY_CHANNEL}', ${NOTIFY_PAYLOAD(\"run_at\")}) AS notified\n FROM inserted`,\n params\n );\n return (rows?.[0]?.id as string) ?? null;\n } catch (error) {\n // The losing side of an idempotency race. Not an error: the\n // work the caller wanted is already queued, which is the\n // outcome they asked for.\n if (isUniqueViolation(error)) return null;\n throw error;\n }\n },\n\n async claim(limit: number, workerId: string, tasks?: readonly string[]): Promise<JobRecord[]> {\n if (tasks && tasks.length === 0) return [];\n // One placeholder per task rather than an array parameter: every\n // driver binds a string, and not every driver binds an array.\n const taskFilter = tasks\n ? `AND task IN (${tasks.map((_, i) => `$${i + 3}`).join(\", \")})`\n : \"\";\n // `FOR UPDATE SKIP LOCKED` is the whole design. The inner select\n // takes row locks on the jobs it picks and *skips* any a concurrent\n // worker already holds, so N workers polling the same table divide\n // the work instead of contending for the head of it — and no job is\n // ever handed to two of them.\n //\n // `attempts` is incremented here, on claim, rather than on failure.\n // A worker that is killed mid-job never reports anything, so\n // counting on failure would let a job that crashes the process be\n // retried forever, once per restart, taking the process down each\n // time.\n const rows = await exec(\n `UPDATE ${TABLE} SET\n status = 'running',\n attempts = attempts + 1,\n locked_at = now(),\n locked_by = $2,\n updated_at = now()\n WHERE id IN (\n SELECT id FROM ${TABLE}\n WHERE status = 'pending' AND run_at <= now() ${taskFilter}\n ORDER BY run_at, created_at\n LIMIT $1\n FOR UPDATE SKIP LOCKED\n )\n RETURNING *`,\n [limit, workerId, ...(tasks ?? [])]\n );\n return sqlRows<JobRow>(rows).map(toRecord);\n },\n\n async complete(id: string, claim: JobClaim): Promise<void> {\n const rows = await exec(\n `UPDATE ${TABLE} SET status = 'succeeded', locked_at = NULL, locked_by = NULL,\n last_error = NULL, updated_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt]\n );\n if (sqlRows(rows).length === 0) warnStaleOutcome(id, claim, \"success\");\n },\n\n async fail(id: string, error: string, retryAt: Date | null, claim: JobClaim): Promise<void> {\n const rows = retryAt\n ? await exec(\n `UPDATE ${TABLE} SET status = 'pending', run_at = $4, locked_at = NULL,\n locked_by = NULL, last_error = $5, updated_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt, retryAt.toISOString(), error]\n )\n : await exec(\n `UPDATE ${TABLE} SET status = 'failed', locked_at = NULL, locked_by = NULL,\n last_error = $4, updated_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt, error]\n );\n if (sqlRows(rows).length === 0) warnStaleOutcome(id, claim, \"failure\");\n },\n\n async heartbeat(id: string, claim: JobClaim): Promise<boolean> {\n const rows = await exec(\n `UPDATE ${TABLE} SET locked_at = now()\n WHERE ${HELD_BY_CLAIM}\n RETURNING id`,\n [id, claim.workerId, claim.attempt]\n );\n return sqlRows(rows).length > 0;\n },\n\n async reapExpired(visibilityTimeoutMs: number): Promise<number> {\n // A worker killed while holding a job cannot release it, so nothing\n // but a timeout will ever free the row. Jobs that still have\n // attempts left go back to `pending`; the rest are dead-lettered\n // with an error that says what happened, because \"attempts: 3,\n // lastError: null\" is otherwise a genuinely baffling row to find.\n const seconds = Math.max(1, Math.round(visibilityTimeoutMs / 1000));\n\n const revived = await exec(\n `UPDATE ${TABLE} SET status = 'pending', locked_at = NULL, locked_by = NULL,\n last_error = 'Worker stopped responding; the job was reclaimed', updated_at = now()\n WHERE status = 'running'\n AND locked_at < now() - make_interval(secs => $1)\n AND attempts < max_attempts\n RETURNING id`,\n [seconds]\n );\n\n const buried = await exec(\n `UPDATE ${TABLE} SET status = 'failed', locked_at = NULL, locked_by = NULL,\n last_error = 'Worker stopped responding on the final attempt', updated_at = now()\n WHERE status = 'running'\n AND locked_at < now() - make_interval(secs => $1)\n AND attempts >= max_attempts\n RETURNING id`,\n [seconds]\n );\n\n const count = (revived?.length ?? 0) + (buried?.length ?? 0);\n if (count > 0) {\n logger.warn(\n `[jobs] Reclaimed ${count} job(s) from a worker that stopped responding ` +\n `(${revived?.length ?? 0} retryable, ${buried?.length ?? 0} dead-lettered)`\n );\n }\n return count;\n },\n\n async sweepExpired(): Promise<number> {\n // `SKIP LOCKED`, so replicas sweeping at once divide the rows\n // rather than queue behind each other's batch. The count comes back\n // as one row, not one id per deleted job.\n let total = 0;\n for (;;) {\n const rows = await exec(\n `WITH swept AS (\n DELETE FROM ${TABLE}\n WHERE id IN (\n SELECT id FROM ${TABLE}\n WHERE (status = 'succeeded' AND updated_at < now() - make_interval(days => $1))\n OR (status = 'failed' AND updated_at < now() - make_interval(days => $2))\n LIMIT $3\n FOR UPDATE SKIP LOCKED\n )\n RETURNING 1\n )\n SELECT count(*)::int AS deleted FROM swept`,\n [SUCCEEDED_RETENTION_DAYS, FAILED_RETENTION_DAYS, RETENTION_BATCH]\n );\n const deleted = Number(firstSqlRow<{ deleted: number }>(rows)?.deleted ?? 0);\n total += deleted;\n if (deleted < RETENTION_BATCH) return total;\n }\n },\n\n async subscribe(onWake: (runAtMs?: number) => void, onReconnect: () => void): Promise<() => Promise<void>> {\n if (!admin.listen) {\n throw new Error(\"this database driver has no notifications\");\n }\n return admin.listen(JOBS_NOTIFY_CHANNEL, (payload) => {\n const runAtMs = Number(payload);\n onWake(Number.isFinite(runAtMs) && runAtMs > 0 ? runAtMs : undefined);\n }, { onReconnect });\n },\n\n async fetch(id: string): Promise<JobRecord | null> {\n const rows = await exec(`SELECT * FROM ${TABLE} WHERE id = $1`, [id]);\n const row = firstSqlRow<JobRow>(rows);\n return row ? toRecord(row) : null;\n }\n };\n}\n","export { createJobStore } from \"./job-store\";\nexport type { JobClaim, JobStore } from \"./job-store\";\nexport { createJobQueue, defaultBackoff, PermanentJobError } from \"./job-queue\";\nexport type { JobQueue } from \"./job-queue\";\nexport type {\n EnqueueOptions,\n JobContext,\n JobHandler,\n JobQueueClient,\n JobQueueOptions,\n JobRecord,\n JobStatus\n} from \"./types\";\n"],"mappings":";;;;;;;;;;;;AA0CA,IAAM,gBAAgB,OAAO,IAAI,0CAA0C;;AAc3E,SAAgB,4B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process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
|
-
import {
|
|
5
|
+
import { Bn as __toESM, Ln as __commonJSMin, zn as __require } from "./src-CNZB3fuE.js";
|
|
6
6
|
import { a as logger } from "./logger-SigQ2oZJ.js";
|
|
7
|
-
import { a as canonicalStorageId } from "./keys-
|
|
7
|
+
import { a as canonicalStorageId } from "./keys-Btt6ZNqF.js";
|
|
8
8
|
import { createPrivateKey, createPublicKey, createSecretKey } from "crypto";
|
|
9
9
|
//#region src/utils/portable-crypto.ts
|
|
10
10
|
/**
|
|
@@ -5093,4 +5093,4 @@ var processJwtService = {
|
|
|
5093
5093
|
//#endregion
|
|
5094
5094
|
export { randomHex as C, sha256Hex as E, constantTimeEqual as S, sha256Bytes as T, verifyAccessToken as _, generateAccessToken as a, normalizePemFromEnv as b, getAccessTokenExpiry as c, hasAsymmetricSigningKey as d, hashRefreshToken as f, setDefaultJwtService as g, processJwtService as h, customClaimsOf as i, getJwks as l, jwtOf as m, configureJwt as n, generateDownloadToken as o, isJwtConfigured as p, createJwtService as r, generateRefreshToken as s, MAX_COOKIE_AGE_MS as t, getRefreshTokenExpiry as u, verifyDownloadToken as v, randomInt$1 as w, require_jsonwebtoken as x, verifyJwt as y };
|
|
5095
5095
|
|
|
5096
|
-
//# sourceMappingURL=jwt-
|
|
5096
|
+
//# sourceMappingURL=jwt-CqhXs8Iz.js.map
|