@ayepi/sqlite 0.0.0-stage → 0.5.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/LICENSE +21 -0
- package/README.md +33 -2
- package/ayepi-sqlite.md +179 -0
- package/dist/index.cjs +427 -0
- package/dist/index.d.cts +169 -0
- package/dist/index.d.ts +169 -0
- package/dist/index.js +419 -0
- package/package.json +77 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Philip Diffenderfer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ayepi/sqlite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
SQLite backends for ayepi on one database file, through a
|
|
4
|
+
[better-sqlite3](https://github.com/WiseLibs/better-sqlite3) connection you open:
|
|
5
|
+
|
|
6
|
+
- **`sqliteQueue`**, **`sqliteStore`**, **`sqlitePubSub`** (or all three as **`sqliteBackend`**) — the
|
|
7
|
+
[`@ayepi/work`](https://www.npmjs.com/package/@ayepi/work) ports: a leased, at-least-once queue with dead
|
|
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.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
pnpm add @ayepi/sqlite better-sqlite3 zod
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import Database from 'better-sqlite3'
|
|
18
|
+
import { createWork } from '@ayepi/work'
|
|
19
|
+
import { sqliteBackend } from '@ayepi/sqlite'
|
|
20
|
+
|
|
21
|
+
const db = new Database('app.db')
|
|
22
|
+
db.pragma('journal_mode = WAL')
|
|
23
|
+
const work = createWork({ work: [send] as const, ...sqliteBackend(db) })
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## For AI coding agents
|
|
27
|
+
|
|
28
|
+
This package ships a dense, machine-oriented reference written for **AI coding agents**:
|
|
29
|
+
|
|
30
|
+
- [`ayepi-sqlite.md`](./ayepi-sqlite.md)
|
|
31
|
+
|
|
32
|
+
## License
|
|
33
|
+
|
|
34
|
+
MIT
|
package/ayepi-sqlite.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
ayepi-sqlite.md — reference for `@ayepi/sqlite`, written for coding agents.
|
|
3
|
+
|
|
4
|
+
Copy this file into any project that depends on `@ayepi/sqlite` (e.g. into your repo's
|
|
5
|
+
`docs/` or `.claude/` directory) and reference it from your agents and slash commands.
|
|
6
|
+
It documents the public API, the patterns the package expects, and how it works under the
|
|
7
|
+
hood, with copy-pasteable examples. Keep it in sync with the installed package version.
|
|
8
|
+
-->
|
|
9
|
+
|
|
10
|
+
# `@ayepi/sqlite` — SQLite backends
|
|
11
|
+
|
|
12
|
+
The `@ayepi/work` ports and an `@ayepi/rate` store on **one SQLite file**, through a connection you open
|
|
13
|
+
(a [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3) `Database`). Your application's own
|
|
14
|
+
tables and every ayepi port can share the file; any number of processes may open it.
|
|
15
|
+
|
|
16
|
+
| Export | Port | Tables |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| `sqliteQueue(db, opts?)` | `@ayepi/work` `Queue` (leased, at-least-once, dead letters) | `<prefix>queue`, `<prefix>queue_dead` |
|
|
19
|
+
| `sqliteStore(db, opts?)` | `@ayepi/work` `Store` (TTL, atomic `setIfNotExists`, atomic `increment`) | `<prefix>kv` |
|
|
20
|
+
| `sqlitePubSub(db, opts?)` | `@ayepi/work` `PubSub` (in-process at once, other processes by polling) | `<prefix>pubsub` |
|
|
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` |
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pnpm add @ayepi/sqlite better-sqlite3 zod
|
|
26
|
+
# plus @ayepi/work and/or @ayepi/rate, for the ports you use
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import Database from 'better-sqlite3'
|
|
31
|
+
import { createWork, defineWork } from '@ayepi/work'
|
|
32
|
+
import { limiter } from '@ayepi/rate'
|
|
33
|
+
import { sqliteBackend, sqliteRateStore } from '@ayepi/sqlite'
|
|
34
|
+
|
|
35
|
+
const db = new Database('hub.db')
|
|
36
|
+
db.pragma('journal_mode = WAL') // readers never block the writer
|
|
37
|
+
db.pragma('busy_timeout = 5000') // wait for the write lock instead of failing at once
|
|
38
|
+
|
|
39
|
+
const work = createWork({ work: [run] as const, ...sqliteBackend(db) })
|
|
40
|
+
const spend = limiter({ limit: 5_000_000, window: 86_400_000, store: sqliteRateStore(db) })
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## The database port
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
type SqlValue = string | number | bigint
|
|
47
|
+
|
|
48
|
+
interface SqliteStatement {
|
|
49
|
+
run(...params: SqlValue[]): { readonly changes: number }
|
|
50
|
+
get(...params: SqlValue[]): unknown
|
|
51
|
+
all(...params: SqlValue[]): unknown[]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface SqliteDatabase {
|
|
55
|
+
prepare(sql: string): SqliteStatement
|
|
56
|
+
exec(sql: string): unknown
|
|
57
|
+
readonly inTransaction?: boolean
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
A `better-sqlite3` `Database` satisfies it as is. Every read row is parsed with a zod schema, so a table
|
|
62
|
+
that does not match what the store expects fails loudly. Bound values are never `null`: a store that needs
|
|
63
|
+
SQL `NULL` uses a statement with a `NULL` literal.
|
|
64
|
+
|
|
65
|
+
Options every store takes (`SqliteOptions`):
|
|
66
|
+
|
|
67
|
+
| Option | Default | |
|
|
68
|
+
|---|---|---|
|
|
69
|
+
| `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
|
+
| `now` | `Date.now` | Clock, for tests (`sqliteRateStore` uses the `now` each hit passes instead). |
|
|
71
|
+
|
|
72
|
+
Tables and indexes are created on construction (`CREATE … IF NOT EXISTS`), so constructing a store is
|
|
73
|
+
the migration.
|
|
74
|
+
|
|
75
|
+
`atomic(db, fn)` runs `fn` in `BEGIN IMMEDIATE … COMMIT` (or a savepoint when `db.inTransaction`), and
|
|
76
|
+
rolls back if it throws. `sqliteRateStore` uses it for each hit.
|
|
77
|
+
|
|
78
|
+
## `sqliteQueue`
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
function sqliteQueue(db: SqliteDatabase, opts?: SqliteQueueOptions): SqliteQueue
|
|
82
|
+
|
|
83
|
+
interface SqliteQueueOptions extends SqliteOptions {
|
|
84
|
+
readonly name?: string // which queue in the shared table (default 'default')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface SqliteQueue extends Queue { // every operation is synchronous
|
|
88
|
+
size(): number // items in this queue, leased or not
|
|
89
|
+
dead(limit?: number): SqliteDeadLetter[] // { body, error, at }, oldest first (default 100)
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- `push(body, { delay?, dedupeKey? })` — visible after `delay`. A `dedupeKey` collapses pushes while the
|
|
94
|
+
first is still in the queue (a unique index); afterwards the key is free again.
|
|
95
|
+
- `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
|
|
97
|
+
workers (in any process) never lease the same item.
|
|
98
|
+
- `heartbeat` / `ack` / `fail(pulled, delay?)` are gated on the lease token: a worker whose lease lapsed
|
|
99
|
+
can't extend, remove or return an item another worker now holds. A handle this queue didn't issue is
|
|
100
|
+
ignored.
|
|
101
|
+
- Give a work type its own queue by name: `defineWork('ingest', h, { queue: sqliteQueue(db, { name: 'bulk' }) })`.
|
|
102
|
+
|
|
103
|
+
## `sqliteStore`
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
function sqliteStore(db: SqliteDatabase, opts?: SqliteStoreOptions): SqliteStore
|
|
107
|
+
|
|
108
|
+
interface SqliteStoreOptions extends SqliteOptions {
|
|
109
|
+
readonly sweepEvery?: number // delete expired keys every N writes (default 1000)
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
- `get` never returns an expired key; `set(key, value, ttl?)` overwrites.
|
|
114
|
+
- `setIfNotExists(key, value, ttl?)` is one statement: it inserts, or takes over an **expired** key, so
|
|
115
|
+
exactly one caller wins across every process.
|
|
116
|
+
- `increment(key, by, ttl?)` is one statement on an integer value: an expired key counts from 0, and a
|
|
117
|
+
given `ttl` restarts with every increment.
|
|
118
|
+
|
|
119
|
+
## `sqlitePubSub`
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
function sqlitePubSub(db: SqliteDatabase, opts?: SqlitePubSubOptions): SqlitePubSub
|
|
123
|
+
|
|
124
|
+
interface SqlitePubSubOptions extends SqliteOptions {
|
|
125
|
+
readonly poll?: number | false // read other processes' messages every N ms (default 100); false = one process only
|
|
126
|
+
readonly retention?: number // keep messages this long for slow pollers (ms, default 60 000)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface SqlitePubSub extends PubSub { close(): void } // stop polling, drop subscribers
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
A publish reaches this process's subscribers at once and is written to the table; other processes poll for
|
|
133
|
+
rows newer than they have seen (skipping their own). Polling runs only while someone is subscribed, and a
|
|
134
|
+
subscriber hears only messages published while someone listened. With `poll: false` messages never touch
|
|
135
|
+
the database. Pub/sub is best-effort for `@ayepi/work` (waiters also poll the store), so the default poll
|
|
136
|
+
interval only bounds how fast a cross-process wake-up or cancel arrives.
|
|
137
|
+
|
|
138
|
+
## `sqliteBackend`
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
function sqliteBackend(db: SqliteDatabase, opts?: SqliteBackendOptions): SqliteBackend
|
|
142
|
+
// opts: { prefix?, now?, queue?: { name? }, store?: { sweepEvery? }, pubsub?: { poll?, retention? } }
|
|
143
|
+
// → { queue: SqliteQueue; store: SqliteStore; pubsub: SqlitePubSub }
|
|
144
|
+
|
|
145
|
+
const backend = sqliteBackend(db)
|
|
146
|
+
const work = createWork({ work, ...backend })
|
|
147
|
+
// at shutdown: await work.stop(); backend.pubsub.close()
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## `sqliteRateStore`
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
function sqliteRateStore(db: SqliteDatabase, opts?: SqliteRateStoreOptions): SqliteRateStore
|
|
154
|
+
|
|
155
|
+
interface SqliteRateStoreOptions {
|
|
156
|
+
readonly prefix?: string
|
|
157
|
+
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)
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Each hit runs `@ayepi/rate`'s own `applyHit` (the single implementation of `fixed-window`,
|
|
163
|
+
`sliding-window` and `token-bucket`, with weighted costs) on rows instead of Maps, inside one
|
|
164
|
+
`BEGIN IMMEDIATE` transaction, so it decides exactly as `memoryStore` does while the limit is shared by every
|
|
165
|
+
process using the file. `reset(key)` clears the key, its sliding-window buckets and its token bucket.
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { limiter, rateLimitedDoer } from '@ayepi/rate'
|
|
169
|
+
const perModel = rateLimitedDoer({ limit: 60, window: 60_000, store: sqliteRateStore(db) })
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## Gotchas
|
|
173
|
+
|
|
174
|
+
- **One writer at a time.** SQLite serializes writes; use WAL mode and a `busy_timeout` so concurrent
|
|
175
|
+
processes wait for the lock instead of failing with `SQLITE_BUSY`.
|
|
176
|
+
- **Synchronous.** Every operation runs on the calling thread (better-sqlite3 is synchronous), which is
|
|
177
|
+
the fastest choice for a local file but blocks the event loop for the length of a statement.
|
|
178
|
+
- **Integer counters.** `sqliteStore.increment` works on integers, as the work engine's group counter does.
|
|
179
|
+
- **No cache store.** For `@ayepi/cache`, use its `memoryCache` or `@ayepi/redis`'s `redisCache`.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
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
|
|
47
|
+
//#region src/queue.ts
|
|
48
|
+
/**
|
|
49
|
+
* # `sqliteQueue` — the `@ayepi/work` Queue
|
|
50
|
+
*
|
|
51
|
+
* A durable work log with visibility-timeout leasing, in one table shared by any number of named queues. `pop`
|
|
52
|
+
* reclaims expired leases (a dead worker's items are redelivered, `attempt + 1`) and then leases visible items in
|
|
53
|
+
* one `UPDATE … RETURNING`, so two workers can never lease the same item. `heartbeat`/`ack`/`fail` are gated on the
|
|
54
|
+
* lease token, so a worker whose lease lapsed cannot touch an item another worker now holds. Pushes with the same
|
|
55
|
+
* `dedupeKey` collapse while the first is still in the queue (a unique index).
|
|
56
|
+
*
|
|
57
|
+
* @module
|
|
58
|
+
*/
|
|
59
|
+
/** The lease handle `pop` hands out: the row and the lease token. */
|
|
60
|
+
const Lease = zod.z.object({
|
|
61
|
+
id: zod.z.number(),
|
|
62
|
+
token: zod.z.string()
|
|
63
|
+
});
|
|
64
|
+
const LeasedRow = zod.z.object({
|
|
65
|
+
id: zod.z.number(),
|
|
66
|
+
body: zod.z.string(),
|
|
67
|
+
attempt: zod.z.number()
|
|
68
|
+
});
|
|
69
|
+
const CountRow = zod.z.object({ n: zod.z.number() });
|
|
70
|
+
const DeadRow = zod.z.object({
|
|
71
|
+
body: zod.z.string(),
|
|
72
|
+
error: zod.z.string(),
|
|
73
|
+
at: zod.z.number()
|
|
74
|
+
});
|
|
75
|
+
const DEAD_LIMIT = 100;
|
|
76
|
+
/**
|
|
77
|
+
* Create a `@ayepi/work` {@link Queue} on `db` (tables `<prefix>queue` and `<prefix>queue_dead`).
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* const bulk = sqliteQueue(db, { name: 'bulk' }) // a separate queue for a noisy type
|
|
82
|
+
* const ingest = defineWork('ingest', handler, { queue: bulk })
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
function sqliteQueue(db, opts = {}) {
|
|
86
|
+
const { prefix, now } = resolveOptions(opts);
|
|
87
|
+
const name = opts.name ?? "default";
|
|
88
|
+
const t = `${prefix}queue`;
|
|
89
|
+
const dt = `${prefix}queue_dead`;
|
|
90
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${t} (
|
|
91
|
+
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;
|
|
94
|
+
CREATE INDEX IF NOT EXISTS ${t}_leased ON ${t}(name, lease_until) WHERE lease_token IS NOT NULL;
|
|
95
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${t}_dedupe ON ${t}(name, dedupe_key) WHERE dedupe_key IS NOT NULL;
|
|
96
|
+
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`);
|
|
99
|
+
const reclaim = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = attempt + 1
|
|
100
|
+
WHERE name = ? AND lease_token IS NOT NULL AND lease_until <= ?`);
|
|
101
|
+
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`);
|
|
104
|
+
const extend = db.prepare(`UPDATE ${t} SET lease_until = ? WHERE id = ? AND lease_token = ?`);
|
|
105
|
+
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 = ?`);
|
|
107
|
+
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 = ?`);
|
|
109
|
+
const graveyard = db.prepare(`SELECT body, error, at FROM ${dt} WHERE name = ? ORDER BY id LIMIT ?`);
|
|
110
|
+
/** The lease of a handle this queue issued, or `null` for anything else. */
|
|
111
|
+
const leaseOf = (pulled) => {
|
|
112
|
+
const parsed = Lease.safeParse(pulled.handle);
|
|
113
|
+
return parsed.success ? parsed.data : null;
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
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);
|
|
120
|
+
},
|
|
121
|
+
pop(max, visibility) {
|
|
122
|
+
const at = now();
|
|
123
|
+
reclaim.run(name, at);
|
|
124
|
+
const token = crypto.randomUUID();
|
|
125
|
+
const rows = lease.all(token, at + visibility, name, at, max).map((r) => LeasedRow.parse(r));
|
|
126
|
+
rows.sort((a, b) => a.id - b.id);
|
|
127
|
+
return rows.map((r) => ({
|
|
128
|
+
body: r.body,
|
|
129
|
+
handle: {
|
|
130
|
+
id: r.id,
|
|
131
|
+
token
|
|
132
|
+
},
|
|
133
|
+
attempt: r.attempt + 1
|
|
134
|
+
}));
|
|
135
|
+
},
|
|
136
|
+
heartbeat(pulled, visibility) {
|
|
137
|
+
const l = leaseOf(pulled);
|
|
138
|
+
if (l) extend.run(now() + visibility, l.id, l.token);
|
|
139
|
+
},
|
|
140
|
+
ack(pulled) {
|
|
141
|
+
const l = leaseOf(pulled);
|
|
142
|
+
if (l) remove.run(l.id, l.token);
|
|
143
|
+
},
|
|
144
|
+
fail(pulled, delay) {
|
|
145
|
+
const l = leaseOf(pulled);
|
|
146
|
+
if (l) release.run(pulled.attempt, now() + (delay ?? 0), l.id, l.token);
|
|
147
|
+
},
|
|
148
|
+
deadLetter(body, error) {
|
|
149
|
+
bury.run(name, body, error, now());
|
|
150
|
+
},
|
|
151
|
+
size() {
|
|
152
|
+
return CountRow.parse(count.get(name)).n;
|
|
153
|
+
},
|
|
154
|
+
dead(limit = DEAD_LIMIT) {
|
|
155
|
+
return graveyard.all(name, limit).map((r) => DeadRow.parse(r));
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
//#endregion
|
|
160
|
+
//#region src/store.ts
|
|
161
|
+
/**
|
|
162
|
+
* # `sqliteStore` — the `@ayepi/work` Store
|
|
163
|
+
*
|
|
164
|
+
* A key/value table with per-key expiry. `setIfNotExists` (the claim every work lease and fire-once relies on) and
|
|
165
|
+
* `increment` (the group counter) are single statements, so they are atomic across every process sharing the file.
|
|
166
|
+
*
|
|
167
|
+
* @module
|
|
168
|
+
*/
|
|
169
|
+
const SWEEP_EVERY$1 = 1e3;
|
|
170
|
+
const ValueRow = zod.z.object({ value: zod.z.string() });
|
|
171
|
+
/**
|
|
172
|
+
* Create the `@ayepi/work` {@link Store} on `db` (table `<prefix>kv`).
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* ```ts
|
|
176
|
+
* import Database from 'better-sqlite3'
|
|
177
|
+
* const db = new Database('hub.db')
|
|
178
|
+
* createWork({ work, ...sqliteBackend(db) }) // queue + store + pubsub in one file
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
function sqliteStore(db, opts = {}) {
|
|
182
|
+
const { prefix, now } = resolveOptions(opts);
|
|
183
|
+
const t = `${prefix}kv`;
|
|
184
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${t} (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER) WITHOUT ROWID;
|
|
185
|
+
CREATE INDEX IF NOT EXISTS ${t}_expires ON ${t}(expires_at) WHERE expires_at IS NOT NULL;`);
|
|
186
|
+
const read = db.prepare(`SELECT value FROM ${t} WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)`);
|
|
187
|
+
/** One statement per expiry form: `?` (expires at a time) and `NULL` (kept until deleted). */
|
|
188
|
+
const both = (sql) => ({
|
|
189
|
+
at: db.prepare(sql("?")),
|
|
190
|
+
never: db.prepare(sql("NULL"))
|
|
191
|
+
});
|
|
192
|
+
const write = both((e) => `INSERT INTO ${t} (key, value, expires_at) VALUES (?, ?, ${e})
|
|
193
|
+
ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`);
|
|
194
|
+
const remove = db.prepare(`DELETE FROM ${t} WHERE key = ?`);
|
|
195
|
+
const claim = both((e) => `INSERT INTO ${t} (key, value, expires_at) VALUES (?, ?, ${e})
|
|
196
|
+
ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at
|
|
197
|
+
WHERE ${t}.expires_at IS NOT NULL AND ${t}.expires_at <= ?`);
|
|
198
|
+
const add = both((e) => `INSERT INTO ${t} (key, value, expires_at) VALUES (?, CAST(CAST(? AS INTEGER) AS TEXT), ${e})
|
|
199
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
200
|
+
value = CAST((CASE WHEN ${t}.expires_at IS NOT NULL AND ${t}.expires_at <= ? THEN 0 ELSE CAST(${t}.value AS INTEGER) END) + CAST(? AS INTEGER) AS TEXT),
|
|
201
|
+
expires_at = excluded.expires_at
|
|
202
|
+
RETURNING value`);
|
|
203
|
+
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()));
|
|
205
|
+
return {
|
|
206
|
+
get(key) {
|
|
207
|
+
const row = ValueRow.safeParse(read.get(key, now()));
|
|
208
|
+
return row.success ? row.data.value : void 0;
|
|
209
|
+
},
|
|
210
|
+
set(key, value, ttl) {
|
|
211
|
+
if (ttl) write.at.run(key, value, now() + ttl);
|
|
212
|
+
else write.never.run(key, value);
|
|
213
|
+
sweep();
|
|
214
|
+
},
|
|
215
|
+
delete(key) {
|
|
216
|
+
remove.run(key);
|
|
217
|
+
},
|
|
218
|
+
setIfNotExists(key, value, ttl) {
|
|
219
|
+
sweep();
|
|
220
|
+
return (ttl ? claim.at.run(key, value, now() + ttl, now()) : claim.never.run(key, value, now())).changes === 1;
|
|
221
|
+
},
|
|
222
|
+
increment(key, by, ttl) {
|
|
223
|
+
sweep();
|
|
224
|
+
const row = ttl ? add.at.get(key, by, now() + ttl, now(), by) : add.never.get(key, by, now(), by);
|
|
225
|
+
return Number(ValueRow.parse(row).value);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
//#region src/pubsub.ts
|
|
231
|
+
/**
|
|
232
|
+
* # `sqlitePubSub` — the `@ayepi/work` PubSub
|
|
233
|
+
*
|
|
234
|
+
* Fans a message out to every subscriber in this process at once, and through a messages table to the other
|
|
235
|
+
* processes sharing the database file, which poll it. Pub/sub is best-effort for the work engine (waiters also poll
|
|
236
|
+
* the store), so a message older than `retention` is simply dropped.
|
|
237
|
+
*
|
|
238
|
+
* @module
|
|
239
|
+
*/
|
|
240
|
+
const POLL = 100;
|
|
241
|
+
const RETENTION = 6e4;
|
|
242
|
+
const PRUNE_EVERY = 100;
|
|
243
|
+
const MessageRow = zod.z.object({
|
|
244
|
+
id: zod.z.number(),
|
|
245
|
+
origin: zod.z.string(),
|
|
246
|
+
body: zod.z.string()
|
|
247
|
+
});
|
|
248
|
+
const MaxRow = zod.z.object({ id: zod.z.number().nullable() });
|
|
249
|
+
/** Create the `@ayepi/work` {@link PubSub} on `db` (table `<prefix>pubsub`). */
|
|
250
|
+
function sqlitePubSub(db, opts = {}) {
|
|
251
|
+
const { prefix, now } = resolveOptions(opts);
|
|
252
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
253
|
+
const deliver = (message) => {
|
|
254
|
+
for (const l of [...listeners]) l(message);
|
|
255
|
+
};
|
|
256
|
+
if (opts.poll === false) return {
|
|
257
|
+
publish: deliver,
|
|
258
|
+
subscribe(l) {
|
|
259
|
+
listeners.add(l);
|
|
260
|
+
return () => void listeners.delete(l);
|
|
261
|
+
},
|
|
262
|
+
close: () => listeners.clear()
|
|
263
|
+
};
|
|
264
|
+
const interval = opts.poll ?? POLL;
|
|
265
|
+
const retention = opts.retention ?? RETENTION;
|
|
266
|
+
const origin = crypto.randomUUID();
|
|
267
|
+
const t = `${prefix}pubsub`;
|
|
268
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${t} (id INTEGER PRIMARY KEY AUTOINCREMENT, origin TEXT NOT NULL, body TEXT NOT NULL, at INTEGER NOT NULL);
|
|
269
|
+
CREATE INDEX IF NOT EXISTS ${t}_at ON ${t}(at);`);
|
|
270
|
+
const insert = db.prepare(`INSERT INTO ${t} (origin, body, at) VALUES (?, ?, ?)`);
|
|
271
|
+
const since = db.prepare(`SELECT id, origin, body FROM ${t} WHERE id > ? ORDER BY id`);
|
|
272
|
+
const last = db.prepare(`SELECT max(id) AS id FROM ${t}`);
|
|
273
|
+
const purge = db.prepare(`DELETE FROM ${t} WHERE at < ?`);
|
|
274
|
+
const prune = every(PRUNE_EVERY, () => void purge.run(now() - retention));
|
|
275
|
+
const latest = () => MaxRow.parse(last.get()).id ?? 0;
|
|
276
|
+
let cursor = 0;
|
|
277
|
+
let timer = null;
|
|
278
|
+
const read = () => {
|
|
279
|
+
for (const raw of since.all(cursor)) {
|
|
280
|
+
const row = MessageRow.parse(raw);
|
|
281
|
+
cursor = row.id;
|
|
282
|
+
if (row.origin !== origin) deliver(row.body);
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
const stop = () => {
|
|
286
|
+
if (timer) clearInterval(timer);
|
|
287
|
+
timer = null;
|
|
288
|
+
};
|
|
289
|
+
return {
|
|
290
|
+
publish(message) {
|
|
291
|
+
insert.run(origin, message, now());
|
|
292
|
+
prune();
|
|
293
|
+
deliver(message);
|
|
294
|
+
},
|
|
295
|
+
subscribe(l) {
|
|
296
|
+
listeners.add(l);
|
|
297
|
+
if (!timer) {
|
|
298
|
+
cursor = latest();
|
|
299
|
+
timer = setInterval(read, interval);
|
|
300
|
+
timer.unref?.();
|
|
301
|
+
}
|
|
302
|
+
return () => {
|
|
303
|
+
listeners.delete(l);
|
|
304
|
+
if (listeners.size === 0) stop();
|
|
305
|
+
};
|
|
306
|
+
},
|
|
307
|
+
close() {
|
|
308
|
+
listeners.clear();
|
|
309
|
+
stop();
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
//#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
|
+
//#region src/index.ts
|
|
398
|
+
/** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
|
|
399
|
+
function sqliteBackend(db, opts = {}) {
|
|
400
|
+
const shared = {
|
|
401
|
+
prefix: opts.prefix,
|
|
402
|
+
now: opts.now
|
|
403
|
+
};
|
|
404
|
+
return {
|
|
405
|
+
queue: sqliteQueue(db, {
|
|
406
|
+
...shared,
|
|
407
|
+
...opts.queue
|
|
408
|
+
}),
|
|
409
|
+
store: sqliteStore(db, {
|
|
410
|
+
...shared,
|
|
411
|
+
...opts.store
|
|
412
|
+
}),
|
|
413
|
+
pubsub: sqlitePubSub(db, {
|
|
414
|
+
...shared,
|
|
415
|
+
...opts.pubsub
|
|
416
|
+
})
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
//#endregion
|
|
420
|
+
exports.DEFAULT_PREFIX = DEFAULT_PREFIX;
|
|
421
|
+
exports.Prefix = Prefix;
|
|
422
|
+
exports.atomic = atomic;
|
|
423
|
+
exports.sqliteBackend = sqliteBackend;
|
|
424
|
+
exports.sqlitePubSub = sqlitePubSub;
|
|
425
|
+
exports.sqliteQueue = sqliteQueue;
|
|
426
|
+
exports.sqliteRateStore = sqliteRateStore;
|
|
427
|
+
exports.sqliteStore = sqliteStore;
|