Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for graceful shutdown in fastify #843

Merged
merged 5 commits into from
Oct 3, 2023
Merged
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
24 changes: 24 additions & 0 deletions packages/connect-fastify/src/fastify-connect-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import type { JsonValue } from "@bufbuild/protobuf";
import { Code, ConnectError, createConnectRouter } from "@connectrpc/connect";
import { createLinkedAbortController } from "@connectrpc/connect/protocol";
import type {
ConnectRouter,
ConnectRouterOptions,
Expand Down Expand Up @@ -48,6 +49,19 @@ interface FastifyConnectPluginOptions extends ConnectRouterOptions {
* Then pass this function here.
*/
routes?: (router: ConnectRouter) => void;

/**
* If set, once `fastify.close` is called, waits for the requests to be finished for the specified duration
* before aborting them.
*/
shutdownTimeoutMs?: number;

/**
* The abort error caused by the shutdown timeout.
*
* If this is a ConnectError, it will be sent to the client.
*/
shutdownError?: unknown;
/**
* Context values to extract from the request. These values are passed to
* the handlers.
Expand All @@ -70,6 +84,16 @@ export function fastifyConnectPlugin(
if (opts.acceptCompression === undefined) {
opts.acceptCompression = [compressionGzip, compressionBrotli];
}
if (opts.shutdownTimeoutMs !== undefined) {
const shutdownController = createLinkedAbortController(opts.shutdownSignal);
opts.shutdownSignal = shutdownController.signal;
instance.addHook("preClose", (done) => {
setTimeout(() => {
shutdownController.abort(opts.shutdownError);
}, opts.shutdownTimeoutMs);
done();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't done be called after the grace period? So in the setTimeout callback?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either should be fine, Fastify waits for the requests to finish even there are no preClosehooks.

});
}
const router = createConnectRouter(opts);
opts.routes(router);

Expand Down