@postgresx/noredis 0.6.0 → 0.7.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 CHANGED
@@ -140,6 +140,18 @@ await cache.persist("token:abc");
140
140
  await cache.touch("token:abc");
141
141
  ```
142
142
 
143
+ Cache, counter, collection, and rate-limit schemas default to PostgreSQL
144
+ `UNLOGGED` tables. They survive a clean restart, but PostgreSQL truncates them
145
+ after crash recovery and does not replicate them to standbys. Use
146
+ `ensureSchema({ unlogged: false })` when those values require WAL-backed
147
+ persistence. The unified client applies the option to every cache-style schema:
148
+
149
+ ```ts
150
+ await pg.ensureSchema({ unlogged: false });
151
+ ```
152
+
153
+ The durable outbox remains logged regardless of this option.
154
+
143
155
  Use `serializer` when values need an application envelope before they are stored
144
156
  as JSONB:
145
157
 
@@ -249,6 +261,36 @@ If package-name aliasing is useful during migration, use the thin re-export
249
261
  packages `@postgresx/noredis-ioredis` and `@postgresx/noredis-redis`. They are
250
262
  still facades over `PgredisClient`; they do not provide drop-in constructors.
251
263
 
264
+ ### L1 invalidation and atomic swaps
265
+
266
+ Configure a listener factory to keep the local L1 cache coherent across
267
+ processes. The listener must use a dedicated connection that supports
268
+ `LISTEN`; do not reuse a transaction-pooled request connection.
269
+
270
+ ```ts
271
+ import { createPgredis } from "@postgresx/noredis";
272
+ import { createPgNodeListener } from "@postgresx/noredis/adapters/node";
273
+
274
+ const pg = createPgredis({
275
+ sql,
276
+ cache: {
277
+ notify: {
278
+ listener: ({ channels, onNotify }) =>
279
+ createPgNodeListener(directDatabaseUrl, { channels, onNotify })
280
+ }
281
+ }
282
+ });
283
+
284
+ pg.cache.stopInvalidationListener();
285
+ ```
286
+
287
+ Remote notifications invalidate matching L1 entries. A listener reconnect
288
+ clears the complete L1 cache by default so notifications missed during the
289
+ disconnect cannot leave stale entries behind. `getset()` runs in a retried
290
+ serializable transaction and therefore requires an adapter with `begin()`;
291
+ the built-in Bun and Node adapters provide it. `getdel()` uses one atomic
292
+ `DELETE ... RETURNING` statement.
293
+
252
294
  ## Pub/Sub
253
295
 
254
296
  Publishing uses only the configured SQL adapter. Bun LISTEN/NOTIFY consumption
@@ -411,7 +453,7 @@ Remaining gates before a production or 1.0 launch:
411
453
 
412
454
  | Area | Status | Why it matters | Recommended action |
413
455
  | --- | --- | --- | --- |
414
- | Real database coverage | Added in CI | PostgreSQL DDL, indexes, transactions, JSONB behavior, and LISTEN/NOTIFY reconnect behavior need real database coverage. | CI runs `bun run test:integration` against PostgreSQL 16. Run locally with `TEST_DATABASE_URL` when debugging. |
456
+ | Real database coverage | Added in CI | PostgreSQL DDL, indexes, transactions, JSONB behavior, and LISTEN/NOTIFY reconnect behavior need real database coverage. | CI runs `bun run test:integration` against PostgreSQL 17 and 18. Run locally with `TEST_DATABASE_URL` when debugging. |
415
457
  | Benchmark baseline | Generated | `benchmark.md` is generated by GitHub Actions and includes both service-level PostgreSQL columns and L1 hot-read columns. | Benchmark-relevant changes refresh it automatically; local benchmark runs are optional. |
416
458
  | Install smoke test | Added in CI | Build output exists, but the published package shape should be verified from a packed tarball, including subpath exports. | CI runs `bun run smoke:pack` to import packed tarballs from clean Node and Bun entrypoints. |
417
459
  | Monorepo release chain | Guarded in CI | Source package manifests must keep internal packages as `workspace:*`; publish rewrites them to concrete versions in a temp tree. | CI runs `check:workspace-deps` before install, and `publish:packages` remains the only npm publish path. |
@@ -487,7 +529,7 @@ outbox/stream, list blocking-pop helpers, production metrics, Redis-style
487
529
  aliases, web adapters, and expanded KV write semantics.
488
530
 
489
531
  Follow-up documentation and benchmark candidates are tracked in
490
- the [repository migration examples](https://github.com/zuohuadong/postgresx/blob/main/docs/redis-migration-examples.md):
532
+ the [repository migration examples](https://github.com/vibeunion/postgresx/blob/main/docs/redis-migration-examples.md):
491
533
 
492
534
  1. Redis Streams consumer-group migration patterns for `XREADGROUP`, pending entries, and retries.
493
535
  2. Framework-specific session middleware examples built on the web adapter.
@@ -643,6 +685,16 @@ await cache.persist("token:abc");
643
685
  await cache.touch("token:abc");
644
686
  ```
645
687
 
