@postgresx/noredis 0.1.0 → 0.5.2

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/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-GBFG2TOL.js";
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/hash.ts
241
- var DEFAULT_TABLE_NAME2 = "pgredis_hash";
242
- var DEFAULT_NAMESPACE2 = "default";
243
- function jsonValue(value) {
244
- return JSON.stringify(value);
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);
245
254
  }
246
- function parseValue(value) {
247
- if (typeof value !== "string") return value;
248
- try {
249
- return JSON.parse(value);
250
- } catch {
251
- return value;
252
- }
255
+ function defaultTableNames(prefix) {
256
+ return DEFAULT_SUFFIXES.map((suffix) => `${prefix}_${suffix}`);
253
257
  }
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;
258
+ async function collectTtlBacklog(sql, tableName2) {
486
259
  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(
260
+ const rows = await sql.unsafe(
560
261
  `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]
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);
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)]);
266
+ } catch {
267
+ return null;
268
+ }
772
269
  }
773
- function createPgPublisher(sql) {
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)
295
+ });
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
- publish(channel, payload) {
776
- return publishPgNotify(sql, channel, payload);
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,8 +410,8 @@ function createPgBossJobQueue(options) {
836
410
  }
837
411
 
838
412
  // src/rate-limit.ts
839
- var DEFAULT_TABLE_NAME4 = "pg_rate_limit";
840
- var DEFAULT_NAMESPACE4 = "default";
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";
843
417
  var PgFixedWindowRateLimiter = class {
@@ -850,8 +424,8 @@ var PgFixedWindowRateLimiter = class {
850
424
  windowMs;
851
425
  constructor(options) {
852
426
  this.sql = options.sql;
853
- this.namespace = options.namespace || DEFAULT_NAMESPACE4;
854
- this.tableName = options.tableName || DEFAULT_TABLE_NAME4;
427
+ this.namespace = options.namespace || DEFAULT_NAMESPACE2;
428
+ this.tableName = options.tableName || DEFAULT_TABLE_NAME2;
855
429
  this.quotedTableName = quoteQualifiedName(this.tableName);
856
430
  this.now = options.now || Date.now;
857
431
  this.limit = normalizePositiveInteger(options.limit, "limit");
@@ -940,7 +514,7 @@ var PgSlidingWindowRateLimiter = class {
940
514
  precisionMs;
941
515
  constructor(options) {
942
516
  this.sql = options.sql;
943
- this.namespace = options.namespace || DEFAULT_NAMESPACE4;
517
+ this.namespace = options.namespace || DEFAULT_NAMESPACE2;
944
518
  this.tableName = options.tableName || DEFAULT_SLIDING_TABLE_NAME;
945
519
  this.quotedTableName = quoteQualifiedName(this.tableName);
946
520
  this.now = options.now || Date.now;
@@ -1033,7 +607,7 @@ var PgTokenBucketRateLimiter = class {
1033
607
  refillIntervalMs;
1034
608
  constructor(options) {
1035
609
  this.sql = options.sql;
1036
- this.namespace = options.namespace || DEFAULT_NAMESPACE4;
610
+ this.namespace = options.namespace || DEFAULT_NAMESPACE2;
1037
611
  this.tableName = options.tableName || DEFAULT_TOKEN_BUCKET_TABLE_NAME;
1038
612
  this.quotedTableName = quoteQualifiedName(this.tableName);
1039
613
  this.now = options.now || Date.now;
@@ -1117,489 +691,199 @@ function createPgTokenBucketRateLimiter(options) {
1117
691
  return new PgTokenBucketRateLimiter(options);
1118
692
  }
1119
693
 
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;
694
+ // src/stream.ts
695
+ var DEFAULT_TABLE_NAME3 = "pgredis_outbox";
696
+ var DEFAULT_NAMESPACE3 = "default";
697
+ function jsonValue(value) {
698
+ return JSON.stringify(value);
699
+ }
700
+ function parseValue(value) {
701
+ if (typeof value !== "string") return value;
702
+ try {
703
+ return JSON.parse(value);
704
+ } catch {
705
+ return value;
1346
706
  }
1347
- };
1348
- function createPgSet(options) {
1349
- return new PgSet(options);
1350
707
  }
1351
-
1352
- // src/sorted-set.ts
1353
- var DEFAULT_TABLE_NAME6 = "pgredis_sorted_set";
1354
- var DEFAULT_NAMESPACE6 = "default";
1355
- var PgSortedSet = class {
708
+ function toDate2(value) {
709
+ if (value === null) return null;
710
+ return value instanceof Date ? value : new Date(value);
711
+ }
712
+ function normalizeLimit(limit, fallback) {
713
+ if (limit === void 0) return fallback;
714
+ if (!Number.isFinite(limit)) throw new Error(`Invalid limit: ${limit}`);
715
+ return Math.max(1, Math.floor(limit));
716
+ }
717
+ var PgOutboxStream = class {
1356
718
  namespace;
1357
719
  tableName;
1358
720
  quotedTableName;
1359
721
  sql;
1360
722
  constructor(options) {
1361
723
  this.sql = options.sql;
1362
- this.namespace = options.namespace || DEFAULT_NAMESPACE6;
1363
- this.tableName = options.tableName || DEFAULT_TABLE_NAME6;
724
+ this.namespace = options.namespace || DEFAULT_NAMESPACE3;
725
+ this.tableName = options.tableName || DEFAULT_TABLE_NAME3;
1364
726
  this.quotedTableName = quoteQualifiedName(this.tableName);
1365
727
  }
1366
728
  async ensureSchema(options = {}) {
1367
- const persistence = options.unlogged === false ? "" : "UNLOGGED ";
729
+ const persistence = options.unlogged === true ? "UNLOGGED " : "";
1368
730
  await this.sql.unsafe(`
1369
731
  CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
732
+ id BIGSERIAL PRIMARY KEY,
1370
733
  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)
734
+ stream TEXT NOT NULL,
735
+ payload JSONB NOT NULL,
736
+ consumer TEXT,
737
+ delivery_count INTEGER NOT NULL DEFAULT 0,
738
+ available_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
739
+ locked_until TIMESTAMPTZ,
740
+ processed_at TIMESTAMPTZ,
741
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
742
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
1377
743
  )
1378
744
  `);
1379
745
  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)
746
+ CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "ready")}
747
+ ON ${this.quotedTableName} (namespace, stream, available_at, id)
748
+ WHERE processed_at IS NULL
1386
749
  `);
1387
750
  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
751
+ CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "processed")}
752
+ ON ${this.quotedTableName} (namespace, processed_at, id)
753
+ WHERE processed_at IS NOT NULL
1391
754
  `);
1392
755
  }
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) {
756
+ async append(stream, payload, options = {}) {
1414
757
  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]
758
+ `INSERT INTO ${this.quotedTableName} (namespace, stream, payload, available_at, updated_at)
759
+ VALUES ($1, $2, $3::jsonb, COALESCE($4::timestamptz, NOW()), NOW())
760
+ RETURNING id`,
761
+ [this.namespace, stream, jsonValue(payload), options.availableAt ?? null]
1421
762
  );
1422
- return rows[0] ? Number(rows[0].score) : null;
763
+ return String(rows[0]?.id);
1423
764
  }
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);
765
+ async xadd(stream, payload, options = {}) {
766
+ return this.append(stream, payload, options);
1441
767
  }
1442
- async zrangeByScore(key, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY, options = {}) {
1443
- const order = options.desc ? "DESC" : "ASC";
768
+ async read(stream, options = {}) {
1444
769
  const rows = await this.sql.unsafe(
1445
- `SELECT member, score
770
+ `SELECT id, stream, payload, consumer, delivery_count, available_at, locked_until, processed_at, created_at
1446
771
  FROM ${this.quotedTableName}
1447
772
  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)`,
