From 417f14dc3a0fbac87c6c5616319de6a9bc124cdf Mon Sep 17 00:00:00 2001 From: Gautam K Date: Wed, 4 Nov 2026 17:41:45 +0530 Subject: [PATCH] feat: add Postgres bus driver Add postgresBusDriver, a bus driver that uses Postgres LISTEN/NOTIFY, exported from bentocache/drivers/postgres. pg and @types/pg are optional peer dependencies. - Opens two connections from one connection string, a listener and a publisher. Either is replaced on its own when it fails. It creates no table or other database object. - Sends each batch in one transaction and one round trip, with synchronous_commit off. Messages published while a transaction runs go in the next one, merged by channel, type and namespace with duplicate keys removed. batchDelay (default 0) trades write latency for fewer transactions. - Splits large messages across notifications and transactions. A key too long for a notification becomes a clear of its namespace and is reported to onError. - An end-to-end heartbeat (every 30s by default) replaces a listener that silently stops receiving notifications. Time the process was frozen doesn't count against it. Its error links to the docs on the usual causes. - Errors go to onError. Without it, they are logged with console.error, each distinct message at most once a minute. - Destroys the socket of a connection a stalled server doesn't close, so it can't keep the process alive. Names its sessions bentocache-bus:listener and :publisher unless an application name is set. - At startup, publishes wait for the first connection. Later, they fail fast while the publisher is down, so the bus keeps them in its retry queue. disconnect() sends pending messages first. - Versioned ASCII wire format whose fields are only appended. Channel names that are too long or not ASCII are mapped to a hash. - Turns off idle_session_timeout on the listener with a plain SET, which poolers such as PgDog keep to that client. --- .changeset/postgres-bus-driver.md | 5 + README.md | 2 +- docs/content/docs/multi_tier.md | 121 ++ packages/bentocache/README.md | 2 +- packages/bentocache/package.json | 12 +- .../src/bus/transports/postgres/channel.ts | 58 + .../src/bus/transports/postgres/encoder.ts | 166 +++ .../transports/postgres/postgres_transport.ts | 1014 ++++++++++++++ packages/bentocache/src/drivers/postgres.ts | 92 ++ .../src/types/options/drivers_options.ts | 62 + .../bentocache/tests/bus/postgres_bus.spec.ts | 1205 +++++++++++++++++ .../tests/bus/postgres_encoding.spec.ts | 247 ++++ 12 files changed, 2983 insertions(+), 3 deletions(-) create mode 100644 .changeset/postgres-bus-driver.md create mode 100644 packages/bentocache/src/bus/transports/postgres/channel.ts create mode 100644 packages/bentocache/src/bus/transports/postgres/encoder.ts create mode 100644 packages/bentocache/src/bus/transports/postgres/postgres_transport.ts create mode 100644 packages/bentocache/src/drivers/postgres.ts create mode 100644 packages/bentocache/tests/bus/postgres_bus.spec.ts create mode 100644 packages/bentocache/tests/bus/postgres_encoding.spec.ts diff --git a/.changeset/postgres-bus-driver.md b/.changeset/postgres-bus-driver.md new file mode 100644 index 0000000..3da0cfe --- /dev/null +++ b/.changeset/postgres-bus-driver.md @@ -0,0 +1,5 @@ +--- +'bentocache': minor +--- + +Add `postgresBusDriver`, a bus driver that uses Postgres `LISTEN/NOTIFY`. Import it from `bentocache/drivers/postgres`. It needs the `pg` package. diff --git a/README.md b/README.md index 599c776..9346846 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ For those looking to go further, you can use the two-levels caching system. Here - **L1: Local Cache**: First level cache. Data is stored in memory with an LRU algorithm for quick access - **L2: Distributed Cache**: If the data is not in the in-memory cache, it is searched in the distributed cache (Redis, for example) -- **Synchronization via Bus**: In a multi-instance context, you can synchronize different local in-memory caches of your instances via a Bus like Redis or RabbitMQ. This method maintains cache integrity across multiple instances +- **Synchronization via Bus**: In a multi-instance context, you can synchronize different local in-memory caches of your instances via a Bus like Redis or Postgres. This method maintains cache integrity across multiple instances Here is a simplified diagram of the flow : diff --git a/docs/content/docs/multi_tier.md b/docs/content/docs/multi_tier.md index 3888da4..5d3f335 100644 --- a/docs/content/docs/multi_tier.md +++ b/docs/content/docs/multi_tier.md @@ -97,3 +97,124 @@ redisBusDriver({ ``` `maxSize` is the maximum number of items that can be stored in the retry queue. If the queue is full, the oldest item will be dropped. If `undefined`, the queue will have no limit. + +### Postgres bus + +If you already run Postgres, you can use it as the bus instead of Redis. `postgresBusDriver` uses Postgres `LISTEN/NOTIFY`. Combined with an in-memory L1 and, optionally, a [database L2](./cache_drivers.md), it lets you run a multi-tier cache without Redis. + +Install the `pg` package first: + +```sh +npm i pg +``` + +With TypeScript, also install `@types/pg`. + +```ts +import { BentoCache, bentostore } from 'bentocache' +import { memoryDriver } from 'bentocache/drivers/memory' +import { postgresBusDriver } from 'bentocache/drivers/postgres' + +const bento = new BentoCache({ + default: 'cache', + stores: { + cache: bentostore() + .useL1Layer(memoryDriver({ maxSize: '10mb' })) + .useBus(postgresBusDriver({ connection: process.env.DATABASE_URL! })), + }, +}) +``` + +`connection` takes a connection string or a [`pg` client config](https://node-postgres.com/apis/client). From it, the driver opens two connections per store and per process: one that listens and one that publishes. It doesn't create any table or other database object. + +All your instances must connect to the same database: Postgres delivers notifications only within a database. + +#### Options + +| Option | Default | Description | +| ---------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `connection` | | Connection string or `pg` client config. Required. | +| `publishTimeout` | `'2s'` | Maximum time for one publish transaction, which carries up to 1,000 notifications or 1 MB. A publish that takes longer fails and goes to the [retry queue](#retry-queue-strategy). | +| `batchDelay` | `0` | Extra time the driver waits after a message before sending it, so that more messages share one transaction. Every write (`set`, `delete`, `clear`...) waits for its publish, so a delay adds to write latency in exchange for fewer Postgres transactions. | +| `heartbeat` | `{ interval: '30s', timeout: '15s' }` | Every `interval`, the driver publishes a message to itself. If a heartbeat was committed but not received within `timeout`, the listening connection is replaced. Set to `false` to disable. See [Heartbeat](#heartbeat). | +| `onError` | | Called with connection errors, failed publishes and dropped messages, for logging. The driver reconnects on its own. Without it, errors are logged with `console.error`, each distinct message at most once a minute. | +| `retryQueue` | | Same as for `redisBusDriver`. | + +#### What the connection must support + +The connection must reach the primary, directly or through a proxy, and `LISTEN` must work on it: + +- A direct connection to Postgres, or a TCP proxy such as HAProxy that routes to the primary, works. +- PgBouncer works in session mode. In transaction mode, `LISTEN` doesn't work. +- Other poolers work if they support `LISTEN/NOTIFY` in the mode you use. PgDog, for example, needs its pub/sub support enabled in transaction mode. + +Many hosting providers show a pooled connection string in transaction mode by default. Use a direct or session-mode one instead: + +- Supabase: the direct connection, or the session pooler on port 5432. Not the transaction pooler on port 6543. +- Neon: the hostname without `-pooler`. +- DigitalOcean: the database cluster itself, not a connection pool in transaction mode. +- Azure Database for PostgreSQL: port 5432. The built-in PgBouncer on port 6432 works only if its pool mode is `session`. + +If `LISTEN` doesn't work on the connection, the heartbeat fails and the driver reports it every time it reconnects. See [If the heartbeat fails](#if-the-heartbeat-fails). + +If a proxy closes idle connections, such as HAProxy with its `timeout client` and `timeout server` settings, keep `heartbeat.interval` below that timeout. The heartbeat is what keeps both connections active. The same applies to the database's `idle_session_timeout`, if you set one: the publishing connection keeps it, and is replaced if it is closed. + +Don't use the Postgres bus where processes are frozen between requests, such as AWS Lambda. A frozen process reads no notifications, so its L1 keeps old values, and its listening session holds back the server's notification queue (see below). + +#### How it behaves + +- Messages are sent in short transactions, each in one round trip, with `synchronous_commit` turned off for that transaction. Every such transaction uses a transaction id, writes to the WAL, takes a lock shared by the whole Postgres cluster and wakes every listening connection, so the driver sends as few as it can: + - A message is sent as soon as no transaction is running. Messages published while one runs are sent together in the next. With a `batchDelay`, a batch also waits that long after its first message, unless it already holds 1,000 messages. + - Messages in a batch with the same type and namespace are merged into one notification, with duplicate keys removed. Other instances can therefore see fewer `bus:message:received` events than were published, and messages of different types or namespaces can arrive in a different order. The caches end up the same, because every message only deletes or expires entries. + - A very large batch is split over several transactions. +- BentoCache waits for the publish in every write, so each `set`, `delete` or `clear` takes at least one round trip to the primary, plus `batchDelay`. +- Right after start, publishes wait for the first connection, up to `publishTimeout`. Later, while the publishing connection is down, publishes fail right away and go to the retry queue. They are sent as soon as the connection is back. The retry queue resends one message at a time, each in its own transaction. +- `disconnect()` first sends the messages still waiting, within `publishTimeout`. +- Postgres limits a notification to 8000 bytes. Messages with many keys are split across several notifications. If a single key doesn't fit, or a key isn't a string, the driver sends a `clear` of the key's namespace instead and reports it to `onError`. This only keeps other instances from serving stale entries: only key names are sent, never values, so it takes a key name of about 8 KB, which is very unlikely. +- Messages sent while an instance's listening connection is down, including right after start before it is ready, are lost for that instance. Its L1 can then keep old values until they expire, so use a TTL you can accept as the worst case for stale reads from L1. +- Each store uses its own channel, named after the store. Two applications that share a database and use the same store name receive each other's messages, and delete each other's L1 entries with the same keys. Give them different store names. +- If you connect through PgDog, it forwards notifications through a buffer of `pub_sub_channel_size` entries and drops them, without an error, for a client that falls more than that many behind. The load to size for is notifications per second times the number of app instances behind one PgDog. Merging keeps that number low, but check PgDog's `SHOW LISTENERS` for a non-zero `dropped` column under your peak load. + +#### Heartbeat + +The listening connection only receives, so it can't always tell when it stops working: + +- A pooler in transaction mode accepts `LISTEN` but never delivers anything. +- A load balancer, NAT gateway or firewall can drop an idle connection without telling either end. +- If the database host goes away or the network is cut, nothing tells the client until it sends something. + +In these cases the connection stays open while notifications are lost, and the instance's L1 keeps old values until they expire. So every `interval` (30 s by default), the driver sends a notification to itself. If one isn't received within `timeout` (15 s by default), the driver replaces the listening connection and reports an error. A silent failure is detected within `interval` + `timeout` + `timeout` / 3, about 50 s with the defaults. + +The heartbeat also keeps both connections active, so a proxy that closes idle connections after longer than `interval` leaves them open. + +Each heartbeat is a small publish transaction. While messages are being published, it goes in one of their transactions. With no traffic, each store in each process sends one every `interval`, which is 2,880 transactions a day at the default. Every one of them wakes every listening session in the database, so with 100 processes the database handles about 3 heartbeat transactions and 330 wakeups per second. With many processes, a longer `interval` lowers this. + +##### If the heartbeat fails + +The error `Postgres bus listener did not receive a heartbeat` means that a heartbeat was committed, but the listening connection didn't receive it in time. The driver replaces the connection on its own. Once, for example during a failover, it needs no action. If it repeats, check for: + +- **A pooler in transaction mode.** `LISTEN` appears to work, but nothing is delivered. Use a direct or session-mode connection, see [What the connection must support](#what-the-connection-must-support). +- **Connections that reach different servers.** Notifications are delivered only within one server. Both connections must reach the same primary, which a proxy that spreads new connections over several nodes doesn't guarantee. +- **Something closing idle connections.** A proxy, load balancer or firewall with an idle timeout shorter than `heartbeat.interval`. Lower the interval below that timeout, or raise the timeout. +- **An unstable network.** The driver recovers each time, but messages are lost for that instance while it reconnects. +- **An overloaded process.** If the process can't read from its connection for longer than `timeout`, the heartbeat arrives too late. Time the process was completely frozen, such as a long garbage collection, is not counted. Raise `timeout` if your process is often busy for that long. + +##### Turning the heartbeat off + +`heartbeat: false` is safe only if both of these hold: + +- The app connects to Postgres directly, with no pooler, proxy, load balancer or NAT between them, for example on the same host. +- You accept that, if a connection silently stops working, the instance's L1 may serve old values until they expire, with no error. A short L1 TTL limits how long. + +Without the heartbeat, the driver still reconnects whenever a connection reports an error or is closed. That covers server restarts, terminated sessions and most failovers. A connection that is silently dropped is found only by TCP keepalive, which the driver turns on, but which with operating system defaults can take hours. The `pg` option `keepAliveInitialDelayMillis` shortens it. + +#### Effect on the rest of your database + +The bus shares the database with your application. It changes nothing outside its own sessions, but its transactions cost the whole server something: + +- **Connections:** each store with a Postgres bus uses two connections per process. Count them when you size `max_connections` or your pooler. +- **Transaction ids:** every publish transaction uses a transaction id and writes a small WAL record that is replicated. At 1,000 transactions per second that is 86.4 million ids a day, so anti-wraparound vacuums of your tables come sooner (they start at `autovacuum_freeze_max_age`, 200 million by default). A `batchDelay` lowers the count. With no traffic, the [heartbeat](#heartbeat) still uses one every `interval` per store and process, so the database is never fully idle. +- **Notification lock:** Postgres runs commits that send notifications one at a time, using a lock shared by all databases on the server. Your other queries and transactions don't take it, but any other application on the same server that uses `NOTIFY` competes with the bus for it. The driver turns off `synchronous_commit` for its transactions to hold the lock briefly. +- **Notification queue:** notifications wait in a queue shared by all databases on the server (8 GB by default) until every listening session has read them. A listening session that stops reading, such as a frozen process or a session left inside a long transaction, holds the queue back. If it fills up, every `NOTIFY` on the server fails at commit. The driver's listener never opens a transaction, and the heartbeat replaces a listener that stops receiving while its process still runs. +- **Other listeners:** each commit wakes the sessions that listen in the same database, including your application's own listeners on other channels. +- **Session settings:** the driver changes only its own sessions. It sets `synchronous_commit = off` inside each publish transaction, and turns off `idle_session_timeout` (Postgres 14 and later) on its listening connection, since that connection is idle by design. It does so even when no timeout is set, so a timeout enabled later by a config reload doesn't close the listener. It uses a plain `SET`, which poolers such as PgDog keep to that client. It doesn't change `pg` defaults, type parsers or the config object you pass. diff --git a/packages/bentocache/README.md b/packages/bentocache/README.md index 1b8a1c4..4ec296f 100644 --- a/packages/bentocache/README.md +++ b/packages/bentocache/README.md @@ -48,7 +48,7 @@ For those looking to go further, you can use the two-levels caching system. Here - **L1: Local Cache**: First level cache. Data is stored in memory with an LRU algorithm for quick access - **L2: Distributed Cache**: If the data is not in the in-memory cache, it is searched in the distributed cache (Redis, for example) -- **Synchronization via Bus**: In a multi-instance context, you can synchronize different local in-memory caches of your instances via a Bus like Redis or RabbitMQ. This method maintains cache integrity across multiple instances +- **Synchronization via Bus**: In a multi-instance context, you can synchronize different local in-memory caches of your instances via a Bus like Redis or Postgres. This method maintains cache integrity across multiple instances Here is a simplified diagram of the flow : diff --git a/packages/bentocache/package.json b/packages/bentocache/package.json index 6652338..c1aedd4 100644 --- a/packages/bentocache/package.json +++ b/packages/bentocache/package.json @@ -7,6 +7,7 @@ "caching", "in-memory", "multi-tier", + "postgres", "redis", "tiered" ], @@ -39,6 +40,7 @@ "exports": { ".": "./build/index.js", "./drivers/redis": "./build/src/drivers/redis.js", + "./drivers/postgres": "./build/src/drivers/postgres.js", "./drivers/memory": "./build/src/drivers/memory.js", "./drivers/file": "./build/src/drivers/file/file.js", "./drivers/dynamodb": "./build/src/drivers/dynamodb.js", @@ -99,10 +101,12 @@ }, "peerDependencies": { "@aws-sdk/client-dynamodb": "^3.438.0", + "@types/pg": "^8.0.0", "ioredis": "^5.3.2 || ^6.0.0", "knex": "^3.0.1", "kysely": "^0.27.3", - "orchid-orm": "^1.24.0" + "orchid-orm": "^1.24.0", + "pg": "^8.0.3" }, "peerDependenciesMeta": { "@aws-sdk/client-dynamodb": { @@ -119,6 +123,12 @@ }, "orchid-orm": { "optional": true + }, + "pg": { + "optional": true + }, + "@types/pg": { + "optional": true } }, "c8": { diff --git a/packages/bentocache/src/bus/transports/postgres/channel.ts b/packages/bentocache/src/bus/transports/postgres/channel.ts new file mode 100644 index 0000000..b27f81a --- /dev/null +++ b/packages/bentocache/src/bus/transports/postgres/channel.ts @@ -0,0 +1,58 @@ +import { createHash } from 'node:crypto' + +/** + * Postgres truncates identifiers to 63 bytes (NAMEDATALEN - 1) and + * `pg_notify()` rejects longer channel names. + */ +export const MAX_CHANNEL_BYTES = 63 + +const HASH_HEX_LENGTH = 16 +const MAX_PREFIX_LENGTH = MAX_CHANNEL_BYTES - HASH_HEX_LENGTH - 1 + +/** + * Printable ASCII. Anything else may not exist in the database encoding: + * a LATIN1 database rejects a channel name with Cyrillic or CJK + * characters, for example. + */ +const PRINTABLE_ASCII = /^[\x20-\x7e]*$/ + +/** + * Map a bus channel name to a Postgres channel name, which is always + * printable ASCII of at most 63 bytes whatever the database encoding is. + * + * Non-empty printable ASCII names up to 63 bytes are used as is. Any other name is + * turned into a prefix, where each character outside printable ASCII is + * replaced by `_`, cut to 46 characters and suffixed with `~` and the + * first 16 hex characters of the sha256 of the full name in UTF-8. The + * hash keeps names that share a prefix distinct. + * + * Every instance must compute the same name for the same channel, so this + * mapping is part of the wire format and must not change. + */ +export function toPostgresChannel(name: string): string { + /** + * Postgres rejects an empty channel name, so it is hashed like the others + */ + if (name.length > 0 && name.length <= MAX_CHANNEL_BYTES && PRINTABLE_ASCII.test(name)) { + return name + } + + const hash = createHash('sha256').update(name, 'utf8').digest('hex').slice(0, HASH_HEX_LENGTH) + + let prefix = '' + for (const char of name) { + if (prefix.length === MAX_PREFIX_LENGTH) break + prefix += PRINTABLE_ASCII.test(char) ? char : '_' + } + + return `${prefix}~${hash}` +} + +/** + * Quote a channel name for `LISTEN` / `UNLISTEN`, which don't accept + * bind parameters. Quoting also keeps the name case-sensitive, which + * matches how `pg_notify()` treats its channel argument. + */ +export function quoteChannel(channel: string): string { + return `"${channel.replace(/"/g, '""')}"` +} diff --git a/packages/bentocache/src/bus/transports/postgres/encoder.ts b/packages/bentocache/src/bus/transports/postgres/encoder.ts new file mode 100644 index 0000000..036d31c --- /dev/null +++ b/packages/bentocache/src/bus/transports/postgres/encoder.ts @@ -0,0 +1,166 @@ +import { CacheBusMessageType } from '../../../types/bus.js' +import type { CacheBusMessage } from '../../../types/bus.js' + +/** + * Wire format of a notification payload, as a JSON array: + * + * [version, busId, typeCode, namespace, keys] + * + * e.g. `[1,"k3x9q2m7p1z8w4n6b5v0c2ds",1,"bentocache",["user:42"]]` + * + * - Type codes match the binary encoder used by the Redis bus. + * - Characters outside ASCII are escaped as `\uXXXX`, so the payload is + * plain ASCII whatever the database encoding is, and its length in + * characters is its length in bytes. + * + * Compatibility rules, so that instances running different releases can + * share a channel during a rolling deploy: + * + * - New fields are only ever appended. Decoders ignore elements after the + * ones they know, so older instances still apply the invalidation. + * - Decoders silently ignore unknown type codes, so new kinds of messages + * can share the channel without older instances reporting errors. + * - The version changes only for a change that older decoders cannot + * safely ignore. Older decoders drop payloads with another version, so + * such a change needs two steps: first release decoders that accept both + * versions, then switch encoders to the new one. + */ +export const WIRE_VERSION = 1 + +/** + * Postgres rejects payloads of 8000 bytes or more + * (`NOTIFY_PAYLOAD_MAX_LENGTH` with the default 8 kB block size). + */ +export const MAX_PAYLOAD_BYTES = 7999 + +const TYPE_TO_CODE: Record = { + [CacheBusMessageType.Set]: 1, + [CacheBusMessageType.Clear]: 2, + [CacheBusMessageType.Delete]: 3, + [CacheBusMessageType.Expire]: 4, +} + +const CODE_TO_TYPE: Record = { + 1: CacheBusMessageType.Set, + 2: CacheBusMessageType.Clear, + 3: CacheBusMessageType.Delete, + 4: CacheBusMessageType.Expire, +} + +export type EncodeResult = { + /** + * Payloads to send, each under the size limit. Empty only when + * `tooLarge` is true. + */ + payloads: string[] + + /** + * True when a single key couldn't fit in one payload, so the message + * was replaced by a `clear` of its namespace + */ + replacedByClear: boolean + + /** + * True when not even a `clear` of the namespace fits, so nothing can + * be sent + */ + tooLarge: boolean +} + +function toAsciiJson(value: unknown): string { + return JSON.stringify(value).replace( + /** + * JSON.stringify already escaped control characters, so this matches + * every UTF-16 code unit from 0x7f up. Surrogate pairs become two escapes. + */ + /[^\x20-\x7e]/g, + char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`, + ) +} + +/** + * Encode a cache bus message into one or more notification payloads. + * + * Keys are split across several payloads when they don't fit in one. + * If a single key is too large for any payload, the message is replaced + * by a `clear` of its namespace. That clears more than needed, but it + * never leaves another instance with a stale entry. + */ +export function encodeMessage( + busId: string, + message: CacheBusMessage, + maxBytes = MAX_PAYLOAD_BYTES, +): EncodeResult { + const code = TYPE_TO_CODE[message.type] + if (code === undefined) throw new TypeError(`Unknown bus message type: ${message.type}`) + + const prefix = `[${WIRE_VERSION},${toAsciiJson(busId)},` + const namespace = toAsciiJson(message.namespace ?? '') + const head = `${prefix}${code},${namespace},[` + const tail = ']]' + const room = maxBytes - head.length - tail.length + + const clear = (): EncodeResult => { + const payload = `${prefix}${TYPE_TO_CODE[CacheBusMessageType.Clear]},${namespace},[]]` + if (payload.length > maxBytes) return { payloads: [], replacedByClear: false, tooLarge: true } + return { + payloads: [payload], + replacedByClear: message.type !== CacheBusMessageType.Clear, + tooLarge: false, + } + } + + if (room < 0) return clear() + + const keys = message.keys ?? [] + if (keys.length === 0) return { payloads: [head + tail], replacedByClear: false, tooLarge: false } + + const payloads: string[] = [] + let current: string[] = [] + let used = 0 + + for (const key of keys) { + const encoded = toAsciiJson(key) + if (encoded.length > room) return clear() + + const added = (current.length > 0 ? 1 : 0) + encoded.length + if (used + added > room) { + payloads.push(head + current.join(',') + tail) + current = [encoded] + used = encoded.length + continue + } + + current.push(encoded) + used += added + } + + payloads.push(head + current.join(',') + tail) + return { payloads, replacedByClear: false, tooLarge: false } +} + +/** + * Decode a notification payload. Returns `undefined` for anything that + * isn't a valid payload of this wire format version. + */ +export function decodeMessage( + payload: string, +): { busId: string; payload: CacheBusMessage } | undefined { + let data: unknown + try { + data = JSON.parse(payload) + } catch { + return + } + + if (!Array.isArray(data) || data[0] !== WIRE_VERSION) return + + const [, busId, code, namespace, keys] = data + if (typeof busId !== 'string' || typeof namespace !== 'string' || typeof code !== 'number') return + if (!Array.isArray(keys) || !keys.every(key => typeof key === 'string')) return + + const type = CODE_TO_TYPE[code] + if (!type) return + + return { busId, payload: { type, namespace, keys } } +} diff --git a/packages/bentocache/src/bus/transports/postgres/postgres_transport.ts b/packages/bentocache/src/bus/transports/postgres/postgres_transport.ts new file mode 100644 index 0000000..812602b --- /dev/null +++ b/packages/bentocache/src/bus/transports/postgres/postgres_transport.ts @@ -0,0 +1,1014 @@ +import pg from 'pg' +import { randomBytes } from 'node:crypto' +import type { Serializable, SubscribeHandler, Transport } from '@boringnode/bus/types/core' + +import { decodeMessage, encodeMessage } from './encoder.js' +import { CacheBusMessageType } from '../../../types/bus.js' +import type { CacheBusMessage } from '../../../types/bus.js' +import { quoteChannel, toPostgresChannel } from './channel.js' + +export type PostgresTransportOptions = { + /** + * Connection string or `pg` client config. Both internal + * connections are opened from it. + */ + connection: string | pg.ClientConfig + + /** + * Maximum time in milliseconds for one publish transaction + */ + publishTimeout: number + + /** + * How long in milliseconds the publisher waits after the first message + * of a batch before sending it, so more messages share the transaction. + * 0 sends as soon as no transaction is running. + */ + batchDelay: number + + /** + * Heartbeat settings in milliseconds, or false to disable the heartbeat + */ + heartbeat: false | { interval: number; timeout: number } + + /** + * Called with connection and publish errors + */ + onError?: (error: Error) => void +} + +export type Notification = [channel: string, payload: string] + +export type QueuedPublish = { + notifications: Notification[] + + /** + * How many of `notifications` were already taken into a transaction + */ + sent: number + + resolve: () => void + reject: (error: Error) => void +} + +/** + * Messages published since the last flush that can be sent as one: same + * channel, type and namespace + */ +type PendingGroup = { + channel: string + type: CacheBusMessage['type'] + namespace: string + keys: Set +} + +/** + * Maximum time to open a connection and run its setup queries + */ +const CONNECT_TIMEOUT = 10_000 + +/** + * Keep each transaction short, so it fits in `publishTimeout`. A message + * larger than this is sent over several transactions. + */ +export const MAX_NOTIFICATIONS_PER_TRANSACTION = 1000 +export const MAX_BYTES_PER_TRANSACTION = 1024 * 1024 + +const MIN_RECONNECT_DELAY = 250 +const MAX_RECONNECT_DELAY = 5000 + +/** + * How long to wait for the server to close a connection we end before + * destroying its socket + */ +const DISCARD_GRACE = 1000 +const DISCONNECT_GRACE = 2000 + +/** + * Without `onError`, each distinct error message is logged to the console + * at most once in this period + */ +const ERROR_LOG_INTERVAL = 60_000 +const MAX_LOGGED_ERRORS = 100 + +export const HEARTBEAT_DOCS_URL = 'https://bentocache.dev/docs/multi-tier#if-the-heartbeat-fails' + +/** + * Bus transport that uses Postgres LISTEN/NOTIFY. + * + * It opens two connections from the same connection settings: + * + * - The listener runs `LISTEN` and receives notifications. It is only + * replaced when its connection fails or the heartbeat shows that it no + * longer receives notifications. + * + * - The publisher sends notifications in short transactions, each in one + * round trip: `BEGIN`, `SET LOCAL synchronous_commit = off`, one + * `pg_notify()` per notification, `COMMIT`. Any error or timeout + * replaces only this connection. + * + * Every transaction costs Postgres a transaction id, a WAL record, its + * global notification lock and a wakeup of every listening session, so + * the publisher sends as few as it can: + * + * - Messages published while a transaction runs wait and are sent + * together in the next one. With a `batchDelay`, a batch also waits + * that long after its first message, unless it already holds + * `MAX_NOTIFICATIONS_PER_TRANSACTION` messages. BentoCache waits for + * the publish in every write, so the delay adds to write latency. + * - Messages in a batch with the same channel, type and namespace are + * merged into one, with their keys deduplicated. A very large batch is + * split over several transactions (see `takeBatch`). + * + * Using a transaction makes connection poolers and proxies that split + * reads from writes send the notifications to the primary. + * + * The heartbeat publishes to a channel private to this transport through + * the publisher and checks that the listener receives it. This tests the + * whole path, including proxies, instead of a single connection. + */ +export class PostgresTransport implements Transport { + #options: PostgresTransportOptions + #id?: string + #closed = false + #reconnectCallbacks: Array<() => void> = [] + + /** + * Handlers keyed by Postgres channel name + */ + #handlers = new Map[]>() + + #listener?: pg.Client + #listenerConnected = false + #listening = false + #listenerAttempts = 0 + #listenerTimer?: NodeJS.Timeout + + #publisher?: pg.Client + #publisherReady = false + #publisherAttempts = 0 + #publisherTimer?: NodeJS.Timeout + + /** + * Settles once the first publisher connection succeeds or fails. + * Publishes made before then wait for it instead of failing. + */ + #firstPublisherAttempt: Promise + #endFirstPublisherAttempt!: () => void + #firstPublisherAttemptDone = false + + #queue: QueuedPublish[] = [] + #flushing = false + #flushRun?: Promise + + /** + * Messages not yet merged into `#queue`, keyed by channel, type and + * namespace, with the callers waiting on them + */ + #pending = new Map() + #pendingWaiters: Array<{ resolve: () => void; reject: (error: Error) => void }> = [] + + /** + * When the batch being collected got its first message + */ + #batchOpenedAt = 0 + + /** + * Ends the `batchDelay` wait early + */ + #wakeFlush?: () => void + + #heartbeatChannel = `bentocache.hb.${randomBytes(12).toString('hex')}` + #heartbeatTimer?: NodeJS.Timeout + #heartbeatCheckTimer?: NodeJS.Timeout + #heartbeatCheckPeriod = 0 + #heartbeatSeq = 0 + #heartbeatReceived = 0 + #lastHeartbeatCheck = 0 + + /** + * When each error message was last logged, for the console fallback + */ + #loggedErrors = new Map() + + #disconnecting?: Promise + + /** + * Heartbeats that were committed while the listener was listening, + * keyed by sequence number, with their commit time + */ + #heartbeatsInFlight = new Map() + + constructor(options: PostgresTransportOptions) { + this.#options = options + this.#firstPublisherAttempt = new Promise(resolve => { + this.#endFirstPublisherAttempt = () => { + this.#firstPublisherAttemptDone = true + resolve() + } + }) + this.#connectListener() + this.#connectPublisher() + + if (options.heartbeat) { + this.#heartbeatTimer = setInterval(() => this.#sendHeartbeat(), options.heartbeat.interval) + this.#heartbeatTimer.unref() + + this.#heartbeatCheckPeriod = heartbeatCheckPeriod(options.heartbeat.timeout) + this.#lastHeartbeatCheck = performance.now() + this.#heartbeatCheckTimer = setInterval( + () => this.#checkHeartbeats(), + this.#heartbeatCheckPeriod, + ) + this.#heartbeatCheckTimer.unref() + } + } + + setId(id: string): Transport { + this.#id = id + return this + } + + /** + * The callbacks run every time the publisher becomes usable, including + * the first time, so the bus can send the messages it queued meanwhile + */ + onReconnect(callback: () => void): void { + this.#reconnectCallbacks.push(callback) + } + + async publish(channel: string, message: Serializable): Promise { + if (!this.#id) throw new Error('The bus id must be set before publishing') + if (this.#closed) throw new Error('The Postgres bus is disconnected') + + /** + * Never reject because of the message content: the bus would keep it at + * the head of its retry queue forever and block every message behind it. + * + * Messages are encoded when the batch is sent, so everything that could + * make encoding fail is checked here. Encoding one without its keys + * checks its type and the length of its namespace. + */ + const cacheMessage = message as CacheBusMessage + let type = cacheMessage.type + let keys: unknown = cacheMessage.keys ?? [] + const namespace: unknown = cacheMessage.namespace ?? '' + if (typeof namespace !== 'string') { + this.#reportError(new Error('Postgres bus message dropped: its namespace is not a string')) + return + } + + /** + * A key that isn't a string can't be sent. Clearing the namespace + * invalidates more than needed, but leaves no other instance stale. + */ + if (!Array.isArray(keys) || !keys.every(key => typeof key === 'string')) { + this.#reportError( + new Error( + 'Postgres bus message has keys that are not strings, so its namespace is cleared', + ), + ) + type = CacheBusMessageType.Clear + keys = [] + } + + let encoded + try { + encoded = encodeMessage(this.#id, { type, namespace, keys: [] }) + } catch (error) { + this.#reportError(error) + return + } + + if (encoded.tooLarge) { + this.#reportError( + new Error( + 'Postgres bus message dropped: its namespace is too long to fit in a notification', + ), + ) + return + } + + /** + * Right after start, wait for the first connection instead of failing + * every early write, bounded by `publishTimeout` + */ + if (!this.#publisherReady && !this.#firstPublisherAttemptDone) { + await withTimeout(this.#firstPublisherAttempt, this.#options.publishTimeout).catch(() => {}) + if (this.#closed) throw new Error('The Postgres bus is disconnected') + } + + /** + * Fail fast while the publisher is down. The bus keeps the message in + * its retry queue and sends it once the publisher reconnects. + */ + if (!this.#publisherReady) throw new Error('The Postgres bus publisher is not connected') + + return new Promise((resolve, reject) => { + this.#openBatch() + + /** + * The channel and the type can't contain a line feed, so the key is + * unambiguous + */ + const pgChannel = toPostgresChannel(channel) + const groupKey = `${pgChannel}\n${type}\n${namespace}` + let group = this.#pending.get(groupKey) + if (!group) { + group = { channel: pgChannel, type, namespace, keys: new Set() } + this.#pending.set(groupKey, group) + } + for (const key of keys as string[]) group.keys.add(key) + + this.#pendingWaiters.push({ resolve, reject }) + if (this.#pendingWaiters.length >= MAX_NOTIFICATIONS_PER_TRANSACTION) this.#wakeFlush?.() + void this.#flush() + }) + } + + async subscribe( + channel: string, + handler: SubscribeHandler, + ): Promise { + const pgChannel = toPostgresChannel(channel) + const handlers = this.#handlers.get(pgChannel) ?? [] + handlers.push(handler) + this.#handlers.set(pgChannel, handlers) + + /** + * If the listener isn't connected yet, it will LISTEN to every + * subscribed channel once it is. BentoCache doesn't await this method, + * so it must not reject: failures go to `onError` and the listener + * reconnects. + */ + const listener = this.#listener + if (!listener || !this.#listenerConnected) return + + try { + await withTimeout(listener.query(`LISTEN ${quoteChannel(pgChannel)}`), CONNECT_TIMEOUT) + } catch (error) { + this.#onListenerLost(listener, error) + } + } + + async unsubscribe(channel: string): Promise { + const pgChannel = toPostgresChannel(channel) + this.#handlers.delete(pgChannel) + + const listener = this.#listener + if (!listener || !this.#listenerConnected) return + + try { + await withTimeout(listener.query(`UNLISTEN ${quoteChannel(pgChannel)}`), CONNECT_TIMEOUT) + } catch (error) { + this.#reportError(error) + } + } + + /** + * Every call returns the same promise, so a second call made while the + * first is still sending pending messages waits for them instead of + * dropping them. Each namespace of a store shares its bus, so several + * calls at shutdown are common. + */ + disconnect(): Promise { + this.#disconnecting ??= this.#disconnect() + return this.#disconnecting + } + + async #disconnect(): Promise { + this.#closed = true + clearInterval(this.#heartbeatTimer) + clearInterval(this.#heartbeatCheckTimer) + clearTimeout(this.#listenerTimer) + clearTimeout(this.#publisherTimer) + this.#endFirstPublisherAttempt() + + await this.#drain() + this.#rejectQueued(new Error('The Postgres bus is disconnected')) + + const clients = [this.#listener, this.#publisher] + this.#listener = undefined + this.#publisher = undefined + this.#listening = false + this.#listenerConnected = false + this.#publisherReady = false + + await Promise.all(clients.map(client => client && closeClient(client, DISCONNECT_GRACE))) + } + + /** + * `fallback_application_name` names the session only when the user sets + * no `application_name` (in the config, the connection string or + * `PGAPPNAME`), so the bus sessions can be found in `pg_stat_activity` + */ + #clientConfig(role: 'listener' | 'publisher'): pg.ClientConfig { + const { connection } = this.#options + const config = typeof connection === 'string' ? { connectionString: connection } : connection + return { keepAlive: true, fallback_application_name: `bentocache-bus:${role}`, ...config } + } + + /** + * Errors go to `onError`. Without it, they are logged to the console, + * each distinct message at most once per `ERROR_LOG_INTERVAL`: a broken + * bus must not fail silently, nor flood the logs while it reconnects. + */ + #reportError(error: unknown) { + const normalized = toError(error) + if (this.#options.onError) { + try { + this.#options.onError(normalized) + } catch { + // An error in the user's callback must not break the bus + } + return + } + + const now = performance.now() + const lastLogged = this.#loggedErrors.get(normalized.message) + if (lastLogged !== undefined && now - lastLogged < ERROR_LOG_INTERVAL) return + if (this.#loggedErrors.size >= MAX_LOGGED_ERRORS) this.#loggedErrors.clear() + this.#loggedErrors.set(normalized.message, now) + console.error('[bentocache] postgres bus error:', normalized) + } + + #reconnectDelay(attempt: number) { + const delay = Math.min(MAX_RECONNECT_DELAY, MIN_RECONNECT_DELAY * 2 ** attempt) + return delay / 2 + Math.random() * (delay / 2) + } + + /** + * --------------------------------------------------------------------- + * Listener + * --------------------------------------------------------------------- + */ + + #connectListener() { + if (this.#closed) return + + const client = new pg.Client(this.#clientConfig('listener')) + this.#listener = client + this.#listenerConnected = false + this.#listening = false + + client.on('error', error => this.#onListenerLost(client, error)) + client.on('end', () => + this.#onListenerLost(client, new Error('Postgres bus listener connection ended')), + ) + client.on('notification', msg => this.#onNotification(msg.channel, msg.payload)) + + const setup = async () => { + await client.connect() + if (client !== this.#listener) return + + /** + * From here on, `subscribe()` sends its own LISTEN on this client, + * so the snapshot below can't miss a channel. + */ + await disableIdleSessionTimeout(client) + if (client !== this.#listener) return + + this.#listenerConnected = true + const channels = [this.#heartbeatChannel, ...this.#handlers.keys()] + for (const channel of channels) await client.query(`LISTEN ${quoteChannel(channel)}`) + } + + withTimeout(setup(), CONNECT_TIMEOUT) + .then(() => { + if (client !== this.#listener) return + this.#listening = true + this.#listenerAttempts = 0 + this.#heartbeatsInFlight.clear() + }) + .catch(error => this.#onListenerLost(client, error)) + } + + #onListenerLost(client: pg.Client | undefined, error: unknown) { + if (!client || client !== this.#listener) return + + this.#listener = undefined + this.#listenerConnected = false + this.#listening = false + this.#heartbeatsInFlight.clear() + discard(client) + + if (this.#closed) return + this.#reportError(error) + + const delay = this.#reconnectDelay(this.#listenerAttempts++) + this.#listenerTimer = setTimeout(() => this.#connectListener(), delay) + } + + #onNotification(channel: string, payload: string | undefined) { + if (channel === this.#heartbeatChannel) { + const seq = Number(payload) + if (!Number.isInteger(seq)) return + this.#heartbeatReceived = Math.max(this.#heartbeatReceived, seq) + for (const pending of this.#heartbeatsInFlight.keys()) { + if (pending <= seq) this.#heartbeatsInFlight.delete(pending) + } + return + } + + const handlers = this.#handlers.get(channel) + if (!handlers || payload === undefined) return + + const message = decodeMessage(payload) + if (!message || message.busId === this.#id) return + + for (const handler of handlers) { + try { + const result = handler(message.payload) + if (result instanceof Promise) result.catch(error => this.#reportError(error)) + } catch (error) { + this.#reportError(error) + } + } + } + + /** + * --------------------------------------------------------------------- + * Publisher + * --------------------------------------------------------------------- + */ + + #connectPublisher() { + if (this.#closed) return + + const client = new pg.Client(this.#clientConfig('publisher')) + this.#publisher = client + this.#publisherReady = false + + client.on('error', error => this.#onPublisherLost(client, error)) + client.on('end', () => + this.#onPublisherLost(client, new Error('Postgres bus publisher connection ended')), + ) + + /** + * The publisher is usable once it has committed a notification. A + * connection alone isn't enough: through a proxy, it can succeed while + * no primary is available. + */ + const listenerAtSend = this.#listening ? this.#listener : undefined + const seq = ++this.#heartbeatSeq + + /** + * Unlike the listener, the publisher keeps `idle_session_timeout`: the + * heartbeat keeps it busy, and a closed publisher is simply replaced. + */ + withTimeout(client.connect(), CONNECT_TIMEOUT) + .then(() => + withTimeout( + sendNotifications(client, [[this.#heartbeatChannel, String(seq)]]), + this.#options.publishTimeout, + ), + ) + .then(() => { + if (client !== this.#publisher) return + this.#recordHeartbeat(seq, listenerAtSend) + this.#publisherReady = true + this.#publisherAttempts = 0 + this.#endFirstPublisherAttempt() + for (const callback of this.#reconnectCallbacks) callback() + void this.#flush() + }) + .catch(error => this.#onPublisherLost(client, error)) + } + + #onPublisherLost(client: pg.Client, error: unknown) { + if (client !== this.#publisher) return + + this.#publisher = undefined + this.#publisherReady = false + discard(client) + this.#endFirstPublisherAttempt() + + const reason = toError(error) + this.#rejectQueued(reason) + + if (this.#closed) return + this.#reportError(reason) + + const delay = this.#reconnectDelay(this.#publisherAttempts++) + this.#publisherTimer = setTimeout(() => this.#connectPublisher(), delay) + } + + #enqueue(notifications: Notification[]): Promise { + return new Promise((resolve, reject) => { + this.#openBatch() + this.#queue.push({ notifications, sent: 0, resolve, reject }) + void this.#flush() + }) + } + + /** + * Start the `batchDelay` wait when a message arrives with nothing else + * waiting to be sent + */ + #openBatch() { + if (this.#queue.length === 0 && this.#pending.size === 0) { + this.#batchOpenedAt = performance.now() + } + } + + #rejectQueued(error: Error) { + for (const item of this.#queue.splice(0)) item.reject(error) + for (const waiter of this.#pendingWaiters.splice(0)) waiter.reject(error) + this.#pending.clear() + this.#wakeFlush?.() + } + + /** + * Encode the pending messages, one per channel, type and namespace, and + * queue them as one item that settles every caller at once. + * + * Messages of different types or namespaces can end up in another order + * than they were published. Every message only deletes or expires + * entries on the receiving side, so the result is the same in any order. + */ + #mergePending() { + if (this.#pending.size === 0) return + + const groups = [...this.#pending.values()] + const waiters = this.#pendingWaiters + this.#pending = new Map() + this.#pendingWaiters = [] + + /** + * `publish()` already checked everything encoding depends on. Should a + * group still fail, it is reported and skipped, and its callers settle + * with the rest of the batch instead of waiting forever. + */ + const notifications: Notification[] = [] + for (const group of groups) { + try { + const { payloads, replacedByClear } = encodeMessage(this.#id!, { + type: group.type, + namespace: group.namespace, + keys: [...group.keys], + }) + if (replacedByClear) { + this.#reportError( + new Error( + `Postgres bus message has a key too long for a notification, so namespace ` + + `"${group.namespace}" is cleared on other instances`, + ), + ) + } + for (const payload of payloads) notifications.push([group.channel, payload]) + } catch (error) { + this.#reportError(error) + } + } + + this.#queue.push({ + notifications, + sent: 0, + resolve: () => { + for (const waiter of waiters) waiter.resolve() + }, + reject: error => { + for (const waiter of waiters) waiter.reject(error) + }, + }) + } + + /** + * Wait until `batchDelay` has passed since the batch opened, unless the + * batch is already full. Returns early when woken by `#wakeFlush`. + */ + async #waitForBatch() { + const { batchDelay } = this.#options + if (batchDelay === 0) return + + /** + * `performance.now()` never goes back, unlike the wall clock. The cap + * is a second guard against a wait longer than `batchDelay`. + */ + const wait = Math.min(this.#batchOpenedAt + batchDelay - performance.now(), batchDelay) + if (wait <= 0 || this.#closed) return + if (this.#pendingWaiters.length >= MAX_NOTIFICATIONS_PER_TRANSACTION) return + + await new Promise(resolve => { + const timer = setTimeout(resolve, wait) + this.#wakeFlush = () => { + clearTimeout(timer) + resolve() + } + }) + this.#wakeFlush = undefined + } + + /** + * Send what is queued, unless a flush is already running. Returns the + * running flush, so `disconnect()` can wait for it. + */ + #flush(): Promise { + if (this.#flushing) return this.#flushRun ?? Promise.resolve() + this.#flushing = true + this.#flushRun = this.#runFlush() + return this.#flushRun + } + + /** + * Send what is still queued before closing, within one `publishTimeout`. + * New publishes are already refused, and the batch delay is skipped. + */ + async #drain() { + const deadline = performance.now() + this.#options.publishTimeout + this.#wakeFlush?.() + + while (this.#queue.length > 0 || this.#pending.size > 0) { + const remaining = deadline - performance.now() + if (remaining <= 0 || !this.#publisherReady) return + await withTimeout(this.#flush(), remaining).catch(() => {}) + } + } + + async #runFlush() { + try { + while (this.#publisherReady && this.#publisher) { + if (this.#queue.length === 0 && this.#pending.size === 0) break + + await this.#waitForBatch() + const client = this.#publisher + if (!this.#publisherReady || !client) break + + this.#mergePending() + const { notifications, completed } = takeBatch(this.#queue) + if (notifications.length === 0) { + for (const item of completed) item.resolve() + continue + } + + try { + await withTimeout(sendNotifications(client, notifications), this.#options.publishTimeout) + for (const item of completed) item.resolve() + } catch (error) { + /** + * A message whose first parts were already committed is rejected + * too, by `#onPublisherLost` below, and the bus sends it again + * whole. Receiving some keys twice is harmless. + */ + const reason = toError(error) + for (const item of completed) item.reject(reason) + + /** + * The connection may be stuck in the middle of a transaction. + * Replace it rather than trying to roll back. + */ + this.#onPublisherLost(client, reason) + } + } + } catch (error) { + /** + * Nothing above should throw. Should it, the publisher is replaced + * so that queued callers are rejected, and the bus retries them. + */ + if (this.#publisher) this.#onPublisherLost(this.#publisher, error) + else this.#reportError(error) + } finally { + this.#flushing = false + } + } + + /** + * --------------------------------------------------------------------- + * Heartbeat + * --------------------------------------------------------------------- + */ + + /** + * Fail the listener once a committed heartbeat is older than `timeout`. + * This runs more often than heartbeats are sent, so a silent failure is + * detected at most `interval + timeout + timeout / 3` after it happens. + */ + #checkHeartbeats() { + const heartbeat = this.#options.heartbeat + if (!heartbeat || this.#closed) return + + const now = performance.now() + discountStall( + this.#heartbeatsInFlight, + now - this.#lastHeartbeatCheck - this.#heartbeatCheckPeriod, + ) + this.#lastHeartbeatCheck = now + + if (!this.#listening) return + for (const committedAt of this.#heartbeatsInFlight.values()) { + if (now - committedAt > heartbeat.timeout) { + this.#onListenerLost( + this.#listener, + new Error( + `Postgres bus listener did not receive a heartbeat within ${heartbeat.timeout}ms, ` + + `so it is replaced. For the usual causes, see ${HEARTBEAT_DOCS_URL}`, + ), + ) + return + } + } + } + + #sendHeartbeat() { + /** + * A failed heartbeat replaces the publisher like any failed publish. + * It never replaces the listener: only a heartbeat that was committed + * and not received shows that the listener is broken. + */ + if (!this.#options.heartbeat || this.#closed || !this.#publisherReady) return + + const seq = ++this.#heartbeatSeq + const listenerAtSend = this.#listening ? this.#listener : undefined + this.#enqueue([[this.#heartbeatChannel, String(seq)]]) + .then(() => this.#recordHeartbeat(seq, listenerAtSend)) + .catch(() => {}) + } + + #recordHeartbeat(seq: number, listenerAtSend: pg.Client | undefined) { + if (!this.#options.heartbeat || !listenerAtSend) return + if (listenerAtSend !== this.#listener || !this.#listening) return + + /** + * The notification can arrive before the COMMIT result is processed + */ + if (seq <= this.#heartbeatReceived) return + + this.#heartbeatsInFlight.set(seq, performance.now()) + } +} + +/** + * Send notifications in one transaction and one round trip. + * `synchronous_commit = off` keeps the commit from waiting for the WAL + * flush, which shortens the time Postgres holds its global notification + * lock. + * + * Several statements can only go in one query without parameters, so + * channels and payloads are escaped as literals. Both are ASCII (see + * `toPostgresChannel` and `encodeMessage`). If a statement fails, + * Postgres skips the rest, COMMIT included, and the caller replaces the + * connection. + */ +async function sendNotifications(client: pg.Client, notifications: Notification[]) { + const values = notifications + .map( + ([channel, payload]) => `(${client.escapeLiteral(channel)},${client.escapeLiteral(payload)})`, + ) + .join(',') + + await client.query( + 'BEGIN;SET LOCAL synchronous_commit = off;' + + `SELECT pg_notify(c, p) FROM (VALUES ${values}) AS t(c, p);COMMIT`, + ) +} + +/** + * Take the notifications for the next transaction from the head of the + * queue: up to `maxNotifications` and `maxBytes`, but always at least + * one. Several small messages share a transaction, and a large message + * is split over several. + * + * Returns the messages whose last notification is in this batch. They + * are removed from the queue. A message that is only partly in the batch + * stays at the head of the queue for the next one. + */ +export function takeBatch( + queue: QueuedPublish[], + maxNotifications = MAX_NOTIFICATIONS_PER_TRANSACTION, + maxBytes = MAX_BYTES_PER_TRANSACTION, +): { notifications: Notification[]; completed: QueuedPublish[] } { + const notifications: Notification[] = [] + const completed: QueuedPublish[] = [] + let bytes = 0 + + while (queue.length > 0) { + const item = queue[0] + + while (item.sent < item.notifications.length) { + const notification = item.notifications[item.sent] + const size = notification[0].length + notification[1].length + const full = notifications.length >= maxNotifications || bytes + size > maxBytes + if (notifications.length > 0 && full) return { notifications, completed } + + notifications.push(notification) + bytes += size + item.sent++ + } + + completed.push(queue.shift()!) + } + + return { notifications, completed } +} + +/** + * Don't count time the process was frozen (a long garbage collection, a + * blocking call, a paused debugger) against heartbeats in flight. After a + * stall, Node runs due timers before it reads sockets, so a heartbeat can + * be waiting unread on a healthy listener when the check runs. + * + * `stall` is how late the heartbeat check timer fired. Moving the commit + * times forward by it measures each heartbeat's age in time the process + * was running. + */ +/** + * How often heartbeats in flight are checked: often enough that a missing + * one is detected soon after `timeout`, without a timer running far more + * often than needed + */ +export function heartbeatCheckPeriod(timeout: number) { + return Math.max(1, Math.round(timeout / 3)) +} + +export function discountStall(inFlight: Map, stall: number) { + if (stall <= 0) return + for (const [seq, committedAt] of inFlight) inFlight.set(seq, committedAt + stall) +} + +/** + * Postgres 14+ closes sessions that stay idle longer than + * `idle_session_timeout`, and receiving notifications doesn't count as + * activity. The listener never runs a query once it listens, so a + * database or role with that setting would close it over and over. + * + * - The timeout is turned off even when the server has none yet. A timeout + * enabled later by a config reload reaches this session on its next + * query, such as a LISTEN for a new channel, and a session-level `SET` + * overrides reloaded values. + * - `current_setting(..., true)` returns NULL on versions without the + * setting, and nothing is changed there. + * - A plain `SET` is used because poolers in transaction mode, such as + * PgDog, track it for this client only and reset it before handing the + * server connection to another client. A `SELECT set_config(...)` is + * not tracked and would stay on a server connection other clients use. + */ +async function disableIdleSessionTimeout(client: pg.Client) { + const result = await client.query( + "SELECT current_setting('idle_session_timeout', true) AS timeout", + ) + const timeout: unknown = result.rows[0]?.timeout + if (timeout === null || timeout === undefined) return + await client.query('SET idle_session_timeout = 0') +} + +/** + * Close a client we no longer use, without waiting for it + */ +function discard(client: pg.Client) { + client.removeAllListeners() + client.on('error', () => {}) + void closeClient(client, DISCARD_GRACE) +} + +/** + * End a client, then destroy its socket if the server hasn't closed the + * connection within `grace`. On an idle client, `end()` waits for the + * server to close its side, which a stalled server or proxy never does, + * and the open socket would keep the process alive. Never rejects. + */ +async function closeClient(client: pg.Client, grace: number) { + try { + await withTimeout(client.end(), grace) + } catch { + try { + client.connection.stream.destroy() + } catch { + // Nothing more can be done + } + } +} + +function withTimeout(promise: Promise, ms: number): Promise { + let timer: NodeJS.Timeout + const timeout = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`Postgres bus operation timed out after ${ms}ms`)), + ms, + ) + timer.unref() + }) + + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)) +} + +/** + * Normalize anything thrown into an Error with a useful message. A refused + * connection to a host with several addresses (e.g. `localhost`) fails + * with an `AggregateError` whose own message is empty. + */ +function toError(error: unknown): Error { + if (!(error instanceof Error)) return new Error(String(error)) + if (error.message) return error + + const details = + error instanceof AggregateError + ? error.errors + .map(inner => (inner instanceof Error ? inner.message : String(inner))) + .filter(Boolean) + .join('; ') + : '' + const code = (error as NodeJS.ErrnoException).code + return new Error(`Postgres bus connection error: ${details || code || error.name}`, { + cause: error, + }) +} diff --git a/packages/bentocache/src/drivers/postgres.ts b/packages/bentocache/src/drivers/postgres.ts new file mode 100644 index 0000000..16d08aa --- /dev/null +++ b/packages/bentocache/src/drivers/postgres.ts @@ -0,0 +1,92 @@ +import { resolveTtl } from '../helpers.js' +import { PostgresTransport } from '../bus/transports/postgres/postgres_transport.js' +import type { + BusOptions, + CreateBusDriverResult, + Duration, + PostgresBusConfig, +} from '../types/main.js' + +const DEFAULT_PUBLISH_TIMEOUT = 2000 +const DEFAULT_BATCH_DELAY = 0 +const DEFAULT_HEARTBEAT_INTERVAL = 30_000 +const DEFAULT_HEARTBEAT_TIMEOUT = 15_000 + +/** + * Node turns timer delays outside 1 to 2^31 - 1 milliseconds (about 24.8 + * days) into 1 millisecond, so durations outside that range are rejected + */ +const MIN_DURATION = 1 +const MAX_DURATION = 2 ** 31 - 1 + +function toMilliseconds( + name: string, + value: Duration | undefined, + defaultValue: number, + min = MIN_DURATION, +) { + const error = new TypeError( + `postgresBusDriver: "${name}" must be a duration between ${min}ms and ${MAX_DURATION}ms (about 24 days)`, + ) + + let ms: number | undefined + try { + ms = resolveTtl(value ?? undefined, defaultValue) + } catch { + throw error + } + + if (typeof ms !== 'number' || !(ms >= min && ms <= MAX_DURATION)) throw error + return ms +} + +/** + * Create a bus driver that uses Postgres LISTEN/NOTIFY to send messages + * between your different processes. + * + * It opens two connections from the connection you pass: one that + * listens and one that publishes. It doesn't create any table. + */ +export function postgresBusDriver(options: PostgresBusConfig & BusOptions): CreateBusDriverResult { + if (!options?.connection) { + throw new TypeError('postgresBusDriver: "connection" is required') + } + + const publishTimeout = toMilliseconds( + 'publishTimeout', + options.publishTimeout, + DEFAULT_PUBLISH_TIMEOUT, + ) + + /** + * 0, the default, sends each batch as soon as no transaction is running + */ + const batchDelay = toMilliseconds('batchDelay', options.batchDelay, DEFAULT_BATCH_DELAY, 0) + + let heartbeat: false | { interval: number; timeout: number } = false + if (options.heartbeat !== false) { + const interval = toMilliseconds( + 'heartbeat.interval', + options.heartbeat?.interval, + DEFAULT_HEARTBEAT_INTERVAL, + ) + const timeout = toMilliseconds( + 'heartbeat.timeout', + options.heartbeat?.timeout, + DEFAULT_HEARTBEAT_TIMEOUT, + ) + heartbeat = { interval, timeout } + } + + return { + options, + factory: () => + new PostgresTransport({ + connection: options.connection, + publishTimeout, + batchDelay, + heartbeat, + onError: options.onError, + }), + } +} diff --git a/packages/bentocache/src/types/options/drivers_options.ts b/packages/bentocache/src/types/options/drivers_options.ts index 1b255b1..6045153 100644 --- a/packages/bentocache/src/types/options/drivers_options.ts +++ b/packages/bentocache/src/types/options/drivers_options.ts @@ -1,5 +1,6 @@ import type { Knex } from 'knex' import type { Kysely } from 'kysely' +import type { ClientConfig as PgClientConfig } from 'pg' import type { DynamoDBClientConfig } from '@aws-sdk/client-dynamodb' import type { DbResult, DefaultColumnTypes, DefaultSchemaConfig } from 'orchid-orm' import type { @@ -114,6 +115,67 @@ export type RedisConfig = { connection: IoRedis | IoRedisCluster | IoRedisOptions } & DriverCommonOptions +/** + * Options for the Postgres bus driver + */ +export type PostgresBusConfig = { + /** + * A Postgres connection string or `pg` client config. The driver opens + * two connections from it: one that listens and one that publishes. + * + * It must reach the primary, directly or through a proxy, and LISTEN + * must work on it. A pooler in transaction mode breaks LISTEN unless it + * supports it explicitly. + */ + connection: string | PgClientConfig + + /** + * Maximum time for one publish transaction. A publish that takes longer + * fails, goes to the retry queue, and the publishing connection is + * replaced. + * + * @default '2s' + */ + publishTimeout?: Duration + + /** + * Extra time the driver waits after a message before it sends it, so + * that more messages share one transaction. + * + * Even at `0`, messages published while a transaction runs are sent + * together in the next one, and messages with the same type and + * namespace are merged into one notification. Every transaction costs + * Postgres a transaction id, a WAL record and a cluster-wide lock, so a + * delay lowers the load on Postgres. BentoCache waits for the publish in + * every write (`set`, `delete`, `clear`...), so the delay also adds to + * the latency of each write. + * + * @default 0 + */ + batchDelay?: Duration + + /** + * End-to-end check of the bus. Every `interval`, the driver publishes a + * message only it listens to and checks that it receives it. If a + * committed heartbeat isn't received within `timeout`, the listening + * connection is replaced. It also keeps both connections active, so + * proxies with an idle timeout longer than `interval` don't close them. + * + * Set to `false` to disable it. See the docs for when that is safe. + * + * @default { interval: '30s', timeout: '15s' } + */ + heartbeat?: false | { interval?: Duration; timeout?: Duration } + + /** + * Called with connection errors, failed publishes and dropped messages. + * The driver retries on its own, so this is for logging. Without it, + * errors are logged with `console.error`, each distinct message at most + * once a minute. + */ + onError?: (error: Error) => void +} + /** * Options for File driver */ diff --git a/packages/bentocache/tests/bus/postgres_bus.spec.ts b/packages/bentocache/tests/bus/postgres_bus.spec.ts new file mode 100644 index 0000000..0cf4f5e --- /dev/null +++ b/packages/bentocache/tests/bus/postgres_bus.spec.ts @@ -0,0 +1,1205 @@ +import pg from 'pg' +import net from 'node:net' +import { test } from '@japa/runner' +import { randomUUID } from 'node:crypto' +import { sleep } from '@julr/utils/misc' + +import { BentoCache, bentostore } from '../../index.js' +import { memoryDriver } from '../../src/drivers/memory.js' +import { POSTGRES_CREDENTIALS } from '../helpers/index.js' +import { CacheBusMessageType } from '../../src/types/bus.js' +import type { CacheBusMessage } from '../../src/types/bus.js' +import type { PostgresBusConfig } from '../../src/types/main.js' +import { postgresBusDriver } from '../../src/drivers/postgres.js' +import type { + Notification, + QueuedPublish, +} from '../../src/bus/transports/postgres/postgres_transport.js' +import { + HEARTBEAT_DOCS_URL, + MAX_BYTES_PER_TRANSACTION, + MAX_NOTIFICATIONS_PER_TRANSACTION, + discountStall, + heartbeatCheckPeriod, + takeBatch, +} from '../../src/bus/transports/postgres/postgres_transport.js' + +const PG_HOST = process.env.POSTGRES_HOST || 'localhost' +const PG_PORT = Number(process.env.POSTGRES_PORT) || 5432 +const PG_CONNECTION = { ...POSTGRES_CREDENTIALS, host: PG_HOST, port: PG_PORT } + +/** + * Poll until `fn` returns true + */ +async function until( + fn: () => boolean | Promise, + timeout = 10_000, + message = 'condition', +) { + const start = Date.now() + while (!(await fn())) { + if (Date.now() - start > timeout) throw new Error(`Timed out waiting for ${message}`) + await sleep(25) + } +} + +async function adminQuery(sql: string, params: unknown[] = []) { + const client = new pg.Client(PG_CONNECTION) + await client.connect() + try { + return await client.query(sql, params) + } finally { + await client.end() + } +} + +async function backendCount(applicationName: string) { + const result = await adminQuery( + 'SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name = $1', + [applicationName], + ) + return result.rows[0].count as number +} + +type TestBus = ReturnType + +/** + * Create a transport with its own application name, so the test can find + * and kill its connections + */ +function createBus(id: string, options: Partial = {}, connection = {}) { + const applicationName = `bentocache-test-${randomUUID().slice(0, 8)}` + const errors: Error[] = [] + const received: Array<{ channel: string; message: CacheBusMessage }> = [] + let reconnects = 0 + + const transport = postgresBusDriver({ + connection: { ...PG_CONNECTION, application_name: applicationName, ...connection }, + onError: error => errors.push(error), + ...options, + }) + .factory(null) + .setId(id) + + transport.onReconnect(() => reconnects++) + + return { + id, + transport, + errors, + received, + applicationName, + get reconnects() { + return reconnects + }, + subscribe(channel: string) { + return transport.subscribe(channel, message => { + received.push({ channel, message }) + }) + }, + } +} + +async function closeAll(...buses: TestBus[]) { + await Promise.all(buses.map(bus => bus.transport.disconnect())) +} + +function message(keys: string[], type = CacheBusMessageType.Set): CacheBusMessage { + return { type, namespace: 'users', keys } +} + +/** + * Publish from `from` until `to` receives it: proves that the publisher + * of one and the listener of the other are both up + */ +async function waitForPath(from: TestBus, to: TestBus, channel: string, timeout = 15_000) { + const key = `probe:${randomUUID()}` + await until( + async () => { + await from.transport.publish(channel, message([key])).catch(() => {}) + await sleep(50) + return to.received.some(r => r.message.keys.includes(key)) + }, + timeout, + `a message from ${from.id} to reach ${to.id}`, + ) +} + +/** + * TCP proxy in front of Postgres that can silently stop forwarding on the + * connections it already has, like a dead proxy or a half-open socket + */ +async function createFreezableProxy() { + const active: Array<{ client: net.Socket; server: net.Socket }> = [] + const sockets: net.Socket[] = [] + const server = net.createServer(client => { + const upstream = net.connect(PG_PORT, PG_HOST) + client.pipe(upstream) + upstream.pipe(client) + client.on('error', () => upstream.destroy()) + upstream.on('error', () => client.destroy()) + active.push({ client, server: upstream }) + sockets.push(client, upstream) + }) + + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const port = (server.address() as net.AddressInfo).port + + return { + port, + freezeExisting() { + for (const pair of active.splice(0)) { + pair.client.unpipe(pair.server) + pair.server.unpipe(pair.client) + pair.client.pause() + pair.server.pause() + } + }, + async close() { + for (const socket of sockets) socket.destroy() + await new Promise(resolve => server.close(resolve)) + }, + } +} + +/** + * Record every `pg.Client` that connects while the test runs + */ +function captureClients(cleanup: (handler: () => void) => void) { + const clients: pg.Client[] = [] + const connect = pg.Client.prototype.connect + pg.Client.prototype.connect = function (this: pg.Client, ...args: any[]) { + clients.push(this) + return (connect as any).apply(this, args) + } as any + cleanup(() => { + pg.Client.prototype.connect = connect + }) + return clients +} + +test.group('Postgres bus', group => { + group.each.timeout(30_000) + + test('delivers messages between instances and ignores its own', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus1.subscribe('channel') + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + await waitForPath(bus2, bus1, 'channel') + + bus1.received.length = 0 + bus2.received.length = 0 + await bus1.transport.publish('channel', message(['user:1', 'café:日本'])) + await until(() => bus2.received.length === 1) + await sleep(100) + + assert.deepEqual(bus2.received, [ + { channel: 'channel', message: message(['user:1', 'café:日本']) }, + ]) + assert.deepEqual(bus1.received, []) + assert.deepEqual(bus1.errors, []) + assert.deepEqual(bus2.errors, []) + }) + + test('opens exactly two connections and closes them on disconnect', async ({ assert }) => { + const bus = createBus('bus-1') + await bus.subscribe('channel') + await until(() => bus.reconnects > 0) + + assert.equal(await backendCount(bus.applicationName), 2) + + await bus.transport.disconnect() + await until(async () => (await backendCount(bus.applicationName)) === 0) + await assert.rejects( + () => bus.transport.publish('channel', message(['a'])), + 'The Postgres bus is disconnected', + ) + }) + + test('creates no table or other database object', async ({ assert, cleanup }) => { + const objectCount = async () => { + const result = await adminQuery( + `SELECT count(*)::int AS count FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')`, + ) + return result.rows[0].count as number + } + + const before = await objectCount() + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + + assert.equal(await objectCount(), before) + }) + + test('holds publishes made before the first connection, then calls onReconnect', async ({ + assert, + cleanup, + }) => { + const bus2 = createBus('bus-2') + cleanup(() => bus2.transport.disconnect()) + await bus2.subscribe('channel') + await until(() => bus2.reconnects === 1) + + /** + * bus-1 was just created, so its publisher isn't connected yet + */ + const bus1 = createBus('bus-1') + cleanup(() => bus1.transport.disconnect()) + await bus1.transport.publish('channel', message(['early'])) + assert.equal(bus1.reconnects, 1) + + await until(() => bus2.received.some(r => r.message.keys.includes('early'))) + assert.deepEqual(bus1.errors, []) + }) + + test('rejects publishes once the first connection has failed', async ({ assert, cleanup }) => { + const bus = createBus('bus-1', {}, { host: '127.0.0.1', port: 1 }) + cleanup(() => bus.transport.disconnect()) + + await assert.rejects( + () => bus.transport.publish('channel', message(['a'])), + 'The Postgres bus publisher is not connected', + ) + assert.isAbove(bus.errors.length, 0) + + /** + * Later publishes fail right away + */ + const startedAt = Date.now() + await assert.rejects( + () => bus.transport.publish('channel', message(['b'])), + 'The Postgres bus publisher is not connected', + ) + assert.isBelow(Date.now() - startedAt, 1000) + }) + + test('works with channel names longer than 63 bytes', async ({ assert, cleanup }) => { + const channel = `bentocache.notifications:${'a-very-long-store-name-'.repeat(4)}` + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe(channel) + await waitForPath(bus1, bus2, channel) + + assert.isTrue(bus2.received.every(r => r.channel === channel)) + assert.deepEqual(bus2.errors, []) + }) + + test('delivers keys, namespaces and channel names in any language', async ({ + assert, + cleanup, + }) => { + const channel = 'bentocache.notifications:магазин' + const keys = [ + 'zh:用户资料', + 'ar:مستخدم', + 'hi:उपयोगकर्ता', + 'emoji:👨‍👩‍👧‍👦🇮🇳', + `nfc:${String.fromCodePoint(0xe9)}`, // é as one character + `nfd:e${String.fromCodePoint(0x301)}`, // é as e + combining accent + `ctrl:${String.fromCodePoint(0, 10, 0x2028)}`, // NUL, newline, line separator + `lone:${String.fromCharCode(0xd800)}`, // lone surrogate + ] + const namespaces = ['naïve', '名前空間', '😀'] + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe(channel) + await waitForPath(bus1, bus2, channel) + + bus2.received.length = 0 + for (const namespace of namespaces) { + await bus1.transport.publish(channel, { type: CacheBusMessageType.Delete, namespace, keys }) + } + await until(() => bus2.received.length === namespaces.length) + + assert.deepEqual( + bus2.received, + namespaces.map(namespace => ({ + channel, + message: { type: CacheBusMessageType.Delete, namespace, keys }, + })), + ) + assert.deepEqual(bus1.errors, []) + assert.deepEqual(bus2.errors, []) + }) + + test('splits messages with many keys across notifications', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + const keys = Array.from({ length: 3000 }, (_, i) => `product:${i}:`.padEnd(40, 'x')) + await bus1.transport.publish('channel', message(keys, CacheBusMessageType.Delete)) + await until(() => bus2.received.flatMap(r => r.message.keys).length >= keys.length) + + assert.isAbove(bus2.received.length, 1) + assert.deepEqual( + bus2.received.flatMap(r => r.message.keys), + keys, + ) + }) + + test('sends a message larger than one transaction over several', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + /** + * About 4 MB of notifications, so at least 4 transactions + */ + const keys = Array.from({ length: 100_000 }, (_, i) => `product:${i}:`.padEnd(40, 'x')) + await bus1.transport.publish('channel', message(keys, CacheBusMessageType.Delete)) + await bus1.transport.publish('channel', message(['after'])) + await until(() => bus2.received.some(r => r.message.keys.includes('after'))) + + const receivedKeys = bus2.received.flatMap(r => r.message.keys) + assert.deepEqual(receivedKeys.slice(0, -1), keys) + assert.deepEqual(bus1.errors, []) + }) + + test('keeps its listener when the server closes idle sessions', async ({ assert, cleanup }) => { + /** + * A heartbeat longer than the test keeps both connections idle. The + * publishers may be closed and replaced; the listeners must stay. + */ + const options = { heartbeat: { interval: '1m' } } + const idleTimeout = { options: '-c idle_session_timeout=500' } + const bus1 = createBus('bus-1', options, idleTimeout) + const bus2 = createBus('bus-2', options, idleTimeout) + cleanup(() => closeAll(bus1, bus2)) + + const listenerPids = async () => { + const result = await adminQuery( + `SELECT pid FROM pg_stat_activity + WHERE application_name = ANY($1) AND query LIKE 'LISTEN%' ORDER BY pid`, + [[bus1.applicationName, bus2.applicationName]], + ) + return result.rows + } + + await bus1.subscribe('channel') + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + await waitForPath(bus2, bus1, 'channel') + const before = await listenerPids() + + await sleep(2000) + await waitForPath(bus1, bus2, 'channel') + await waitForPath(bus2, bus1, 'channel') + + assert.lengthOf(before, 2) + assert.deepEqual(await listenerPids(), before) + }) + + test('keeps its listener when an idle timeout is enabled by a config reload', async ({ + assert, + cleanup, + }) => { + /** + * Changes a server-wide setting, so it relies on tests running one at a + * time. A session picks up a reloaded value on its next query, here the + * LISTEN sent by a later subscribe. + */ + cleanup(async () => { + await adminQuery('ALTER SYSTEM RESET idle_session_timeout') + await adminQuery('SELECT pg_reload_conf()') + }) + + const options = { heartbeat: { interval: '1m' } } + const bus1 = createBus('bus-1', options) + const bus2 = createBus('bus-2', options) + cleanup(() => closeAll(bus1, bus2)) + + const listenerPids = async () => { + const result = await adminQuery( + `SELECT pid FROM pg_stat_activity + WHERE application_name = ANY($1) AND query LIKE 'LISTEN%' ORDER BY pid`, + [[bus1.applicationName, bus2.applicationName]], + ) + return result.rows + } + + await bus1.subscribe('channel') + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + await waitForPath(bus2, bus1, 'channel') + + await adminQuery("ALTER SYSTEM SET idle_session_timeout = '500ms'") + await adminQuery('SELECT pg_reload_conf()') + await sleep(300) + + await bus1.subscribe('other') + await bus2.subscribe('other') + await waitForPath(bus1, bus2, 'other') + await waitForPath(bus2, bus1, 'other') + const before = await listenerPids() + + await sleep(2000) + await waitForPath(bus1, bus2, 'channel') + await waitForPath(bus2, bus1, 'channel') + + assert.lengthOf(before, 2) + assert.deepEqual(await listenerPids(), before) + }) + + test('merges concurrent publishes into one message', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + const keys = Array.from({ length: 500 }, (_, i) => `key:${i}`) + await Promise.all(keys.map(key => bus1.transport.publish('channel', message([key])))) + await until(() => bus2.received.length > 0) + await sleep(100) + + assert.deepEqual(bus2.received, [{ channel: 'channel', message: message(keys) }]) + }) + + test('merges by type and namespace, deduplicates keys and keeps first-seen order', async ({ + assert, + cleanup, + }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + const { Set: SET, Delete: DELETE, Clear: CLEAR } = CacheBusMessageType + const published: CacheBusMessage[] = [ + { type: SET, namespace: 'users', keys: ['a', 'b'] }, + { type: DELETE, namespace: 'users', keys: ['c'] }, + { type: SET, namespace: 'users', keys: ['b', 'd'] }, + { type: SET, namespace: 'posts', keys: ['e'] }, + { type: CLEAR, namespace: 'users', keys: [] }, + { type: CLEAR, namespace: 'users', keys: [] }, + ] + await Promise.all(published.map(m => bus1.transport.publish('channel', m))) + await until(() => bus2.received.length >= 4) + await sleep(100) + + assert.deepEqual( + bus2.received.map(r => r.message), + [ + { type: SET, namespace: 'users', keys: ['a', 'b', 'd'] }, + { type: DELETE, namespace: 'users', keys: ['c'] }, + { type: SET, namespace: 'posts', keys: ['e'] }, + { type: CLEAR, namespace: 'users', keys: [] }, + ], + ) + }) + + test('waits batchDelay after the first message of a batch', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1', { batchDelay: '500ms' }) + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + const start = Date.now() + const first = bus1.transport.publish('channel', message(['first'])) + await sleep(100) + const second = bus1.transport.publish('channel', message(['second'])) + await Promise.all([first, second]) + await until(() => bus2.received.length > 0) + const elapsed = Date.now() - start + await sleep(100) + + assert.isAtLeast(elapsed, 450) + assert.deepEqual(bus2.received, [{ channel: 'channel', message: message(['first', 'second']) }]) + }) + + test('sends a full batch without waiting for batchDelay', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1', { batchDelay: '20s', heartbeat: false }) + const bus2 = createBus('bus-2') + const probe = createBus('probe') + cleanup(() => closeAll(bus1, bus2, probe)) + + /** + * Probing from bus1 would wait 20s per attempt + */ + await bus2.subscribe('channel') + await waitForPath(probe, bus2, 'channel') + await until(() => bus1.reconnects === 1) + bus2.received.length = 0 + + const keys = Array.from({ length: MAX_NOTIFICATIONS_PER_TRANSACTION }, (_, i) => `key:${i}`) + await Promise.all(keys.map(key => bus1.transport.publish('channel', message([key])))) + await until(() => bus2.received.flatMap(r => r.message.keys).length === keys.length, 10_000) + assert.deepEqual( + bus2.received.flatMap(r => r.message.keys), + keys, + ) + }) + + test('escapes quotes and backslashes in channels, namespaces and keys', async ({ + assert, + cleanup, + }) => { + const channel = String.raw`bentocache.notifications:o'brien\x"y` + const keys = [`'; DROP TABLE x; --`, String.raw`back\slash`, `"double"`, String.raw`\'`] + const namespace = String.raw`ns'\"` + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe(channel) + await waitForPath(bus1, bus2, channel) + bus2.received.length = 0 + + await bus1.transport.publish(channel, { type: CacheBusMessageType.Delete, namespace, keys }) + await until(() => bus2.received.length === 1) + + assert.deepEqual(bus2.received, [ + { channel, message: { type: CacheBusMessageType.Delete, namespace, keys } }, + ]) + assert.deepEqual(bus1.errors, []) + }) + + test('rejects every merged publish when the publisher is lost', async ({ assert, cleanup }) => { + const bus = createBus('bus-1', { batchDelay: '5s', heartbeat: false }) + cleanup(() => bus.transport.disconnect()) + await until(() => bus.reconnects === 1) + + const results = Promise.allSettled( + Array.from({ length: 20 }, (_, i) => bus.transport.publish('channel', message([`key:${i}`]))), + ) + await adminQuery( + 'SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name = $1', + [bus.applicationName], + ) + + const settled = await results + assert.lengthOf(settled, 20) + assert.isTrue(settled.every(result => result.status === 'rejected')) + }) + + test('sends pending publishes when disconnect is called twice at once', async ({ + assert, + cleanup, + }) => { + const bus1 = createBus('bus-1', { batchDelay: '5s', heartbeat: false }) + const bus2 = createBus('bus-2') + const probe = createBus('probe') + cleanup(() => closeAll(bus2, probe)) + + await bus2.subscribe('channel') + await waitForPath(probe, bus2, 'channel') + await until(() => bus1.reconnects === 1) + bus2.received.length = 0 + + const keys = ['a', 'b', 'c', 'd', 'e'] + const outcomes = keys.map(key => + bus1.transport.publish('channel', message([key])).then( + () => 'resolved', + (error: Error) => error.message, + ), + ) + await Promise.all([bus1.transport.disconnect(), bus1.transport.disconnect()]) + + assert.deepEqual( + await Promise.all(outcomes), + keys.map(() => 'resolved'), + ) + await until(() => bus2.received.length === 1) + assert.deepEqual(bus2.received, [{ channel: 'channel', message: message(keys) }]) + }) + + test('is not delayed by a wall clock that goes back', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1', { heartbeat: false }) + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + /** + * Every read of the wall clock returns a time a minute earlier than + * the previous one + */ + const realNow = Date.now + let fakeNow = realNow() + Date.now = () => (fakeNow -= 60_000) + cleanup(() => { + Date.now = realNow + }) + + const publishes = Promise.all( + ['a', 'b', 'c'].map(key => bus1.transport.publish('channel', message([key]))), + ) + const outcome = await Promise.race([ + publishes.then(() => 'sent'), + sleep(2000).then(() => 'stuck'), + ]) + Date.now = realNow + + assert.equal(outcome, 'sent') + await until(() => bus2.received.flatMap(r => r.message.keys).length === 3) + }) + + test('sends pending publishes before disconnecting', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1', { batchDelay: '5s', heartbeat: false }) + const bus2 = createBus('bus-2') + const probe = createBus('probe') + cleanup(() => closeAll(bus2, probe)) + + await bus2.subscribe('channel') + await waitForPath(probe, bus2, 'channel') + await until(() => bus1.reconnects === 1) + bus2.received.length = 0 + + const start = Date.now() + const outcome = bus1.transport.publish('channel', message(['last'])).then( + () => 'resolved', + (error: Error) => error.message, + ) + await bus1.transport.disconnect() + + assert.equal(await outcome, 'resolved') + assert.isBelow(Date.now() - start, 4000) + await until(() => bus2.received.length === 1) + assert.deepEqual(bus2.received, [{ channel: 'channel', message: message(['last']) }]) + await assert.rejects( + () => bus1.transport.publish('channel', message(['after'])), + 'The Postgres bus is disconnected', + ) + }) + + test('replaces keys that are not strings with a clear of the namespace', async ({ + assert, + cleanup, + }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + const invalid = [[undefined], [42n], [Symbol('key')], 'not-an-array'] + for (const keys of invalid) { + await bus1.transport.publish('channel', { + type: CacheBusMessageType.Delete, + namespace: 'users', + keys, + } as any) + } + const isProbe = (r: TestBus['received'][number]) => + r.message.keys.some(key => key.startsWith('probe:')) + await until(() => bus2.received.some(r => !isProbe(r))) + await sleep(100) + + const received = bus2.received.filter(r => !isProbe(r)) + assert.isNotEmpty(received) + assert.isTrue( + received.every( + r => r.message.type === CacheBusMessageType.Clear && r.message.namespace === 'users', + ), + ) + assert.lengthOf(bus1.errors, invalid.length) + assert.isTrue(bus1.errors.every(error => error.message.includes('not strings'))) + + /** + * `null` keys mean no keys, like a missing `keys`: a harmless no-op + */ + bus2.received.length = 0 + await bus1.transport.publish('channel', { + type: CacheBusMessageType.Delete, + namespace: 'users', + keys: null, + } as any) + await until(() => bus2.received.some(r => !isProbe(r))) + assert.deepEqual( + bus2.received.filter(r => !isProbe(r)).map(r => r.message), + [{ type: CacheBusMessageType.Delete, namespace: 'users', keys: [] }], + ) + assert.lengthOf(bus1.errors, invalid.length) + }) + + test('drops messages whose namespace is not a string', async ({ assert, cleanup }) => { + const bus = createBus('bus-1') + cleanup(() => bus.transport.disconnect()) + await until(() => bus.reconnects === 1) + + await bus.transport.publish('channel', { + type: CacheBusMessageType.Delete, + namespace: 42, + keys: ['a'], + } as any) + + assert.lengthOf(bus.errors, 1) + assert.include(bus.errors[0].message, 'namespace is not a string') + }) + + test('stops delivering after unsubscribe', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + + await bus2.transport.unsubscribe('channel') + bus2.received.length = 0 + await bus1.transport.publish('channel', message(['after'])) + await sleep(300) + + assert.deepEqual(bus2.received, []) + }) + + test('reconnects both connections after they are terminated', async ({ assert, cleanup }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus1.subscribe('channel') + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + await waitForPath(bus2, bus1, 'channel') + + await adminQuery( + 'SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name = $1', + [bus2.applicationName], + ) + + await until(() => bus2.errors.length > 0) + await waitForPath(bus1, bus2, 'channel') + await waitForPath(bus2, bus1, 'channel') + + assert.isAtLeast(bus2.reconnects, 2) + assert.equal(await backendCount(bus2.applicationName), 2) + }) + + test('the heartbeat replaces a listener that silently stopped receiving', async ({ + assert, + cleanup, + }) => { + const proxy = await createFreezableProxy() + const bus1 = createBus('bus-1') + const bus2 = createBus( + 'bus-2', + { publishTimeout: 500, heartbeat: { interval: 200, timeout: 1000 } }, + { host: '127.0.0.1', port: proxy.port }, + ) + cleanup(async () => { + await Promise.all([bus1.transport.disconnect(), bus2.transport.disconnect()]) + await proxy.close() + }) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + + proxy.freezeExisting() + + await until( + () => bus2.errors.some(error => error.message.includes('did not receive a heartbeat')), + 10_000, + 'the heartbeat to detect the frozen listener', + ) + await waitForPath(bus1, bus2, 'channel') + + assert.isTrue(bus2.errors.some(error => error.message.includes('timed out'))) + const heartbeatError = bus2.errors.find(error => error.message.includes('heartbeat'))! + assert.include(heartbeatError.message, HEARTBEAT_DOCS_URL) + }) + + test('destroys connections that a stalled server never closes', async ({ assert, cleanup }) => { + const clients = captureClients(cleanup) + const proxy = await createFreezableProxy() + const bus1 = createBus('bus-1') + const bus2 = createBus( + 'bus-2', + { publishTimeout: 500, heartbeat: { interval: 200, timeout: 1000 } }, + { host: '127.0.0.1', port: proxy.port }, + ) + cleanup(async () => { + await closeAll(bus1, bus2) + await proxy.close() + }) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + + const open = () => + clients.filter(client => client.port === proxy.port && !client.connection.stream.destroyed) + + /** + * The heartbeat replaces both connections. Their sockets must not stay + * open waiting for a server that never answers, or the process could + * not exit. + */ + const stalled = open() + assert.lengthOf(stalled, 2) + proxy.freezeExisting() + await until( + () => stalled.every(client => client.connection.stream.destroyed), + 10_000, + 'the stalled connections to be destroyed', + ) + + /** + * The same on disconnect + */ + await waitForPath(bus1, bus2, 'channel') + const current = open() + assert.lengthOf(current, 2) + proxy.freezeExisting() + await bus2.transport.disconnect() + + assert.isTrue(current.every(client => client.connection.stream.destroyed)) + }) + + test('logs errors to the console when onError is not set, once a minute per message', async ({ + assert, + cleanup, + }) => { + const logged: unknown[][] = [] + const consoleError = console.error + console.error = (...args: unknown[]) => { + logged.push(args) + } + + const transport = postgresBusDriver({ + connection: { ...PG_CONNECTION, host: '127.0.0.1', port: 1 }, + heartbeat: false, + }) + .factory(null) + .setId('bus-1') + cleanup(async () => { + console.error = consoleError + await transport.disconnect() + }) + + /** + * Both connections fail and retry several times meanwhile, with the + * same message + */ + await until(() => logged.length > 0) + await sleep(1500) + + assert.lengthOf(logged, 1) + assert.equal(logged[0][0], '[bentocache] postgres bus error:') + assert.match((logged[0][1] as Error).message, /ECONNREFUSED/) + }) + + test('names its sessions unless an application name is set', async ({ assert, cleanup }) => { + const before = { + listener: await backendCount('bentocache-bus:listener'), + publisher: await backendCount('bentocache-bus:publisher'), + } + + const unnamed = createBus('bus-1', {}, { application_name: undefined }) + const { user, password } = POSTGRES_CREDENTIALS + const customName = `custom-${randomUUID().slice(0, 8)}` + const named = postgresBusDriver({ + connection: `postgres://${user}:${password}@${PG_HOST}:${PG_PORT}/postgres?application_name=${customName}`, + onError: () => {}, + }) + .factory(null) + .setId('bus-2') + cleanup(async () => { + await Promise.all([unnamed.transport.disconnect(), named.disconnect()]) + }) + + await until( + async () => + (await backendCount('bentocache-bus:listener')) === before.listener + 1 && + (await backendCount('bentocache-bus:publisher')) === before.publisher + 1 && + (await backendCount(customName)) === 2, + 10_000, + 'the bus sessions to be named', + ) + assert.equal(await backendCount('bentocache-bus:listener'), before.listener + 1) + }) + + test('reports refused connections with a readable message', async ({ assert, cleanup }) => { + /** + * `localhost` resolves to several addresses, so Node fails with an + * AggregateError whose own message is empty + */ + const bus = createBus('bus-1', {}, { host: 'localhost', port: 1 }) + cleanup(() => bus.transport.disconnect()) + + await until(() => bus.errors.length >= 2) + + for (const error of bus.errors) { + assert.match(error.message, /\S/) + } + assert.isTrue(bus.errors.some(error => error.message.includes('ECONNREFUSED'))) + }) + + test('reports a key too long to send and clears its namespace instead', async ({ + assert, + cleanup, + }) => { + const bus1 = createBus('bus-1') + const bus2 = createBus('bus-2') + cleanup(() => closeAll(bus1, bus2)) + + await bus2.subscribe('channel') + await waitForPath(bus1, bus2, 'channel') + bus2.received.length = 0 + + await bus1.transport.publish('channel', { + type: CacheBusMessageType.Delete, + namespace: 'users', + keys: ['ok', 'x'.repeat(9000)], + }) + + await until(() => bus2.received.length === 1) + assert.deepEqual(bus2.received[0].message, { + type: CacheBusMessageType.Clear, + namespace: 'users', + keys: [], + }) + assert.lengthOf(bus1.errors, 1) + assert.include(bus1.errors[0].message, 'namespace "users" is cleared') + }) + + test('reports messages whose namespace is too long to send', async ({ assert, cleanup }) => { + const bus = createBus('bus-1') + cleanup(() => bus.transport.disconnect()) + await until(() => bus.reconnects === 1) + + await bus.transport.publish('channel', { + type: CacheBusMessageType.Set, + namespace: 'n'.repeat(9000), + keys: ['a'], + }) + + assert.lengthOf(bus.errors, 1) + assert.include(bus.errors[0].message, 'namespace is too long') + }) +}) + +test.group('Postgres bus | with BentoCache', group => { + group.each.timeout(30_000) + + function createCache(applicationName: string) { + return new BentoCache({ + default: 'cache', + stores: { + cache: bentostore() + .useL1Layer(memoryDriver({})) + .useBus( + postgresBusDriver({ + connection: { ...PG_CONNECTION, application_name: applicationName }, + }), + ), + }, + }) + } + + test('invalidates other instances on set, delete and clear', async ({ assert, cleanup }) => { + const applicationName = `bentocache-test-${randomUUID().slice(0, 8)}` + const cache1 = createCache(applicationName) + const cache2 = createCache(applicationName) + cleanup(async () => { + await Promise.all([cache1.disconnectAll(), cache2.disconnectAll()]) + }) + + /** + * Each store opens its two connections when it is first used + */ + await cache1.get({ key: 'warmup' }) + await cache2.get({ key: 'warmup' }) + await until(async () => (await backendCount(applicationName)) === 4) + + const users1 = cache1.namespace('users') + const users2 = cache2.namespace('users') + + /** + * Retry until the listeners are ready: the first sets may be published + * before the other instance listens + */ + await until(async () => { + await cache2.set({ key: 'foo', value: 'old' }) + await users2.set({ key: 'bar', value: 'old' }) + await cache1.set({ key: 'foo', value: 'new' }) + await users1.set({ key: 'bar', value: 'new' }) + await sleep(100) + return ( + (await cache2.get({ key: 'foo' })) === undefined && + (await users2.get({ key: 'bar' })) === undefined + ) + }) + + await cache2.set({ key: 'foo', value: 'old' }) + await users2.set({ key: 'bar', value: 'old' }) + await cache1.delete({ key: 'foo' }) + await until(async () => (await cache2.get({ key: 'foo' })) === undefined) + assert.equal(await users2.get({ key: 'bar' }), 'old') + + await users1.clear() + await until(async () => (await users2.get({ key: 'bar' })) === undefined) + }) +}) + +test.group('Postgres bus | batching', () => { + function queued(channel: string, count: number, payloadLength = 10): QueuedPublish { + const notifications = Array.from({ length: count }, (_, i): Notification => [ + channel, + `${i}`.padEnd(payloadLength, 'p'), + ]) + return { notifications, sent: 0, resolve: () => {}, reject: () => {} } + } + + test('puts several small messages in one transaction', ({ assert }) => { + const queue = [queued('a', 2), queued('b', 3)] + const { notifications, completed } = takeBatch(queue) + + assert.lengthOf(notifications, 5) + assert.lengthOf(completed, 2) + assert.lengthOf(queue, 0) + }) + + test('caps a transaction by notification count', ({ assert }) => { + const queue = [queued('a', 700), queued('b', 700)] + + const first = takeBatch(queue, 1000) + assert.lengthOf(first.notifications, 1000) + assert.lengthOf(first.completed, 1) + assert.equal(queue[0].sent, 300) + + const second = takeBatch(queue, 1000) + assert.lengthOf(second.notifications, 400) + assert.lengthOf(second.completed, 1) + assert.lengthOf(queue, 0) + }) + + test('splits one large message by size and completes it with its last part', ({ assert }) => { + const message = queued('channel', 2756, 7990) + const next = queued('next', 1) + const queue = [message, next] + const batches = [] + + while (queue.length > 0) batches.push(takeBatch(queue)) + + for (const batch of batches) { + const bytes = batch.notifications.reduce((sum, [c, p]) => sum + c.length + p.length, 0) + assert.isAtMost(bytes, MAX_BYTES_PER_TRANSACTION) + assert.isAtMost(batch.notifications.length, MAX_NOTIFICATIONS_PER_TRANSACTION) + } + + assert.isAbove(batches.length, 20) + assert.deepEqual( + batches.flatMap(batch => batch.notifications), + [...message.notifications, ...next.notifications], + ) + assert.deepEqual( + batches.flatMap(batch => batch.completed).map(item => item.notifications[0][0]), + ['channel', 'next'], + ) + }) + + test('always takes at least one notification', ({ assert }) => { + const queue = [queued('a', 2, 100)] + const { notifications } = takeBatch(queue, 1000, 10) + + assert.lengthOf(notifications, 1) + assert.equal(queue[0].sent, 1) + }) +}) + +test.group('Postgres bus | heartbeat stalls', () => { + test('does not count a stall against heartbeats in flight', ({ assert }) => { + /** + * Committed at the 1,000 tick, then the process froze: the next 5 s + * tick ran at 25,000 instead of 6,000. The heartbeat's age is the + * 5,000 ms the process was running, not 24,000. + */ + const inFlight = new Map([[7, 1000]]) + const lastTick = 1000 + const now = 25_000 + discountStall(inFlight, now - lastTick - 5000) + + assert.equal(now - inFlight.get(7)!, 5000) + }) + + test('leaves heartbeats alone when the timer fired on time or early', ({ assert }) => { + const inFlight = new Map([[7, 1000]]) + discountStall(inFlight, 0) + discountStall(inFlight, -3) + + assert.equal(inFlight.get(7), 1000) + }) + + test('checks heartbeats three times per timeout', ({ assert }) => { + assert.equal(heartbeatCheckPeriod(15_000), 5000) + assert.equal(heartbeatCheckPeriod(1000), 333) + assert.equal(heartbeatCheckPeriod(1), 1) + }) +}) + +test.group('Postgres bus | options', () => { + const connection = 'postgres://localhost/test' + + test('rejects durations that Node timers cannot represent', ({ assert }) => { + const invalid: Array> = [ + { publishTimeout: '30d' }, + { publishTimeout: 2 ** 31 }, + { publishTimeout: 0.5 }, + { publishTimeout: 0 }, + { publishTimeout: '0s' }, + { publishTimeout: 'abc' }, + { heartbeat: { interval: '30d' } }, + { heartbeat: { interval: 0.0001 } }, + { heartbeat: { timeout: '25d' } }, + ] + + for (const options of invalid) { + assert.throws( + () => postgresBusDriver({ connection, ...options }), + /postgresBusDriver: ".+" must be a duration between 1ms and 2147483647ms/, + ) + } + }) + + test('accepts the largest durations', ({ assert }) => { + assert.doesNotThrow(() => postgresBusDriver({ connection, publishTimeout: 2 ** 31 - 1 })) + assert.doesNotThrow(() => postgresBusDriver({ connection, heartbeat: { interval: '20d' } })) + }) + + test('accepts a batchDelay of 0 and rejects negative or too long ones', ({ assert }) => { + assert.doesNotThrow(() => postgresBusDriver({ connection, batchDelay: 0 })) + assert.doesNotThrow(() => postgresBusDriver({ connection, batchDelay: '1s' })) + + for (const batchDelay of [-1, '30d', 'abc']) { + assert.throws( + () => postgresBusDriver({ connection, batchDelay }), + /postgresBusDriver: "batchDelay" must be a duration between 0ms and 2147483647ms/, + ) + } + }) +}) diff --git a/packages/bentocache/tests/bus/postgres_encoding.spec.ts b/packages/bentocache/tests/bus/postgres_encoding.spec.ts new file mode 100644 index 0000000..487762c --- /dev/null +++ b/packages/bentocache/tests/bus/postgres_encoding.spec.ts @@ -0,0 +1,247 @@ +import { test } from '@japa/runner' + +import { CacheBusMessageType } from '../../src/types/bus.js' +import type { CacheBusMessage } from '../../src/types/bus.js' +import { + MAX_PAYLOAD_BYTES, + decodeMessage, + encodeMessage, +} from '../../src/bus/transports/postgres/encoder.js' +import { + MAX_CHANNEL_BYTES, + quoteChannel, + toPostgresChannel, +} from '../../src/bus/transports/postgres/channel.js' + +const BUS_ID = 'k3x9q2m7p1z8w4n6b5v0c2ds' + +test.group('Postgres bus | channel names', () => { + test('keeps names of up to 63 bytes as is', ({ assert }) => { + assert.equal(toPostgresChannel('bentocache.notifications'), 'bentocache.notifications') + + const exact = 'a'.repeat(MAX_CHANNEL_BYTES) + assert.equal(toPostgresChannel(exact), exact) + }) + + test('shortens longer names to 63 bytes with a hash suffix', ({ assert }) => { + const name = `bentocache.notifications:${'store'.repeat(20)}` + const channel = toPostgresChannel(name) + + assert.isAtMost(Buffer.byteLength(channel), MAX_CHANNEL_BYTES) + assert.match(channel, /^bentocache\.notifications:store.*~[0-9a-f]{16}$/) + assert.equal(toPostgresChannel(name), channel) + }) + + test('keeps long names that share a prefix distinct', ({ assert }) => { + const prefix = 'x'.repeat(80) + assert.notEqual(toPostgresChannel(`${prefix}a`), toPostgresChannel(`${prefix}b`)) + }) + + test('turns names with characters outside printable ASCII into ASCII', ({ assert }) => { + const channel = toPostgresChannel('bentocache.notifications:магазин') + + assert.match(channel, /^bentocache\.notifications:_{7}~[0-9a-f]{16}$/) + assert.equal(toPostgresChannel('bentocache.notifications:магазин'), channel) + }) + + test('replaces each character, not each UTF-16 unit or byte, by one underscore', ({ assert }) => { + assert.match(toPostgresChannel('a😀b'), /^a_b~[0-9a-f]{16}$/) + assert.match(toPostgresChannel('a\u0000b\nc'), /^a_b_c~[0-9a-f]{16}$/) + }) + + test('keeps non-ASCII names that look the same in ASCII distinct', ({ assert }) => { + const names = [ + 'store:日本', + 'store:中国', + 'store:__', + `store:e${String.fromCodePoint(0x301)}`, // é as e + combining accent + `store:${String.fromCodePoint(0xe9)}`, // é as one character + ] + const channels = names.map(toPostgresChannel) + + assert.lengthOf(new Set(channels), names.length) + assert.equal(channels[2], 'store:__') + }) + + test('cuts long non-ASCII names to 63 bytes of printable ASCII', ({ assert }) => { + for (const name of ['日本'.repeat(40), '😀'.repeat(80), `${'x'.repeat(60)}日本`]) { + const channel = toPostgresChannel(name) + + assert.isAtMost(Buffer.byteLength(channel), MAX_CHANNEL_BYTES) + assert.match(channel, /^[\x20-\x7e]+~[0-9a-f]{16}$/) + } + }) + + test('hashes an empty name, which Postgres rejects', ({ assert }) => { + assert.match(toPostgresChannel(''), /^~[0-9a-f]{16}$/) + }) + + test('quotes channel names for LISTEN', ({ assert }) => { + assert.equal(quoteChannel('bentocache.notifications'), '"bentocache.notifications"') + assert.equal(quoteChannel('a"b'), '"a""b"') + }) +}) + +test.group('Postgres bus | encoding', () => { + test('round trips every message type', ({ assert }) => { + for (const type of Object.values(CacheBusMessageType)) { + const message: CacheBusMessage = { + type, + namespace: 'users', + keys: type === 'clear' ? [] : ['a', 'b'], + } + const { payloads } = encodeMessage(BUS_ID, message) + + assert.lengthOf(payloads, 1) + assert.deepEqual(decodeMessage(payloads[0]), { busId: BUS_ID, payload: message }) + } + }) + + test('uses the compact array format with a version number', ({ assert }) => { + const { payloads } = encodeMessage(BUS_ID, { + type: CacheBusMessageType.Set, + namespace: 'bentocache', + keys: ['user:42'], + }) + + assert.deepEqual(payloads, [`[1,"${BUS_ID}",1,"bentocache",["user:42"]]`]) + }) + + test('encodes a missing namespace as an empty string', ({ assert }) => { + const { payloads } = encodeMessage(BUS_ID, { type: CacheBusMessageType.Delete, keys: ['a'] }) + + assert.deepEqual(decodeMessage(payloads[0])?.payload, { + type: CacheBusMessageType.Delete, + namespace: '', + keys: ['a'], + }) + }) + + test('escapes non-ASCII characters so payloads are plain ASCII', ({ assert }) => { + const message: CacheBusMessage = { + type: CacheBusMessageType.Set, + namespace: 'naïve', + keys: ['café:ü:日本', 'emoji:😀', 'quote:"\\'], + } + const { payloads } = encodeMessage(BUS_ID, message) + + assert.match(payloads[0], /^[\x20-\x7e]+$/) + assert.deepEqual(decodeMessage(payloads[0])?.payload, message) + }) + + test('splits keys across payloads that fit the size limit', ({ assert }) => { + const keys = Array.from({ length: 2000 }, (_, i) => `product:${i}:`.padEnd(40, 'x')) + const result = encodeMessage(BUS_ID, { + type: CacheBusMessageType.Delete, + namespace: 'bentocache', + keys, + }) + + assert.isFalse(result.replacedByClear) + assert.isAbove(result.payloads.length, 1) + + const decodedKeys: string[] = [] + for (const payload of result.payloads) { + assert.isBelow(Buffer.byteLength(payload), 8000) + const decoded = decodeMessage(payload)! + assert.equal(decoded.payload.type, CacheBusMessageType.Delete) + assert.equal(decoded.payload.namespace, 'bentocache') + decodedKeys.push(...decoded.payload.keys) + } + + assert.deepEqual(decodedKeys, keys) + }) + + test('fills payloads up to the size limit', ({ assert }) => { + for (let length = 1; length < 300; length += 7) { + const keys = Array.from({ length: 500 }, (_, i) => `${i}:`.padEnd(length, 'k')) + const { payloads } = encodeMessage(BUS_ID, { + type: CacheBusMessageType.Delete, + namespace: 'ns', + keys, + }) + + for (const [index, payload] of payloads.entries()) { + assert.isAtMost(payload.length, MAX_PAYLOAD_BYTES) + if (index === payloads.length - 1) continue + + const nextKey = decodeMessage(payloads[index + 1])!.payload.keys[0] + assert.isAbove(payload.length + JSON.stringify(nextKey).length + 1, MAX_PAYLOAD_BYTES) + } + } + }) + + test('replaces a message with a key that cannot fit by a namespace clear', ({ assert }) => { + const result = encodeMessage(BUS_ID, { + type: CacheBusMessageType.Set, + namespace: 'users', + keys: ['small', 'k'.repeat(8000)], + }) + + assert.isTrue(result.replacedByClear) + assert.lengthOf(result.payloads, 1) + assert.deepEqual(decodeMessage(result.payloads[0])?.payload, { + type: CacheBusMessageType.Clear, + namespace: 'users', + keys: [], + }) + }) + + test('counts escaped characters when checking the size limit', ({ assert }) => { + const result = encodeMessage(BUS_ID, { + type: CacheBusMessageType.Set, + namespace: 'users', + keys: ['日'.repeat(1500)], + }) + + assert.isTrue(result.replacedByClear) + }) + + test('reports a namespace that is too long to send', ({ assert }) => { + const result = encodeMessage(BUS_ID, { + type: CacheBusMessageType.Set, + namespace: 'n'.repeat(8000), + keys: ['a'], + }) + + assert.isTrue(result.tooLarge) + assert.deepEqual(result.payloads, []) + }) + + test('ignores fields appended by newer releases', ({ assert }) => { + const expected = { + busId: BUS_ID, + payload: { type: CacheBusMessageType.Delete, namespace: 'users', keys: ['a', 'b'] }, + } + + for (const extra of ['"sender",42', '{"seq":1},[1,2]', 'null']) { + const payload = `[1,"${BUS_ID}",3,"users",["a","b"],${extra}]` + assert.deepEqual(decodeMessage(payload), expected, payload) + } + }) + + test('rejects unknown message types', ({ assert }) => { + assert.throws( + () => encodeMessage(BUS_ID, { type: 'nope' as any, keys: [] }), + 'Unknown bus message type: nope', + ) + }) + + test('ignores payloads it does not understand', ({ assert }) => { + const invalid = [ + '', + 'not json', + '{"busId":"a","payload":{}}', + '[]', + `[2,"${BUS_ID}",1,"",["a"]]`, + `[1,"${BUS_ID}",9,"",["a"]]`, + `[1,"${BUS_ID}","1","",["a"]]`, + `[1,42,1,"",["a"]]`, + `[1,"${BUS_ID}",1,null,["a"]]`, + `[1,"${BUS_ID}",1,"","a"]`, + `[1,"${BUS_ID}",1,"",[1]]`, + ] + + for (const payload of invalid) assert.isUndefined(decodeMessage(payload), payload) + }) +})