688
+ 缓存、计数器、集合和限流 schema 默认使用 PostgreSQL `UNLOGGED` 表。它们能在正常重启后保留,
689
+ 但 PostgreSQL 会在崩溃恢复时清空这些表,而且不会把它们复制到备库。需要 WAL 持久化时,请使用
690
+ `ensureSchema({ unlogged: false })`。统一客户端会把该选项应用到全部缓存类 schema:
691
+
692
+ ```ts
693
+ await pg.ensureSchema({ unlogged: false });
694
+ ```
695
+
696
+ durable outbox 不受该选项影响,始终保持 logged。
697
+
646
698
  ## 统一客户端
647
699
 
648
700
  ```ts
@@ -720,6 +772,33 @@ await redisJsLike.hSet("profile:1", "name", "Ada");
720
772
  `@postgresx/noredis-ioredis` 和 `@postgresx/noredis-redis`。它们仍然是
721
773
  `PgredisClient` 之上的外观,不提供即插即用构造器。
722
774
 
775
+ ### L1 失效与原子交换
776
+
777
+ 通过 listener factory 让多个进程的本地 L1 缓存保持一致。监听器必须使用
778
+ 支持 `LISTEN` 的独立连接,不要复用 transaction pooler 的请求连接。
779
+
780
+ ```ts
781
+ import { createPgredis } from "@postgresx/noredis";
782
+ import { createPgNodeListener } from "@postgresx/noredis/adapters/node";
783
+
784
+ const pg = createPgredis({
785
+ sql,
786
+ cache: {
787
+ notify: {
788
+ listener: ({ channels, onNotify }) =>
789
+ createPgNodeListener(directDatabaseUrl, { channels, onNotify })
790
+ }
791
+ }
792
+ });
793
+
794
+ pg.cache.stopInvalidationListener();
795
+ ```
796
+
797
+ 远端通知会使匹配的 L1 条目失效。监听连接重连时默认清空完整 L1,避免断线期间
798
+ 漏掉的通知留下陈旧缓存。`getset()` 在可重试的串行化事务中执行,因此 SQL
799
+ 适配器必须提供 `begin()`;内置 Bun 和 Node 适配器均支持。`getdel()` 使用单条
800
+ 原子 `DELETE ... RETURNING` 语句。
801
+
723
802
  ## Pub/Sub
724
803
 
725
804
  发布仅使用配置的 SQL 适配器。Bun LISTEN/NOTIFY 消费使用独立的 `@postgresx/bun-listen` 包,并动态加载。
@@ -868,7 +947,7 @@ npm install @postgresx/noredis pg-boss
868
947
 
869
948
  | 领域 | 状态 | 重要性 | 建议操作 |
870
949
  | --- | --- | --- | --- |
871
- | 真实数据库覆盖 | CI 中已添加 | PostgreSQL DDL、索引、事务、JSONB 行为和 LISTEN/NOTIFY 重连行为需要真实数据库覆盖。 | CI 针对 PostgreSQL 16 运行 `bun run test:integration`。调试时使用 `TEST_DATABASE_URL` 本地运行。 |
950
+ | 真实数据库覆盖 | CI 中已添加 | PostgreSQL DDL、索引、事务、JSONB 行为和 LISTEN/NOTIFY 重连行为需要真实数据库覆盖。 | CI 针对 PostgreSQL 17 和 18 运行 `bun run test:integration`。调试时使用 `TEST_DATABASE_URL` 本地运行。 |
872
951
  | 基准测试基线 | 已生成 | `benchmark.md` 已由 GitHub Actions 生成,并区分主服务级对比和 L1 热读说明。 | benchmark 相关文件变化会自动刷新;本地基准测试运行是可选的。 |
873
952
  | 安装冒烟测试 | CI 中已添加 | 构建输出存在,但已发布包的形状应从打包的 tarball 验证,包括子路径导出。 | CI 运行 `bun run smoke:pack` 从干净的 Node 和 Bun 入口点导入打包的 tarball。 |
874
953
  | 发布凭证 | 在工作流中保护 | Release Please 和 npm publish 依赖仓库密钥和 npm provenance 设置。 | 当 `RELEASE_PAT` 或 `NPM_TOKEN` 缺失时,工作流会提前失败;首次发布前仍需验证包访问权限。 |
@@ -946,7 +1025,7 @@ Redis 在核心数据类型、服务器操作、可编程性、集群、模块
946
1025
  10. ~~子模块入口~~ — `kv`、`hash`、`set`、`sorted-set`、`list`、`pubsub` 子路径导出类型化原语。
947
1026
 
948
1027
  后续迁移文档和 benchmark 候选项记录在
949
- [仓库迁移示例](https://github.com/zuohuadong/postgresx/blob/main/docs/redis-migration-examples.md) 中:
1028
+ [仓库迁移示例](https://github.com/vibeunion/postgresx/blob/main/docs/redis-migration-examples.md) 中:
950
1029
  Redis Streams consumer-group 迁移、session middleware 示例、SQL adapter
951
1030
  retry/backoff 边界、outbox/list/pipeline benchmark,以及明确非目标。
952
1031
 
@@ -1,9 +1,9 @@
1
- import { Q as PgredisClient, _ as PipelineFacade, U as PgredisMigrationAliases } from '../client-DP3ssToT.js';
1
+ import { Q as PgredisClient, $ as PipelineFacade, U as PgredisMigrationAliases } from '../client-ChVkyyno.js';
2
2
  import '../kv-cache.js';
3
+ import '../pubsub-index.js';
3
4
  import '../sql-DKf2TDlu.js';
4
5
  import '../hash-index.js';
5
6
  import '../list-index.js';
6
- import '../pubsub-index.js';
7
7
  import '../set-index.js';
8
8
  import '../sorted-set-index.js';
9
9
 
@@ -1,9 +1,9 @@
1
- import { Q as PgredisClient, _ as PipelineFacade, U as PgredisMigrationAliases } from '../client-DP3ssToT.js';
1
+ import { Q as PgredisClient, $ as PipelineFacade, U as PgredisMigrationAliases } from '../client-ChVkyyno.js';
2
2
  import '../kv-cache.js';
3
+ import '../pubsub-index.js';
3
4
  import '../sql-DKf2TDlu.js';
4
5
  import '../hash-index.js';
5
6
  import '../list-index.js';
6
- import '../pubsub-index.js';
7
7
  import '../set-index.js';
8
8
  import '../sorted-set-index.js';
9
9
 
@@ -1,4 +1,6 @@
1
1
  import { PgKvSetOptions, PgKvCache } from '../kv-cache.js';
2
+ import '../pubsub-index.js';
3
+ import '../sql-DKf2TDlu.js';
2
4
 
3
5
  type SessionCallback<T = unknown> = (error?: unknown, value?: T | null) => void;
4
6
  interface PgredisSessionStoreOptions {
@@ -49,6 +49,11 @@ function normalizeTtlMs(ttlMs) {
49
49
  if (!Number.isFinite(ttlMs)) throw new Error(`Invalid ttlMs: ${ttlMs}`);
50
50
  return Math.max(0, Math.floor(ttlMs));
51
51
  }
52
+ function isSerializationFailure(error) {
53
+ if (!error || typeof error !== "object") return false;
54
+ if ("code" in error && error.code === "40001") return true;
55
+ return "cause" in error && isSerializationFailure(error.cause);
56
+ }
52
57
  function escapeLike(value) {
53
58
  return value.replace(/[\\%_]/g, (match) => `\\${match}`);
54
59
  }
@@ -75,6 +80,9 @@ var PgKvCache = class {
75
80
  notifyEnabled;
76
81
  serializer;
77
82
  l1 = /* @__PURE__ */ new Map();
83
+ l1Generation = 0;
84
+ invalidationListener = null;
85
+ invalidationReconnectUnsubscribe = null;
78
86
  constructor(options) {
79
87
  this.sql = options.sql;
80
88
  this.namespace = options.namespace || DEFAULT_NAMESPACE;
@@ -91,6 +99,12 @@ var PgKvCache = class {
91
99
  serialize: (value) => value,
92
100
  deserialize: (value) => value
93
101
  };
102
+ const listenerFactory = this.resolveNotifyOptions(options.notify)?.listener;
103
+ if (listenerFactory) {
104
+ this.startInvalidationListener(listenerFactory, {
105
+ clearL1OnReconnect: this.resolveNotifyOptions(options.notify)?.clearL1OnReconnect
106
+ });
107
+ }
94
108
  }
95
109
  async ensureSchema(options = {}) {
96
110
  const persistence = options.unlogged === false ? "" : "UNLOGGED ";
@@ -117,6 +131,7 @@ var PgKvCache = class {
117
131
  async get(key) {
118
132
  const cached = this.getL1(key);
119
133
  if (cached.hit) return cached.value;
134
+ const l1Generation = this.l1Generation;
120
135
  const rows = await this.sql.unsafe(
121
136
  `SELECT value, expires_at
