@ayepi/sqlite 0.7.0 → 0.8.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/README.md CHANGED
@@ -10,7 +10,7 @@ SQLite backends for ayepi on one database file, through a
10
10
  store running rate's own algorithms (weighted costs included) on rows, shared by every process using the file.
11
11
 
12
12
  ```sh
13
- pnpm add @ayepi/sqlite better-sqlite3 zod
13
+ pnpm add @ayepi/sqlite @ayepi/work better-sqlite3 zod
14
14
  ```
15
15
 
16
16
  ```ts
package/ayepi-sqlite.md CHANGED
@@ -15,7 +15,7 @@ tables and every ayepi port can share the file; any number of processes may open
15
15
 
16
16
  | Export | Port | Tables |
17
17
  |---|---|---|
18
- | `sqliteQueue(db, opts?)` | `@ayepi/work` `Queue` (leased, at-least-once, dead letters) | `<prefix>queue`, `<prefix>queue_dead` |
18
+ | `sqliteQueue(db, opts?)` | `@ayepi/work` `Queue` (leased, at-least-once, priority, tags, holds, dead letters) | `<prefix>queue`, `<prefix>queue_hold`, `<prefix>queue_dead` |
19
19
  | `sqliteStore(db, opts?)` | `@ayepi/work` `Store` (TTL, atomic `setIfNotExists`, atomic `increment`) | `<prefix>kv` |
20
20
  | `sqlitePubSub(db, opts?)` | `@ayepi/work` `PubSub` (in-process at once, other processes by polling) | `<prefix>pubsub` |
21
21
  | `sqliteBackend(db, opts?)` | all three work ports, to spread into `createWork` | the above |
@@ -25,8 +25,8 @@ The rate store is a separate entry, `@ayepi/sqlite/rate`, so the main entry neve
25
25
  optional peer).
26
26
 
27
27
  ```sh
28
- pnpm add @ayepi/sqlite better-sqlite3 zod
29
- # plus @ayepi/work and/or @ayepi/rate, for the ports you use
28
+ pnpm add @ayepi/sqlite @ayepi/work better-sqlite3 zod
29
+ # plus @ayepi/rate for the rate store
30
30
  ```
31
31
 
32
32
  ```ts
@@ -73,8 +73,8 @@ Options every store takes (`SqliteOptions`):
73
73
  | `prefix` | `'ayepi_'` | Prefix of every table the store creates. Letters, digits and `_`, not starting with a digit (`Prefix`, a zod schema, checks it; anything else throws). |
74
74
  | `now` | `Date.now` | Clock, for tests (`sqliteRateStore` uses the `now` each hit passes instead). |
75
75
 
76
- Tables and indexes are created on construction (`CREATE … IF NOT EXISTS`), so constructing a store is
77
- the migration.
76
+ Tables and indexes are created on construction (`CREATE … IF NOT EXISTS`, and any column a queue table lacks is
77
+ added), so constructing a store is the migration.
78
78
 
79
79
  `atomic(db, fn)` runs `fn` in `BEGIN IMMEDIATE … COMMIT` (or a savepoint when `db.inTransaction`), and
80
80
  rolls back if it throws. `sqliteRateStore` uses it for each hit.
@@ -85,25 +85,32 @@ rolls back if it throws. `sqliteRateStore` uses it for each hit.
85
85
  function sqliteQueue(db: SqliteDatabase, opts?: SqliteQueueOptions): SqliteQueue
86
86
 
87
87
  interface SqliteQueueOptions extends SqliteOptions {
88
- readonly name?: string // which queue in the shared table (default 'default')
88
+ readonly name?: string // which queue in the shared table (default 'default')
89
+ readonly priority?: boolean // lease higher PushOptions.priority first (default true); false = oldest first
90
+ readonly classify?: (body: string) => readonly string[] // tags derived at push, added to PushOptions.tags
89
91
  }
90
92
 
