@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/README.md CHANGED
@@ -6,11 +6,11 @@ SQLite backends for ayepi on one database file, through a
6
6
  - **`sqliteQueue`**, **`sqliteStore`**, **`sqlitePubSub`** (or all three as **`sqliteBackend`**) — the
7
7
  [`@ayepi/work`](https://www.npmjs.com/package/@ayepi/work) ports: a leased, at-least-once queue with dead
8
8
  letters, a key/value store with an atomic claim and counter, and pub/sub across processes.
9
- - **`sqliteRateStore`** — an [`@ayepi/rate`](https://www.npmjs.com/package/@ayepi/rate) store running rate's
10
- own algorithms (weighted costs included) on rows, shared by every process using the file.
9
+ - **`sqliteRateStore`** (from `@ayepi/sqlite/rate`) — an [`@ayepi/rate`](https://www.npmjs.com/package/@ayepi/rate)
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,22 +15,26 @@ 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 |
22
- | `sqliteRateStore(db, opts?)` | `@ayepi/rate` `RateLimitStore` (every algorithm, weighted costs) | `<prefix>rate_counter`, `<prefix>rate_bucket` |
22
+ | `sqliteRateStore(db, opts?)` from `@ayepi/sqlite/rate` | `@ayepi/rate` `RateLimitStore` (every algorithm, weighted costs) | `<prefix>rate_counter`, `<prefix>rate_bucket` |
23
+
24
+ The rate store is a separate entry, `@ayepi/sqlite/rate`, so the main entry never loads `@ayepi/rate` (an
25
+ optional peer).
23
26
 
24
27
  ```sh
25
- pnpm add @ayepi/sqlite better-sqlite3 zod
26
- # 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
27
30
  ```
28
31
 
29
32
  ```ts
30
33
  import Database from 'better-sqlite3'
31
34
  import { createWork, defineWork } from '@ayepi/work'
32
35
  import { limiter } from '@ayepi/rate'
33
- import { sqliteBackend, sqliteRateStore } from '@ayepi/sqlite'
36
+ import { sqliteBackend } from '@ayepi/sqlite'
37
+ import { sqliteRateStore } from '@ayepi/sqlite/rate'
34
38
 
35
39
  const db = new Database('hub.db')
36
40
  db.pragma('journal_mode = WAL') // readers never block the writer
@@ -69,8 +73,8 @@ Options every store takes (`SqliteOptions`):
69
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). |
70
74
  | `now` | `Date.now` | Clock, for tests (`sqliteRateStore` uses the `now` each hit passes instead). |
71
75
 
72
- Tables and indexes are created on construction (`CREATE … IF NOT EXISTS`), so constructing a store is
73
- 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.
74
78
 
75
79
  `atomic(db, fn)` runs `fn` in `BEGIN IMMEDIATE … COMMIT` (or a savepoint when `db.inTransaction`), and
76
80
  rolls back if it throws. `sqliteRateStore` uses it for each hit.
@@ -81,25 +85,32 @@ rolls back if it throws. `sqliteRateStore` uses it for each hit.
81
85
  function sqliteQueue(db: SqliteDatabase, opts?: SqliteQueueOptions): SqliteQueue
82
86
 
83
87
  interface SqliteQueueOptions extends SqliteOptions {
84
- 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
85
91
  }
86
92
 
87
- 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)
88
95
  size(): number // items in this queue, leased or not
89
96
  dead(limit?: number): SqliteDeadLetter[] // { body, error, at }, oldest first (default 100)
90
97
  }
91
98
  ```
92
99
 
93
- - `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
94
101
  first is still in the queue (a unique index); afterwards the key is free again.
95
102
  - `pop(max, visibility)` — first **reclaims** items whose lease lapsed (`attempt + 1`: a dead worker's item is
96
- 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
97
104
  workers (in any process) never lease the same item.
98
105
  - `heartbeat` / `ack` / `fail(pulled, delay?)` are gated on the lease token: a worker whose lease lapsed
99
106
  can't extend, remove or return an item another worker now holds. A handle this queue didn't issue is
100
107
  ignored.
101
108
  - Give a work type its own queue by name: `defineWork('ingest', h, { queue: sqliteQueue(db, { name: 'bulk' }) })`.
102
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
+
103
114
  ## `sqliteStore`
104
115
 
105
116
  ```ts
@@ -150,12 +161,14 @@ const work = createWork({ work, ...backend })
150
161
  ## `sqliteRateStore`
151
162
 
152
163
  ```ts
164
+ import { sqliteRateStore } from '@ayepi/sqlite/rate'
165
+
153
166
  function sqliteRateStore(db: SqliteDatabase, opts?: SqliteRateStoreOptions): SqliteRateStore
154
167
 
155
168
  interface SqliteRateStoreOptions {
156
169
  readonly prefix?: string
157
170
  readonly sweepEvery?: number // delete rows no window can read any more, every N hits (default 1000)
158
- readonly idle?: number // drop a token bucket idle this long (ms, default 10 min)
171
+ readonly idle?: number // keep an idle token bucket at least this long (ms, default 10 min); never dropped before it is full again
159
172
  }
160
173
  ```
161
174
 
package/dist/db.cjs ADDED
@@ -0,0 +1,74 @@
1
+ let zod = require("zod");
2
+ //#region src/db.ts
3
+ /**
4
+ * # The database port
5
+ *
6
+ * Every store in this package takes a {@link SqliteDatabase}: the small synchronous surface of a SQLite connection
7
+ * it needs. A `better-sqlite3` `Database` satisfies it as is, so the application opens the file once (with its own
8
+ * pragmas) and every ayepi port shares it. Tables are created on construction (`CREATE … IF NOT EXISTS`) under a
9
+ * validated name prefix.
10
+ *
11
+ * @module
12
+ */
13
+ /** The default table-name prefix. */
14
+ const DEFAULT_PREFIX = "ayepi_";
15
+ /** A table-name prefix: it is spliced into SQL, so only identifier characters are allowed. */
16
+ 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");
17
+ /** Resolve the shared options: a validated prefix and a clock. */
18
+ function resolveOptions(opts) {
19
+ return {
20
+ prefix: Prefix.parse(opts.prefix ?? "ayepi_"),
21
+ now: opts.now ?? Date.now
22
+ };
23
+ }
24
+ /** Run `fn` atomically and with the write lock held: `BEGIN IMMEDIATE`, or a savepoint inside an open transaction. */
25
+ function atomic(db, fn) {
26
+ const nested = db.inTransaction === true;
27
+ db.exec(nested ? "SAVEPOINT ayepi_atomic" : "BEGIN IMMEDIATE");
28
+ try {
29
+ const out = fn();
30
+ db.exec(nested ? "RELEASE ayepi_atomic" : "COMMIT");
31
+ return out;
32
+ } catch (err) {
33
+ db.exec(nested ? "ROLLBACK TO ayepi_atomic; RELEASE ayepi_atomic" : "ROLLBACK");
34
+ throw err;
35
+ }
36
+ }
37
+ /** Calls a function once every `every` calls (amortized cleanup). */
38
+ function every(count, fn) {
39
+ let n = 0;
40
+ return () => {
41
+ if (++n % count === 0) fn();
42
+ };
43
+ }
44
+ //#endregion
45
+ Object.defineProperty(exports, "DEFAULT_PREFIX", {
46
+ enumerable: true,
47
+ get: function() {
48
+ return DEFAULT_PREFIX;
49
+ }
50
+ });
51
+ Object.defineProperty(exports, "Prefix", {
52
+ enumerable: true,
53
+ get: function() {
54
+ return Prefix;
55
+ }
56
+ });
57
+ Object.defineProperty(exports, "atomic", {
58
+ enumerable: true,
59
+ get: function() {
60
+ return atomic;
61
+ }
62
+ });
63
+ Object.defineProperty(exports, "every", {
64
+ enumerable: true,
65
+ get: function() {
66
+ return every;
67
+ }
68
+ });
69
+ Object.defineProperty(exports, "resolveOptions", {
70
+ enumerable: true,
71
+ get: function() {
72
+ return resolveOptions;
73
+ }
74
+ });
package/dist/db.d.cts ADDED
@@ -0,0 +1,42 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/db.d.ts
4
+
5
+ /**
6
+ * A value bound to a statement parameter. There is no `null`: the stores write an absent value as a SQL `NULL`
7
+ * literal (a statement of its own), which keeps the port satisfiable by better-sqlite3's statement types.
8
+ */
9
+ type SqlValue = string | number | bigint;
10
+ /** A prepared statement: run it, or read one row or all rows. */
11
+ interface SqliteStatement {
12
+ run(...params: SqlValue[]): {
13
+ readonly changes: number;
14
+ };
15
+ get(...params: SqlValue[]): unknown;
16
+ all(...params: SqlValue[]): unknown[];
17
+ }
18
+ /** The SQLite connection surface the stores drive. A `better-sqlite3` `Database` is one. */
19
+ interface SqliteDatabase {
20
+ prepare(sql: string): SqliteStatement;
21
+ exec(sql: string): unknown;
22
+ /** Whether a transaction is open (better-sqlite3 reports it); nested work then uses a savepoint. */
23
+ readonly inTransaction?: boolean;
24
+ }
25
+ /** Options every store shares. */
26
+ interface SqliteOptions {
27
+ /** Prefix of every table this store creates (default `'ayepi_'`): letters, digits and `_`, not starting with a digit. */
28
+ readonly prefix?: string;
29
+ /** Clock (default `Date.now`). */
30
+ readonly now?: () => number;
31
+ }
32
+ /** The default table-name prefix. */
33
+ declare const DEFAULT_PREFIX = "ayepi_";
34
+ /** A table-name prefix: it is spliced into SQL, so only identifier characters are allowed. */
35
+ declare const Prefix: z.ZodString;
36
+ /** Resolve the shared options: a validated prefix and a clock. */
37
+
38
+ /** Run `fn` atomically and with the write lock held: `BEGIN IMMEDIATE`, or a savepoint inside an open transaction. */
39
+ declare function atomic<T>(db: SqliteDatabase, fn: () => T): T;
40
+ /** Calls a function once every `every` calls (amortized cleanup). */
41
+ //#endregion
42
+ export { SqliteOptions as a, SqliteDatabase as i, Prefix as n, SqliteStatement as o, SqlValue as r, atomic as s, DEFAULT_PREFIX as t };
package/dist/db.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/db.d.ts
4
+
5
+ /**
6
+ * A value bound to a statement parameter. There is no `null`: the stores write an absent value as a SQL `NULL`
7
+ * literal (a statement of its own), which keeps the port satisfiable by better-sqlite3's statement types.
8
+ */
9
+ type SqlValue = string | number | bigint;
10
+ /** A prepared statement: run it, or read one row or all rows. */
11
+ interface SqliteStatement {
12
+ run(...params: SqlValue[]): {
13
+ readonly changes: number;
14
+ };
15
+ get(...params: SqlValue[]): unknown;
16
+ all(...params: SqlValue[]): unknown[];
17
+ }
18
+ /** The SQLite connection surface the stores drive. A `better-sqlite3` `Database` is one. */
19
+ interface SqliteDatabase {
20
+ prepare(sql: string): SqliteStatement;
21
+ exec(sql: string): unknown;
22
+ /** Whether a transaction is open (better-sqlite3 reports it); nested work then uses a savepoint. */
23
+ readonly inTransaction?: boolean;
24
+ }
25
+ /** Options every store shares. */
26
+ interface SqliteOptions {
27
+ /** Prefix of every table this store creates (default `'ayepi_'`): letters, digits and `_`, not starting with a digit. */
28
+ readonly prefix?: string;
29
+ /** Clock (default `Date.now`). */
30
+ readonly now?: () => number;
31
+ }
32
+ /** The default table-name prefix. */
33
+ declare const DEFAULT_PREFIX = "ayepi_";
34
+ /** A table-name prefix: it is spliced into SQL, so only identifier characters are allowed. */
35
+ declare const Prefix: z.ZodString;
36
+ /** Resolve the shared options: a validated prefix and a clock. */
37
+
38
+ /** Run `fn` atomically and with the write lock held: `BEGIN IMMEDIATE`, or a savepoint inside an open transaction. */
39
+ declare function atomic<T>(db: SqliteDatabase, fn: () => T): T;
40
+ /** Calls a function once every `every` calls (amortized cleanup). */
41
+ //#endregion
42
+ export { SqliteOptions as a, SqliteDatabase as i, Prefix as n, SqliteStatement as o, SqlValue as r, atomic as s, DEFAULT_PREFIX as t };
package/dist/db.js ADDED
@@ -0,0 +1,45 @@
1
+ import { z } from "zod";
2
+ //#region src/db.ts
3
+ /**
4
+ * # The database port
5
+ *
6
+ * Every store in this package takes a {@link SqliteDatabase}: the small synchronous surface of a SQLite connection
7
+ * it needs. A `better-sqlite3` `Database` satisfies it as is, so the application opens the file once (with its own
8
+ * pragmas) and every ayepi port shares it. Tables are created on construction (`CREATE … IF NOT EXISTS`) under a
9
+ * validated name prefix.
10
+ *
11
+ * @module
12
+ */
13
+ /** The default table-name prefix. */
14
+ const DEFAULT_PREFIX = "ayepi_";
15
+ /** A table-name prefix: it is spliced into SQL, so only identifier characters are allowed. */
16
+ const Prefix = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "a table prefix is letters, digits and _, not starting with a digit");
17
+ /** Resolve the shared options: a validated prefix and a clock. */
18
+ function resolveOptions(opts) {
19
+ return {
20
+ prefix: Prefix.parse(opts.prefix ?? "ayepi_"),
21
+ now: opts.now ?? Date.now
22
+ };
23
+ }
24
+ /** Run `fn` atomically and with the write lock held: `BEGIN IMMEDIATE`, or a savepoint inside an open transaction. */
25
+ function atomic(db, fn) {
26
+ const nested = db.inTransaction === true;
27
+ db.exec(nested ? "SAVEPOINT ayepi_atomic" : "BEGIN IMMEDIATE");
28
+ try {
29
+ const out = fn();
30
+ db.exec(nested ? "RELEASE ayepi_atomic" : "COMMIT");
31
+ return out;
32
+ } catch (err) {
33
+ db.exec(nested ? "ROLLBACK TO ayepi_atomic; RELEASE ayepi_atomic" : "ROLLBACK");
34
+ throw err;
35
+ }
36
+ }
37
+ /** Calls a function once every `every` calls (amortized cleanup). */
38
+ function every(count, fn) {
39
+ let n = 0;
40
+ return () => {
41
+ if (++n % count === 0) fn();
42
+ };
43
+ }
44
+ //#endregion
45
+ export { resolveOptions as a, every as i, Prefix as n, atomic as r, DEFAULT_PREFIX as t };