@ayepi/sqlite 0.6.1 → 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/dist/index.cjs CHANGED
@@ -1,49 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_db = require("./db.cjs");
2
3
  let zod = require("zod");
3
- let _ayepi_rate = require("@ayepi/rate");
4
- //#region src/db.ts
5
- /**
6
- * # The database port
7
- *
8
- * Every store in this package takes a {@link SqliteDatabase}: the small synchronous surface of a SQLite connection
9
- * it needs. A `better-sqlite3` `Database` satisfies it as is, so the application opens the file once (with its own
10
- * pragmas) and every ayepi port shares it. Tables are created on construction (`CREATE … IF NOT EXISTS`) under a
11
- * validated name prefix.
12
- *
13
- * @module
14
- */
15
- /** The default table-name prefix. */
16
- const DEFAULT_PREFIX = "ayepi_";
17
- /** A table-name prefix: it is spliced into SQL, so only identifier characters are allowed. */
18
- const Prefix = zod.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "a table prefix is letters, digits and _, not starting with a digit");
19
- /** Resolve the shared options: a validated prefix and a clock. */
20
- function resolveOptions(opts) {
21
- return {
22
- prefix: Prefix.parse(opts.prefix ?? "ayepi_"),
23
- now: opts.now ?? Date.now
24
- };
25
- }
26
- /** Run `fn` atomically and with the write lock held: `BEGIN IMMEDIATE`, or a savepoint inside an open transaction. */
27
- function atomic(db, fn) {
28
- const nested = db.inTransaction === true;
29
- db.exec(nested ? "SAVEPOINT ayepi_atomic" : "BEGIN IMMEDIATE");
30
- try {
31
- const out = fn();
32
- db.exec(nested ? "RELEASE ayepi_atomic" : "COMMIT");
33
- return out;
34
- } catch (err) {
35
- db.exec(nested ? "ROLLBACK TO ayepi_atomic; RELEASE ayepi_atomic" : "ROLLBACK");
36
- throw err;
37
- }
38
- }
39
- /** Calls a function once every `every` calls (amortized cleanup). */
40
- function every(count, fn) {
41
- let n = 0;
42
- return () => {
43
- if (++n % count === 0) fn();
44
- };
45
- }
46
- //#endregion
4
+ let _ayepi_work = require("@ayepi/work");
47
5
  //#region src/queue.ts
48
6
  /**
49
7
  * # `sqliteQueue` — the `@ayepi/work` Queue
@@ -53,6 +11,8 @@ function every(count, fn) {
53
11
  * one `UPDATE … RETURNING`, so two workers can never lease the same item. `heartbeat`/`ack`/`fail` are gated on the
54
12
  * lease token, so a worker whose lease lapsed cannot touch an item another worker now holds. Pushes with the same
55
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.
56
16
  *
57
17
  * @module
58
18
  */
