Skip to content

Commit ff8ef4c

Browse files
fix(service-cache): report the derived Redis connection into the cluster driver's liveness (#31787)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi92KQJzU6m7XpwBUwP81YNn2)_ Fixes #31723 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:共享缓存从 Redis 集群驱动另开的那条连接,现在挂上了错误监听,并接入驱动同一个连接状态(liveness);关闭缓存前先摘监听。 - 为什么改:Redis 断线时,这条连接每次重连都打印一大段 "Unhandled error event",把唯一有用的那条断线告警淹没了。 - 风险与回滚:只影响多副本 + Redis 部署的日志与重同步时机;单节点内存缓存不变。回滚即还原本 PR。 - 先看:`packages/services/service-cache/src/cache-service-plugin.ts`(接线与关停顺序)、`packages/services/service-cluster/src/cluster-resync.ts`(`watchConnection` / `watchClusterDriverConnection`)、`packages/services/service-cluster-redis/src/client.ts`(委托)。 - 两分钟验证:`pnpm --filter @objectstack/service-cache exec vitest run src/cache-service-plugin.topology.test.ts`,预期 25/25 通过。 - 需要你做的:无,席位落地。 ## What changes - `@objectstack/service-cluster`: `ClusterDriverLiveness.watchConnection(client, source)` is now the one listener style for a driver's connections (`error` and an unexpected `close` report down, `ready` reports up). The client is typed structurally (`on`/`off`/`status`), so the package stays ioredis-free. New export `watchClusterDriverConnection(cluster, client, source)` resolves the liveness through the module's own private reader and returns a no-op disposer when none is offered. - `@objectstack/service-cluster-redis`: `watchRedisConnection` delegates to `liveness.watchConnection`. Its signature and behaviour are unchanged, and its tests are untouched and green. - `@objectstack/service-cache`: the plugin watches only the connection it derives from the driver's (`duplicate()`), as source `'cache'`. One outage now logs one warning across command, subscriber and cache, and `cluster.resync` waits until the cache's connection is back too. The shutdown hook detaches before `cache.close()` quits that connection, so a deliberate shutdown is not an outage. - No liveness offered (a redis driver released before the liveness offer): the derived connection gets a `ClusterDriverLiveness` of its own, logging through the plugin's logger. Its outage is logged **once**, credential-free, in the same text the driver uses. It is not silent, because the card asks for no silent swallow, and it is never once per attempt. Nothing subscribes to that private liveness's resync. - Not watched: an injected `redis.client` (its owner listens), a borrowed client that cannot `duplicate()`, and the memory cache (no connection). ## Tests New top-level `describe` in `cache-service-plugin.topology.test.ts` (the existing harness file): 1. Real ioredis against a refused port with a password in the URL, over a driver offering a liveness: no `[ioredis] Unhandled error event`, one warning, no credential, health `down`/`outages: 1`, and no plugin-level warning. 2. The same with no liveness offered: no unhandled event, one warning through the plugin's logger, no credential. 3. A deliberate shutdown (the quit emits `close`, as ioredis does) leaves the liveness `up` with 0 outages and no warning. 4. `cluster.resync` waits for the cache's connection: command back gives 0 resyncs, cache back gives exactly 1. 5. CONTROL: an injected client gets no listener. The existing single-node and memory-driver pins (exact log lines) are unchanged and green. New `describe` in `cluster-resync.test.ts`: `watchClusterDriverConnection` reports into the offered liveness and its disposer detaches all three listeners. CONTROL: on the memory driver it attaches nothing. No existing test was edited. ## Acceptance notes - Besides the seat-accepted `watchClusterDriverConnection`, the hoist adds one public member, `ClusterDriverLiveness.watchConnection`. It is the shared inner that `watchRedisConnection` delegates to (a liveness is already in hand there, pubsub's private one included). This is listed for the seat's ruling. - In the no-liveness fallback, the own liveness's warning reuses the driver's text ("Cluster locks, counters and cross-node cache hints fail until it returns…"). That text is accurate for the same store, but it is the driver's wording. ## Verification Head `c9c845d2`. <details><summary>RED on main (src of the four production files restored from origin/main c2bb879, rebuilt)</summary> `Tests 4 failed | 21 passed (25)`. Tests 1 and 2 each saw three `"[ioredis] Unhandled error event:"` lines. Test 3: `expected 'unknown' to be 'up'` (nothing watched). Test 4: `TypeError: liveness.watchConnection is not a function`. The ablation A1 below gives this test its behavioural red. </details> <details><summary>GREEN and package runs</summary> Topology file `Tests 25 passed (25)`. Under the lock, build plus `typecheck` plus `test` for service-cluster (`145/145`, 11 files), service-cluster-redis (`41/41`, 4 files, the real-redis outage test included) and service-cache (`79/79`, 5 files): `VERDICT command-exit 0`. `eslint --no-inline-config` on the three `src` dirs: exit 0. </details> <details><summary>Ablations (scripts/ablation-replace.mjs; each restored, blob == HEAD)</summary> - A1, cache watches nothing (`? (() => {})`): 4 failed (tests 1–4). - A2, detach after quit (`await cache.close(); unwatch();`): 1 failed (test 3, the driver's "lost its connection … connection closed" warning appears). - A3, own-liveness fallback removed (`if (true)`): 1 failed (test 2). - B1, `watchClusterDriverConnection` always a no-op: 1 failed (the service-cluster pin). </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 66 commands on head c9c845d; all 66 ran locally with exit 0. Three first read exit 3 on prerequisites (the teardown self-test's pinned fixture commit, fetched; two gates needing package dists, built with `turbo run build --filter='./packages/**'`, 81/81) and re-ran exit 0. `--ran` reconciliation: "66 derived famil(ies) accounted for — 66 run, 0 NOT-MEASURED". Families CI runs beyond the derived set are left to the PR's check-runs. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmSTGuRMEEW3vjJtdVG)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmSTGuRMEEW3vjJtdVG --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 87d9458 commit ff8ef4c

