@ayepi/sqlite 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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.6.1",
3
+ "version": "0.8.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,15 +49,12 @@
39
49
  },
40
50
  "peerDependencies": {
41
51
  "zod": "^4.6.7",
42
- "@ayepi/rate": "^0.6.1",
43
- "@ayepi/work": "^0.6.1"
52
+ "@ayepi/rate": "^0.8.0",
53
+ "@ayepi/work": "^0.8.0"
44
54
  },
45
55
  "peerDependenciesMeta": {
46
56
  "@ayepi/rate": {
47
57
  "optional": true
48
- },
49
- "@ayepi/work": {
50
- "optional": true
51
58
  }
52
59
  },
53
60
  "devDependencies": {
@@ -58,9 +65,9 @@
58
65
  "tsdown": "^0.12.0",
59
66
  "vitest": "^2.1.8",
60
67
  "zod": "^4.6.7",
61
- "@ayepi/work": "0.6.1",
62
- "@ayepi/rate": "0.6.1",
63
- "@ayepi/core": "0.6.1"
68
+ "@ayepi/core": "0.8.0",
69
+ "@ayepi/rate": "0.8.0",
70
+ "@ayepi/work": "0.8.0"
64
71
  },
65
72
  "keywords": [
66
73
  "ayepi",