@postgresx/noredis 0.1.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 +360 -0
- package/dist/adapters/bun.d.ts +13 -0
- package/dist/adapters/bun.js +15 -0
- package/dist/adapters/node.d.ts +22 -0
- package/dist/adapters/node.js +258 -0
- package/dist/chunk-GBFG2TOL.js +357 -0
- package/dist/index.d.ts +403 -0
- package/dist/index.js +1757 -0
- package/dist/kv-cache.d.ts +84 -0
- package/dist/kv-cache.js +8 -0
- package/dist/pubsub-CHGs5dXU.d.ts +60 -0
- package/dist/sql-DKf2TDlu.d.ts +10 -0
- package/package.json +49 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
// src/kv-cache.ts
|
|
2
|
+
var DEFAULT_TABLE_NAME = "pg_kv_cache";
|
|
3
|
+
var DEFAULT_NAMESPACE = "default";
|
|
4
|
+
var DEFAULT_L1_MAX = 1e4;
|
|
5
|
+
var DEFAULT_L1_TTL_MS = 6e4;
|
|
6
|
+
var DEFAULT_NOTIFY_CHANNEL = "pg_kv_cache_invalidate";
|
|
7
|
+
function randomId() {
|
|
8
|
+
const cryptoApi = globalThis.crypto;
|
|
9
|
+
if (cryptoApi?.randomUUID) return cryptoApi.randomUUID();
|
|
10
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
11
|
+
}
|
|
12
|
+
function quoteIdentifier(identifier) {
|
|
13
|
+
const trimmed = identifier.trim();
|
|
14
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(trimmed)) {
|
|
15
|
+
throw new Error(`Invalid SQL identifier: ${identifier}`);
|
|
16
|
+
}
|
|
17
|
+
return `"${trimmed.replaceAll('"', '""')}"`;
|
|
18
|
+
}
|
|
19
|
+
function quoteQualifiedName(name) {
|
|
20
|
+
const parts = name.split(".").map((part) => part.trim()).filter(Boolean);
|
|
21
|
+
if (parts.length === 0 || parts.length > 2) {
|
|
22
|
+
throw new Error(`Invalid SQL table name: ${name}`);
|
|
23
|
+
}
|
|
24
|
+
return parts.map(quoteIdentifier).join(".");
|
|
25
|
+
}
|
|
26
|
+
function indexName(tableName, suffix) {
|
|
27
|
+
const normalized = tableName.replace(/[^A-Za-z0-9_]/g, "_").replace(/^_+/, "").slice(0, 42) || DEFAULT_TABLE_NAME;
|
|
28
|
+
return quoteIdentifier(`idx_${normalized}_${suffix}`.slice(0, 63));
|
|
29
|
+
}
|
|
30
|
+
function jsonValue(value) {
|
|
31
|
+
return JSON.stringify(value);
|
|
32
|
+
}
|
|
33
|
+
function parseValue(value) {
|
|
34
|
+
if (typeof value !== "string") return value;
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(value);
|
|
37
|
+
} catch {
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function rowExpiresAt(row) {
|
|
42
|
+
if (!row.expires_at) return null;
|
|
43
|
+
if (row.expires_at instanceof Date) return row.expires_at.getTime();
|
|
44
|
+
const time = new Date(row.expires_at).getTime();
|
|
45
|
+
return Number.isFinite(time) ? time : null;
|
|
46
|
+
}
|
|
47
|
+
function normalizeTtlMs(ttlMs) {
|
|
48
|
+
if (ttlMs === null || ttlMs === void 0) return null;
|
|
49
|
+
if (!Number.isFinite(ttlMs)) throw new Error(`Invalid ttlMs: ${ttlMs}`);
|
|
50
|
+
return Math.max(0, Math.floor(ttlMs));
|
|
51
|
+
}
|
|
52
|
+
function escapeLike(value) {
|
|
53
|
+
return value.replace(/[\\%_]/g, (match) => `\\${match}`);
|
|
54
|
+
}
|
|
55
|
+
var PgKvCache = class {
|
|
56
|
+
namespace;
|
|
57
|
+
tableName;
|
|
58
|
+
quotedTableName;
|
|
59
|
+
notifyChannel;
|
|
60
|
+
instanceId;
|
|
61
|
+
sql;
|
|
62
|
+
now;
|
|
63
|
+
l1Enabled;
|
|
64
|
+
l1Max;
|
|
65
|
+
l1TtlMs;
|
|
66
|
+
notifyEnabled;
|
|
67
|
+
l1 = /* @__PURE__ */ new Map();
|
|
68
|
+
constructor(options) {
|
|
69
|
+
this.sql = options.sql;
|
|
70
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE;
|
|
71
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME;
|
|
72
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
73
|
+
this.now = options.now || Date.now;
|
|
74
|
+
this.instanceId = options.instanceId || randomId();
|
|
75
|
+
this.l1Enabled = options.l1 !== false;
|
|
76
|
+
this.l1Max = options.l1 && options.l1.max !== void 0 ? options.l1.max : DEFAULT_L1_MAX;
|
|
77
|
+
this.l1TtlMs = options.l1 && options.l1.ttlMs !== void 0 ? options.l1.ttlMs : DEFAULT_L1_TTL_MS;
|
|
78
|
+
this.notifyEnabled = options.notify !== false && options.notify?.enabled !== false;
|
|
79
|
+
this.notifyChannel = options.notify && options.notify.channel ? options.notify.channel : DEFAULT_NOTIFY_CHANNEL;
|
|
80
|
+
}
|
|
81
|
+
async ensureSchema(options = {}) {
|
|
82
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
83
|
+
await this.sql.unsafe(`
|
|
84
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
85
|
+
namespace TEXT NOT NULL,
|
|
86
|
+
key TEXT NOT NULL,
|
|
87
|
+
value JSONB NOT NULL,
|
|
88
|
+
expires_at TIMESTAMPTZ,
|
|
89
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
90
|
+
PRIMARY KEY (namespace, key)
|
|
91
|
+
)
|
|
92
|
+
`);
|
|
93
|
+
await this.sql.unsafe(`
|
|
94
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
95
|
+
ON ${this.quotedTableName} (expires_at)
|
|
96
|
+
WHERE expires_at IS NOT NULL
|
|
97
|
+
`);
|
|
98
|
+
await this.sql.unsafe(`
|
|
99
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "namespace_key_pattern")}
|
|
100
|
+
ON ${this.quotedTableName} (namespace, key text_pattern_ops)
|
|
101
|
+
`);
|
|
102
|
+
}
|
|
103
|
+
async get(key) {
|
|
104
|
+
const cached = this.getL1(key);
|
|
105
|
+
if (cached.hit) return cached.value;
|
|
106
|
+
const rows = await this.sql.unsafe(
|
|
107
|
+
`SELECT value, expires_at
|
|
108
|
+
FROM ${this.quotedTableName}
|
|
109
|
+
WHERE namespace = $1
|
|
110
|
+
AND key = $2
|
|
111
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
112
|
+
LIMIT 1`,
|
|
113
|
+
[this.namespace, key]
|
|
114
|
+
);
|
|
115
|
+
const row = rows[0];
|
|
116
|
+
if (!row) {
|
|
117
|
+
this.deleteL1(key);
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
const value = parseValue(row.value);
|
|
121
|
+
this.setL1(key, value, rowExpiresAt(row));
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
async mget(keys) {
|
|
125
|
+
const result = /* @__PURE__ */ new Map();
|
|
126
|
+
const missing = [];
|
|
127
|
+
for (const key of keys) {
|
|
128
|
+
const cached = this.getL1(key);
|
|
129
|
+
if (cached.hit) {
|
|
130
|
+
if (cached.value !== null) result.set(key, cached.value);
|
|
131
|
+
} else {
|
|
132
|
+
missing.push(key);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (missing.length === 0) return result;
|
|
136
|
+
const placeholders = missing.map((_, index) => `$${index + 2}`).join(", ");
|
|
137
|
+
const rows = await this.sql.unsafe(
|
|
138
|
+
`SELECT key, value, expires_at
|
|
139
|
+
FROM ${this.quotedTableName}
|
|
140
|
+
WHERE namespace = $1
|
|
141
|
+
AND key IN (${placeholders})
|
|
142
|
+
AND (expires_at IS NULL OR expires_at > NOW())`,
|
|
143
|
+
[this.namespace, ...missing]
|
|
144
|
+
);
|
|
145
|
+
for (const row of rows) {
|
|
146
|
+
if (!row.key) continue;
|
|
147
|
+
const value = parseValue(row.value);
|
|
148
|
+
result.set(row.key, value);
|
|
149
|
+
this.setL1(row.key, value, rowExpiresAt(row));
|
|
150
|
+
}
|
|
151
|
+
for (const key of missing) {
|
|
152
|
+
if (!result.has(key)) this.deleteL1(key);
|
|
153
|
+
}
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
async set(key, value, options = {}) {
|
|
157
|
+
const ttlMs = normalizeTtlMs(options.ttlMs);
|
|
158
|
+
await this.sql.unsafe(
|
|
159
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, value, expires_at, updated_at)
|
|
160
|
+
VALUES (
|
|
161
|
+
$1,
|
|
162
|
+
$2,
|
|
163
|
+
$3::jsonb,
|
|
164
|
+
CASE WHEN $4::bigint IS NULL THEN NULL ELSE NOW() + ($4::bigint * INTERVAL '1 millisecond') END,
|
|
165
|
+
NOW()
|
|
166
|
+
)
|
|
167
|
+
ON CONFLICT (namespace, key) DO UPDATE
|
|
168
|
+
SET value = EXCLUDED.value,
|
|
169
|
+
expires_at = EXCLUDED.expires_at,
|
|
170
|
+
updated_at = NOW()`,
|
|
171
|
+
[this.namespace, key, jsonValue(value), ttlMs]
|
|
172
|
+
);
|
|
173
|
+
this.setL1(key, value, ttlMs === null ? null : this.now() + ttlMs);
|
|
174
|
+
if (options.notify !== false) await this.publish({ op: "set", key });
|
|
175
|
+
}
|
|
176
|
+
async mset(entries, options = {}) {
|
|
177
|
+
const values = Array.from(entries);
|
|
178
|
+
if (values.length === 0) return;
|
|
179
|
+
const ttlMs = normalizeTtlMs(options.ttlMs);
|
|
180
|
+
const params = [];
|
|
181
|
+
const groups = values.map(([key, value], index) => {
|
|
182
|
+
const base = index * 4;
|
|
183
|
+
params.push(this.namespace, key, jsonValue(value), ttlMs);
|
|
184
|
+
return `($${base + 1}, $${base + 2}, $${base + 3}::jsonb, CASE WHEN $${base + 4}::bigint IS NULL THEN NULL ELSE NOW() + ($${base + 4}::bigint * INTERVAL '1 millisecond') END, NOW())`;
|
|
185
|
+
}).join(", ");
|
|
186
|
+
await this.sql.unsafe(
|
|
187
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, value, expires_at, updated_at)
|
|
188
|
+
VALUES ${groups}
|
|
189
|
+
ON CONFLICT (namespace, key) DO UPDATE
|
|
190
|
+
SET value = EXCLUDED.value,
|
|
191
|
+
expires_at = EXCLUDED.expires_at,
|
|
192
|
+
updated_at = NOW()`,
|
|
193
|
+
params
|
|
194
|
+
);
|
|
195
|
+
const expiresAt = ttlMs === null ? null : this.now() + ttlMs;
|
|
196
|
+
for (const [key, value] of values) {
|
|
197
|
+
this.setL1(key, value, expiresAt);
|
|
198
|
+
}
|
|
199
|
+
if (options.notify !== false) await this.publish({ op: "clearNamespace" });
|
|
200
|
+
}
|
|
201
|
+
async delete(key, options = {}) {
|
|
202
|
+
const rows = await this.sql.unsafe(
|
|
203
|
+
`DELETE FROM ${this.quotedTableName}
|
|
204
|
+
WHERE namespace = $1 AND key = $2
|
|
205
|
+
RETURNING key`,
|
|
206
|
+
[this.namespace, key]
|
|
207
|
+
);
|
|
208
|
+
this.deleteL1(key);
|
|
209
|
+
if (options.notify !== false) await this.publish({ op: "delete", key });
|
|
210
|
+
return rows.length > 0;
|
|
211
|
+
}
|
|
212
|
+
async clearPrefix(prefix, options = {}) {
|
|
213
|
+
const rows = await this.sql.unsafe(
|
|
214
|
+
`DELETE FROM ${this.quotedTableName}
|
|
215
|
+
WHERE namespace = $1 AND key LIKE $2 ESCAPE '\\'
|
|
216
|
+
RETURNING key`,
|
|
217
|
+
[this.namespace, `${escapeLike(prefix)}%`]
|
|
218
|
+
);
|
|
219
|
+
for (const row of rows) this.deleteL1(row.key);
|
|
220
|
+
if (options.notify !== false) await this.publish({ op: "clearPrefix", prefix });
|
|
221
|
+
return rows.length;
|
|
222
|
+
}
|
|
223
|
+
async clearNamespace(options = {}) {
|
|
224
|
+
const rows = await this.sql.unsafe(
|
|
225
|
+
`DELETE FROM ${this.quotedTableName}
|
|
226
|
+
WHERE namespace = $1
|
|
227
|
+
RETURNING key`,
|
|
228
|
+
[this.namespace]
|
|
229
|
+
);
|
|
230
|
+
this.l1.clear();
|
|
231
|
+
if (options.notify !== false) await this.publish({ op: "clearNamespace" });
|
|
232
|
+
return rows.length;
|
|
233
|
+
}
|
|
234
|
+
async cleanupExpired(limit = 1e3) {
|
|
235
|
+
const rows = await this.sql.unsafe(
|
|
236
|
+
`DELETE FROM ${this.quotedTableName}
|
|
237
|
+
WHERE ctid IN (
|
|
238
|
+
SELECT ctid
|
|
239
|
+
FROM ${this.quotedTableName}
|
|
240
|
+
WHERE expires_at IS NOT NULL AND expires_at <= NOW()
|
|
241
|
+
LIMIT $1
|
|
242
|
+
)
|
|
243
|
+
RETURNING namespace, key`,
|
|
244
|
+
[Math.max(1, Math.floor(limit))]
|
|
245
|
+
);
|
|
246
|
+
for (const row of rows) {
|
|
247
|
+
if (row.namespace === this.namespace) this.deleteL1(row.key);
|
|
248
|
+
}
|
|
249
|
+
this.cleanupL1();
|
|
250
|
+
return rows.length;
|
|
251
|
+
}
|
|
252
|
+
invalidate(key) {
|
|
253
|
+
this.deleteL1(key);
|
|
254
|
+
}
|
|
255
|
+
handleNotification(payload) {
|
|
256
|
+
const event = typeof payload === "string" ? this.parseNotification(payload) : payload;
|
|
257
|
+
if (!event || event.namespace !== this.namespace || event.senderId === this.instanceId) return false;
|
|
258
|
+
if (event.op === "set" || event.op === "delete") {
|
|
259
|
+
if (event.key) this.deleteL1(event.key);
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
if (event.op === "clearPrefix") {
|
|
263
|
+
if (!event.prefix) return false;
|
|
264
|
+
for (const key of this.l1.keys()) {
|
|
265
|
+
if (key.startsWith(event.prefix)) this.l1.delete(key);
|
|
266
|
+
}
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
if (event.op === "clearNamespace") {
|
|
270
|
+
this.l1.clear();
|
|
271
|
+
return true;
|
|
272
|
+
}
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
stats() {
|
|
276
|
+
this.cleanupL1();
|
|
277
|
+
return {
|
|
278
|
+
namespace: this.namespace,
|
|
279
|
+
tableName: this.tableName,
|
|
280
|
+
l1Size: this.l1.size,
|
|
281
|
+
l1Max: this.l1Max
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
async publish(event) {
|
|
285
|
+
if (!this.notifyEnabled) return;
|
|
286
|
+
const payload = {
|
|
287
|
+
namespace: this.namespace,
|
|
288
|
+
senderId: this.instanceId,
|
|
289
|
+
...event
|
|
290
|
+
};
|
|
291
|
+
await this.sql.unsafe("SELECT pg_notify($1, $2)", [this.notifyChannel, JSON.stringify(payload)]);
|
|
292
|
+
}
|
|
293
|
+
parseNotification(payload) {
|
|
294
|
+
try {
|
|
295
|
+
const value = JSON.parse(payload);
|
|
296
|
+
if (!value || typeof value !== "object") return null;
|
|
297
|
+
return value;
|
|
298
|
+
} catch {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
getL1(key) {
|
|
303
|
+
if (!this.l1Enabled) return { hit: false };
|
|
304
|
+
const entry = this.l1.get(key);
|
|
305
|
+
if (!entry) return { hit: false };
|
|
306
|
+
if (entry.expiresAt !== null && entry.expiresAt <= this.now()) {
|
|
307
|
+
this.l1.delete(key);
|
|
308
|
+
return { hit: false };
|
|
309
|
+
}
|
|
310
|
+
this.l1.delete(key);
|
|
311
|
+
this.l1.set(key, entry);
|
|
312
|
+
return { hit: true, value: entry.value };
|
|
313
|
+
}
|
|
314
|
+
setL1(key, value, l2ExpiresAt) {
|
|
315
|
+
if (!this.l1Enabled || this.l1Max <= 0) return;
|
|
316
|
+
const l1ExpiresAt = this.computeL1ExpiresAt(l2ExpiresAt);
|
|
317
|
+
if (l1ExpiresAt !== null && l1ExpiresAt <= this.now()) {
|
|
318
|
+
this.l1.delete(key);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
this.l1.delete(key);
|
|
322
|
+
this.l1.set(key, { value, expiresAt: l1ExpiresAt });
|
|
323
|
+
this.enforceL1Max();
|
|
324
|
+
}
|
|
325
|
+
computeL1ExpiresAt(l2ExpiresAt) {
|
|
326
|
+
const localExpiresAt = this.l1TtlMs > 0 ? this.now() + this.l1TtlMs : null;
|
|
327
|
+
if (l2ExpiresAt === null) return localExpiresAt;
|
|
328
|
+
if (localExpiresAt === null) return l2ExpiresAt;
|
|
329
|
+
return Math.min(localExpiresAt, l2ExpiresAt);
|
|
330
|
+
}
|
|
331
|
+
deleteL1(key) {
|
|
332
|
+
if (!this.l1Enabled) return;
|
|
333
|
+
this.l1.delete(key);
|
|
334
|
+
}
|
|
335
|
+
cleanupL1() {
|
|
336
|
+
if (!this.l1Enabled) return;
|
|
337
|
+
const now = this.now();
|
|
338
|
+
for (const [key, entry] of this.l1.entries()) {
|
|
339
|
+
if (entry.expiresAt !== null && entry.expiresAt <= now) this.l1.delete(key);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
enforceL1Max() {
|
|
343
|
+
while (this.l1.size > this.l1Max) {
|
|
344
|
+
const oldest = this.l1.keys().next();
|
|
345
|
+
if (oldest.done) return;
|
|
346
|
+
this.l1.delete(oldest.value);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
function createPgKvCache(options) {
|
|
351
|
+
return new PgKvCache(options);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export {
|
|
355
|
+
PgKvCache,
|
|
356
|
+
createPgKvCache
|
|
357
|
+
};
|