7 files changed

Lines changed: 368 additions & 18 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/service-cache': patch
3+
'@objectstack/service-cluster': patch
4+
'@objectstack/service-cluster-redis': patch
5+
---
6+
7+
fix(service-cache): the shared cache's Redis connection reports its outage once instead of printing an unhandled error per reconnect
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
- `@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.
15+
- `@objectstack/service-cluster-redis`: `watchRedisConnection` delegates to `ClusterDriverLiveness.watchConnection`. Its signature and behaviour are unchanged.
16+
- `@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.

‎packages/services/service-cache/src/cache-service-plugin.topology.test.ts‎

Lines changed: 176 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,18 @@
2020
import RedisMock from 'ioredis-mock';
2121
import { afterEach, describe, expect, it, vi } from 'vitest';
2222
import { ObjectKernel } from '@objectstack/core';
23-
import { ClusterServicePlugin, offerClusterDriverConnection } from '@objectstack/service-cluster';
23+
import { createServer, type AddressInfo } from 'node:net';
24+
import {
25+
ClusterDriverLiveness,
26+
ClusterServicePlugin,
27+
offerClusterDriverConnection,
28+
offerClusterDriverLiveness,
29+
onClusterResync,
30+
readClusterDriverHealth,
31+
} from '@objectstack/service-cluster';
2432
// Importing the driver registers `redis` with `defineCluster()` — at module
2533
// eval, so no test body pays the cold load.
26-
import '@objectstack/service-cluster-redis';
34+
import { createRedisClient } from '@objectstack/service-cluster-redis';
2735

