@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
package/dist/index.js
ADDED
|
@@ -0,0 +1,1757 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PgKvCache,
|
|
3
|
+
createPgKvCache
|
|
4
|
+
} from "./chunk-GBFG2TOL.js";
|
|
5
|
+
|
|
6
|
+
// src/advisory-lock.ts
|
|
7
|
+
var PgAdvisoryLockBusyError = class extends Error {
|
|
8
|
+
key;
|
|
9
|
+
constructor(key) {
|
|
10
|
+
super(`Postgres advisory lock is busy: ${String(key)}`);
|
|
11
|
+
this.name = "PgAdvisoryLockBusyError";
|
|
12
|
+
this.key = key;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
function toInt32(value) {
|
|
16
|
+
return value | 0;
|
|
17
|
+
}
|
|
18
|
+
function fnv1a32(input, seed) {
|
|
19
|
+
let hash = seed >>> 0;
|
|
20
|
+
for (let index = 0; index < input.length; index++) {
|
|
21
|
+
hash ^= input.charCodeAt(index);
|
|
22
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
23
|
+
}
|
|
24
|
+
return toInt32(hash);
|
|
25
|
+
}
|
|
26
|
+
function advisoryLockKeyToSqlArgs(key) {
|
|
27
|
+
if (Array.isArray(key)) {
|
|
28
|
+
return {
|
|
29
|
+
expression: "$1::int, $2::int",
|
|
30
|
+
params: [toInt32(key[0]), toInt32(key[1])]
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (typeof key === "bigint") {
|
|
34
|
+
return {
|
|
35
|
+
expression: "$1::bigint",
|
|
36
|
+
params: [key.toString()]
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
if (typeof key === "number") {
|
|
40
|
+
if (!Number.isSafeInteger(key)) throw new Error(`Invalid advisory lock number key: ${key}`);
|
|
41
|
+
return {
|
|
42
|
+
expression: "$1::bigint",
|
|
43
|
+
params: [Math.trunc(key)]
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
if (typeof key === "string") {
|
|
47
|
+
return {
|
|
48
|
+
expression: "$1::int, $2::int",
|
|
49
|
+
params: [fnv1a32(key, 2166136261), fnv1a32(key, 2166136261 ^ 2654435769)]
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
throw new Error("Invalid advisory lock key");
|
|
53
|
+
}
|
|
54
|
+
async function withPgAdvisoryLock(sql, key, callback, options = {}) {
|
|
55
|
+
const runInTransaction = options.transaction ?? sql.begin?.bind(sql);
|
|
56
|
+
if (!runInTransaction) {
|
|
57
|
+
throw new Error("withPgAdvisoryLock requires a transaction-capable sql adapter");
|
|
58
|
+
}
|
|
59
|
+
return runInTransaction(async (tx) => {
|
|
60
|
+
const args = advisoryLockKeyToSqlArgs(key);
|
|
61
|
+
if (options.lockTimeoutMs !== void 0) {
|
|
62
|
+
const timeoutMs = Math.max(1, Math.floor(options.lockTimeoutMs));
|
|
63
|
+
await tx.unsafe("SELECT set_config('lock_timeout', $1, true)", [`${timeoutMs}ms`]);
|
|
64
|
+
}
|
|
65
|
+
if (options.wait === false) {
|
|
66
|
+
const rows = await tx.unsafe(
|
|
67
|
+
`SELECT pg_try_advisory_xact_lock(${args.expression}) AS locked`,
|
|
68
|
+
args.params
|
|
69
|
+
);
|
|
70
|
+
if (!rows[0]?.locked) throw new PgAdvisoryLockBusyError(key);
|
|
71
|
+
} else {
|
|
72
|
+
await tx.unsafe(`SELECT pg_advisory_xact_lock(${args.expression})`, args.params);
|
|
73
|
+
}
|
|
74
|
+
return callback(tx);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
var PgAdvisoryLocker = class {
|
|
78
|
+
constructor(sql) {
|
|
79
|
+
this.sql = sql;
|
|
80
|
+
}
|
|
81
|
+
sql;
|
|
82
|
+
withLock(key, callback, options) {
|
|
83
|
+
return withPgAdvisoryLock(this.sql, key, callback, options);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
function createPgAdvisoryLocker(sql) {
|
|
87
|
+
return new PgAdvisoryLocker(sql);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/sql.ts
|
|
91
|
+
function quoteIdentifier(identifier) {
|
|
92
|
+
const trimmed = identifier.trim();
|
|
93
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(trimmed)) {
|
|
94
|
+
throw new Error(`Invalid SQL identifier: ${identifier}`);
|
|
95
|
+
}
|
|
96
|
+
return `"${trimmed.replaceAll('"', '""')}"`;
|
|
97
|
+
}
|
|
98
|
+
function quoteQualifiedName(name) {
|
|
99
|
+
const parts = name.split(".").map((part) => part.trim()).filter(Boolean);
|
|
100
|
+
if (parts.length === 0 || parts.length > 2) {
|
|
101
|
+
throw new Error(`Invalid SQL table name: ${name}`);
|
|
102
|
+
}
|
|
103
|
+
return parts.map(quoteIdentifier).join(".");
|
|
104
|
+
}
|
|
105
|
+
function indexName(tableName2, suffix) {
|
|
106
|
+
const normalized = tableName2.replace(/[^A-Za-z0-9_]/g, "_").replace(/^_+/, "").slice(0, 42) || "pg_redis_kit";
|
|
107
|
+
return quoteIdentifier(`idx_${normalized}_${suffix}`.slice(0, 63));
|
|
108
|
+
}
|
|
109
|
+
function normalizePositiveInteger(value, name) {
|
|
110
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive number`);
|
|
111
|
+
return Math.floor(value);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// src/counter.ts
|
|
115
|
+
var DEFAULT_TABLE_NAME = "pgredis_counter";
|
|
116
|
+
var DEFAULT_NAMESPACE = "default";
|
|
117
|
+
function normalizeTtlMs(ttlMs) {
|
|
118
|
+
if (ttlMs === null || ttlMs === void 0) return null;
|
|
119
|
+
if (!Number.isFinite(ttlMs)) throw new Error(`Invalid ttlMs: ${ttlMs}`);
|
|
120
|
+
return Math.max(0, Math.floor(ttlMs));
|
|
121
|
+
}
|
|
122
|
+
var PgCounter = class {
|
|
123
|
+
namespace;
|
|
124
|
+
tableName;
|
|
125
|
+
quotedTableName;
|
|
126
|
+
sql;
|
|
127
|
+
constructor(options) {
|
|
128
|
+
this.sql = options.sql;
|
|
129
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE;
|
|
130
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME;
|
|
131
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
132
|
+
}
|
|
133
|
+
async ensureSchema(options = {}) {
|
|
134
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
135
|
+
await this.sql.unsafe(`
|
|
136
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
137
|
+
namespace TEXT NOT NULL,
|
|
138
|
+
key TEXT NOT NULL,
|
|
139
|
+
value BIGINT NOT NULL,
|
|
140
|
+
expires_at TIMESTAMPTZ,
|
|
141
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
142
|
+
PRIMARY KEY (namespace, key)
|
|
143
|
+
)
|
|
144
|
+
`);
|
|
145
|
+
await this.sql.unsafe(`
|
|
146
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
147
|
+
ON ${this.quotedTableName} (expires_at)
|
|
148
|
+
WHERE expires_at IS NOT NULL
|
|
149
|
+
`);
|
|
150
|
+
}
|
|
151
|
+
async get(key) {
|
|
152
|
+
const rows = await this.sql.unsafe(
|
|
153
|
+
`SELECT value
|
|
154
|
+
FROM ${this.quotedTableName}
|
|
155
|
+
WHERE namespace = $1
|
|
156
|
+
AND key = $2
|
|
157
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
158
|
+
LIMIT 1`,
|
|
159
|
+
[this.namespace, key]
|
|
160
|
+
);
|
|
161
|
+
return rows[0] ? Number(rows[0].value) : null;
|
|
162
|
+
}
|
|
163
|
+
async set(key, value, options = {}) {
|
|
164
|
+
if (!Number.isSafeInteger(value)) throw new Error(`Invalid counter value: ${value}`);
|
|
165
|
+
const ttlMs = normalizeTtlMs(options.ttlMs);
|
|
166
|
+
const rows = await this.sql.unsafe(
|
|
167
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, value, expires_at, updated_at)
|
|
168
|
+
VALUES (
|
|
169
|
+
$1,
|
|
170
|
+
$2,
|
|
171
|
+
$3,
|
|
172
|
+
CASE WHEN $4::bigint IS NULL THEN NULL ELSE NOW() + ($4::bigint * INTERVAL '1 millisecond') END,
|
|
173
|
+
NOW()
|
|
174
|
+
)
|
|
175
|
+
ON CONFLICT (namespace, key) DO UPDATE
|
|
176
|
+
SET value = EXCLUDED.value,
|
|
177
|
+
expires_at = EXCLUDED.expires_at,
|
|
178
|
+
updated_at = NOW()
|
|
179
|
+
RETURNING value`,
|
|
180
|
+
[this.namespace, key, Math.trunc(value), ttlMs]
|
|
181
|
+
);
|
|
182
|
+
return Number(rows[0]?.value ?? value);
|
|
183
|
+
}
|
|
184
|
+
async incr(key, amount = 1, options = {}) {
|
|
185
|
+
if (!Number.isSafeInteger(amount)) throw new Error(`Invalid counter increment: ${amount}`);
|
|
186
|
+
const ttlMs = normalizeTtlMs(options.ttlMs);
|
|
187
|
+
const rows = await this.sql.unsafe(
|
|
188
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, value, expires_at, updated_at)
|
|
189
|
+
VALUES (
|
|
190
|
+
$1,
|
|
191
|
+
$2,
|
|
192
|
+
$3,
|
|
193
|
+
CASE WHEN $4::bigint IS NULL THEN NULL ELSE NOW() + ($4::bigint * INTERVAL '1 millisecond') END,
|
|
194
|
+
NOW()
|
|
195
|
+
)
|
|
196
|
+
ON CONFLICT (namespace, key) DO UPDATE
|
|
197
|
+
SET value = CASE
|
|
198
|
+
WHEN ${this.quotedTableName}.expires_at IS NOT NULL AND ${this.quotedTableName}.expires_at <= NOW()
|
|
199
|
+
THEN EXCLUDED.value
|
|
200
|
+
ELSE ${this.quotedTableName}.value + EXCLUDED.value
|
|
201
|
+
END,
|
|
202
|
+
expires_at = COALESCE(EXCLUDED.expires_at, ${this.quotedTableName}.expires_at),
|
|
203
|
+
updated_at = NOW()
|
|
204
|
+
RETURNING value`,
|
|
205
|
+
[this.namespace, key, Math.trunc(amount), ttlMs]
|
|
206
|
+
);
|
|
207
|
+
return Number(rows[0]?.value ?? amount);
|
|
208
|
+
}
|
|
209
|
+
decr(key, amount = 1, options = {}) {
|
|
210
|
+
return this.incr(key, -Math.abs(amount), options);
|
|
211
|
+
}
|
|
212
|
+
async delete(key) {
|
|
213
|
+
const rows = await this.sql.unsafe(
|
|
214
|
+
`DELETE FROM ${this.quotedTableName}
|
|
215
|
+
WHERE namespace = $1 AND key = $2
|
|
216
|
+
RETURNING key`,
|
|
217
|
+
[this.namespace, key]
|
|
218
|
+
);
|
|
219
|
+
return rows.length > 0;
|
|
220
|
+
}
|
|
221
|
+
async cleanupExpired(limit = 1e3) {
|
|
222
|
+
const rows = await this.sql.unsafe(
|
|
223
|
+
`DELETE FROM ${this.quotedTableName}
|
|
224
|
+
WHERE ctid IN (
|
|
225
|
+
SELECT ctid
|
|
226
|
+
FROM ${this.quotedTableName}
|
|
227
|
+
WHERE expires_at IS NOT NULL AND expires_at <= NOW()
|
|
228
|
+
LIMIT $1
|
|
229
|
+
)
|
|
230
|
+
RETURNING key`,
|
|
231
|
+
[Math.max(1, Math.floor(limit))]
|
|
232
|
+
);
|
|
233
|
+
return rows.length;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
function createPgCounter(options) {
|
|
237
|
+
return new PgCounter(options);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// src/hash.ts
|
|
241
|
+
var DEFAULT_TABLE_NAME2 = "pgredis_hash";
|
|
242
|
+
var DEFAULT_NAMESPACE2 = "default";
|
|
243
|
+
function jsonValue(value) {
|
|
244
|
+
return JSON.stringify(value);
|
|
245
|
+
}
|
|
246
|
+
function parseValue(value) {
|
|
247
|
+
if (typeof value !== "string") return value;
|
|
248
|
+
try {
|
|
249
|
+
return JSON.parse(value);
|
|
250
|
+
} catch {
|
|
251
|
+
return value;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
var PgHash = class {
|
|
255
|
+
namespace;
|
|
256
|
+
tableName;
|
|
257
|
+
quotedTableName;
|
|
258
|
+
sql;
|
|
259
|
+
constructor(options) {
|
|
260
|
+
this.sql = options.sql;
|
|
261
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE2;
|
|
262
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME2;
|
|
263
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
264
|
+
}
|
|
265
|
+
async ensureSchema(options = {}) {
|
|
266
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
267
|
+
await this.sql.unsafe(`
|
|
268
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
269
|
+
namespace TEXT NOT NULL,
|
|
270
|
+
key TEXT NOT NULL,
|
|
271
|
+
field TEXT NOT NULL,
|
|
272
|
+
value JSONB NOT NULL,
|
|
273
|
+
expires_at TIMESTAMPTZ,
|
|
274
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
275
|
+
PRIMARY KEY (namespace, key, field)
|
|
276
|
+
)
|
|
277
|
+
`);
|
|
278
|
+
await this.sql.unsafe(`
|
|
279
|
+
ALTER TABLE ${this.quotedTableName}
|
|
280
|
+
ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ
|
|
281
|
+
`);
|
|
282
|
+
await this.sql.unsafe(`
|
|
283
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "namespace_key")}
|
|
284
|
+
ON ${this.quotedTableName} (namespace, key)
|
|
285
|
+
`);
|
|
286
|
+
await this.sql.unsafe(`
|
|
287
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
288
|
+
ON ${this.quotedTableName} (expires_at)
|
|
289
|
+
WHERE expires_at IS NOT NULL
|
|
290
|
+
`);
|
|
291
|
+
}
|
|
292
|
+
async hget(key, field) {
|
|
293
|
+
const rows = await this.sql.unsafe(
|
|
294
|
+
`SELECT value
|
|
295
|
+
FROM ${this.quotedTableName}
|
|
296
|
+
WHERE namespace = $1 AND key = $2 AND field = $3
|
|
297
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
298
|
+
LIMIT 1`,
|
|
299
|
+
[this.namespace, key, field]
|
|
300
|
+
);
|
|
301
|
+
return rows[0] ? parseValue(rows[0].value) : null;
|
|
302
|
+
}
|
|
303
|
+
async hset(key, field, value) {
|
|
304
|
+
await this.sql.unsafe(
|
|
305
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, field, value, expires_at, updated_at)
|
|
306
|
+
VALUES (
|
|
307
|
+
$1,
|
|
308
|
+
$2,
|
|
309
|
+
$3,
|
|
310
|
+
$4::jsonb,
|
|
311
|
+
(SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $1 AND key = $2),
|
|
312
|
+
NOW()
|
|
313
|
+
)
|
|
314
|
+
ON CONFLICT (namespace, key, field) DO UPDATE
|
|
315
|
+
SET value = EXCLUDED.value,
|
|
316
|
+
updated_at = NOW()`,
|
|
317
|
+
[this.namespace, key, field, jsonValue(value)]
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
async hmset(key, entries) {
|
|
321
|
+
const values = Array.from(entries);
|
|
322
|
+
if (values.length === 0) return;
|
|
323
|
+
const params = [];
|
|
324
|
+
const groups = values.map(([field, value], index) => {
|
|
325
|
+
const base = index * 4;
|
|
326
|
+
params.push(this.namespace, key, field, jsonValue(value));
|
|
327
|
+
return `($${base + 1}, $${base + 2}, $${base + 3}, $${base + 4}::jsonb, (SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $${base + 1} AND key = $${base + 2}), NOW())`;
|
|
328
|
+
}).join(", ");
|
|
329
|
+
await this.sql.unsafe(
|
|
330
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, field, value, expires_at, updated_at)
|
|
331
|
+
VALUES ${groups}
|
|
332
|
+
ON CONFLICT (namespace, key, field) DO UPDATE
|
|
333
|
+
SET value = EXCLUDED.value,
|
|
334
|
+
updated_at = NOW()`,
|
|
335
|
+
params
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
async hgetall(key) {
|
|
339
|
+
const rows = await this.sql.unsafe(
|
|
340
|
+
`SELECT field, value
|
|
341
|
+
FROM ${this.quotedTableName}
|
|
342
|
+
WHERE namespace = $1 AND key = $2
|
|
343
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
344
|
+
ORDER BY field ASC`,
|
|
345
|
+
[this.namespace, key]
|
|
346
|
+
);
|
|
347
|
+
return Object.fromEntries(rows.map((row) => [row.field, parseValue(row.value)]));
|
|
348
|
+
}
|
|
349
|
+
async hdel(key, field) {
|
|
350
|
+
const rows = await this.sql.unsafe(
|
|
351
|
+
`DELETE FROM ${this.quotedTableName}
|
|
352
|
+
WHERE namespace = $1 AND key = $2 AND field = $3
|
|
353
|
+
RETURNING field`,
|
|
354
|
+
[this.namespace, key, field]
|
|
355
|
+
);
|
|
356
|
+
return rows.length > 0;
|
|
357
|
+
}
|
|
358
|
+
async hclear(key) {
|
|
359
|
+
const rows = await this.sql.unsafe(
|
|
360
|
+
`DELETE FROM ${this.quotedTableName}
|
|
361
|
+
WHERE namespace = $1 AND key = $2
|
|
362
|
+
RETURNING field`,
|
|
363
|
+
[this.namespace, key]
|
|
364
|
+
);
|
|
365
|
+
return rows.length;
|
|
366
|
+
}
|
|
367
|
+
async hexists(key, field) {
|
|
368
|
+
const rows = await this.sql.unsafe(
|
|
369
|
+
`SELECT EXISTS (
|
|
370
|
+
SELECT 1 FROM ${this.quotedTableName}
|
|
371
|
+
WHERE namespace = $1 AND key = $2 AND field = $3
|
|
372
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
373
|
+
) AS exists`,
|
|
374
|
+
[this.namespace, key, field]
|
|
375
|
+
);
|
|
376
|
+
return !!rows[0]?.exists;
|
|
377
|
+
}
|
|
378
|
+
async hlen(key) {
|
|
379
|
+
const rows = await this.sql.unsafe(
|
|
380
|
+
`SELECT COUNT(*)::bigint AS value
|
|
381
|
+
FROM ${this.quotedTableName}
|
|
382
|
+
WHERE namespace = $1 AND key = $2
|
|
383
|
+
AND (expires_at IS NULL OR expires_at > NOW())`,
|
|
384
|
+
[this.namespace, key]
|
|
385
|
+
);
|
|
386
|
+
return Number(rows[0]?.value ?? 0);
|
|
387
|
+
}
|
|
388
|
+
async hincrby(key, field, amount = 1) {
|
|
389
|
+
if (!Number.isSafeInteger(amount)) throw new Error(`Invalid hash increment: ${amount}`);
|
|
390
|
+
const rows = await this.sql.unsafe(
|
|
391
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, field, value, expires_at, updated_at)
|
|
392
|
+
VALUES (
|
|
393
|
+
$1,
|
|
394
|
+
$2,
|
|
395
|
+
$3,
|
|
396
|
+
to_jsonb($4::bigint),
|
|
397
|
+
(SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $1 AND key = $2),
|
|
398
|
+
NOW()
|
|
399
|
+
)
|
|
400
|
+
ON CONFLICT (namespace, key, field) DO UPDATE
|
|
401
|
+
SET value = to_jsonb(((${this.quotedTableName}.value #>> '{}')::bigint + $4::bigint)),
|
|
402
|
+
updated_at = NOW()
|
|
403
|
+
RETURNING (value #>> '{}')::bigint AS value`,
|
|
404
|
+
[this.namespace, key, field, Math.trunc(amount)]
|
|
405
|
+
);
|
|
406
|
+
return Number(rows[0]?.value ?? amount);
|
|
407
|
+
}
|
|
408
|
+
async hscan(key, cursor = null, count = 100) {
|
|
409
|
+
const rows = await this.sql.unsafe(
|
|
410
|
+
`SELECT field, value
|
|
411
|
+
FROM ${this.quotedTableName}
|
|
412
|
+
WHERE namespace = $1
|
|
413
|
+
AND key = $2
|
|
414
|
+
AND field > COALESCE($3::text, '')
|
|
415
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
416
|
+
ORDER BY field ASC
|
|
417
|
+
LIMIT $4`,
|
|
418
|
+
[this.namespace, key, cursor, Math.max(1, Math.floor(count))]
|
|
419
|
+
);
|
|
420
|
+
return {
|
|
421
|
+
cursor: rows.length === count ? rows[rows.length - 1].field : null,
|
|
422
|
+
entries: rows.map((row) => [row.field, parseValue(row.value)])
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
async expire(key, ttlMs) {
|
|
426
|
+
const rows = await this.sql.unsafe(
|
|
427
|
+
`UPDATE ${this.quotedTableName}
|
|
428
|
+
SET expires_at = NOW() + ($3::bigint * INTERVAL '1 millisecond'),
|
|
429
|
+
updated_at = NOW()
|
|
430
|
+
WHERE namespace = $1 AND key = $2
|
|
431
|
+
RETURNING field`,
|
|
432
|
+
[this.namespace, key, Math.max(0, Math.floor(ttlMs))]
|
|
433
|
+
);
|
|
434
|
+
return rows.length;
|
|
435
|
+
}
|
|
436
|
+
async persist(key) {
|
|
437
|
+
const rows = await this.sql.unsafe(
|
|
438
|
+
`UPDATE ${this.quotedTableName}
|
|
439
|
+
SET expires_at = NULL,
|
|
440
|
+
updated_at = NOW()
|
|
441
|
+
WHERE namespace = $1 AND key = $2
|
|
442
|
+
RETURNING field`,
|
|
443
|
+
[this.namespace, key]
|
|
444
|
+
);
|
|
445
|
+
return rows.length;
|
|
446
|
+
}
|
|
447
|
+
async ttl(key) {
|
|
448
|
+
const rows = await this.sql.unsafe(
|
|
449
|
+
`SELECT CASE
|
|
450
|
+
WHEN MAX(expires_at) IS NULL THEN NULL
|
|
451
|
+
ELSE GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (MAX(expires_at) - NOW())) * 1000))::bigint
|
|
452
|
+
END AS ttl_ms
|
|
453
|
+
FROM ${this.quotedTableName}
|
|
454
|
+
WHERE namespace = $1 AND key = $2`,
|
|
455
|
+
[this.namespace, key]
|
|
456
|
+
);
|
|
457
|
+
return rows[0]?.ttl_ms === null || rows[0]?.ttl_ms === void 0 ? null : Number(rows[0].ttl_ms);
|
|
458
|
+
}
|
|
459
|
+
async cleanupExpired(limit = 1e3) {
|
|
460
|
+
const rows = await this.sql.unsafe(
|
|
461
|
+
`DELETE FROM ${this.quotedTableName}
|
|
462
|
+
WHERE ctid IN (
|
|
463
|
+
SELECT ctid
|
|
464
|
+
FROM ${this.quotedTableName}
|
|
465
|
+
WHERE expires_at IS NOT NULL AND expires_at <= NOW()
|
|
466
|
+
LIMIT $1
|
|
467
|
+
)
|
|
468
|
+
RETURNING field`,
|
|
469
|
+
[Math.max(1, Math.floor(limit))]
|
|
470
|
+
);
|
|
471
|
+
return rows.length;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
function createPgHash(options) {
|
|
475
|
+
return new PgHash(options);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// src/list.ts
|
|
479
|
+
var DEFAULT_TABLE_NAME3 = "pgredis_list";
|
|
480
|
+
var DEFAULT_NAMESPACE3 = "default";
|
|
481
|
+
function jsonValue2(value) {
|
|
482
|
+
return JSON.stringify(value);
|
|
483
|
+
}
|
|
484
|
+
function parseValue2(value) {
|
|
485
|
+
if (typeof value !== "string") return value;
|
|
486
|
+
try {
|
|
487
|
+
return JSON.parse(value);
|
|
488
|
+
} catch {
|
|
489
|
+
return value;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
var PgList = class {
|
|
493
|
+
namespace;
|
|
494
|
+
tableName;
|
|
495
|
+
quotedTableName;
|
|
496
|
+
sql;
|
|
497
|
+
now;
|
|
498
|
+
constructor(options) {
|
|
499
|
+
this.sql = options.sql;
|
|
500
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE3;
|
|
501
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME3;
|
|
502
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
503
|
+
this.now = options.now || Date.now;
|
|
504
|
+
}
|
|
505
|
+
async ensureSchema(options = {}) {
|
|
506
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
507
|
+
await this.sql.unsafe(`
|
|
508
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
509
|
+
id BIGSERIAL PRIMARY KEY,
|
|
510
|
+
namespace TEXT NOT NULL,
|
|
511
|
+
key TEXT NOT NULL,
|
|
512
|
+
position DOUBLE PRECISION NOT NULL,
|
|
513
|
+
value JSONB NOT NULL,
|
|
514
|
+
expires_at TIMESTAMPTZ,
|
|
515
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
516
|
+
)
|
|
517
|
+
`);
|
|
518
|
+
await this.sql.unsafe(`
|
|
519
|
+
ALTER TABLE ${this.quotedTableName}
|
|
520
|
+
ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ
|
|
521
|
+
`);
|
|
522
|
+
await this.sql.unsafe(`
|
|
523
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "position")}
|
|
524
|
+
ON ${this.quotedTableName} (namespace, key, position ASC, id ASC)
|
|
525
|
+
`);
|
|
526
|
+
await this.sql.unsafe(`
|
|
527
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
528
|
+
ON ${this.quotedTableName} (expires_at)
|
|
529
|
+
WHERE expires_at IS NOT NULL
|
|
530
|
+
`);
|
|
531
|
+
}
|
|
532
|
+
async lpush(key, ...values) {
|
|
533
|
+
return this.push(key, values, "left");
|
|
534
|
+
}
|
|
535
|
+
async rpush(key, ...values) {
|
|
536
|
+
return this.push(key, values, "right");
|
|
537
|
+
}
|
|
538
|
+
async lpop(key, count = 1) {
|
|
539
|
+
return this.pop(key, count, "ASC");
|
|
540
|
+
}
|
|
541
|
+
async rpop(key, count = 1) {
|
|
542
|
+
return this.pop(key, count, "DESC");
|
|
543
|
+
}
|
|
544
|
+
async lrange(key, start = 0, stop = -1) {
|
|
545
|
+
const limit = stop < 0 ? null : Math.max(0, stop - start + 1);
|
|
546
|
+
const rows = await this.sql.unsafe(
|
|
547
|
+
`SELECT value
|
|
548
|
+
FROM ${this.quotedTableName}
|
|
549
|
+
WHERE namespace = $1 AND key = $2
|
|
550
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
551
|
+
ORDER BY position ASC, id ASC
|
|
552
|
+
OFFSET $3
|
|
553
|
+
LIMIT COALESCE($4::bigint, 9223372036854775807)`,
|
|
554
|
+
[this.namespace, key, Math.max(0, start), limit]
|
|
555
|
+
);
|
|
556
|
+
return rows.map((row) => parseValue2(row.value));
|
|
557
|
+
}
|
|
558
|
+
async llen(key) {
|
|
559
|
+
const rows = await this.sql.unsafe(
|
|
560
|
+
`SELECT COUNT(*)::bigint AS count
|
|
561
|
+
FROM ${this.quotedTableName}
|
|
562
|
+
WHERE namespace = $1 AND key = $2
|
|
563
|
+
AND (expires_at IS NULL OR expires_at > NOW())`,
|
|
564
|
+
[this.namespace, key]
|
|
565
|
+
);
|
|
566
|
+
return Number(rows[0]?.count ?? 0);
|
|
567
|
+
}
|
|
568
|
+
async lclear(key) {
|
|
569
|
+
const rows = await this.sql.unsafe(
|
|
570
|
+
`DELETE FROM ${this.quotedTableName}
|
|
571
|
+
WHERE namespace = $1 AND key = $2
|
|
572
|
+
RETURNING id`,
|
|
573
|
+
[this.namespace, key]
|
|
574
|
+
);
|
|
575
|
+
return rows.length;
|
|
576
|
+
}
|
|
577
|
+
async push(key, values, side) {
|
|
578
|
+
if (values.length === 0) return this.llen(key);
|
|
579
|
+
const base = this.now();
|
|
580
|
+
const params = [];
|
|
581
|
+
const groups = values.map((value, index) => {
|
|
582
|
+
const position = side === "left" ? -(base + values.length - index) : base + index;
|
|
583
|
+
const paramIndex = index * 4;
|
|
584
|
+
params.push(this.namespace, key, position, jsonValue2(value));
|
|
585
|
+
return `($${paramIndex + 1}, $${paramIndex + 2}, $${paramIndex + 3}, $${paramIndex + 4}::jsonb, (SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $${paramIndex + 1} AND key = $${paramIndex + 2}), NOW())`;
|
|
586
|
+
}).join(", ");
|
|
587
|
+
await this.sql.unsafe(
|
|
588
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, position, value, expires_at, created_at)
|
|
589
|
+
VALUES ${groups}`,
|
|
590
|
+
params
|
|
591
|
+
);
|
|
592
|
+
return this.llen(key);
|
|
593
|
+
}
|
|
594
|
+
async pop(key, count, direction) {
|
|
595
|
+
const limit = Math.max(1, Math.floor(count));
|
|
596
|
+
const rows = await this.sql.unsafe(
|
|
597
|
+
`WITH picked AS (
|
|
598
|
+
SELECT id, value, position
|
|
599
|
+
FROM ${this.quotedTableName}
|
|
600
|
+
WHERE namespace = $1 AND key = $2
|
|
601
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
602
|
+
ORDER BY position ${direction}, id ${direction}
|
|
603
|
+
LIMIT $3
|
|
604
|
+
), deleted AS (
|
|
605
|
+
DELETE FROM ${this.quotedTableName} target
|
|
606
|
+
USING picked
|
|
607
|
+
WHERE target.id = picked.id
|
|
608
|
+
RETURNING picked.value, picked.position
|
|
609
|
+
)
|
|
610
|
+
SELECT value
|
|
611
|
+
FROM deleted
|
|
612
|
+
ORDER BY position ${direction}`,
|
|
613
|
+
[this.namespace, key, limit]
|
|
614
|
+
);
|
|
615
|
+
return rows.map((row) => parseValue2(row.value));
|
|
616
|
+
}
|
|
617
|
+
async lscan(key, cursor = null, count = 100) {
|
|
618
|
+
const limit = Math.max(1, Math.floor(count));
|
|
619
|
+
const rows = await this.sql.unsafe(
|
|
620
|
+
`SELECT position, value
|
|
621
|
+
FROM ${this.quotedTableName}
|
|
622
|
+
WHERE namespace = $1
|
|
623
|
+
AND key = $2
|
|
624
|
+
AND position > COALESCE($3::double precision, '-Infinity'::double precision)
|
|
625
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
626
|
+
ORDER BY position ASC, id ASC
|
|
627
|
+
LIMIT $4`,
|
|
628
|
+
[this.namespace, key, cursor, limit]
|
|
629
|
+
);
|
|
630
|
+
return {
|
|
631
|
+
cursor: rows.length === limit ? Number(rows[rows.length - 1].position) : null,
|
|
632
|
+
values: rows.map((row) => parseValue2(row.value))
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
async expire(key, ttlMs) {
|
|
636
|
+
const rows = await this.sql.unsafe(
|
|
637
|
+
`UPDATE ${this.quotedTableName}
|
|
638
|
+
SET expires_at = NOW() + ($3::bigint * INTERVAL '1 millisecond')
|
|
639
|
+
WHERE namespace = $1 AND key = $2
|
|
640
|
+
RETURNING id`,
|
|
641
|
+
[this.namespace, key, Math.max(0, Math.floor(ttlMs))]
|
|
642
|
+
);
|
|
643
|
+
return rows.length;
|
|
644
|
+
}
|
|
645
|
+
async persist(key) {
|
|
646
|
+
const rows = await this.sql.unsafe(
|
|
647
|
+
`UPDATE ${this.quotedTableName}
|
|
648
|
+
SET expires_at = NULL
|
|
649
|
+
WHERE namespace = $1 AND key = $2
|
|
650
|
+
RETURNING id`,
|
|
651
|
+
[this.namespace, key]
|
|
652
|
+
);
|
|
653
|
+
return rows.length;
|
|
654
|
+
}
|
|
655
|
+
async ttl(key) {
|
|
656
|
+
const rows = await this.sql.unsafe(
|
|
657
|
+
`SELECT CASE
|
|
658
|
+
WHEN MAX(expires_at) IS NULL THEN NULL
|
|
659
|
+
ELSE GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (MAX(expires_at) - NOW())) * 1000))::bigint
|
|
660
|
+
END AS ttl_ms
|
|
661
|
+
FROM ${this.quotedTableName}
|
|
662
|
+
WHERE namespace = $1 AND key = $2`,
|
|
663
|
+
[this.namespace, key]
|
|
664
|
+
);
|
|
665
|
+
return rows[0]?.ttl_ms === null || rows[0]?.ttl_ms === void 0 ? null : Number(rows[0].ttl_ms);
|
|
666
|
+
}
|
|
667
|
+
async cleanupExpired(limit = 1e3) {
|
|
668
|
+
const rows = await this.sql.unsafe(
|
|
669
|
+
`DELETE FROM ${this.quotedTableName}
|
|
670
|
+
WHERE ctid IN (
|
|
671
|
+
SELECT ctid
|
|
672
|
+
FROM ${this.quotedTableName}
|
|
673
|
+
WHERE expires_at IS NOT NULL AND expires_at <= NOW()
|
|
674
|
+
LIMIT $1
|
|
675
|
+
)
|
|
676
|
+
RETURNING id`,
|
|
677
|
+
[Math.max(1, Math.floor(limit))]
|
|
678
|
+
);
|
|
679
|
+
return rows.length;
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
function createPgList(options) {
|
|
683
|
+
return new PgList(options);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// src/pubsub.ts
|
|
687
|
+
function createBunPgListener(databaseUrl, channelsOrOptions = [], onNotify, maybeOptions = {}) {
|
|
688
|
+
let handle = null;
|
|
689
|
+
let loadError = null;
|
|
690
|
+
let closed = false;
|
|
691
|
+
const queue = [];
|
|
692
|
+
void import("@postgresx/bun-listen").then((mod) => {
|
|
693
|
+
if (closed) return;
|
|
694
|
+
handle = Array.isArray(channelsOrOptions) ? mod.createPgListener(databaseUrl, channelsOrOptions, onNotify, maybeOptions) : mod.createPgListener(databaseUrl, channelsOrOptions);
|
|
695
|
+
const activeHandle = handle;
|
|
696
|
+
for (const item of queue.splice(0)) {
|
|
697
|
+
try {
|
|
698
|
+
item.resolve(item.action(activeHandle));
|
|
699
|
+
} catch (error) {
|
|
700
|
+
item.reject(error instanceof Error ? error : new Error(String(error)));
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
}).catch((error) => {
|
|
704
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
705
|
+
loadError = new Error(`@postgresx/bun-listen is required for Bun LISTEN/NOTIFY. Install it with \`bun add @postgresx/bun-listen\`. ${message}`);
|
|
706
|
+
for (const item of queue.splice(0)) item.reject(loadError);
|
|
707
|
+
});
|
|
708
|
+
const run = (action) => {
|
|
709
|
+
if (handle) return Promise.resolve(action(handle));
|
|
710
|
+
if (loadError) return Promise.reject(loadError);
|
|
711
|
+
return new Promise((resolve, reject) => {
|
|
712
|
+
queue.push({
|
|
713
|
+
action,
|
|
714
|
+
resolve,
|
|
715
|
+
reject
|
|
716
|
+
});
|
|
717
|
+
});
|
|
718
|
+
};
|
|
719
|
+
return {
|
|
720
|
+
close() {
|
|
721
|
+
closed = true;
|
|
722
|
+
if (handle) handle.close();
|
|
723
|
+
queue.length = 0;
|
|
724
|
+
},
|
|
725
|
+
notify(channel, payload) {
|
|
726
|
+
return run((listener) => listener.notify(channel, payload)).then(() => void 0);
|
|
727
|
+
},
|
|
728
|
+
getHealth() {
|
|
729
|
+
return handle?.getHealth() ?? {
|
|
730
|
+
status: closed ? "closed" : "connecting",
|
|
731
|
+
connected: false,
|
|
732
|
+
listeningChannels: Array.isArray(channelsOrOptions) ? channelsOrOptions : channelsOrOptions.channels ?? [],
|
|
733
|
+
queuedQueries: queue.length,
|
|
734
|
+
activeQuery: false,
|
|
735
|
+
reconnectAttempts: 0,
|
|
736
|
+
lastConnectedAt: null,
|
|
737
|
+
lastMessageAt: null,
|
|
738
|
+
lastNotificationAt: null,
|
|
739
|
+
lastError: null
|
|
740
|
+
};
|
|
741
|
+
},
|
|
742
|
+
on(event, handler) {
|
|
743
|
+
if (handle) return handle.on(event, handler);
|
|
744
|
+
let unsubscribe = null;
|
|
745
|
+
const item = {
|
|
746
|
+
action(listener) {
|
|
747
|
+
unsubscribe = listener.on(event, handler);
|
|
748
|
+
},
|
|
749
|
+
resolve() {
|
|
750
|
+
},
|
|
751
|
+
reject() {
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
queue.push(item);
|
|
755
|
+
return () => {
|
|
756
|
+
const index = queue.indexOf(item);
|
|
757
|
+
if (index >= 0) queue.splice(index, 1);
|
|
758
|
+
unsubscribe?.();
|
|
759
|
+
};
|
|
760
|
+
},
|
|
761
|
+
off(event, handler) {
|
|
762
|
+
if (handle) handle.off(event, handler);
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
var createPgListener = createBunPgListener;
|
|
767
|
+
function serializePayload(payload) {
|
|
768
|
+
return typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
769
|
+
}
|
|
770
|
+
async function publishPgNotify(sql, channel, payload) {
|
|
771
|
+
await sql.unsafe("SELECT pg_notify($1, $2)", [channel, serializePayload(payload)]);
|
|
772
|
+
}
|
|
773
|
+
function createPgPublisher(sql) {
|
|
774
|
+
return {
|
|
775
|
+
publish(channel, payload) {
|
|
776
|
+
return publishPgNotify(sql, channel, payload);
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// src/queue.ts
|
|
782
|
+
async function loadPgBoss() {
|
|
783
|
+
try {
|
|
784
|
+
const specifier = "pg-boss";
|
|
785
|
+
return await import(specifier);
|
|
786
|
+
} catch (error) {
|
|
787
|
+
throw new Error("pg-boss is required for pgredis queue features. Install it with `npm install pg-boss`.", {
|
|
788
|
+
cause: error
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
var PgBossJobQueue = class {
|
|
793
|
+
constructor(options) {
|
|
794
|
+
this.options = options;
|
|
795
|
+
}
|
|
796
|
+
options;
|
|
797
|
+
boss = null;
|
|
798
|
+
async start() {
|
|
799
|
+
if (this.boss) return this.boss;
|
|
800
|
+
const { PgBoss } = await loadPgBoss();
|
|
801
|
+
const boss = typeof this.options === "string" ? new PgBoss(this.options) : new PgBoss(this.options);
|
|
802
|
+
await boss.start();
|
|
803
|
+
const queues = typeof this.options === "string" ? void 0 : this.options.queues;
|
|
804
|
+
if (queues) {
|
|
805
|
+
for (const [name, options] of Object.entries(queues)) {
|
|
806
|
+
await boss.createQueue(name, options);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
this.boss = boss;
|
|
810
|
+
return boss;
|
|
811
|
+
}
|
|
812
|
+
async stop() {
|
|
813
|
+
if (!this.boss) return;
|
|
814
|
+
const boss = this.boss;
|
|
815
|
+
this.boss = null;
|
|
816
|
+
await boss.stop();
|
|
817
|
+
}
|
|
818
|
+
async ensureQueue(name, options = {}) {
|
|
819
|
+
const boss = await this.start();
|
|
820
|
+
await boss.createQueue(name, options);
|
|
821
|
+
}
|
|
822
|
+
async send(name, data, options) {
|
|
823
|
+
const boss = await this.start();
|
|
824
|
+
return boss.send(name, data ?? null, options);
|
|
825
|
+
}
|
|
826
|
+
async work(name, options, handler) {
|
|
827
|
+
const boss = await this.start();
|
|
828
|
+
return boss.work(name, options, handler);
|
|
829
|
+
}
|
|
830
|
+
async getBoss() {
|
|
831
|
+
return this.start();
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
function createPgBossJobQueue(options) {
|
|
835
|
+
return new PgBossJobQueue(options);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// src/rate-limit.ts
|
|
839
|
+
var DEFAULT_TABLE_NAME4 = "pg_rate_limit";
|
|
840
|
+
var DEFAULT_NAMESPACE4 = "default";
|
|
841
|
+
var DEFAULT_SLIDING_TABLE_NAME = "pg_sliding_rate_limit";
|
|
842
|
+
var DEFAULT_TOKEN_BUCKET_TABLE_NAME = "pg_token_bucket_rate_limit";
|
|
843
|
+
var PgFixedWindowRateLimiter = class {
|
|
844
|
+
namespace;
|
|
845
|
+
tableName;
|
|
846
|
+
quotedTableName;
|
|
847
|
+
sql;
|
|
848
|
+
now;
|
|
849
|
+
limit;
|
|
850
|
+
windowMs;
|
|
851
|
+
constructor(options) {
|
|
852
|
+
this.sql = options.sql;
|
|
853
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE4;
|
|
854
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME4;
|
|
855
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
856
|
+
this.now = options.now || Date.now;
|
|
857
|
+
this.limit = normalizePositiveInteger(options.limit, "limit");
|
|
858
|
+
this.windowMs = normalizePositiveInteger(options.windowMs, "windowMs");
|
|
859
|
+
}
|
|
860
|
+
async ensureSchema(options = {}) {
|
|
861
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
862
|
+
await this.sql.unsafe(`
|
|
863
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
864
|
+
namespace TEXT NOT NULL,
|
|
865
|
+
key TEXT NOT NULL,
|
|
866
|
+
window_start BIGINT NOT NULL,
|
|
867
|
+
count BIGINT NOT NULL,
|
|
868
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
869
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
870
|
+
PRIMARY KEY (namespace, key, window_start)
|
|
871
|
+
)
|
|
872
|
+
`);
|
|
873
|
+
await this.sql.unsafe(`
|
|
874
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
875
|
+
ON ${this.quotedTableName} (expires_at)
|
|
876
|
+
`);
|
|
877
|
+
}
|
|
878
|
+
async hit(key, options = {}) {
|
|
879
|
+
const limit = normalizePositiveInteger(options.limit ?? this.limit, "limit");
|
|
880
|
+
const windowMs = normalizePositiveInteger(options.windowMs ?? this.windowMs, "windowMs");
|
|
881
|
+
const cost = normalizePositiveInteger(options.cost ?? 1, "cost");
|
|
882
|
+
const now = this.now();
|
|
883
|
+
const windowStart = Math.floor(now / windowMs) * windowMs;
|
|
884
|
+
const resetAtMs = windowStart + windowMs;
|
|
885
|
+
const rows = await this.sql.unsafe(
|
|
886
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, window_start, count, expires_at, updated_at)
|
|
887
|
+
VALUES (
|
|
888
|
+
$1,
|
|
889
|
+
$2,
|
|
890
|
+
$3,
|
|
891
|
+
$4,
|
|
892
|
+
NOW() + ($5::bigint * INTERVAL '1 millisecond'),
|
|
893
|
+
NOW()
|
|
894
|
+
)
|
|
895
|
+
ON CONFLICT (namespace, key, window_start) DO UPDATE
|
|
896
|
+
SET count = ${this.quotedTableName}.count + EXCLUDED.count,
|
|
897
|
+
expires_at = GREATEST(${this.quotedTableName}.expires_at, EXCLUDED.expires_at),
|
|
898
|
+
updated_at = NOW()
|
|
899
|
+
RETURNING count`,
|
|
900
|
+
[this.namespace, key, windowStart, cost, windowMs]
|
|
901
|
+
);
|
|
902
|
+
const count = Number(rows[0]?.count ?? cost);
|
|
903
|
+
const allowed = count <= limit;
|
|
904
|
+
const retryAfterMs = allowed ? 0 : Math.max(0, resetAtMs - now);
|
|
905
|
+
return {
|
|
906
|
+
allowed,
|
|
907
|
+
limit,
|
|
908
|
+
count,
|
|
909
|
+
remaining: Math.max(0, limit - count),
|
|
910
|
+
resetAt: new Date(resetAtMs),
|
|
911
|
+
retryAfterMs
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
async cleanupExpired(limit = 1e3) {
|
|
915
|
+
const rows = await this.sql.unsafe(
|
|
916
|
+
`DELETE FROM ${this.quotedTableName}
|
|
917
|
+
WHERE ctid IN (
|
|
918
|
+
SELECT ctid
|
|
919
|
+
FROM ${this.quotedTableName}
|
|
920
|
+
WHERE expires_at <= NOW()
|
|
921
|
+
LIMIT $1
|
|
922
|
+
)
|
|
923
|
+
RETURNING key`,
|
|
924
|
+
[Math.max(1, Math.floor(limit))]
|
|
925
|
+
);
|
|
926
|
+
return rows.length;
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
function createPgFixedWindowRateLimiter(options) {
|
|
930
|
+
return new PgFixedWindowRateLimiter(options);
|
|
931
|
+
}
|
|
932
|
+
var PgSlidingWindowRateLimiter = class {
|
|
933
|
+
namespace;
|
|
934
|
+
tableName;
|
|
935
|
+
quotedTableName;
|
|
936
|
+
sql;
|
|
937
|
+
now;
|
|
938
|
+
limit;
|
|
939
|
+
windowMs;
|
|
940
|
+
precisionMs;
|
|
941
|
+
constructor(options) {
|
|
942
|
+
this.sql = options.sql;
|
|
943
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE4;
|
|
944
|
+
this.tableName = options.tableName || DEFAULT_SLIDING_TABLE_NAME;
|
|
945
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
946
|
+
this.now = options.now || Date.now;
|
|
947
|
+
this.limit = normalizePositiveInteger(options.limit, "limit");
|
|
948
|
+
this.windowMs = normalizePositiveInteger(options.windowMs, "windowMs");
|
|
949
|
+
this.precisionMs = normalizePositiveInteger(options.precisionMs || 1e3, "precisionMs");
|
|
950
|
+
}
|
|
951
|
+
async ensureSchema(options = {}) {
|
|
952
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
953
|
+
await this.sql.unsafe(`
|
|
954
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
955
|
+
namespace TEXT NOT NULL,
|
|
956
|
+
key TEXT NOT NULL,
|
|
957
|
+
bucket_start BIGINT NOT NULL,
|
|
958
|
+
count BIGINT NOT NULL,
|
|
959
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
960
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
961
|
+
PRIMARY KEY (namespace, key, bucket_start)
|
|
962
|
+
)
|
|
963
|
+
`);
|
|
964
|
+
await this.sql.unsafe(`
|
|
965
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
966
|
+
ON ${this.quotedTableName} (expires_at)
|
|
967
|
+
`);
|
|
968
|
+
}
|
|
969
|
+
async hit(key, options = {}) {
|
|
970
|
+
const limit = normalizePositiveInteger(options.limit ?? this.limit, "limit");
|
|
971
|
+
const windowMs = normalizePositiveInteger(options.windowMs ?? this.windowMs, "windowMs");
|
|
972
|
+
const cost = normalizePositiveInteger(options.cost ?? 1, "cost");
|
|
973
|
+
const now = this.now();
|
|
974
|
+
const bucketStart = Math.floor(now / this.precisionMs) * this.precisionMs;
|
|
975
|
+
const windowStart = now - windowMs;
|
|
976
|
+
const rows = await this.sql.unsafe(
|
|
977
|
+
`WITH upserted AS (
|
|
978
|
+
INSERT INTO ${this.quotedTableName} (namespace, key, bucket_start, count, expires_at, updated_at)
|
|
979
|
+
VALUES (
|
|
980
|
+
$1,
|
|
981
|
+
$2,
|
|
982
|
+
$3,
|
|
983
|
+
$4,
|
|
984
|
+
NOW() + ($5::bigint * INTERVAL '1 millisecond'),
|
|
985
|
+
NOW()
|
|
986
|
+
)
|
|
987
|
+
ON CONFLICT (namespace, key, bucket_start) DO UPDATE
|
|
988
|
+
SET count = ${this.quotedTableName}.count + EXCLUDED.count,
|
|
989
|
+
expires_at = GREATEST(${this.quotedTableName}.expires_at, EXCLUDED.expires_at),
|
|
990
|
+
updated_at = NOW()
|
|
991
|
+
)
|
|
992
|
+
SELECT COALESCE(SUM(count), 0)::bigint AS count
|
|
993
|
+
FROM ${this.quotedTableName}
|
|
994
|
+
WHERE namespace = $1
|
|
995
|
+
AND key = $2
|
|
996
|
+
AND bucket_start > $6`,
|
|
997
|
+
[this.namespace, key, bucketStart, cost, windowMs, windowStart]
|
|
998
|
+
);
|
|
999
|
+
const count = Number(rows[0]?.count ?? cost);
|
|
1000
|
+
const allowed = count <= limit;
|
|
1001
|
+
return {
|
|
1002
|
+
allowed,
|
|
1003
|
+
limit,
|
|
1004
|
+
count,
|
|
1005
|
+
remaining: Math.max(0, limit - count),
|
|
1006
|
+
resetAt: new Date(bucketStart + windowMs),
|
|
1007
|
+
retryAfterMs: allowed ? 0 : this.precisionMs
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
async cleanupExpired(limit = 1e3) {
|
|
1011
|
+
const rows = await this.sql.unsafe(
|
|
1012
|
+
`DELETE FROM ${this.quotedTableName}
|
|
1013
|
+
WHERE ctid IN (
|
|
1014
|
+
SELECT ctid
|
|
1015
|
+
FROM ${this.quotedTableName}
|
|
1016
|
+
WHERE expires_at <= NOW()
|
|
1017
|
+
LIMIT $1
|
|
1018
|
+
)
|
|
1019
|
+
RETURNING key`,
|
|
1020
|
+
[Math.max(1, Math.floor(limit))]
|
|
1021
|
+
);
|
|
1022
|
+
return rows.length;
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
var PgTokenBucketRateLimiter = class {
|
|
1026
|
+
namespace;
|
|
1027
|
+
tableName;
|
|
1028
|
+
quotedTableName;
|
|
1029
|
+
sql;
|
|
1030
|
+
now;
|
|
1031
|
+
capacity;
|
|
1032
|
+
refillTokens;
|
|
1033
|
+
refillIntervalMs;
|
|
1034
|
+
constructor(options) {
|
|
1035
|
+
this.sql = options.sql;
|
|
1036
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE4;
|
|
1037
|
+
this.tableName = options.tableName || DEFAULT_TOKEN_BUCKET_TABLE_NAME;
|
|
1038
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
1039
|
+
this.now = options.now || Date.now;
|
|
1040
|
+
this.capacity = normalizePositiveInteger(options.capacity, "capacity");
|
|
1041
|
+
this.refillTokens = normalizePositiveInteger(options.refillTokens, "refillTokens");
|
|
1042
|
+
this.refillIntervalMs = normalizePositiveInteger(options.refillIntervalMs, "refillIntervalMs");
|
|
1043
|
+
}
|
|
1044
|
+
async ensureSchema(options = {}) {
|
|
1045
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
1046
|
+
await this.sql.unsafe(`
|
|
1047
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
1048
|
+
namespace TEXT NOT NULL,
|
|
1049
|
+
key TEXT NOT NULL,
|
|
1050
|
+
tokens DOUBLE PRECISION NOT NULL,
|
|
1051
|
+
last_refill_ms BIGINT NOT NULL,
|
|
1052
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
1053
|
+
PRIMARY KEY (namespace, key)
|
|
1054
|
+
)
|
|
1055
|
+
`);
|
|
1056
|
+
}
|
|
1057
|
+
async consume(key, cost = 1) {
|
|
1058
|
+
const normalizedCost = normalizePositiveInteger(cost, "cost");
|
|
1059
|
+
const now = this.now();
|
|
1060
|
+
const rows = await this.sql.unsafe(
|
|
1061
|
+
`WITH seeded AS (
|
|
1062
|
+
INSERT INTO ${this.quotedTableName} (namespace, key, tokens, last_refill_ms, updated_at)
|
|
1063
|
+
VALUES ($1, $2, $3, $4, NOW())
|
|
1064
|
+
ON CONFLICT (namespace, key) DO NOTHING
|
|
1065
|
+
), state AS (
|
|
1066
|
+
SELECT tokens, last_refill_ms
|
|
1067
|
+
FROM ${this.quotedTableName}
|
|
1068
|
+
WHERE namespace = $1 AND key = $2
|
|
1069
|
+
FOR UPDATE
|
|
1070
|
+
), computed AS (
|
|
1071
|
+
SELECT LEAST(
|
|
1072
|
+
$3::double precision,
|
|
1073
|
+
tokens + GREATEST(0, $4::bigint - last_refill_ms)::double precision / $5::double precision * $6::double precision
|
|
1074
|
+
) AS available
|
|
1075
|
+
FROM state
|
|
1076
|
+
), updated AS (
|
|
1077
|
+
UPDATE ${this.quotedTableName} target
|
|
1078
|
+
SET tokens = CASE
|
|
1079
|
+
WHEN computed.available >= $7 THEN computed.available - $7
|
|
1080
|
+
ELSE computed.available
|
|
1081
|
+
END,
|
|
1082
|
+
last_refill_ms = $4,
|
|
1083
|
+
updated_at = NOW()
|
|
1084
|
+
FROM computed
|
|
1085
|
+
WHERE target.namespace = $1 AND target.key = $2
|
|
1086
|
+
RETURNING target.tokens, computed.available, computed.available >= $7 AS allowed
|
|
1087
|
+
)
|
|
1088
|
+
SELECT tokens, available, allowed FROM updated`,
|
|
1089
|
+
[
|
|
1090
|
+
this.namespace,
|
|
1091
|
+
key,
|
|
1092
|
+
this.capacity,
|
|
1093
|
+
now,
|
|
1094
|
+
this.refillIntervalMs,
|
|
1095
|
+
this.refillTokens,
|
|
1096
|
+
normalizedCost
|
|
1097
|
+
]
|
|
1098
|
+
);
|
|
1099
|
+
const row = rows[0];
|
|
1100
|
+
const available = Number(row?.available ?? this.capacity);
|
|
1101
|
+
const tokens = Number(row?.tokens ?? Math.max(0, this.capacity - normalizedCost));
|
|
1102
|
+
const allowed = !!row?.allowed;
|
|
1103
|
+
const retryAfterMs = allowed ? 0 : Math.ceil(Math.max(0, normalizedCost - available) / this.refillTokens * this.refillIntervalMs);
|
|
1104
|
+
return {
|
|
1105
|
+
allowed,
|
|
1106
|
+
capacity: this.capacity,
|
|
1107
|
+
tokens,
|
|
1108
|
+
remaining: Math.max(0, Math.floor(tokens)),
|
|
1109
|
+
retryAfterMs
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
function createPgSlidingWindowRateLimiter(options) {
|
|
1114
|
+
return new PgSlidingWindowRateLimiter(options);
|
|
1115
|
+
}
|
|
1116
|
+
function createPgTokenBucketRateLimiter(options) {
|
|
1117
|
+
return new PgTokenBucketRateLimiter(options);
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// src/set.ts
|
|
1121
|
+
var DEFAULT_TABLE_NAME5 = "pgredis_set";
|
|
1122
|
+
var DEFAULT_NAMESPACE5 = "default";
|
|
1123
|
+
var PgSet = class {
|
|
1124
|
+
namespace;
|
|
1125
|
+
tableName;
|
|
1126
|
+
quotedTableName;
|
|
1127
|
+
sql;
|
|
1128
|
+
constructor(options) {
|
|
1129
|
+
this.sql = options.sql;
|
|
1130
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE5;
|
|
1131
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME5;
|
|
1132
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
1133
|
+
}
|
|
1134
|
+
async ensureSchema(options = {}) {
|
|
1135
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
1136
|
+
await this.sql.unsafe(`
|
|
1137
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
1138
|
+
namespace TEXT NOT NULL,
|
|
1139
|
+
key TEXT NOT NULL,
|
|
1140
|
+
member TEXT NOT NULL,
|
|
1141
|
+
expires_at TIMESTAMPTZ,
|
|
1142
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
1143
|
+
PRIMARY KEY (namespace, key, member)
|
|
1144
|
+
)
|
|
1145
|
+
`);
|
|
1146
|
+
await this.sql.unsafe(`
|
|
1147
|
+
ALTER TABLE ${this.quotedTableName}
|
|
1148
|
+
ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ
|
|
1149
|
+
`);
|
|
1150
|
+
await this.sql.unsafe(`
|
|
1151
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "namespace_key")}
|
|
1152
|
+
ON ${this.quotedTableName} (namespace, key)
|
|
1153
|
+
`);
|
|
1154
|
+
await this.sql.unsafe(`
|
|
1155
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
1156
|
+
ON ${this.quotedTableName} (expires_at)
|
|
1157
|
+
WHERE expires_at IS NOT NULL
|
|
1158
|
+
`);
|
|
1159
|
+
}
|
|
1160
|
+
async sadd(key, ...members) {
|
|
1161
|
+
const values = [...new Set(members)];
|
|
1162
|
+
if (values.length === 0) return 0;
|
|
1163
|
+
const params = [];
|
|
1164
|
+
const groups = values.map((member, index) => {
|
|
1165
|
+
const base = index * 3;
|
|
1166
|
+
params.push(this.namespace, key, member);
|
|
1167
|
+
return `($${base + 1}, $${base + 2}, $${base + 3}, (SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $${base + 1} AND key = $${base + 2}), NOW())`;
|
|
1168
|
+
}).join(", ");
|
|
1169
|
+
const rows = await this.sql.unsafe(
|
|
1170
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, member, expires_at, updated_at)
|
|
1171
|
+
VALUES ${groups}
|
|
1172
|
+
ON CONFLICT (namespace, key, member) DO NOTHING
|
|
1173
|
+
RETURNING member`,
|
|
1174
|
+
params
|
|
1175
|
+
);
|
|
1176
|
+
return rows.length;
|
|
1177
|
+
}
|
|
1178
|
+
async srem(key, ...members) {
|
|
1179
|
+
const values = [...new Set(members)];
|
|
1180
|
+
if (values.length === 0) return 0;
|
|
1181
|
+
const placeholders = values.map((_, index) => `$${index + 3}`).join(", ");
|
|
1182
|
+
const rows = await this.sql.unsafe(
|
|
1183
|
+
`DELETE FROM ${this.quotedTableName}
|
|
1184
|
+
WHERE namespace = $1 AND key = $2 AND member IN (${placeholders})
|
|
1185
|
+
RETURNING member`,
|
|
1186
|
+
[this.namespace, key, ...values]
|
|
1187
|
+
);
|
|
1188
|
+
return rows.length;
|
|
1189
|
+
}
|
|
1190
|
+
async sismember(key, member) {
|
|
1191
|
+
const rows = await this.sql.unsafe(
|
|
1192
|
+
`SELECT EXISTS (
|
|
1193
|
+
SELECT 1 FROM ${this.quotedTableName}
|
|
1194
|
+
WHERE namespace = $1 AND key = $2 AND member = $3
|
|
1195
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1196
|
+
) AS exists`,
|
|
1197
|
+
[this.namespace, key, member]
|
|
1198
|
+
);
|
|
1199
|
+
return !!rows[0]?.exists;
|
|
1200
|
+
}
|
|
1201
|
+
async smembers(key) {
|
|
1202
|
+
const rows = await this.sql.unsafe(
|
|
1203
|
+
`SELECT member
|
|
1204
|
+
FROM ${this.quotedTableName}
|
|
1205
|
+
WHERE namespace = $1 AND key = $2
|
|
1206
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1207
|
+
ORDER BY member ASC`,
|
|
1208
|
+
[this.namespace, key]
|
|
1209
|
+
);
|
|
1210
|
+
return rows.map((row) => row.member);
|
|
1211
|
+
}
|
|
1212
|
+
async sinter(...keys) {
|
|
1213
|
+
const values = [...new Set(keys)];
|
|
1214
|
+
if (values.length === 0) return [];
|
|
1215
|
+
const rows = await this.sql.unsafe(
|
|
1216
|
+
`SELECT member
|
|
1217
|
+
FROM ${this.quotedTableName}
|
|
1218
|
+
WHERE namespace = $1 AND key = ANY($2::text[])
|
|
1219
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1220
|
+
GROUP BY member
|
|
1221
|
+
HAVING COUNT(DISTINCT key) = $3
|
|
1222
|
+
ORDER BY member ASC`,
|
|
1223
|
+
[this.namespace, values, values.length]
|
|
1224
|
+
);
|
|
1225
|
+
return rows.map((row) => row.member);
|
|
1226
|
+
}
|
|
1227
|
+
async sunion(...keys) {
|
|
1228
|
+
const values = [...new Set(keys)];
|
|
1229
|
+
if (values.length === 0) return [];
|
|
1230
|
+
const rows = await this.sql.unsafe(
|
|
1231
|
+
`SELECT DISTINCT member
|
|
1232
|
+
FROM ${this.quotedTableName}
|
|
1233
|
+
WHERE namespace = $1 AND key = ANY($2::text[])
|
|
1234
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1235
|
+
ORDER BY member ASC`,
|
|
1236
|
+
[this.namespace, values]
|
|
1237
|
+
);
|
|
1238
|
+
return rows.map((row) => row.member);
|
|
1239
|
+
}
|
|
1240
|
+
async sdiff(key, ...otherKeys) {
|
|
1241
|
+
const values = [...new Set(otherKeys)];
|
|
1242
|
+
const rows = await this.sql.unsafe(
|
|
1243
|
+
`SELECT member
|
|
1244
|
+
FROM ${this.quotedTableName}
|
|
1245
|
+
WHERE namespace = $1
|
|
1246
|
+
AND key = $2
|
|
1247
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1248
|
+
AND (
|
|
1249
|
+
$3::text[] = ARRAY[]::text[]
|
|
1250
|
+
OR member NOT IN (
|
|
1251
|
+
SELECT member
|
|
1252
|
+
FROM ${this.quotedTableName}
|
|
1253
|
+
WHERE namespace = $1 AND key = ANY($3::text[])
|
|
1254
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1255
|
+
)
|
|
1256
|
+
)
|
|
1257
|
+
ORDER BY member ASC`,
|
|
1258
|
+
[this.namespace, key, values]
|
|
1259
|
+
);
|
|
1260
|
+
return rows.map((row) => row.member);
|
|
1261
|
+
}
|
|
1262
|
+
async scard(key) {
|
|
1263
|
+
const rows = await this.sql.unsafe(
|
|
1264
|
+
`SELECT COUNT(*)::bigint AS count
|
|
1265
|
+
FROM ${this.quotedTableName}
|
|
1266
|
+
WHERE namespace = $1 AND key = $2
|
|
1267
|
+
AND (expires_at IS NULL OR expires_at > NOW())`,
|
|
1268
|
+
[this.namespace, key]
|
|
1269
|
+
);
|
|
1270
|
+
return Number(rows[0]?.count ?? 0);
|
|
1271
|
+
}
|
|
1272
|
+
async sclear(key) {
|
|
1273
|
+
const rows = await this.sql.unsafe(
|
|
1274
|
+
`DELETE FROM ${this.quotedTableName}
|
|
1275
|
+
WHERE namespace = $1 AND key = $2
|
|
1276
|
+
RETURNING member`,
|
|
1277
|
+
[this.namespace, key]
|
|
1278
|
+
);
|
|
1279
|
+
return rows.length;
|
|
1280
|
+
}
|
|
1281
|
+
async sscan(key, cursor = null, count = 100) {
|
|
1282
|
+
const limit = Math.max(1, Math.floor(count));
|
|
1283
|
+
const rows = await this.sql.unsafe(
|
|
1284
|
+
`SELECT member
|
|
1285
|
+
FROM ${this.quotedTableName}
|
|
1286
|
+
WHERE namespace = $1
|
|
1287
|
+
AND key = $2
|
|
1288
|
+
AND member > COALESCE($3::text, '')
|
|
1289
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1290
|
+
ORDER BY member ASC
|
|
1291
|
+
LIMIT $4`,
|
|
1292
|
+
[this.namespace, key, cursor, limit]
|
|
1293
|
+
);
|
|
1294
|
+
return {
|
|
1295
|
+
cursor: rows.length === limit ? rows[rows.length - 1].member : null,
|
|
1296
|
+
members: rows.map((row) => row.member)
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
async expire(key, ttlMs) {
|
|
1300
|
+
const rows = await this.sql.unsafe(
|
|
1301
|
+
`UPDATE ${this.quotedTableName}
|
|
1302
|
+
SET expires_at = NOW() + ($3::bigint * INTERVAL '1 millisecond'),
|
|
1303
|
+
updated_at = NOW()
|
|
1304
|
+
WHERE namespace = $1 AND key = $2
|
|
1305
|
+
RETURNING member`,
|
|
1306
|
+
[this.namespace, key, Math.max(0, Math.floor(ttlMs))]
|
|
1307
|
+
);
|
|
1308
|
+
return rows.length;
|
|
1309
|
+
}
|
|
1310
|
+
async persist(key) {
|
|
1311
|
+
const rows = await this.sql.unsafe(
|
|
1312
|
+
`UPDATE ${this.quotedTableName}
|
|
1313
|
+
SET expires_at = NULL,
|
|
1314
|
+
updated_at = NOW()
|
|
1315
|
+
WHERE namespace = $1 AND key = $2
|
|
1316
|
+
RETURNING member`,
|
|
1317
|
+
[this.namespace, key]
|
|
1318
|
+
);
|
|
1319
|
+
return rows.length;
|
|
1320
|
+
}
|
|
1321
|
+
async ttl(key) {
|
|
1322
|
+
const rows = await this.sql.unsafe(
|
|
1323
|
+
`SELECT CASE
|
|
1324
|
+
WHEN MAX(expires_at) IS NULL THEN NULL
|
|
1325
|
+
ELSE GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (MAX(expires_at) - NOW())) * 1000))::bigint
|
|
1326
|
+
END AS ttl_ms
|
|
1327
|
+
FROM ${this.quotedTableName}
|
|
1328
|
+
WHERE namespace = $1 AND key = $2`,
|
|
1329
|
+
[this.namespace, key]
|
|
1330
|
+
);
|
|
1331
|
+
return rows[0]?.ttl_ms === null || rows[0]?.ttl_ms === void 0 ? null : Number(rows[0].ttl_ms);
|
|
1332
|
+
}
|
|
1333
|
+
async cleanupExpired(limit = 1e3) {
|
|
1334
|
+
const rows = await this.sql.unsafe(
|
|
1335
|
+
`DELETE FROM ${this.quotedTableName}
|
|
1336
|
+
WHERE ctid IN (
|
|
1337
|
+
SELECT ctid
|
|
1338
|
+
FROM ${this.quotedTableName}
|
|
1339
|
+
WHERE expires_at IS NOT NULL AND expires_at <= NOW()
|
|
1340
|
+
LIMIT $1
|
|
1341
|
+
)
|
|
1342
|
+
RETURNING member`,
|
|
1343
|
+
[Math.max(1, Math.floor(limit))]
|
|
1344
|
+
);
|
|
1345
|
+
return rows.length;
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
function createPgSet(options) {
|
|
1349
|
+
return new PgSet(options);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// src/sorted-set.ts
|
|
1353
|
+
var DEFAULT_TABLE_NAME6 = "pgredis_sorted_set";
|
|
1354
|
+
var DEFAULT_NAMESPACE6 = "default";
|
|
1355
|
+
var PgSortedSet = class {
|
|
1356
|
+
namespace;
|
|
1357
|
+
tableName;
|
|
1358
|
+
quotedTableName;
|
|
1359
|
+
sql;
|
|
1360
|
+
constructor(options) {
|
|
1361
|
+
this.sql = options.sql;
|
|
1362
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE6;
|
|
1363
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME6;
|
|
1364
|
+
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
1365
|
+
}
|
|
1366
|
+
async ensureSchema(options = {}) {
|
|
1367
|
+
const persistence = options.unlogged === false ? "" : "UNLOGGED ";
|
|
1368
|
+
await this.sql.unsafe(`
|
|
1369
|
+
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
1370
|
+
namespace TEXT NOT NULL,
|
|
1371
|
+
key TEXT NOT NULL,
|
|
1372
|
+
member TEXT NOT NULL,
|
|
1373
|
+
score DOUBLE PRECISION NOT NULL,
|
|
1374
|
+
expires_at TIMESTAMPTZ,
|
|
1375
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
1376
|
+
PRIMARY KEY (namespace, key, member)
|
|
1377
|
+
)
|
|
1378
|
+
`);
|
|
1379
|
+
await this.sql.unsafe(`
|
|
1380
|
+
ALTER TABLE ${this.quotedTableName}
|
|
1381
|
+
ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ
|
|
1382
|
+
`);
|
|
1383
|
+
await this.sql.unsafe(`
|
|
1384
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "score")}
|
|
1385
|
+
ON ${this.quotedTableName} (namespace, key, score ASC, member ASC)
|
|
1386
|
+
`);
|
|
1387
|
+
await this.sql.unsafe(`
|
|
1388
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
|
|
1389
|
+
ON ${this.quotedTableName} (expires_at)
|
|
1390
|
+
WHERE expires_at IS NOT NULL
|
|
1391
|
+
`);
|
|
1392
|
+
}
|
|
1393
|
+
async zadd(key, score, member) {
|
|
1394
|
+
if (!Number.isFinite(score)) throw new Error(`Invalid sorted-set score: ${score}`);
|
|
1395
|
+
const rows = await this.sql.unsafe(
|
|
1396
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, member, score, expires_at, updated_at)
|
|
1397
|
+
VALUES (
|
|
1398
|
+
$1,
|
|
1399
|
+
$2,
|
|
1400
|
+
$3,
|
|
1401
|
+
$4,
|
|
1402
|
+
(SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $1 AND key = $2),
|
|
1403
|
+
NOW()
|
|
1404
|
+
)
|
|
1405
|
+
ON CONFLICT (namespace, key, member) DO UPDATE
|
|
1406
|
+
SET score = EXCLUDED.score,
|
|
1407
|
+
updated_at = NOW()
|
|
1408
|
+
RETURNING (xmax = 0)::int AS inserted`,
|
|
1409
|
+
[this.namespace, key, member, score]
|
|
1410
|
+
);
|
|
1411
|
+
return Number(rows[0]?.inserted ?? 0) === 1;
|
|
1412
|
+
}
|
|
1413
|
+
async zscore(key, member) {
|
|
1414
|
+
const rows = await this.sql.unsafe(
|
|
1415
|
+
`SELECT score
|
|
1416
|
+
FROM ${this.quotedTableName}
|
|
1417
|
+
WHERE namespace = $1 AND key = $2 AND member = $3
|
|
1418
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1419
|
+
LIMIT 1`,
|
|
1420
|
+
[this.namespace, key, member]
|
|
1421
|
+
);
|
|
1422
|
+
return rows[0] ? Number(rows[0].score) : null;
|
|
1423
|
+
}
|
|
1424
|
+
async zrange(key, start = 0, stop = -1, options = {}) {
|
|
1425
|
+
const limit = stop < 0 ? null : Math.max(0, stop - start + 1);
|
|
1426
|
+
const order = options.desc ? "DESC" : "ASC";
|
|
1427
|
+
const rows = await this.sql.unsafe(
|
|
1428
|
+
`SELECT member, score
|
|
1429
|
+
FROM ${this.quotedTableName}
|
|
1430
|
+
WHERE namespace = $1 AND key = $2
|
|
1431
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1432
|
+
ORDER BY score ${order}, member ${order}
|
|
1433
|
+
OFFSET $3
|
|
1434
|
+
LIMIT COALESCE($4::bigint, 9223372036854775807)`,
|
|
1435
|
+
[this.namespace, key, Math.max(0, start), limit]
|
|
1436
|
+
);
|
|
1437
|
+
if (options.withScores) {
|
|
1438
|
+
return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
|
|
1439
|
+
}
|
|
1440
|
+
return rows.map((row) => row.member);
|
|
1441
|
+
}
|
|
1442
|
+
async zrangeByScore(key, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY, options = {}) {
|
|
1443
|
+
const order = options.desc ? "DESC" : "ASC";
|
|
1444
|
+
const rows = await this.sql.unsafe(
|
|
1445
|
+
`SELECT member, score
|
|
1446
|
+
FROM ${this.quotedTableName}
|
|
1447
|
+
WHERE namespace = $1
|
|
1448
|
+
AND key = $2
|
|
1449
|
+
AND score >= $3
|
|
1450
|
+
AND score <= $4
|
|
1451
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1452
|
+
ORDER BY score ${order}, member ${order}
|
|
1453
|
+
OFFSET $5
|
|
1454
|
+
LIMIT COALESCE($6::bigint, 9223372036854775807)`,
|
|
1455
|
+
[
|
|
1456
|
+
this.namespace,
|
|
1457
|
+
key,
|
|
1458
|
+
min,
|
|
1459
|
+
max,
|
|
1460
|
+
Math.max(0, options.offset || 0),
|
|
1461
|
+
options.limit === void 0 ? null : Math.max(0, Math.floor(options.limit))
|
|
1462
|
+
]
|
|
1463
|
+
);
|
|
1464
|
+
if (options.withScores) {
|
|
1465
|
+
return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
|
|
1466
|
+
}
|
|
1467
|
+
return rows.map((row) => row.member);
|
|
1468
|
+
}
|
|
1469
|
+
async zrank(key, member, options = {}) {
|
|
1470
|
+
const comparator = options.desc ? "(candidate.score > target.score OR (candidate.score = target.score AND candidate.member > target.member))" : "(candidate.score < target.score OR (candidate.score = target.score AND candidate.member < target.member))";
|
|
1471
|
+
const rows = await this.sql.unsafe(
|
|
1472
|
+
`WITH target AS (
|
|
1473
|
+
SELECT score, member
|
|
1474
|
+
FROM ${this.quotedTableName}
|
|
1475
|
+
WHERE namespace = $1 AND key = $2 AND member = $3
|
|
1476
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1477
|
+
)
|
|
1478
|
+
SELECT CASE
|
|
1479
|
+
WHEN EXISTS (SELECT 1 FROM target) THEN COUNT(candidate.member)::bigint
|
|
1480
|
+
ELSE NULL
|
|
1481
|
+
END AS count
|
|
1482
|
+
FROM target
|
|
1483
|
+
JOIN ${this.quotedTableName} candidate
|
|
1484
|
+
ON candidate.namespace = $1
|
|
1485
|
+
AND candidate.key = $2
|
|
1486
|
+
AND (candidate.expires_at IS NULL OR candidate.expires_at > NOW())
|
|
1487
|
+
AND ${comparator}`,
|
|
1488
|
+
[this.namespace, key, member]
|
|
1489
|
+
);
|
|
1490
|
+
if (rows.length === 0 || rows[0]?.count === null || rows[0]?.count === void 0) return null;
|
|
1491
|
+
return Number(rows[0].count);
|
|
1492
|
+
}
|
|
1493
|
+
async zcount(key, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
|
|
1494
|
+
const rows = await this.sql.unsafe(
|
|
1495
|
+
`SELECT COUNT(*)::bigint AS count
|
|
1496
|
+
FROM ${this.quotedTableName}
|
|
1497
|
+
WHERE namespace = $1
|
|
1498
|
+
AND key = $2
|
|
1499
|
+
AND score >= $3
|
|
1500
|
+
AND score <= $4
|
|
1501
|
+
AND (expires_at IS NULL OR expires_at > NOW())`,
|
|
1502
|
+
[this.namespace, key, min, max]
|
|
1503
|
+
);
|
|
1504
|
+
return Number(rows[0]?.count ?? 0);
|
|
1505
|
+
}
|
|
1506
|
+
async zrem(key, ...members) {
|
|
1507
|
+
const values = [...new Set(members)];
|
|
1508
|
+
if (values.length === 0) return 0;
|
|
1509
|
+
const placeholders = values.map((_, index) => `$${index + 3}`).join(", ");
|
|
1510
|
+
const rows = await this.sql.unsafe(
|
|
1511
|
+
`DELETE FROM ${this.quotedTableName}
|
|
1512
|
+
WHERE namespace = $1 AND key = $2 AND member IN (${placeholders})
|
|
1513
|
+
RETURNING member`,
|
|
1514
|
+
[this.namespace, key, ...values]
|
|
1515
|
+
);
|
|
1516
|
+
return rows.length;
|
|
1517
|
+
}
|
|
1518
|
+
async zpopmin(key, count = 1) {
|
|
1519
|
+
const rows = await this.sql.unsafe(
|
|
1520
|
+
`DELETE FROM ${this.quotedTableName}
|
|
1521
|
+
WHERE (namespace, key, member) IN (
|
|
1522
|
+
SELECT namespace, key, member
|
|
1523
|
+
FROM ${this.quotedTableName}
|
|
1524
|
+
WHERE namespace = $1 AND key = $2
|
|
1525
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1526
|
+
ORDER BY score ASC, member ASC
|
|
1527
|
+
LIMIT $3
|
|
1528
|
+
)
|
|
1529
|
+
RETURNING member, score`,
|
|
1530
|
+
[this.namespace, key, Math.max(1, Math.floor(count))]
|
|
1531
|
+
);
|
|
1532
|
+
return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
|
|
1533
|
+
}
|
|
1534
|
+
async zscan(key, cursor = null, count = 100) {
|
|
1535
|
+
const limit = Math.max(1, Math.floor(count));
|
|
1536
|
+
const rows = await this.sql.unsafe(
|
|
1537
|
+
`SELECT member, score
|
|
1538
|
+
FROM ${this.quotedTableName}
|
|
1539
|
+
WHERE namespace = $1
|
|
1540
|
+
AND key = $2
|
|
1541
|
+
AND member > COALESCE($3::text, '')
|
|
1542
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1543
|
+
ORDER BY member ASC
|
|
1544
|
+
LIMIT $4`,
|
|
1545
|
+
[this.namespace, key, cursor, limit]
|
|
1546
|
+
);
|
|
1547
|
+
return {
|
|
1548
|
+
cursor: rows.length === limit ? rows[rows.length - 1].member : null,
|
|
1549
|
+
entries: rows.map((row) => ({ member: row.member, score: Number(row.score) }))
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
async expire(key, ttlMs) {
|
|
1553
|
+
const rows = await this.sql.unsafe(
|
|
1554
|
+
`UPDATE ${this.quotedTableName}
|
|
1555
|
+
SET expires_at = NOW() + ($3::bigint * INTERVAL '1 millisecond'),
|
|
1556
|
+
updated_at = NOW()
|
|
1557
|
+
WHERE namespace = $1 AND key = $2
|
|
1558
|
+
RETURNING member`,
|
|
1559
|
+
[this.namespace, key, Math.max(0, Math.floor(ttlMs))]
|
|
1560
|
+
);
|
|
1561
|
+
return rows.length;
|
|
1562
|
+
}
|
|
1563
|
+
async persist(key) {
|
|
1564
|
+
const rows = await this.sql.unsafe(
|
|
1565
|
+
`UPDATE ${this.quotedTableName}
|
|
1566
|
+
SET expires_at = NULL,
|
|
1567
|
+
updated_at = NOW()
|
|
1568
|
+
WHERE namespace = $1 AND key = $2
|
|
1569
|
+
RETURNING member`,
|
|
1570
|
+
[this.namespace, key]
|
|
1571
|
+
);
|
|
1572
|
+
return rows.length;
|
|
1573
|
+
}
|
|
1574
|
+
async ttl(key) {
|
|
1575
|
+
const rows = await this.sql.unsafe(
|
|
1576
|
+
`SELECT CASE
|
|
1577
|
+
WHEN MAX(expires_at) IS NULL THEN NULL
|
|
1578
|
+
ELSE GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (MAX(expires_at) - NOW())) * 1000))::bigint
|
|
1579
|
+
END AS ttl_ms
|
|
1580
|
+
FROM ${this.quotedTableName}
|
|
1581
|
+
WHERE namespace = $1 AND key = $2`,
|
|
1582
|
+
[this.namespace, key]
|
|
1583
|
+
);
|
|
1584
|
+
return rows[0]?.ttl_ms === null || rows[0]?.ttl_ms === void 0 ? null : Number(rows[0].ttl_ms);
|
|
1585
|
+
}
|
|
1586
|
+
async cleanupExpired(limit = 1e3) {
|
|
1587
|
+
const rows = await this.sql.unsafe(
|
|
1588
|
+
`DELETE FROM ${this.quotedTableName}
|
|
1589
|
+
WHERE ctid IN (
|
|
1590
|
+
SELECT ctid
|
|
1591
|
+
FROM ${this.quotedTableName}
|
|
1592
|
+
WHERE expires_at IS NOT NULL AND expires_at <= NOW()
|
|
1593
|
+
LIMIT $1
|
|
1594
|
+
)
|
|
1595
|
+
RETURNING member`,
|
|
1596
|
+
[Math.max(1, Math.floor(limit))]
|
|
1597
|
+
);
|
|
1598
|
+
return rows.length;
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
function createPgSortedSet(options) {
|
|
1602
|
+
return new PgSortedSet(options);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
// src/client.ts
|
|
1606
|
+
function tableName(prefix, name) {
|
|
1607
|
+
return `${prefix}_${name}`;
|
|
1608
|
+
}
|
|
1609
|
+
function createPgredis(options) {
|
|
1610
|
+
const namespace = options.namespace || "default";
|
|
1611
|
+
const prefix = options.tablePrefix || "pgredis";
|
|
1612
|
+
const cache = createPgKvCache({
|
|
1613
|
+
...options.cache,
|
|
1614
|
+
sql: options.sql,
|
|
1615
|
+
namespace,
|
|
1616
|
+
tableName: options.cache?.tableName || tableName(prefix, "kv")
|
|
1617
|
+
});
|
|
1618
|
+
const counter = createPgCounter({
|
|
1619
|
+
sql: options.sql,
|
|
1620
|
+
namespace,
|
|
1621
|
+
tableName: tableName(prefix, "counter")
|
|
1622
|
+
});
|
|
1623
|
+
const hash = createPgHash({
|
|
1624
|
+
sql: options.sql,
|
|
1625
|
+
namespace,
|
|
1626
|
+
tableName: tableName(prefix, "hash")
|
|
1627
|
+
});
|
|
1628
|
+
const set = createPgSet({
|
|
1629
|
+
sql: options.sql,
|
|
1630
|
+
namespace,
|
|
1631
|
+
tableName: tableName(prefix, "set")
|
|
1632
|
+
});
|
|
1633
|
+
const list = createPgList({
|
|
1634
|
+
sql: options.sql,
|
|
1635
|
+
namespace,
|
|
1636
|
+
tableName: tableName(prefix, "list")
|
|
1637
|
+
});
|
|
1638
|
+
const sortedSet = createPgSortedSet({
|
|
1639
|
+
sql: options.sql,
|
|
1640
|
+
namespace,
|
|
1641
|
+
tableName: tableName(prefix, "sorted_set")
|
|
1642
|
+
});
|
|
1643
|
+
const rateLimit = options.rateLimit ? createPgFixedWindowRateLimiter({
|
|
1644
|
+
sql: options.sql,
|
|
1645
|
+
namespace,
|
|
1646
|
+
limit: options.rateLimit.limit,
|
|
1647
|
+
windowMs: options.rateLimit.windowMs,
|
|
1648
|
+
tableName: options.rateLimit.tableName || tableName(prefix, "rate_limit")
|
|
1649
|
+
}) : void 0;
|
|
1650
|
+
const queue = options.queue ? createPgBossJobQueue(options.queue) : void 0;
|
|
1651
|
+
return {
|
|
1652
|
+
cache,
|
|
1653
|
+
counter,
|
|
1654
|
+
hash,
|
|
1655
|
+
set,
|
|
1656
|
+
list,
|
|
1657
|
+
sortedSet,
|
|
1658
|
+
locks: createPgAdvisoryLocker(options.sql),
|
|
1659
|
+
pubsub: createPgPublisher(options.sql),
|
|
1660
|
+
rateLimit,
|
|
1661
|
+
queue,
|
|
1662
|
+
async health() {
|
|
1663
|
+
await options.sql.unsafe("SELECT 1");
|
|
1664
|
+
return { ok: true };
|
|
1665
|
+
},
|
|
1666
|
+
async stats() {
|
|
1667
|
+
const boss = queue ? await queue.getBoss() : null;
|
|
1668
|
+
return {
|
|
1669
|
+
cache: cache.stats(),
|
|
1670
|
+
queue: boss ? await boss.getQueues() : void 0
|
|
1671
|
+
};
|
|
1672
|
+
},
|
|
1673
|
+
async cleanupExpired(limit = 1e3) {
|
|
1674
|
+
const [
|
|
1675
|
+
cacheDeleted,
|
|
1676
|
+
counterDeleted,
|
|
1677
|
+
hashDeleted,
|
|
1678
|
+
setDeleted,
|
|
1679
|
+
listDeleted,
|
|
1680
|
+
sortedSetDeleted,
|
|
1681
|
+
rateLimitDeleted
|
|
1682
|
+
] = await Promise.all([
|
|
1683
|
+
cache.cleanupExpired(limit),
|
|
1684
|
+
counter.cleanupExpired(limit),
|
|
1685
|
+
hash.cleanupExpired(limit),
|
|
1686
|
+
set.cleanupExpired(limit),
|
|
1687
|
+
list.cleanupExpired(limit),
|
|
1688
|
+
sortedSet.cleanupExpired(limit),
|
|
1689
|
+
rateLimit ? rateLimit.cleanupExpired(limit) : Promise.resolve(0)
|
|
1690
|
+
]);
|
|
1691
|
+
return {
|
|
1692
|
+
cache: cacheDeleted,
|
|
1693
|
+
counter: counterDeleted,
|
|
1694
|
+
hash: hashDeleted,
|
|
1695
|
+
set: setDeleted,
|
|
1696
|
+
list: listDeleted,
|
|
1697
|
+
sortedSet: sortedSetDeleted,
|
|
1698
|
+
rateLimit: rateLimitDeleted
|
|
1699
|
+
};
|
|
1700
|
+
},
|
|
1701
|
+
startCleanupWorker(cleanupOptions = {}) {
|
|
1702
|
+
const intervalMs = cleanupOptions.intervalMs ?? 6e4;
|
|
1703
|
+
const limit = cleanupOptions.limit ?? 1e3;
|
|
1704
|
+
const timer = setInterval(() => {
|
|
1705
|
+
void this.cleanupExpired(limit).catch((error) => {
|
|
1706
|
+
cleanupOptions.onError?.(error);
|
|
1707
|
+
});
|
|
1708
|
+
}, intervalMs);
|
|
1709
|
+
return () => clearInterval(timer);
|
|
1710
|
+
},
|
|
1711
|
+
async ensureSchema() {
|
|
1712
|
+
await cache.ensureSchema();
|
|
1713
|
+
await counter.ensureSchema();
|
|
1714
|
+
await hash.ensureSchema();
|
|
1715
|
+
await set.ensureSchema();
|
|
1716
|
+
await list.ensureSchema();
|
|
1717
|
+
await sortedSet.ensureSchema();
|
|
1718
|
+
if (rateLimit) await rateLimit.ensureSchema();
|
|
1719
|
+
}
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
export {
|
|
1723
|
+
PgAdvisoryLockBusyError,
|
|
1724
|
+
PgAdvisoryLocker,
|
|
1725
|
+
PgBossJobQueue,
|
|
1726
|
+
PgCounter,
|
|
1727
|
+
PgFixedWindowRateLimiter,
|
|
1728
|
+
PgHash,
|
|
1729
|
+
PgKvCache,
|
|
1730
|
+
PgList,
|
|
1731
|
+
PgSet,
|
|
1732
|
+
PgSlidingWindowRateLimiter,
|
|
1733
|
+
PgSortedSet,
|
|
1734
|
+
PgTokenBucketRateLimiter,
|
|
1735
|
+
advisoryLockKeyToSqlArgs,
|
|
1736
|
+
createBunPgListener,
|
|
1737
|
+
createPgAdvisoryLocker,
|
|
1738
|
+
createPgBossJobQueue,
|
|
1739
|
+
createPgCounter,
|
|
1740
|
+
createPgFixedWindowRateLimiter,
|
|
1741
|
+
createPgHash,
|
|
1742
|
+
createPgKvCache,
|
|
1743
|
+
createPgList,
|
|
1744
|
+
createPgListener,
|
|
1745
|
+
createPgPublisher,
|
|
1746
|
+
createPgSet,
|
|
1747
|
+
createPgSlidingWindowRateLimiter,
|
|
1748
|
+
createPgSortedSet,
|
|
1749
|
+
createPgTokenBucketRateLimiter,
|
|
1750
|
+
createPgredis,
|
|
1751
|
+
indexName,
|
|
1752
|
+
normalizePositiveInteger,
|
|
1753
|
+
publishPgNotify,
|
|
1754
|
+
quoteIdentifier,
|
|
1755
|
+
quoteQualifiedName,
|
|
1756
|
+
withPgAdvisoryLock
|
|
1757
|
+
};
|