122
137
  FROM ${this.quotedTableName}
@@ -132,7 +147,7 @@ var PgKvCache = class {
132
147
  return null;
133
148
  }
134
149
  const value = this.deserialize(row.value);
135
- this.setL1(key, value, rowExpiresAt(row));
150
+ this.setL1(key, value, rowExpiresAt(row), l1Generation);
136
151
  return value;
137
152
  }
138
153
  async mget(keys) {
@@ -147,6 +162,7 @@ var PgKvCache = class {
147
162
  }
148
163
  }
149
164
  if (missing.length === 0) return result;
165
+ const l1Generation = this.l1Generation;
150
166
  const placeholders = missing.map((_, index) => `$${index + 2}`).join(", ");
151
167
  const rows = await this.sql.unsafe(
152
168
  `SELECT key, value, expires_at
@@ -160,7 +176,7 @@ var PgKvCache = class {
160
176
  if (!row.key) continue;
161
177
  const value = this.deserialize(row.value);
162
178
  result.set(row.key, value);
163
- this.setL1(row.key, value, rowExpiresAt(row));
179
+ this.setL1(row.key, value, rowExpiresAt(row), l1Generation);
164
180
  }
165
181
  for (const key of missing) {
166
182
  if (!result.has(key)) this.deleteL1(key);
@@ -261,7 +277,7 @@ var PgKvCache = class {
261
277
  RETURNING key`,
262
278
  [this.namespace]
263
279
  );
264
- this.l1.clear();
280
+ this.invalidateAll();
265
281
  if (options.notify !== false) await this.publish({ op: "clearNamespace" });
266
282
  return rows.length;
267
283
  }
