Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/__tests__/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ describe('runServer', () => {
let mockHttpHandle: HttpServerHandle;
let mockClose: jest.Mock;
let processOnSpy: jest.SpyInstance;
let processOffSpy: jest.SpyInstance;

beforeEach(() => {
jest.clearAllMocks();
Expand All @@ -51,15 +52,17 @@ describe('runServer', () => {

MockStartHttpTransport.mockResolvedValue(mockHttpHandle);

// Spy on process.on method
// Spy on process methods
processOnSpy = jest.spyOn(process, 'on').mockImplementation();
processOffSpy = jest.spyOn(process, 'off');

// Mock process.exit to prevent Jest from exiting
jest.spyOn(process, 'exit').mockImplementation((() => {}) as never);
});

afterEach(() => {
processOnSpy.mockRestore();
processOffSpy.mockRestore();
// Note: We don't call jest.restoreAllMocks() here as it would clear module mocks
// The memoization cache persists across tests, which is expected behavior
});
Expand Down Expand Up @@ -175,6 +178,7 @@ describe('runServer', () => {

await serverInstance.stop();

expect(processOffSpy).toHaveBeenCalledWith('SIGINT', expect.any(Function));
expect(serverInstance.isRunning()).toBe(false);
expect({
events: MockLog.info.mock.calls
Expand Down
13 changes: 10 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ const runServer = async (options: ServerOptions = getOptions(), {
let transport: StdioServerTransport | null = null;
let httpHandle: HttpServerHandle | null = null;
let unsubscribeServerLogger: (() => void) | null = null;
let sigintHandler: (() => void) | null = null;
let running = false;
let onLogSetup: ServerOnLog = () => () => {};

Expand All @@ -144,6 +145,11 @@ const runServer = async (options: ServerOptions = getOptions(), {
httpHandle = null;
}

if (sigintHandler) {
process.off('SIGINT', sigintHandler);
sigintHandler = null;
}

log.debug('...closing Server');
await server?.close();
running = false;
Expand Down Expand Up @@ -246,10 +252,11 @@ const runServer = async (options: ServerOptions = getOptions(), {
})));
});

if (enableSigint) {
process.on('SIGINT', () => {
if (enableSigint && !sigintHandler) {
sigintHandler = () => {
void stopServer();
});
};
process.on('SIGINT', sigintHandler);
}

if (options.isHttp) {
Expand Down
Loading