@postgresx/noredis 0.8.0 → 0.9.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
@@ -286,11 +286,19 @@ pg.cache.stopInvalidationListener();
286
286
 
287
287
  Remote notifications invalidate matching L1 entries. A listener reconnect
288
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
289
+ disconnect cannot leave stale entries behind. By default the cache also
290
+ pauses L1 while the listener is unhealthy: `close`, `error`, and `reconnect`
291
+ events clear and bypass L1, and the listener's `connected` event clears and
292
+ resumes it. Set `notify.pauseOnDisconnect: false` to keep serving L1 through
293
+ disconnects at the cost of potentially stale reads. `getset()` runs in a retried
290
294
  serializable transaction and therefore requires an adapter with `begin()`;
291
295
  the built-in Bun and Node adapters provide it. `getdel()` uses one atomic
292
296
  `DELETE ... RETURNING` statement.
293
297
 
298
+ Concurrent reads of the same key are coalesced into a single Postgres
299
+ round-trip by default. Disable it with `singleflight: false`; `stats()`
300
+ reports `inflightReads` and the monotonic `coalescedReads` counter.
301
+
294
302
  ## Pub/Sub
295
303
 
296
304
  Publishing uses only the configured SQL adapter. Bun LISTEN/NOTIFY consumption
@@ -79,12 +79,16 @@ var PgKvCache = class {
79
79
  l1TtlMs;
80
80
  notifyEnabled;
81
81
  serializer;
82
+ singleflight;
82
83
  l1 = /* @__PURE__ */ new Map();
84
+ inflight = /* @__PURE__ */ new Map();
83
85
  l1Generation = 0;
84
86
  l1Hits = 0;
85
87
  l1Misses = 0;
88
+ l1Paused = false;
89
+ coalescedReads = 0;
86
90
  invalidationListener = null;
87
- invalidationReconnectUnsubscribe = null;
91
+ invalidationUnsubscribers = [];
88
92
  constructor(options) {
89
93
  this.sql = options.sql;
90
94
  this.namespace = options.namespace || DEFAULT_NAMESPACE;
@@ -101,10 +105,12 @@ var PgKvCache = class {
101
105
  serialize: (value) => value,
102
106
  deserialize: (value) => value
103
107
  };
108
+ this.singleflight = options.singleflight !== false;
104
109
  const listenerFactory = this.resolveNotifyOptions(options.notify)?.listener;
105
110
  if (listenerFactory) {
106
111
  this.startInvalidationListener(listenerFactory, {
107
- clearL1OnReconnect: this.resolveNotifyOptions(options.notify)?.clearL1OnReconnect
112
+ clearL1OnReconnect: this.resolveNotifyOptions(options.notify)?.clearL1OnReconnect,
113
+ pauseOnDisconnect: this.resolveNotifyOptions(options.notify)?.pauseOnDisconnect
108
114
  });
109
115
  }
110
116
  }
@@ -133,6 +139,22 @@ var PgKvCache = class {
133
139
  async get(key) {
134
140
  const cached = this.getL1(key);
135
141
  if (cached.hit) return cached.value;
142
+ return this.loadKey(key);
143
+ }
144
+ loadKey(key) {
145
+ if (!this.singleflight) return this.readKey(key);
146
+ const existing = this.inflight.get(key);
147
+ if (existing) {
148
+ this.coalescedReads += 1;
149
+ return existing;
150
+ }
151
+ const pending = this.readKey(key).finally(() => {
152
+ if (this.inflight.get(key) === pending) this.inflight.delete(key);
153
+ });
154
+ this.inflight.set(key, pending);
155
+ return pending;
156
+ }
157
+ async readKey(key) {
136
158
  const l1Generation = this.l1Generation;
137
159
  const rows = await this.sql.unsafe(
138
160
  `SELECT value, expires_at
@@ -428,19 +450,45 @@ var PgKvCache = class {
428
450
  if (channel === this.notifyChannel) this.handleNotification(payload);
429
451
  }
430
452
  });
431
- const reconnectUnsubscribe = options.clearL1OnReconnect === false ? null : listener.on("reconnect", () => this.invalidateAll());
453
+ const unsubscribers = [];
454
+ if (options.pauseOnDisconnect !== false) {
455
+ unsubscribers.push(listener.on("close", () => this.pauseL1()));
456
+ unsubscribers.push(listener.on("error", () => this.pauseL1()));
457
+ unsubscribers.push(listener.on("reconnect", () => this.pauseL1()));
458
+ unsubscribers.push(listener.on("connected", () => this.resumeL1()));
459
+ }
460
+ if (options.clearL1OnReconnect !== false) {
461
+ unsubscribers.push(listener.on("reconnect", () => this.invalidateAll()));
462
+ }
432
463
  this.invalidationListener = listener;
433
- this.invalidationReconnectUnsubscribe = reconnectUnsubscribe;
464
+ this.invalidationUnsubscribers = unsubscribers;
465
+ if (options.pauseOnDisconnect !== false) {
466
+ if (listener.getHealth().connected) {
467
+ this.resumeL1();
468
+ } else {
469
+ this.pauseL1();
470
+ }
471
+ }
434
472
  return listener;
435
473
  }
436
474
  stopInvalidationListener() {
437
475
  const listener = this.invalidationListener;
438
- const reconnectUnsubscribe = this.invalidationReconnectUnsubscribe;
476
+ const unsubscribers = this.invalidationUnsubscribers;
439
477
  this.invalidationListener = null;
440
- this.invalidationReconnectUnsubscribe = null;
441
- reconnectUnsubscribe?.();
478
+ this.invalidationUnsubscribers = [];
479
+ for (const unsubscribe of unsubscribers) unsubscribe();
442
480
  listener?.close();
443
481
  }
482
+ pauseL1() {
483
+ this.l1Paused = true;
484
+ this.l1Generation += 1;
485
+ this.l1.clear();
486
+ }
487
+ resumeL1() {
488
+ this.l1Generation += 1;
489
+ this.l1.clear();
490
+ this.l1Paused = false;
491
+ }
444
492
  handleNotification(payload) {
445
493
  const event = typeof payload === "string" ? this.parseNotification(payload) : payload;
446
494
  if (!event || event.namespace !== this.namespace || event.senderId === this.instanceId) return false;
@@ -601,7 +649,10 @@ var PgKvCache = class {
601
649
  l1Size: this.l1.size,
602
650
  l1Max: this.l1Max,
603
651
  l1Hits: this.l1Hits,
604
- l1Misses: this.l1Misses
652
+ l1Misses: this.l1Misses,
653
+ l1Paused: this.l1Paused,
654
+ inflightReads: this.inflight.size,
655
+ coalescedReads: this.coalescedReads
605
656
  };
606
657
  }
607
658
  async publish(event) {
@@ -652,7 +703,7 @@ var PgKvCache = class {
652
703
  }
653
704
  }
654
705
  getL1(key) {
655
- if (!this.l1Enabled) return { hit: false };
706
+ if (!this.l1Enabled || this.l1Paused) return { hit: false };
656
707
  const entry = this.l1.get(key);
657
708
  if (!entry) {
658
709
  this.l1Misses += 1;
@@ -669,7 +720,7 @@ var PgKvCache = class {
669
720
  return { hit: true, value: entry.value };
670
721
  }
671
722
  setL1(key, value, l2ExpiresAt, generation = this.l1Generation) {
672
- if (!this.l1Enabled || this.l1Max <= 0) return;
723
+ if (!this.l1Enabled || this.l1Paused || this.l1Max <= 0) return;
673
724
  if (generation !== this.l1Generation) return;
674
725
  const l1ExpiresAt = this.computeL1ExpiresAt(l2ExpiresAt);
675
726
  if (l1ExpiresAt !== null && l1ExpiresAt <= this.now()) {
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  import {
10
10
  PgKvCache,
11
11
  createPgKvCache
12
- } from "./chunk-6D2PPDAW.js";
12
+ } from "./chunk-YB4P7SGQ.js";
13
13
  import {
14
14
  PgList,
15
15
  createPgList
@@ -14,6 +14,8 @@ interface PgKvCacheNotifyOptions {
14
14
  enabled?: boolean;
15
15
  listener?: PgKvCacheListenerFactory;
16
16
  clearL1OnReconnect?: boolean;
17
+ /** Pause L1 reads and fills while the invalidation listener is unhealthy. Defaults to true. */
18
+ pauseOnDisconnect?: boolean;
17
19
  }
18
20
  interface PgKvCacheListenerFactoryOptions {
19
21
  channels: string[];
@@ -22,6 +24,8 @@ interface PgKvCacheListenerFactoryOptions {
22
24
  type PgKvCacheListenerFactory = (options: PgKvCacheListenerFactoryOptions) => PgListenerHandle;
23
25
  interface PgKvCacheInvalidationOptions {
24
26
  clearL1OnReconnect?: boolean;
27
+ /** Pause L1 reads and fills while the invalidation listener is unhealthy. Defaults to true. */
28
+ pauseOnDisconnect?: boolean;
25
29
  }
26
30
  interface PgKvCacheOptions {
27
31
  sql: BunSqlLike;
@@ -32,6 +36,11 @@ interface PgKvCacheOptions {
32
36
  instanceId?: string;
33
37
  now?: () => number;
34
38
  serializer?: PgKvSerializer;
39
+ /**
40
+ * Coalesce concurrent reads of the same key into a single Postgres query.
41
+ * Defaults to true; set to false to issue one query per caller.
42
+ */
43
+ singleflight?: boolean;
35
44
  }
36
45
  interface PgKvSetOptions {
37
46
  ttlMs?: number | null;
@@ -66,6 +75,12 @@ interface PgKvCacheStats {
66
75
  l1Hits: number;
67
76
  /** Monotonic L1 read misses (absent or expired) since the cache was created. */
68
77
  l1Misses: number;
78
+ /** True while L1 is bypassed because the invalidation listener is unhealthy. */
79
+ l1Paused: boolean;
80
+ /** Reads currently coalesced into an in-flight query. */
81
+ inflightReads: number;
82
+ /** Monotonic count of reads that joined an in-flight query for the same key. */
83
+ coalescedReads: number;
69
84
  }
70
85
  declare class PgKvCache {
71
86
  readonly namespace: string;
@@ -80,15 +95,21 @@ declare class PgKvCache {
80
95
  private readonly l1TtlMs;
81
96
  private readonly notifyEnabled;
82
97
  private readonly serializer;
98
+ private readonly singleflight;
83
99
  private readonly l1;
100
+ private readonly inflight;
84
101
  private l1Generation;
85
102
  private l1Hits;
86
103
  private l1Misses;
104
+ private l1Paused;
105
+ private coalescedReads;
87
106
  private invalidationListener;
88
- private invalidationReconnectUnsubscribe;
107
+ private invalidationUnsubscribers;
89
108
  constructor(options: PgKvCacheOptions);
90
109
  ensureSchema(options?: PgKvSchemaOptions): Promise<void>;
91
110
  get<T = unknown>(key: string): Promise<T | null>;
111
+ private loadKey;
112
+ private readKey;
92
113
  mget<T = unknown>(keys: readonly string[]): Promise<Map<string, T>>;
93
114
  set<T = unknown>(key: string, value: T, options?: PgKvSetOptions): Promise<boolean>;
94
115
  mset<T = unknown>(entries: Iterable<readonly [string, T]>, options?: PgKvSetOptions): Promise<void>;
@@ -115,6 +136,8 @@ declare class PgKvCache {
115
136
  invalidateAll(): void;
116
137
  startInvalidationListener(factory: PgKvCacheListenerFactory, options?: PgKvCacheInvalidationOptions): PgListenerHandle;
117
138
  stopInvalidationListener(): void;
139
+ private pauseL1;
140
+ private resumeL1;
118
141
  handleNotification(payload: string | PgKvNotification): boolean;
119
142
  keys(pattern?: string, limit?: number): Promise<string[]>;
120
143
  scan(cursor?: string | null, count?: number, pattern?: string): Promise<{
package/dist/kv-cache.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  PgKvCache,
3
3
  createPgKvCache
4
- } from "./chunk-6D2PPDAW.js";
4
+ } from "./chunk-YB4P7SGQ.js";
5
5
  export {
6
6
  PgKvCache,
7
7
  createPgKvCache
package/dist/kv.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  PgKvCache,
3
3
  createPgKvCache
4
- } from "./chunk-6D2PPDAW.js";
4
+ } from "./chunk-YB4P7SGQ.js";
5
5
  export {
6
6
  PgKvCache,
7
7
  createPgKvCache
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postgresx/noredis",
3
- "version": "0.8.0",
3
+ "version": "0.9.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",