fix(core): own cache transports and accept cleanup reviews

This commit is contained in:
Boki 2026-10-26 23:57:39 -04:00
parent bd9332b2f6
commit b4ac6460ef
24 changed files with 504 additions and 97 deletions

View file

@ -0,0 +1,130 @@
import { expect, test } from 'bun:test';
/** Mock only the socket transport in a child: production factories, wrappers and DI stay real. */
test('container and queue caches own endpoint-specific transports through shutdown and rollback', async () => {
const child = Bun.spawn(
[
process.execPath,
'-e',
String.raw`
import { mock } from 'bun:test';
import { EventEmitter } from 'node:events';
const sockets = [];
class Redis {
constructor(options) { this.options = options; this.closed = 0; this.status = 'ready'; sockets.push(this); }
on() { return this; }
disconnect() { this.closed++; this.status = 'end'; }
async quit() { this.disconnect(); }
async setex(key, ttl) { this.lastWrite = {key,ttl}; }
async get(key) { if (this.closed) throw new Error('closed socket'); return JSON.stringify({host:this.options.host, username:this.options.username, key}); }
scanStream() { const stream = new EventEmitter(); queueMicrotask(() => this.failClear ? stream.emit('error',new Error('fixture clear failed')) : stream.emit('end')); return stream; }
pipeline() { return { del() {}, async exec() {} }; }
}
mock.module('ioredis', () => ({ default: Redis, Redis, Cluster: Redis }));
const { ServiceContainerBuilder } = await import('./libs/core/di/src/container/builder.ts');
const { ProxyManager } = await import('@stock-bot/proxy');
const { QueueManager } = await import('@stock-bot/queue');
const { createCache } = await import('@stock-bot/cache');
const options = {enableMongoDB:false,enablePostgres:false,enableQuestDB:false,enableQueue:false,enableBrowser:false,enableProxy:true};
const config = (name) => ({
name:'cache-owner', version:'1.0.0', service:{name:'cache-owner',port:3000}, log:{level:'fatal'},
database:{dragonfly:{enabled:true,host:name+'.fixture.test',port:16379,username:name,password:'fixture-only',maxRetries:7,retryDelay:456,ttl:123},
mongodb:{enabled:false,uri:'mongodb://unused/test',database:'test'},
postgres:{enabled:false,database:'test',user:'test',password:'fixture-only'},questdb:{enabled:false}},
});
const builder = name => new ServiceContainerBuilder().withConfig(config(name)).withOptions(options);
const first = await builder('first').buildOwned();
const firstSockets = sockets.slice();
const firstCache = first.container.resolve('cache');
const keys = await Promise.all([
firstCache.get('x'), first.container.resolve('globalCache').get('x'), first.container.resolve('proxyCache').get('x')
]);
await firstCache.set('x',1);
await first.container.resolve('globalCache').set('x',1);
await first.container.resolve('proxyCache').set('x',1);
const ttl = firstSockets.map(s=>s.lastWrite.ttl);
const second = await builder('second').buildOwned();
const secondSockets = sockets.slice(firstSockets.length);
await first.shutdown(); await first.shutdown();
const isolated = { first:firstSockets.map(s=>s.closed), second:secondSockets.map(s=>s.closed), read:await second.container.resolve('cache').get('x') };
const third = await builder('first').buildOwned();
const thirdSockets = sockets.slice(firstSockets.length + secondSockets.length);
const fresh = await third.container.resolve('cache').get('x');
const beforeRollback = sockets.length;
const originalInitialize = ProxyManager.prototype.initialize;
const failure = new Error('fixture proxy initialization failed');
ProxyManager.prototype.initialize = async () => { throw failure; };
let originalFailure = false;
try { await builder('rollback').buildOwned(); } catch (error) { originalFailure = error === failure; }
finally { ProxyManager.prototype.initialize = originalInitialize; }
const rollback = sockets.slice(beforeRollback).map(s=>s.closed);
const disposed = await builder('dispose').skipInitialization().buildOwned();
const beforeDispose = sockets.length;
disposed.container.resolve('serviceContainer');
await disposed.container.dispose(); await disposed.container.dispose();
const directDispose = sockets.slice(beforeDispose).map(s=>s.closed);
const queue = new QueueManager({serviceName:'cache-owner',redis:{host:'queue.fixture.test',port:16379,username:'queue',password:'fixture-only',maxRetriesPerRequest:7,retryDelay:456},autoDiscoverHandlers:false},undefined,first.container.resolve('logger'));
const beforeQueueCache = sockets.length;
const batch = queue.getCache('same-name');
const batchRead = await batch.get('x');
const workerPolicy = {maxRetriesPerRequest:queue.redisConnection.maxRetriesPerRequest,retryDelay:queue.redisConnection.retryStrategy(99)};
sockets.at(-1).failClear = true;
await queue.shutdown();
const queueClosed = sockets.slice(beforeQueueCache-1).map(s=>s.closed);
const shared = createCache({keyPrefix:'borrowed:',redisConfig:{host:'shared.fixture.test',port:16379}});
const sharedAgain = createCache({keyPrefix:'borrowed:',redisConfig:{host:'shared.fixture.test',port:16379}});
const sharedSocket = sockets.at(-1);
await shared.disconnect?.();
await second.shutdown(); await third.shutdown();
const wire = sockets.filter(s=>s.options.host!=='shared.fixture.test').map(s=>({host:s.options.host,username:s.options.username,db:s.options.db,retries:s.options.maxRetriesPerRequest,delay:s.options.retryStrategy?.(99)}));
process.stdout.write('__cache_ownership__'+JSON.stringify({keys,ttl,isolated,fresh,thirdClosed:thirdSockets.map(s=>s.closed),originalFailure,rollback,directDispose,batchRead,workerPolicy,queueClosed,sharedSame:shared===sharedAgain,sharedClosed:sharedSocket.closed,wire})+'\n');
`,
],
{ stdout: 'pipe', stderr: 'pipe' }
);
const [stdout, stderr, code] = await Promise.all([
new Response(child.stdout).text(),
new Response(child.stderr).text(),
child.exited,
]);
if (code !== 0) {
throw new Error(`Cache ownership probe failed: ${stderr}`);
}
const line = stdout.split('\n').find(value => value.startsWith('__cache_ownership__'));
expect(line).toBeDefined();
const result = JSON.parse(line!.slice('__cache_ownership__'.length));
expect(result.keys.map((value: { key: string }) => value.key)).toEqual([
'cache:cache-owner:x',
'stock-bot:shared:x',
'cache:proxy:x',
]);
expect(result.ttl).toEqual([123, 123, 86400]);
expect(result.isolated).toEqual({
first: [1, 1, 1],
second: [0, 0, 0],
read: { host: 'second.fixture.test', username: 'second', key: 'cache:cache-owner:x' },
});
expect(result.fresh).toEqual({
host: 'first.fixture.test',
username: 'first',
key: 'cache:cache-owner:x',
});
expect(result.thirdClosed).toEqual([1, 1, 1]);
expect(result.originalFailure).toBe(true);
expect(result.rollback).toEqual([1, 1, 1]);
expect(result.directDispose).toEqual([1, 1, 1]);
expect(result.batchRead).toEqual({
host: 'queue.fixture.test',
username: 'queue',
key: 'batch:same-name:x',
});
expect(result.queueClosed).toEqual([1, 1]);
expect(result.workerPolicy).toEqual({ maxRetriesPerRequest: null, retryDelay: 456 });
expect(result.sharedSame).toBe(true);
expect(result.sharedClosed).toBe(0);
for (const wire of result.wire) {
expect(wire.retries).toBe(7);
expect(wire.delay).toBe(456);
expect(wire.db).toBe(wire.host === 'queue.fixture.test' ? 0 : 1);
}
}, 15_000);

