@fedify/sqlite 1.8.1-dev.1257

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/kv.ts ADDED
@@ -0,0 +1,283 @@
1
+ import { type PlatformDatabase, SqliteDatabase } from "#sqlite";
2
+ import type { KvKey, KvStore, KvStoreSetOptions } from "@fedify/fedify";
3
+ import { Temporal } from "@js-temporal/polyfill";
4
+ import { getLogger } from "@logtape/logtape";
5
+ import { isEqual } from "es-toolkit";
6
+ import type { SqliteDatabaseAdapter } from "./adapter.ts";
7
+
8
+ const logger = getLogger(["fedify", "sqlite", "kv"]);
9
+
10
+ /**
11
+ * Options for the SQLite key–value store.
12
+ */
13
+ export interface SqliteKvStoreOptions {
14
+ /**
15
+ * The table name to use for the key–value store.
16
+ * Only letters, digits, and underscores are allowed.
17
+ * `"fedify_kv"` by default.
18
+ * @default `"fedify_kv"`
19
+ */
20
+ tableName?: string;
21
+
22
+ /**
23
+ * Whether the table has been initialized. `false` by default.
24
+ * @default `false`
25
+ */
26
+ initialized?: boolean;
27
+ }
28
+
29
+ /**
30
+ * A key–value store that uses SQLite as the underlying storage.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { createFederation } from "@fedify/fedify";
35
+ * import { SqliteKvStore } from "@fedify/sqlite";
36
+ * import { DatabaseSync } from "node:sqlite";
37
+ *
38
+ * const db = new DatabaseSync(":memory:");
39
+ * const federation = createFederation({
40
+ * // ...
41
+ * kv: new SqliteKvStore(db),
42
+ * });
43
+ * ```
44
+ */
45
+ export class SqliteKvStore implements KvStore {
46
+ static readonly #defaultTableName = "fedify_kv";
47
+ static readonly #tableNameRegex = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
48
+ readonly #db: SqliteDatabaseAdapter;
49
+ readonly #tableName: string;
50
+ #initialized: boolean;
51
+
52
+ /**
53
+ * Creates a new SQLite key–value store.
54
+ * @param db The SQLite database to use. Supports `node:sqlite` and `bun:sqlite`.
55
+ * @param options The options for the key–value store.
56
+ */
57
+ constructor(
58
+ readonly db: PlatformDatabase,
59
+ readonly options: SqliteKvStoreOptions = {},
60
+ ) {
61
+ this.#db = new SqliteDatabase(db);
62
+ this.#initialized = options.initialized ?? false;
63
+ this.#tableName = options.tableName ?? SqliteKvStore.#defaultTableName;
64
+
65
+ if (!SqliteKvStore.#tableNameRegex.test(this.#tableName)) {
66
+ throw new Error(
67
+ `Invalid table name for the key–value store: ${this.#tableName}`,
68
+ );
69
+ }
70
+ }
71
+
72
+ /**
73
+ * {@inheritDoc KvStore.get}
74
+ */
75
+ // deno-lint-ignore require-await
76
+ async get<T = unknown>(key: KvKey): Promise<T | undefined> {
77
+ this.initialize();
78
+
79
+ const encodedKey = this.#encodeKey(key);
80
+ const now = Temporal.Now.instant().epochMilliseconds;
81
+
82
+ const result = this.#db
83
+ .prepare(`
84
+ SELECT value
85
+ FROM "${this.#tableName}"
86
+ WHERE key = ? AND (expires IS NULL OR expires > ?)
87
+ `)
88
+ .get(encodedKey, now);
89
+
90
+ if (!result) {
91
+ return undefined;
92
+ }
93
+ return this.#decodeValue((result as { value: string }).value) as T;
94
+ }
95
+
96
+ /**
97
+ * {@inheritDoc KvStore.set}
98
+ */
99
+ // deno-lint-ignore require-await
100
+ async set(
101
+ key: KvKey,
102
+ value: unknown,
103
+ options?: KvStoreSetOptions,
104
+ ): Promise<void> {
105
+ this.initialize();
106
+
107
+ if (value === undefined) {
108
+ return;
109
+ }
110
+
111
+ const encodedKey = this.#encodeKey(key);
112
+ const encodedValue = this.#encodeValue(value);
113
+ const now = Temporal.Now.instant().epochMilliseconds;
114
+ const expiresAt = options?.ttl !== undefined
115
+ ? now + options.ttl.total({ unit: "milliseconds" })
116
+ : null;
117
+
118
+ this.#db
119
+ .prepare(
120
+ `INSERT INTO "${this.#tableName}" (key, value, created, expires)
121
+ VALUES (?, ?, ?, ?)
122
+ ON CONFLICT(key) DO UPDATE SET
123
+ value = excluded.value,
124
+ expires = excluded.expires`,
125
+ )
126
+ .run(encodedKey, encodedValue, now, expiresAt);
127
+
128
+ this.#expire();
129
+ return;
130
+ }
131
+
132
+ /**
133
+ * {@inheritDoc KvStore.delete}
134
+ */
135
+ // deno-lint-ignore require-await
136
+ async delete(key: KvKey): Promise<void> {
137
+ this.initialize();
138
+
139
+ const encodedKey = this.#encodeKey(key);
140
+
141
+ this.#db
142
+ .prepare(`
143
+ DELETE FROM "${this.#tableName}" WHERE key = ?
144
+ `)
145
+ .run(encodedKey);
146
+ this.#expire();
147
+ return Promise.resolve();
148
+ }
149
+
150
+ /**
151
+ * {@inheritDoc KvStore.cas}
152
+ */
153
+ // deno-lint-ignore require-await
154
+ async cas(
155
+ key: KvKey,
156
+ expectedValue: unknown,
157
+ newValue: unknown,
158
+ options?: KvStoreSetOptions,
159
+ ): Promise<boolean> {
160
+ this.initialize();
161
+
162
+ const encodedKey = this.#encodeKey(key);
163
+ const now = Temporal.Now.instant().epochMilliseconds;
164
+ const expiresAt = options?.ttl !== undefined
165
+ ? now + options.ttl.total({ unit: "milliseconds" })
166
+ : null;
167
+
168
+ try {
169
+ this.#db.exec("BEGIN IMMEDIATE");
170
+
171
+ const currentResult = this.#db
172
+ .prepare(`
173
+ SELECT value
174
+ FROM "${this.#tableName}"
175
+ WHERE key = ? AND (expires IS NULL OR expires > ?)
176
+ `)
177
+ .get(encodedKey, now) as { value: string } | undefined;
178
+ const currentValue = currentResult === undefined
179
+ ? undefined
180
+ : this.#decodeValue(currentResult.value);
181
+
182
+ if (!isEqual(currentValue, expectedValue)) {
183
+ this.#db.exec("ROLLBACK");
184
+ return false;
185
+ }
186
+
187
+ if (newValue === undefined) {
188
+ this.#db
189
+ .prepare(`
190
+ DELETE FROM "${this.#tableName}" WHERE key = ?
191
+ `)
192
+ .run(encodedKey);
193
+ } else {
194
+ const newValueJson = this.#encodeValue(newValue);
195
+
196
+ this.#db
197
+ .prepare(`
198
+ INSERT INTO "${this.#tableName}" (key, value, created, expires)
199
+ VALUES (?, ?, ?, ?)
200
+ ON CONFLICT(key) DO UPDATE SET
201
+ value = excluded.value,
202
+ expires = excluded.expires
203
+ `)
204
+ .run(encodedKey, newValueJson, now, expiresAt);
205
+ }
206
+
207
+ this.#db.exec("COMMIT");
208
+ this.#expire();
209
+ return true;
210
+ } catch (error) {
211
+ this.#db.exec("ROLLBACK");
212
+ throw error;
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Creates the table used by the key–value store if it does not already exist.
218
+ * Does nothing if the table already exists.
219
+ */
220
+ initialize() {
221
+ if (this.#initialized) {
222
+ return;
223
+ }
224
+
225
+ logger.debug("Initializing the key–value store table {tableName}...", {
226
+ tableName: this.#tableName,
227
+ });
228
+
229
+ this.#db.exec(`
230
+ CREATE TABLE IF NOT EXISTS "${this.#tableName}" (
231
+ key TEXT PRIMARY KEY,
232
+ value TEXT NOT NULL,
233
+ created INTEGER NOT NULL,
234
+ expires INTEGER
235
+ )
236
+ `);
237
+
238
+ this.#db.exec(`
239
+ CREATE INDEX IF NOT EXISTS "idx_${this.#tableName}_expires"
240
+ ON "${this.#tableName}" (expires)
241
+ `);
242
+
243
+ this.#initialized = true;
244
+ logger.debug("Initialized the key–value store table {tableName}.", {
245
+ tableName: this.#tableName,
246
+ });
247
+ }
248
+
249
+ #expire() {
250
+ const now = Temporal.Now.instant().epochMilliseconds;
251
+ this.#db
252
+ .prepare(`
253
+ DELETE FROM "${this.#tableName}"
254
+ WHERE expires IS NOT NULL AND expires <= ?
255
+ `)
256
+ .run(now);
257
+ }
258
+
259
+ /**
260
+ * Drops the table used by the key–value store. Does nothing if the table
261
+ * does not exist.
262
+ */
263
+ drop() {
264
+ this.#db.exec(`DROP TABLE IF EXISTS "${this.#tableName}"`);
265
+ this.#initialized = false;
266
+ }
267
+
268
+ #encodeKey(key: KvKey): string {
269
+ return JSON.stringify(key);
270
+ }
271
+
272
+ #decodeKey(key: string): KvKey {
273
+ return JSON.parse(key);
274
+ }
275
+
276
+ #encodeValue(value: unknown): string {
277
+ return JSON.stringify(value);
278
+ }
279
+
280
+ #decodeValue(value: string): unknown {
281
+ return JSON.parse(value);
282
+ }
283
+ }
package/mod.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * SQLite drivers for Fedify.
3
+ * @module
4
+ */
5
+ export { SqliteKvStore } from "./kv.ts";
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@fedify/sqlite",
3
+ "version": "1.8.1-dev.1257+0f5c486a",
4
+ "description": "SQLite drivers for Fedify",
5
+ "keywords": [
6
+ "fedify",
7
+ "sqlite"
8
+ ],
9
+ "license": "MIT",
10
+ "author": "An Nyeong <me@annyeong.me>",
11
+ "homepage": "https://fedify.dev/",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/fedify-dev/fedify.git",
15
+ "directory": "sqlite"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/fedify-dev/fedify/issues"
19
+ },
20
+ "funding": [
21
+ "https://opencollective.com/fedify",
22
+ "https://github.com/sponsors/dahlia"
23
+ ],
24
+ "type": "module",
25
+ "main": "./dist/mod.js",
26
+ "module": "./dist/mod.js",
27
+ "types": "./dist/mod.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/mod.d.ts",
31
+ "import": "./dist/mod.js",
32
+ "default": "./dist/mod.js"
33
+ },
34
+ "./kv": {
35
+ "types": "./dist/kv.d.ts",
36
+ "import": "./dist/kv.js",
37
+ "default": "./dist/kv.js"
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "imports": {
42
+ "#sqlite": {
43
+ "bun": "./dist/sqlite.bun.js",
44
+ "deno": "./dist/sqlite.node.js",
45
+ "import": "./dist/sqlite.node.js",
46
+ "require": "./dist/sqlite.node.cjs"
47
+ }
48
+ },
49
+ "dependencies": {
50
+ "@logtape/logtape": "^1.0.0",
51
+ "es-toolkit": "^1.31.0"
52
+ },
53
+ "peerDependencies": {
54
+ "@fedify/fedify": "1.8.1-dev.1257+0f5c486a"
55
+ },
56
+ "devDependencies": {
57
+ "@js-temporal/polyfill": "^0.5.1",
58
+ "@std/async": "npm:@jsr/std__async@^1.0.13",
59
+ "tsdown": "^0.12.9",
60
+ "typescript": "^5.8.3"
61
+ },
62
+ "scripts": {
63
+ "build": "tsdown",
64
+ "prepublish": "tsdown",
65
+ "test": "tsdown && node --experimental-transform-types --test kv.test.ts",
66
+ "test:bun": "tsdown && bun test --timeout=10000 kv.test.ts",
67
+ "test:deno": "tsdown && deno test kv.test.ts"
68
+ }
69
+ }
package/sqlite.bun.ts ADDED
@@ -0,0 +1,45 @@
1
+ import { Database, type Statement } from "bun:sqlite";
2
+ import type {
3
+ SqliteDatabaseAdapter,
4
+ SqliteStatementAdapter,
5
+ } from "./adapter.ts";
6
+
7
+ export { Database as PlatformDatabase };
8
+ export type { Statement as PlatformStatement };
9
+
10
+ export class SqliteDatabase implements SqliteDatabaseAdapter {
11
+ constructor(private readonly db: Database) {}
12
+
13
+ prepare(sql: string): SqliteStatementAdapter {
14
+ return new SqliteStatement(this.db.query(sql));
15
+ }
16
+
17
+ exec(sql: string): void {
18
+ this.db.exec(sql);
19
+ }
20
+
21
+ close(): void {
22
+ this.db.close(false);
23
+ }
24
+ }
25
+
26
+ export class SqliteStatement implements SqliteStatementAdapter {
27
+ constructor(private readonly stmt: Statement) {}
28
+
29
+ run(...params: unknown[]): { changes: number; lastInsertRowid: number } {
30
+ return this.stmt.run(...params);
31
+ }
32
+
33
+ get(...params: unknown[]): unknown | undefined {
34
+ const result = this.stmt.get(...params);
35
+ // to make the return type compatible with the node version
36
+ if (result === null) {
37
+ return undefined;
38
+ }
39
+ return result;
40
+ }
41
+
42
+ all(...params: unknown[]): unknown[] {
43
+ return this.stmt.all(...params);
44
+ }
45
+ }
package/sqlite.node.ts ADDED
@@ -0,0 +1,48 @@
1
+ import {
2
+ DatabaseSync,
3
+ type SQLInputValue,
4
+ type StatementSync,
5
+ } from "node:sqlite";
6
+ import type {
7
+ SqliteDatabaseAdapter,
8
+ SqliteStatementAdapter,
9
+ } from "./adapter.ts";
10
+
11
+ export { DatabaseSync as PlatformDatabase };
12
+ export type { StatementSync as PlatformStatement };
13
+
14
+ export class SqliteDatabase implements SqliteDatabaseAdapter {
15
+ constructor(private readonly db: DatabaseSync) {}
16
+
17
+ prepare(sql: string): SqliteStatementAdapter {
18
+ return new SqliteStatement(this.db.prepare(sql));
19
+ }
20
+
21
+ exec(sql: string): void {
22
+ this.db.exec(sql);
23
+ }
24
+
25
+ close(): void {
26
+ this.db.close();
27
+ }
28
+ }
29
+
30
+ export class SqliteStatement implements SqliteStatementAdapter {
31
+ constructor(private readonly stmt: StatementSync) {}
32
+
33
+ run(...params: unknown[]): { changes: number; lastInsertRowid: number } {
34
+ const result = this.stmt.run(...params as SQLInputValue[]);
35
+ return {
36
+ changes: Number(result.changes),
37
+ lastInsertRowid: Number(result.lastInsertRowid),
38
+ };
39
+ }
40
+
41
+ get(...params: unknown[]): unknown | undefined {
42
+ return this.stmt.get(...params as SQLInputValue[]);
43
+ }
44
+
45
+ all(...params: unknown[]): unknown[] {
46
+ return this.stmt.all(...params as SQLInputValue[]);
47
+ }
48
+ }
@@ -0,0 +1,24 @@
1
+ import { defineConfig } from "tsdown";
2
+
3
+ export default defineConfig({
4
+ entry: ["mod.ts", "kv.ts", "sqlite.node.ts", "sqlite.bun.ts"],
5
+ dts: true,
6
+ unbundle: true,
7
+ platform: "node",
8
+ inputOptions: {
9
+ onwarn(warning, defaultHandler) {
10
+ if (
11
+ warning.code === "UNRESOLVED_IMPORT" &&
12
+ ["#sqlite", "bun:sqlite"].includes(warning.exporter ?? "")
13
+ ) {
14
+ return;
15
+ }
16
+ defaultHandler(warning);
17
+ },
18
+ },
19
+ outputOptions: {
20
+ intro: `
21
+ import { Temporal } from "@js-temporal/polyfill";
22
+ `,
23
+ },
24
+ });