@happyvertical/smrt-jobs 0.61.2 → 0.61.4

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.
@@ -1,58 +0,0 @@
1
- import { detectEngine } from "@happyvertical/smrt-core";
2
- import { createId } from "@happyvertical/utils";
3
- //#region src/worker-liveness.ts
4
- var LIVE_WORKERS_KEY = "__smrtLiveWorkers";
5
- function liveWorkers() {
6
- const g = globalThis;
7
- let set = g[LIVE_WORKERS_KEY];
8
- if (!set) {
9
- set = /* @__PURE__ */ new Set();
10
- g[LIVE_WORKERS_KEY] = set;
11
- }
12
- return set;
13
- }
14
- function registerLiveWorker(workerKey) {
15
- liveWorkers().add(workerKey);
16
- }
17
- function unregisterLiveWorker(workerKey) {
18
- liveWorkers().delete(workerKey);
19
- }
20
- function isLiveWorker(workerKey) {
21
- return liveWorkers().has(workerKey);
22
- }
23
- function isWorkerAlive(workerKey, freshLeaseKeys) {
24
- if (!workerKey) return false;
25
- return isLiveWorker(workerKey) || freshLeaseKeys.has(workerKey);
26
- }
27
- function createWorkerKey(baseId) {
28
- return `${baseId}~${createId().slice(0, 8)}`;
29
- }
30
- function resolveUrl(db) {
31
- const withConfig = db;
32
- return db.url || withConfig.config?.url || "";
33
- }
34
- async function tuneSqliteForConcurrency(db) {
35
- try {
36
- await db.query("PRAGMA busy_timeout = 5000");
37
- await db.query("PRAGMA journal_mode = WAL");
38
- } catch {}
39
- }
40
- function resolveEngine(db) {
41
- const withConfig = db;
42
- const type = withConfig.type || withConfig.config?.type;
43
- return detectEngine(resolveUrl(db), type);
44
- }
45
- function isInMemory(db) {
46
- const url = resolveUrl(db).toLowerCase();
47
- return url === ":memory:" || url.includes("mode=memory") || url.includes("file::memory:");
48
- }
49
- function offLoopEligible(db) {
50
- const engine = resolveEngine(db);
51
- if (engine === "postgres") return true;
52
- if (engine === "sqlite") return !isInMemory(db);
53
- return false;
54
- }
55
- //#endregion
56
- export { resolveEngine as a, unregisterLiveWorker as c, registerLiveWorker as i, isWorkerAlive as n, resolveUrl as o, offLoopEligible as r, tuneSqliteForConcurrency as s, createWorkerKey as t };
57
-
58
- //# sourceMappingURL=worker-liveness-C1Gjnhax.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"worker-liveness-C1Gjnhax.js","names":[],"sources":["../../src/worker-liveness.ts"],"sourcesContent":["import { detectEngine } from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\n\ntype DatabaseEngine = ReturnType<typeof detectEngine>;\n\n/**\n * Worker liveness primitives shared by {@link ../runner.js} and\n * {@link ../schedule-runner.js}.\n *\n * Job recovery keys on whether a job's *owning worker* is alive, never on\n * per-job heartbeat freshness (issue #1474). \"Alive\" has two independent\n * sources, combined by {@link isWorkerAlive}:\n *\n * 1. **Process-global live set** — an in-memory {@link Set} of worker keys\n * whose runner is live *in this process*. Checked synchronously, so it can\n * never be starved by a CPU-bound handler holding the event loop. Covers\n * every same-process topology (a runner's own jobs, a co-located\n * ScheduleRunner, a second in-process runner).\n * 2. **Database lease** — a `_smrt_workers` row whose `lease_expires_at` is\n * still in the future. Covers cross-process recovery. The lease is renewed\n * by the owning runner; a dead worker stops renewing and its lease expires.\n *\n * The live set takes precedence: a worker live in this process is alive even\n * if its database lease looks stale.\n *\n * The lease is compared against the recovering host's clock (the same approach\n * the previous heartbeat recovery used), so it is no more sensitive to clock\n * skew than the code it replaces. For eligible engines the lease is renewed off\n * the main loop by a worker thread (see worker-liveness-ticker.ts) so a blocked\n * handler can't starve it; otherwise it is renewed on the main loop and the\n * live set covers same-process correctness.\n */\n\nconst LIVE_WORKERS_KEY = '__smrtLiveWorkers';\n\ntype GlobalWithLiveWorkers = typeof globalThis & {\n [LIVE_WORKERS_KEY]?: Set<string>;\n};\n\nfunction liveWorkers(): Set<string> {\n const g = globalThis as GlobalWithLiveWorkers;\n let set = g[LIVE_WORKERS_KEY];\n if (!set) {\n // Singleton on globalThis so it survives HMR / duplicate module instances,\n // mirroring the ObjectRegistry pattern.\n set = new Set<string>();\n g[LIVE_WORKERS_KEY] = set;\n }\n return set;\n}\n\n/** Mark a worker key as live in this process. */\nexport function registerLiveWorker(workerKey: string): void {\n liveWorkers().add(workerKey);\n}\n\n/** Remove a worker key from this process's live set. */\nexport function unregisterLiveWorker(workerKey: string): void {\n liveWorkers().delete(workerKey);\n}\n\n/** Whether a worker key is live in this process. */\nexport function isLiveWorker(workerKey: string): boolean {\n return liveWorkers().has(workerKey);\n}\n\n/** Snapshot of every worker key live in this process. */\nexport function liveWorkerKeys(): Set<string> {\n return new Set(liveWorkers());\n}\n\n/**\n * Whether a worker is alive: live in *this* process (synchronous truth, never\n * starved), or holding a fresh database lease in some process. `null`/unknown\n * worker keys are never alive.\n */\nexport function isWorkerAlive(\n workerKey: string | null | undefined,\n freshLeaseKeys: Set<string>,\n): boolean {\n if (!workerKey) return false;\n return isLiveWorker(workerKey) || freshLeaseKeys.has(workerKey);\n}\n\n/**\n * Build a per-incarnation-unique worker key.\n *\n * Recovery treats a worker key as the unit of liveness, so the key must be\n * unique per process incarnation: a runner that crashes and restarts under the\n * same configured `id` must get a *new* key, otherwise its orphaned `running`\n * jobs would look owned by the live restart and never be recovered. We append\n * a random token to the (optional) configured id, which also keeps the\n * human-facing runner id stable for logs/events.\n */\nexport function createWorkerKey(baseId: string): string {\n return `${baseId}~${createId().slice(0, 8)}`;\n}\n\n/**\n * The connection URL, honoring adapters that leave `db.url` empty and carry the\n * real URL on `db.config.url`. Used consistently for engine detection, the\n * in-memory check, and the URL handed to the off-loop thread so they never\n * disagree.\n */\nexport function resolveUrl(db: DatabaseInterface): string {\n const withConfig = db as DatabaseInterface & { config?: { url?: string } };\n return db.url || withConfig.config?.url || '';\n}\n\n/**\n * Tune a SQLite connection for the off-loop liveness topology.\n *\n * The runner's main connection and the off-loop ticker's connection both touch\n * the same file. Stock libsql/SQLite opens in rollback-journal mode with no busy\n * timeout, so the instant two connections contend it returns `SQLITE_BUSY` —\n * surfacing as a flaky \"Failed to execute raw query\" under CI load. WAL lets\n * readers run concurrently with the single writer, and `busy_timeout` makes a\n * contended writer wait for the lock instead of failing immediately. Both are\n * idempotent and file-level (WAL persists for every connection to the file).\n *\n * Best-effort: a PRAGMA failure must never break startup — the in-process live\n * set keeps same-process recovery correct regardless. Callers gate this on a\n * SQLite engine so it is never issued to Postgres.\n */\nexport async function tuneSqliteForConcurrency(\n db: DatabaseInterface,\n): Promise<void> {\n try {\n await db.query('PRAGMA busy_timeout = 5000');\n await db.query('PRAGMA journal_mode = WAL');\n } catch {\n // Best-effort connection tuning.\n }\n}\n\n/** Resolve the database engine for a connection. */\nexport function resolveEngine(db: DatabaseInterface): DatabaseEngine {\n const withConfig = db as DatabaseInterface & {\n config?: { type?: string };\n type?: string;\n };\n const type = withConfig.type || withConfig.config?.type;\n return detectEngine(resolveUrl(db), type);\n}\n\n/**\n * Whether a connection points at an in-memory SQLite database. In-memory\n * databases are single-process (nothing to recover cross-process) and a second\n * connection cannot see the same data, so the off-loop liveness thread is\n * skipped for them.\n */\nexport function isInMemory(db: DatabaseInterface): boolean {\n const url = resolveUrl(db).toLowerCase();\n return (\n url === ':memory:' ||\n url.includes('mode=memory') ||\n url.includes('file::memory:')\n );\n}\n\n/**\n * Whether the off-loop liveness thread can run against this connection.\n *\n * Requires a second independent connection to the same data: true for Postgres\n * and file-backed SQLite. In-memory SQLite cannot be reached from another\n * connection, and DuckDB is single-writer per file — both fall back to\n * main-loop lease renewal + the in-process live set.\n */\nexport function offLoopEligible(db: DatabaseInterface): boolean {\n const engine = resolveEngine(db);\n if (engine === 'postgres') return true;\n if (engine === 'sqlite') return !isInMemory(db);\n return false;\n}\n"],"mappings":";;;AAkCA,IAAM,mBAAmB;AAMzB,SAAS,cAA2B;CAClC,MAAM,IAAI;CACV,IAAI,MAAM,EAAE;CACZ,IAAI,CAAC,KAAK;EAGR,sBAAM,IAAI,IAAY;EACtB,EAAE,oBAAoB;CACxB;CACA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