@fungi.computer/watchdog 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,50 +1,25 @@
1
1
  # Watchdog (`@fungi.computer/watchdog`)
2
2
 
3
3
  Watchdog is a small durable job engine. You hand it jobs, it stores them in your
4
- SQLite database, and each `tick()` claims one ready job, runs your executor and
5
- records exactly one terminal outcome. If the process dies mid-job, the next tick
6
- asks your liveness probe what happened and recovers the work.
7
-
8
- ```sh
9
- npm install @fungi.computer/watchdog
4
+ SQLite database, and if the process dies mid-job it recovers the work.
5
+
6
+ ```mermaid
7
+ flowchart LR
8
+ Host[Your host] -->|enqueue| Watchdog
9
+ Watchdog --> Db[(Your SQLite)]
10
+ Tick[tick] -->|claims one ready job| Watchdog
11
+ Watchdog -->|runs| Exec[Your executor]
12
+ Exec -->|one terminal outcome| Watchdog
13
+ Watchdog -->|after a crash, asks| Probe[Your liveness probe]
10
14
  ```
11
15
 
12
- Then run the quick start below: one short file, in-memory `node:sqlite` on Node
13
- 24, no other setup.
14
-
15
- Watchdog never looks inside a job. The payload, queue name and lane are opaque
16
- values you choose. Your code decides what a job means and how to run it.
17
- Watchdog owns the lifecycle: queued, running, completing, settled. Claims, claim
18
- tokens and the SQL that moves rows between states stay private to the package.
19
-
20
- Use it when you need work to survive a restart, run once per claim, and settle
21
- with an honest outcome, without writing your own state machine. It runs on any
22
- synchronous SQLite owner, such as a Cloudflare Durable Object's storage or
23
- `node:sqlite`, and on shared D1 or PostgreSQL databases.
24
-
25
- ## Requirements and entrypoints
26
-
27
- Watchdog is ESM-only. The SQLite entrypoint runs anywhere you have a synchronous
28
- SQLite handle, such as Cloudflare Durable Object storage or `node:sqlite` in
29
- Node 24. Its runtime dependencies include Cairn, `effect`, `pg`, `@types/pg` and
30
- `@cloudflare/workers-types`, which npm installs for you.
31
-
32
- Entrypoints:
16
+ ## Quick start
33
17
 
34
- - `@fungi.computer/watchdog`: the Promise API, `Watchdog.make`, and the public
35
- job types and schemas.
36
- - `@fungi.computer/watchdog/effect`: the same runtime as Effect values, via
37
- `makeRuntime`.
38
- - `@fungi.computer/watchdog/node-sqlite`: `fromNodeSqlite(database)` for a
39
- caller-owned Node SQLite database. It returns `NodeSqliteOwner`; its
40
- `NodeSqliteCursor` provides `toArray()` and `one()`, which returns exactly one
41
- decoded row and throws for zero or multiple rows.
42
- - `@fungi.computer/watchdog/d1`: a runtime over a migrated Cloudflare D1
43
- database.
44
- - `@fungi.computer/watchdog/postgres`: a runtime over a migrated PostgreSQL
45
- database.
18
+ Install it:
46
19
 
47
- ## Quick start
20
+ ```sh
21
+ npm install @fungi.computer/watchdog
22
+ ```
48
23
 
49
24
  This runs one job through an in-memory `node:sqlite` database. The `owner`
50
25
  object is the whole host contract for the SQLite entrypoint: run a statement,
@@ -95,6 +70,73 @@ again and it returns `{ status: "duplicate" }`.
95
70
 
96
71
  In a Durable Object, `ctx.storage` is already the SQLite owner.
97
72
 
73
+ ## Common tasks
74
+
75
+ ### Run one job
76
+
77
+ The Quick start runs a job through in-memory `node:sqlite`.
78
+
79
+ ### Schedule work and track delivery
80
+
81
+ See
82
+ [Scheduled work and delivery attempts](#scheduled-work-and-delivery-attempts).
83
+
84
+ ### Use D1 or PostgreSQL
85
+
86
+ See [Shared D1 and PostgreSQL storage](#shared-d1-and-postgresql-storage).
87
+
88
+ ### Understand recovery
89
+
90
+ See [Core concepts](#core-concepts).
91
+
92
+ ## Reference
93
+
94
+ ### Overview
95
+
96
+ Watchdog is a small durable job engine. You hand it jobs, it stores them in your
97
+ SQLite database, and each `tick()` claims one ready job, runs your executor and
98
+ records exactly one terminal outcome. If the process dies mid-job, the next tick
99
+ asks your liveness probe what happened and recovers the work.
100
+
101
+ ```sh
102
+ npm install @fungi.computer/watchdog
103
+ ```
104
+
105
+ Then run the quick start below: one short file, in-memory `node:sqlite` on Node
106
+ 24, no other setup.
107
+
108
+ Watchdog never looks inside a job. The payload, queue name and lane are opaque
109
+ values you choose. Your code decides what a job means and how to run it.
110
+ Watchdog owns the lifecycle: queued, running, completing, settled. Claims, claim
111
+ tokens and the SQL that moves rows between states stay private to the package.
112
+
113
+ Use it when you need work to survive a restart, run once per claim, and settle
114
+ with an honest outcome, without writing your own state machine. It runs on any
115
+ synchronous SQLite owner, such as a Cloudflare Durable Object's storage or
116
+ `node:sqlite`, and on shared D1 or PostgreSQL databases.
117
+
118
+ ## Requirements and entrypoints
119
+
120
+ Watchdog is ESM-only. The SQLite entrypoint runs anywhere you have a synchronous
121
+ SQLite handle, such as Cloudflare Durable Object storage or `node:sqlite` in
122
+ Node 24. Its runtime dependencies include Cairn, `effect`, `pg`, `@types/pg` and
123
+ `@cloudflare/workers-types`, which npm installs for you.
124
+
125
+ Entrypoints:
126
+
127
+ - `@fungi.computer/watchdog`: the Promise API, `Watchdog.make`, and the public
128
+ job types and schemas.
129
+ - `@fungi.computer/watchdog/effect`: the same runtime as Effect values, via
130
+ `makeRuntime`.
131
+ - `@fungi.computer/watchdog/node-sqlite`: `fromNodeSqlite(database)` for a
132
+ caller-owned Node SQLite database. It returns `NodeSqliteOwner`; its
133
+ `NodeSqliteCursor` provides `toArray()` and `one()`, which returns exactly one
134
+ decoded row and throws for zero or multiple rows.
135
+ - `@fungi.computer/watchdog/d1`: a runtime over a migrated Cloudflare D1
136
+ database.
137
+ - `@fungi.computer/watchdog/postgres`: a runtime over a migrated PostgreSQL
138
+ database.
139
+
98
140
  ## Core concepts
99
141
 
100
142
  **Jobs.** A job has a `jobId`, a `queue`, a `lane`, an integer `priority`, an
@@ -21,6 +21,11 @@ export function openAsyncStore(database, now) {
21
21
  const at = (parameter) => database.clock === undefined
22
22
  ? `CAST($${String(parameter)} AS DOUBLE PRECISION)`
23
23
  : `(CASE WHEN $${String(parameter)}>${database.clock} THEN $${String(parameter)} ELSE ${database.clock} END)`;
24
+ // Concurrent claimers must not all queue behind the one job the first of them
25
+ // is taking: losing that race reports nothing ready while other jobs wait. A
26
+ // locked head is skipped, so each claimer takes the next job. SQLite and D1
27
+ // have one writer and no row locks.
28
+ const skipLocked = database.dialect === "postgres" ? " FOR UPDATE SKIP LOCKED" : "";
24
29
  let schemaChecked = false;
25
30
  const query = async (text, values = []) => {
26
31
  if (!schemaChecked) {
@@ -138,7 +143,7 @@ export function openAsyncStore(database, now) {
138
143
  WHERE job_id=(SELECT job_id FROM watchdog_jobs WHERE state='queued'
139
144
  AND (cancellation_id IS NOT NULL OR not_before<=${at(2)})
140
145
  AND ${queuedHeadPredicate}
141
- ORDER BY priority DESC,sequence LIMIT 1) AND state='queued' RETURNING ${columns}`, [token, now()]))[0];
146
+ ORDER BY priority DESC,sequence LIMIT 1${skipLocked}) AND state='queued' RETURNING ${columns}`, [token, now()]))[0];
142
147
  if (raw === undefined)
143
148
  return { status: "no_ready" };
144
149
  const parsed = parseJobRow(raw);
@@ -47,6 +47,11 @@ export function fromNodeSqlite(database) {
47
47
  },
48
48
  transactionSync: (operation) => {
49
49
  const name = `watchdog_owner_${String(transaction++)}`;
50
+ // The outermost savepoint opens the real transaction, so its RELEASE is
51
+ // the commit, and SQLite refuses a commit as busy while another
52
+ // connection reads. A refused commit leaves the transaction open.
53
+ const inTransaction = () => database.isTransaction;
54
+ const outermost = !inTransaction();
50
55
  database.exec(`SAVEPOINT ${name}`);
51
56
  try {
52
57
  const result = operation();
@@ -54,8 +59,25 @@ export function fromNodeSqlite(database) {
54
59
  return result;
55
60
  }
56
61
  catch (cause) {
57
- database.exec(`ROLLBACK TO ${name}`);
58
- database.exec(`RELEASE ${name}`);
62
+ if (!outermost) {
63
+ // Inside the caller's transaction a RELEASE never commits.
64
+ database.exec(`ROLLBACK TO ${name}`);
65
+ database.exec(`RELEASE ${name}`);
66
+ throw cause;
67
+ }
68
+ // A plain ROLLBACK needs no exclusive lock, so it succeeds exactly
69
+ // when the commit could not: the connection never stays in the
70
+ // transaction, holding its lock against every other connection.
71
+ // Some failures (OR ROLLBACK, disk full) end the transaction in
72
+ // SQLite itself; then there is nothing to roll back and the caller
73
+ // sees the original error.
74
+ try {
75
+ if (inTransaction())
76
+ database.exec("ROLLBACK");
77
+ }
78
+ catch (rollbackCause) {
79
+ throw new AggregateError([cause, rollbackCause], "SQLite transaction failed and could not be rolled back", { cause: rollbackCause });
80
+ }
59
81
  throw cause;
60
82
  }
61
83
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/watchdog",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Payload-blind durable work scheduling and settlement core",
6
6
  "type": "module",