2836
import { CacheServicePlugin, planCacheAdapter, type CacheAdapterPlanInput } from './cache-service-plugin.js';
2937
import { MemoryCacheAdapter } from './memory-cache-adapter.js';
@@ -273,3 +281,169 @@ describe('real ObjectKernel boots — cluster plugin + redis driver over ioredis
273281
await expect(boot(new CacheServicePlugin({ adapter: 'memory' }), mockClient())).rejects.toThrow(/per-process cache/);
274282
});
275283
});
284+
285+
describe('the derived connection reports its outage — never an unhandled error event', () => {
286+
/** A port nothing listens on: every connect attempt is refused at once. */
287+
async function refusedPort(): Promise<number> {
288+
const server = createServer();
289+
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
290+
const { port } = server.address() as AddressInfo;
291+
await new Promise<void>((r) => server.close(() => r()));
292+
return port;
293+
}
294+
295+
/** Records the connection the cache derives through `base.duplicate()`. */
296+
function captureDerived<C extends { duplicate?: () => unknown }>(base: C): { client?: any } {
297+
const box: { client?: any } = {};
298+
const original = base.duplicate!.bind(base);
299+
base.duplicate = () => (box.client = original());
300+
return box;
301+
}
302+
303+
async function until(check: () => boolean, what: string): Promise<void> {
304+
const deadline = Date.now() + 5_000;
305+
while (!check()) {
306+
if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
307+
await new Promise((r) => setTimeout(r, 10));
308+
}
309+
}
310+
311+
function livenessFor(cluster: object, port?: number) {
312+
const warns: string[] = [];
313+
const liveness = new ClusterDriverLiveness({
314+
driver: 'redis',
315+
nodeId: 'n1',
316+
target: port === undefined ? undefined : `127.0.0.1:${port}`,
317+
logger: { warn: (m) => warns.push(m), info: () => {} },
318+
});
319+
offerClusterDriverLiveness(cluster, liveness);
320+
return { liveness, warns };
321+
}
322+
323+
async function shutdown(hooks: Map<string, Array<() => Promise<void>>>): Promise<void> {
324+
for (const fn of hooks.get('kernel:shutdown') ?? []) await fn();
325+
}
326+
327+
/** Real ioredis against a refused port, with a password in the URL and a fast reconnect. */
328+
async function refusedRedis() {
329+
const port = await refusedPort();
330+
const base = createRedisClient({
331+
url: `redis://:s3cret@127.0.0.1:${port}`,
332+
options: { retryStrategy: () => 20, maxRetriesPerRequest: 1 },
333+
});
334+
const derived = captureDerived(base);
335+
const cluster = { driver: 'redis', nodeId: 'n1' };
336+
offerClusterDriverConnection(cluster, { driver: 'redis', client: base, keyPrefix: 'os:' });
337+
return { port, base, derived, cluster };
338+
}
339+
340+
/** Init a multi-node cache over `cluster`, fail a GET, and let the derived connection retry a few times. */
341+
async function failThroughOutage(cluster: object, derived: { client?: any }) {
342+
vi.stubEnv('OS_CLUSTER_REPLICAS', '2');
343+
const { ctx, services, logs, hooks } = makeCtx({ cluster });
344+
await new CacheServicePlugin().init(ctx);
345+
let reconnects = 0;
346+
derived.client.on('reconnecting', () => { reconnects += 1; });
347+
await expect((services.get('cache') as RedisCacheAdapter).get('k')).rejects.toThrow();
348+
await until(() => reconnects >= 3, 'three reconnect attempts');
349+
return { logs, hooks };
350+
}
351+
352+
const unhandledLines = (spy: { mock: { calls: unknown[][] } }) =>
353+
spy.mock.calls.filter((call) => String(call[0]).includes('Unhandled error event'));
354+
355+
it('a refused store over the redis driver: no unhandled error event, ONE outage warning in the driver\'s liveness, no credential', async () => {
356+
const { port, base, derived, cluster } = await refusedRedis();
357+
const { warns } = livenessFor(cluster, port);
358+
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
359+
try {
360+
const { logs, hooks } = await failThroughOutage(cluster, derived);
361+
expect(unhandledLines(consoleError)).toEqual([]);
362+
expect(warns).toHaveLength(1);
363+
expect(warns[0]).toMatch(/lost its connection/);
364+
expect(warns.join('\n')).not.toContain('s3cret');
365+
expect(readClusterDriverHealth(cluster)).toMatchObject({ state: 'down', outages: 1 });
366+
// The plugin adds no outage line of its own.
367+
expect(logs.filter(([level]) => level !== 'info')).toEqual([]);
368+
await shutdown(hooks);
369+
} finally {
370+
consoleError.mockRestore();
371+
derived.client?.disconnect();
372+
base.disconnect();
373+
}
374+
});
375+
376+
it('a driver that offers no liveness: still no unhandled error event — the outage is logged once through the plugin\'s logger', async () => {
377+
const { base, derived, cluster } = await refusedRedis();
378+
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
379+
try {
380+
const { logs, hooks } = await failThroughOutage(cluster, derived);
381+
expect(unhandledLines(consoleError)).toEqual([]);
382+
const warnings = logs.filter(([level]) => level === 'warn').map(([, message]) => message);
383+
expect(warnings).toHaveLength(1);
384+
expect(warnings[0]).toMatch(/lost its connection/);
385+
expect(warnings[0]).not.toContain('s3cret');
386+
await shutdown(hooks);
387+
} finally {
388+
consoleError.mockRestore();
389+
derived.client?.disconnect();
390+
base.disconnect();
391+
}
392+
});
393+
394+
it('a deliberate shutdown is not an outage: the cache detaches before it quits its connection', async () => {
395+
vi.stubEnv('OS_CLUSTER_REPLICAS', '2');
396+
const base = mockClient();
397+
const derived = captureDerived(base as { duplicate?: () => unknown });
398+
const cluster = redisCluster(base);
399+
const { warns } = livenessFor(cluster);
400+
const { ctx, hooks } = makeCtx({ cluster });
401+
await new CacheServicePlugin().init(ctx);
402+
derived.client.emit('ready');
403+
expect(readClusterDriverHealth(cluster)?.state).toBe('up');
404+
// ioredis emits `close` when the quit closes the socket.
405+
const quit = derived.client.quit.bind(derived.client);
406+
derived.client.quit = async () => { derived.client.emit('close'); return quit(); };
407+
408+
await shutdown(hooks);
409+
410+
expect(warns).toEqual([]);
411+
expect(readClusterDriverHealth(cluster)).toMatchObject({ state: 'up', outages: 0 });
412+
});
413+
414+
it('`cluster.resync` waits for the cache\'s connection too — the reason it shares the driver\'s liveness', async () => {
415+
vi.stubEnv('OS_CLUSTER_REPLICAS', '2');
416+
const base = mockClient() as any;
417+
const derived = captureDerived(base);
418+
const cluster = redisCluster(base);
419+
const { liveness, warns } = livenessFor(cluster);
420+
liveness.watchConnection(base, 'command');
421+
const { ctx, hooks } = makeCtx({ cluster });
422+
await new CacheServicePlugin().init(ctx);
423+
let resyncs = 0;
424+
onClusterResync(cluster, () => { resyncs += 1; });
425+
426+
derived.client.emit('error', new Error('ECONNREFUSED'));
427+
base.emit('error', new Error('ECONNREFUSED'));
428+
base.emit('ready');
429+
expect(resyncs).toBe(0);
430+
expect(readClusterDriverHealth(cluster)?.state).toBe('down');
431+
432+
derived.client.emit('ready');
433+
expect(resyncs).toBe(1);
434+
expect(warns).toHaveLength(1);
435+
await shutdown(hooks);
436+
});
437+
438+
it('CONTROL: an injected client is its owner\'s — the cache attaches no listener to it', async () => {
439+
vi.stubEnv('OS_CLUSTER_REPLICAS', '2');
440+
const own = mockClient() as any;
441+
const before = ['error', 'close', 'ready'].map((e) => own.listenerCount(e));
442+
const cluster = redisCluster();
443+
livenessFor(cluster);
444+
const { ctx, hooks } = makeCtx({ cluster });
445+
await new CacheServicePlugin({ redis: { client: own } }).init(ctx);
446+
expect(['error', 'close', 'ready'].map((e) => own.listenerCount(e))).toEqual(before);
447+
await shutdown(hooks);
448+
});
449+
});