91
- interface SqliteQueue extends Queue { // every operation is synchronous
93
+ interface SqliteQueue extends Queue, QueueHolds, QueueQueries { // every operation is synchronous
94
+ reclassify(batch?: number): number // classify items with no tags recorded (default 500)
92
95
  size(): number // items in this queue, leased or not
93
96
  dead(limit?: number): SqliteDeadLetter[] // { body, error, at }, oldest first (default 100)
94
97
  }
95
98
  ```
96
99
 
97
- - `push(body, { delay?, dedupeKey? })` — visible after `delay`. A `dedupeKey` collapses pushes while the
100
+ - `push(body, { delay?, dedupeKey?, priority?, tags? })` — visible after `delay`. A `dedupeKey` collapses pushes while the
98
101
  first is still in the queue (a unique index); afterwards the key is free again.
99
102
  - `pop(max, visibility)` — first **reclaims** items whose lease lapsed (`attempt + 1`: a dead worker's item is
100
- redelivered), then leases up to `max` visible items, oldest first, in one `UPDATE … RETURNING`, so two
103
+ redelivered), then leases up to `max` visible items that carry no held tag, highest priority then oldest first, in one `UPDATE … RETURNING`, so two
101
104
  workers (in any process) never lease the same item.
102
105
  - `heartbeat` / `ack` / `fail(pulled, delay?)` are gated on the lease token: a worker whose lease lapsed
103
106
  can't extend, remove or return an item another worker now holds. A handle this queue didn't issue is
104
107
  ignored.
105
108
  - Give a work type its own queue by name: `defineWork('ingest', h, { queue: sqliteQueue(db, { name: 'bulk' }) })`.
106
109
 
110
+ - Priority, tags, holds and queries follow
111
+ [the work port](./ayepi-work-ports.md#priority-tags-holds-and-queries). Tags are a JSON column matched by scanning
112
+ the queue's rows, which suits the sizes a single SQLite file serves.
113
+
107
114
  ## `sqliteStore`
108
115
 
109
116
  ```ts
package/dist/index.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_db = require("./db.cjs");
3
3
  let zod = require("zod");
4
+ let _ayepi_work = require("@ayepi/work");
4
5
  //#region src/queue.ts
5
6
  /**
6
7
  * # `sqliteQueue` — the `@ayepi/work` Queue
@@ -10,6 +11,8 @@ let zod = require("zod");
10
11
  * one `UPDATE … RETURNING`, so two workers can never lease the same item. `heartbeat`/`ack`/`fail` are gated on the
11
12
  * lease token, so a worker whose lease lapsed cannot touch an item another worker now holds. Pushes with the same
12
13
  * `dedupeKey` collapse while the first is still in the queue (a unique index).
14
+ * Higher priority leases first. Items carry tags (from `push` and `classify`) by which they can be held, counted,
15
+ * listed and removed.
13
16
  *
14
17
  * @module
15
18
  */
@@ -21,8 +24,59 @@ const Lease = zod.z.object({
21
24
  const LeasedRow = zod.z.object({
22
25
  id: zod.z.number(),
23
26
  body: zod.z.string(),
24
- attempt: zod.z.number()
27
+ attempt: zod.z.number(),
28
+ priority: zod.z.number()
25
29
  });
30
+ /** A JSON array of tags as a column stores it. */
31
+ const Tags = zod.z.string().transform((json) => zod.z.array(zod.z.string()).parse(JSON.parse(json)));
32
+ const HoldRow = zod.z.object({
33
+ tag: zod.z.string(),
34
+ info: zod.z.string(),
35
+ at: zod.z.number()
36
+ });
37
+ const TagCountRow = zod.z.object({
38
+ tag: zod.z.string(),
39
+ n: zod.z.number()
40
+ });
41
+ const ItemRow = zod.z.object({
42
+ id: zod.z.number(),
43
+ tags: Tags,
44
+ priority: zod.z.number(),
45
+ attempt: zod.z.number(),
46
+ leased: zod.z.number(),
47
+ visible_at: zod.z.number(),
48
+ body: zod.z.string()
49
+ });
50
+ const BodyRow = zod.z.object({
51
+ id: zod.z.number(),
52
+ body: zod.z.string()
53
+ });
54
+ /** A page cursor: an id this queue handed out. */
55
+ const Cursor = zod.z.string().regex(/^\d+$/, "a list cursor is an item id");
56
+ const RECLASSIFY_BATCH = 500;
57
+ /** SQLite reads a negative `LIMIT` as no limit. */
58
+ const NO_LIMIT = -1;
59
+ /** Columns a table created with only the base ones gains. */
60
+ const ADDED_COLUMNS = [["priority", "REAL NOT NULL DEFAULT 0"], ["tags", "TEXT"]];
61
+ const ColumnRow = zod.z.object({ name: zod.z.string() });
62
+ const LIVE = "(lease_token IS NOT NULL AND lease_until > ?)";
63
+ const FILTER = `NOT EXISTS (SELECT 1 FROM json_each(?) AS w WHERE NOT EXISTS (SELECT 1 FROM json_each(coalesce(tags, '[]')) AS c WHERE c.value = w.value))
64
+ AND (? = 0 OR EXISTS (SELECT 1 FROM json_each(coalesce(tags, '[]')) AS c WHERE c.value IN (SELECT value FROM json_each(?))))
65
+ AND (? = -1 OR ${LIVE} = ?)
66
+ AND (? = -1 OR (CASE WHEN lease_token IS NULL THEN visible_at <= ? ELSE lease_until <= ? END) = ?)`;
67
+ const flag = (value) => value === void 0 ? -1 : Number(value);
68
+ const filterParams = (f, at) => [
69
+ JSON.stringify(f.tags ?? []),
70
+ Number(f.anyTag !== void 0),
71
+ JSON.stringify(f.anyTag ?? []),
72
+ flag(f.leased),
73
+ at,
74
+ flag(f.leased),
75
+ flag(f.visible),
76
+ at,
77
+ at,
78
+ flag(f.visible)
79
+ ];
26
80
  const CountRow = zod.z.object({ n: zod.z.number() });
27
81
  const DeadRow = zod.z.object({
28
82
  body: zod.z.string(),
@@ -30,8 +84,15 @@ const DeadRow = zod.z.object({
30
84
  at: zod.z.number()
31
85
  });
32
86
  const DEAD_LIMIT = 100;
87
+ /** Add the columns an existing table lacks, one process at a time. */
88
+ function addColumns(db, table) {
89
+ require_db.atomic(db, () => {
90
+ const have = new Set(db.prepare("SELECT name FROM pragma_table_info(?)").all(table).map((r) => ColumnRow.parse(r).name));
91
+ for (const [column, type] of ADDED_COLUMNS) if (!have.has(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
92
+ });
93
+ }
33
94
  /**
34
- * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue` and `<prefix>queue_dead`).
95
+ * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue`, `<prefix>queue_hold` and `<prefix>queue_dead`).
35
96
  *
36
97
  * @example
37
98
  * ```ts
@@ -44,26 +105,53 @@ function sqliteQueue(db, opts = {}) {
44
105
  const name = opts.name ?? "default";
45
106
  const t = `${prefix}queue`;
46
107
  const dt = `${prefix}queue_dead`;
108
+ const ht = `${prefix}queue_hold`;
109
+ const prioritized = opts.priority !== false;
110
+ const classify = opts.classify;
47
111
  db.exec(`CREATE TABLE IF NOT EXISTS ${t} (
48
112
  id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, body TEXT NOT NULL, visible_at INTEGER NOT NULL,
49
- lease_token TEXT, lease_until INTEGER, attempt INTEGER NOT NULL DEFAULT 0, dedupe_key TEXT);
50
- CREATE INDEX IF NOT EXISTS ${t}_ready ON ${t}(name, visible_at) WHERE lease_token IS NULL;
113
+ lease_token TEXT, lease_until INTEGER, attempt INTEGER NOT NULL DEFAULT 0, dedupe_key TEXT,
114
+ priority REAL NOT NULL DEFAULT 0, tags TEXT);`);
115
+ addColumns(db, t);
116
+ db.exec(`DROP INDEX IF EXISTS ${t}_ready;
117
+ CREATE INDEX IF NOT EXISTS ${t}_ready_p ON ${t}(name, priority DESC, visible_at) WHERE lease_token IS NULL;
51
118
  CREATE INDEX IF NOT EXISTS ${t}_leased ON ${t}(name, lease_until) WHERE lease_token IS NOT NULL;
52
119
  CREATE UNIQUE INDEX IF NOT EXISTS ${t}_dedupe ON ${t}(name, dedupe_key) WHERE dedupe_key IS NOT NULL;
120
+ CREATE TABLE IF NOT EXISTS ${ht} (name TEXT NOT NULL, tag TEXT NOT NULL, info TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (name, tag));
53
121
  CREATE TABLE IF NOT EXISTS ${dt} (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, body TEXT NOT NULL, error TEXT NOT NULL, at INTEGER NOT NULL);`);
54
- const insert = db.prepare(`INSERT INTO ${t} (name, body, visible_at) VALUES (?, ?, ?)`);
55
- const insertOnce = db.prepare(`INSERT INTO ${t} (name, body, visible_at, dedupe_key) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING`);
122
+ const inserts = (columns, marks) => ({
123
+ plain: db.prepare(`INSERT INTO ${t} (name, body, visible_at, priority${columns}) VALUES (?, ?, ?, ?${marks})`),
124
+ once: db.prepare(`INSERT INTO ${t} (name, body, visible_at, priority${columns}, dedupe_key) VALUES (?, ?, ?, ?${marks}, ?) ON CONFLICT DO NOTHING`)
125
+ });
126
+ const untagged = inserts("", "");
127
+ const tagged = inserts(", tags", ", ?");
56
128
  const reclaim = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = attempt + 1
57
129
  WHERE name = ? AND lease_token IS NOT NULL AND lease_until <= ?`);
130
+ const free = `NOT EXISTS (SELECT 1 FROM json_each(q.tags) AS c JOIN ${ht} AS h ON h.tag = c.value WHERE h.name = q.name)`;
58
131
  const lease = db.prepare(`UPDATE ${t} SET lease_token = ?, lease_until = ?
59
- WHERE id IN (SELECT id FROM ${t} WHERE name = ? AND lease_token IS NULL AND visible_at <= ? ORDER BY visible_at, id LIMIT ?)
60
- RETURNING id, body, attempt`);
132
+ WHERE id IN (SELECT id FROM ${t} AS q WHERE name = ? AND lease_token IS NULL AND visible_at <= ? AND ${free}
133
+ ORDER BY priority DESC, visible_at, id LIMIT ?)
134
+ RETURNING id, body, attempt, priority`);
61
135
  const extend = db.prepare(`UPDATE ${t} SET lease_until = ? WHERE id = ? AND lease_token = ?`);
62
136
  const remove = db.prepare(`DELETE FROM ${t} WHERE id = ? AND lease_token = ?`);
63
- const release = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = ?, visible_at = ? WHERE id = ? AND lease_token = ?`);
137
+ const putBack = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = ?, visible_at = ? WHERE id = ? AND lease_token = ?`);
64
138
  const bury = db.prepare(`INSERT INTO ${dt} (name, body, error, at) VALUES (?, ?, ?, ?)`);
65
- const count = db.prepare(`SELECT count(*) AS n FROM ${t} WHERE name = ?`);
139
+ const depth = db.prepare(`SELECT count(*) AS n FROM ${t} WHERE name = ?`);
66
140
  const graveyard = db.prepare(`SELECT body, error, at FROM ${dt} WHERE name = ? ORDER BY id LIMIT ?`);
141
+ const holdTag = db.prepare(`INSERT INTO ${ht} (name, tag, info, created_at) VALUES (?, ?, ?, ?)
142
+ ON CONFLICT (name, tag) DO UPDATE SET info = excluded.info`);
143
+ const releaseTag = db.prepare(`DELETE FROM ${ht} WHERE name = ? AND tag = ?`);
144
+ const held = db.prepare(`SELECT tag, info, created_at AS at FROM ${ht} WHERE name = ? ORDER BY tag`);
145
+ const counted = db.prepare(`SELECT count(*) AS n FROM ${t} WHERE name = ? AND ${FILTER}`);
146
+ const tagCounts = db.prepare(`SELECT c.value AS tag, count(*) AS n FROM ${t} AS q, json_each(q.tags) AS c
147
+ WHERE q.name = ? AND substr(c.value, 1, length(?)) = ? GROUP BY c.value`);
148
+ const page = db.prepare(`SELECT id, coalesce(tags, '[]') AS tags, priority, attempt + (lease_token IS NOT NULL) AS attempt,
149
+ ${LIVE} AS leased, coalesce(lease_until, visible_at) AS visible_at, body
150
+ FROM ${t} WHERE name = ? AND id > ? AND ${FILTER} ORDER BY id LIMIT ?`);
151
+ const matching = db.prepare(`SELECT id, body FROM ${t} WHERE name = ? AND ${FILTER} ORDER BY id LIMIT ?`);
152
+ const erase = db.prepare(`DELETE FROM ${t} WHERE id IN (SELECT value FROM json_each(?))`);
153
+ const unclassified = db.prepare(`SELECT id, body FROM ${t} WHERE name = ? AND tags IS NULL ORDER BY id LIMIT ?`);
154
+ const classified = db.prepare(`UPDATE ${t} SET tags = ? WHERE id = ? AND tags IS NULL`);
67
155
  /** The lease of a handle this queue issued, or `null` for anything else. */
68
156
  const leaseOf = (pulled) => {
69
157
  const parsed = Lease.safeParse(pulled.handle);
@@ -71,16 +159,23 @@ function sqliteQueue(db, opts = {}) {
71
159
  };
72
160
  return {
73
161
  push(body, o) {
74
- const visibleAt = now() + (o?.delay ?? 0);
75
- if (o?.dedupeKey) insertOnce.run(name, body, visibleAt, o.dedupeKey);
76
- else insert.run(name, body, visibleAt);
162
+ const row = [
163
+ name,
164
+ body,
165
+ now() + (o?.delay ?? 0),
166
+ prioritized ? (0, _ayepi_work.queuePriority)(o?.priority) : 0
167
+ ];
168
+ const to = classify || o?.tags?.length ? tagged : untagged;
169
+ if (to === tagged) row.push(JSON.stringify((0, _ayepi_work.mergeTags)(o?.tags, classify?.(body))));
170
+ if (o?.dedupeKey) to.once.run(...row, o.dedupeKey);
171
+ else to.plain.run(...row);
77
172
  },
78
173
  pop(max, visibility) {
79
174
  const at = now();
80
175
  reclaim.run(name, at);
81
176
  const token = crypto.randomUUID();
82
177
  const rows = lease.all(token, at + visibility, name, at, max).map((r) => LeasedRow.parse(r));
83
- rows.sort((a, b) => a.id - b.id);
178
+ rows.sort((a, b) => b.priority - a.priority || a.id - b.id);
84
179
  return rows.map((r) => ({
85
180
  body: r.body,
86
181
  handle: {
@@ -100,13 +195,74 @@ function sqliteQueue(db, opts = {}) {
100
195
  },
101
196
  fail(pulled, delay) {
102
197
  const l = leaseOf(pulled);
103
- if (l) release.run(pulled.attempt, now() + (delay ?? 0), l.id, l.token);
198
+ if (l) putBack.run(pulled.attempt, now() + (delay ?? 0), l.id, l.token);
104
199
  },
105
200
  deadLetter(body, error) {
106
201
  bury.run(name, body, error, now());
107
202
  },
108
203
  size() {
109
- return CountRow.parse(count.get(name)).n;
204
+ return CountRow.parse(depth.get(name)).n;
205
+ },
206
+ hold(tag, info) {
207
+ holdTag.run(name, tag, info === void 0 ? "" : JSON.stringify(info), now());
208
+ },
209
+ release(tag) {
210
+ releaseTag.run(name, tag);
211
+ },
212
+ holds() {
213
+ return held.all(name).map((r) => {
214
+ const h = HoldRow.parse(r);
215
+ const info = h.info === "" ? void 0 : JSON.parse(h.info);
216
+ return {
217
+ tag: h.tag,
218
+ ...info === void 0 ? {} : { info },
219
+ createdAt: h.at
220
+ };
221
+ });
222
+ },
223
+ count(filter = {}) {
224
+ return CountRow.parse(counted.get(name, ...filterParams(filter, now()))).n;
225
+ },
226
+ countBy(tagPrefix) {
227
+ const rows = tagCounts.all(name, tagPrefix, tagPrefix).map((r) => TagCountRow.parse(r));
228
+ return Object.fromEntries(rows.map((r) => [r.tag, r.n]));
229
+ },
230
+ list(o = {}) {
231
+ const at = now();
232
+ const after = Number(o.after === void 0 ? 0 : Cursor.parse(o.after));
233
+ return page.all(at, name, after, ...filterParams(o, at), o.limit ?? _ayepi_work.DEFAULT_LIST_LIMIT).map((r) => {
234
+ const i = ItemRow.parse(r);
235
+ return {
236
+ id: String(i.id),
237
+ tags: i.tags,
238
+ priority: i.priority,
239
+ attempt: i.attempt,
240
+ leased: i.leased === 1,
241
+ visibleAt: i.visible_at,
242
+ ...o.bodies ? { body: i.body } : {}
243
+ };
244
+ });
245
+ },
246
+ remove(filter) {
247
+ (0, _ayepi_work.assertRemoveFilter)(filter);
248
+ const match = {
249
+ tags: filter.tags,
250
+ anyTag: filter.anyTag,
251
+ leased: false
252
+ };
253
+ return require_db.atomic(db, () => {
254
+ const rows = matching.all(name, ...filterParams(match, now()), filter.limit ?? NO_LIMIT).map((r) => BodyRow.parse(r));
255
+ erase.run(JSON.stringify(rows.map((r) => r.id)));
256
+ return rows.map((r) => r.body);
257
+ });
258
+ },
259
+ reclassify(batch = RECLASSIFY_BATCH) {
260
+ if (!classify) return 0;
261
+ return require_db.atomic(db, () => {
262
+ const rows = unclassified.all(name, batch).map((r) => BodyRow.parse(r));
263
+ for (const r of rows) classified.run(JSON.stringify((0, _ayepi_work.mergeTags)(classify(r.body))), r.id);
264
+ return rows.length;
265
+ });
110
266
  },
111
267
  dead(limit = DEAD_LIMIT) {
112
268
  return graveyard.all(name, limit).map((r) => DeadRow.parse(r));
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as SqliteOptions, i as SqliteDatabase, n as Prefix, o as SqliteStatement, r as SqlValue, s as atomic, t as DEFAULT_PREFIX } from "./db.cjs";
2
- import { Backend, PubSub, PulledWork, Queue, Store } from "@ayepi/work";
2
+ import { Backend, PubSub, PulledWork, PushOptions, Queue, QueueClassifier, QueueFilter, QueueHold, QueueHolds, QueueListOptions, QueueQueries, QueueRemoveFilter, QueuedItem, Store } from "@ayepi/work";
3
3
 
4
4
  //#region src/queue.d.ts
5
5
 
@@ -7,6 +7,10 @@ import { Backend, PubSub, PulledWork, Queue, Store } from "@ayepi/work";
7
7
  interface SqliteQueueOptions extends SqliteOptions {
8
8
  /** Which queue in the shared table (default `'default'`); give a work type its own queue by name. */
9
9
  readonly name?: string;
10
+ /** Lease higher `PushOptions.priority` first (default true); false records no priority, so leasing is oldest first. */
11
+ readonly priority?: boolean;
12
+ /** Derive tags from each body at `push`, added to `PushOptions.tags`. A throw fails the push. */
13
+ readonly classify?: QueueClassifier;
10
14
  }
11
15
  /** A dead-lettered body. */
12
16
  interface SqliteDeadLetter {
@@ -15,12 +19,9 @@ interface SqliteDeadLetter {
15
19
  /** When it was dead-lettered (epoch ms). */
16
20
  readonly at: number;
17
21
  }
18
- /** A {@link Queue} whose operations are synchronous, plus a look at its dead letters. */
19
- interface SqliteQueue extends Queue {
20
- push(body: string, opts?: {
21
- readonly delay?: number;
22
- readonly dedupeKey?: string;
23
- }): void;
22
+ /** A {@link Queue} with holds and queries by tag, whose operations are synchronous, plus a look at its dead letters. */
23
+ interface SqliteQueue extends Queue, QueueHolds, QueueQueries {
24
+ push(body: string, opts?: PushOptions): void;
24
25
  pop(max: number, visibility: number): PulledWork[];
25
26
  heartbeat(pulled: PulledWork, visibility: number): void;
26
27
  ack(pulled: PulledWork): void;
@@ -30,9 +31,21 @@ interface SqliteQueue extends Queue {
30
31
  size(): number;
31
32
  /** Dead-lettered bodies, oldest first (up to `limit`, default 100). */
32
33
  dead(limit?: number): SqliteDeadLetter[];
34
+ hold(tag: string, info?: unknown): void;
35
+ release(tag: string): void;
36
+ holds(): QueueHold[];
37
+ count(filter?: QueueFilter): number;
38
+ countBy(prefix: string): Record<string, number>;
39
+ list(options?: QueueListOptions): QueuedItem[];
40
+ remove(filter: QueueRemoveFilter): string[];
41
+ /**
42
+ * Run `classify` on up to `batch` (default 500) items that have no tags recorded (pushed without a classifier or
43
+ * tags) and store the result. Returns how many it classified: call until 0. Without `classify`, 0.
44
+ */
45
+ reclassify(batch?: number): number;
33
46
  }
34
47
  /**
35
- * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue` and `<prefix>queue_dead`).
48
+ * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue`, `<prefix>queue_hold` and `<prefix>queue_dead`).
36
49
  *
37
50
  * @example
38
51
  * ```ts
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as SqliteOptions, i as SqliteDatabase, n as Prefix, o as SqliteStatement, r as SqlValue, s as atomic, t as DEFAULT_PREFIX } from "./db.js";
2
- import { Backend, PubSub, PulledWork, Queue, Store } from "@ayepi/work";
2
+ import { Backend, PubSub, PulledWork, PushOptions, Queue, QueueClassifier, QueueFilter, QueueHold, QueueHolds, QueueListOptions, QueueQueries, QueueRemoveFilter, QueuedItem, Store } from "@ayepi/work";
3
3
 
4
4
  //#region src/queue.d.ts
5
5
 
@@ -7,6 +7,10 @@ import { Backend, PubSub, PulledWork, Queue, Store } from "@ayepi/work";
7
7
  interface SqliteQueueOptions extends SqliteOptions {
8
8
  /** Which queue in the shared table (default `'default'`); give a work type its own queue by name. */
9
9
  readonly name?: string;
10
+ /** Lease higher `PushOptions.priority` first (default true); false records no priority, so leasing is oldest first. */
11
+ readonly priority?: boolean;
12
+ /** Derive tags from each body at `push`, added to `PushOptions.tags`. A throw fails the push. */
13
+ readonly classify?: QueueClassifier;
10
14
  }
11
15
  /** A dead-lettered body. */
12
16
  interface SqliteDeadLetter {
@@ -15,12 +19,9 @@ interface SqliteDeadLetter {
15
19
  /** When it was dead-lettered (epoch ms). */
16
20
  readonly at: number;
17
21
  }
18
- /** A {@link Queue} whose operations are synchronous, plus a look at its dead letters. */
19
- interface SqliteQueue extends Queue {
20
- push(body: string, opts?: {
21
- readonly delay?: number;
22
- readonly dedupeKey?: string;
23
- }): void;
22
+ /** A {@link Queue} with holds and queries by tag, whose operations are synchronous, plus a look at its dead letters. */
23
+ interface SqliteQueue extends Queue, QueueHolds, QueueQueries {
24
+ push(body: string, opts?: PushOptions): void;
24
25
  pop(max: number, visibility: number): PulledWork[];
25
26
  heartbeat(pulled: PulledWork, visibility: number): void;
26
27
  ack(pulled: PulledWork): void;
@@ -30,9 +31,21 @@ interface SqliteQueue extends Queue {
30
31
  size(): number;
31
32
  /** Dead-lettered bodies, oldest first (up to `limit`, default 100). */
32
33
  dead(limit?: number): SqliteDeadLetter[];
34
+ hold(tag: string, info?: unknown): void;
35
+ release(tag: string): void;
36
+ holds(): QueueHold[];
37
+ count(filter?: QueueFilter): number;
38
+ countBy(prefix: string): Record<string, number>;
39
+ list(options?: QueueListOptions): QueuedItem[];
40
+ remove(filter: QueueRemoveFilter): string[];
41
+ /**
42
+ * Run `classify` on up to `batch` (default 500) items that have no tags recorded (pushed without a classifier or
43
+ * tags) and store the result. Returns how many it classified: call until 0. Without `classify`, 0.
44
+ */
45
+ reclassify(batch?: number): number;
33
46
  }
34
47
  /**
35
- * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue` and `<prefix>queue_dead`).
48
+ * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue`, `<prefix>queue_hold` and `<prefix>queue_dead`).
36
49
  *
37
50
  * @example
38
51
  * ```ts
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { a as resolveOptions, i as every, n as Prefix, r as atomic, t as DEFAULT_PREFIX } from "./db.js";
2
2
  import { z } from "zod";
3
+ import { DEFAULT_LIST_LIMIT, assertRemoveFilter, mergeTags, queuePriority } from "@ayepi/work";
3
4
  //#region src/queue.ts
4
5
  /**
5
6
  * # `sqliteQueue` — the `@ayepi/work` Queue
@@ -9,6 +10,8 @@ import { z } from "zod";
9
10
  * one `UPDATE … RETURNING`, so two workers can never lease the same item. `heartbeat`/`ack`/`fail` are gated on the
10
11
  * lease token, so a worker whose lease lapsed cannot touch an item another worker now holds. Pushes with the same
11
12
  * `dedupeKey` collapse while the first is still in the queue (a unique index).
13
+ * Higher priority leases first. Items carry tags (from `push` and `classify`) by which they can be held, counted,
14
+ * listed and removed.
12
15
  *
13
16
  * @module
14
17
  */
@@ -20,8 +23,59 @@ const Lease = z.object({
20
23
  const LeasedRow = z.object({
21
24
  id: z.number(),
22
25
  body: z.string(),
23
- attempt: z.number()
26
+ attempt: z.number(),
27
+ priority: z.number()
24
28
  });
29
+ /** A JSON array of tags as a column stores it. */
30
+ const Tags = z.string().transform((json) => z.array(z.string()).parse(JSON.parse(json)));
31
+ const HoldRow = z.object({
32
+ tag: z.string(),
33
+ info: z.string(),
34
+ at: z.number()
35
+ });
36
+ const TagCountRow = z.object({
37
+ tag: z.string(),
38
+ n: z.number()
39
+ });
40
+ const ItemRow = z.object({
41
+ id: z.number(),
42
+ tags: Tags,
43
+ priority: z.number(),
44
+ attempt: z.number(),
45
+ leased: z.number(),
46
+ visible_at: z.number(),
47
+ body: z.string()
48
+ });
49
+ const BodyRow = z.object({
50
+ id: z.number(),
51
+ body: z.string()
52
+ });
53
+ /** A page cursor: an id this queue handed out. */
54
+ const Cursor = z.string().regex(/^\d+$/, "a list cursor is an item id");
55
+ const RECLASSIFY_BATCH = 500;
56
+ /** SQLite reads a negative `LIMIT` as no limit. */
57
+ const NO_LIMIT = -1;
58
+ /** Columns a table created with only the base ones gains. */
59
+ const ADDED_COLUMNS = [["priority", "REAL NOT NULL DEFAULT 0"], ["tags", "TEXT"]];
60
+ const ColumnRow = z.object({ name: z.string() });
61
+ const LIVE = "(lease_token IS NOT NULL AND lease_until > ?)";
62
+ const FILTER = `NOT EXISTS (SELECT 1 FROM json_each(?) AS w WHERE NOT EXISTS (SELECT 1 FROM json_each(coalesce(tags, '[]')) AS c WHERE c.value = w.value))
63
+ AND (? = 0 OR EXISTS (SELECT 1 FROM json_each(coalesce(tags, '[]')) AS c WHERE c.value IN (SELECT value FROM json_each(?))))
64
+ AND (? = -1 OR ${LIVE} = ?)
65
+ AND (? = -1 OR (CASE WHEN lease_token IS NULL THEN visible_at <= ? ELSE lease_until <= ? END) = ?)`;
66
+ const flag = (value) => value === void 0 ? -1 : Number(value);
67
+ const filterParams = (f, at) => [
68
+ JSON.stringify(f.tags ?? []),
69
+ Number(f.anyTag !== void 0),
70
+ JSON.stringify(f.anyTag ?? []),
71
+ flag(f.leased),
72
+ at,
73
+ flag(f.leased),
74
+ flag(f.visible),
75
+ at,
76
+ at,
77
+ flag(f.visible)
78
+ ];
25
79
  const CountRow = z.object({ n: z.number() });
26
80
  const DeadRow = z.object({
27
81
  body: z.string(),
@@ -29,8 +83,15 @@ const DeadRow = z.object({
29
83
  at: z.number()
30
84
  });
31
85
  const DEAD_LIMIT = 100;
86
+ /** Add the columns an existing table lacks, one process at a time. */
87
+ function addColumns(db, table) {
88
+ atomic(db, () => {
89
+ const have = new Set(db.prepare("SELECT name FROM pragma_table_info(?)").all(table).map((r) => ColumnRow.parse(r).name));
90
+ for (const [column, type] of ADDED_COLUMNS) if (!have.has(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
91
+ });
92
+ }
32
93
  /**
33
- * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue` and `<prefix>queue_dead`).
94
+ * Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue`, `<prefix>queue_hold` and `<prefix>queue_dead`).
34
95
  *
35
96
  * @example
36
97
  * ```ts
@@ -43,26 +104,53 @@ function sqliteQueue(db, opts = {}) {
43
104
  const name = opts.name ?? "default";
44
105
  const t = `${prefix}queue`;
45
106
  const dt = `${prefix}queue_dead`;
107
+ const ht = `${prefix}queue_hold`;
108
+ const prioritized = opts.priority !== false;
109
+ const classify = opts.classify;
46
110
  db.exec(`CREATE TABLE IF NOT EXISTS ${t} (
47
111
  id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, body TEXT NOT NULL, visible_at INTEGER NOT NULL,
48
- lease_token TEXT, lease_until INTEGER, attempt INTEGER NOT NULL DEFAULT 0, dedupe_key TEXT);
49
- CREATE INDEX IF NOT EXISTS ${t}_ready ON ${t}(name, visible_at) WHERE lease_token IS NULL;
112
+ lease_token TEXT, lease_until INTEGER, attempt INTEGER NOT NULL DEFAULT 0, dedupe_key TEXT,
113
+ priority REAL NOT NULL DEFAULT 0, tags TEXT);`);
114
+ addColumns(db, t);
115
+ db.exec(`DROP INDEX IF EXISTS ${t}_ready;
116
+ CREATE INDEX IF NOT EXISTS ${t}_ready_p ON ${t}(name, priority DESC, visible_at) WHERE lease_token IS NULL;
50
117
  CREATE INDEX IF NOT EXISTS ${t}_leased ON ${t}(name, lease_until) WHERE lease_token IS NOT NULL;
51
118
  CREATE UNIQUE INDEX IF NOT EXISTS ${t}_dedupe ON ${t}(name, dedupe_key) WHERE dedupe_key IS NOT NULL;
119
+ CREATE TABLE IF NOT EXISTS ${ht} (name TEXT NOT NULL, tag TEXT NOT NULL, info TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (name, tag));
52
120
  CREATE TABLE IF NOT EXISTS ${dt} (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, body TEXT NOT NULL, error TEXT NOT NULL, at INTEGER NOT NULL);`);
53
- const insert = db.prepare(`INSERT INTO ${t} (name, body, visible_at) VALUES (?, ?, ?)`);
54
- const insertOnce = db.prepare(`INSERT INTO ${t} (name, body, visible_at, dedupe_key) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING`);
121
+ const inserts = (columns, marks) => ({
122
+ plain: db.prepare(`INSERT INTO ${t} (name, body, visible_at, priority${columns}) VALUES (?, ?, ?, ?${marks})`),
123
+ once: db.prepare(`INSERT INTO ${t} (name, body, visible_at, priority${columns}, dedupe_key) VALUES (?, ?, ?, ?${marks}, ?) ON CONFLICT DO NOTHING`)
124
+ });
125
+ const untagged = inserts("", "");
126
+ const tagged = inserts(", tags", ", ?");
55
127
  const reclaim = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = attempt + 1
56
128
  WHERE name = ? AND lease_token IS NOT NULL AND lease_until <= ?`);
129
+ const free = `NOT EXISTS (SELECT 1 FROM json_each(q.tags) AS c JOIN ${ht} AS h ON h.tag = c.value WHERE h.name = q.name)`;
57
130
  const lease = db.prepare(`UPDATE ${t} SET lease_token = ?, lease_until = ?
58
- WHERE id IN (SELECT id FROM ${t} WHERE name = ? AND lease_token IS NULL AND visible_at <= ? ORDER BY visible_at, id LIMIT ?)
59
- RETURNING id, body, attempt`);
131
+ WHERE id IN (SELECT id FROM ${t} AS q WHERE name = ? AND lease_token IS NULL AND visible_at <= ? AND ${free}
132
+ ORDER BY priority DESC, visible_at, id LIMIT ?)
133
+ RETURNING id, body, attempt, priority`);
60
134
  const extend = db.prepare(`UPDATE ${t} SET lease_until = ? WHERE id = ? AND lease_token = ?`);
61
135
  const remove = db.prepare(`DELETE FROM ${t} WHERE id = ? AND lease_token = ?`);
62
- const release = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = ?, visible_at = ? WHERE id = ? AND lease_token = ?`);
136
+ const putBack = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = ?, visible_at = ? WHERE id = ? AND lease_token = ?`);
63
137
  const bury = db.prepare(`INSERT INTO ${dt} (name, body, error, at) VALUES (?, ?, ?, ?)`);
64
- const count = db.prepare(`SELECT count(*) AS n FROM ${t} WHERE name = ?`);
138
+ const depth = db.prepare(`SELECT count(*) AS n FROM ${t} WHERE name = ?`);
65
139
  const graveyard = db.prepare(`SELECT body, error, at FROM ${dt} WHERE name = ? ORDER BY id LIMIT ?`);
140
+ const holdTag = db.prepare(`INSERT INTO ${ht} (name, tag, info, created_at) VALUES (?, ?, ?, ?)
141
+ ON CONFLICT (name, tag) DO UPDATE SET info = excluded.info`);
142
+ const releaseTag = db.prepare(`DELETE FROM ${ht} WHERE name = ? AND tag = ?`);
143
+ const held = db.prepare(`SELECT tag, info, created_at AS at FROM ${ht} WHERE name = ? ORDER BY tag`);
144
+ const counted = db.prepare(`SELECT count(*) AS n FROM ${t} WHERE name = ? AND ${FILTER}`);
145
+ const tagCounts = db.prepare(`SELECT c.value AS tag, count(*) AS n FROM ${t} AS q, json_each(q.tags) AS c
146
+ WHERE q.name = ? AND substr(c.value, 1, length(?)) = ? GROUP BY c.value`);
147
+ const page = db.prepare(`SELECT id, coalesce(tags, '[]') AS tags, priority, attempt + (lease_token IS NOT NULL) AS attempt,
148
+ ${LIVE} AS leased, coalesce(lease_until, visible_at) AS visible_at, body
149
+ FROM ${t} WHERE name = ? AND id > ? AND ${FILTER} ORDER BY id LIMIT ?`);
150
+ const matching = db.prepare(`SELECT id, body FROM ${t} WHERE name = ? AND ${FILTER} ORDER BY id LIMIT ?`);
151
+ const erase = db.prepare(`DELETE FROM ${t} WHERE id IN (SELECT value FROM json_each(?))`);
152
+ const unclassified = db.prepare(`SELECT id, body FROM ${t} WHERE name = ? AND tags IS NULL ORDER BY id LIMIT ?`);
153
+ const classified = db.prepare(`UPDATE ${t} SET tags = ? WHERE id = ? AND tags IS NULL`);
66
154
  /** The lease of a handle this queue issued, or `null` for anything else. */
67
155
  const leaseOf = (pulled) => {
68
156
  const parsed = Lease.safeParse(pulled.handle);
@@ -70,16 +158,23 @@ function sqliteQueue(db, opts = {}) {
70
158
  };
71
159
  return {
72
160
  push(body, o) {
73
- const visibleAt = now() + (o?.delay ?? 0);
74
- if (o?.dedupeKey) insertOnce.run(name, body, visibleAt, o.dedupeKey);
75
- else insert.run(name, body, visibleAt);
161
+ const row = [
162
+ name,
163
+ body,
164
+ now() + (o?.delay ?? 0),
165
+ prioritized ? queuePriority(o?.priority) : 0
166
+ ];
167
+ const to = classify || o?.tags?.length ? tagged : untagged;
168
+ if (to === tagged) row.push(JSON.stringify(mergeTags(o?.tags, classify?.(body))));
169
+ if (o?.dedupeKey) to.once.run(...row, o.dedupeKey);
170
+ else to.plain.run(...row);
76
171
  },
77
172
  pop(max, visibility) {
78
173
  const at = now();
79
174
  reclaim.run(name, at);
80
175
  const token = crypto.randomUUID();
81
176
  const rows = lease.all(token, at + visibility, name, at, max).map((r) => LeasedRow.parse(r));
82
- rows.sort((a, b) => a.id - b.id);
177
+ rows.sort((a, b) => b.priority - a.priority || a.id - b.id);
83
178
  return rows.map((r) => ({
84
179
  body: r.body,
85
180
  handle: {
@@ -99,13 +194,74 @@ function sqliteQueue(db, opts = {}) {
99
194
  },
100
195
  fail(pulled, delay) {
101
196
  const l = leaseOf(pulled);
102
- if (l) release.run(pulled.attempt, now() + (delay ?? 0), l.id, l.token);
197
+ if (l) putBack.run(pulled.attempt, now() + (delay ?? 0), l.id, l.token);
103
198
  },
104
199
  deadLetter(body, error) {
105
200
  bury.run(name, body, error, now());
106
201
  },
107
202
  size() {
108
- return CountRow.parse(count.get(name)).n;
203
+ return CountRow.parse(depth.get(name)).n;
204
+ },
205
+ hold(tag, info) {
206
+ holdTag.run(name, tag, info === void 0 ? "" : JSON.stringify(info), now());
207
+ },
208
+ release(tag) {
209
+ releaseTag.run(name, tag);
210
+ },
211
+ holds() {
212
+ return held.all(name).map((r) => {
213
+ const h = HoldRow.parse(r);
214
+ const info = h.info === "" ? void 0 : JSON.parse(h.info);
215
+ return {
216
+ tag: h.tag,
217
+ ...info === void 0 ? {} : { info },
218
+ createdAt: h.at
219
+ };
220
+ });
221
+ },
222
+ count(filter = {}) {
223
+ return CountRow.parse(counted.get(name, ...filterParams(filter, now()))).n;
224
+ },
225
+ countBy(tagPrefix) {
226
+ const rows = tagCounts.all(name, tagPrefix, tagPrefix).map((r) => TagCountRow.parse(r));
227
+ return Object.fromEntries(rows.map((r) => [r.tag, r.n]));
228
+ },
229
+ list(o = {}) {
230
+ const at = now();
231
+ const after = Number(o.after === void 0 ? 0 : Cursor.parse(o.after));
232
+ return page.all(at, name, after, ...filterParams(o, at), o.limit ?? DEFAULT_LIST_LIMIT).map((r) => {
233
+ const i = ItemRow.parse(r);
234
+ return {
235
+ id: String(i.id),
236
+ tags: i.tags,
237
+ priority: i.priority,
238
+ attempt: i.attempt,
239
+ leased: i.leased === 1,
240
+ visibleAt: i.visible_at,
241
+ ...o.bodies ? { body: i.body } : {}
242
+ };
243
+ });
244
+ },
245
+ remove(filter) {
246
+ assertRemoveFilter(filter);
247
+ const match = {
248
+ tags: filter.tags,
249
+ anyTag: filter.anyTag,
250
+ leased: false
251
+ };
252
+ return atomic(db, () => {
253
+ const rows = matching.all(name, ...filterParams(match, now()), filter.limit ?? NO_LIMIT).map((r) => BodyRow.parse(r));
254
+ erase.run(JSON.stringify(rows.map((r) => r.id)));
255
+ return rows.map((r) => r.body);
256
+ });
257
+ },
258
+ reclassify(batch = RECLASSIFY_BATCH) {
259
+ if (!classify) return 0;
260
+ return atomic(db, () => {
261
+ const rows = unclassified.all(name, batch).map((r) => BodyRow.parse(r));
262
+ for (const r of rows) classified.run(JSON.stringify(mergeTags(classify(r.body))), r.id);
263
+ return rows.length;
264
+ });
109
265
  },
110
266
  dead(limit = DEAD_LIMIT) {
111
267
  return graveyard.all(name, limit).map((r) => DeadRow.parse(r));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ayepi/sqlite",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "SQLite backends for ayepi (better-sqlite3) — the @ayepi/work Queue, Store and PubSub, and an @ayepi/rate store, in one database file",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -49,15 +49,12 @@
49
49
  },
50
50
  "peerDependencies": {
51
51
  "zod": "^4.6.7",
52
- "@ayepi/rate": "^0.7.0",
53
- "@ayepi/work": "^0.7.0"
52
+ "@ayepi/rate": "^0.8.0",
53
+ "@ayepi/work": "^0.8.0"
54
54
  },
55
55
  "peerDependenciesMeta": {
56
56
  "@ayepi/rate": {
57
57
  "optional": true
58
- },
59
- "@ayepi/work": {
60
- "optional": true
61
58
  }
62
59
  },
63
60
  "devDependencies": {
@@ -68,9 +65,9 @@
68
65
  "tsdown": "^0.12.0",
69
66
  "vitest": "^2.1.8",
70
67
  "zod": "^4.6.7",
71
- "@ayepi/core": "0.7.0",
72
- "@ayepi/rate": "0.7.0",
73
- "@ayepi/work": "0.7.0"
68
+ "@ayepi/core": "0.8.0",
69
+ "@ayepi/rate": "0.8.0",
70
+ "@ayepi/work": "0.8.0"
74
71
  },
75
72
  "keywords": [
76
73
  "ayepi",