-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
210 lines (181 loc) · 5.53 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import { Database } from 'bun:sqlite';
import type { Store, Config } from 'cache-manager';
import * as cbor from 'cbor-x';
import * as msgpackr from 'msgpackr';
const configurePragmas = `
PRAGMA main.synchronous = NORMAL;
PRAGMA main.journal_mode = WAL2;
PRAGMA main.auto_vacuum = INCREMENTAL;
`;
const createTableStm = `
CREATE TABLE IF NOT EXISTS {table} (
key TEXT PRIMARY KEY,
val BLOB,
created_at INTEGER,
expire_at INTEGER
);
CREATE INDEX IF NOT EXISTS index_expire_{table} ON {table}(expire_at);
`;
interface CacheRow {
key: string;
val: string & (Uint8Array | Buffer);
created_at: number;
expire_at: number;
}
const serializers = {
json: {
serialize: JSON.stringify,
deserialize: JSON.parse,
},
cbor: {
serialize: cbor.encode,
deserialize: cbor.decode,
},
msgpackr: {
serialize: msgpackr.pack,
deserialize: msgpackr.unpack,
},
};
type SqliteCacheOptions = Config & {
name?: string;
path?: string;
serializer?: 'msgpackr' | 'cbor' | 'json';
ttl?: number;
};
export interface SqliteStore extends Store {
name: string;
isCacheable: (value: unknown) => boolean;
get client(): Database;
}
export class NoCacheableError implements Error {
name = 'NoCacheableError';
constructor(public message: string) {}
}
export default async function bunSqliteStore({
name = 'cache',
path = ':memory:',
serializer = 'msgpackr',
ttl = 24 * 60 * 60, // 1 day in seconds
...options
}: SqliteCacheOptions = {}): Promise<SqliteStore> {
const db = new Database(path);
const serializerAdapter = serializers[serializer];
const defaultTtl = ttl * 1000;
let lastPurgeTime = 0;
try {
db.exec(configurePragmas);
const stmt = createTableStm.replace(/{table}/g, name);
db.exec(stmt);
} catch (err) {
throw new Error(`Failed to initialize SQLite store: ${err}`);
}
const isCacheable =
options?.isCacheable ||
(value => value !== undefined && value !== null && typeof value !== 'function');
const purgeExpired = async () => {
const now = Date.now();
if (now - lastPurgeTime >= 60 * 60 * 1000) {
// One hour
const statement = db.prepare(`DELETE FROM ${name} WHERE expire_at < ?`);
statement.run(now);
lastPurgeTime = now;
}
};
const set = async (key: string, value: unknown, ttl?: number) => {
const ttlValue = ttl !== undefined ? ttl * 1000 : defaultTtl;
if (ttlValue < 0) {
return;
}
if (!isCacheable(value)) {
throw new NoCacheableError(`"${value}" is not a cacheable value`);
}
const expireAt = Date.now() + ttlValue;
const serializedVal = serializerAdapter.serialize(value);
const statement = db.prepare(
`INSERT OR REPLACE INTO ${name}(key, val, created_at, expire_at) VALUES (?, ?, ?, ?)`
);
statement.run(key, serializedVal, Date.now(), expireAt);
};
const get = async <T>(key: string): Promise<T | undefined> => {
await purgeExpired();
const statement = db.prepare(
`SELECT * FROM ${name} WHERE key = ? AND expire_at > ? LIMIT 1`
);
const rows = statement.all(key, Date.now()) as CacheRow[];
if (rows.length > 0) {
return serializerAdapter.deserialize(rows[0].val) as T;
}
};
const del = async (key: string) => {
const statement = db.prepare(`DELETE FROM ${name} WHERE key = ?`);
statement.run(key);
};
const mset = async (pairs: [string, unknown][], ttl?: number) => {
const ttlValue = ttl !== undefined ? ttl * 1000 : defaultTtl;
if (ttlValue < 0) {
return;
}
const expireAt = Date.now() + ttlValue;
const stmt = `INSERT OR REPLACE INTO ${name} (key, val, created_at, expire_at) VALUES ${pairs.map(() => '(?, ?, ?, ?)').join(', ')}`;
const bindings = pairs.flatMap(([key, value]) => {
if (!isCacheable(value)) {
throw new NoCacheableError(`"${value}" is not a cacheable value`);
}
return [key, serializerAdapter.serialize(value), Date.now(), expireAt];
});
const statement = db.prepare(stmt);
statement.run(...bindings);
};
const mget = async <T>(...keys: string[]): Promise<(T | undefined)[]> => {
await purgeExpired();
const placeholders = keys.map(() => '?').join(', ');
const statement = db.prepare(
`SELECT * FROM ${name} WHERE key IN (${placeholders}) AND expire_at > ?`
);
const rows = statement.all(...keys, Date.now()) as CacheRow[];
return keys.map(key => {
const row = rows.find(r => r.key === key);
return row ? (serializerAdapter.deserialize(row.val) as T) : undefined;
});
};
const mdel = async (...keys: string[]) => {
const placeholders = keys.map(() => '?').join(', ');
const statement = db.prepare(`DELETE FROM ${name} WHERE key IN (${placeholders})`);
statement.run(...keys);
};
const keys = async (): Promise<string[]> => {
await purgeExpired();
const statement = db.prepare(`SELECT key FROM ${name}`);
const rows = statement.all() as CacheRow[];
return rows.map(row => row.key);
};
const reset = async () => {
const statement = db.prepare(`DELETE FROM ${name}`);
statement.run();
};
const ttlFn = async (key: string): Promise<number> => {
await purgeExpired();
const statement = db.prepare(`SELECT expire_at FROM ${name} WHERE key = ?`);
const rows = statement.all(key) as CacheRow[];
if (rows.length > 0) {
return rows[0].expire_at - Date.now();
}
return -1;
};
return {
name,
get,
set,
mset,
mget,
del,
mdel,
keys,
reset,
ttl: ttlFn,
isCacheable,
get client() {
return db;
},
};
}