@@ -64,8 +24,59 @@ const Lease = zod.z.object({
64
24
  const LeasedRow = zod.z.object({
65
25
  id: zod.z.number(),
66
26
  body: zod.z.string(),
67
- attempt: zod.z.number()
27
+ attempt: zod.z.number(),
28
+ priority: zod.z.number()
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()
68
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
+ ];
69
80
  const CountRow = zod.z.object({ n: zod.z.number() });
70
81
  const DeadRow = zod.z.object({
71
82
  body: zod.z.string(),
@@ -73,8 +84,15 @@ const DeadRow = zod.z.object({
73
84
  at: zod.z.number()
74
85
  });
75
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
+ }
76
94
  /**
77
- * 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`).
78
96
  *
79
97
  * @example
80
98
  * ```ts
@@ -83,30 +101,57 @@ const DEAD_LIMIT = 100;
83
101
  * ```
84
102
  */
85
103
  function sqliteQueue(db, opts = {}) {
86
- const { prefix, now } = resolveOptions(opts);
104
+ const { prefix, now } = require_db.resolveOptions(opts);
87
105
  const name = opts.name ?? "default";
88
106
  const t = `${prefix}queue`;
89
107
  const dt = `${prefix}queue_dead`;
108
+ const ht = `${prefix}queue_hold`;
109
+ const prioritized = opts.priority !== false;
110
+ const classify = opts.classify;
90
111
  db.exec(`CREATE TABLE IF NOT EXISTS ${t} (
91
112
  id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, body TEXT NOT NULL, visible_at INTEGER NOT NULL,
92
- lease_token TEXT, lease_until INTEGER, attempt INTEGER NOT NULL DEFAULT 0, dedupe_key TEXT);
93
- 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;
94
118
  CREATE INDEX IF NOT EXISTS ${t}_leased ON ${t}(name, lease_until) WHERE lease_token IS NOT NULL;
95
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));
96
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);`);
97
- const insert = db.prepare(`INSERT INTO ${t} (name, body, visible_at) VALUES (?, ?, ?)`);
98
- 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", ", ?");
99
128
  const reclaim = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = attempt + 1
100
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)`;
101
131
  const lease = db.prepare(`UPDATE ${t} SET lease_token = ?, lease_until = ?
102
- WHERE id IN (SELECT id FROM ${t} WHERE name = ? AND lease_token IS NULL AND visible_at <= ? ORDER BY visible_at, id LIMIT ?)
103
- 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`);
104
135
  const extend = db.prepare(`UPDATE ${t} SET lease_until = ? WHERE id = ? AND lease_token = ?`);
105
136
  const remove = db.prepare(`DELETE FROM ${t} WHERE id = ? AND lease_token = ?`);
106
- 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 = ?`);
107
138
  const bury = db.prepare(`INSERT INTO ${dt} (name, body, error, at) VALUES (?, ?, ?, ?)`);
108
- 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 = ?`);
109
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`);
110
155
  /** The lease of a handle this queue issued, or `null` for anything else. */
111
156
  const leaseOf = (pulled) => {
112
157
  const parsed = Lease.safeParse(pulled.handle);
@@ -114,16 +159,23 @@ function sqliteQueue(db, opts = {}) {
114
159
  };
115
160
  return {
116
161
  push(body, o) {
117
- const visibleAt = now() + (o?.delay ?? 0);
118
- if (o?.dedupeKey) insertOnce.run(name, body, visibleAt, o.dedupeKey);
119
- 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);
120
172
  },
121
173
  pop(max, visibility) {
122
174
  const at = now();
123
175
  reclaim.run(name, at);
124
176
  const token = crypto.randomUUID();
125
177
  const rows = lease.all(token, at + visibility, name, at, max).map((r) => LeasedRow.parse(r));
126
- rows.sort((a, b) => a.id - b.id);
178
+ rows.sort((a, b) => b.priority - a.priority || a.id - b.id);
127
179
  return rows.map((r) => ({
128
180
  body: r.body,
129
181
  handle: {
@@ -143,13 +195,74 @@ function sqliteQueue(db, opts = {}) {
143
195
  },
144
196
  fail(pulled, delay) {
145
197
  const l = leaseOf(pulled);
146
- 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);
147
199
  },
148
200
  deadLetter(body, error) {
149
201
  bury.run(name, body, error, now());
150
202
  },
151
203
  size() {
152
- 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
+ });
153
266
  },
154
267
  dead(limit = DEAD_LIMIT) {
155
268
  return graveyard.all(name, limit).map((r) => DeadRow.parse(r));
@@ -166,7 +279,7 @@ function sqliteQueue(db, opts = {}) {
166
279
  *
167
280
  * @module
168
281
  */
169
- const SWEEP_EVERY$1 = 1e3;
282
+ const SWEEP_EVERY = 1e3;
170
283
  const ValueRow = zod.z.object({ value: zod.z.string() });
171
284
  /**
172
285
  * Create the `@ayepi/work` {@link Store} on `db` (table `<prefix>kv`).
@@ -179,7 +292,7 @@ const ValueRow = zod.z.object({ value: zod.z.string() });
179
292
  * ```
180
293
  */
181
294
  function sqliteStore(db, opts = {}) {
182
- const { prefix, now } = resolveOptions(opts);
295
+ const { prefix, now } = require_db.resolveOptions(opts);
183
296
  const t = `${prefix}kv`;
184
297
  db.exec(`CREATE TABLE IF NOT EXISTS ${t} (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER) WITHOUT ROWID;
185
298
  CREATE INDEX IF NOT EXISTS ${t}_expires ON ${t}(expires_at) WHERE expires_at IS NOT NULL;`);
@@ -201,7 +314,7 @@ function sqliteStore(db, opts = {}) {
201
314
  expires_at = excluded.expires_at
202
315
  RETURNING value`);
203
316
  const purge = db.prepare(`DELETE FROM ${t} WHERE expires_at IS NOT NULL AND expires_at <= ?`);
204
- const sweep = every(opts.sweepEvery ?? SWEEP_EVERY$1, () => void purge.run(now()));
317
+ const sweep = require_db.every(opts.sweepEvery ?? SWEEP_EVERY, () => void purge.run(now()));
205
318
  return {
206
319
  get(key) {
207
320
  const row = ValueRow.safeParse(read.get(key, now()));
@@ -248,7 +361,7 @@ const MessageRow = zod.z.object({
248
361
  const MaxRow = zod.z.object({ id: zod.z.number().nullable() });
249
362
  /** Create the `@ayepi/work` {@link PubSub} on `db` (table `<prefix>pubsub`). */
250
363
  function sqlitePubSub(db, opts = {}) {
251
- const { prefix, now } = resolveOptions(opts);
364
+ const { prefix, now } = require_db.resolveOptions(opts);
252
365
  const listeners = /* @__PURE__ */ new Set();
253
366
  const deliver = (message) => {
254
367
  for (const l of [...listeners]) l(message);
@@ -271,7 +384,7 @@ function sqlitePubSub(db, opts = {}) {
271
384
  const since = db.prepare(`SELECT id, origin, body FROM ${t} WHERE id > ? ORDER BY id`);
272
385
  const last = db.prepare(`SELECT max(id) AS id FROM ${t}`);
273
386
  const purge = db.prepare(`DELETE FROM ${t} WHERE at < ?`);
274
- const prune = every(PRUNE_EVERY, () => void purge.run(now() - retention));
387
+ const prune = require_db.every(PRUNE_EVERY, () => void purge.run(now() - retention));
275
388
  const latest = () => MaxRow.parse(last.get()).id ?? 0;
276
389
  let cursor = 0;
277
390
  let timer = null;
@@ -311,89 +424,6 @@ function sqlitePubSub(db, opts = {}) {
311
424
  };
312
425
  }
313
426
  //#endregion
314
- //#region src/rate.ts
315
- /**
316
- * # `sqliteRateStore` — an `@ayepi/rate` store
317
- *
318
- * Runs `@ayepi/rate`'s own algorithms ({@link applyHit}) on rows instead of Maps, inside one write transaction per
319
- * hit, so every algorithm and weighted cost behaves exactly as in the in-memory store while the limit is shared by
320
- * every process using the file.
321
- *
322
- * @module
323
- */
324
- const SWEEP_EVERY = 1e3;
325
- const IDLE = 600 * 1e3;
326
- const CounterRow = zod.z.object({
327
- count: zod.z.number(),
328
- reset: zod.z.number()
329
- });
330
- const BucketRow = zod.z.object({
331
- tokens: zod.z.number(),
332
- ts: zod.z.number()
333
- });
334
- /**
335
- * Create an `@ayepi/rate` {@link RateLimitStore} on `db` (tables `<prefix>rate_counter` and `<prefix>rate_bucket`).
336
- *
337
- * @example
338
- * ```ts
339
- * const spend = limiter({ limit: 5_000_000, window: 86_400_000, store: sqliteRateStore(db) })
340
- * ```
341
- */
342
- function sqliteRateStore(db, opts = {}) {
343
- const { prefix } = resolveOptions(opts);
344
- const idle = opts.idle ?? IDLE;
345
- const ct = `${prefix}rate_counter`;
346
- const bt = `${prefix}rate_bucket`;
347
- db.exec(`CREATE TABLE IF NOT EXISTS ${ct} (key TEXT PRIMARY KEY, count REAL NOT NULL, reset INTEGER NOT NULL, expires_at INTEGER NOT NULL) WITHOUT ROWID;
348
- CREATE TABLE IF NOT EXISTS ${bt} (key TEXT PRIMARY KEY, tokens REAL NOT NULL, ts INTEGER NOT NULL, expires_at INTEGER NOT NULL) WITHOUT ROWID;`);
349
- const readCounter = db.prepare(`SELECT count, reset FROM ${ct} WHERE key = ?`);
350
- const writeCounter = db.prepare(`INSERT INTO ${ct} (key, count, reset, expires_at) VALUES (?, ?, ?, ?)
351
- ON CONFLICT (key) DO UPDATE SET count = excluded.count, reset = excluded.reset, expires_at = excluded.expires_at`);
352
- const readBucket = db.prepare(`SELECT tokens, ts FROM ${bt} WHERE key = ?`);
353
- const writeBucket = db.prepare(`INSERT INTO ${bt} (key, tokens, ts, expires_at) VALUES (?, ?, ?, ?)
354
- ON CONFLICT (key) DO UPDATE SET tokens = excluded.tokens, ts = excluded.ts, expires_at = excluded.expires_at`);
355
- const dropCounters = db.prepare(`DELETE FROM ${ct} WHERE key = ? OR substr(key, 1, length(?) + 1) = ? || '|'`);
356
- const dropBucket = db.prepare(`DELETE FROM ${bt} WHERE key = ?`);
357
- const purgeCounters = db.prepare(`DELETE FROM ${ct} WHERE expires_at <= ?`);
358
- const purgeBuckets = db.prepare(`DELETE FROM ${bt} WHERE expires_at <= ?`);
359
- let clock = 0;
360
- const sweep = every(opts.sweepEvery ?? SWEEP_EVERY, () => {
361
- purgeCounters.run(clock);
362
- purgeBuckets.run(clock);
363
- });
364
- return {
365
- consume(key, rule, now, cost) {
366
- clock = now;
367
- const counters = {
368
- get: (k) => {
369
- const row = CounterRow.safeParse(readCounter.get(k));
370
- return row.success ? row.data : void 0;
371
- },
372
- set: (k, c) => void writeCounter.run(k, c.count, c.reset, c.reset + rule.window)
373
- };
374
- const buckets = {
375
- get: (k) => {
376
- const row = BucketRow.safeParse(readBucket.get(k));
377
- return row.success ? row.data : void 0;
378
- },
379
- set: (k, b) => void writeBucket.run(k, b.tokens, b.ts, b.ts + idle)
380
- };
381
- const result = atomic(db, () => (0, _ayepi_rate.applyHit)({
382
- counters,
383
- buckets
384
- }, key, rule, now, cost));
385
- sweep();
386
- return result;
387
- },
388
- reset(key) {
389
- atomic(db, () => {
390
- dropCounters.run(key, key, key);
391
- dropBucket.run(key);
392
- });
393
- }
394
- };
395
- }
396
- //#endregion
397
427
  //#region src/index.ts
398
428
  /** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
399
429
  function sqliteBackend(db, opts = {}) {
@@ -417,11 +447,10 @@ function sqliteBackend(db, opts = {}) {
417
447
  };
418
448
  }
419
449
  //#endregion
420
- exports.DEFAULT_PREFIX = DEFAULT_PREFIX;
421
- exports.Prefix = Prefix;
422
- exports.atomic = atomic;
450
+ exports.DEFAULT_PREFIX = require_db.DEFAULT_PREFIX;
451
+ exports.Prefix = require_db.Prefix;
452
+ exports.atomic = require_db.atomic;
423
453
  exports.sqliteBackend = sqliteBackend;
424
454
  exports.sqlitePubSub = sqlitePubSub;
425
455
  exports.sqliteQueue = sqliteQueue;
426
- exports.sqliteRateStore = sqliteRateStore;
427
456
  exports.sqliteStore = sqliteStore;
package/dist/index.d.cts CHANGED
@@ -1,51 +1,16 @@
1
- import { Backend, PubSub, PulledWork, Queue, Store } from "@ayepi/work";
2
- import { z } from "zod";
3
- import { RateLimitStore, applyHit } from "@ayepi/rate";
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, PushOptions, Queue, QueueClassifier, QueueFilter, QueueHold, QueueHolds, QueueListOptions, QueueQueries, QueueRemoveFilter, QueuedItem, Store } from "@ayepi/work";
4
3
 
5
- //#region src/db.d.ts
6
-
7
- /**
8
- * A value bound to a statement parameter. There is no `null`: the stores write an absent value as a SQL `NULL`
9
- * literal (a statement of its own), which keeps the port satisfiable by better-sqlite3's statement types.
10
- */
11
- type SqlValue = string | number | bigint;
12
- /** A prepared statement: run it, or read one row or all rows. */
13
- interface SqliteStatement {
14
- run(...params: SqlValue[]): {
15
- readonly changes: number;
16
- };
17
- get(...params: SqlValue[]): unknown;
18
- all(...params: SqlValue[]): unknown[];
19
- }
20
- /** The SQLite connection surface the stores drive. A `better-sqlite3` `Database` is one. */
21
- interface SqliteDatabase {
22
- prepare(sql: string): SqliteStatement;
23
- exec(sql: string): unknown;
24
- /** Whether a transaction is open (better-sqlite3 reports it); nested work then uses a savepoint. */
25
- readonly inTransaction?: boolean;
26
- }
27
- /** Options every store shares. */
28
- interface SqliteOptions {
29
- /** Prefix of every table this store creates (default `'ayepi_'`): letters, digits and `_`, not starting with a digit. */
30
- readonly prefix?: string;
31
- /** Clock (default `Date.now`). */
32
- readonly now?: () => number;
33
- }
34
- /** The default table-name prefix. */
35
- declare const DEFAULT_PREFIX = "ayepi_";
36
- /** A table-name prefix: it is spliced into SQL, so only identifier characters are allowed. */
37
- declare const Prefix: z.ZodString;
38
- /** Resolve the shared options: a validated prefix and a clock. */
39
-
40
- /** Run `fn` atomically and with the write lock held: `BEGIN IMMEDIATE`, or a savepoint inside an open transaction. */
41
- declare function atomic<T>(db: SqliteDatabase, fn: () => T): T;
42
- /** Calls a function once every `every` calls (amortized cleanup). */
43
- //#endregion
44
4
  //#region src/queue.d.ts
5
+
45
6
  /** Options for {@link sqliteQueue}. */
46
7
  interface SqliteQueueOptions extends SqliteOptions {
47
8
  /** Which queue in the shared table (default `'default'`); give a work type its own queue by name. */
48
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;
49
14
  }
50
15
  /** A dead-lettered body. */
51
16
  interface SqliteDeadLetter {
@@ -54,12 +19,9 @@ interface SqliteDeadLetter {
54
19
  /** When it was dead-lettered (epoch ms). */
55
20
  readonly at: number;
56
21
  }
57
- /** A {@link Queue} whose operations are synchronous, plus a look at its dead letters. */
58
- interface SqliteQueue extends Queue {
59
- push(body: string, opts?: {
60
- readonly delay?: number;
61
- readonly dedupeKey?: string;
62
- }): 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;
63
25
  pop(max: number, visibility: number): PulledWork[];
64
26
  heartbeat(pulled: PulledWork, visibility: number): void;
65
27
  ack(pulled: PulledWork): void;
@@ -69,9 +31,21 @@ interface SqliteQueue extends Queue {
69
31
  size(): number;
70
32
  /** Dead-lettered bodies, oldest first (up to `limit`, default 100). */
71
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;
72
46
  }
73
47
  /**
74
- * 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`).
75
49
  *
76
50
  * @example
77
51
  * ```ts
@@ -127,29 +101,6 @@ interface SqlitePubSub extends PubSub {
127
101
  /** Create the `@ayepi/work` {@link PubSub} on `db` (table `<prefix>pubsub`). */
128
102
  declare function sqlitePubSub(db: SqliteDatabase, opts?: SqlitePubSubOptions): SqlitePubSub;
129
103
  //#endregion
130
- //#region src/rate.d.ts
131
- /** Options for {@link sqliteRateStore}. */
132
- interface SqliteRateStoreOptions extends Omit<SqliteOptions, 'now'> {
133
- /** Delete rows no window can read any more once every this many hits (default 1000). */
134
- readonly sweepEvery?: number;
135
- /** Drop a token bucket idle this long (ms, default 10 minutes); it would have refilled anyway. */
136
- readonly idle?: number;
137
- }
138
- /** A {@link RateLimitStore} whose operations are synchronous. */
139
- interface SqliteRateStore extends RateLimitStore {
140
- consume(...args: Parameters<RateLimitStore['consume']>): ReturnType<typeof applyHit>;
141
- reset(key: string): void;
142
- }
143
- /**
144
- * Create an `@ayepi/rate` {@link RateLimitStore} on `db` (tables `<prefix>rate_counter` and `<prefix>rate_bucket`).
145
- *
146
- * @example
147
- * ```ts
148
- * const spend = limiter({ limit: 5_000_000, window: 86_400_000, store: sqliteRateStore(db) })
149
- * ```
150
- */
151
- declare function sqliteRateStore(db: SqliteDatabase, opts?: SqliteRateStoreOptions): SqliteRateStore;
152
- //#endregion
153
104
  //#region src/index.d.ts
154
105
  /** Options for {@link sqliteBackend}: the shared prefix and clock, and per-port options. */
155
106
  interface SqliteBackendOptions extends SqliteOptions {
@@ -166,4 +117,4 @@ interface SqliteBackend extends Backend {
166
117
  /** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
167
118
  declare function sqliteBackend(db: SqliteDatabase, opts?: SqliteBackendOptions): SqliteBackend;
168
119
  //#endregion
169
- export { DEFAULT_PREFIX, Prefix, type SqlValue, SqliteBackend, SqliteBackendOptions, type SqliteDatabase, type SqliteDeadLetter, type SqliteOptions, type SqlitePubSub, type SqlitePubSubOptions, type SqliteQueue, type SqliteQueueOptions, type SqliteRateStore, type SqliteRateStoreOptions, type SqliteStatement, type SqliteStore, type SqliteStoreOptions, atomic, sqliteBackend, sqlitePubSub, sqliteQueue, sqliteRateStore, sqliteStore };
120
+ export { DEFAULT_PREFIX, Prefix, type SqlValue, SqliteBackend, SqliteBackendOptions, type SqliteDatabase, type SqliteDeadLetter, type SqliteOptions, type SqlitePubSub, type SqlitePubSubOptions, type SqliteQueue, type SqliteQueueOptions, type SqliteStatement, type SqliteStore, type SqliteStoreOptions, atomic, sqliteBackend, sqlitePubSub, sqliteQueue, sqliteStore };