View file

@ -1,7 +1,11 @@
import { expect, test } from 'bun:test';
import { asValue, createContainer } from 'awilix';
import { expect, mock, test } from 'bun:test';
import type { PoolConfig } from 'pg';
import { baseAppSchema } from '@stock-bot/config';
import { appConfigSchema } from '../../libs/core/di/src/config/schemas';
import { ServiceContainerBuilder } from '../../libs/core/di/src/container/builder';
import type { ServiceDefinitions } from '../../libs/core/di/src/container/types';
import { registerCacheServices } from '../../libs/core/di/src/registrations/cache.registration';
function configuration(enabled = true) {
return baseAppSchema.parse({
@ -42,8 +46,9 @@ for (const enabled of [true, false]) {
.skipInitialization()
.build();
try {
for (const name of ['cache', 'mongoClient', 'postgresClient'])
for (const name of ['cache', 'mongoClient', 'postgresClient']) {
expect(c.resolve(name)).toBeNull();
}
const config = c.resolve('config');
expect(config.redis.enabled).toBe(false);
expect(config.mongodb.enabled).toBe(false);
@ -61,8 +66,9 @@ test('enable options do not override disabled configurations', async () => {
.skipInitialization()
.build();
try {
for (const name of ['cache', 'mongoClient', 'postgresClient'])
for (const name of ['cache', 'mongoClient', 'postgresClient']) {
expect(c.resolve(name)).toBeNull();
}
} finally {
await c.dispose();
}
@ -106,7 +112,7 @@ test('PostgreSQL nondefault fields reach wire configuration and Mongo retains UR
}
});
test('flat QuestDB alias takes precedence without discarding credentials or schema settings', async () => {
test('flat QuestDB alias and credentials reach the client; unsupported tuning is diagnosed', async () => {
const c = await new ServiceContainerBuilder()
.withConfig({
...configuration(false),
@ -123,6 +129,9 @@ test('flat QuestDB alias takes precedence without discarding credentials or sche
} as never)
.skipInitialization()
.build();
const logger = c.resolve('logger');
const originalWarn = logger.warn;
logger.warn = mock(() => {});
try {
expect(c.resolve('config').questdb).toMatchObject({
influxPort: 29009,
@ -131,7 +140,34 @@ test('flat QuestDB alias takes precedence without discarding credentials or sche
user: 'fixture',
password: 'fixture',
});
expect(c.resolve('questdbClient')!.configuration).toMatchObject({
influxPort: 29009,
user: 'fixture',
password: 'fixture',
});
expect(logger.warn).toHaveBeenCalledWith(
'QuestDB bufferSize/flushInterval are deprecated and have no effect; configure explicit writer batch options instead'
);
expect(logger.warn).toHaveBeenCalledTimes(1);
} finally {
logger.warn = originalWarn;
await c.dispose();
}
});
test('default QuestDB compatibility settings do not produce tuning diagnostics', async () => {
const c = await new ServiceContainerBuilder()
.withConfig({ ...configuration(false), questdb: { enabled: true } } as never)
.skipInitialization()
.build();
const logger = c.resolve('logger');
const originalWarn = logger.warn;
logger.warn = mock(() => {});
try {
expect(c.resolve('questdbClient')).not.toBeNull();
expect(logger.warn).not.toHaveBeenCalled();
} finally {
logger.warn = originalWarn;
await c.dispose();
}
});
@ -150,8 +186,9 @@ test('all-disabled default composition needs neither store settings nor connecti
})
.build();
try {
for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient'])
for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient']) {
expect(c.resolve(name)).toBeNull();
}
} finally {
await c.dispose();
}
@ -193,11 +230,13 @@ test('Redis ACL username reaches cache and both queue connection settings withou
new Response(child.stderr).text(),
child.exited,
]);
if (code !== 0) throw new Error(`Redis transport probe failed: ${stderr}`);
if (code !== 0) {
throw new Error(`Redis transport probe failed: ${stderr}`);
}
const line = stdout.split('\n').find(line => line.startsWith('__redis_capture__'));
expect(line).toBeDefined();
const result = JSON.parse(line!.slice('__redis_capture__'.length));
expect(result.captured).toHaveLength(2);
expect(result.captured).toHaveLength(3);
for (const config of [...result.captured, result.queue]) {
expect(config).toMatchObject({
host: 'redis.fixture.test',
@ -206,3 +245,20 @@ test('Redis ACL username reaches cache and both queue connection settings withou
});
}
});
test('deprecated DI cache prefixes produce a diagnostic without echoing supplied values', () => {
const logger = { warn: mock(() => {}) };
// Registration validates the compatibility setting without constructing Redis transports.
const container = createContainer<ServiceDefinitions>();
container.register('logger', asValue(logger as unknown as ServiceDefinitions['logger']));
const config = appConfigSchema.parse({
redis: { enabled: true, keyPrefix: 'private-operator-prefix' },
mongodb: { enabled: false, uri: 'mongodb://unused/test', database: 'test' },
postgres: { enabled: false, database: 'test', user: 'test', password: 'fixture-only' },
});
registerCacheServices(container, config);
expect(logger.warn).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
'Redis keyPrefix is deprecated at the DI boundary; service/global/proxy namespaces remain fixed'
);
});