@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 +3 -3
- package/ayepi-sqlite.md +25 -12
- package/dist/db.cjs +74 -0
- package/dist/db.d.cts +42 -0
- package/dist/db.d.ts +42 -0
- package/dist/db.js +45 -0
- package/dist/index.cjs +182 -153
- package/dist/index.d.cts +24 -73
- package/dist/index.d.ts +24 -73
- package/dist/index.js +176 -146
- package/dist/rate.cjs +92 -0
- package/dist/rate.d.cts +28 -0
- package/dist/rate.d.ts +28 -0
- package/dist/rate.js +91 -0
- package/package.json +16 -9
package/dist/index.d.ts
CHANGED
|
@@ -1,51 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { Backend, PubSub, PulledWork, Queue, Store } from "@ayepi/work";
|
|
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, 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
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -1,48 +1,6 @@
|
|
|
1
|
+
import { a as resolveOptions, i as every, n as Prefix, r as atomic, t as DEFAULT_PREFIX } from "./db.js";
|
|
1
2
|
import { z } from "zod";
|
|
2
|
-
import {
|
|
3
|
-
//#region src/db.ts
|
|
4
|
-
/**
|
|
5
|
-
* # The database port
|
|
6
|
-
*
|
|
7
|
-
* Every store in this package takes a {@link SqliteDatabase}: the small synchronous surface of a SQLite connection
|
|
8
|
-
* it needs. A `better-sqlite3` `Database` satisfies it as is, so the application opens the file once (with its own
|
|
9
|
-
* pragmas) and every ayepi port shares it. Tables are created on construction (`CREATE … IF NOT EXISTS`) under a
|
|
10
|
-
* validated name prefix.
|
|
11
|
-
*
|
|
12
|
-
* @module
|
|
13
|
-
*/
|
|
14
|
-
/** The default table-name prefix. */
|
|
15
|
-
const DEFAULT_PREFIX = "ayepi_";
|
|
16
|
-
/** A table-name prefix: it is spliced into SQL, so only identifier characters are allowed. */
|
|
17
|
-
const Prefix = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "a table prefix is letters, digits and _, not starting with a digit");
|
|
18
|
-
/** Resolve the shared options: a validated prefix and a clock. */
|
|
19
|
-
function resolveOptions(opts) {
|
|
20
|
-
return {
|
|
21
|
-
prefix: Prefix.parse(opts.prefix ?? "ayepi_"),
|
|
22
|
-
now: opts.now ?? Date.now
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
/** Run `fn` atomically and with the write lock held: `BEGIN IMMEDIATE`, or a savepoint inside an open transaction. */
|
|
26
|
-
function atomic(db, fn) {
|
|
27
|
-
const nested = db.inTransaction === true;
|
|
28
|
-
db.exec(nested ? "SAVEPOINT ayepi_atomic" : "BEGIN IMMEDIATE");
|
|
29
|
-
try {
|
|
30
|
-
const out = fn();
|
|
31
|
-
db.exec(nested ? "RELEASE ayepi_atomic" : "COMMIT");
|
|
32
|
-
return out;
|
|
33
|
-
} catch (err) {
|
|
34
|
-
db.exec(nested ? "ROLLBACK TO ayepi_atomic; RELEASE ayepi_atomic" : "ROLLBACK");
|
|
35
|
-
throw err;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
/** Calls a function once every `every` calls (amortized cleanup). */
|
|
39
|
-
function every(count, fn) {
|
|
40
|
-
let n = 0;
|
|
41
|
-
return () => {
|
|
42
|
-
if (++n % count === 0) fn();
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
//#endregion
|
|
3
|
+
import { DEFAULT_LIST_LIMIT, assertRemoveFilter, mergeTags, queuePriority } from "@ayepi/work";
|
|
46
4
|
//#region src/queue.ts
|
|
47
5
|
/**
|
|
48
6
|
* # `sqliteQueue` — the `@ayepi/work` Queue
|
|
@@ -52,6 +10,8 @@ function every(count, fn) {
|
|
|
52
10
|
* one `UPDATE … RETURNING`, so two workers can never lease the same item. `heartbeat`/`ack`/`fail` are gated on the
|
|
53
11
|
* lease token, so a worker whose lease lapsed cannot touch an item another worker now holds. Pushes with the same
|
|
54
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.
|
|
55
15
|
*
|
|
56
16
|
* @module
|
|
57
17
|
*/
|
|
@@ -63,8 +23,59 @@ const Lease = z.object({
|
|
|
63
23
|
const LeasedRow = z.object({
|
|
64
24
|
id: z.number(),
|
|
65
25
|
body: z.string(),
|
|
66
|
-
attempt: z.number()
|
|
26
|
+
attempt: z.number(),
|
|
27
|
+
priority: z.number()
|
|
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()
|
|
67
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
|
+
];
|
|
68
79
|
const CountRow = z.object({ n: z.number() });
|
|
69
80
|
const DeadRow = z.object({
|
|
70
81
|
body: z.string(),
|
|
@@ -72,8 +83,15 @@ const DeadRow = z.object({
|
|
|
72
83
|
at: z.number()
|
|
73
84
|
});
|
|
74
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
|
+
}
|
|
75
93
|
/**
|
|
76
|
-
* 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`).
|
|
77
95
|
*
|
|
78
96
|
* @example
|
|
79
97
|
* ```ts
|
|
@@ -86,26 +104,53 @@ function sqliteQueue(db, opts = {}) {
|
|
|
86
104
|
const name = opts.name ?? "default";
|
|
87
105
|
const t = `${prefix}queue`;
|
|
88
106
|
const dt = `${prefix}queue_dead`;
|
|
107
|
+
const ht = `${prefix}queue_hold`;
|
|
108
|
+
const prioritized = opts.priority !== false;
|
|
109
|
+
const classify = opts.classify;
|
|
89
110
|
db.exec(`CREATE TABLE IF NOT EXISTS ${t} (
|
|
90
111
|
id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, body TEXT NOT NULL, visible_at INTEGER NOT NULL,
|
|
91
|
-
lease_token TEXT, lease_until INTEGER, attempt INTEGER NOT NULL DEFAULT 0, dedupe_key TEXT
|
|
92
|
-
|
|
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;
|
|
93
117
|
CREATE INDEX IF NOT EXISTS ${t}_leased ON ${t}(name, lease_until) WHERE lease_token IS NOT NULL;
|
|
94
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));
|
|
95
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);`);
|
|
96
|
-
const
|
|
97
|
-
|
|
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", ", ?");
|
|
98
127
|
const reclaim = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = attempt + 1
|
|
99
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)`;
|
|
100
130
|
const lease = db.prepare(`UPDATE ${t} SET lease_token = ?, lease_until = ?
|
|
101
|
-
WHERE id IN (SELECT id FROM ${t} WHERE name = ? AND lease_token IS NULL AND visible_at <= ?
|
|
102
|
-
|
|
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`);
|
|
103
134
|
const extend = db.prepare(`UPDATE ${t} SET lease_until = ? WHERE id = ? AND lease_token = ?`);
|
|
104
135
|
const remove = db.prepare(`DELETE FROM ${t} WHERE id = ? AND lease_token = ?`);
|
|
105
|
-
const
|
|
136
|
+
const putBack = db.prepare(`UPDATE ${t} SET lease_token = NULL, lease_until = NULL, attempt = ?, visible_at = ? WHERE id = ? AND lease_token = ?`);
|
|
106
137
|
const bury = db.prepare(`INSERT INTO ${dt} (name, body, error, at) VALUES (?, ?, ?, ?)`);
|
|
107
|
-
const
|
|
138
|
+
const depth = db.prepare(`SELECT count(*) AS n FROM ${t} WHERE name = ?`);
|
|
108
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`);
|
|
109
154
|
/** The lease of a handle this queue issued, or `null` for anything else. */
|
|
110
155
|
const leaseOf = (pulled) => {
|
|
111
156
|
const parsed = Lease.safeParse(pulled.handle);
|
|
@@ -113,16 +158,23 @@ function sqliteQueue(db, opts = {}) {
|
|
|
113
158
|
};
|
|
114
159
|
return {
|
|
115
160
|
push(body, o) {
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
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);
|
|
119
171
|
},
|
|
120
172
|
pop(max, visibility) {
|
|
121
173
|
const at = now();
|
|
122
174
|
reclaim.run(name, at);
|
|
123
175
|
const token = crypto.randomUUID();
|
|
124
176
|
const rows = lease.all(token, at + visibility, name, at, max).map((r) => LeasedRow.parse(r));
|
|
125
|
-
rows.sort((a, b) => a.id - b.id);
|
|
177
|
+
rows.sort((a, b) => b.priority - a.priority || a.id - b.id);
|
|
126
178
|
return rows.map((r) => ({
|
|
127
179
|
body: r.body,
|
|
128
180
|
handle: {
|
|
@@ -142,13 +194,74 @@ function sqliteQueue(db, opts = {}) {
|
|
|
142
194
|
},
|
|
143
195
|
fail(pulled, delay) {
|
|
144
196
|
const l = leaseOf(pulled);
|
|
145
|
-
if (l)
|
|
197
|
+
if (l) putBack.run(pulled.attempt, now() + (delay ?? 0), l.id, l.token);
|
|
146
198
|
},
|
|
147
199
|
deadLetter(body, error) {
|
|
148
200
|
bury.run(name, body, error, now());
|
|
149
201
|
},
|
|
150
202
|
size() {
|
|
151
|
-
return CountRow.parse(
|
|
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
|
+
});
|
|
152
265
|
},
|
|
153
266
|
dead(limit = DEAD_LIMIT) {
|
|
154
267
|
return graveyard.all(name, limit).map((r) => DeadRow.parse(r));
|
|
@@ -165,7 +278,7 @@ function sqliteQueue(db, opts = {}) {
|
|
|
165
278
|
*
|
|
166
279
|
* @module
|
|
167
280
|
*/
|
|
168
|
-
const SWEEP_EVERY
|
|
281
|
+
const SWEEP_EVERY = 1e3;
|
|
169
282
|
const ValueRow = z.object({ value: z.string() });
|
|
170
283
|
/**
|
|
171
284
|
* Create the `@ayepi/work` {@link Store} on `db` (table `<prefix>kv`).
|
|
@@ -200,7 +313,7 @@ function sqliteStore(db, opts = {}) {
|
|
|
200
313
|
expires_at = excluded.expires_at
|
|
201
314
|
RETURNING value`);
|
|
202
315
|
const purge = db.prepare(`DELETE FROM ${t} WHERE expires_at IS NOT NULL AND expires_at <= ?`);
|
|
203
|
-
const sweep = every(opts.sweepEvery ?? SWEEP_EVERY
|
|
316
|
+
const sweep = every(opts.sweepEvery ?? SWEEP_EVERY, () => void purge.run(now()));
|
|
204
317
|
return {
|
|
205
318
|
get(key) {
|
|
206
319
|
const row = ValueRow.safeParse(read.get(key, now()));
|
|
@@ -310,89 +423,6 @@ function sqlitePubSub(db, opts = {}) {
|
|
|
310
423
|
};
|
|
311
424
|
}
|
|
312
425
|
//#endregion
|
|
313
|
-
//#region src/rate.ts
|
|
314
|
-
/**
|
|
315
|
-
* # `sqliteRateStore` — an `@ayepi/rate` store
|
|
316
|
-
*
|
|
317
|
-
* Runs `@ayepi/rate`'s own algorithms ({@link applyHit}) on rows instead of Maps, inside one write transaction per
|
|
318
|
-
* hit, so every algorithm and weighted cost behaves exactly as in the in-memory store while the limit is shared by
|
|
319
|
-
* every process using the file.
|
|
320
|
-
*
|
|
321
|
-
* @module
|
|
322
|
-
*/
|
|
323
|
-
const SWEEP_EVERY = 1e3;
|
|
324
|
-
const IDLE = 600 * 1e3;
|
|
325
|
-
const CounterRow = z.object({
|
|
326
|
-
count: z.number(),
|
|
327
|
-
reset: z.number()
|
|
328
|
-
});
|
|
329
|
-
const BucketRow = z.object({
|
|
330
|
-
tokens: z.number(),
|
|
331
|
-
ts: z.number()
|
|
332
|
-
});
|
|
333
|
-
/**
|
|
334
|
-
* Create an `@ayepi/rate` {@link RateLimitStore} on `db` (tables `<prefix>rate_counter` and `<prefix>rate_bucket`).
|
|
335
|
-
*
|
|
336
|
-
* @example
|
|
337
|
-
* ```ts
|
|
338
|
-
* const spend = limiter({ limit: 5_000_000, window: 86_400_000, store: sqliteRateStore(db) })
|
|
339
|
-
* ```
|
|
340
|
-
*/
|
|
341
|
-
function sqliteRateStore(db, opts = {}) {
|
|
342
|
-
const { prefix } = resolveOptions(opts);
|
|
343
|
-
const idle = opts.idle ?? IDLE;
|
|
344
|
-
const ct = `${prefix}rate_counter`;
|
|
345
|
-
const bt = `${prefix}rate_bucket`;
|
|
346
|
-
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;
|
|
347
|
-
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;`);
|
|
348
|
-
const readCounter = db.prepare(`SELECT count, reset FROM ${ct} WHERE key = ?`);
|
|
349
|
-
const writeCounter = db.prepare(`INSERT INTO ${ct} (key, count, reset, expires_at) VALUES (?, ?, ?, ?)
|
|
350
|
-
ON CONFLICT (key) DO UPDATE SET count = excluded.count, reset = excluded.reset, expires_at = excluded.expires_at`);
|
|
351
|
-
const readBucket = db.prepare(`SELECT tokens, ts FROM ${bt} WHERE key = ?`);
|
|
352
|
-
const writeBucket = db.prepare(`INSERT INTO ${bt} (key, tokens, ts, expires_at) VALUES (?, ?, ?, ?)
|
|
353
|
-
ON CONFLICT (key) DO UPDATE SET tokens = excluded.tokens, ts = excluded.ts, expires_at = excluded.expires_at`);
|
|
354
|
-
const dropCounters = db.prepare(`DELETE FROM ${ct} WHERE key = ? OR substr(key, 1, length(?) + 1) = ? || '|'`);
|
|
355
|
-
const dropBucket = db.prepare(`DELETE FROM ${bt} WHERE key = ?`);
|
|
356
|
-
const purgeCounters = db.prepare(`DELETE FROM ${ct} WHERE expires_at <= ?`);
|
|
357
|
-
const purgeBuckets = db.prepare(`DELETE FROM ${bt} WHERE expires_at <= ?`);
|
|
358
|
-
let clock = 0;
|
|
359
|
-
const sweep = every(opts.sweepEvery ?? SWEEP_EVERY, () => {
|
|
360
|
-
purgeCounters.run(clock);
|
|
361
|
-
purgeBuckets.run(clock);
|
|
362
|
-
});
|
|
363
|
-
return {
|
|
364
|
-
consume(key, rule, now, cost) {
|
|
365
|
-
clock = now;
|
|
366
|
-
const counters = {
|
|
367
|
-
get: (k) => {
|
|
368
|
-
const row = CounterRow.safeParse(readCounter.get(k));
|
|
369
|
-
return row.success ? row.data : void 0;
|
|
370
|
-
},
|
|
371
|
-
set: (k, c) => void writeCounter.run(k, c.count, c.reset, c.reset + rule.window)
|
|
372
|
-
};
|
|
373
|
-
const buckets = {
|
|
374
|
-
get: (k) => {
|
|
375
|
-
const row = BucketRow.safeParse(readBucket.get(k));
|
|
376
|
-
return row.success ? row.data : void 0;
|
|
377
|
-
},
|
|
378
|
-
set: (k, b) => void writeBucket.run(k, b.tokens, b.ts, b.ts + idle)
|
|
379
|
-
};
|
|
380
|
-
const result = atomic(db, () => applyHit({
|
|
381
|
-
counters,
|
|
382
|
-
buckets
|
|
383
|
-
}, key, rule, now, cost));
|
|
384
|
-
sweep();
|
|
385
|
-
return result;
|
|
386
|
-
},
|
|
387
|
-
reset(key) {
|
|
388
|
-
atomic(db, () => {
|
|
389
|
-
dropCounters.run(key, key, key);
|
|
390
|
-
dropBucket.run(key);
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
//#endregion
|
|
396
426
|
//#region src/index.ts
|
|
397
427
|
/** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
|
|
398
428
|
function sqliteBackend(db, opts = {}) {
|
|
@@ -416,4 +446,4 @@ function sqliteBackend(db, opts = {}) {
|
|
|
416
446
|
};
|
|
417
447
|
}
|
|
418
448
|
//#endregion
|
|
419
|
-
export { DEFAULT_PREFIX, Prefix, atomic, sqliteBackend, sqlitePubSub, sqliteQueue,
|
|
449
|
+
export { DEFAULT_PREFIX, Prefix, atomic, sqliteBackend, sqlitePubSub, sqliteQueue, sqliteStore };
|
package/dist/rate.cjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_db = require("./db.cjs");
|
|
3
|
+
let zod = require("zod");
|
|
4
|
+
let _ayepi_rate = require("@ayepi/rate");
|
|
5
|
+
//#region src/rate.ts
|
|
6
|
+
/**
|
|
7
|
+
* # `sqliteRateStore` — an `@ayepi/rate` store
|
|
8
|
+
*
|
|
9
|
+
* Runs `@ayepi/rate`'s own algorithms ({@link applyHit}) on rows instead of Maps, inside one write transaction per
|
|
10
|
+
* hit, so every algorithm and weighted cost behaves exactly as in the in-memory store while the limit is shared by
|
|
11
|
+
* every process using the file. Imported from `@ayepi/sqlite/rate`, so the main entry never loads `@ayepi/rate`.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { sqliteRateStore } from '@ayepi/sqlite/rate'
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
const SWEEP_EVERY = 1e3;
|
|
20
|
+
const IDLE = 600 * 1e3;
|
|
21
|
+
const CounterRow = zod.z.object({
|
|
22
|
+
count: zod.z.number(),
|
|
23
|
+
reset: zod.z.number()
|
|
24
|
+
});
|
|
25
|
+
const BucketRow = zod.z.object({
|
|
26
|
+
tokens: zod.z.number(),
|
|
27
|
+
ts: zod.z.number()
|
|
28
|
+
});
|
|
29
|
+
/**
|
|
30
|
+
* Create an `@ayepi/rate` {@link RateLimitStore} on `db` (tables `<prefix>rate_counter` and `<prefix>rate_bucket`).
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* const spend = limiter({ limit: 5_000_000, window: 86_400_000, store: sqliteRateStore(db) })
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
function sqliteRateStore(db, opts = {}) {
|
|
38
|
+
const { prefix } = require_db.resolveOptions(opts);
|
|
39
|
+
const idle = opts.idle ?? IDLE;
|
|
40
|
+
const ct = `${prefix}rate_counter`;
|
|
41
|
+
const bt = `${prefix}rate_bucket`;
|
|
42
|
+
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;
|
|
43
|
+
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;`);
|
|
44
|
+
const readCounter = db.prepare(`SELECT count, reset FROM ${ct} WHERE key = ?`);
|
|
45
|
+
const writeCounter = db.prepare(`INSERT INTO ${ct} (key, count, reset, expires_at) VALUES (?, ?, ?, ?)
|
|
46
|
+
ON CONFLICT (key) DO UPDATE SET count = excluded.count, reset = excluded.reset, expires_at = excluded.expires_at`);
|
|
47
|
+
const readBucket = db.prepare(`SELECT tokens, ts FROM ${bt} WHERE key = ?`);
|
|
48
|
+
const writeBucket = db.prepare(`INSERT INTO ${bt} (key, tokens, ts, expires_at) VALUES (?, ?, ?, ?)
|
|
49
|
+
ON CONFLICT (key) DO UPDATE SET tokens = excluded.tokens, ts = excluded.ts, expires_at = excluded.expires_at`);
|
|
50
|
+
const dropCounters = db.prepare(`DELETE FROM ${ct} WHERE key = ? OR substr(key, 1, length(?) + 1) = ? || '|'`);
|
|
51
|
+
const dropBucket = db.prepare(`DELETE FROM ${bt} WHERE key = ?`);
|
|
52
|
+
const purgeCounters = db.prepare(`DELETE FROM ${ct} WHERE expires_at <= ?`);
|
|
53
|
+
const purgeBuckets = db.prepare(`DELETE FROM ${bt} WHERE expires_at <= ?`);
|
|
54
|
+
let clock = 0;
|
|
55
|
+
const sweep = require_db.every(opts.sweepEvery ?? SWEEP_EVERY, () => {
|
|
56
|
+
purgeCounters.run(clock);
|
|
57
|
+
purgeBuckets.run(clock);
|
|
58
|
+
});
|
|
59
|
+
return {
|
|
60
|
+
consume(key, rule, now, cost) {
|
|
61
|
+
clock = now;
|
|
62
|
+
const counters = {
|
|
63
|
+
get: (k) => {
|
|
64
|
+
const row = CounterRow.safeParse(readCounter.get(k));
|
|
65
|
+
return row.success ? row.data : void 0;
|
|
66
|
+
},
|
|
67
|
+
set: (k, c) => void writeCounter.run(k, c.count, c.reset, (0, _ayepi_rate.counterExpiry)(c, rule))
|
|
68
|
+
};
|
|
69
|
+
const buckets = {
|
|
70
|
+
get: (k) => {
|
|
71
|
+
const row = BucketRow.safeParse(readBucket.get(k));
|
|
72
|
+
return row.success ? row.data : void 0;
|
|
73
|
+
},
|
|
74
|
+
set: (k, b) => void writeBucket.run(k, b.tokens, b.ts, (0, _ayepi_rate.bucketExpiry)(b, rule, idle))
|
|
75
|
+
};
|
|
76
|
+
const result = require_db.atomic(db, () => (0, _ayepi_rate.applyHit)({
|
|
77
|
+
counters,
|
|
78
|
+
buckets
|
|
79
|
+
}, key, rule, now, cost));
|
|
80
|
+
sweep();
|
|
81
|
+
return result;
|
|
82
|
+
},
|
|
83
|
+
reset(key) {
|
|
84
|
+
require_db.atomic(db, () => {
|
|
85
|
+
dropCounters.run(key, key, key);
|
|
86
|
+
dropBucket.run(key);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
exports.sqliteRateStore = sqliteRateStore;
|
package/dist/rate.d.cts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { a as SqliteOptions, i as SqliteDatabase } from "./db.cjs";
|
|
2
|
+
import { RateLimitStore, applyHit } from "@ayepi/rate";
|
|
3
|
+
|
|
4
|
+
//#region src/rate.d.ts
|
|
5
|
+
|
|
6
|
+
/** Options for {@link sqliteRateStore}. */
|
|
7
|
+
interface SqliteRateStoreOptions extends Omit<SqliteOptions, 'now'> {
|
|
8
|
+
/** Delete rows no window can read any more once every this many hits (default 1000). */
|
|
9
|
+
readonly sweepEvery?: number;
|
|
10
|
+
/** Keep an idle token bucket at least this long (ms, default 10 minutes); it is never dropped before it has refilled to full. */
|
|
11
|
+
readonly idle?: number;
|
|
12
|
+
}
|
|
13
|
+
/** A {@link RateLimitStore} whose operations are synchronous. */
|
|
14
|
+
interface SqliteRateStore extends RateLimitStore {
|
|
15
|
+
consume(...args: Parameters<RateLimitStore['consume']>): ReturnType<typeof applyHit>;
|
|
16
|
+
reset(key: string): void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Create an `@ayepi/rate` {@link RateLimitStore} on `db` (tables `<prefix>rate_counter` and `<prefix>rate_bucket`).
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* const spend = limiter({ limit: 5_000_000, window: 86_400_000, store: sqliteRateStore(db) })
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
declare function sqliteRateStore(db: SqliteDatabase, opts?: SqliteRateStoreOptions): SqliteRateStore;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { type SqliteDatabase, type SqliteOptions, SqliteRateStore, SqliteRateStoreOptions, sqliteRateStore };
|