Skip to content

Commit

Permalink
onDispose and other disposal improvements (#1899)
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan authored Dec 17, 2024
1 parent 424ad2a commit a84e84a
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 6 deletions.
24 changes: 24 additions & 0 deletions .changeset/olive-mirrors-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
'@whatwg-node/server': patch
---

- New `onDispose` hook which is alias of `Symbol.asyncDispose` for Explicit Resource Management
- Registration of the server adapter's disposal to the global process termination listener is now opt-in and configurable.

```ts
const plugin: ServerAdapterPlugin = {
onDispose() {
console.log('Server adapter is disposed');
}
};

const serverAdapter = createServerAdapter(() => new Response('Hello world!'), {
plugins: [plugin],
// Register the server adapter's disposal to the global process termination listener
// Then the server adapter will be disposed when the process exit signals only in Node.js!
disposeOnProcessTerminate: true
});

await serverAdapter.dispose();
// Prints 'Server adapter is disposed'
```
23 changes: 20 additions & 3 deletions packages/server/src/createServerAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ function isRequestAccessible(serverContext: any): serverContext is RequestContai
export interface ServerAdapterOptions<TServerContext> {
plugins?: ServerAdapterPlugin<TServerContext>[];
fetchAPI?: Partial<FetchAPI>;
/**
* Node.js only!
*
* If true, the server adapter will dispose itself when the process is terminated.
* If false, you have to dispose the server adapter by using the `dispose` method,
* or [Explicit Resource Management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html)
*/
disposeOnProcessTerminate?: boolean;
}

const EMPTY_OBJECT = {};
Expand Down Expand Up @@ -104,7 +112,9 @@ function createServerAdapter<
function ensureDisposableStack() {
if (!_disposableStack) {
_disposableStack = new AsyncDisposableStack();
ensureDisposableStackRegisteredForTerminateEvents(_disposableStack);
if (options?.disposeOnProcessTerminate) {
ensureDisposableStackRegisteredForTerminateEvents(_disposableStack);
}
_disposableStack.defer(() => {
if (waitUntilPromises.size > 0) {
return Promise.allSettled(waitUntilPromises).then(
Expand Down Expand Up @@ -144,10 +154,17 @@ function createServerAdapter<
if (plugin.onResponse) {
onResponseHooks.push(plugin.onResponse);
}
const disposeFn = plugin[DisposableSymbols.asyncDispose] || plugin[DisposableSymbols.dispose];
if (disposeFn != null) {
const disposeFn = plugin[DisposableSymbols.dispose];
if (disposeFn) {
ensureDisposableStack().defer(disposeFn);
}
const asyncDisposeFn = plugin[DisposableSymbols.asyncDispose];
if (asyncDisposeFn) {
ensureDisposableStack().defer(asyncDisposeFn);
}
if (plugin.onDispose) {
ensureDisposableStack().defer(plugin.onDispose);
}
}
}

Expand Down
10 changes: 8 additions & 2 deletions packages/server/src/plugins/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,22 @@ export interface ServerAdapterPlugin<TServerContext = {}> {
onResponse?: OnResponseHook<TServerContext & ServerAdapterInitialContext>;
/**
* This hook is invoked when the server is being disposed.
* The server disposal is triggered either by the request termination or the explicit server disposal.
* The server disposal is triggered either by the process termination or the explicit server disposal.
* @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html
*/
[Symbol.dispose]?: () => void;
/**
* This hook is invoked when the server is being disposed.
* The server disposal is triggered either by the request termination or the explicit server disposal.
* The server disposal is triggered either by the process termination or the explicit server disposal.
* @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html
*/
[Symbol.asyncDispose]?: () => PromiseLike<void> | void;
/**
* This hook is invoked when the server is being disposed.
* The server disposal is triggered either by the process termination or the explicit server disposal.
* @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html
*/
onDispose?: () => PromiseLike<void> | void;
}
export type OnRequestHook<TServerContext> = (
payload: OnRequestEventPayload<TServerContext>,
Expand Down
51 changes: 50 additions & 1 deletion packages/server/test/adapter.fetch.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createDeferredPromise } from '@whatwg-node/server';
import { createDeferredPromise, DisposableSymbols } from '@whatwg-node/server';
import { runTestsForEachFetchImpl } from './test-fetch.js';

describe('adapter.fetch', () => {
Expand Down Expand Up @@ -251,6 +251,55 @@ describe('adapter.fetch', () => {
expect(requestHandler).toHaveBeenCalledTimes(2);
expect(requestHandler.mock.calls[0][1]).not.toBe(requestHandler.mock.calls[1][1]);
});

describe('Disposal', () => {
const hookNames = [
DisposableSymbols.asyncDispose,
DisposableSymbols.dispose,
'onDispose',
] as const;
it('handles explicit resource management (await using)', async () => {
for (const disposalHookName of hookNames) {
const disposeFn = jest.fn();
{
await using serverAdapter = createServerAdapter(() => new Response('Hello world!'), {
plugins: [
{
[disposalHookName]: disposeFn,
},
],
});
await serverAdapter.fetch('http://localhost:8080/');
}
expect(disposeFn).toHaveBeenCalledTimes(1);
}
});
const methodNames = [DisposableSymbols.asyncDispose, 'dispose'] as const;
hookNames.forEach(hookName => {
methodNames.forEach(methodName => {
it(`handles ${hookName.toString()} hook (with ${methodName.toString()} method)`, async () => {
const hookNames = [
DisposableSymbols.asyncDispose,
DisposableSymbols.dispose,
'onDispose',
];
for (const disposalHookName of hookNames) {
const disposeFn = jest.fn();
const serverAdapter = createServerAdapter(() => new Response('Hello world!'), {
plugins: [
{
[disposalHookName]: disposeFn,
},
],
});
await serverAdapter.fetch('http://localhost:8080/');
await serverAdapter[methodName]();
expect(disposeFn).toHaveBeenCalledTimes(1);
}
});
});
});
});
},
{ noLibCurl: true },
);
Expand Down

0 comments on commit a84e84a

Please sign in to comment.