@postgresx/noredis 0.1.0 → 0.6.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 +625 -25
- package/dist/adapters/ioredis.d.ts +130 -0
- package/dist/adapters/ioredis.js +141 -0
- package/dist/adapters/node.d.ts +1 -1
- package/dist/adapters/redis.d.ts +143 -0
- package/dist/adapters/redis.js +118 -0
- package/dist/adapters/web.d.ts +30 -0
- package/dist/adapters/web.js +64 -0
- package/dist/chunk-3DNTNHVD.js +295 -0
- package/dist/chunk-5ZGPCW5N.js +288 -0
- package/dist/chunk-HW3WONAC.js +239 -0
- package/dist/chunk-QI73S2FT.js +101 -0
- package/dist/chunk-RWRM5RVO.js +30 -0
- package/dist/{chunk-GBFG2TOL.js → chunk-VLFUE33D.js} +264 -16
- package/dist/chunk-WRMEEA6T.js +246 -0
- package/dist/chunk-YSWHEFPX.js +328 -0
- package/dist/client-DP3ssToT.d.ts +509 -0
- package/dist/hash-index.d.ts +43 -0
- package/dist/hash-index.js +9 -0
- package/dist/index.d.ts +16 -403
- package/dist/index.js +448 -988
- package/dist/kv-cache.d.ts +38 -2
- package/dist/kv-cache.js +1 -1
- package/dist/kv.d.ts +1 -0
- package/dist/kv.js +8 -0
- package/dist/list-index.d.ts +53 -0
- package/dist/list-index.js +9 -0
- package/dist/{pubsub-CHGs5dXU.d.ts → pubsub-index.d.ts} +1 -1
- package/dist/pubsub-index.js +12 -0
- package/dist/set-index.d.ts +42 -0
- package/dist/set-index.js +9 -0
- package/dist/sorted-set-index.d.ts +58 -0
- package/dist/sorted-set-index.js +9 -0
- package/package.json +54 -4
package/dist/index.js
CHANGED
|
@@ -1,7 +1,39 @@
|
|
|
1
|
+
import {
|
|
2
|
+
UnsupportedCommandError,
|
|
3
|
+
createPgredisMigrationAliases
|
|
4
|
+
} from "./chunk-WRMEEA6T.js";
|
|
5
|
+
import {
|
|
6
|
+
PgHash,
|
|
7
|
+
createPgHash
|
|
8
|
+
} from "./chunk-5ZGPCW5N.js";
|
|
1
9
|
import {
|
|
2
10
|
PgKvCache,
|
|
3
11
|
createPgKvCache
|
|
4
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-VLFUE33D.js";
|
|
13
|
+
import {
|
|
14
|
+
PgList,
|
|
15
|
+
createPgList
|
|
16
|
+
} from "./chunk-HW3WONAC.js";
|
|
17
|
+
import {
|
|
18
|
+
createBunPgListener,
|
|
19
|
+
createPgListener,
|
|
20
|
+
createPgPublisher,
|
|
21
|
+
publishPgNotify
|
|
22
|
+
} from "./chunk-QI73S2FT.js";
|
|
23
|
+
import {
|
|
24
|
+
PgSet,
|
|
25
|
+
createPgSet
|
|
26
|
+
} from "./chunk-3DNTNHVD.js";
|
|
27
|
+
import {
|
|
28
|
+
PgSortedSet,
|
|
29
|
+
createPgSortedSet
|
|
30
|
+
} from "./chunk-YSWHEFPX.js";
|
|
31
|
+
import {
|
|
32
|
+
indexName,
|
|
33
|
+
normalizePositiveInteger,
|
|
34
|
+
quoteIdentifier,
|
|
35
|
+
quoteQualifiedName
|
|
36
|
+
} from "./chunk-RWRM5RVO.js";
|
|
5
37
|
|
|
6
38
|
// src/advisory-lock.ts
|
|
7
39
|
var PgAdvisoryLockBusyError = class extends Error {
|
|
@@ -87,30 +119,6 @@ function createPgAdvisoryLocker(sql) {
|
|
|
87
119
|
return new PgAdvisoryLocker(sql);
|
|
88
120
|
}
|
|
89
121
|
|
|
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
122
|
// src/counter.ts
|
|
115
123
|
var DEFAULT_TABLE_NAME = "pgredis_counter";
|
|
116
124
|
var DEFAULT_NAMESPACE = "default";
|
|
@@ -237,547 +245,113 @@ function createPgCounter(options) {
|
|
|
237
245
|
return new PgCounter(options);
|
|
238
246
|
}
|
|
239
247
|
|
|
240
|
-
// src/
|
|
241
|
-
var
|
|
242
|
-
var
|
|
243
|
-
function
|
|
244
|
-
|
|
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);
|
|
248
|
+
// src/metrics.ts
|
|
249
|
+
var DEFAULT_TABLE_PREFIX = "pgredis";
|
|
250
|
+
var DEFAULT_SUFFIXES = ["kv", "counter", "hash", "set", "list", "sorted_set", "rate_limit", "outbox"];
|
|
251
|
+
function toDate(value) {
|
|
252
|
+
if (value === null) return null;
|
|
253
|
+
return value instanceof Date ? value : new Date(value);
|
|
476
254
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
var DEFAULT_TABLE_NAME3 = "pgredis_list";
|
|
480
|
-
var DEFAULT_NAMESPACE3 = "default";
|
|
481
|
-
function jsonValue2(value) {
|
|
482
|
-
return JSON.stringify(value);
|
|
255
|
+
function defaultTableNames(prefix) {
|
|
256
|
+
return DEFAULT_SUFFIXES.map((suffix) => `${prefix}_${suffix}`);
|
|
483
257
|
}
|
|
484
|
-
function
|
|
485
|
-
if (typeof value !== "string") return value;
|
|
258
|
+
async function collectTtlBacklog(sql, tableName2) {
|
|
486
259
|
try {
|
|
487
|
-
|
|
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(
|
|
260
|
+
const rows = await sql.unsafe(
|
|
560
261
|
`SELECT COUNT(*)::bigint AS count
|
|
561
|
-
FROM ${
|
|
562
|
-
WHERE
|
|
563
|
-
AND (expires_at IS NULL OR expires_at > NOW())`,
|
|
564
|
-
[this.namespace, key]
|
|
262
|
+
FROM ${quoteQualifiedName(tableName2)}
|
|
263
|
+
WHERE expires_at IS NOT NULL AND expires_at <= NOW()`
|
|
565
264
|
);
|
|
566
265
|
return Number(rows[0]?.count ?? 0);
|
|
266
|
+
} catch {
|
|
267
|
+
return null;
|
|
567
268
|
}
|
|
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
269
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
if (loadError) return Promise.reject(loadError);
|
|
711
|
-
return new Promise((resolve, reject) => {
|
|
712
|
-
queue.push({
|
|
713
|
-
action,
|
|
714
|
-
resolve,
|
|
715
|
-
reject
|
|
716
|
-
});
|
|
270
|
+
async function collectPgredisMetrics(options) {
|
|
271
|
+
const tableNames = [...options.tableNames ?? defaultTableNames(options.tablePrefix ?? DEFAULT_TABLE_PREFIX)];
|
|
272
|
+
const rows = await options.sql.unsafe(
|
|
273
|
+
`SELECT
|
|
274
|
+
relname,
|
|
275
|
+
pg_total_relation_size(relid)::bigint AS total_bytes,
|
|
276
|
+
n_live_tup,
|
|
277
|
+
n_dead_tup,
|
|
278
|
+
last_vacuum,
|
|
279
|
+
last_autovacuum
|
|
280
|
+
FROM pg_stat_user_tables
|
|
281
|
+
WHERE relname = ANY($1::text[])
|
|
282
|
+
ORDER BY relname ASC`,
|
|
283
|
+
[tableNames]
|
|
284
|
+
);
|
|
285
|
+
const tables = [];
|
|
286
|
+
for (const row of rows) {
|
|
287
|
+
tables.push({
|
|
288
|
+
tableName: row.relname,
|
|
289
|
+
totalBytes: Number(row.total_bytes),
|
|
290
|
+
liveRows: Number(row.n_live_tup),
|
|
291
|
+
deadRows: Number(row.n_dead_tup),
|
|
292
|
+
lastVacuum: toDate(row.last_vacuum),
|
|
293
|
+
lastAutovacuum: toDate(row.last_autovacuum),
|
|
294
|
+
ttlBacklog: await collectTtlBacklog(options.sql, row.relname)
|
|
717
295
|
});
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
|
|
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) {
|
|
296
|
+
}
|
|
297
|
+
const listenerHealth = options.listener?.getHealth();
|
|
298
|
+
const queue = options.queue ? { queues: await (await options.queue.getBoss()).getQueues() } : void 0;
|
|
774
299
|
return {
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
300
|
+
namespace: options.namespace,
|
|
301
|
+
tables,
|
|
302
|
+
cleanup: options.cleanup,
|
|
303
|
+
listener: listenerHealth ? {
|
|
304
|
+
status: listenerHealth.status,
|
|
305
|
+
connected: listenerHealth.connected,
|
|
306
|
+
reconnectAttempts: listenerHealth.reconnectAttempts,
|
|
307
|
+
listeningChannels: listenerHealth.listeningChannels,
|
|
308
|
+
lastConnectedAt: listenerHealth.lastConnectedAt,
|
|
309
|
+
lastNotificationAt: listenerHealth.lastNotificationAt,
|
|
310
|
+
lastError: listenerHealth.lastError
|
|
311
|
+
} : void 0,
|
|
312
|
+
queue
|
|
778
313
|
};
|
|
779
314
|
}
|
|
780
315
|
|
|
316
|
+
// src/pipeline.ts
|
|
317
|
+
var PgredisPipeline = class {
|
|
318
|
+
constructor(runBatch) {
|
|
319
|
+
this.runBatch = runBatch;
|
|
320
|
+
}
|
|
321
|
+
runBatch;
|
|
322
|
+
operations = [];
|
|
323
|
+
add(operation) {
|
|
324
|
+
this.operations.push(operation);
|
|
325
|
+
return this;
|
|
326
|
+
}
|
|
327
|
+
get(key) {
|
|
328
|
+
return this.add((client) => client.cache.get(key));
|
|
329
|
+
}
|
|
330
|
+
set(key, value, options) {
|
|
331
|
+
return this.add((client) => client.cache.set(key, value, options));
|
|
332
|
+
}
|
|
333
|
+
del(key) {
|
|
334
|
+
return this.add((client) => client.cache.delete(key));
|
|
335
|
+
}
|
|
336
|
+
incr(key, amount) {
|
|
337
|
+
return this.add((client) => client.counter.incr(key, amount));
|
|
338
|
+
}
|
|
339
|
+
publish(channel, payload) {
|
|
340
|
+
return this.add((client) => client.pubsub.publish(channel, payload));
|
|
341
|
+
}
|
|
342
|
+
async exec() {
|
|
343
|
+
const operations = [...this.operations];
|
|
344
|
+
this.operations.length = 0;
|
|
345
|
+
return this.runBatch(async (client) => {
|
|
346
|
+
const results = [];
|
|
347
|
+
for (const operation of operations) {
|
|
348
|
+
results.push(await operation(client));
|
|
349
|
+
}
|
|
350
|
+
return results;
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
|
|
781
355
|
// src/queue.ts
|
|
782
356
|
async function loadPgBoss() {
|
|
783
357
|
try {
|
|
@@ -836,10 +410,24 @@ function createPgBossJobQueue(options) {
|
|
|
836
410
|
}
|
|
837
411
|
|
|
838
412
|
// src/rate-limit.ts
|
|
839
|
-
var
|
|
840
|
-
var
|
|
413
|
+
var DEFAULT_TABLE_NAME2 = "pg_rate_limit";
|
|
414
|
+
var DEFAULT_NAMESPACE2 = "default";
|
|
841
415
|
var DEFAULT_SLIDING_TABLE_NAME = "pg_sliding_rate_limit";
|
|
842
416
|
var DEFAULT_TOKEN_BUCKET_TABLE_NAME = "pg_token_bucket_rate_limit";
|
|
417
|
+
var BLOCK_WINDOW_START = -1;
|
|
418
|
+
function normalizeLimit(value, name) {
|
|
419
|
+
if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid ${name}: ${value}`);
|
|
420
|
+
return Math.floor(value);
|
|
421
|
+
}
|
|
422
|
+
function dateMs(value, fallback) {
|
|
423
|
+
if (value instanceof Date) return value.getTime();
|
|
424
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
425
|
+
if (typeof value === "string") {
|
|
426
|
+
const parsed = Date.parse(value);
|
|
427
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
428
|
+
}
|
|
429
|
+
return fallback;
|
|
430
|
+
}
|
|
843
431
|
var PgFixedWindowRateLimiter = class {
|
|
844
432
|
namespace;
|
|
845
433
|
tableName;
|
|
@@ -850,8 +438,8 @@ var PgFixedWindowRateLimiter = class {
|
|
|
850
438
|
windowMs;
|
|
851
439
|
constructor(options) {
|
|
852
440
|
this.sql = options.sql;
|
|
853
|
-
this.namespace = options.namespace ||
|
|
854
|
-
this.tableName = options.tableName ||
|
|
441
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE2;
|
|
442
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME2;
|
|
855
443
|
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
856
444
|
this.now = options.now || Date.now;
|
|
857
445
|
this.limit = normalizePositiveInteger(options.limit, "limit");
|
|
@@ -882,6 +470,8 @@ var PgFixedWindowRateLimiter = class {
|
|
|
882
470
|
const now = this.now();
|
|
883
471
|
const windowStart = Math.floor(now / windowMs) * windowMs;
|
|
884
472
|
const resetAtMs = windowStart + windowMs;
|
|
473
|
+
const blocked = await this.getActiveBlock(key, limit, now, resetAtMs);
|
|
474
|
+
if (blocked) return blocked;
|
|
885
475
|
const rows = await this.sql.unsafe(
|
|
886
476
|
`INSERT INTO ${this.quotedTableName} (namespace, key, window_start, count, expires_at, updated_at)
|
|
887
477
|
VALUES (
|
|
@@ -911,6 +501,90 @@ var PgFixedWindowRateLimiter = class {
|
|
|
911
501
|
retryAfterMs
|
|
912
502
|
};
|
|
913
503
|
}
|
|
504
|
+
async get(key, options = {}) {
|
|
505
|
+
const limit = normalizeLimit(options.limit ?? this.limit, "limit");
|
|
506
|
+
const windowMs = normalizePositiveInteger(options.windowMs ?? this.windowMs, "windowMs");
|
|
507
|
+
const now = this.now();
|
|
508
|
+
const windowStart = Math.floor(now / windowMs) * windowMs;
|
|
509
|
+
const resetAtMs = windowStart + windowMs;
|
|
510
|
+
const blocked = await this.getActiveBlock(key, limit, now, resetAtMs);
|
|
511
|
+
if (blocked) return blocked;
|
|
512
|
+
const rows = await this.sql.unsafe(
|
|
513
|
+
`SELECT count, expires_at
|
|
514
|
+
FROM ${this.quotedTableName}
|
|
515
|
+
WHERE namespace = $1
|
|
516
|
+
AND key = $2
|
|
517
|
+
AND window_start = $3
|
|
518
|
+
AND expires_at > NOW()
|
|
519
|
+
LIMIT 1`,
|
|
520
|
+
[this.namespace, key, windowStart]
|
|
521
|
+
);
|
|
522
|
+
const row = rows[0];
|
|
523
|
+
if (!row) return null;
|
|
524
|
+
return this.resultFromRow(row, limit, now, resetAtMs);
|
|
525
|
+
}
|
|
526
|
+
async reward(key, cost = 1, options = {}) {
|
|
527
|
+
const limit = normalizeLimit(options.limit ?? this.limit, "limit");
|
|
528
|
+
const windowMs = normalizePositiveInteger(options.windowMs ?? this.windowMs, "windowMs");
|
|
529
|
+
const normalizedCost = normalizePositiveInteger(cost, "cost");
|
|
530
|
+
const now = this.now();
|
|
531
|
+
const windowStart = Math.floor(now / windowMs) * windowMs;
|
|
532
|
+
const resetAtMs = windowStart + windowMs;
|
|
533
|
+
const blockRows = await this.decrementWindow(key, BLOCK_WINDOW_START, normalizedCost);
|
|
534
|
+
const blockRow = blockRows[0];
|
|
535
|
+
if (blockRow) return this.resultFromRow(blockRow, limit, now, resetAtMs);
|
|
536
|
+
const rows = await this.decrementWindow(key, windowStart, normalizedCost);
|
|
537
|
+
const row = rows[0];
|
|
538
|
+
if (!row) return null;
|
|
539
|
+
return this.resultFromRow(row, limit, now, resetAtMs);
|
|
540
|
+
}
|
|
541
|
+
async decrementWindow(key, windowStart, cost) {
|
|
542
|
+
return await this.sql.unsafe(
|
|
543
|
+
`UPDATE ${this.quotedTableName}
|
|
544
|
+
SET count = GREATEST(count - $4, 0),
|
|
545
|
+
updated_at = NOW()
|
|
546
|
+
WHERE namespace = $1
|
|
547
|
+
AND key = $2
|
|
548
|
+
AND window_start = $3
|
|
549
|
+
AND expires_at > NOW()
|
|
550
|
+
RETURNING count, expires_at`,
|
|
551
|
+
[this.namespace, key, windowStart, cost]
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
async block(key, options) {
|
|
555
|
+
const limit = normalizeLimit(options.limit ?? this.limit, "limit");
|
|
556
|
+
const blockMs = normalizePositiveInteger(options.blockMs, "blockMs");
|
|
557
|
+
const count = normalizePositiveInteger(options.count ?? Math.max(limit + 1, 1), "count");
|
|
558
|
+
const now = this.now();
|
|
559
|
+
const resetAtMs = now + blockMs;
|
|
560
|
+
const rows = await this.sql.unsafe(
|
|
561
|
+
`INSERT INTO ${this.quotedTableName} (namespace, key, window_start, count, expires_at, updated_at)
|
|
562
|
+
VALUES (
|
|
563
|
+
$1,
|
|
564
|
+
$2,
|
|
565
|
+
$3,
|
|
566
|
+
$4,
|
|
567
|
+
NOW() + ($5::bigint * INTERVAL '1 millisecond'),
|
|
568
|
+
NOW()
|
|
569
|
+
)
|
|
570
|
+
ON CONFLICT (namespace, key, window_start) DO UPDATE
|
|
571
|
+
SET count = GREATEST(${this.quotedTableName}.count, EXCLUDED.count),
|
|
572
|
+
expires_at = GREATEST(${this.quotedTableName}.expires_at, EXCLUDED.expires_at),
|
|
573
|
+
updated_at = NOW()
|
|
574
|
+
RETURNING count, expires_at`,
|
|
575
|
+
[this.namespace, key, BLOCK_WINDOW_START, count, blockMs]
|
|
576
|
+
);
|
|
577
|
+
return this.resultFromRow(rows[0] ?? { count }, limit, now, resetAtMs);
|
|
578
|
+
}
|
|
579
|
+
async delete(key) {
|
|
580
|
+
const rows = await this.sql.unsafe(
|
|
581
|
+
`DELETE FROM ${this.quotedTableName}
|
|
582
|
+
WHERE namespace = $1 AND key = $2
|
|
583
|
+
RETURNING key`,
|
|
584
|
+
[this.namespace, key]
|
|
585
|
+
);
|
|
586
|
+
return rows.length > 0;
|
|
587
|
+
}
|
|
914
588
|
async cleanupExpired(limit = 1e3) {
|
|
915
589
|
const rows = await this.sql.unsafe(
|
|
916
590
|
`DELETE FROM ${this.quotedTableName}
|
|
@@ -923,7 +597,35 @@ var PgFixedWindowRateLimiter = class {
|
|
|
923
597
|
RETURNING key`,
|
|
924
598
|
[Math.max(1, Math.floor(limit))]
|
|
925
599
|
);
|
|
926
|
-
return rows.length;
|
|
600
|
+
return rows.length;
|
|
601
|
+
}
|
|
602
|
+
resultFromRow(row, limit, now, fallbackResetAtMs) {
|
|
603
|
+
const count = Number(row.count);
|
|
604
|
+
const resetAtMs = dateMs(row.expires_at, fallbackResetAtMs);
|
|
605
|
+
const allowed = count <= limit;
|
|
606
|
+
return {
|
|
607
|
+
allowed,
|
|
608
|
+
limit,
|
|
609
|
+
count,
|
|
610
|
+
remaining: Math.max(0, limit - count),
|
|
611
|
+
resetAt: new Date(resetAtMs),
|
|
612
|
+
retryAfterMs: allowed ? 0 : Math.max(0, resetAtMs - now)
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
async getActiveBlock(key, limit, now, fallbackResetAtMs) {
|
|
616
|
+
const rows = await this.sql.unsafe(
|
|
617
|
+
`SELECT count, expires_at
|
|
618
|
+
FROM ${this.quotedTableName}
|
|
619
|
+
WHERE namespace = $1
|
|
620
|
+
AND key = $2
|
|
621
|
+
AND window_start = $3
|
|
622
|
+
AND expires_at > NOW()
|
|
623
|
+
LIMIT 1`,
|
|
624
|
+
[this.namespace, key, BLOCK_WINDOW_START]
|
|
625
|
+
);
|
|
626
|
+
const row = rows[0];
|
|
627
|
+
if (!row || Number(row.count) <= limit) return null;
|
|
628
|
+
return this.resultFromRow(row, limit, now, fallbackResetAtMs);
|
|
927
629
|
}
|
|
928
630
|
};
|
|
929
631
|
function createPgFixedWindowRateLimiter(options) {
|
|
@@ -940,7 +642,7 @@ var PgSlidingWindowRateLimiter = class {
|
|
|
940
642
|
precisionMs;
|
|
941
643
|
constructor(options) {
|
|
942
644
|
this.sql = options.sql;
|
|
943
|
-
this.namespace = options.namespace ||
|
|
645
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE2;
|
|
944
646
|
this.tableName = options.tableName || DEFAULT_SLIDING_TABLE_NAME;
|
|
945
647
|
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
946
648
|
this.now = options.now || Date.now;
|
|
@@ -1033,7 +735,7 @@ var PgTokenBucketRateLimiter = class {
|
|
|
1033
735
|
refillIntervalMs;
|
|
1034
736
|
constructor(options) {
|
|
1035
737
|
this.sql = options.sql;
|
|
1036
|
-
this.namespace = options.namespace ||
|
|
738
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE2;
|
|
1037
739
|
this.tableName = options.tableName || DEFAULT_TOKEN_BUCKET_TABLE_NAME;
|
|
1038
740
|
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
1039
741
|
this.now = options.now || Date.now;
|
|
@@ -1117,489 +819,199 @@ function createPgTokenBucketRateLimiter(options) {
|
|
|
1117
819
|
return new PgTokenBucketRateLimiter(options);
|
|
1118
820
|
}
|
|
1119
821
|
|
|
1120
|
-
// src/
|
|
1121
|
-
var
|
|
1122
|
-
var
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
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;
|
|
822
|
+
// src/stream.ts
|
|
823
|
+
var DEFAULT_TABLE_NAME3 = "pgredis_outbox";
|
|
824
|
+
var DEFAULT_NAMESPACE3 = "default";
|
|
825
|
+
function jsonValue(value) {
|
|
826
|
+
return JSON.stringify(value);
|
|
827
|
+
}
|
|
828
|
+
function parseValue(value) {
|
|
829
|
+
if (typeof value !== "string") return value;
|
|
830
|
+
try {
|
|
831
|
+
return JSON.parse(value);
|
|
832
|
+
} catch {
|
|
833
|
+
return value;
|
|
1346
834
|
}
|
|
1347
|
-
};
|
|
1348
|
-
function createPgSet(options) {
|
|
1349
|
-
return new PgSet(options);
|
|
1350
835
|
}
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
836
|
+
function toDate2(value) {
|
|
837
|
+
if (value === null) return null;
|
|
838
|
+
return value instanceof Date ? value : new Date(value);
|
|
839
|
+
}
|
|
840
|
+
function normalizeLimit2(limit, fallback) {
|
|
841
|
+
if (limit === void 0) return fallback;
|
|
842
|
+
if (!Number.isFinite(limit)) throw new Error(`Invalid limit: ${limit}`);
|
|
843
|
+
return Math.max(1, Math.floor(limit));
|
|
844
|
+
}
|
|
845
|
+
var PgOutboxStream = class {
|
|
1356
846
|
namespace;
|
|
1357
847
|
tableName;
|
|
1358
848
|
quotedTableName;
|
|
1359
849
|
sql;
|
|
1360
850
|
constructor(options) {
|
|
1361
851
|
this.sql = options.sql;
|
|
1362
|
-
this.namespace = options.namespace ||
|
|
1363
|
-
this.tableName = options.tableName ||
|
|
852
|
+
this.namespace = options.namespace || DEFAULT_NAMESPACE3;
|
|
853
|
+
this.tableName = options.tableName || DEFAULT_TABLE_NAME3;
|
|
1364
854
|
this.quotedTableName = quoteQualifiedName(this.tableName);
|
|
1365
855
|
}
|
|
1366
856
|
async ensureSchema(options = {}) {
|
|
1367
|
-
const persistence = options.unlogged ===
|
|
857
|
+
const persistence = options.unlogged === true ? "UNLOGGED " : "";
|
|
1368
858
|
await this.sql.unsafe(`
|
|
1369
859
|
CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
|
|
860
|
+
id BIGSERIAL PRIMARY KEY,
|
|
1370
861
|
namespace TEXT NOT NULL,
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
862
|
+
stream TEXT NOT NULL,
|
|
863
|
+
payload JSONB NOT NULL,
|
|
864
|
+
consumer TEXT,
|
|
865
|
+
delivery_count INTEGER NOT NULL DEFAULT 0,
|
|
866
|
+
available_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
867
|
+
locked_until TIMESTAMPTZ,
|
|
868
|
+
processed_at TIMESTAMPTZ,
|
|
869
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
870
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
1377
871
|
)
|
|
1378
872
|
`);
|
|
1379
873
|
await this.sql.unsafe(`
|
|
1380
|
-
|
|
1381
|
-
|
|
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)
|
|
874
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "ready")}
|
|
875
|
+
ON ${this.quotedTableName} (namespace, stream, available_at, id)
|
|
876
|
+
WHERE processed_at IS NULL
|
|
1386
877
|
`);
|
|
1387
878
|
await this.sql.unsafe(`
|
|
1388
|
-
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "
|
|
1389
|
-
ON ${this.quotedTableName} (
|
|
1390
|
-
WHERE
|
|
879
|
+
CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "processed")}
|
|
880
|
+
ON ${this.quotedTableName} (namespace, processed_at, id)
|
|
881
|
+
WHERE processed_at IS NOT NULL
|
|
1391
882
|
`);
|
|
1392
883
|
}
|
|
1393
|
-
async
|
|
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) {
|
|
884
|
+
async append(stream, payload, options = {}) {
|
|
1414
885
|
const rows = await this.sql.unsafe(
|
|
1415
|
-
`
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
LIMIT 1`,
|
|
1420
|
-
[this.namespace, key, member]
|
|
886
|
+
`INSERT INTO ${this.quotedTableName} (namespace, stream, payload, available_at, updated_at)
|
|
887
|
+
VALUES ($1, $2, $3::jsonb, COALESCE($4::timestamptz, NOW()), NOW())
|
|
888
|
+
RETURNING id`,
|
|
889
|
+
[this.namespace, stream, jsonValue(payload), options.availableAt ?? null]
|
|
1421
890
|
);
|
|
1422
|
-
return
|
|
891
|
+
return String(rows[0]?.id);
|
|
1423
892
|
}
|
|
1424
|
-
async
|
|
1425
|
-
|
|
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);
|
|
893
|
+
async xadd(stream, payload, options = {}) {
|
|
894
|
+
return this.append(stream, payload, options);
|
|
1441
895
|
}
|
|
1442
|
-
async
|
|
1443
|
-
const order = options.desc ? "DESC" : "ASC";
|
|
896
|
+
async read(stream, options = {}) {
|
|
1444
897
|
const rows = await this.sql.unsafe(
|
|
1445
|
-
`SELECT
|
|
898
|
+
`SELECT id, stream, payload, consumer, delivery_count, available_at, locked_until, processed_at, created_at
|
|
1446
899
|
FROM ${this.quotedTableName}
|
|
1447
900
|
WHERE namespace = $1
|
|
1448
|
-
AND
|
|
1449
|
-
AND
|
|
1450
|
-
AND
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
OFFSET $5
|
|
1454
|
-
LIMIT COALESCE($6::bigint, 9223372036854775807)`,
|
|
901
|
+
AND stream = $2
|
|
902
|
+
AND id > $3::bigint
|
|
903
|
+
AND ($5::boolean OR processed_at IS NULL)
|
|
904
|
+
ORDER BY id ASC
|
|
905
|
+
LIMIT $4`,
|
|
1455
906
|
[
|
|
1456
907
|
this.namespace,
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
options.limit === void 0 ? null : Math.max(0, Math.floor(options.limit))
|
|
908
|
+
stream,
|
|
909
|
+
options.afterId ?? 0,
|
|
910
|
+
normalizeLimit2(options.limit, 100),
|
|
911
|
+
options.includeProcessed ?? false
|
|
1462
912
|
]
|
|
1463
913
|
);
|
|
1464
|
-
|
|
1465
|
-
return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
|
|
1466
|
-
}
|
|
1467
|
-
return rows.map((row) => row.member);
|
|
914
|
+
return rows.map((row) => this.mapMessage(row));
|
|
1468
915
|
}
|
|
1469
|
-
async
|
|
1470
|
-
const
|
|
916
|
+
async claim(stream, consumer, options = {}) {
|
|
917
|
+
const visibilityTimeoutMs = Math.max(1, Math.floor(options.visibilityTimeoutMs ?? 3e4));
|
|
1471
918
|
const rows = await this.sql.unsafe(
|
|
1472
|
-
`WITH
|
|
1473
|
-
SELECT
|
|
919
|
+
`WITH picked AS (
|
|
920
|
+
SELECT id
|
|
1474
921
|
FROM ${this.quotedTableName}
|
|
1475
|
-
WHERE namespace = $1
|
|
1476
|
-
AND
|
|
922
|
+
WHERE namespace = $1
|
|
923
|
+
AND stream = $2
|
|
924
|
+
AND processed_at IS NULL
|
|
925
|
+
AND available_at <= NOW()
|
|
926
|
+
AND (locked_until IS NULL OR locked_until <= NOW())
|
|
927
|
+
ORDER BY id ASC
|
|
928
|
+
LIMIT $4
|
|
929
|
+
FOR UPDATE SKIP LOCKED
|
|
1477
930
|
)
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
[this.namespace, key, member]
|
|
931
|
+
UPDATE ${this.quotedTableName} target
|
|
932
|
+
SET consumer = $3,
|
|
933
|
+
delivery_count = target.delivery_count + 1,
|
|
934
|
+
locked_until = NOW() + ($5::bigint * INTERVAL '1 millisecond'),
|
|
935
|
+
updated_at = NOW()
|
|
936
|
+
FROM picked
|
|
937
|
+
WHERE target.id = picked.id
|
|
938
|
+
RETURNING target.id, target.stream, target.payload, target.consumer, target.delivery_count,
|
|
939
|
+
target.available_at, target.locked_until, target.processed_at, target.created_at`,
|
|
940
|
+
[this.namespace, stream, consumer, normalizeLimit2(options.limit, 1), visibilityTimeoutMs]
|
|
1489
941
|
);
|
|
1490
|
-
|
|
1491
|
-
return Number(rows[0].count);
|
|
942
|
+
return rows.map((row) => this.mapMessage(row));
|
|
1492
943
|
}
|
|
1493
|
-
async
|
|
944
|
+
async ack(ids) {
|
|
945
|
+
if (ids.length === 0) return 0;
|
|
1494
946
|
const rows = await this.sql.unsafe(
|
|
1495
|
-
`
|
|
1496
|
-
|
|
947
|
+
`UPDATE ${this.quotedTableName}
|
|
948
|
+
SET processed_at = NOW(),
|
|
949
|
+
locked_until = NULL,
|
|
950
|
+
updated_at = NOW()
|
|
1497
951
|
WHERE namespace = $1
|
|
1498
|
-
AND
|
|
1499
|
-
AND
|
|
1500
|
-
|
|
1501
|
-
|
|
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]
|
|
952
|
+
AND id = ANY($2::bigint[])
|
|
953
|
+
AND processed_at IS NULL
|
|
954
|
+
RETURNING id`,
|
|
955
|
+
[this.namespace, ids.map(String)]
|
|
1515
956
|
);
|
|
1516
957
|
return rows.length;
|
|
1517
958
|
}
|
|
1518
|
-
async
|
|
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));
|
|
959
|
+
async pending(stream) {
|
|
1536
960
|
const rows = await this.sql.unsafe(
|
|
1537
|
-
`SELECT
|
|
961
|
+
`SELECT
|
|
962
|
+
COUNT(*) FILTER (WHERE processed_at IS NULL)::bigint AS pending,
|
|
963
|
+
COUNT(*) FILTER (WHERE processed_at IS NULL AND locked_until > NOW())::bigint AS locked
|
|
1538
964
|
FROM ${this.quotedTableName}
|
|
1539
965
|
WHERE namespace = $1
|
|
1540
|
-
AND
|
|
1541
|
-
|
|
1542
|
-
AND (expires_at IS NULL OR expires_at > NOW())
|
|
1543
|
-
ORDER BY member ASC
|
|
1544
|
-
LIMIT $4`,
|
|
1545
|
-
[this.namespace, key, cursor, limit]
|
|
966
|
+
AND ($2::text IS NULL OR stream = $2)`,
|
|
967
|
+
[this.namespace, stream ?? null]
|
|
1546
968
|
);
|
|
1547
969
|
return {
|
|
1548
|
-
|
|
1549
|
-
|
|
970
|
+
pending: Number(rows[0]?.pending ?? 0),
|
|
971
|
+
locked: Number(rows[0]?.locked ?? 0)
|
|
1550
972
|
};
|
|
1551
973
|
}
|
|
1552
|
-
async
|
|
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) {
|
|
974
|
+
async trim(options = {}) {
|
|
1587
975
|
const rows = await this.sql.unsafe(
|
|
1588
976
|
`DELETE FROM ${this.quotedTableName}
|
|
1589
|
-
WHERE
|
|
1590
|
-
SELECT
|
|
977
|
+
WHERE id IN (
|
|
978
|
+
SELECT id
|
|
1591
979
|
FROM ${this.quotedTableName}
|
|
1592
|
-
WHERE
|
|
1593
|
-
|
|
980
|
+
WHERE namespace = $1
|
|
981
|
+
AND ($2::text IS NULL OR stream = $2)
|
|
982
|
+
AND processed_at IS NOT NULL
|
|
983
|
+
AND ($3::bigint IS NULL OR id < $3::bigint)
|
|
984
|
+
AND ($4::bigint IS NULL OR processed_at <= NOW() - ($4::bigint * INTERVAL '1 millisecond'))
|
|
985
|
+
ORDER BY id ASC
|
|
986
|
+
LIMIT $5
|
|
1594
987
|
)
|
|
1595
|
-
RETURNING
|
|
1596
|
-
[
|
|
988
|
+
RETURNING id`,
|
|
989
|
+
[
|
|
990
|
+
this.namespace,
|
|
991
|
+
options.stream ?? null,
|
|
992
|
+
options.beforeId ?? null,
|
|
993
|
+
options.maxAgeMs ?? null,
|
|
994
|
+
normalizeLimit2(options.limit, 1e3)
|
|
995
|
+
]
|
|
1597
996
|
);
|
|
1598
997
|
return rows.length;
|
|
1599
998
|
}
|
|
999
|
+
mapMessage(row) {
|
|
1000
|
+
return {
|
|
1001
|
+
id: String(row.id),
|
|
1002
|
+
stream: row.stream,
|
|
1003
|
+
payload: parseValue(row.payload),
|
|
1004
|
+
consumer: row.consumer,
|
|
1005
|
+
deliveryCount: Number(row.delivery_count),
|
|
1006
|
+
availableAt: toDate2(row.available_at),
|
|
1007
|
+
lockedUntil: toDate2(row.locked_until),
|
|
1008
|
+
processedAt: toDate2(row.processed_at),
|
|
1009
|
+
createdAt: toDate2(row.created_at)
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1600
1012
|
};
|
|
1601
|
-
function
|
|
1602
|
-
return new
|
|
1013
|
+
function createPgOutboxStream(options) {
|
|
1014
|
+
return new PgOutboxStream(options);
|
|
1603
1015
|
}
|
|
1604
1016
|
|
|
1605
1017
|
// src/client.ts
|
|
@@ -1640,6 +1052,11 @@ function createPgredis(options) {
|
|
|
1640
1052
|
namespace,
|
|
1641
1053
|
tableName: tableName(prefix, "sorted_set")
|
|
1642
1054
|
});
|
|
1055
|
+
const outbox = createPgOutboxStream({
|
|
1056
|
+
sql: options.sql,
|
|
1057
|
+
namespace,
|
|
1058
|
+
tableName: options.outbox?.tableName || tableName(prefix, "outbox")
|
|
1059
|
+
});
|
|
1643
1060
|
const rateLimit = options.rateLimit ? createPgFixedWindowRateLimiter({
|
|
1644
1061
|
sql: options.sql,
|
|
1645
1062
|
namespace,
|
|
@@ -1648,7 +1065,13 @@ function createPgredis(options) {
|
|
|
1648
1065
|
tableName: options.rateLimit.tableName || tableName(prefix, "rate_limit")
|
|
1649
1066
|
}) : void 0;
|
|
1650
1067
|
const queue = options.queue ? createPgBossJobQueue(options.queue) : void 0;
|
|
1651
|
-
|
|
1068
|
+
const cleanupMetrics = {
|
|
1069
|
+
totalDeleted: 0,
|
|
1070
|
+
lastDeleted: 0,
|
|
1071
|
+
lastRunAt: null
|
|
1072
|
+
};
|
|
1073
|
+
let client;
|
|
1074
|
+
client = {
|
|
1652
1075
|
cache,
|
|
1653
1076
|
counter,
|
|
1654
1077
|
hash,
|
|
@@ -1659,6 +1082,19 @@ function createPgredis(options) {
|
|
|
1659
1082
|
pubsub: createPgPublisher(options.sql),
|
|
1660
1083
|
rateLimit,
|
|
1661
1084
|
queue,
|
|
1085
|
+
outbox,
|
|
1086
|
+
stream: outbox,
|
|
1087
|
+
redis: void 0,
|
|
1088
|
+
async batch(operation) {
|
|
1089
|
+
if (!options.sql.begin) return operation(client);
|
|
1090
|
+
return options.sql.begin(async (tx) => {
|
|
1091
|
+
const txClient = createPgredis({ ...options, sql: tx });
|
|
1092
|
+
return operation(txClient);
|
|
1093
|
+
});
|
|
1094
|
+
},
|
|
1095
|
+
pipeline() {
|
|
1096
|
+
return new PgredisPipeline((operation) => client.batch(operation));
|
|
1097
|
+
},
|
|
1662
1098
|
async health() {
|
|
1663
1099
|
await options.sql.unsafe("SELECT 1");
|
|
1664
1100
|
return { ok: true };
|
|
@@ -1667,9 +1103,19 @@ function createPgredis(options) {
|
|
|
1667
1103
|
const boss = queue ? await queue.getBoss() : null;
|
|
1668
1104
|
return {
|
|
1669
1105
|
cache: cache.stats(),
|
|
1670
|
-
queue: boss ? await boss.getQueues() : void 0
|
|
1106
|
+
queue: boss ? await boss.getQueues() : void 0,
|
|
1107
|
+
cleanup: { ...cleanupMetrics }
|
|
1671
1108
|
};
|
|
1672
1109
|
},
|
|
1110
|
+
async metrics() {
|
|
1111
|
+
return collectPgredisMetrics({
|
|
1112
|
+
sql: options.sql,
|
|
1113
|
+
namespace,
|
|
1114
|
+
tablePrefix: prefix,
|
|
1115
|
+
cleanup: { ...cleanupMetrics },
|
|
1116
|
+
queue
|
|
1117
|
+
});
|
|
1118
|
+
},
|
|
1673
1119
|
async cleanupExpired(limit = 1e3) {
|
|
1674
1120
|
const [
|
|
1675
1121
|
cacheDeleted,
|
|
@@ -1688,7 +1134,7 @@ function createPgredis(options) {
|
|
|
1688
1134
|
sortedSet.cleanupExpired(limit),
|
|
1689
1135
|
rateLimit ? rateLimit.cleanupExpired(limit) : Promise.resolve(0)
|
|
1690
1136
|
]);
|
|
1691
|
-
|
|
1137
|
+
const result = {
|
|
1692
1138
|
cache: cacheDeleted,
|
|
1693
1139
|
counter: counterDeleted,
|
|
1694
1140
|
hash: hashDeleted,
|
|
@@ -1697,6 +1143,11 @@ function createPgredis(options) {
|
|
|
1697
1143
|
sortedSet: sortedSetDeleted,
|
|
1698
1144
|
rateLimit: rateLimitDeleted
|
|
1699
1145
|
};
|
|
1146
|
+
const deleted = Object.values(result).reduce((total, value) => total + value, 0);
|
|
1147
|
+
cleanupMetrics.totalDeleted += deleted;
|
|
1148
|
+
cleanupMetrics.lastDeleted = deleted;
|
|
1149
|
+
cleanupMetrics.lastRunAt = /* @__PURE__ */ new Date();
|
|
1150
|
+
return result;
|
|
1700
1151
|
},
|
|
1701
1152
|
startCleanupWorker(cleanupOptions = {}) {
|
|
1702
1153
|
const intervalMs = cleanupOptions.intervalMs ?? 6e4;
|
|
@@ -1715,9 +1166,12 @@ function createPgredis(options) {
|
|
|
1715
1166
|
await set.ensureSchema();
|
|
1716
1167
|
await list.ensureSchema();
|
|
1717
1168
|
await sortedSet.ensureSchema();
|
|
1169
|
+
await outbox.ensureSchema();
|
|
1718
1170
|
if (rateLimit) await rateLimit.ensureSchema();
|
|
1719
1171
|
}
|
|
1720
1172
|
};
|
|
1173
|
+
client.redis = createPgredisMigrationAliases(client);
|
|
1174
|
+
return client;
|
|
1721
1175
|
}
|
|
1722
1176
|
export {
|
|
1723
1177
|
PgAdvisoryLockBusyError,
|
|
@@ -1728,11 +1182,15 @@ export {
|
|
|
1728
1182
|
PgHash,
|
|
1729
1183
|
PgKvCache,
|
|
1730
1184
|
PgList,
|
|
1185
|
+
PgOutboxStream,
|
|
1731
1186
|
PgSet,
|
|
1732
1187
|
PgSlidingWindowRateLimiter,
|
|
1733
1188
|
PgSortedSet,
|
|
1734
1189
|
PgTokenBucketRateLimiter,
|
|
1190
|
+
PgredisPipeline,
|
|
1191
|
+
UnsupportedCommandError,
|
|
1735
1192
|
advisoryLockKeyToSqlArgs,
|
|
1193
|
+
collectPgredisMetrics,
|
|
1736
1194
|
createBunPgListener,
|
|
1737
1195
|
createPgAdvisoryLocker,
|
|
1738
1196
|
createPgBossJobQueue,
|
|
@@ -1742,12 +1200,14 @@ export {
|
|
|
1742
1200
|
createPgKvCache,
|
|
1743
1201
|
createPgList,
|
|
1744
1202
|
createPgListener,
|
|
1203
|
+
createPgOutboxStream,
|
|
1745
1204
|
createPgPublisher,
|
|
1746
1205
|
createPgSet,
|
|
1747
1206
|
createPgSlidingWindowRateLimiter,
|
|
1748
1207
|
createPgSortedSet,
|
|
1749
1208
|
createPgTokenBucketRateLimiter,
|
|
1750
1209
|
createPgredis,
|
|
1210
|
+
createPgredisMigrationAliases,
|
|
1751
1211
|
indexName,
|
|
1752
1212
|
normalizePositiveInteger,
|
|
1753
1213
|
publishPgNotify,
|