From 5b6732fa37346a46f10e3819cdfa42732ec96b40 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 03:22:12 +0000 Subject: [PATCH 1/2] fix(service-cache): report the derived Redis connection into the cluster driver's liveness The shared cache's connection (base.duplicate()) had no error listener, so every reconnect during a Redis outage printed "[ioredis] Unhandled error event" with a stack. The listener style the redis driver uses is hoisted into service-cluster (ClusterDriverLiveness.watchConnection, reached from a derived connection through watchClusterDriverConnection); the redis driver's watchRedisConnection delegates to it, and the cache plugin watches the connection it derives, detaching before its deliberate quit. Claude-Session: https://claude.ai/code/session_01ADHkmSTGuRMEEW3vjJtdVG Co-authored-by: Claude --- .../src/cache-service-plugin.topology.test.ts | 178 +++++++++++++++++- .../service-cache/src/cache-service-plugin.ts | 67 ++++++- .../service-cluster-redis/src/client.ts | 18 +- .../service-cluster/src/cluster-resync.ts | 65 +++++++ .../services/service-cluster/src/index.ts | 1 + 5 files changed, 311 insertions(+), 18 deletions(-) diff --git a/packages/services/service-cache/src/cache-service-plugin.topology.test.ts b/packages/services/service-cache/src/cache-service-plugin.topology.test.ts index f9dc875536d..018b3638053 100644 --- a/packages/services/service-cache/src/cache-service-plugin.topology.test.ts +++ b/packages/services/service-cache/src/cache-service-plugin.topology.test.ts @@ -20,10 +20,18 @@ import RedisMock from 'ioredis-mock'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { ObjectKernel } from '@objectstack/core'; -import { ClusterServicePlugin, offerClusterDriverConnection } from '@objectstack/service-cluster'; +import { createServer, type AddressInfo } from 'node:net'; +import { + ClusterDriverLiveness, + ClusterServicePlugin, + offerClusterDriverConnection, + offerClusterDriverLiveness, + onClusterResync, + readClusterDriverHealth, +} from '@objectstack/service-cluster'; // Importing the driver registers `redis` with `defineCluster()` — at module // eval, so no test body pays the cold load. -import '@objectstack/service-cluster-redis'; +import { createRedisClient } from '@objectstack/service-cluster-redis'; import { CacheServicePlugin, planCacheAdapter, type CacheAdapterPlanInput } from './cache-service-plugin.js'; import { MemoryCacheAdapter } from './memory-cache-adapter.js'; @@ -273,3 +281,169 @@ describe('real ObjectKernel boots — cluster plugin + redis driver over ioredis await expect(boot(new CacheServicePlugin({ adapter: 'memory' }), mockClient())).rejects.toThrow(/per-process cache/); }); }); + +describe('the derived connection reports its outage — never an unhandled error event', () => { + /** A port nothing listens on: every connect attempt is refused at once. */ + async function refusedPort(): Promise { + const server = createServer(); + await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); + const { port } = server.address() as AddressInfo; + await new Promise((r) => server.close(() => r())); + return port; + } + + /** Records the connection the cache derives through `base.duplicate()`. */ + function captureDerived unknown }>(base: C): { client?: any } { + const box: { client?: any } = {}; + const original = base.duplicate!.bind(base); + base.duplicate = () => (box.client = original()); + return box; + } + + async function until(check: () => boolean, what: string): Promise { + const deadline = Date.now() + 5_000; + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((r) => setTimeout(r, 10)); + } + } + + function livenessFor(cluster: object, port?: number) { + const warns: string[] = []; + const liveness = new ClusterDriverLiveness({ + driver: 'redis', + nodeId: 'n1', + target: port === undefined ? undefined : `127.0.0.1:${port}`, + logger: { warn: (m) => warns.push(m), info: () => {} }, + }); + offerClusterDriverLiveness(cluster, liveness); + return { liveness, warns }; + } + + async function shutdown(hooks: Map Promise>>): Promise { + for (const fn of hooks.get('kernel:shutdown') ?? []) await fn(); + } + + /** Real ioredis against a refused port, with a password in the URL and a fast reconnect. */ + async function refusedRedis() { + const port = await refusedPort(); + const base = createRedisClient({ + url: `redis://:s3cret@127.0.0.1:${port}`, + options: { retryStrategy: () => 20, maxRetriesPerRequest: 1 }, + }); + const derived = captureDerived(base); + const cluster = { driver: 'redis', nodeId: 'n1' }; + offerClusterDriverConnection(cluster, { driver: 'redis', client: base, keyPrefix: 'os:' }); + return { port, base, derived, cluster }; + } + + /** Init a multi-node cache over `cluster`, fail a GET, and let the derived connection retry a few times. */ + async function failThroughOutage(cluster: object, derived: { client?: any }) { + vi.stubEnv('OS_CLUSTER_REPLICAS', '2'); + const { ctx, services, logs, hooks } = makeCtx({ cluster }); + await new CacheServicePlugin().init(ctx); + let reconnects = 0; + derived.client.on('reconnecting', () => { reconnects += 1; }); + await expect((services.get('cache') as RedisCacheAdapter).get('k')).rejects.toThrow(); + await until(() => reconnects >= 3, 'three reconnect attempts'); + return { logs, hooks }; + } + + const unhandledLines = (spy: { mock: { calls: unknown[][] } }) => + spy.mock.calls.filter((call) => String(call[0]).includes('Unhandled error event')); + + it('a refused store over the redis driver: no unhandled error event, ONE outage warning in the driver\'s liveness, no credential', async () => { + const { port, base, derived, cluster } = await refusedRedis(); + const { warns } = livenessFor(cluster, port); + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const { logs, hooks } = await failThroughOutage(cluster, derived); + expect(unhandledLines(consoleError)).toEqual([]); + expect(warns).toHaveLength(1); + expect(warns[0]).toMatch(/lost its connection/); + expect(warns.join('\n')).not.toContain('s3cret'); + expect(readClusterDriverHealth(cluster)).toMatchObject({ state: 'down', outages: 1 }); + // The plugin adds no outage line of its own. + expect(logs.filter(([level]) => level !== 'info')).toEqual([]); + await shutdown(hooks); + } finally { + consoleError.mockRestore(); + derived.client?.disconnect(); + base.disconnect(); + } + }); + + it('a driver that offers no liveness: still no unhandled error event — the outage is logged once through the plugin\'s logger', async () => { + const { base, derived, cluster } = await refusedRedis(); + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const { logs, hooks } = await failThroughOutage(cluster, derived); + expect(unhandledLines(consoleError)).toEqual([]); + const warnings = logs.filter(([level]) => level === 'warn').map(([, message]) => message); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toMatch(/lost its connection/); + expect(warnings[0]).not.toContain('s3cret'); + await shutdown(hooks); + } finally { + consoleError.mockRestore(); + derived.client?.disconnect(); + base.disconnect(); + } + }); + + it('a deliberate shutdown is not an outage: the cache detaches before it quits its connection', async () => { + vi.stubEnv('OS_CLUSTER_REPLICAS', '2'); + const base = mockClient(); + const derived = captureDerived(base as { duplicate?: () => unknown }); + const cluster = redisCluster(base); + const { warns } = livenessFor(cluster); + const { ctx, hooks } = makeCtx({ cluster }); + await new CacheServicePlugin().init(ctx); + derived.client.emit('ready'); + expect(readClusterDriverHealth(cluster)?.state).toBe('up'); + // ioredis emits `close` when the quit closes the socket. + const quit = derived.client.quit.bind(derived.client); + derived.client.quit = async () => { derived.client.emit('close'); return quit(); }; + + await shutdown(hooks); + + expect(warns).toEqual([]); + expect(readClusterDriverHealth(cluster)).toMatchObject({ state: 'up', outages: 0 }); + }); + + it('`cluster.resync` waits for the cache\'s connection too — the reason it shares the driver\'s liveness', async () => { + vi.stubEnv('OS_CLUSTER_REPLICAS', '2'); + const base = mockClient() as any; + const derived = captureDerived(base); + const cluster = redisCluster(base); + const { liveness, warns } = livenessFor(cluster); + liveness.watchConnection(base, 'command'); + const { ctx, hooks } = makeCtx({ cluster }); + await new CacheServicePlugin().init(ctx); + let resyncs = 0; + onClusterResync(cluster, () => { resyncs += 1; }); + + derived.client.emit('error', new Error('ECONNREFUSED')); + base.emit('error', new Error('ECONNREFUSED')); + base.emit('ready'); + expect(resyncs).toBe(0); + expect(readClusterDriverHealth(cluster)?.state).toBe('down'); + + derived.client.emit('ready'); + expect(resyncs).toBe(1); + expect(warns).toHaveLength(1); + await shutdown(hooks); + }); + + it('CONTROL: an injected client is its owner\'s — the cache attaches no listener to it', async () => { + vi.stubEnv('OS_CLUSTER_REPLICAS', '2'); + const own = mockClient() as any; + const before = ['error', 'close', 'ready'].map((e) => own.listenerCount(e)); + const cluster = redisCluster(); + livenessFor(cluster); + const { ctx, hooks } = makeCtx({ cluster }); + await new CacheServicePlugin({ redis: { client: own } }).init(ctx); + expect(['error', 'close', 'ready'].map((e) => own.listenerCount(e))).toEqual(before); + await shutdown(hooks); + }); +}); diff --git a/packages/services/service-cache/src/cache-service-plugin.ts b/packages/services/service-cache/src/cache-service-plugin.ts index ee76efc16b5..bdd103cc42e 100644 --- a/packages/services/service-cache/src/cache-service-plugin.ts +++ b/packages/services/service-cache/src/cache-service-plugin.ts @@ -6,7 +6,13 @@ import { NoopMetricsRegistry, type MetricsRegistry, } from '@objectstack/observability'; -import { declaresMultiNode, readClusterDriverConnection } from '@objectstack/service-cluster'; +import { + ClusterDriverLiveness, + declaresMultiNode, + readClusterDriverConnection, + readClusterDriverHealth, + watchClusterDriverConnection, +} from '@objectstack/service-cluster'; import { MemoryCacheAdapter } from './memory-cache-adapter.js'; import type { MemoryCacheAdapterOptions } from './memory-cache-adapter.js'; import { RedisCacheAdapter, type RedisCacheClient } from './redis-cache-adapter.js'; @@ -280,7 +286,15 @@ export class CacheServicePlugin implements Plugin { ownsClient: plan.ownsClient, }); ctx.registerService('cache', cache); + // Only the connection this plugin derived is watched: an injected client + // and a borrowed driver connection belong to their owners, who listen. + const unwatch = + plan.ownsClient && plan.source === 'cluster-driver' + ? watchDerivedConnection(readRegisteredCluster(ctx), plan.client, ctx.logger) + : () => {}; ctx.hook('kernel:shutdown', async () => { + // Detach first: the close the deliberate quit causes is not an outage. + unwatch(); await cache.close(); }); ctx.logger.info( @@ -299,6 +313,57 @@ export class CacheServicePlugin implements Plugin { } } +/** The events a derived ioredis connection emits, checked structurally (a test double may have none). */ +type WatchableConnection = Parameters[0]; + +function isWatchable(client: unknown): client is WatchableConnection { + const c = client as Partial> | null; + return !!c && typeof c.on === 'function' && typeof c.off === 'function'; +} + +/** + * Watch the connection this plugin derived from the cluster driver's, so an + * outage is never an unhandled `error` event (ioredis prints one, with a stack, + * per reconnect attempt). Returns the disposer to call before the cache quits. + * + * - The driver offers a liveness (the redis driver does): the connection + * reports into it as `'cache'`, the same way the driver's own connections + * do — one outage logs once across all of them, and `cluster.resync` waits + * for this connection too. + * - It offers none (a driver released before the liveness offer): the + * connection gets a liveness of its own, so its outage is still logged once, + * credential-free, through this plugin's logger — never one line per + * reconnect attempt, and never silently swallowed. Nothing subscribes to + * that liveness's resync. + */ +function watchDerivedConnection( + cluster: unknown, + client: unknown, + logger: PluginContext['logger'], +): () => void { + if (!isWatchable(client)) return () => {}; + if (readClusterDriverHealth(cluster) !== undefined) { + return watchClusterDriverConnection(cluster, client, 'cache'); + } + const own = new ClusterDriverLiveness({ + driver: describeDriver(cluster) ?? 'redis', + nodeId: describeNodeId(cluster) ?? 'node', + logger, + }); + const unwatch = own.watchConnection(client, 'cache'); + return () => { + unwatch(); + own.close(); + }; +} + +/** The registered cluster's node id, or `undefined`. */ +function describeNodeId(cluster: unknown): string | undefined { + if (!cluster || typeof cluster !== 'object') return undefined; + const nodeId = (cluster as { nodeId?: unknown }).nodeId; + return typeof nodeId === 'string' ? nodeId : undefined; +} + /** * The registered `cluster` service, or `undefined` when none is. Read only by * the branches of {@link planCacheAdapter} that need it; `optionalDependencies` diff --git a/packages/services/service-cluster-redis/src/client.ts b/packages/services/service-cluster-redis/src/client.ts index aed728cee60..1c46a226fb4 100644 --- a/packages/services/service-cluster-redis/src/client.ts +++ b/packages/services/service-cluster-redis/src/client.ts @@ -111,21 +111,9 @@ export function watchRedisConnection( liveness: ClusterDriverLiveness, source: string, ): () => void { - const onError = (err: unknown): void => liveness.reportDown(source, err); - const onClose = (): void => liveness.reportDown(source); - const onReady = (): void => liveness.reportUp(source); - client.on('error', onError); - client.on('close', onClose); - client.on('ready', onReady); - if (client.status === 'ready') liveness.reportUp(source); - let watching = true; - return () => { - if (!watching) return; - watching = false; - client.off('error', onError); - client.off('close', onClose); - client.off('ready', onReady); - }; + // The one listener style (`ClusterDriverLiveness.watchConnection`), shared + // with the connections derived from this one (`watchClusterDriverConnection`). + return liveness.watchConnection(client, source); } /** diff --git a/packages/services/service-cluster/src/cluster-resync.ts b/packages/services/service-cluster/src/cluster-resync.ts index bd74e61721a..1d03db94dbb 100644 --- a/packages/services/service-cluster/src/cluster-resync.ts +++ b/packages/services/service-cluster/src/cluster-resync.ts @@ -106,6 +106,17 @@ export interface ClusterDriverLivenessOptions { now?: () => number; } +/** + * The slice of a connection {@link ClusterDriverLiveness.watchConnection} + * listens on — an ioredis client's, declared structurally so this package + * takes no dependency on a Redis client library. + */ +interface WatchedConnection { + on(event: 'error' | 'close' | 'ready', listener: (...args: unknown[]) => void): unknown; + off(event: 'error' | 'close' | 'ready', listener: (...args: unknown[]) => void): unknown; + readonly status?: string; +} + /** * The connection state machine a remote driver feeds. The driver reports each * connection it holds by a stable `source` name (`'command'`, `'subscriber'`): @@ -180,6 +191,38 @@ export class ClusterDriverLiveness { this.emitResync({ event: CLUSTER_RESYNC_EVENT, driver: this.driver, nodeId: this.nodeId, outageMs, at }); } + /** + * Feed this liveness from one connection, reported as `source`: `error` + * and an unexpected `close` report it down, `ready` reports it up (as does + * a connection already ready when watched). The `error` listener is also + * what keeps the client from treating its failures as unhandled — ioredis + * otherwise prints `[ioredis] Unhandled error event` with a stack on every + * reconnect attempt. + * + * The one listener style for every connection a remote driver's store is + * reached through: the driver's own (the redis driver's + * `watchRedisConnection` delegates here) and any connection derived from + * one ({@link watchClusterDriverConnection}). Returns the disposer; call it + * BEFORE a deliberate `quit()`, so that close is not reported as an outage. + */ + watchConnection(client: WatchedConnection, source: string): () => void { + const onError = (err: unknown): void => this.reportDown(source, err); + const onClose = (): void => this.reportDown(source); + const onReady = (): void => this.reportUp(source); + client.on('error', onError); + client.on('close', onClose); + client.on('ready', onReady); + if (client.status === 'ready') this.reportUp(source); + let watching = true; + return () => { + if (!watching) return; + watching = false; + client.off('error', onError); + client.off('close', onClose); + client.off('ready', onReady); + }; + } + /** Stop reporting: a deliberate close is not an outage. Idempotent. */ close(): void { this.closed = true; @@ -297,6 +340,28 @@ export function onClusterResync(cluster: unknown, handler: ClusterResyncHandler) return liveness.onResync(handler); } +/** + * Report `client` — a connection derived from `cluster`'s driver connection + * (`readClusterDriverConnection(...).client.duplicate()`) — into the driver's + * liveness as `source`. One outage across every connection to the store then + * logs once, and `cluster.resync` waits until this connection is back too. + * See {@link ClusterDriverLiveness.watchConnection}: call the returned + * disposer before quitting `client`. + * + * On a cluster whose driver offers no liveness this attaches nothing and + * returns a disposer that does nothing (`readClusterDriverHealth(cluster)` is + * `undefined` in exactly that case, for a caller that must still listen). + */ +export function watchClusterDriverConnection( + cluster: unknown, + client: WatchedConnection, + source: string, +): () => void { + const liveness = readLiveness(cluster); + if (!liveness) return () => {}; + return liveness.watchConnection(client, source); +} + /** * `cluster`'s driver connection health, or `undefined` when its driver offers * none (the in-process `memory` driver). Read it per probe: it is a snapshot. diff --git a/packages/services/service-cluster/src/index.ts b/packages/services/service-cluster/src/index.ts index e0f855c7dfc..eefd7097f79 100644 --- a/packages/services/service-cluster/src/index.ts +++ b/packages/services/service-cluster/src/index.ts @@ -83,6 +83,7 @@ export { offerClusterDriverLiveness, onClusterResync, readClusterDriverHealth, + watchClusterDriverConnection, describeConnectionError, redactCredentials, type ClusterResyncEvent, From c9c845d29e5d1acf4475a078aadfca1bed8ea176 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 03:23:59 +0000 Subject: [PATCH 2/2] test(service-cluster): pin watchClusterDriverConnection; changeset Claude-Session: https://claude.ai/code/session_01ADHkmSTGuRMEEW3vjJtdVG Co-authored-by: Claude --- ...31723-cache-derived-connection-liveness.md | 16 ++++++++ .../src/cluster-resync.test.ts | 41 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 .changeset/31723-cache-derived-connection-liveness.md diff --git a/.changeset/31723-cache-derived-connection-liveness.md b/.changeset/31723-cache-derived-connection-liveness.md new file mode 100644 index 00000000000..d7b31522ce6 --- /dev/null +++ b/.changeset/31723-cache-derived-connection-liveness.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-cache': patch +'@objectstack/service-cluster': patch +'@objectstack/service-cluster-redis': patch +--- + +fix(service-cache): the shared cache's Redis connection reports its outage once instead of printing an unhandled error per reconnect + +Clause-②: yes (widening) +Metadata-protocol: none + +During a Redis outage, the connection the shared cache derives from the redis cluster driver's (`duplicate()`) had no `error` listener. Every reconnect attempt on every replica printed `[ioredis] Unhandled error event` with a stack, which buried the single outage warning operators need. + +- `@objectstack/service-cluster`: new `watchClusterDriverConnection(cluster, client, source)` reports a connection derived from the driver's into the driver's liveness. It returns a disposer and attaches nothing when the driver offers no liveness. `ClusterDriverLiveness` gains `watchConnection(client, source)`, the one listener style both use. +- `@objectstack/service-cluster-redis`: `watchRedisConnection` delegates to `ClusterDriverLiveness.watchConnection`. Its signature and behaviour are unchanged. +- `@objectstack/service-cache`: the plugin watches the connection it derives, as source `'cache'`. One outage now logs one warning across all of the driver's connections, and `cluster.resync` waits until the cache's connection is back too. If the driver offers no liveness (a redis driver released before the liveness offer), the connection gets a liveness of its own, so its outage is still logged once, without credentials, through the plugin's logger. The plugin detaches before its deliberate `quit()` on shutdown, so a shutdown is not reported as an outage. An injected `redis.client` belongs to its owner and gets no listener, and the memory cache is unchanged. diff --git a/packages/services/service-cluster/src/cluster-resync.test.ts b/packages/services/service-cluster/src/cluster-resync.test.ts index 888ae360075..184134ee276 100644 --- a/packages/services/service-cluster/src/cluster-resync.test.ts +++ b/packages/services/service-cluster/src/cluster-resync.test.ts @@ -17,7 +17,9 @@ import { onClusterResync, readClusterDriverHealth, redactCredentials, + watchClusterDriverConnection, } from './cluster-resync.js'; +import { EventEmitter } from 'node:events'; import { defineCluster } from './cluster.js'; function makeLiveness() { @@ -164,3 +166,42 @@ describe('the offer on the cluster instance — onClusterResync / readClusterDri await cluster.close(); }); }); + +describe('watchClusterDriverConnection — a derived connection joins the driver\'s liveness', () => { + function connection(status?: string) { + return Object.assign(new EventEmitter(), { status }); + } + const counts = (c: EventEmitter) => ['error', 'close', 'ready'].map((e) => c.listenerCount(e)); + + it('reports into the offered liveness as its source; the disposer detaches all three listeners', () => { + const cluster = {}; + const { liveness, logger } = makeLiveness(); + offerClusterDriverLiveness(cluster, liveness); + const conn = connection('ready'); + const unwatch = watchClusterDriverConnection(cluster, conn, 'cache'); + expect(readClusterDriverHealth(cluster)?.state).toBe('up'); + expect(counts(conn)).toEqual([1, 1, 1]); + + conn.emit('error', new Error('ECONNREFUSED')); + conn.emit('error', new Error('ECONNREFUSED')); + expect(readClusterDriverHealth(cluster)).toMatchObject({ state: 'down', outages: 1 }); + expect(logger.warn).toHaveBeenCalledTimes(1); + conn.emit('ready'); + expect(readClusterDriverHealth(cluster)?.state).toBe('up'); + + unwatch(); + unwatch(); + expect(counts(conn)).toEqual([0, 0, 0]); + conn.emit('close'); + expect(readClusterDriverHealth(cluster)?.state).toBe('up'); + }); + + it('CONTROL — no liveness offered (the memory driver): attaches nothing, the disposer is inert', async () => { + const cluster = defineCluster({ driver: 'memory' }); + const conn = connection(); + const unwatch = watchClusterDriverConnection(cluster, conn, 'cache'); + expect(counts(conn)).toEqual([0, 0, 0]); + unwatch(); + await cluster.close(); + }); +});