Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/31723-cache-derived-connection-liveness.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<number> {
const server = createServer();
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const { port } = server.address() as AddressInfo;
await new Promise<void>((r) => server.close(() => r()));
return port;
}

/** Records the connection the cache derives through `base.duplicate()`. */
function captureDerived<C extends { duplicate?: () => 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<void> {
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<string, Array<() => Promise<void>>>): Promise<void> {
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);
});
});
67 changes: 66 additions & 1 deletion packages/services/service-cache/src/cache-service-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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(
Expand All @@ -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<ClusterDriverLiveness['watchConnection']>[0];

function isWatchable(client: unknown): client is WatchableConnection {
const c = client as Partial<Record<'on' | 'off', unknown>> | 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`
Expand Down
18 changes: 3 additions & 15 deletions packages/services/service-cluster-redis/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
41 changes: 41 additions & 0 deletions packages/services/service-cluster/src/cluster-resync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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();
});
});
Loading
Loading