|
20 | 20 | import RedisMock from 'ioredis-mock'; |
21 | 21 | import { afterEach, describe, expect, it, vi } from 'vitest'; |
22 | 22 | 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'; |
24 | 32 | // Importing the driver registers `redis` with `defineCluster()` — at module |
25 | 33 | // eval, so no test body pays the cold load. |
26 | | -import '@objectstack/service-cluster-redis'; |
| 34 | +import { createRedisClient } from '@objectstack/service-cluster-redis'; |
27 | 35 |
|
28 | 36 | import { CacheServicePlugin, planCacheAdapter, type CacheAdapterPlanInput } from './cache-service-plugin.js'; |
29 | 37 | import { MemoryCacheAdapter } from './memory-cache-adapter.js'; |
@@ -273,3 +281,169 @@ describe('real ObjectKernel boots — cluster plugin + redis driver over ioredis |
273 | 281 | await expect(boot(new CacheServicePlugin({ adapter: 'memory' }), mockClient())).rejects.toThrow(/per-process cache/); |
274 | 282 | }); |
275 | 283 | }); |
| 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 | +}); |
0 commit comments