@ayepi/sqlite 0.6.1 → 0.7.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 +2 -2
- package/ayepi-sqlite.md +9 -3
- 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 +10 -137
- package/dist/index.d.cts +3 -65
- package/dist/index.d.ts +3 -65
- package/dist/index.js +4 -130
- 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 -6
package/README.md
CHANGED
|
@@ -6,8 +6,8 @@ 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)
|
|
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
13
|
pnpm add @ayepi/sqlite better-sqlite3 zod
|
package/ayepi-sqlite.md
CHANGED
|
@@ -19,7 +19,10 @@ tables and every ayepi port can share the file; any number of processes may open
|
|
|
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
28
|
pnpm add @ayepi/sqlite better-sqlite3 zod
|
|
@@ -30,7 +33,8 @@ pnpm add @ayepi/sqlite better-sqlite3 zod
|
|
|
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
|
|
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
|
|
@@ -150,12 +154,14 @@ const work = createWork({ work, ...backend })
|
|
|
150
154
|
## `sqliteRateStore`
|
|
151
155
|
|
|
152
156
|
```ts
|
|
157
|
+
import { sqliteRateStore } from '@ayepi/sqlite/rate'
|
|
158
|
+
|
|
153
159
|
function sqliteRateStore(db: SqliteDatabase, opts?: SqliteRateStoreOptions): SqliteRateStore
|
|
154
160
|
|
|
155
161
|
interface SqliteRateStoreOptions {
|
|
156
162
|
readonly prefix?: string
|
|
157
163
|
readonly sweepEvery?: number // delete rows no window can read any more, every N hits (default 1000)
|
|
158
|
-
readonly idle?: number //
|
|
164
|
+
readonly idle?: number // keep an idle token bucket at least this long (ms, default 10 min); never dropped before it is full again
|
|
159
165
|
}
|
|
160
166
|
```
|
|
161
167
|
|
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 };
|
package/dist/index.cjs
CHANGED
|
@@ -1,49 +1,6 @@
|
|
|
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
|
|
47
4
|
//#region src/queue.ts
|
|
48
5
|
/**
|
|
49
6
|
* # `sqliteQueue` — the `@ayepi/work` Queue
|
|
@@ -83,7 +40,7 @@ const DEAD_LIMIT = 100;
|
|
|
83
40
|
* ```
|
|
84
41
|
*/
|
|
85
42
|
function sqliteQueue(db, opts = {}) {
|
|
86
|
-
const { prefix, now } = resolveOptions(opts);
|
|
43
|
+
const { prefix, now } = require_db.resolveOptions(opts);
|
|
87
44
|
const name = opts.name ?? "default";
|
|
88
45
|
const t = `${prefix}queue`;
|
|
89
46
|
const dt = `${prefix}queue_dead`;
|
|
@@ -166,7 +123,7 @@ function sqliteQueue(db, opts = {}) {
|
|
|
166
123
|
*
|
|
167
124
|
* @module
|
|
168
125
|
*/
|
|
169
|
-
const SWEEP_EVERY
|
|
126
|
+
const SWEEP_EVERY = 1e3;
|
|
170
127
|
const ValueRow = zod.z.object({ value: zod.z.string() });
|
|
171
128
|
/**
|
|
172
129
|
* Create the `@ayepi/work` {@link Store} on `db` (table `<prefix>kv`).
|
|
@@ -179,7 +136,7 @@ const ValueRow = zod.z.object({ value: zod.z.string() });
|
|
|
179
136
|
* ```
|
|
180
137
|
*/
|
|
181
138
|
function sqliteStore(db, opts = {}) {
|
|
182
|
-
const { prefix, now } = resolveOptions(opts);
|
|
139
|
+
const { prefix, now } = require_db.resolveOptions(opts);
|
|
183
140
|
const t = `${prefix}kv`;
|
|
184
141
|
db.exec(`CREATE TABLE IF NOT EXISTS ${t} (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER) WITHOUT ROWID;
|
|
185
142
|
CREATE INDEX IF NOT EXISTS ${t}_expires ON ${t}(expires_at) WHERE expires_at IS NOT NULL;`);
|
|
@@ -201,7 +158,7 @@ function sqliteStore(db, opts = {}) {
|
|
|
201
158
|
expires_at = excluded.expires_at
|
|
202
159
|
RETURNING value`);
|
|
203
160
|
const purge = db.prepare(`DELETE FROM ${t} WHERE expires_at IS NOT NULL AND expires_at <= ?`);
|
|
204
|
-
const sweep = every(opts.sweepEvery ?? SWEEP_EVERY
|
|
161
|
+
const sweep = require_db.every(opts.sweepEvery ?? SWEEP_EVERY, () => void purge.run(now()));
|
|
205
162
|
return {
|
|
206
163
|
get(key) {
|
|
207
164
|
const row = ValueRow.safeParse(read.get(key, now()));
|
|
@@ -248,7 +205,7 @@ const MessageRow = zod.z.object({
|
|
|
248
205
|
const MaxRow = zod.z.object({ id: zod.z.number().nullable() });
|
|
249
206
|
/** Create the `@ayepi/work` {@link PubSub} on `db` (table `<prefix>pubsub`). */
|
|
250
207
|
function sqlitePubSub(db, opts = {}) {
|
|
251
|
-
const { prefix, now } = resolveOptions(opts);
|
|
208
|
+
const { prefix, now } = require_db.resolveOptions(opts);
|
|
252
209
|
const listeners = /* @__PURE__ */ new Set();
|
|
253
210
|
const deliver = (message) => {
|
|
254
211
|
for (const l of [...listeners]) l(message);
|
|
@@ -271,7 +228,7 @@ function sqlitePubSub(db, opts = {}) {
|
|
|
271
228
|
const since = db.prepare(`SELECT id, origin, body FROM ${t} WHERE id > ? ORDER BY id`);
|
|
272
229
|
const last = db.prepare(`SELECT max(id) AS id FROM ${t}`);
|
|
273
230
|
const purge = db.prepare(`DELETE FROM ${t} WHERE at < ?`);
|
|
274
|
-
const prune = every(PRUNE_EVERY, () => void purge.run(now() - retention));
|
|
231
|
+
const prune = require_db.every(PRUNE_EVERY, () => void purge.run(now() - retention));
|
|
275
232
|
const latest = () => MaxRow.parse(last.get()).id ?? 0;
|
|
276
233
|
let cursor = 0;
|
|
277
234
|
let timer = null;
|
|
@@ -311,89 +268,6 @@ function sqlitePubSub(db, opts = {}) {
|
|
|
311
268
|
};
|
|
312
269
|
}
|
|
313
270
|
//#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
271
|
//#region src/index.ts
|
|
398
272
|
/** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
|
|
399
273
|
function sqliteBackend(db, opts = {}) {
|
|
@@ -417,11 +291,10 @@ function sqliteBackend(db, opts = {}) {
|
|
|
417
291
|
};
|
|
418
292
|
}
|
|
419
293
|
//#endregion
|
|
420
|
-
exports.DEFAULT_PREFIX = DEFAULT_PREFIX;
|
|
421
|
-
exports.Prefix = Prefix;
|
|
422
|
-
exports.atomic = atomic;
|
|
294
|
+
exports.DEFAULT_PREFIX = require_db.DEFAULT_PREFIX;
|
|
295
|
+
exports.Prefix = require_db.Prefix;
|
|
296
|
+
exports.atomic = require_db.atomic;
|
|
423
297
|
exports.sqliteBackend = sqliteBackend;
|
|
424
298
|
exports.sqlitePubSub = sqlitePubSub;
|
|
425
299
|
exports.sqliteQueue = sqliteQueue;
|
|
426
|
-
exports.sqliteRateStore = sqliteRateStore;
|
|
427
300
|
exports.sqliteStore = sqliteStore;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,47 +1,8 @@
|
|
|
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";
|
|
1
2
|
import { Backend, PubSub, PulledWork, Queue, Store } from "@ayepi/work";
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
import { RateLimitStore, applyHit } from "@ayepi/rate";
|
|
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. */
|
|
@@ -127,29 +88,6 @@ interface SqlitePubSub extends PubSub {
|
|
|
127
88
|
/** Create the `@ayepi/work` {@link PubSub} on `db` (table `<prefix>pubsub`). */
|
|
128
89
|
declare function sqlitePubSub(db: SqliteDatabase, opts?: SqlitePubSubOptions): SqlitePubSub;
|
|
129
90
|
//#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
91
|
//#region src/index.d.ts
|
|
154
92
|
/** Options for {@link sqliteBackend}: the shared prefix and clock, and per-port options. */
|
|
155
93
|
interface SqliteBackendOptions extends SqliteOptions {
|
|
@@ -166,4 +104,4 @@ interface SqliteBackend extends Backend {
|
|
|
166
104
|
/** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
|
|
167
105
|
declare function sqliteBackend(db: SqliteDatabase, opts?: SqliteBackendOptions): SqliteBackend;
|
|
168
106
|
//#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
|
|
107
|
+
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.d.ts
CHANGED
|
@@ -1,47 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
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.js";
|
|
3
2
|
import { Backend, PubSub, PulledWork, Queue, 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. */
|
|
@@ -127,29 +88,6 @@ interface SqlitePubSub extends PubSub {
|
|
|
127
88
|
/** Create the `@ayepi/work` {@link PubSub} on `db` (table `<prefix>pubsub`). */
|
|
128
89
|
declare function sqlitePubSub(db: SqliteDatabase, opts?: SqlitePubSubOptions): SqlitePubSub;
|
|
129
90
|
//#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
91
|
//#region src/index.d.ts
|
|
154
92
|
/** Options for {@link sqliteBackend}: the shared prefix and clock, and per-port options. */
|
|
155
93
|
interface SqliteBackendOptions extends SqliteOptions {
|
|
@@ -166,4 +104,4 @@ interface SqliteBackend extends Backend {
|
|
|
166
104
|
/** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
|
|
167
105
|
declare function sqliteBackend(db: SqliteDatabase, opts?: SqliteBackendOptions): SqliteBackend;
|
|
168
106
|
//#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
|
|
107
|
+
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,5 @@
|
|
|
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 { applyHit } from "@ayepi/rate";
|
|
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
|
|
46
3
|
//#region src/queue.ts
|
|
47
4
|
/**
|
|
48
5
|
* # `sqliteQueue` — the `@ayepi/work` Queue
|
|
@@ -165,7 +122,7 @@ function sqliteQueue(db, opts = {}) {
|
|
|
165
122
|
*
|
|
166
123
|
* @module
|
|
167
124
|
*/
|
|
168
|
-
const SWEEP_EVERY
|
|
125
|
+
const SWEEP_EVERY = 1e3;
|
|
169
126
|
const ValueRow = z.object({ value: z.string() });
|
|
170
127
|
/**
|
|
171
128
|
* Create the `@ayepi/work` {@link Store} on `db` (table `<prefix>kv`).
|
|
@@ -200,7 +157,7 @@ function sqliteStore(db, opts = {}) {
|
|
|
200
157
|
expires_at = excluded.expires_at
|
|
201
158
|
RETURNING value`);
|
|
202
159
|
const purge = db.prepare(`DELETE FROM ${t} WHERE expires_at IS NOT NULL AND expires_at <= ?`);
|
|
203
|
-
const sweep = every(opts.sweepEvery ?? SWEEP_EVERY
|
|
160
|
+
const sweep = every(opts.sweepEvery ?? SWEEP_EVERY, () => void purge.run(now()));
|
|
204
161
|
return {
|
|
205
162
|
get(key) {
|
|
206
163
|
const row = ValueRow.safeParse(read.get(key, now()));
|
|
@@ -310,89 +267,6 @@ function sqlitePubSub(db, opts = {}) {
|
|
|
310
267
|
};
|
|
311
268
|
}
|
|
312
269
|
//#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
270
|
//#region src/index.ts
|
|
397
271
|
/** Create the `@ayepi/work` queue, store and pub/sub on `db` — spread it into `createWork`. */
|
|
398
272
|
function sqliteBackend(db, opts = {}) {
|
|
@@ -416,4 +290,4 @@ function sqliteBackend(db, opts = {}) {
|
|
|
416
290
|
};
|
|
417
291
|
}
|
|
418
292
|
//#endregion
|
|
419
|
-
export { DEFAULT_PREFIX, Prefix, atomic, sqliteBackend, sqlitePubSub, sqliteQueue,
|
|
293
|
+
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 };
|
package/dist/rate.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { a as SqliteOptions, i as SqliteDatabase } from "./db.js";
|
|
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 };
|
package/dist/rate.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { a as resolveOptions, i as every, r as atomic } from "./db.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { applyHit, bucketExpiry, counterExpiry } from "@ayepi/rate";
|
|
4
|
+
//#region src/rate.ts
|
|
5
|
+
/**
|
|
6
|
+
* # `sqliteRateStore` — an `@ayepi/rate` store
|
|
7
|
+
*
|
|
8
|
+
* Runs `@ayepi/rate`'s own algorithms ({@link applyHit}) on rows instead of Maps, inside one write transaction per
|
|
9
|
+
* hit, so every algorithm and weighted cost behaves exactly as in the in-memory store while the limit is shared by
|
|
10
|
+
* every process using the file. Imported from `@ayepi/sqlite/rate`, so the main entry never loads `@ayepi/rate`.
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { sqliteRateStore } from '@ayepi/sqlite/rate'
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
const SWEEP_EVERY = 1e3;
|
|
19
|
+
const IDLE = 600 * 1e3;
|
|
20
|
+
const CounterRow = z.object({
|
|
21
|
+
count: z.number(),
|
|
22
|
+
reset: z.number()
|
|
23
|
+
});
|
|
24
|
+
const BucketRow = z.object({
|
|
25
|
+
tokens: z.number(),
|
|
26
|
+
ts: z.number()
|
|
27
|
+
});
|
|
28
|
+
/**
|
|
29
|
+
* Create an `@ayepi/rate` {@link RateLimitStore} on `db` (tables `<prefix>rate_counter` and `<prefix>rate_bucket`).
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* const spend = limiter({ limit: 5_000_000, window: 86_400_000, store: sqliteRateStore(db) })
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
function sqliteRateStore(db, opts = {}) {
|
|
37
|
+
const { prefix } = resolveOptions(opts);
|
|
38
|
+
const idle = opts.idle ?? IDLE;
|
|
39
|
+
const ct = `${prefix}rate_counter`;
|
|
40
|
+
const bt = `${prefix}rate_bucket`;
|
|
41
|
+
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;
|
|
42
|
+
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;`);
|
|
43
|
+
const readCounter = db.prepare(`SELECT count, reset FROM ${ct} WHERE key = ?`);
|
|
44
|
+
const writeCounter = db.prepare(`INSERT INTO ${ct} (key, count, reset, expires_at) VALUES (?, ?, ?, ?)
|
|
45
|
+
ON CONFLICT (key) DO UPDATE SET count = excluded.count, reset = excluded.reset, expires_at = excluded.expires_at`);
|
|
46
|
+
const readBucket = db.prepare(`SELECT tokens, ts FROM ${bt} WHERE key = ?`);
|
|
47
|
+
const writeBucket = db.prepare(`INSERT INTO ${bt} (key, tokens, ts, expires_at) VALUES (?, ?, ?, ?)
|
|
48
|
+
ON CONFLICT (key) DO UPDATE SET tokens = excluded.tokens, ts = excluded.ts, expires_at = excluded.expires_at`);
|
|
49
|
+
const dropCounters = db.prepare(`DELETE FROM ${ct} WHERE key = ? OR substr(key, 1, length(?) + 1) = ? || '|'`);
|
|
50
|
+
const dropBucket = db.prepare(`DELETE FROM ${bt} WHERE key = ?`);
|
|
51
|
+
const purgeCounters = db.prepare(`DELETE FROM ${ct} WHERE expires_at <= ?`);
|
|
52
|
+
const purgeBuckets = db.prepare(`DELETE FROM ${bt} WHERE expires_at <= ?`);
|
|
53
|
+
let clock = 0;
|
|
54
|
+
const sweep = every(opts.sweepEvery ?? SWEEP_EVERY, () => {
|
|
55
|
+
purgeCounters.run(clock);
|
|
56
|
+
purgeBuckets.run(clock);
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
consume(key, rule, now, cost) {
|
|
60
|
+
clock = now;
|
|
61
|
+
const counters = {
|
|
62
|
+
get: (k) => {
|
|
63
|
+
const row = CounterRow.safeParse(readCounter.get(k));
|
|
64
|
+
return row.success ? row.data : void 0;
|
|
65
|
+
},
|
|
66
|
+
set: (k, c) => void writeCounter.run(k, c.count, c.reset, counterExpiry(c, rule))
|
|
67
|
+
};
|
|
68
|
+
const buckets = {
|
|
69
|
+
get: (k) => {
|
|
70
|
+
const row = BucketRow.safeParse(readBucket.get(k));
|
|
71
|
+
return row.success ? row.data : void 0;
|
|
72
|
+
},
|
|
73
|
+
set: (k, b) => void writeBucket.run(k, b.tokens, b.ts, bucketExpiry(b, rule, idle))
|
|
74
|
+
};
|
|
75
|
+
const result = atomic(db, () => applyHit({
|
|
76
|
+
counters,
|
|
77
|
+
buckets
|
|
78
|
+
}, key, rule, now, cost));
|
|
79
|
+
sweep();
|
|
80
|
+
return result;
|
|
81
|
+
},
|
|
82
|
+
reset(key) {
|
|
83
|
+
atomic(db, () => {
|
|
84
|
+
dropCounters.run(key, key, key);
|
|
85
|
+
dropBucket.run(key);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
export { sqliteRateStore };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ayepi/sqlite",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "SQLite backends for ayepi (better-sqlite3) — the @ayepi/work Queue, Store and PubSub, and an @ayepi/rate store, in one database file",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -32,6 +32,16 @@
|
|
|
32
32
|
"default": "./dist/index.cjs"
|
|
33
33
|
}
|
|
34
34
|
},
|
|
35
|
+
"./rate": {
|
|
36
|
+
"import": {
|
|
37
|
+
"types": "./dist/rate.d.ts",
|
|
38
|
+
"default": "./dist/rate.js"
|
|
39
|
+
},
|
|
40
|
+
"require": {
|
|
41
|
+
"types": "./dist/rate.d.cts",
|
|
42
|
+
"default": "./dist/rate.cjs"
|
|
43
|
+
}
|
|
44
|
+
},
|
|
35
45
|
"./package.json": "./package.json"
|
|
36
46
|
},
|
|
37
47
|
"engines": {
|
|
@@ -39,8 +49,8 @@
|
|
|
39
49
|
},
|
|
40
50
|
"peerDependencies": {
|
|
41
51
|
"zod": "^4.6.7",
|
|
42
|
-
"@ayepi/rate": "^0.
|
|
43
|
-
"@ayepi/work": "^0.
|
|
52
|
+
"@ayepi/rate": "^0.7.0",
|
|
53
|
+
"@ayepi/work": "^0.7.0"
|
|
44
54
|
},
|
|
45
55
|
"peerDependenciesMeta": {
|
|
46
56
|
"@ayepi/rate": {
|
|
@@ -58,9 +68,9 @@
|
|
|
58
68
|
"tsdown": "^0.12.0",
|
|
59
69
|
"vitest": "^2.1.8",
|
|
60
70
|
"zod": "^4.6.7",
|
|
61
|
-
"@ayepi/
|
|
62
|
-
"@ayepi/rate": "0.
|
|
63
|
-
"@ayepi/
|
|
71
|
+
"@ayepi/core": "0.7.0",
|
|
72
|
+
"@ayepi/rate": "0.7.0",
|
|
73
|
+
"@ayepi/work": "0.7.0"
|
|
64
74
|
},
|
|
65
75
|
"keywords": [
|
|
66
76
|
"ayepi",
|