@postgresx/noredis 0.1.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # pgredis
2
2
 
3
+ > 🌐 **English | [中文](#中文)**
4
+
3
5
  PostgreSQL-only application infrastructure toolkit for projects that want to
4
6
  replace a Redis + PostgreSQL stack with PostgreSQL alone.
5
7
 
@@ -10,6 +12,7 @@ Redis infrastructure use cases with PostgreSQL-friendly primitives.
10
12
  It provides:
11
13
 
12
14
  - KV/TTL cache
15
+ - KV conditional writes: `NX`/`XX`, compare-and-swap, `expire`, `persist`, `touch`, and pluggable serialization
13
16
  - atomic counters
14
17
  - hash, set, list, and sorted-set helpers
15
18
  - cursor-style scans and structure-level TTL for collection helpers
@@ -17,7 +20,10 @@ It provides:
17
20
  - transaction-scoped advisory locks
18
21
  - fixed-window, sliding-window, and token-bucket rate limiting
19
22
  - a simple `pg-boss` queue adapter for background jobs and long tasks
20
- - a `createPgredis()` facade for one-shot initialization, health, stats, and cleanup
23
+ - a durable outbox/stream helper for event-log style processing
24
+ - Redis-style migration aliases for common commands, without protocol compatibility claims
25
+ - framework-neutral session stores and cache helpers for Express/Fastify/Elysia-style stacks
26
+ - a `createPgredis()` facade for one-shot initialization, `batch()`/`pipeline()`, health, stats, metrics, and cleanup
21
27
 
22
28
  ## Installation
23
29
 
@@ -125,6 +131,30 @@ const cache = createPgKvCache({
125
131
  await cache.ensureSchema();
126
132
  await cache.set("token:abc", { userId: 1 }, { ttlMs: 60_000 });
127
133
  const value = await cache.get<{ userId: number }>("token:abc");
134
+
135
+ await cache.set("token:abc", { userId: 2 }, { nx: true }); // only when missing
136
+ await cache.set("token:abc", { userId: 3 }, { xx: true }); // only when present
137
+ await cache.compareAndSwap("token:abc", { userId: 3 }, { userId: 4 });
138
+ await cache.expire("token:abc", 60_000);
139
+ await cache.persist("token:abc");
140
+ await cache.touch("token:abc");
141
+ ```
142
+
143
+ Use `serializer` when values need an application envelope before they are stored
144
+ as JSONB:
145
+
146
+ ```ts
147
+ const cache = createPgKvCache({
148
+ sql,
149
+ serializer: {
150
+ serialize(value) {
151
+ return { v: 1, value };
152
+ },
153
+ deserialize(row) {
154
+ return (row as { value: unknown }).value;
155
+ }
156
+ }
157
+ });
128
158
  ```
129
159
 
130
160
  ## Unified client
@@ -154,9 +184,71 @@ await pg.hash.expire("session:abc", 60_000);
154
184
  await pg.hash.hscan("session:abc", null, 100);
155
185
  await pg.health();
156
186
  await pg.stats();
187
+ await pg.metrics();
157
188
  const stopCleanup = pg.startCleanupWorker({ intervalMs: 60_000 });
158
189
  ```
159
190
 
191
+ `batch()` runs a callback inside the SQL adapter transaction when the adapter
192
+ supports `begin()`. `pipeline()` is an ergonomic ordered-operation facade for
193
+ migration work; it is not a Redis wire protocol pipeline.
194
+
195
+ ```ts
196
+ const result = await pg.batch(async (tx) => {
197
+ await tx.cache.set("session:abc", { userId: 1 });
198
+ return tx.cache.get("session:abc");
199
+ });
200
+
201
+ const results = await pg.pipeline()
202
+ .set("counter-cache", 1)
203
+ .get("counter-cache")
204
+ .incr("daily:requests")
205
+ .exec();
206
+ ```
207
+
208
+ Common Redis-style aliases are available under `pg.redis` for migration
209
+ ergonomics:
210
+
211
+ ```ts
212
+ await pg.redis.set("session:abc", { userId: 1 }, { PX: 60_000, NX: true });
213
+ await pg.redis.get("session:abc");
214
+ await pg.redis.hset("profile:1", "name", "Ada");
215
+ await pg.redis.blpop("worker:list", 5);
216
+ ```
217
+
218
+ These aliases call typed pgredis primitives and do not make the package Redis
219
+ protocol compatible.
220
+
221
+ ### ioredis and node-redis facades
222
+
223
+ For code that expects a Redis client-shaped object, use the additive adapter
224
+ subpaths. They expose a whitelist of high-frequency `ioredis` lower-case
225
+ methods and node-redis camelCase methods while still requiring an existing
226
+ `PgredisClient`.
227
+
228
+ ```ts
229
+ import { createIoredisAdapter } from "@postgresx/noredis/adapters/ioredis";
230
+ import { createRedisJsAdapter } from "@postgresx/noredis/adapters/redis";
231
+
232
+ const ioredisLike = createIoredisAdapter({ client: pg });
233
+ const redisJsLike = createRedisJsAdapter({ client: pg });
234
+
235
+ await ioredisLike.set("cache:user:1", "Ada", "EX", 60, "NX");
236
+ await redisJsLike.hSet("profile:1", "name", "Ada");
237
+ ```
238
+
239
+ The facades are useful for cache-manager-style `get`/`set`/`del`/`mget`/`mset`
240
+ calls and simple Pub/Sub publishing. They do not create a Redis TCP connection,
241
+ do not implement `EVAL`/Lua, Cluster, Sentinel, `WATCH`, Redis Streams consumer
242
+ groups, or server administration commands. Unsupported commands throw
243
+ `UnsupportedCommandError` instead of silently pretending to work.
244
+
245
+ The typed primitives are also available from explicit subpaths:
246
+ `@postgresx/noredis/kv`, `hash`, `set`, `sorted-set`, `list`, and `pubsub`.
247
+
248
+ If package-name aliasing is useful during migration, use the thin re-export
249
+ packages `@postgresx/noredis-ioredis` and `@postgresx/noredis-redis`. They are
250
+ still facades over `PgredisClient`; they do not provide drop-in constructors.
251
+
160
252
  ## Pub/Sub
161
253
 
162
254
  Publishing uses only the configured SQL adapter. Bun LISTEN/NOTIFY consumption
@@ -189,6 +281,55 @@ createPgNodeListener(process.env.DATABASE_URL!, {
189
281
  });
190
282
  ```
191
283
 
284
+ ## Durable outbox / stream
285
+
286
+ Use `PgOutboxStream` when an application previously used Redis Streams for a
287
+ durable event log or worker inbox. It intentionally exposes PostgreSQL outbox
288
+ semantics instead of Redis consumer-group compatibility.
289
+
290
+ ```ts
291
+ await pg.outbox.append("billing.events", { invoiceId: "inv_1" });
292
+
293
+ const messages = await pg.outbox.claim("billing.events", "worker-a", {
294
+ limit: 10,
295
+ visibilityTimeoutMs: 30_000
296
+ });
297
+
298
+ for (const message of messages) {
299
+ await deliver(message.payload);
300
+ await pg.outbox.ack([message.id]);
301
+ }
302
+ ```
303
+
304
+ For job queues, retries, and scheduling, prefer the `pg-boss` queue adapter.
305
+ Use list `blpop()` / `brpop()` only as a migration bridge for simple worker
306
+ pulls; it polls PostgreSQL and is not a queue scheduler.
307
+
308
+ ## Web adapters
309
+
310
+ The web adapter subpath has no Express, Fastify, or Elysia runtime dependency.
311
+ It exports framework-neutral helpers that match common session-store and
312
+ read-through cache shapes:
313
+
314
+ ```ts
315
+ import {
316
+ createElysiaSessionStore,
317
+ createPgredisCacheHelpers
318
+ } from "@postgresx/noredis/adapters/web";
319
+
320
+ const sessions = createElysiaSessionStore(pg.cache, {
321
+ prefix: "sess:",
322
+ ttlMs: 24 * 60 * 60 * 1000
323
+ });
324
+
325
+ const cache = createPgredisCacheHelpers(pg.cache, {
326
+ prefix: "http:",
327
+ ttlMs: 60_000
328
+ });
329
+
330
+ const profile = await cache.wrap("profile:1", () => loadProfile("1"));
331
+ ```
332
+
192
333
  ## Advisory lock
193
334
 
194
335
  `withPgAdvisoryLock` uses transaction-scoped locks, so locks are released by
@@ -255,7 +396,8 @@ npm install @postgresx/noredis pg-boss
255
396
 
256
397
  This covers Redis-backed background job use cases such as Bull-style async
257
398
  webhooks, billing flushes, retries, and long tasks. It does not emulate Redis
258
- Streams commands.
399
+ Streams commands. Use `pg.outbox` for event-log processing and `pg.queue` for
400
+ queue-first worker migration.
259
401
 
260
402
  ## Launch readiness
261
403
 
@@ -270,14 +412,15 @@ Remaining gates before a production or 1.0 launch:
270
412
  | Area | Status | Why it matters | Recommended action |
271
413
  | --- | --- | --- | --- |
272
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. |
273
- | Benchmark baseline | Pending CI run | `benchmark.md` has not been generated yet, so there is no measured Redis vs PostgreSQL baseline to set user expectations. | Run the manual benchmark workflow before release; local benchmark runs are optional. |
415
+ | 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. |
274
416
  | 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
+ | 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. |
275
418
  | Release credentials | Guarded in workflows | Release Please and npm publish depend on repository secrets and npm provenance setup. | Workflows fail early when `RELEASE_PAT` or `NPM_TOKEN` is missing; still verify package access before the first release. |
276
419
  | Runtime operations | Documented | Cleanup, table growth, queue lag, and listener health are app-operational concerns. | See `docs/production-runbook.md` for cleanup, bloat checks, listener health, queue monitoring, and rollback guidance. |
277
420
 
278
421
  The package is suitable for an early beta once CI passes and the benchmark
279
- workflow has produced a baseline. It should not be described as a drop-in Redis
280
- or ioredis replacement.
422
+ baseline remains refreshable. It should not be described as a drop-in Redis or
423
+ ioredis replacement.
281
424
 
282
425
  ## ioredis comparison
283
426
 
@@ -289,11 +432,11 @@ Redis protocol or supporting every Redis command.
289
432
  | --- | --- | --- | --- |
290
433
  | Protocol and command surface | Sends Redis commands and supports arbitrary Redis command methods. | Exposes typed PostgreSQL-backed primitives only. | Migration requires code changes. Redis command compatibility is intentionally out of scope. |
291
434
  | Runtime dependency | Requires Redis, Redis-compatible service, or Redis Cluster/Sentinel. | Requires PostgreSQL; optional `pg`, `pg-boss`, or `@postgresx/bun-listen` only for selected features. | Good fit for teams removing a separate Redis tier. |
292
- | Strings / KV / TTL | Full Redis string command surface. | JSONB KV cache with TTL, batch get/set, prefix clear, optional local L1 cache, and notification invalidation. | Covers cache/session-style values, but not byte-string commands such as `APPEND`, `GETRANGE`, or `SETRANGE`. |
293
- | Hashes, lists, sets, sorted sets | Native Redis data structures and command coverage. | PostgreSQL table-backed helpers for common hash/list/set/zset operations. | Covers common app usage; advanced/blocking/list mutation and full command parity are not complete. |
435
+ | Strings / KV / TTL | Full Redis string command surface. | JSONB KV cache with TTL, batch get/set, prefix clear, optional local L1 cache, notification invalidation, `NX`/`XX`, CAS, `expire`, `persist`, `touch`, and pluggable serialization. | Covers cache/session-style values, but not byte-string commands such as `APPEND`, `GETRANGE`, or `SETRANGE`. |
436
+ | Hashes, lists, sets, sorted sets | Native Redis data structures and command coverage. | PostgreSQL table-backed helpers for common hash/list/set/zset operations. | Covers common app usage; list blocking pop is a polling migration bridge, not a scheduler. |
294
437
  | Pub/Sub | Redis Pub/Sub, pattern subscriptions, binary messages, cluster behavior. | PostgreSQL `LISTEN/NOTIFY` publisher and Node/Bun listeners. | Good for lightweight invalidation/events; not durable and limited by PostgreSQL NOTIFY payload size. |
295
- | Streams / consumer groups | Redis Streams commands such as `XADD` and consumer groups. | No Redis Streams API; queues are delegated to `pg-boss`. | Add a durable outbox/stream API if event-log semantics are required. |
296
- | Pipelining / transactions | `pipeline`, `multi`, `exec`, and cluster-aware behavior. | Batch helpers exist for some primitives; no generic pipeline or Redis-style transaction facade. | Add a pgredis batch/pipeline facade for migration ergonomics. |
438
+ | Streams / consumer groups | Redis Streams commands such as `XADD` and consumer groups. | Durable outbox/stream helper plus `pg-boss` queue adapter. | No Redis consumer-group protocol or pending-entry-list compatibility. |
439
+ | Pipelining / transactions | `pipeline`, `multi`, `exec`, and cluster-aware behavior. | `batch()` uses SQL adapter transactions when available; `pipeline()` executes ordered pgredis operations. | No Redis wire-level pipeline or `WATCH` semantics. |
297
440
  | Lua scripting / Redis Functions | Supports scripting commands and custom command definitions. | Out of scope; use SQL, stored procedures, or application code. | Do not port Lua directly; rewrite as SQL/app logic. |
298
441
  | Cluster / Sentinel / NAT mapping | Built into ioredis. | Inherited from PostgreSQL HA, pooling, and networking. | Document PostgreSQL deployment assumptions instead of Redis HA options. |
299
442
  | TLS / ACL / auth | Redis connection, TLS, and ACL options. | Delegated to PostgreSQL driver, DSN, and database roles. | Use PostgreSQL credentials and transport settings. |
@@ -310,7 +453,7 @@ feature replacement, not command compatibility.
310
453
  | --- | --- | --- | --- |
311
454
  | String `GET`/`SET`/`DEL`/TTL | Covered | `PgKvCache` stores JSONB values with optional TTL and L1 cache | No byte-level Redis string ops such as `APPEND`, `GETRANGE`, `SETRANGE` |
312
455
  | Key expiration | Covered | `expires_at`, `cleanupExpired`, L1 TTL | No Redis passive/active eviction semantics or keyspace notifications |
313
- | Batch get/set | Covered | `mget`, `mset` | No pipelining API yet |
456
+ | Batch get/set | Covered | `mget`, `mset`, `batch()`, and `pipeline()` | Pipeline groups pgredis operations, not Redis commands |
314
457
  | Atomic counters | Covered | `PgCounter` over BIGINT UPSERT | Integer counters only |
315
458
  | Pub/Sub | Covered | `LISTEN/NOTIFY` plus `createPgListener` | Not durable, payload size is limited by PostgreSQL NOTIFY |
316
459
  | Distributed locks | Covered | Transaction-scoped advisory locks | No Redlock-compatible lease renewal model |
@@ -319,11 +462,11 @@ feature replacement, not command compatibility.
319
462
  | Token-bucket rate limit | Covered | PostgreSQL row state with refill calculation | Designed for app-level API throttling |
320
463
  | Queues / delayed jobs / retries | Covered via adapter | `pg-boss` wrapper | Not Redis Streams compatible |
321
464
  | Hashes | Covered | `PgHash` over `(namespace, key, field)` rows | `HSCAN`-style cursor scan and key TTL covered; no per-field TTL |
322
- | Lists | Covered | `PgList` over ordered rows | Cursor scan and key TTL covered; no blocking pop; use pg-boss for real job queues |
323
- | Sets | Covered | `PgSet` over unique-indexed rows | `SINTER`, `SUNION`, `SDIFF`, cursor scan, and key TTL covered |
324
- | Sorted sets | Covered | `PgSortedSet` over `(member, score)` rows | Rank, score range, count, pop-min, scan, and key TTL covered |
325
- | Streams / consumer groups | Delegated / missing | Use `pg-boss` for jobs; application table for event logs | No `XADD`, `XREADGROUP`, pending-entry list |
326
- | Transactions / optimistic watch | Missing | Use PostgreSQL transactions and row locks directly | No Redis `MULTI`/`EXEC`/`WATCH` facade |
465
+ | Lists | Covered | `PgList` over ordered rows | Cursor scan, key TTL, and polling `blpop`/`brpop`; use pg-boss for real job queues |
466
+ | Sets | Covered | `PgSet` over unique-indexed rows | `SINTER`, `SUNION`, `SDIFF`, `SPOP`, `SRANDMEMBER`, `SMOVE`, cursor scan, and key TTL covered |
467
+ | Sorted sets | Covered | `PgSortedSet` over `(member, score)` rows | Rank, score range, count, increment, pop-min/max, scan, and key TTL covered |
468
+ | Streams / consumer groups | Partially covered | Use `PgOutboxStream` for event logs and `pg-boss` for jobs | No Redis `XREADGROUP` or pending-entry-list compatibility |
469
+ | Transactions / optimistic watch | Partially covered | Use `batch()` for adapter transactions; use PostgreSQL row locks directly for optimistic flows | No Redis `WATCH` facade |
327
470
  | Lua scripting / functions | Out of scope | Use SQL, stored procedures, or app code | No Redis Lua/function runtime |
328
471
  | Bitmaps / bitfields | Missing | Use `bytea`, roaring bitmap extension, or SQL tables | No bit operation API |
329
472
  | HyperLogLog | Missing | Use PostgreSQL extensions or approximate-count tables | No `PFADD`/`PFCOUNT` |
@@ -334,20 +477,22 @@ feature replacement, not command compatibility.
334
477
  | Bloom / Cuckoo / Count-Min | Missing | Use PostgreSQL extensions or app tables | No RedisBloom-compatible API |
335
478
  | ACL/auth | Out of scope | Use PostgreSQL credentials and application auth | No Redis ACL facade |
336
479
  | Persistence/replication/cluster | Out of scope | Inherited from PostgreSQL deployment | No Redis Cluster slot/hash semantics |
337
- | Server introspection | Partial | `createPgredis().health()` and `stats()` expose basic health/cache/queue stats | No Redis `INFO`, `MONITOR`, command stats facade |
480
+ | Server introspection | Partial | `createPgredis().health()`, `stats()`, and `metrics()` expose health, cleanup, table size, TTL backlog, listener, and queue views | No Redis `INFO`, `MONITOR`, command stats facade |
338
481
 
339
482
  ## Missing pieces to consider next
340
483
 
341
- The highest-value additions for Redis replacement are now:
484
+ The highest-value migration features now have first-pass APIs and tests:
485
+ PostgreSQL integration coverage, tarball smoke tests, `batch()`/`pipeline()`,
486
+ outbox/stream, list blocking-pop helpers, production metrics, Redis-style
487
+ aliases, web adapters, and expanded KV write semantics.
342
488
 
343
- 1. PostgreSQL integration test suite and tarball install smoke tests.
344
- 2. Generic `batch()` or `pipeline()` facade for grouping pgredis operations.
345
- 3. Durable outbox/stream API for applications that currently use Redis Streams.
346
- 4. Blocking list pop or explicit queue-first migration guidance for worker pulls.
347
- 5. Production metrics for table sizes, cleanup counts, TTL backlog, listener reconnects, and queue lag.
348
- 6. Redis-style migration aliases for the most common commands, without claiming protocol compatibility.
349
- 7. Framework adapters such as session stores for Express/Fastify/Elysia and cache helpers for common web stacks.
350
- 8. More KV options: `set` NX/XX semantics, compare-and-swap, touch/expire helpers, and configurable serialization.
489
+ 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):
491
+
492
+ 1. Redis Streams consumer-group migration patterns for `XREADGROUP`, pending entries, and retries.
493
+ 2. Framework-specific session middleware examples built on the web adapter.
494
+ 3. Operation-level retry/backoff boundaries for SQL adapters.
495
+ 4. Benchmark baselines for outbox, list pop, and pipeline workloads.
351
496
 
352
497
  ## Design notes
353
498
 
@@ -358,3 +503,458 @@ PostgreSQL-friendly semantics:
358
503
  - pub/sub is `LISTEN/NOTIFY`, not durable messaging
359
504
  - queues are delegated to `pg-boss`
360
505
  - KV values are JSONB rows with optional local L1 caching
506
+
507
+ ---
508
+
509
+ ## 中文
510
+
511
+ > 🌐 [English](#pgredis) | **中文**
512
+
513
+ `pgredis` 是一个纯 PostgreSQL 的应用基础设施工具包,旨在帮助项目从 Redis + PostgreSQL 架构迁移到仅使用 PostgreSQL。
514
+
515
+ `pgredis` 不是 Redis 协议兼容客户端,也不是 `ioredis`、`node-redis`、Bull 或 Redis Cluster 的即插即用替代品。它使用 PostgreSQL 友好的原语来替代 Redis 的基础设施用例。
516
+
517
+ 功能包括:
518
+
519
+ - KV/TTL 缓存
520
+ - KV 条件写入:`NX`/`XX`、比较并交换、`expire`、`persist`、`touch` 和可插拔序列化
521
+ - 原子计数器
522
+ - 哈希、集合、列表和有序集合辅助函数
523
+ - 游标式扫描和集合辅助函数的结构级 TTL
524
+ - 通过 PostgreSQL `LISTEN/NOTIFY` 实现的 Pub/Sub 辅助函数
525
+ - 事务作用域的咨询锁
526
+ - 固定窗口、滑动窗口和令牌桶限流
527
+ - 简单的 `pg-boss` 队列适配器,用于后台任务和长任务
528
+ - 用于事件日志式处理的持久化 outbox/stream 辅助函数
529
+ - 常见命令的 Redis 风格迁移别名,但不声明协议兼容
530
+ - 面向 Express/Fastify/Elysia 风格栈的框架中立 session store 和 cache helper
531
+ - `createPgredis()` 外观,用于一次性初始化、`batch()`/`pipeline()`、健康检查、统计、指标和清理
532
+
533
+ ## 安装
534
+
535
+ `@postgresx/noredis` 本身没有必需的运行时依赖。请仅为你使用的适配器或功能安装特定的运行时包。
536
+
537
+ ### Bun.js
538
+
539
+ 使用 `Bun.SQL` 的基础工具包:
540
+
541
+ ```bash
542
+ bun add @postgresx/noredis
543
+ ```
544
+
545
+ ```ts
546
+ import { SQL } from "bun";
547
+ import { createPgredis } from "@postgresx/noredis";
548
+ import { createBunSqlAdapter } from "@postgresx/noredis/adapters/bun";
549
+
550
+ const sql = createBunSqlAdapter(new SQL(process.env.DATABASE_URL!));
551
+ const pg = createPgredis({ sql, namespace: "app" });
552
+ ```
553
+
554
+ Bun 实时 `LISTEN/NOTIFY`:
555
+
556
+ ```bash
557
+ bun add @postgresx/noredis @postgresx/bun-listen
558
+ ```
559
+
560
+ ```ts
561
+ import { createBunPgListener, publishPgNotify } from "@postgresx/noredis";
562
+
563
+ const listener = createBunPgListener(process.env.DATABASE_URL!, {
564
+ channels: ["cache_invalidate"],
565
+ onNotify(channel, payload) {
566
+ console.log(channel, payload);
567
+ }
568
+ });
569
+
570
+ await publishPgNotify(sql, "cache_invalidate", { key: "token:abc" });
571
+ listener.close();
572
+ ```
573
+
574
+ 当你不需要其余工具包时,仅安装 Bun 原生监听器:
575
+
576
+ ```bash
577
+ bun add @postgresx/bun-listen
578
+ ```
579
+
580
+ ```ts
581
+ import { createPgListener } from "@postgresx/bun-listen";
582
+
583
+ const listener = createPgListener(process.env.DATABASE_URL!, ["events"], (_channel, payload) => {
584
+ console.log(payload);
585
+ });
586
+ ```
587
+
588
+ ### Node.js
589
+
590
+ 使用 `pg` 的基础工具包:
591
+
592
+ ```bash
593
+ npm install @postgresx/noredis pg
594
+ ```
595
+
596
+ ```ts
597
+ import { createPgredis } from "@postgresx/noredis";
598
+ import { createPgAdapter } from "@postgresx/noredis/adapters/node";
599
+
600
+ const sql = createPgAdapter(process.env.DATABASE_URL!);
601
+ const pg = createPgredis({ sql, namespace: "app" });
602
+ ```
603
+
604
+ Node.js `LISTEN/NOTIFY`:
605
+
606
+ ```ts
607
+ import { createPgNodeListener } from "@postgresx/noredis/adapters/node";
608
+
609
+ const listener = createPgNodeListener(process.env.DATABASE_URL!, {
610
+ channels: ["cache_invalidate"],
611
+ onNotify(channel, payload) {
612
+ console.log(channel, payload);
613
+ }
614
+ });
615
+ ```
616
+
617
+ 使用 `pg-boss` 的队列:
618
+
619
+ ```bash
620
+ npm install @postgresx/noredis pg pg-boss
621
+ ```
622
+
623
+ ## KV/TTL 缓存
624
+
625
+ ```ts
626
+ import { createPgKvCache } from "@postgresx/noredis";
627
+
628
+ const cache = createPgKvCache({
629
+ sql,
630
+ namespace: "auth",
631
+ l1: { max: 10_000, ttlMs: 60_000 }
632
+ });
633
+
634
+ await cache.ensureSchema();
635
+ await cache.set("token:abc", { userId: 1 }, { ttlMs: 60_000 });
636
+ const value = await cache.get<{ userId: number }>("token:abc");
637
+
638
+ await cache.set("token:abc", { userId: 2 }, { nx: true });
639
+ await cache.set("token:abc", { userId: 3 }, { xx: true });
640
+ await cache.compareAndSwap("token:abc", { userId: 3 }, { userId: 4 });
641
+ await cache.expire("token:abc", 60_000);
642
+ await cache.persist("token:abc");
643
+ await cache.touch("token:abc");
644
+ ```
645
+
646
+ ## 统一客户端
647
+
648
+ ```ts
649
+ import { createPgredis } from "@postgresx/noredis";
650
+
651
+ const pg = createPgredis({
652
+ sql,
653
+ namespace: "app",
654
+ rateLimit: { limit: 60, windowMs: 60_000 },
655
+ queue: {
656
+ connectionString: process.env.DATABASE_URL,
657
+ schema: "pgboss"
658
+ }
659
+ });
660
+
661
+ await pg.ensureSchema();
662
+
663
+ await pg.cache.set("token:abc", { userId: 1 }, { ttlMs: 60_000 });
664
+ await pg.counter.incr("daily:requests");
665
+ await pg.hash.hset("session:abc", "userId", 1);
666
+ await pg.set.sadd("online-users", "1");
667
+ await pg.list.rpush("recent-events", { id: "evt_1" });
668
+ await pg.sortedSet.zadd("leaderboard", 100, "user:1");
669
+ await pg.hash.expire("session:abc", 60_000);
670
+ await pg.hash.hscan("session:abc", null, 100);
671
+ await pg.health();
672
+ await pg.stats();
673
+ await pg.metrics();
674
+ const stopCleanup = pg.startCleanupWorker({ intervalMs: 60_000 });
675
+ ```
676
+
677
+ `batch()` 在 SQL 适配器支持 `begin()` 时会使用事务;`pipeline()` 是迁移时用于顺序分组 pgredis 操作的外观,不是 Redis 协议管道。
678
+
679
+ ```ts
680
+ const result = await pg.batch(async (tx) => {
681
+ await tx.cache.set("session:abc", { userId: 1 });
682
+ return tx.cache.get("session:abc");
683
+ });
684
+
685
+ const results = await pg.pipeline()
686
+ .set("counter-cache", 1)
687
+ .get("counter-cache")
688
+ .incr("daily:requests")
689
+ .exec();
690
+
691
+ await pg.redis.set("session:abc", { userId: 1 }, { PX: 60_000, NX: true });
692
+ await pg.redis.blpop("worker:list", 5);
693
+ ```
694
+
695
+ ### ioredis 和 node-redis 外观适配器
696
+
697
+ 如果现有代码需要 Redis client 形状的对象,可以使用 additive adapter
698
+ 子路径。它们暴露白名单内的高频 `ioredis` 小写方法和 node-redis camelCase
699
+ 方法,但仍然需要一个已有的 `PgredisClient`。
700
+
701
+ ```ts
702
+ import { createIoredisAdapter } from "@postgresx/noredis/adapters/ioredis";
703
+ import { createRedisJsAdapter } from "@postgresx/noredis/adapters/redis";
704
+
705
+ const ioredisLike = createIoredisAdapter({ client: pg });
706
+ const redisJsLike = createRedisJsAdapter({ client: pg });
707
+
708
+ await ioredisLike.set("cache:user:1", "Ada", "EX", 60, "NX");
709
+ await redisJsLike.hSet("profile:1", "name", "Ada");
710
+ ```
711
+
712
+ 这些外观适合 cache-manager 风格的 `get`/`set`/`del`/`mget`/`mset` 调用和简单 Pub/Sub 发布。
713
+ 它们不会创建 Redis TCP 连接,也不实现 `EVAL`/Lua、Cluster、Sentinel、`WATCH`、Redis Streams consumer group 或服务器管理命令。
714
+ 不支持的命令会抛出 `UnsupportedCommandError`。
715
+
716
+ 类型化原语也可以从明确的子路径导入:
717
+ `@postgresx/noredis/kv`、`hash`、`set`、`sorted-set`、`list` 和 `pubsub`。
718
+
719
+ 如果迁移时需要包名 alias,可以使用薄 re-export 包
720
+ `@postgresx/noredis-ioredis` 和 `@postgresx/noredis-redis`。它们仍然是
721
+ `PgredisClient` 之上的外观,不提供即插即用构造器。
722
+
723
+ ## Pub/Sub
724
+
725
+ 发布仅使用配置的 SQL 适配器。Bun LISTEN/NOTIFY 消费使用独立的 `@postgresx/bun-listen` 包,并动态加载。
726
+
727
+ ```bash
728
+ bun add @postgresx/bun-listen
729
+ ```
730
+
731
+ ```ts
732
+ import { createBunPgListener, publishPgNotify } from "@postgresx/noredis";
733
+
734
+ createBunPgListener(databaseUrl, ["cache_invalidate"], (_channel, payload) => {
735
+ console.log(payload);
736
+ });
737
+
738
+ await publishPgNotify(sql, "cache_invalidate", { key: "token:abc" });
739
+ ```
740
+
741
+ Node.js 可以使用适配器子路径中基于 `pg` 的监听器:
742
+
743
+ ```ts
744
+ import { createPgNodeListener } from "@postgresx/noredis/adapters/node";
745
+
746
+ createPgNodeListener(process.env.DATABASE_URL!, {
747
+ channels: ["cache_invalidate"],
748
+ onNotify(_channel, payload) {
749
+ console.log(payload);
750
+ }
751
+ });
752
+ ```
753
+
754
+ ## 持久化 outbox / stream
755
+
756
+ 当应用过去用 Redis Streams 做持久化事件日志或 worker inbox 时,可以使用 `PgOutboxStream`。它暴露 PostgreSQL outbox 语义,不模拟 Redis consumer group 协议。
757
+
758
+ ```ts
759
+ await pg.outbox.append("billing.events", { invoiceId: "inv_1" });
760
+
761
+ const messages = await pg.outbox.claim("billing.events", "worker-a", {
762
+ limit: 10,
763
+ visibilityTimeoutMs: 30_000
764
+ });
765
+
766
+ for (const message of messages) {
767
+ await deliver(message.payload);
768
+ await pg.outbox.ack([message.id]);
769
+ }
770
+ ```
771
+
772
+ 真实作业队列、重试和调度优先使用 `pg-boss` 队列适配器。列表 `blpop()` / `brpop()` 只适合简单 worker pull 的迁移桥接。
773
+
774
+ ## Web 适配器
775
+
776
+ `@postgresx/noredis/adapters/web` 不依赖 Express、Fastify 或 Elysia 运行时,只导出常见 session store 和 read-through cache helper 形状:
777
+
778
+ ```ts
779
+ import {
780
+ createElysiaSessionStore,
781
+ createPgredisCacheHelpers
782
+ } from "@postgresx/noredis/adapters/web";
783
+
784
+ const sessions = createElysiaSessionStore(pg.cache, {
785
+ prefix: "sess:",
786
+ ttlMs: 24 * 60 * 60 * 1000
787
+ });
788
+
789
+ const cache = createPgredisCacheHelpers(pg.cache, {
790
+ prefix: "http:",
791
+ ttlMs: 60_000
792
+ });
793
+ ```
794
+
795
+ ## 咨询锁
796
+
797
+ `withPgAdvisoryLock` 使用事务作用域锁,因此当事务结束时,PostgreSQL 会自动释放锁。
798
+
799
+ ```ts
800
+ import { withPgAdvisoryLock } from "@postgresx/noredis";
801
+
802
+ await withPgAdvisoryLock(sql, "billing:flush", async (tx) => {
803
+ await tx.unsafe("SELECT 1");
804
+ });
805
+ ```
806
+
807
+ ## 限流
808
+
809
+ ```ts
810
+ import { createPgFixedWindowRateLimiter } from "@postgresx/noredis";
811
+
812
+ const limiter = createPgFixedWindowRateLimiter({
813
+ sql,
814
+ namespace: "api",
815
+ limit: 60,
816
+ windowMs: 60_000
817
+ });
818
+
819
+ await limiter.ensureSchema();
820
+ const result = await limiter.hit("user:1");
821
+ ```
822
+
823
+ ## 队列
824
+
825
+ ```ts
826
+ import { createPgBossJobQueue } from "@postgresx/noredis";
827
+
828
+ const queue = createPgBossJobQueue({
829
+ connectionString: process.env.DATABASE_URL,
830
+ schema: "pgboss",
831
+ queues: {
832
+ "webhook.deliver": { retryLimit: 5, retryBackoff: true }
833
+ }
834
+ });
835
+
836
+ await queue.start();
837
+ await queue.send("webhook.deliver", { event: "created" });
838
+ await queue.work("webhook.deliver", { batchSize: 1 }, async (jobs) => {
839
+ for (const job of jobs) console.log(job.data);
840
+ });
841
+ ```
842
+
843
+ `pg-boss` 是动态加载的,不是 `@postgresx/noredis` 的运行时依赖。仅在使用队列功能时安装:
844
+
845
+ ```bash
846
+ npm install @postgresx/noredis pg-boss
847
+ ```
848
+
849
+ `@postgresx/noredis` 有意保持队列 API 与 `pg-boss` 接近:
850
+
851
+ - `start()` 启动 `pg-boss` 并创建配置的队列。
852
+ - `ensureQueue()` 创建或更新队列元数据。
853
+ - `send()` 将作业加入队列。
854
+ - `work()` 注册工作者。
855
+ - `getBoss()` 返回底层的 `PgBoss` 实例,用于高级场景。
856
+
857
+ 这涵盖了 Redis 支持的后台作业用例,如 Bull 风格的异步 webhook、计费刷新、重试和长任务。它不模拟 Redis Streams 命令。事件日志处理使用 `pg.outbox`,队列优先迁移使用 `pg.queue`。
858
+
859
+ ## 发布准备状态
860
+
861
+ 当前本地验证:
862
+
863
+ - `@postgresx/bun-listen` 和 `@postgresx/noredis` 的 `bun run build` 通过。
864
+ - `bun test packages/` 通过包测试套件。
865
+ - `bun run check` 通过 TypeScript 检查。
866
+
867
+ 生产环境或 1.0 发布前的剩余检查项:
868
+
869
+ | 领域 | 状态 | 重要性 | 建议操作 |
870
+ | --- | --- | --- | --- |
871
+ | 真实数据库覆盖 | CI 中已添加 | PostgreSQL DDL、索引、事务、JSONB 行为和 LISTEN/NOTIFY 重连行为需要真实数据库覆盖。 | CI 针对 PostgreSQL 16 运行 `bun run test:integration`。调试时使用 `TEST_DATABASE_URL` 本地运行。 |
872
+ | 基准测试基线 | 已生成 | `benchmark.md` 已由 GitHub Actions 生成,并区分主服务级对比和 L1 热读说明。 | benchmark 相关文件变化会自动刷新;本地基准测试运行是可选的。 |
873
+ | 安装冒烟测试 | CI 中已添加 | 构建输出存在,但已发布包的形状应从打包的 tarball 验证,包括子路径导出。 | CI 运行 `bun run smoke:pack` 从干净的 Node 和 Bun 入口点导入打包的 tarball。 |
874
+ | 发布凭证 | 在工作流中保护 | Release Please 和 npm publish 依赖仓库密钥和 npm provenance 设置。 | 当 `RELEASE_PAT` 或 `NPM_TOKEN` 缺失时,工作流会提前失败;首次发布前仍需验证包访问权限。 |
875
+ | 运行时操作 | 已文档化 | 清理、表增长、队列延迟和监听器健康是应用操作关注点。 | 请参阅 `docs/production-runbook.md` 了解清理、膨胀检查、监听器健康、队列监控和回滚指南。 |
876
+
877
+ 包在 CI 通过且 benchmark 基线保持可刷新后适合早期测试版。不应将其描述为 Redis 或 ioredis 的即插即用替代品。
878
+
879
+ ## ioredis 对比
880
+
881
+ `ioredis` 是 Redis 协议客户端。`pgredis` 是 PostgreSQL 原生工具包,
882
+ 在不使用 Redis 协议或支持每个 Redis 命令的情况下替换常见的 Redis 支持的应用原语。
883
+
884
+ | 能力 | ioredis | pgredis | 发布影响 |
885
+ | --- | --- | --- | --- |
886
+ | 协议和命令表面 | 发送 Redis 命令并支持任意 Redis 命令方法。 | 仅公开类型化的 PostgreSQL 支持的原语。 | 迁移需要代码更改。Redis 命令兼容性有意不在范围内。 |
887
+ | 运行时依赖 | 需要 Redis、Redis 兼容服务或 Redis Cluster/Sentinel。 | 需要 PostgreSQL;仅为选定功能可选安装 `pg`、`pg-boss` 或 `@postgresx/bun-listen`。 | 适合希望移除独立 Redis 层的团队。 |
888
+ | 字符串 / KV / TTL | 完整的 Redis 字符串命令表面。 | JSONB KV 缓存,支持 TTL、批量 get/set、前缀清除、可选本地 L1 缓存和通知失效。 | 覆盖缓存/会话样式的值,但不支持字节字符串命令如 `APPEND`、`GETRANGE` 或 `SETRANGE`。 |
889
+ | 哈希、列表、集合、有序集合 | 原生 Redis 数据结构和命令覆盖。 | PostgreSQL 表支持的常见 hash/list/set/zset 操作辅助函数。 | 覆盖常见应用用法;高级/阻塞/列表突变和完整命令对等性不完整。 |
890
+ | Pub/Sub | Redis Pub/Sub、模式订阅、二进制消息、集群行为。 | PostgreSQL `LISTEN/NOTIFY` 发布者和 Node/Bun 监听器。 | 适用于轻量级失效/事件;不持久且受 PostgreSQL NOTIFY 有效负载大小限制。 |
891
+ | 流 / 消费者组 | Redis Streams 命令如 `XADD` 和消费者组。 | 持久化 outbox/stream 辅助函数加 `pg-boss` 队列适配器。 | 无 Redis consumer-group 协议或 pending-entry-list 兼容。 |
892
+ | 管道 / 事务 | `pipeline`、`multi`、`exec` 和集群感知行为。 | `batch()` 使用 SQL 适配器事务;`pipeline()` 执行有序 pgredis 操作。 | 无 Redis wire-level 管道或 `WATCH` 语义。 |
893
+ | Lua 脚本 / Redis Functions | 支持脚本命令和自定义命令定义。 | 不在范围内;使用 SQL、存储过程或应用代码。 | 不要直接移植 Lua;重写为 SQL/应用逻辑。 |
894
+ | 集群 / Sentinel / NAT 映射 | 内置在 ioredis 中。 | 继承自 PostgreSQL HA、池化和网络。 | 记录 PostgreSQL 部署假设而非 Redis HA 选项。 |
895
+ | TLS / ACL / 认证 | Redis 连接、TLS 和 ACL 选项。 | 委托给 PostgreSQL 驱动、DSN 和数据库角色。 | 使用 PostgreSQL 凭据和传输设置。 |
896
+ | Redis Stack 模块 | 可以发送模块命令,取决于 Redis 服务器支持。 | 无 RedisJSON、RediSearch、RedisTimeSeries、RedisBloom 外观。 | 首选 PostgreSQL JSONB、全文搜索、pgvector、PostGIS 或扩展。 |
897
+ | 离线队列 / 重连策略 | 客户端级离线队列、重试、就绪检查、自动重新订阅。 | Node/Bun 监听器包括重连和健康状态;SQL 操作取决于数据库适配器/池行为。 | 添加操作级重试指南和适配器冒烟测试。 |
898
+
899
+ ## Redis 功能覆盖
900
+
901
+ Redis 在核心数据类型、服务器操作、可编程性、集群、模块和可观测性方面具有广泛的表面。`pgredis` 目标是功能替代,而非命令兼容性。
902
+
903
+ | Redis 能力 | pgredis 状态 | 替代策略 | 差距 |
904
+ | --- | --- | --- | --- |
905
+ | 字符串 `GET`/`SET`/`DEL`/TTL | 已覆盖 | `PgKvCache` 存储 JSONB 值,支持可选 TTL 和 L1 缓存 | 无字节级 Redis 字符串操作如 `APPEND`、`GETRANGE`、`SETRANGE` |
906
+ | 键过期 | 已覆盖 | `expires_at`、`cleanupExpired`、L1 TTL | 无 Redis 被动/主动驱逐语义或键空间通知 |
907
+ | 批量 get/set | 已覆盖 | `mget`、`mset`、`batch()` 和 `pipeline()` | Pipeline 分组 pgredis 操作,不是 Redis 协议管道 |
908
+ | 原子计数器 | 已覆盖 | `PgCounter` 基于 BIGINT UPSERT | 仅整数计数器 |
909
+ | Pub/Sub | 已覆盖 | `LISTEN/NOTIFY` 加上 `createPgListener` | 不持久,有效负载大小受 PostgreSQL NOTIFY 限制 |
910
+ | 分布式锁 | 已覆盖 | 事务作用域咨询锁 | 无 Redlock 兼容的租约续期模型 |
911
+ | 固定窗口限流 | 已覆盖 | UPSERT 计数器表,带窗口重置元数据 | 适用于粗粒度窗口 |
912
+ | 滑动窗口限流 | 已覆盖 | 分桶移动窗口计数器 | 精度取决于配置的桶大小 |
913
+ | 令牌桶限流 | 已覆盖 | PostgreSQL 行状态,带补充计算 | 设计用于应用级 API 限流 |
914
+ | 队列 / 延迟作业 / 重试 | 通过适配器覆盖 | `pg-boss` 包装器 | 不兼容 Redis Streams |
915
+ | 哈希 | 已覆盖 | `PgHash` 基于 `(namespace, key, field)` 行 | 覆盖 `HSCAN` 风格游标扫描和键 TTL;无字段级 TTL |
916
+ | 列表 | 已覆盖 | `PgList` 基于有序行 | 覆盖游标扫描、键 TTL 和轮询式 `blpop`/`brpop`;真实作业队列使用 pg-boss |
917
+ | 集合 | 已覆盖 | `PgSet` 基于唯一索引行 | 覆盖 `SINTER`、`SUNION`、`SDIFF`、`SPOP`、`SRANDMEMBER`、`SMOVE`、游标扫描和键 TTL |
918
+ | 有序集合 | 已覆盖 | `PgSortedSet` 基于 `(member, score)` 行 | 覆盖排名、分数范围、计数、递增、弹出最小/最大值、扫描和键 TTL |
919
+ | 流 / 消费者组 | 部分覆盖 | 使用 `PgOutboxStream` 处理事件日志,使用 `pg-boss` 处理作业 | 无 Redis `XREADGROUP` 或待处理条目列表兼容 |
920
+ | 事务 / 乐观锁 | 部分覆盖 | 使用 `batch()` 处理适配器事务;乐观流程直接使用 PostgreSQL 行锁 | 无 Redis `WATCH` 外观 |
921
+ | Lua 脚本 / 函数 | 不在范围内 | 使用 SQL、存储过程或应用代码 | 无 Redis Lua/函数运行时 |
922
+ | 位图 / 位域 | 缺失 | 使用 `bytea`、roaring bitmap 扩展或 SQL 表 | 无位操作 API |
923
+ | HyperLogLog | 缺失 | 使用 PostgreSQL 扩展或近似计数表 | 无 `PFADD`/`PFCOUNT` |
924
+ | 地理空间 | 缺失 | 使用 PostGIS | 无 Redis GEO 命令外观 |
925
+ | JSON 文档命令 | 部分 | KV 值为 JSONB | 无 RedisJSON 路径突变/查询 API |
926
+ | 搜索 / 向量搜索 | 缺失 | 使用 PostgreSQL 全文搜索、`pg_trgm`、`pgvector` | 无 RediSearch 兼容查询 API |
927
+ | 时间序列 | 缺失 | 使用 hypertables/分区表/TimescaleDB | 无 RedisTimeSeries API |
928
+ | Bloom / Cuckoo / Count-Min | 缺失 | 使用 PostgreSQL 扩展或应用表 | 无 RedisBloom 兼容 API |
929
+ | ACL/认证 | 不在范围内 | 使用 PostgreSQL 凭据和应用认证 | 无 Redis ACL 外观 |
930
+ | 持久化/复制/集群 | 不在范围内 | 继承自 PostgreSQL 部署 | 无 Redis Cluster 槽/哈希语义 |
931
+ | 服务器内省 | 部分 | `createPgredis().health()`、`stats()` 和 `metrics()` 暴露健康、清理、表大小、TTL backlog、listener 和队列视图 | 无 Redis `INFO`、`MONITOR`、命令统计外观 |
932
+
933
+ ## 已完成的迁移功能
934
+
935
+ 所有最初规划的高价值 Redis 迁移功能已有第一版 API 和测试:
936
+
937
+ 1. ~~PostgreSQL 集成测试和 tarball 安装冒烟测试~~ — CI 运行 `test:integration` 和 `smoke:pack`。
938
+ 2. ~~`batch()` 和 `pipeline()` 分组外观~~ — `batch()` 使用 SQL 事务;`pipeline()` 执行有序操作;包含 `multi()` 别名。
939
+ 3. ~~持久化 outbox/stream API~~ — `PgOutboxStream` 提供 `append`、`claim`、`ack`,用于事件日志迁移。
940
+ 4. ~~轮询式 `blpop()` / `brpop()` 列表辅助函数~~ — 加上 `pg-boss` 队列适配器用于真实作业队列。
941
+ 5. ~~生产指标~~ — `health()`、`stats()`、`metrics()` 暴露表大小、清理计数、TTL 积压、监听器和队列状态。
942
+ 6. ~~Redis 风格别名~~ — `pg.redis.*` 覆盖 KV、哈希、列表、集合、有序集合、pub/sub、计数器、扫描、TTL 和连接生命周期。
943
+ 7. ~~框架中立 Web 适配器~~ — `@postgresx/noredis/adapters/web` 下的会话存储和缓存辅助函数。
944
+ 8. ~~KV 条件写入~~ — `NX`/`XX`、比较并交换、`touch`、`expire`、`persist`、可插拔序列化和可选 L1 缓存。
945
+ 9. ~~ioredis 和 node-redis 外观~~ — `@postgresx/noredis/adapters/ioredis` 和 `@postgresx/noredis/adapters/redis`,带白名单方法表面。
946
+ 10. ~~子模块入口~~ — `kv`、`hash`、`set`、`sorted-set`、`list`、`pubsub` 子路径导出类型化原语。
947
+
948
+ 后续迁移文档和 benchmark 候选项记录在
949
+ [仓库迁移示例](https://github.com/zuohuadong/postgresx/blob/main/docs/redis-migration-examples.md) 中:
950
+ Redis Streams consumer-group 迁移、session middleware 示例、SQL adapter
951
+ retry/backoff 边界、outbox/list/pipeline benchmark,以及明确非目标。
952
+
953
+ ## 设计说明
954
+
955
+ 这是一个工具包,不是 Redis 兼容客户端。它有意公开 PostgreSQL 友好的语义:
956
+
957
+ - 锁是事务作用域的咨询锁
958
+ - pub/sub 是 `LISTEN/NOTIFY`,不是持久消息传递
959
+ - 队列委托给 `pg-boss`
960
+ - KV 值是 JSONB 行,支持可选本地 L1 缓存