773
+ AND stream = $2
774
+ AND id > $3::bigint
775
+ AND ($5::boolean OR processed_at IS NULL)
776
+ ORDER BY id ASC
777
+ LIMIT $4`,
1455
778
  [
1456
779
  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))
780
+ stream,
781
+ options.afterId ?? 0,
782
+ normalizeLimit(options.limit, 100),
783
+ options.includeProcessed ?? false
1462
784
  ]
1463
785
  );
1464
- if (options.withScores) {
1465
- return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
1466
- }
1467
- return rows.map((row) => row.member);
786
+ return rows.map((row) => this.mapMessage(row));
1468
787
  }
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))";
788
+ async claim(stream, consumer, options = {}) {
789
+ const visibilityTimeoutMs = Math.max(1, Math.floor(options.visibilityTimeoutMs ?? 3e4));
1471
790
  const rows = await this.sql.unsafe(
1472
- `WITH target AS (
1473
- SELECT score, member
791
+ `WITH picked AS (
792
+ SELECT id
1474
793
  FROM ${this.quotedTableName}
1475
- WHERE namespace = $1 AND key = $2 AND member = $3
1476
- AND (expires_at IS NULL OR expires_at > NOW())
794
+ WHERE namespace = $1
795
+ AND stream = $2
796
+ AND processed_at IS NULL
797
+ AND available_at <= NOW()
798
+ AND (locked_until IS NULL OR locked_until <= NOW())
799
+ ORDER BY id ASC
800
+ LIMIT $4
801
+ FOR UPDATE SKIP LOCKED
1477
802
  )
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]
803
+ UPDATE ${this.quotedTableName} target
804
+ SET consumer = $3,
805
+ delivery_count = target.delivery_count + 1,
806
+ locked_until = NOW() + ($5::bigint * INTERVAL '1 millisecond'),
807
+ updated_at = NOW()
808
+ FROM picked
809
+ WHERE target.id = picked.id
810
+ RETURNING target.id, target.stream, target.payload, target.consumer, target.delivery_count,
811
+ target.available_at, target.locked_until, target.processed_at, target.created_at`,
812
+ [this.namespace, stream, consumer, normalizeLimit(options.limit, 1), visibilityTimeoutMs]
1489
813
  );
