@statewalker/ai-tasks 0.0.0-stage → 0.1.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/queue.js ADDED
@@ -0,0 +1,591 @@
1
+ import { INBOX_PREFIX, isInbox, isPattern, isSubject, subjectMatches } from "./subjects.js";
2
+ // src/queue.ts
3
+ const DEFAULTS = {
4
+ maxPayloadBytes: 65536,
5
+ defaultExpiryMs: 6048e5,
6
+ maxExpiryMs: 2592e6,
7
+ deadLetterMs: 12096e5,
8
+ maxWaiting: 1e4,
9
+ defaultLeaseMs: 3e5,
10
+ defaultMaxAttempts: 3
11
+ };
12
+ const MIN_LEASE_MS = 1e3;
13
+ const MAX_LEASE_MS = 432e5;
14
+ const MAX_ATTEMPTS = 100;
15
+ const MAX_READ = 100;
16
+ const DEFAULT_READ = 10;
17
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
18
+ const DESTINATION = /^[a-z]+:[^\s]{1,256}$/;
19
+ const CORRELATION = /^[^\s]{1,128}$/;
20
+ const MAX_SENDER_FILTER = 256;
21
+ /** An error whose message starts with its code, as the harness's errors do. */
22
+ function taskError(code, message) {
23
+ const e = /* @__PURE__ */ new Error(`${code}: ${message}`);
24
+ e.code = code;
25
+ return e;
26
+ }
27
+ const utf8 = new TextEncoder();
28
+ /**
29
+ * Whether `text` matches `pattern`, where `*` is any run of characters: a linear two-pointer match
30
+ * (back to the last star on a mismatch), never a regular expression, so no filter can make a
31
+ * publish backtrack for ever.
32
+ */
33
+ function globMatches(pattern, text) {
34
+ let p = 0;
35
+ let t = 0;
36
+ let star = -1;
37
+ let mark = 0;
38
+ while (t < text.length) if (p < pattern.length && pattern[p] !== "*" && pattern[p] === text[t]) {
39
+ p++;
40
+ t++;
41
+ } else if (p < pattern.length && pattern[p] === "*") {
42
+ star = p++;
43
+ mark = t;
44
+ } else if (star >= 0) {
45
+ p = star + 1;
46
+ t = ++mark;
47
+ } else return false;
48
+ while (p < pattern.length && pattern[p] === "*") p++;
49
+ return p === pattern.length;
50
+ }
51
+ function taskOf(r) {
52
+ return {
53
+ id: r.id,
54
+ subject: r.subject,
55
+ ...r.destination ? { destination: r.destination } : {},
56
+ sender: r.sender,
57
+ payload: JSON.parse(r.payload),
58
+ created: Number(r.created),
59
+ expires_at: Number(r.expires_at),
60
+ ...r.reply_to ? { reply_to: r.reply_to } : {},
61
+ ...r.correlation_id ? { correlation_id: r.correlation_id } : {}
62
+ };
63
+ }
64
+ function subscriptionOf(r, counts) {
65
+ return {
66
+ name: r.name,
67
+ filter: {
68
+ subject: r.subject,
69
+ ...r.destination ? { destination: r.destination } : {},
70
+ ...r.sender ? { sender: r.sender } : {}
71
+ },
72
+ lease_ms: Number(r.lease_ms),
73
+ max_attempts: Number(r.max_attempts),
74
+ owner: r.owner,
75
+ created: Number(r.created),
76
+ ...r.inbox ? { inbox: true } : {},
77
+ ...counts ? { counts } : {}
78
+ };
79
+ }
80
+ function matches(sub, task) {
81
+ if (!subjectMatches(sub.subject, task.subject)) return false;
82
+ if (sub.destination && sub.destination !== task.destination) return false;
83
+ if (sub.sender && !globMatches(sub.sender, task.sender)) return false;
84
+ return true;
85
+ }
86
+ var TaskQueue = class {
87
+ #sql;
88
+ #now;
89
+ #newId;
90
+ #o;
91
+ constructor(sql, options = {}) {
92
+ this.#sql = sql;
93
+ this.#now = options.now ?? Date.now;
94
+ this.#newId = options.newId ?? (() => crypto.randomUUID());
95
+ this.#o = {
96
+ maxPayloadBytes: options.maxPayloadBytes ?? DEFAULTS.maxPayloadBytes,
97
+ defaultExpiryMs: options.defaultExpiryMs ?? DEFAULTS.defaultExpiryMs,
98
+ maxExpiryMs: options.maxExpiryMs ?? DEFAULTS.maxExpiryMs,
99
+ deadLetterMs: options.deadLetterMs ?? DEFAULTS.deadLetterMs,
100
+ maxWaiting: options.maxWaiting ?? DEFAULTS.maxWaiting,
101
+ defaultLeaseMs: options.defaultLeaseMs ?? DEFAULTS.defaultLeaseMs,
102
+ defaultMaxAttempts: options.defaultMaxAttempts ?? DEFAULTS.defaultMaxAttempts
103
+ };
104
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_items (seq INTEGER PRIMARY KEY AUTOINCREMENT,
105
+ project TEXT NOT NULL, id TEXT NOT NULL, subject TEXT NOT NULL, destination TEXT,
106
+ sender TEXT NOT NULL, payload TEXT NOT NULL, bytes INTEGER NOT NULL, created INTEGER NOT NULL,
107
+ expires_at INTEGER NOT NULL, reply_to TEXT, correlation_id TEXT,
108
+ matched INTEGER NOT NULL DEFAULT 0, UNIQUE (project, id))`);
109
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_subscriptions (project TEXT NOT NULL,
110
+ name TEXT NOT NULL, subject TEXT NOT NULL, destination TEXT, sender TEXT,
111
+ lease_ms INTEGER NOT NULL, max_attempts INTEGER NOT NULL, owner TEXT NOT NULL,
112
+ created INTEGER NOT NULL, inbox INTEGER NOT NULL DEFAULT 0, expired INTEGER NOT NULL DEFAULT 0,
113
+ PRIMARY KEY (project, name))`);
114
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_deliveries (project TEXT NOT NULL,
115
+ subscription TEXT NOT NULL, task INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
116
+ lease TEXT, lease_expires INTEGER, holder TEXT, PRIMARY KEY (project, subscription, task))`);
117
+ sql.exec("CREATE INDEX IF NOT EXISTS task_deliveries_lease ON task_deliveries (lease)");
118
+ sql.exec("CREATE INDEX IF NOT EXISTS task_deliveries_task ON task_deliveries (task)");
119
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_dead (seq INTEGER PRIMARY KEY AUTOINCREMENT,
120
+ project TEXT NOT NULL, subscription TEXT NOT NULL, task TEXT NOT NULL, bytes INTEGER NOT NULL,
121
+ attempts INTEGER NOT NULL, reason TEXT NOT NULL, dead_at INTEGER NOT NULL,
122
+ expires INTEGER NOT NULL)`);
123
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_takers (project TEXT NOT NULL, task TEXT NOT NULL,
124
+ holder TEXT NOT NULL, reply_to TEXT NOT NULL, correlation_id TEXT, until INTEGER NOT NULL,
125
+ replied INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (project, task, holder))`);
126
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_jobs (id TEXT PRIMARY KEY, project TEXT NOT NULL,
127
+ task TEXT NOT NULL, subscription TEXT NOT NULL, holder TEXT NOT NULL, sender TEXT NOT NULL,
128
+ until INTEGER NOT NULL)`);
129
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_job_entries (seq INTEGER PRIMARY KEY AUTOINCREMENT,
130
+ job TEXT NOT NULL, at INTEGER NOT NULL, progress TEXT NOT NULL)`);
131
+ sql.exec(`CREATE TABLE IF NOT EXISTS task_changes (project TEXT PRIMARY KEY,
132
+ seq INTEGER NOT NULL)`);
133
+ }
134
+ #rows(query, ...bindings) {
135
+ return this.#sql.exec(query, ...bindings).toArray();
136
+ }
137
+ /** The project's change counter: it grows whenever a subscription may have tasks to read. */
138
+ changeSeq(project) {
139
+ const row = this.#rows("SELECT seq FROM task_changes WHERE project = ?", project)[0];
140
+ return row ? Number(row.seq) : 0;
141
+ }
142
+ #waiters = /* @__PURE__ */ new Map();
143
+ /**
144
+ * Waits up to `waitMs` for the project's change counter to pass `after`: the current counter at
145
+ * once when it already has (or when `after` is undefined). In memory: one queue instance's
146
+ * waiters (a Durable Object's).
147
+ */
148
+ async waitChange(project, after, waitMs) {
149
+ const seq = this.changeSeq(project);
150
+ if (after === void 0 || seq > after || !(waitMs > 0)) return seq;
151
+ await new Promise((resolve) => {
152
+ const set = this.#waiters.get(project) ?? /* @__PURE__ */ new Set();
153
+ this.#waiters.set(project, set);
154
+ const done = () => {
155
+ clearTimeout(timer);
156
+ set.delete(done);
157
+ if (!set.size) this.#waiters.delete(project);
158
+ resolve();
159
+ };
160
+ const timer = setTimeout(done, waitMs);
161
+ set.add(done);
162
+ });
163
+ return this.changeSeq(project);
164
+ }
165
+ #changed(project) {
166
+ queueMicrotask(() => {
167
+ for (const wake of [...this.#waiters.get(project) ?? []]) wake();
168
+ });
169
+ this.#sql.exec(`INSERT INTO task_changes (project, seq) VALUES (?, 1)
170
+ ON CONFLICT (project) DO UPDATE SET seq = seq + 1`, project);
171
+ }
172
+ /** Publishes a task from `sender`; an inbox's subject only through `reply`. */
173
+ publish(project, input, sender) {
174
+ const subject = (input ?? {}).subject;
175
+ if (!isSubject(subject)) throw taskError("EINVAL", "a task's subject is `.`-separated tokens, without wildcards");
176
+ if (isInbox(subject)) throw taskError("EACCES", "an inbox takes only replies");
177
+ if (input.reply_to !== void 0) {
178
+ const inbox = typeof input.reply_to === "string" ? this.#sub(project, input.reply_to) : void 0;
179
+ if (!inbox?.inbox || inbox.owner !== sender) throw taskError("EACCES", "reply_to is an inbox of the sender's");
180
+ }
181
+ return this.#insert(project, input, sender);
182
+ }
183
+ #insert(project, input, sender) {
184
+ this.sweep(project);
185
+ const now = this.#now();
186
+ const { destination, correlation_id } = input;
187
+ if (destination !== void 0 && (typeof destination !== "string" || !DESTINATION.test(destination))) throw taskError("EINVAL", "a destination is `<kind>:<name>`");
188
+ if (correlation_id !== void 0 && (typeof correlation_id !== "string" || !CORRELATION.test(correlation_id))) throw taskError("EINVAL", "a correlation id is up to 128 characters, without spaces");
189
+ const payload = JSON.stringify(input.payload ?? null);
190
+ const bytes = utf8.encode(payload).length;
191
+ if (bytes > this.#o.maxPayloadBytes) throw taskError("EINVAL", `a task's payload is at most ${this.#o.maxPayloadBytes} bytes`);
192
+ let expires = now + this.#o.defaultExpiryMs;
193
+ if (input.expires_in_ms !== void 0) {
194
+ if (!Number.isFinite(input.expires_in_ms) || input.expires_in_ms <= 0) throw taskError("EINVAL", "expires_in_ms is a positive number");
195
+ expires = now + Number(input.expires_in_ms);
196
+ } else if (input.expires_at !== void 0) {
197
+ if (!Number.isFinite(input.expires_at) || input.expires_at <= now) throw taskError("EINVAL", "expires_at is a time in the future (ms since the epoch)");
198
+ expires = Number(input.expires_at);
199
+ }
200
+ expires = Math.min(expires, now + this.#o.maxExpiryMs);
201
+ if (this.waitingCount(project) >= this.#o.maxWaiting) throw taskError("ELIMIT", `the project's queue holds at most ${this.#o.maxWaiting} waiting tasks; retry after 60 s`);
202
+ const id = this.#newId();
203
+ this.#sql.exec(`INSERT INTO task_items (project, id, subject, destination, sender, payload, bytes, created,
204
+ expires_at, reply_to, correlation_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, project, id, input.subject, destination ?? null, sender, payload, bytes, now, expires, input.reply_to ?? null, correlation_id ?? null);
205
+ const row = this.#task(project, id);
206
+ for (const sub of this.#subs(project)) if (matches(sub, row)) this.#deliver(sub, row);
207
+ this.#changed(project);
208
+ return taskOf(row);
209
+ }
210
+ #deliver(sub, task) {
211
+ this.#sql.exec("INSERT OR IGNORE INTO task_deliveries (project, subscription, task) VALUES (?, ?, ?)", sub.project, sub.name, task.seq);
212
+ this.#sql.exec("UPDATE task_items SET matched = 1 WHERE seq = ?", task.seq);
213
+ }
214
+ /** Tasks the project holds now (those waiting for an inbox included). */
215
+ waitingCount(project) {
216
+ return Number(this.#rows("SELECT count(*) AS n FROM task_items WHERE project = ?", project)[0]?.n ?? 0);
217
+ }
218
+ /** The bytes the project's queue holds: waiting tasks' and dead letters' payloads. */
219
+ bytes(project) {
220
+ const t = this.#rows("SELECT coalesce(sum(bytes), 0) AS n FROM task_items WHERE project = ?", project)[0];
221
+ const d = this.#rows("SELECT coalesce(sum(bytes), 0) AS n FROM task_dead WHERE project = ?", project)[0];
222
+ return Number(t?.n ?? 0) + Number(d?.n ?? 0);
223
+ }
224
+ /** The project's waiting tasks, oldest first. */
225
+ listTasks(project, options = {}) {
226
+ this.sweep(project);
227
+ return this.#rows("SELECT * FROM task_items WHERE project = ? ORDER BY seq LIMIT ?", project, limitOf(options.limit, 1e3)).map(taskOf);
228
+ }
229
+ #task(project, id) {
230
+ return this.#rows("SELECT * FROM task_items WHERE project = ? AND id = ?", project, id)[0];
231
+ }
232
+ #subs(project) {
233
+ return this.#rows("SELECT * FROM task_subscriptions WHERE project = ?", project);
234
+ }
235
+ #sub(project, name) {
236
+ return this.#rows("SELECT * FROM task_subscriptions WHERE project = ? AND name = ?", project, name)[0];
237
+ }
238
+ /** Creates a subscription owned by `owner`; it receives the matching tasks still waiting. */
239
+ subscribe(project, input, owner) {
240
+ const { name, filter, lease_ms, max_attempts } = input ?? {};
241
+ if (typeof name !== "string" || !NAME.test(name)) throw taskError("EINVAL", "a subscription's name is letters, digits, `_`, `.` and `-`");
242
+ if (!filter || typeof filter !== "object" || !isPattern(filter.subject)) throw taskError("EINVAL", "a subscription filters on a subject (`*` and a last `>` allowed)");
243
+ if (filter.subject.startsWith("_inbox.") || filter.subject.startsWith("_inbox")) throw taskError("EINVAL", "inboxes are read through their own subscription");
244
+ if (filter.destination !== void 0 && (typeof filter.destination !== "string" || !DESTINATION.test(filter.destination))) throw taskError("EINVAL", "a destination is `<kind>:<name>`");
245
+ if (filter.sender !== void 0 && (typeof filter.sender !== "string" || !filter.sender || filter.sender.length > MAX_SENDER_FILTER)) throw taskError("EINVAL", "a sender filter is a principal, `*` matching any characters");
246
+ const lease = leaseOf(lease_ms, this.#o.defaultLeaseMs);
247
+ const attempts = max_attempts === void 0 ? this.#o.defaultMaxAttempts : Number(max_attempts);
248
+ if (!Number.isInteger(attempts) || attempts < 1 || attempts > MAX_ATTEMPTS) throw taskError("EINVAL", `max_attempts is a whole number from 1 to ${MAX_ATTEMPTS}`);
249
+ if (this.#sub(project, name)) throw taskError("EEXIST", `the subscription '${name}' exists`);
250
+ return this.#createSub(project, {
251
+ name,
252
+ subject: filter.subject,
253
+ destination: filter.destination ?? null,
254
+ sender: filter.sender ?? null,
255
+ lease_ms: lease,
256
+ max_attempts: attempts,
257
+ owner,
258
+ inbox: 0
259
+ });
260
+ }
261
+ /** A new reply inbox of `owner`'s: a subscription named by its subject, read only by it. */
262
+ createInbox(project, owner) {
263
+ const subject = `${INBOX_PREFIX}${this.#newId().replace(/[^A-Za-z0-9_-]/g, "")}`;
264
+ return this.#createSub(project, {
265
+ name: subject,
266
+ subject,
267
+ destination: null,
268
+ sender: null,
269
+ lease_ms: this.#o.defaultLeaseMs,
270
+ max_attempts: this.#o.defaultMaxAttempts,
271
+ owner,
272
+ inbox: 1
273
+ });
274
+ }
275
+ #createSub(project, s) {
276
+ this.sweep(project);
277
+ this.#sql.exec(`INSERT INTO task_subscriptions (project, name, subject, destination, sender, lease_ms,
278
+ max_attempts, owner, created, inbox) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, project, s.name, s.subject, s.destination, s.sender, s.lease_ms, s.max_attempts, s.owner, this.#now(), s.inbox);
279
+ const sub = this.#sub(project, s.name);
280
+ if (!s.inbox) {
281
+ let found = false;
282
+ for (const task of this.#rows("SELECT * FROM task_items WHERE project = ? ORDER BY seq", project)) if (matches(sub, task)) {
283
+ this.#deliver(sub, task);
284
+ found = true;
285
+ }
286
+ if (found) this.#changed(project);
287
+ }
288
+ return subscriptionOf(sub, this.#counts(sub));
289
+ }
290
+ #counts(sub) {
291
+ const d = this.#rows(`SELECT count(*) AS waiting, coalesce(sum(lease IS NOT NULL), 0) AS leased
292
+ FROM task_deliveries WHERE project = ? AND subscription = ?`, sub.project, sub.name)[0];
293
+ const dead = this.#rows("SELECT count(*) AS n FROM task_dead WHERE project = ? AND subscription = ?", sub.project, sub.name)[0];
294
+ return {
295
+ waiting: Number(d?.waiting ?? 0),
296
+ leased: Number(d?.leased ?? 0),
297
+ dead_letters: Number(dead?.n ?? 0),
298
+ expired: Number(sub.expired)
299
+ };
300
+ }
301
+ /** The project's subscriptions (inboxes left out unless `inboxes`), with their counts. */
302
+ listSubscriptions(project, options = {}) {
303
+ this.sweep(project);
304
+ return this.#subs(project).filter((s) => options.inboxes || !s.inbox).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((s) => subscriptionOf(s, this.#counts(s)));
305
+ }
306
+ /** One subscription with its counts; ENOENT when there is none. */
307
+ getSubscription(project, name) {
308
+ this.sweep(project);
309
+ const sub = this.#sub(project, name);
310
+ if (!sub) throw taskError("ENOENT", `no subscription '${name}'`);
311
+ return subscriptionOf(sub, this.#counts(sub));
312
+ }
313
+ /** Deletes a subscription: what waited for it is done for it, its dead letters dropped. */
314
+ unsubscribe(project, name) {
315
+ if (!this.#sub(project, name)) throw taskError("ENOENT", `no subscription '${name}'`);
316
+ this.#sql.exec("DELETE FROM task_deliveries WHERE project = ? AND subscription = ?", project, name);
317
+ this.#sql.exec("DELETE FROM task_dead WHERE project = ? AND subscription = ?", project, name);
318
+ this.#sql.exec("DELETE FROM task_subscriptions WHERE project = ? AND name = ?", project, name);
319
+ this.#collect(project);
320
+ }
321
+ #readable(project, name, reader) {
322
+ this.sweep(project);
323
+ const sub = this.#sub(project, name);
324
+ if (!sub || sub.inbox && sub.owner !== reader.id) throw taskError("ENOENT", `no subscription '${name}'`);
325
+ return sub;
326
+ }
327
+ /** The deliveries the reader may take now, oldest first, up to `limit`. */
328
+ #candidates(sub, reader, limit) {
329
+ const out = [];
330
+ const may = /* @__PURE__ */ new Map();
331
+ const rows = this.#rows(`SELECT t.*, d.attempts AS attempts FROM task_deliveries d JOIN task_items t ON t.seq = d.task
332
+ WHERE d.project = ? AND d.subscription = ? AND d.lease IS NULL ORDER BY t.seq`, sub.project, sub.name);
333
+ for (const row of rows) {
334
+ if (out.length >= limit) break;
335
+ if (row.destination && !reader.destinations.includes(row.destination)) continue;
336
+ if (reader.may) {
337
+ let ok = may.get(row.subject);
338
+ if (ok === void 0) {
339
+ ok = reader.may(row.subject);
340
+ may.set(row.subject, ok);
341
+ }
342
+ if (!ok) continue;
343
+ }
344
+ out.push({
345
+ delivery: { attempts: Number(row.attempts) },
346
+ task: row
347
+ });
348
+ }
349
+ return out;
350
+ }
351
+ /** Tasks waiting for the subscription that the reader may take, left in place. */
352
+ peek(project, name, reader, options = {}) {
353
+ const sub = this.#readable(project, name, reader);
354
+ return this.#candidates(sub, reader, limitOf(options.limit)).map((c) => taskOf(c.task));
355
+ }
356
+ /** Takes tasks: each is done for the subscription as it is read. */
357
+ take(project, name, reader, options = {}) {
358
+ const sub = this.#readable(project, name, reader);
359
+ const found = this.#candidates(sub, reader, limitOf(options.limit));
360
+ for (const { task } of found) {
361
+ this.#sql.exec("DELETE FROM task_deliveries WHERE project = ? AND subscription = ? AND task = ?", project, name, task.seq);
362
+ this.#tookFor(task, reader.id);
363
+ }
364
+ const tasks = found.map((c) => taskOf(c.task));
365
+ if (found.length) this.#collect(project);
366
+ return tasks;
367
+ }
368
+ /** Remembers who took a task that asks for a reply: only they may send it. */
369
+ #tookFor(task, holder) {
370
+ if (!task.reply_to) return;
371
+ this.#sql.exec(`INSERT OR IGNORE INTO task_takers (project, task, holder, reply_to, correlation_id, until)
372
+ VALUES (?, ?, ?, ?, ?, ?)`, task.project, task.id, holder, task.reply_to, task.correlation_id, Number(task.expires_at));
373
+ }
374
+ /** Leases tasks to the reader: each is its until acked, released, or the lease runs out. */
375
+ claim(project, name, reader, options = {}) {
376
+ const sub = this.#readable(project, name, reader);
377
+ const leaseMs = leaseOf(options.lease_ms, Number(sub.lease_ms));
378
+ const now = this.#now();
379
+ const leases = [];
380
+ for (const { delivery, task } of this.#candidates(sub, reader, limitOf(options.limit))) {
381
+ const id = this.#newId();
382
+ const attempt = delivery.attempts + 1;
383
+ this.#sql.exec(`UPDATE task_deliveries SET attempts = ?, lease = ?, lease_expires = ?, holder = ?
384
+ WHERE project = ? AND subscription = ? AND task = ?`, attempt, id, now + leaseMs, reader.id, project, name, task.seq);
385
+ this.#tookFor(task, reader.id);
386
+ this.#sql.exec(`INSERT INTO task_jobs (id, project, task, subscription, holder, sender, until)
387
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, id, project, task.id, name, reader.id, task.sender, Math.max(Number(task.expires_at), now + this.#o.deadLetterMs));
388
+ leases.push({
389
+ id,
390
+ subscription: name,
391
+ task: taskOf(task),
392
+ attempt,
393
+ max_attempts: Number(sub.max_attempts),
394
+ expires: now + leaseMs
395
+ });
396
+ }
397
+ return leases;
398
+ }
399
+ /** The live lease `id` held by `holder`, its project swept first; ENOENT otherwise. */
400
+ #lease(id, holder) {
401
+ const find = () => this.#rows("SELECT * FROM task_deliveries WHERE lease = ?", String(id))[0];
402
+ const first = find();
403
+ if (first) this.sweep(first.project);
404
+ const row = first && find();
405
+ if (!row || row.holder !== holder) throw taskError("ENOENT", "no such lease (it may have run out)");
406
+ return {
407
+ row,
408
+ sub: this.#sub(row.project, row.subscription),
409
+ task: this.#rows("SELECT * FROM task_items WHERE seq = ?", row.task)[0]
410
+ };
411
+ }
412
+ /** Done: the task is done for the lease's subscription. */
413
+ ack(id, holder) {
414
+ const { row } = this.#lease(id, holder);
415
+ this.#sql.exec("DELETE FROM task_deliveries WHERE lease = ?", String(id));
416
+ this.#collect(row.project);
417
+ }
418
+ /** Not done: the task waits again, or goes to the dead letters once its attempts are used up. */
419
+ release(id, holder, options = {}) {
420
+ const { row, sub, task } = this.#lease(id, holder);
421
+ const reason = typeof options.reason === "string" && options.reason ? options.reason.slice(0, 1e3) : "released";
422
+ const dead = Number(row.attempts) >= Number(sub.max_attempts);
423
+ if (dead) this.#bury(sub, task, Number(row.attempts), reason);
424
+ else this.#sql.exec("UPDATE task_deliveries SET lease = NULL, lease_expires = NULL, holder = NULL WHERE lease = ?", String(id));
425
+ this.#changed(row.project);
426
+ return { dead };
427
+ }
428
+ /** Extends a live lease (by the subscription's lease, or `lease_ms`), logging progress. */
429
+ renew(id, holder, options = {}) {
430
+ const { row, sub, task } = this.#lease(id, holder);
431
+ const now = this.#now();
432
+ const expires = now + leaseOf(options.lease_ms, Number(sub.lease_ms));
433
+ this.#sql.exec("UPDATE task_deliveries SET lease_expires = ? WHERE lease = ?", expires, String(id));
434
+ if (options.progress !== void 0) {
435
+ const progress = JSON.stringify(options.progress);
436
+ if (utf8.encode(progress).length > this.#o.maxPayloadBytes) throw taskError("EINVAL", `a progress entry is at most ${this.#o.maxPayloadBytes} bytes`);
437
+ this.#sql.exec("INSERT INTO task_job_entries (job, at, progress) VALUES (?, ?, ?)", String(id), now, progress);
438
+ }
439
+ return {
440
+ id: String(id),
441
+ subscription: sub.name,
442
+ task: taskOf(task),
443
+ attempt: Number(row.attempts),
444
+ max_attempts: Number(sub.max_attempts),
445
+ expires
446
+ };
447
+ }
448
+ /** Moves a task's delivery to the subscription's dead letters. */
449
+ #bury(sub, task, attempts, reason) {
450
+ const now = this.#now();
451
+ this.#sql.exec(`INSERT INTO task_dead (project, subscription, task, bytes, attempts, reason, dead_at, expires)
452
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, sub.project, sub.name, JSON.stringify(taskOf(task)), Number(task.bytes), attempts, reason, now, now + this.#o.deadLetterMs);
453
+ this.#sql.exec("DELETE FROM task_deliveries WHERE project = ? AND subscription = ? AND task = ?", sub.project, sub.name, task.seq);
454
+ this.#collect(sub.project);
455
+ }
456
+ /** A subscription's dead letters, oldest first. */
457
+ deadLetters(project, name) {
458
+ this.sweep(project);
459
+ if (!this.#sub(project, name)) throw taskError("ENOENT", `no subscription '${name}'`);
460
+ return this.#rows("SELECT * FROM task_dead WHERE project = ? AND subscription = ? ORDER BY seq LIMIT 1000", project, name).map((r) => ({
461
+ task: JSON.parse(r.task),
462
+ subscription: r.subscription,
463
+ attempts: Number(r.attempts),
464
+ reason: r.reason,
465
+ dead_at: Number(r.dead_at),
466
+ expires: Number(r.expires)
467
+ }));
468
+ }
469
+ /**
470
+ * Replies to a task `holder` took or claimed, once: a task in its `reply_to` inbox with its
471
+ * correlation id, sent by `holder`.
472
+ */
473
+ reply(project, taskId, holder, input) {
474
+ this.sweep(project);
475
+ const taker = this.#rows("SELECT * FROM task_takers WHERE project = ? AND task = ? AND holder = ?", project, String(taskId), holder)[0];
476
+ if (!taker) throw taskError("EACCES", "only a consumer that took or claimed a task replies to it");
477
+ if (taker.replied) throw taskError("EBUSY", "this task has its reply");
478
+ if (!this.#sub(project, taker.reply_to)) throw taskError("ENOENT", "the reply inbox is gone");
479
+ const task = this.#insert(project, {
480
+ subject: taker.reply_to,
481
+ payload: input?.payload ?? null,
482
+ ...taker.correlation_id ? { correlation_id: taker.correlation_id } : {}
483
+ }, holder);
484
+ this.#sql.exec("UPDATE task_takers SET replied = 1 WHERE project = ? AND task = ? AND holder = ?", project, String(taskId), holder);
485
+ return task;
486
+ }
487
+ /** A job log, for its lease's holder and its task's sender; ENOENT for anyone else. */
488
+ job(project, id, reader) {
489
+ this.sweep(project);
490
+ const job = this.#rows("SELECT * FROM task_jobs WHERE project = ? AND id = ?", project, String(id))[0];
491
+ if (!job || job.holder !== reader && job.sender !== reader) throw taskError("ENOENT", "no such job");
492
+ return {
493
+ id: job.id,
494
+ task: job.task,
495
+ subscription: job.subscription,
496
+ entries: this.#rows("SELECT at, progress FROM task_job_entries WHERE job = ? ORDER BY seq", job.id).map((e) => ({
497
+ at: Number(e.at),
498
+ progress: JSON.parse(e.progress)
499
+ }))
500
+ };
501
+ }
502
+ /** The project of a lease (live or not yet swept); undefined for an unknown one. */
503
+ leaseProject(id) {
504
+ return this.#rows("SELECT project FROM task_deliveries WHERE lease = ?", String(id))[0]?.project;
505
+ }
506
+ /** An inbox of `owner`'s in the project, if it has one (the oldest). */
507
+ inboxOf(project, owner) {
508
+ const row = this.#rows("SELECT * FROM task_subscriptions WHERE project = ? AND owner = ? AND inbox = 1 ORDER BY created LIMIT 1", project, owner)[0];
509
+ return row ? subscriptionOf(row) : void 0;
510
+ }
511
+ /** Where `holder`'s reply to a task would go; EACCES unless it took or claimed the task. */
512
+ replyTo(project, taskId, holder) {
513
+ this.sweep(project);
514
+ const row = this.#rows("SELECT reply_to FROM task_takers WHERE project = ? AND task = ? AND holder = ?", project, String(taskId), holder)[0];
515
+ if (!row) throw taskError("EACCES", "only a consumer that took or claimed a task replies to it");
516
+ return row.reply_to;
517
+ }
518
+ /** Forgets a project's queue: its tasks, subscriptions, dead letters and job logs. */
519
+ dropProject(project) {
520
+ for (const table of [
521
+ "task_items",
522
+ "task_subscriptions",
523
+ "task_deliveries",
524
+ "task_dead",
525
+ "task_takers",
526
+ "task_changes"
527
+ ]) this.#sql.exec(`DELETE FROM ${table} WHERE project = ?`, project);
528
+ this.#sql.exec("DELETE FROM task_job_entries WHERE job IN (SELECT id FROM task_jobs WHERE project = ?)", project);
529
+ this.#sql.exec("DELETE FROM task_jobs WHERE project = ?", project);
530
+ }
531
+ /** Removes tasks that had a matching subscription and that none waits for any more. */
532
+ #collect(project) {
533
+ this.#sql.exec(`DELETE FROM task_items WHERE project = ? AND matched = 1
534
+ AND NOT EXISTS (SELECT 1 FROM task_deliveries d WHERE d.task = task_items.seq)`, project);
535
+ }
536
+ /** Expires what is due in a project: tasks, leases, dead letters, job logs. */
537
+ sweep(project) {
538
+ const now = this.#now();
539
+ let changed = false;
540
+ const expired = this.#rows("SELECT * FROM task_items WHERE project = ? AND expires_at <= ?", project, now);
541
+ for (const task of expired) {
542
+ for (const d of this.#rows("SELECT subscription FROM task_deliveries WHERE task = ?", task.seq)) this.#sql.exec("UPDATE task_subscriptions SET expired = expired + 1 WHERE project = ? AND name = ?", project, d.subscription);
543
+ this.#sql.exec("DELETE FROM task_deliveries WHERE task = ?", task.seq);
544
+ this.#sql.exec("DELETE FROM task_items WHERE seq = ?", task.seq);
545
+ }
546
+ for (const d of this.#rows("SELECT * FROM task_deliveries WHERE project = ? AND lease IS NOT NULL AND lease_expires <= ?", project, now)) {
547
+ changed = true;
548
+ const sub = this.#sub(project, d.subscription);
549
+ const task = this.#rows("SELECT * FROM task_items WHERE seq = ?", d.task)[0];
550
+ if (task && Number(d.attempts) >= Number(sub.max_attempts)) this.#bury(sub, task, Number(d.attempts), "the lease ran out");
551
+ else this.#sql.exec(`UPDATE task_deliveries SET lease = NULL, lease_expires = NULL, holder = NULL
552
+ WHERE project = ? AND subscription = ? AND task = ?`, project, d.subscription, d.task);
553
+ }
554
+ this.#sql.exec("DELETE FROM task_dead WHERE project = ? AND expires <= ?", project, now);
555
+ this.#sql.exec("DELETE FROM task_takers WHERE project = ? AND until <= ?", project, now);
556
+ for (const job of this.#rows("SELECT id FROM task_jobs WHERE project = ? AND until <= ?", project, now)) {
557
+ this.#sql.exec("DELETE FROM task_job_entries WHERE job = ?", job.id);
558
+ this.#sql.exec("DELETE FROM task_jobs WHERE id = ?", job.id);
559
+ }
560
+ if (changed) this.#changed(project);
561
+ }
562
+ /** The projects with something due by now (for an alarm's sweep). */
563
+ dueProjects() {
564
+ const now = this.#now();
565
+ return this.#rows(`SELECT project FROM task_items WHERE expires_at <= ?1
566
+ UNION SELECT project FROM task_deliveries WHERE lease_expires <= ?1
567
+ UNION SELECT project FROM task_dead WHERE expires <= ?1`, now).map((r) => r.project);
568
+ }
569
+ /** When the next task, lease or dead letter is due, across projects (undefined: none). */
570
+ nextDue() {
571
+ const row = this.#rows(`SELECT min(at) AS at FROM (SELECT min(expires_at) AS at FROM task_items
572
+ UNION ALL SELECT min(lease_expires) FROM task_deliveries
573
+ UNION ALL SELECT min(expires) FROM task_dead)`)[0];
574
+ return row?.at === null || row?.at === void 0 ? void 0 : Number(row.at);
575
+ }
576
+ };
577
+ function limitOf(limit, max = MAX_READ) {
578
+ if (limit === void 0 || limit === null) return Math.min(DEFAULT_READ, max);
579
+ const n = Number(limit);
580
+ if (!Number.isInteger(n) || n < 1) throw taskError("EINVAL", "limit is a positive whole number");
581
+ return Math.min(n, max);
582
+ }
583
+ function leaseOf(value, fallback) {
584
+ if (value === void 0 || value === null) return fallback;
585
+ const n = Number(value);
586
+ if (!Number.isFinite(n) || n < MIN_LEASE_MS || n > MAX_LEASE_MS) throw taskError("EINVAL", `a lease is from ${MIN_LEASE_MS} ms to ${MAX_LEASE_MS} ms`);
587
+ return Math.round(n);
588
+ }
589
+ export { DEFAULTS, TaskQueue, globMatches, taskError };
590
+
591
+ //# sourceMappingURL=queue.js.map