130 lines
7.4 KiB
TypeScript
130 lines
7.4 KiB
TypeScript
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);
|