‎packages/services/service-cache/src/cache-service-plugin.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@ import {
66
NoopMetricsRegistry,
77
type MetricsRegistry,
88
} from '@objectstack/observability';
9-
import { declaresMultiNode, readClusterDriverConnection } from '@objectstack/service-cluster';
9+
import {
10+
ClusterDriverLiveness,
11+
declaresMultiNode,
12+
readClusterDriverConnection,
13+
readClusterDriverHealth,
14+
watchClusterDriverConnection,
15+
} from '@objectstack/service-cluster';
1016
import { MemoryCacheAdapter } from './memory-cache-adapter.js';
1117
import type { MemoryCacheAdapterOptions } from './memory-cache-adapter.js';
1218
import { RedisCacheAdapter, type RedisCacheClient } from './redis-cache-adapter.js';
@@ -280,7 +286,15 @@ export class CacheServicePlugin implements Plugin {
280286
ownsClient: plan.ownsClient,
281287
});
282288
ctx.registerService('cache', cache);
289+
// Only the connection this plugin derived is watched: an injected client
290+
// and a borrowed driver connection belong to their owners, who listen.
291+
const unwatch =
292+
plan.ownsClient && plan.source === 'cluster-driver'
293+
? watchDerivedConnection(readRegisteredCluster(ctx), plan.client, ctx.logger)
294+
: () => {};
283295
ctx.hook('kernel:shutdown', async () => {
296+
// Detach first: the close the deliberate quit causes is not an outage.
297+
unwatch();
284298
await cache.close();
285299
});
286300
ctx.logger.info(
@@ -299,6 +313,57 @@ export class CacheServicePlugin implements Plugin {
299313
}
300314
}
301315

