T-16: M0.1b — Make repo-wide bun test green: fix queue, shutdown-signal and research-workflow test failures

This commit is contained in:
Studio 2026-11-27 12:01:06 -05:00
parent 890761e0d5
commit 9c4e87cdfd
17 changed files with 366 additions and 266 deletions

View file

@ -15,6 +15,7 @@ export class Shutdown {
private shutdownTimeout: number;
private callbacks: CallbackEntry[] = [];
private signalHandlersRegistered = false;
private registeredSignalHandlers = new Map<NodeJS.Signals, () => void>();
private shutdownPromise: Promise<void> | null = null;
private triggerSignal: string | null = null;
@ -33,6 +34,37 @@ export class Shutdown {
return Shutdown.instance;
}
/**
* Dispose the singleton instance and remove its signal listeners.
*/
static reset(): void {
if (Shutdown.instance) {
Shutdown.instance.dispose();
Shutdown.instance = null;
}
}
/**
* Remove process signal handlers registered by this instance.
*/
removeSignalHandlers(): void {
for (const [signal, listener] of this.registeredSignalHandlers) {
process.off(signal, listener);
}
this.registeredSignalHandlers.clear();
this.signalHandlersRegistered = false;
}
/**
* Clean up signal listeners and clear singleton reference if this is the active singleton.
*/
dispose(): void {
this.removeSignalHandlers();
if (Shutdown.instance === this) {
Shutdown.instance = null;
}
}
/**
* Get current shutdown status
*/
@ -153,7 +185,7 @@ export class Shutdown {
signals.forEach(signal => {
// Use process.on instead of process.once to handle multiple signals
process.on(signal, async () => {
const listener = async () => {
this.logger.info(`Received ${signal} signal`);
// If already shutting down, ignore the signal
@ -178,7 +210,10 @@ export class Shutdown {
process.exit(1);
}
});
};
this.registeredSignalHandlers.set(signal, listener);
process.on(signal, listener);
this.logger.debug(`Registered handler for ${signal}`);
});

View file

@ -6,14 +6,15 @@ describe('Shutdown Comprehensive Tests', () => {
beforeEach(() => {
// Reset singleton instance for each test
(Shutdown as any).instance = null;
Shutdown.reset();
// Create a fresh instance for each test
shutdownInstance = new Shutdown({ autoRegister: false });
});
afterEach(() => {
// Clean up singleton
(Shutdown as any).instance = null;
// Clean up singleton and any signal listeners
shutdownInstance?.dispose();
Shutdown.reset();
});
describe('Basic Functionality', () => {
@ -250,10 +251,18 @@ describe('Shutdown Comprehensive Tests', () => {
});
it('should use default timeout', () => {
const _defaultShutdown = new Shutdown();
const defaultShutdown = new Shutdown();
let secondShutdown: Shutdown | undefined;
// Can't directly test timeout value, but we can verify it doesn't throw
expect(() => new Shutdown()).not.toThrow();
try {
// Can't directly test timeout value, but we can verify it doesn't throw
expect(() => {
secondShutdown = new Shutdown();
}).not.toThrow();
} finally {
defaultShutdown.dispose();
secondShutdown?.dispose();
}
});
});
});

View file

@ -1,46 +1,46 @@
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import { Shutdown } from '../src/shutdown';
describe('Shutdown Signal Handlers', () => {
let shutdown: Shutdown;
let processOnceSpy: any;
let processExitSpy: any;
const originalOn = process.on;
const originalExit = process.exit;
let shutdown: Shutdown | undefined;
let processOnceSpy: ReturnType<typeof spyOn>;
let processExitSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
// Reset singleton instance
(Shutdown as any).instance = null;
Shutdown.reset();
shutdown = undefined;
// Mock process.on to capture signal handlers
const listeners: Record<string, Function[]> = {};
processOnceSpy = mock((event: string, handler: Function) => {
processOnceSpy = spyOn(process, 'on').mockImplementation(((event: string, handler: Function) => {
if (!listeners[event]) {
listeners[event] = [];
}
listeners[event].push(handler);
return process;
});
process.on = processOnceSpy as any;
}) as any);
// Mock process.exit
processExitSpy = mock((_code?: number) => {
processExitSpy = spyOn(process, 'exit').mockImplementation(((_code?: number) => {
// Just record the call, don't actually exit
return undefined as never;
});
process.exit = processExitSpy as any;
}) as any);
// Store listeners for manual triggering
(global as any).__testListeners = listeners;
});
afterEach(() => {
// Restore original methods
process.on = originalOn;
process.exit = originalExit;
// Clean up any registered listeners and singleton before restoring process spies
shutdown?.dispose();
shutdown = undefined;
Shutdown.reset();
// Restore original methods
processOnceSpy?.mockRestore();
processExitSpy?.mockRestore();
// Clean up
(Shutdown as any).instance = null;
delete (global as any).__testListeners;
});

View file

@ -5,14 +5,14 @@ describe('Shutdown', () => {
let shutdown: Shutdown;
beforeEach(() => {
// Reset singleton instance for each test
(Shutdown as any).instance = null;
shutdown = Shutdown.getInstance({ timeout: 1000 });
// Reset singleton instance and remove any prior signal listeners
Shutdown.reset();
shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false });
});
afterEach(() => {
// Clean up
(Shutdown as any).instance = null;
// Clean up listeners and singleton
Shutdown.reset();
});
describe('getInstance', () => {
@ -24,7 +24,8 @@ describe('Shutdown', () => {
});
it('should use provided config on first call', () => {
const instance = Shutdown.getInstance({ timeout: 5000 });
Shutdown.reset();
const instance = Shutdown.getInstance({ timeout: 5000, autoRegister: false });
expect(instance).toBeDefined();
});
});
@ -125,20 +126,28 @@ describe('Shutdown', () => {
});
it('should respect timeout', async () => {
let slowTimer: ReturnType<typeof setTimeout> | undefined;
const slowHandler = mock(async () => {
await new Promise(resolve => setTimeout(resolve, 2000));
await new Promise(resolve => {
slowTimer = setTimeout(resolve, 2000);
});
});
shutdown = Shutdown.getInstance({ timeout: 100 });
Shutdown.reset();
shutdown = Shutdown.getInstance({ timeout: 100, autoRegister: false });
shutdown.onShutdown(slowHandler, 10, 'Slow Handler');
const start = Date.now();
await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout');
try {
await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout');
} finally {
clearTimeout(slowTimer);
}
const duration = Date.now() - start;
// Shutdown waits for timeout (100ms) plus some processing time
expect(duration).toBeGreaterThan(90);
expect(duration).toBeLessThan(1500); // But not the full 2000ms
expect(duration).toBeLessThan(500);
});
});
@ -161,8 +170,8 @@ describe('Shutdown', () => {
await shutdown.shutdown();
// Reset by creating new instance
(Shutdown as any).instance = null;
shutdown = Shutdown.getInstance({ timeout: 1000 });
Shutdown.reset();
shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false });
shutdown.onShutdown(handler, 10, 'Handler');
await shutdown.shutdown();