@fungi.computer/watchdog 0.1.4 → 0.1.6
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 +82 -40
- package/dist/d1.js +1 -0
- package/dist/internal/async-sql.d.ts +5 -0
- package/dist/internal/async-store.js +48 -20
- package/package.json +1 -1
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
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
package/dist/d1.js
CHANGED
|
@@ -10,6 +10,7 @@ export function createD1Watchdog(options) {
|
|
|
10
10
|
.bind(...statement.values);
|
|
11
11
|
const runtime = createAsyncRuntime({
|
|
12
12
|
dialect: "sqlite",
|
|
13
|
+
shared: options.database,
|
|
13
14
|
clock: options.now === undefined ? "unixepoch('subsec')*1000" : undefined,
|
|
14
15
|
query: async (statement) => (await prepare(statement).all()).results,
|
|
15
16
|
}, options);
|
|
@@ -8,6 +8,11 @@ export type Statement = Readonly<{
|
|
|
8
8
|
export type SqlDatabase = Readonly<{
|
|
9
9
|
dialect: "sqlite" | "postgres";
|
|
10
10
|
clock?: string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* The native database object runtimes over the same database share. Its
|
|
13
|
+
* schema is verified once for all of them; absent, each store verifies its own.
|
|
14
|
+
*/
|
|
15
|
+
shared?: object | undefined;
|
|
11
16
|
query: (statement: Statement) => Promise<readonly SqlRow[]>;
|
|
12
17
|
}>;
|
|
13
18
|
export declare const columns = "sequence, job_id, queue_name, lane, priority, payload_json, not_before, attempt_count,\n recovery_max, recovery_window_ms, recovery_window_started_at, state, outcome, claim_token, recovery_count, cancellation_id, failure_reason";
|
|
@@ -15,34 +15,62 @@ export const attempt = (run) => Effect.tryPromise({
|
|
|
15
15
|
? error
|
|
16
16
|
: new WatchdogError("store_unavailable", error),
|
|
17
17
|
});
|
|
18
|
+
// One schema verification per native database, shared by every runtime opened
|
|
19
|
+
// on it and by their concurrent first queries. A failed verification is
|
|
20
|
+
// forgotten, so the next query retries it after a migration lands.
|
|
21
|
+
const verifiedSchemas = new WeakMap();
|
|
18
22
|
export function openAsyncStore(database, now) {
|
|
19
23
|
// The database checks wall time when the mutation executes, so a delayed
|
|
20
24
|
// renewal cannot resurrect a lease that expired while the request was in flight.
|
|
21
25
|
const at = (parameter) => database.clock === undefined
|
|
22
26
|
? `CAST($${String(parameter)} AS DOUBLE PRECISION)`
|
|
23
27
|
: `(CASE WHEN $${String(parameter)}>${database.clock} THEN $${String(parameter)} ELSE ${database.clock} END)`;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
// Concurrent claimers must not all queue behind the one job the first of them
|
|
29
|
+
// is taking: losing that race reports nothing ready while other jobs wait. A
|
|
30
|
+
// locked head is skipped, so each claimer takes the next job. SQLite and D1
|
|
31
|
+
// have one writer and no row locks.
|
|
32
|
+
const skipLocked = database.dialect === "postgres" ? " FOR UPDATE SKIP LOCKED" : "";
|
|
33
|
+
const verifySchema = async () => {
|
|
34
|
+
const current = await database.query({
|
|
35
|
+
text: database.dialect === "postgres"
|
|
36
|
+
? "SELECT 1 AS current FROM pg_constraint WHERE conrelid = 'watchdog_jobs'::regclass AND conname = 'watchdog_execution_state'"
|
|
37
|
+
: "SELECT 1 AS current FROM sqlite_schema WHERE name = 'watchdog_jobs' AND instr(sql, 'watchdog_execution_state') > 0",
|
|
38
|
+
values: [],
|
|
39
|
+
});
|
|
40
|
+
if (current.length !== 1)
|
|
41
|
+
throw new WatchdogError("store_invalid", new Error("Obsolete Watchdog execution schema"));
|
|
42
|
+
try {
|
|
43
|
+
await database.query({
|
|
44
|
+
text: `SELECT ${columns} FROM watchdog_jobs LIMIT 0`,
|
|
31
45
|
values: [],
|
|
32
46
|
});
|
|
33
|
-
if (current.length !== 1)
|
|
34
|
-
throw new WatchdogError("store_invalid", new Error("Obsolete Watchdog execution schema"));
|
|
35
|
-
try {
|
|
36
|
-
await database.query({
|
|
37
|
-
text: `SELECT ${columns} FROM watchdog_jobs LIMIT 0`,
|
|
38
|
-
values: [],
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
catch (error) {
|
|
42
|
-
throw new WatchdogError("store_invalid", error);
|
|
43
|
-
}
|
|
44
|
-
schemaChecked = true;
|
|
45
47
|
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
throw new WatchdogError("store_invalid", error);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
let ownSchema;
|
|
53
|
+
const ensureSchema = () => {
|
|
54
|
+
const known = database.shared === undefined
|
|
55
|
+
? ownSchema
|
|
56
|
+
: verifiedSchemas.get(database.shared);
|
|
57
|
+
if (known !== undefined)
|
|
58
|
+
return known;
|
|
59
|
+
const pending = verifySchema().catch((error) => {
|
|
60
|
+
if (database.shared === undefined)
|
|
61
|
+
ownSchema = undefined;
|
|
62
|
+
else
|
|
63
|
+
verifiedSchemas.delete(database.shared);
|
|
64
|
+
throw error;
|
|
65
|
+
});
|
|
66
|
+
if (database.shared === undefined)
|
|
67
|
+
ownSchema = pending;
|
|
68
|
+
else
|
|
69
|
+
verifiedSchemas.set(database.shared, pending);
|
|
70
|
+
return pending;
|
|
71
|
+
};
|
|
72
|
+
const query = async (text, values = []) => {
|
|
73
|
+
await ensureSchema();
|
|
46
74
|
return database.query({ text, values });
|
|
47
75
|
};
|
|
48
76
|
const row = async (id) => {
|
|
@@ -138,7 +166,7 @@ export function openAsyncStore(database, now) {
|
|
|
138
166
|
WHERE job_id=(SELECT job_id FROM watchdog_jobs WHERE state='queued'
|
|
139
167
|
AND (cancellation_id IS NOT NULL OR not_before<=${at(2)})
|
|
140
168
|
AND ${queuedHeadPredicate}
|
|
141
|
-
ORDER BY priority DESC,sequence LIMIT 1) AND state='queued' RETURNING ${columns}`, [token, now()]))[0];
|
|
169
|
+
ORDER BY priority DESC,sequence LIMIT 1${skipLocked}) AND state='queued' RETURNING ${columns}`, [token, now()]))[0];
|
|
142
170
|
if (raw === undefined)
|
|
143
171
|
return { status: "no_ready" };
|
|
144
172
|
const parsed = parseJobRow(raw);
|