1490
- if (rows.length === 0 || rows[0]?.count === null || rows[0]?.count === void 0) return null;
1491
- return Number(rows[0].count);
814
+ return rows.map((row) => this.mapMessage(row));
1492
815
  }
1493
- async zcount(key, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
816
+ async ack(ids) {
817
+ if (ids.length === 0) return 0;
1494
818
  const rows = await this.sql.unsafe(
1495
- `SELECT COUNT(*)::bigint AS count
1496
- FROM ${this.quotedTableName}
819
+ `UPDATE ${this.quotedTableName}
820
+ SET processed_at = NOW(),
821
+ locked_until = NULL,
822
+ updated_at = NOW()
1497
823
  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]
824
+ AND id = ANY($2::bigint[])
825
+ AND processed_at IS NULL
826
+ RETURNING id`,
827
+ [this.namespace, ids.map(String)]
1515
828
  );
1516
829
  return rows.length;
1517
830
  }
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));
831
+ async pending(stream) {
1536
832
  const rows = await this.sql.unsafe(
1537
- `SELECT member, score
833
+ `SELECT
834
+ COUNT(*) FILTER (WHERE processed_at IS NULL)::bigint AS pending,
835
+ COUNT(*) FILTER (WHERE processed_at IS NULL AND locked_until > NOW())::bigint AS locked
1538
836
  FROM ${this.quotedTableName}
1539
837
  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]
838
+ AND ($2::text IS NULL OR stream = $2)`,
839
+ [this.namespace, stream ?? null]
1546
840
  );
1547
841
  return {
1548
- cursor: rows.length === limit ? rows[rows.length - 1].member : null,
1549
- entries: rows.map((row) => ({ member: row.member, score: Number(row.score) }))
842
+ pending: Number(rows[0]?.pending ?? 0),
843
+ locked: Number(rows[0]?.locked ?? 0)
1550
844
  };
1551
845
  }
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) {
846
+ async trim(options = {}) {
1587
847
  const rows = await this.sql.unsafe(
1588
848
  `DELETE FROM ${this.quotedTableName}
1589
- WHERE ctid IN (
1590
- SELECT ctid
849
+ WHERE id IN (
850
+ SELECT id
1591
851
  FROM ${this.quotedTableName}
1592
- WHERE expires_at IS NOT NULL AND expires_at <= NOW()
1593
- LIMIT $1
852
+ WHERE namespace = $1
853
+ AND ($2::text IS NULL OR stream = $2)
854
+ AND processed_at IS NOT NULL
855
+ AND ($3::bigint IS NULL OR id < $3::bigint)
856
+ AND ($4::bigint IS NULL OR processed_at <= NOW() - ($4::bigint * INTERVAL '1 millisecond'))
857
+ ORDER BY id ASC
858
+ LIMIT $5
1594
859
  )
1595
- RETURNING member`,
1596
- [Math.max(1, Math.floor(limit))]
860
+ RETURNING id`,
861
+ [
862
+ this.namespace,
863
+ options.stream ?? null,
864
+ options.beforeId ?? null,
865
+ options.maxAgeMs ?? null,
866
+ normalizeLimit(options.limit, 1e3)
867
+ ]
1597
868
  );
1598
869
  return rows.length;
1599
870
  }
871
+ mapMessage(row) {
872
+ return {
873
+ id: String(row.id),
874
+ stream: row.stream,
875
+ payload: parseValue(row.payload),
876
+ consumer: row.consumer,
877
+ deliveryCount: Number(row.delivery_count),
878
+ availableAt: toDate2(row.available_at),
879
+ lockedUntil: toDate2(row.locked_until),
880
+ processedAt: toDate2(row.processed_at),
881
+ createdAt: toDate2(row.created_at)
882
+ };
883
+ }
1600
884
  };
1601
- function createPgSortedSet(options) {
1602
- return new PgSortedSet(options);
885
+ function createPgOutboxStream(options) {
886
+ return new PgOutboxStream(options);
1603
887
  }
1604
888
 
1605
889
  // src/client.ts
@@ -1640,6 +924,11 @@ function createPgredis(options) {
1640
924
  namespace,
1641
925
  tableName: tableName(prefix, "sorted_set")
1642
926
  });
927
+ const outbox = createPgOutboxStream({
928
+ sql: options.sql,
929
+ namespace,
930
+ tableName: options.outbox?.tableName || tableName(prefix, "outbox")
931
+ });
1643
932
  const rateLimit = options.rateLimit ? createPgFixedWindowRateLimiter({
1644
933
  sql: options.sql,
1645
934
  namespace,
@@ -1648,7 +937,13 @@ function createPgredis(options) {
1648
937
  tableName: options.rateLimit.tableName || tableName(prefix, "rate_limit")
1649
938
  }) : void 0;
1650
939
  const queue = options.queue ? createPgBossJobQueue(options.queue) : void 0;
1651
- return {
940
+ const cleanupMetrics = {
941
+ totalDeleted: 0,
942
+ lastDeleted: 0,
943
+ lastRunAt: null
944
+ };
945
+ let client;
946
+ client = {
1652
947
  cache,
1653
948
  counter,
1654
949
  hash,
@@ -1659,6 +954,19 @@ function createPgredis(options) {
1659
954
  pubsub: createPgPublisher(options.sql),
1660
955
  rateLimit,
1661
956
  queue,
957
+ outbox,
958
+ stream: outbox,
959
+ redis: void 0,
960
+ async batch(operation) {
961
+ if (!options.sql.begin) return operation(client);
962
+ return options.sql.begin(async (tx) => {
963
+ const txClient = createPgredis({ ...options, sql: tx });
964
+ return operation(txClient);
965
+ });
966
+ },
967
+ pipeline() {
968
+ return new PgredisPipeline((operation) => client.batch(operation));
969
+ },
1662
970
  async health() {
1663
971
  await options.sql.unsafe("SELECT 1");
1664
972
  return { ok: true };
@@ -1667,9 +975,19 @@ function createPgredis(options) {
1667
975
  const boss = queue ? await queue.getBoss() : null;
1668
976
  return {
1669
977
  cache: cache.stats(),
1670
- queue: boss ? await boss.getQueues() : void 0
978
+ queue: boss ? await boss.getQueues() : void 0,
979
+ cleanup: { ...cleanupMetrics }
1671
980
  };
1672
981
  },
982
+ async metrics() {
983
+ return collectPgredisMetrics({
984
+ sql: options.sql,
985
+ namespace,
986
+ tablePrefix: prefix,
987
+ cleanup: { ...cleanupMetrics },
988
+ queue
989
+ });
990
+ },
1673
991
  async cleanupExpired(limit = 1e3) {
1674
992
  const [
1675
993
  cacheDeleted,
@@ -1688,7 +1006,7 @@ function createPgredis(options) {
1688
1006
  sortedSet.cleanupExpired(limit),
1689
1007
  rateLimit ? rateLimit.cleanupExpired(limit) : Promise.resolve(0)
1690
1008
  ]);
1691
- return {
1009
+ const result = {
1692
1010
  cache: cacheDeleted,
1693
1011
  counter: counterDeleted,
1694
1012
  hash: hashDeleted,
@@ -1697,6 +1015,11 @@ function createPgredis(options) {
1697
1015
  sortedSet: sortedSetDeleted,
1698
1016
  rateLimit: rateLimitDeleted
1699
1017
  };
1018
+ const deleted = Object.values(result).reduce((total, value) => total + value, 0);
1019
+ cleanupMetrics.totalDeleted += deleted;
1020
+ cleanupMetrics.lastDeleted = deleted;
1021
+ cleanupMetrics.lastRunAt = /* @__PURE__ */ new Date();
1022
+ return result;
1700
1023
  },
1701
1024
  startCleanupWorker(cleanupOptions = {}) {
1702
1025
  const intervalMs = cleanupOptions.intervalMs ?? 6e4;
@@ -1715,9 +1038,12 @@ function createPgredis(options) {
1715
1038
  await set.ensureSchema();
1716
1039
  await list.ensureSchema();
1717
1040
  await sortedSet.ensureSchema();
1041
+ await outbox.ensureSchema();
1718
1042
  if (rateLimit) await rateLimit.ensureSchema();
1719
1043
  }
1720
1044
  };
1045
+ client.redis = createPgredisMigrationAliases(client);
1046
+ return client;
1721
1047
  }
1722
1048
  export {
1723
1049
  PgAdvisoryLockBusyError,
@@ -1728,11 +1054,15 @@ export {
1728
1054
  PgHash,
1729
1055
  PgKvCache,
1730
1056
  PgList,
1057
+ PgOutboxStream,
1731
1058
  PgSet,
1732
1059
  PgSlidingWindowRateLimiter,
1733
1060
  PgSortedSet,
1734
1061
  PgTokenBucketRateLimiter,
1062
+ PgredisPipeline,
1063
+ UnsupportedCommandError,
1735
1064
  advisoryLockKeyToSqlArgs,
1065
+ collectPgredisMetrics,
1736
1066
  createBunPgListener,
1737
1067
  createPgAdvisoryLocker,
1738
1068
  createPgBossJobQueue,
@@ -1742,12 +1072,14 @@ export {
1742
1072
  createPgKvCache,
1743
1073
  createPgList,
1744
1074
  createPgListener,
1075
+ createPgOutboxStream,
1745
1076
  createPgPublisher,
1746
1077
  createPgSet,
1747
1078
  createPgSlidingWindowRateLimiter,
1748
1079
  createPgSortedSet,
1749
1080
  createPgTokenBucketRateLimiter,
1750
1081
  createPgredis,
1082
+ createPgredisMigrationAliases,
1751
1083
  indexName,
1752
1084
  normalizePositiveInteger,
1753
1085
  publishPgNotify,