@@ -396,6 +412,31 @@ var PgKvCache = class {
396
412
  invalidate(key) {
397
413
  this.deleteL1(key);
398
414
  }
415
+ invalidateAll() {
416
+ this.l1Generation += 1;
417
+ this.l1.clear();
418
+ }
419
+ startInvalidationListener(factory, options = {}) {
420
+ this.stopInvalidationListener();
421
+ const listener = factory({
422
+ channels: [this.notifyChannel],
423
+ onNotify: (channel, payload) => {
424
+ if (channel === this.notifyChannel) this.handleNotification(payload);
425
+ }
426
+ });
427
+ const reconnectUnsubscribe = options.clearL1OnReconnect === false ? null : listener.on("reconnect", () => this.invalidateAll());
428
+ this.invalidationListener = listener;
429
+ this.invalidationReconnectUnsubscribe = reconnectUnsubscribe;
430
+ return listener;
431
+ }
432
+ stopInvalidationListener() {
433
+ const listener = this.invalidationListener;
434
+ const reconnectUnsubscribe = this.invalidationReconnectUnsubscribe;
435
+ this.invalidationListener = null;
436
+ this.invalidationReconnectUnsubscribe = null;
437
+ reconnectUnsubscribe?.();
438
+ listener?.close();
439
+ }
399
440
  handleNotification(payload) {
400
441
  const event = typeof payload === "string" ? this.parseNotification(payload) : payload;
401
442
  if (!event || event.namespace !== this.namespace || event.senderId === this.instanceId) return false;
@@ -405,13 +446,14 @@ var PgKvCache = class {
405
446
  }
406
447
  if (event.op === "clearPrefix") {
407
448
  if (!event.prefix) return false;
449
+ this.l1Generation += 1;
408
450
  for (const key of this.l1.keys()) {
409
451
  if (key.startsWith(event.prefix)) this.l1.delete(key);
410
452
  }
411
453
  return true;
412
454
  }
413
455
  if (event.op === "clearNamespace") {
414
- this.l1.clear();
456
+ this.invalidateAll();
415
457
  return true;
416
458
  }
417
459
  return false;
@@ -502,14 +544,50 @@ var PgKvCache = class {
502
544
  return written ? 1 : 0;
503
545
  }
504
546
  async getset(key, value) {
505
- const old = await this.get(key);
506
- await this.set(key, value);
507
- return old;
547
+ const serialized = jsonValue(this.serializer.serialize(value));
548
+ const l1Generation = this.l1Generation;
549
+ const oldValue = await this.runSerializable(async (tx) => {
550
+ const rows = await tx.unsafe(
551
+ `SELECT value, expires_at
552
+ FROM ${this.quotedTableName}
553
+ WHERE namespace = $1
554
+ AND key = $2
555
+ AND (expires_at IS NULL OR expires_at > NOW())
556
+ FOR UPDATE`,
557
+ [this.namespace, key]
558
+ );
559
+ await tx.unsafe(
560
+ `INSERT INTO ${this.quotedTableName} (namespace, key, value, expires_at, updated_at)
561
+ VALUES ($1, $2, $3::jsonb, NULL, NOW())
562
+ ON CONFLICT (namespace, key) DO UPDATE
563
+ SET value = EXCLUDED.value,
564
+ expires_at = NULL,
565
+ updated_at = NOW()`,
566
+ [this.namespace, key, serialized]
567
+ );
568
+ return rows[0] ? this.deserialize(rows[0].value) : null;
569
+ });
570
+ this.setL1(key, value, null, l1Generation);
571
+ await this.publish({ op: "set", key });
572
+ return oldValue;
508
573
  }
509
574
  async getdel(key) {
510
- const value = await this.get(key);
511
- if (value !== null) await this.delete(key);
512
- return value;
575
+ const rows = await this.sql.unsafe(
576
+ `WITH deleted AS (
577
+ DELETE FROM ${this.quotedTableName}
578
+ WHERE namespace = $1 AND key = $2
579
+ RETURNING value, expires_at
580
+ )
581
+ SELECT value,
582
+ (expires_at IS NULL OR expires_at > NOW()) AS is_live
583
+ FROM deleted`,
584
+ [this.namespace, key]
585
+ );
586
+ const row = rows[0];
587
+ this.deleteL1(key);
588
+ if (!row) return null;
589
+ await this.publish({ op: "delete", key });
590
+ return row.is_live ? this.deserialize(row.value) : null;
513
591
  }
514
592
  stats() {
515
593
  this.cleanupL1();
@@ -529,6 +607,23 @@ var PgKvCache = class {
529
607
  };
530
608
  await this.sql.unsafe("SELECT pg_notify($1, $2)", [this.notifyChannel, JSON.stringify(payload)]);
531
609
  }
610
+ async runSerializable(operation) {
611
+ const begin = this.sql.begin?.bind(this.sql);
612
+ if (!begin) {
613
+ throw new Error("PgKvCache.getset requires a transaction-capable sql adapter");
614
+ }
615
+ for (let attempt = 0; attempt < 3; attempt += 1) {
616
+ try {
617
+ return await begin(async (tx) => {
618
+ await tx.unsafe("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
619
+ return operation(tx);
620
+ });
621
+ } catch (error) {
622
+ if (!isSerializationFailure(error) || attempt === 2) throw error;
623
+ }
624
+ }
625
+ throw new Error("PgKvCache serializable transaction retry exhausted");
626
+ }
532
627
  deserialize(value) {
533
628
  return this.serializer.deserialize(parseValue(value));
534
629
  }
@@ -538,6 +633,9 @@ var PgKvCache = class {
538
633
  if (options.xx) return "xx";
539
634
  return options.mode ?? "always";
540
635
  }
636
+ resolveNotifyOptions(options) {
637
+ return options === false ? void 0 : options;
638
+ }
541
639
  parseNotification(payload) {
542
640
  try {
543
641
  const value = JSON.parse(payload);
@@ -559,8 +657,9 @@ var PgKvCache = class {
559
657
  this.l1.set(key, entry);
560
658
  return { hit: true, value: entry.value };
561
659
  }
562
- setL1(key, value, l2ExpiresAt) {
660
+ setL1(key, value, l2ExpiresAt, generation = this.l1Generation) {
563
661
  if (!this.l1Enabled || this.l1Max <= 0) return;
662
+ if (generation !== this.l1Generation) return;
564
663
  const l1ExpiresAt = this.computeL1ExpiresAt(l2ExpiresAt);
565
664
  if (l1ExpiresAt !== null && l1ExpiresAt <= this.now()) {
566
665
  this.l1.delete(key);
@@ -578,6 +677,7 @@ var PgKvCache = class {
578
677
  }
579
678
  deleteL1(key) {
580
679
  if (!this.l1Enabled) return;
680
+ this.l1Generation += 1;
581
681
  this.l1.delete(key);
582
682
  }
583
683
  cleanupL1() {
@@ -471,6 +471,10 @@ interface PgredisOptions {
471
471
  tableName?: string;
472
472
  };
473
473
  }
474
+ interface PgredisSchemaOptions {
475
+ /** Controls cache-style primitives; the durable outbox always remains logged. */
476
+ unlogged?: boolean;
477
+ }
474
478
  interface PgredisClient {
475
479
  cache: PgKvCache;
476
480
  counter: PgCounter;
@@ -502,8 +506,8 @@ interface PgredisClient {
502
506
  limit?: number;
503
507
  onError?: (error: unknown) => void;
504
508
  }): () => void;
505
- ensureSchema(): Promise<void>;
509
+ ensureSchema(options?: PgredisSchemaOptions): Promise<void>;
506
510
  }
507
511
  declare function createPgredis(options: PgredisOptions): PgredisClient;
508
512
 
509
- export { type RedisSetAliasOptions as $, type PgOutboxStreamSchemaOptions as A, type PgOutboxTrimOptions as B, type PgRateLimitBlockOptions as C, type PgRateLimitHitOptions as D, type PgRateLimitResult as E, type PgRateLimitSchemaOptions as F, type PgRateLimitStateOptions as G, type PgRateLimiterOptions as H, PgSlidingWindowRateLimiter as I, type PgSlidingWindowRateLimiterOptions as J, PgTokenBucketRateLimiter as K, type PgTokenBucketRateLimiterOptions as L, type PgTokenBucketResult as M, type PgredisBatchOperation as N, type PgredisCleanupMetrics as O, PgAdvisoryLockBusyError as P, type PgredisClient as Q, type PgredisListenerMetrics as R, type PgredisMetrics as S, type PgredisMetricsOptions as T, type PgredisMigrationAliases as U, type PgredisOptions as V, PgredisPipeline as W, type PgredisQueueMetrics as X, type PgredisTableMetrics as Y, type PipelineCommand as Z, type PipelineFacade as _, type PgAdvisoryLockKey as a, advisoryLockKeyToSqlArgs as a0, collectPgredisMetrics as a1, createPgAdvisoryLocker as a2, createPgBossJobQueue as a3, createPgCounter as a4, createPgFixedWindowRateLimiter as a5, createPgOutboxStream as a6, createPgSlidingWindowRateLimiter as a7, createPgTokenBucketRateLimiter as a8, createPgredis as a9, createPgredisMigrationAliases as aa, withPgAdvisoryLock as ab, type PgAdvisoryLockOptions as b, PgAdvisoryLocker as c, type PgBossJob as d, PgBossJobQueue as e, type PgBossLike as f, type PgBossOptions as g, type PgBossQueueDefinition as h, type PgBossQueueMap as i, type PgBossQueueOptions as j, type PgBossQueueResult as k, type PgBossSendOptions as l, type PgBossWorkHandler as m, type PgBossWorkOptions as n, PgCounter as o, type PgCounterOptions as p, type PgCounterSchemaOptions as q, type PgCounterSetOptions as r, PgFixedWindowRateLimiter as s, type PgOutboxAppendOptions as t, type PgOutboxClaimOptions as u, type PgOutboxMessage as v, type PgOutboxPendingSummary as w, type PgOutboxReadOptions as x, PgOutboxStream as y, type PgOutboxStreamOptions as z };
513
+ export { type PipelineFacade as $, type PgOutboxStreamSchemaOptions as A, type PgOutboxTrimOptions as B, type PgRateLimitBlockOptions as C, type PgRateLimitHitOptions as D, type PgRateLimitResult as E, type PgRateLimitSchemaOptions as F, type PgRateLimitStateOptions as G, type PgRateLimiterOptions as H, PgSlidingWindowRateLimiter as I, type PgSlidingWindowRateLimiterOptions as J, PgTokenBucketRateLimiter as K, type PgTokenBucketRateLimiterOptions as L, type PgTokenBucketResult as M, type PgredisBatchOperation as N, type PgredisCleanupMetrics as O, PgAdvisoryLockBusyError as P, type PgredisClient as Q, type PgredisListenerMetrics as R, type PgredisMetrics as S, type PgredisMetricsOptions as T, type PgredisMigrationAliases as U, type PgredisOptions as V, PgredisPipeline as W, type PgredisQueueMetrics as X, type PgredisSchemaOptions as Y, type PgredisTableMetrics as Z, type PipelineCommand as _, type PgAdvisoryLockKey as a, type RedisSetAliasOptions as a0, advisoryLockKeyToSqlArgs as a1, collectPgredisMetrics as a2, createPgAdvisoryLocker as a3, createPgBossJobQueue as a4, createPgCounter as a5, createPgFixedWindowRateLimiter as a6, createPgOutboxStream as a7, createPgSlidingWindowRateLimiter as a8, createPgTokenBucketRateLimiter as a9, createPgredis as aa, createPgredisMigrationAliases as ab, withPgAdvisoryLock as ac, type PgAdvisoryLockOptions as b, PgAdvisoryLocker as c, type PgBossJob as d, PgBossJobQueue as e, type PgBossLike as f, type PgBossOptions as g, type PgBossQueueDefinition as h, type PgBossQueueMap as i, type PgBossQueueOptions as j, type PgBossQueueResult as k, type PgBossSendOptions as l, type PgBossWorkHandler as m, type PgBossWorkOptions as n, PgCounter as o, type PgCounterOptions as p, type PgCounterSchemaOptions as q, type PgCounterSetOptions as r, PgFixedWindowRateLimiter as s, type PgOutboxAppendOptions as t, type PgOutboxClaimOptions as u, type PgOutboxMessage as v, type PgOutboxPendingSummary as w, type PgOutboxReadOptions as x, PgOutboxStream as y, type PgOutboxStreamOptions as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { BunSqlLike, PgKvCache, PgKvCacheL1Options, PgKvCacheNotifyOptions, PgKvCacheOptions, PgKvCacheStats, PgKvNotification, PgKvSchemaOptions, PgKvSetOptions, createPgKvCache } from './kv-cache.js';
2
- export { d as Job, P as PgAdvisoryLockBusyError, a as PgAdvisoryLockKey, b as PgAdvisoryLockOptions, c as PgAdvisoryLocker, f as PgBoss, d as PgBossJob, e as PgBossJobQueue, f as PgBossLike, g as PgBossOptions, h as PgBossQueueDefinition, i as PgBossQueueMap, j as PgBossQueueOptions, k as PgBossQueueResult, l as PgBossSendOptions, m as PgBossWorkHandler, n as PgBossWorkOptions, o as PgCounter, p as PgCounterOptions, q as PgCounterSchemaOptions, r as PgCounterSetOptions, s as PgFixedWindowRateLimiter, t as PgOutboxAppendOptions, u as PgOutboxClaimOptions, v as PgOutboxMessage, w as PgOutboxPendingSummary, x as PgOutboxReadOptions, y as PgOutboxStream, z as PgOutboxStreamOptions, A as PgOutboxStreamSchemaOptions, B as PgOutboxTrimOptions, C as PgRateLimitBlockOptions, D as PgRateLimitHitOptions, E as PgRateLimitResult, F as PgRateLimitSchemaOptions, G as PgRateLimitStateOptions, H as PgRateLimiterOptions, I as PgSlidingWindowRateLimiter, J as PgSlidingWindowRateLimiterOptions, K as PgTokenBucketRateLimiter, L as PgTokenBucketRateLimiterOptions, M as PgTokenBucketResult, N as PgredisBatchOperation, O as PgredisCleanupMetrics, Q as PgredisClient, R as PgredisListenerMetrics, S as PgredisMetrics, T as PgredisMetricsOptions, U as PgredisMigrationAliases, V as PgredisOptions, W as PgredisPipeline, X as PgredisQueueMetrics, Y as PgredisTableMetrics, Z as PipelineCommand, _ as PipelineFacade, h as Queue, k as QueueResult, $ as RedisSetAliasOptions, l as SendOptions, m as WorkHandler, n as WorkOptions, a0 as advisoryLockKeyToSqlArgs, a1 as collectPgredisMetrics, a2 as createPgAdvisoryLocker, a3 as createPgBossJobQueue, a4 as createPgCounter, a5 as createPgFixedWindowRateLimiter, a6 as createPgOutboxStream, a7 as createPgSlidingWindowRateLimiter, a8 as createPgTokenBucketRateLimiter, a9 as createPgredis, aa as createPgredisMigrationAliases, ab as withPgAdvisoryLock } from './client-DP3ssToT.js';
1
+ export { BunSqlLike, PgKvCache, PgKvCacheInvalidationOptions, PgKvCacheL1Options, PgKvCacheListenerFactory, PgKvCacheListenerFactoryOptions, PgKvCacheNotifyOptions, PgKvCacheOptions, PgKvCacheStats, PgKvNotification, PgKvSchemaOptions, PgKvSetOptions, createPgKvCache } from './kv-cache.js';
2
+ export { d as Job, P as PgAdvisoryLockBusyError, a as PgAdvisoryLockKey, b as PgAdvisoryLockOptions, c as PgAdvisoryLocker, f as PgBoss, d as PgBossJob, e as PgBossJobQueue, f as PgBossLike, g as PgBossOptions, h as PgBossQueueDefinition, i as PgBossQueueMap, j as PgBossQueueOptions, k as PgBossQueueResult, l as PgBossSendOptions, m as PgBossWorkHandler, n as PgBossWorkOptions, o as PgCounter, p as PgCounterOptions, q as PgCounterSchemaOptions, r as PgCounterSetOptions, s as PgFixedWindowRateLimiter, t as PgOutboxAppendOptions, u as PgOutboxClaimOptions, v as PgOutboxMessage, w as PgOutboxPendingSummary, x as PgOutboxReadOptions, y as PgOutboxStream, z as PgOutboxStreamOptions, A as PgOutboxStreamSchemaOptions, B as PgOutboxTrimOptions, C as PgRateLimitBlockOptions, D as PgRateLimitHitOptions, E as PgRateLimitResult, F as PgRateLimitSchemaOptions, G as PgRateLimitStateOptions, H as PgRateLimiterOptions, I as PgSlidingWindowRateLimiter, J as PgSlidingWindowRateLimiterOptions, K as PgTokenBucketRateLimiter, L as PgTokenBucketRateLimiterOptions, M as PgTokenBucketResult, N as PgredisBatchOperation, O as PgredisCleanupMetrics, Q as PgredisClient, R as PgredisListenerMetrics, S as PgredisMetrics, T as PgredisMetricsOptions, U as PgredisMigrationAliases, V as PgredisOptions, W as PgredisPipeline, X as PgredisQueueMetrics, Y as PgredisSchemaOptions, Z as PgredisTableMetrics, _ as PipelineCommand, $ as PipelineFacade, h as Queue, k as QueueResult, a0 as RedisSetAliasOptions, l as SendOptions, m as WorkHandler, n as WorkOptions, a1 as advisoryLockKeyToSqlArgs, a2 as collectPgredisMetrics, a3 as createPgAdvisoryLocker, a4 as createPgBossJobQueue, a5 as createPgCounter, a6 as createPgFixedWindowRateLimiter, a7 as createPgOutboxStream, a8 as createPgSlidingWindowRateLimiter, a9 as createPgTokenBucketRateLimiter, aa as createPgredis, ab as createPgredisMigrationAliases, ac as withPgAdvisoryLock } from './client-ChVkyyno.js';
3
3
  export { PgHash, PgHashOptions, PgHashScanResult, PgHashSchemaOptions, createPgHash } from './hash-index.js';
4
4
  export { PgList, PgListBlockingPopOptions, PgListBlockingPopResult, PgListOptions, PgListScanResult, PgListSchemaOptions, createPgList } from './list-index.js';
5
5
  export { NotifyHandler, PgListenerEvents, PgListenerHandle, PgListenerHealth, PgListenerOptions, PgNotifyPayload, PgPublisher, createBunPgListener, createPgListener, createPgPublisher, publishPgNotify } from './pubsub-index.js';
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  import {
10
10
  PgKvCache,
11
11
  createPgKvCache
12
- } from "./chunk-VLFUE33D.js";
12
+ } from "./chunk-BD36RDOX.js";
13
13
  import {
14
14
  PgList,
15
15
  createPgList
@@ -1159,15 +1159,15 @@ function createPgredis(options) {
1159
1159
  }, intervalMs);
1160
1160
  return () => clearInterval(timer);
1161
1161
  },
1162
- async ensureSchema() {
1163
- await cache.ensureSchema();
1164
- await counter.ensureSchema();
1165
- await hash.ensureSchema();
1166
- await set.ensureSchema();
1167
- await list.ensureSchema();
1168
- await sortedSet.ensureSchema();
1162
+ async ensureSchema(schemaOptions = {}) {
1163
+ await cache.ensureSchema(schemaOptions);
1164
+ await counter.ensureSchema(schemaOptions);
1165
+ await hash.ensureSchema(schemaOptions);
1166
+ await set.ensureSchema(schemaOptions);
1167
+ await list.ensureSchema(schemaOptions);
1168
+ await sortedSet.ensureSchema(schemaOptions);
1169
1169
  await outbox.ensureSchema();
1170
- if (rateLimit) await rateLimit.ensureSchema();
1170
+ if (rateLimit) await rateLimit.ensureSchema(schemaOptions);
1171
1171
  }
1172
1172
  };
1173
1173
  client.redis = createPgredisMigrationAliases(client);
@@ -1,5 +1,9 @@
1
+ import { NotifyHandler, PgListenerHandle } from './pubsub-index.js';
2
+ import './sql-DKf2TDlu.js';
3
+
1
4
  interface BunSqlLike {
2
5
  unsafe<T = Record<string, unknown>>(query: string, params?: readonly unknown[]): Promise<T[]>;
6
+ begin?<T>(callback: (tx: BunSqlLike) => Promise<T>): Promise<T>;
3
7
  }
4
8
  interface PgKvCacheL1Options {
5
9
  max?: number;
@@ -8,6 +12,16 @@ interface PgKvCacheL1Options {
8
12
  interface PgKvCacheNotifyOptions {
9
13
  channel?: string;
10
14
  enabled?: boolean;
15
+ listener?: PgKvCacheListenerFactory;
16
+ clearL1OnReconnect?: boolean;
17
+ }
18
+ interface PgKvCacheListenerFactoryOptions {
19
+ channels: string[];
20
+ onNotify: NotifyHandler;
21
+ }
22
+ type PgKvCacheListenerFactory = (options: PgKvCacheListenerFactoryOptions) => PgListenerHandle;
23
+ interface PgKvCacheInvalidationOptions {
24
+ clearL1OnReconnect?: boolean;
11
25
  }
12
26
  interface PgKvCacheOptions {
13
27
  sql: BunSqlLike;
@@ -63,6 +77,9 @@ declare class PgKvCache {
63
77
  private readonly notifyEnabled;
64
78
  private readonly serializer;
65
79
  private readonly l1;
80
+ private l1Generation;
81
+ private invalidationListener;
82
+ private invalidationReconnectUnsubscribe;
66
83
  constructor(options: PgKvCacheOptions);
67
84
  ensureSchema(options?: PgKvSchemaOptions): Promise<void>;
68
85
  get<T = unknown>(key: string): Promise<T | null>;
@@ -89,6 +106,9 @@ declare class PgKvCache {
89
106
  touch(key: string): Promise<boolean>;
90
107
  ttl(key: string): Promise<number | null>;
91
108
  invalidate(key: string): void;
109
+ invalidateAll(): void;
110
+ startInvalidationListener(factory: PgKvCacheListenerFactory, options?: PgKvCacheInvalidationOptions): PgListenerHandle;
111
+ stopInvalidationListener(): void;
92
112
  handleNotification(payload: string | PgKvNotification): boolean;
93
113
  keys(pattern?: string, limit?: number): Promise<string[]>;
94
114
  scan(cursor?: string | null, count?: number, pattern?: string): Promise<{
@@ -105,8 +125,10 @@ declare class PgKvCache {
105
125
  getdel<T = unknown>(key: string): Promise<T | null>;
106
126
  stats(): PgKvCacheStats;
107
127
  private publish;
128
+ private runSerializable;
108
129
  private deserialize;
109
130
  private resolveSetMode;
131
+ private resolveNotifyOptions;
110
132
  private parseNotification;
111
133
  private getL1;
112
134
  private setL1;
@@ -117,4 +139,4 @@ declare class PgKvCache {
117
139
  }
118
140
  declare function createPgKvCache(options: PgKvCacheOptions): PgKvCache;
119
141
 
120
- export { type BunSqlLike, PgKvCache, type PgKvCacheL1Options, type PgKvCacheNotifyOptions, type PgKvCacheOptions, type PgKvCacheStats, type PgKvCompareAndSwapOptions, type PgKvNotification, type PgKvSchemaOptions, type PgKvSerializer, type PgKvSetOptions, createPgKvCache };
142
+ export { type BunSqlLike, PgKvCache, type PgKvCacheInvalidationOptions, type PgKvCacheL1Options, type PgKvCacheListenerFactory, type PgKvCacheListenerFactoryOptions, type PgKvCacheNotifyOptions, type PgKvCacheOptions, type PgKvCacheStats, type PgKvCompareAndSwapOptions, type PgKvNotification, type PgKvSchemaOptions, type PgKvSerializer, type PgKvSetOptions, createPgKvCache };
package/dist/kv-cache.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  PgKvCache,
3
3
  createPgKvCache
4
- } from "./chunk-VLFUE33D.js";
4
+ } from "./chunk-BD36RDOX.js";
5
5
  export {
6
6
  PgKvCache,
7
7
  createPgKvCache
package/dist/kv.d.ts CHANGED
@@ -1 +1,3 @@
1
- export { BunSqlLike, PgKvCache, PgKvCacheL1Options, PgKvCacheNotifyOptions, PgKvCacheOptions, PgKvCacheStats, PgKvNotification, PgKvSchemaOptions, PgKvSerializer, PgKvSetOptions, createPgKvCache } from './kv-cache.js';
1
+ export { BunSqlLike, PgKvCache, PgKvCacheInvalidationOptions, PgKvCacheL1Options, PgKvCacheListenerFactory, PgKvCacheListenerFactoryOptions, PgKvCacheNotifyOptions, PgKvCacheOptions, PgKvCacheStats, PgKvNotification, PgKvSchemaOptions, PgKvSerializer, PgKvSetOptions, createPgKvCache } from './kv-cache.js';
2
+ import './pubsub-index.js';
3
+ import './sql-DKf2TDlu.js';
package/dist/kv.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  PgKvCache,
3
3
  createPgKvCache
4
- } from "./chunk-VLFUE33D.js";
4
+ } from "./chunk-BD36RDOX.js";
5
5
  export {
6
6
  PgKvCache,
7
7
  createPgKvCache
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@postgresx/noredis",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "PostgreSQL-backed Redis feature replacement toolkit: KV/TTL cache, pub/sub, advisory locks, rate limiting, and pg-boss queues",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "https://github.com/zuohuadong/postgresx",
9
+ "url": "https://github.com/vibeunion/postgresx",
10
10
  "directory": "packages/pgredis"
11
11
  },
12
12
  "sideEffects": false,
@@ -92,7 +92,7 @@
92
92
  "@types/bun": "^1.3.14",
93
93
  "@types/node": "^25.0.0",
94
94
  "@types/pg": "^8.16.0",
95
- "@postgresx/bun-listen": "^0.3.1",
95
+ "@postgresx/bun-listen": "^0.3.2",
96
96
  "tsup": "^8.5.0",
97
97
  "typescript": "^6.0.3"
98
98
  }