316+
/** The events a derived ioredis connection emits, checked structurally (a test double may have none). */
317+
type WatchableConnection = Parameters<ClusterDriverLiveness['watchConnection']>[0];
318+
319+
function isWatchable(client: unknown): client is WatchableConnection {
320+
const c = client as Partial<Record<'on' | 'off', unknown>> | null;
321+
return !!c && typeof c.on === 'function' && typeof c.off === 'function';
322+
}
323+
324+
/**
325+
* Watch the connection this plugin derived from the cluster driver's, so an
326+
* outage is never an unhandled `error` event (ioredis prints one, with a stack,
327+
* per reconnect attempt). Returns the disposer to call before the cache quits.
328+
*
329+
* - The driver offers a liveness (the redis driver does): the connection
330+
* reports into it as `'cache'`, the same way the driver's own connections
331+
* do — one outage logs once across all of them, and `cluster.resync` waits
332+
* for this connection too.
333+
* - It offers none (a driver released before the liveness offer): the
334+
* connection gets a liveness of its own, so its outage is still logged once,
335+
* credential-free, through this plugin's logger — never one line per
336+
* reconnect attempt, and never silently swallowed. Nothing subscribes to
337+
* that liveness's resync.
338+
*/
339+
function watchDerivedConnection(
340+
cluster: unknown,
341+
client: unknown,
342+
logger: PluginContext['logger'],
343+
): () => void {
344+
if (!isWatchable(client)) return () => {};
345+
if (readClusterDriverHealth(cluster) !== undefined) {
346+
return watchClusterDriverConnection(cluster, client, 'cache');
347+
}
348+
const own = new ClusterDriverLiveness({
349+
driver: describeDriver(cluster) ?? 'redis',
350+
nodeId: describeNodeId(cluster) ?? 'node',
351+
logger,
352+
});
353+
const unwatch = own.watchConnection(client, 'cache');
354+
return () => {
355+
unwatch();
356+
own.close();
357+
};
358+
}
359+
360+
/** The registered cluster's node id, or `undefined`. */
361+
function describeNodeId(cluster: unknown): string | undefined {
362+
if (!cluster || typeof cluster !== 'object') return undefined;
363+
const nodeId = (cluster as { nodeId?: unknown }).nodeId;
364+
return typeof nodeId === 'string' ? nodeId : undefined;
365+
}
366+
302367
/**
303368
* The registered `cluster` service, or `undefined` when none is. Read only by
304369
* the branches of {@link planCacheAdapter} that need it; `optionalDependencies`

‎packages/services/service-cluster-redis/src/client.ts‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -111,21 +111,9 @@ export function watchRedisConnection(
111111
liveness: ClusterDriverLiveness,
112112
source: string,
113113
): () => void {
114-
const onError = (err: unknown): void => liveness.reportDown(source, err);
115-
const onClose = (): void => liveness.reportDown(source);
116-
const onReady = (): void => liveness.reportUp(source);
117-
client.on('error', onError);
118-
client.on('close', onClose);
119-
client.on('ready', onReady);
120-
if (client.status === 'ready') liveness.reportUp(source);
121-
let watching = true;
122-
return () => {
123-
if (!watching) return;
124-
watching = false;
125-
client.off('error', onError);
126-
client.off('close', onClose);
127-
client.off('ready', onReady);
128-
};
114+
// The one listener style (`ClusterDriverLiveness.watchConnection`), shared
115+
// with the connections derived from this one (`watchClusterDriverConnection`).
116+
return liveness.watchConnection(client, source);
129117
}
130118

131119
/**

‎packages/services/service-cluster/src/cluster-resync.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ import {
1717
onClusterResync,
1818
readClusterDriverHealth,
1919
redactCredentials,
20+
watchClusterDriverConnection,
2021
} from './cluster-resync.js';
22+
import { EventEmitter } from 'node:events';
2123
import { defineCluster } from './cluster.js';
2224

2325
function makeLiveness() {
@@ -164,3 +166,42 @@ describe('the offer on the cluster instance — onClusterResync / readClusterDri
164166
await cluster.close();
165167
});
166168
});
169+
170+
describe('watchClusterDriverConnection — a derived connection joins the driver\'s liveness', () => {
171+
function connection(status?: string) {
172+
return Object.assign(new EventEmitter(), { status });
173+
}
174+
const counts = (c: EventEmitter) => ['error', 'close', 'ready'].map((e) => c.listenerCount(e));
175+
176+
it('reports into the offered liveness as its source; the disposer detaches all three listeners', () => {
177+
const cluster = {};
178+
const { liveness, logger } = makeLiveness();
179+
offerClusterDriverLiveness(cluster, liveness);
180+
const conn = connection('ready');
181+
const unwatch = watchClusterDriverConnection(cluster, conn, 'cache');
182+
expect(readClusterDriverHealth(cluster)?.state).toBe('up');
183+
expect(counts(conn)).toEqual([1, 1, 1]);
184+
185+
conn.emit('error', new Error('ECONNREFUSED'));
186+
conn.emit('error', new Error('ECONNREFUSED'));
187+
expect(readClusterDriverHealth(cluster)).toMatchObject({ state: 'down', outages: 1 });
188+
expect(logger.warn).toHaveBeenCalledTimes(1);
189+
conn.emit('ready');
190+
expect(readClusterDriverHealth(cluster)?.state).toBe('up');
191+
192+
unwatch();
193+
unwatch();
194+
expect(counts(conn)).toEqual([0, 0, 0]);
195+
conn.emit('close');
196+
expect(readClusterDriverHealth(cluster)?.state).toBe('up');
197+
});
198+
199+
it('CONTROL — no liveness offered (the memory driver): attaches nothing, the disposer is inert', async () => {
200+
const cluster = defineCluster({ driver: 'memory' });
201+
const conn = connection();
202+
const unwatch = watchClusterDriverConnection(cluster, conn, 'cache');
203+
expect(counts(conn)).toEqual([0, 0, 0]);
204+
unwatch();
205+
await cluster.close();
206+
});
207+
});

0 commit comments

Comments
 (0)