From 8f2b735cfc509055dc6ee29bc84d7295dfb4d72a Mon Sep 17 00:00:00 2001 From: Vadym Kurachevskyi Date: Wed, 25 Nov 2026 12:00:06 +1100 Subject: [PATCH 1/3] feat: let HTTP stop() wait for the requests in flight server.stop({ timeoutMs }) stops accepting new connections, then waits until no request is in flight or timeoutMs passes, and only then closes all connections. Without timeoutMs, stop() works as before. --- README.md | 16 +++++++ src/server/Allserver.js | 7 ++- src/server/HttpTransport.js | 39 +++++++++++++--- test/server/Allserver.test.js | 14 ++++++ test/server/HttpTransport.test.js | 77 +++++++++++++++++++++++++++++++ 5 files changed, 145 insertions(+), 8 deletions(-) create mode 100644 test/server/HttpTransport.test.js diff --git a/README.md b/README.md index adc7b2e..b07fe4e 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,22 @@ Allserver({ }).start(); ``` +#### Graceful stop + +By default, `stop()` closes the connections of the requests that are still in flight. To let them complete first, give a `timeoutMs`: + +```js +const server = Allserver({ procedures, transport: HttpTransport({ port: process.env.PORT }) }); +await server.start(); + +process.on("SIGTERM", async () => { + await server.stop({ timeoutMs: 20_000 }); + process.exit(0); +}); +``` + +The server stops accepting new connections at once and replies to new requests on open keep-alive connections with `Connection: close`. When no request is in flight, or after `timeoutMs`, it closes all connections. Keep `timeoutMs` below the time your platform gives the process to stop (for example, the ECS `stopTimeout`, 30s by default). + #### Replying non-standard HTTP response from a procedure You'd need to deal with node.js `res` yourself. diff --git a/src/server/Allserver.js b/src/server/Allserver.js index 62002d2..dadb1f2 100644 --- a/src/server/Allserver.js +++ b/src/server/Allserver.js @@ -168,8 +168,11 @@ module.exports = require("stampit")({ start() { return this.transport.startServer({ allserver: this }); }, - stop() { - return this.transport.stopServer(); + /** + * @param [options] {Object} Passed to the transport. HttpTransport accepts `{ timeoutMs }`. + */ + stop(options) { + return this.transport.stopServer(options); }, }, diff --git a/src/server/HttpTransport.js b/src/server/HttpTransport.js index 4828f27..36d2cec 100644 --- a/src/server/HttpTransport.js +++ b/src/server/HttpTransport.js @@ -7,6 +7,9 @@ module.exports = require("./Transport").compose({ props: { micro: require("micro"), port: process.env.PORT, + _requestsInFlight: 0, + _stopping: false, + _onNoRequestsInFlight: null, }, init({ port }) { @@ -42,6 +45,14 @@ module.exports = require("./Transport").compose({ startServer(defaultCtx) { this.server = new http.Server( this.micro.serve(async (req, res) => { + this._requestsInFlight += 1; + res.once("close", () => { + this._requestsInFlight -= 1; + if (this._requestsInFlight === 0 && this._onNoRequestsInFlight) this._onNoRequestsInFlight(); + }); + // Tell keep-alive clients to open a new connection, which goes to another server. + if (this._stopping) res.setHeader("Connection", "close"); + const ctx = { ...defaultCtx, http: { req, res, url: parseUrl(req.url) } }; ctx.http.query = {}; @@ -56,12 +67,28 @@ module.exports = require("./Transport").compose({ ); return new Promise((r) => this.server.listen(this.port, r)); }, - stopServer() { - return new Promise((r) => { - if (this.server.closeIdleConnections) this.server.closeIdleConnections(); - this.server.close(r); - if (this.server.closeAllConnections) this.server.closeAllConnections(); - }); + /** + * @param [options.timeoutMs=0] {number} How long to wait for the requests in flight to complete. + * After this time, or with 0, the connections of the requests that are still in flight are closed. + */ + async stopServer({ timeoutMs = 0 } = {}) { + this._stopping = true; + const closed = new Promise((r) => this.server.close(r)); + if (this.server.closeIdleConnections) this.server.closeIdleConnections(); + + if (timeoutMs > 0 && this._requestsInFlight > 0) { + await new Promise((resolve) => { + const timer = setTimeout(resolve, timeoutMs); + this._onNoRequestsInFlight = () => { + clearTimeout(timer); + resolve(); + }; + }); + this._onNoRequestsInFlight = null; + } + + if (this.server.closeAllConnections) this.server.closeAllConnections(); + return closed; }, getProcedureName(ctx) { diff --git a/test/server/Allserver.test.js b/test/server/Allserver.test.js index 550eaed..9590456 100644 --- a/test/server/Allserver.test.js +++ b/test/server/Allserver.test.js @@ -215,6 +215,20 @@ describe("Allserver", () => { await promise; assert(stopped); }); + + it("should pass the options to transport stopServer()", async () => { + let stopOptions; + const MockedTransport = VoidTransport.methods({ + async stopServer(options) { + stopOptions = options; + }, + }); + + const server = Allserver({ transport: MockedTransport() }); + await server.stop({ timeoutMs: 100 }); + + assert.deepEqual(stopOptions, { timeoutMs: 100 }); + }); }); describe("introspection", () => { diff --git a/test/server/HttpTransport.test.js b/test/server/HttpTransport.test.js new file mode 100644 index 0000000..bea8ba6 --- /dev/null +++ b/test/server/HttpTransport.test.js @@ -0,0 +1,77 @@ +const assert = require("node:assert/strict"); +const { describe, it } = require("node:test"); +const { setTimeout } = require("node:timers/promises"); + +const { Allserver, HttpTransport } = require("../.."); + +const procedures = { + async slow({ ms }) { + await setTimeout(Number(ms)); + return "done"; + }, +}; + +async function startServer() { + const transport = HttpTransport({ port: 0 }); + const server = Allserver({ procedures, transport, logger: { error() {} } }); + await server.start(); + return { server, url: `http://localhost:${transport.server.address().port}` }; +} + +describe("HttpTransport", () => { + describe("#stopServer", () => { + it("should complete the requests in flight before it closes the connections", async () => { + const { server, url } = await startServer(); + const response = fetch(`${url}/slow?ms=200`).then((res) => res.json()); + await setTimeout(50); + + await server.stop({ timeoutMs: 1000 }); + + assert.equal((await response).slow, "done"); + }); + + it("should close the connections of the requests in flight without a timeout", async () => { + const { server, url } = await startServer(); + const response = fetch(`${url}/slow?ms=200`); + await setTimeout(50); + + await server.stop(); + + await assert.rejects(response); + }); + + it("should close the connections of the requests in flight after the timeout", async () => { + const { server, url } = await startServer(); + const response = fetch(`${url}/slow?ms=2000`); + await setTimeout(50); + + const start = Date.now(); + await server.stop({ timeoutMs: 200 }); + + assert(Date.now() - start < 1000); + await assert.rejects(response); + }); + + it("should stop at once when no request is in flight", async () => { + const { server } = await startServer(); + + const start = Date.now(); + await server.stop({ timeoutMs: 5000 }); + + assert(Date.now() - start < 1000); + }); + + it("should stop accepting new connections", async () => { + const { server, url } = await startServer(); + const slowResponse = fetch(`${url}/slow?ms=200`); + await setTimeout(50); + + const stopped = server.stop({ timeoutMs: 1000 }); + const newResponse = fetch(`${url}/slow?ms=0`); + + await assert.rejects(newResponse); + await slowResponse; + await stopped; + }); + }); +}); From f467ce9d23481644167189d69a6c173fc876c62b Mon Sep 17 00:00:00 2001 From: Vadym Kurachevskyi Date: Wed, 25 Nov 2026 12:04:37 +1100 Subject: [PATCH 2/3] refactor: use server.close() to wait for the requests in flight Node's server.close() already lets the running requests complete. Instead of counting the requests, stop() now calls closeAllConnections() only after timeoutMs, if connections are still open. --- README.md | 7 ++++-- src/server/HttpTransport.js | 46 ++++++++++++------------------------- 2 files changed, 20 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index b07fe4e..15a44ce 100644 --- a/README.md +++ b/README.md @@ -312,7 +312,10 @@ Allserver({ By default, `stop()` closes the connections of the requests that are still in flight. To let them complete first, give a `timeoutMs`: ```js -const server = Allserver({ procedures, transport: HttpTransport({ port: process.env.PORT }) }); +const server = Allserver({ + procedures, + transport: HttpTransport({ port: process.env.PORT }), +}); await server.start(); process.on("SIGTERM", async () => { @@ -321,7 +324,7 @@ process.on("SIGTERM", async () => { }); ``` -The server stops accepting new connections at once and replies to new requests on open keep-alive connections with `Connection: close`. When no request is in flight, or after `timeoutMs`, it closes all connections. Keep `timeoutMs` below the time your platform gives the process to stop (for example, the ECS `stopTimeout`, 30s by default). +The server stops accepting new connections at once and `stop()` resolves when all connections have ended. Idle keep-alive connections end after the server's `keepAliveTimeout` (5s by default). After `timeoutMs`, the server closes all connections that are still open. Keep `timeoutMs` below the time your platform gives the process to stop (for example, the ECS `stopTimeout`, 30s by default). #### Replying non-standard HTTP response from a procedure diff --git a/src/server/HttpTransport.js b/src/server/HttpTransport.js index 36d2cec..c884bf4 100644 --- a/src/server/HttpTransport.js +++ b/src/server/HttpTransport.js @@ -7,9 +7,6 @@ module.exports = require("./Transport").compose({ props: { micro: require("micro"), port: process.env.PORT, - _requestsInFlight: 0, - _stopping: false, - _onNoRequestsInFlight: null, }, init({ port }) { @@ -45,14 +42,6 @@ module.exports = require("./Transport").compose({ startServer(defaultCtx) { this.server = new http.Server( this.micro.serve(async (req, res) => { - this._requestsInFlight += 1; - res.once("close", () => { - this._requestsInFlight -= 1; - if (this._requestsInFlight === 0 && this._onNoRequestsInFlight) this._onNoRequestsInFlight(); - }); - // Tell keep-alive clients to open a new connection, which goes to another server. - if (this._stopping) res.setHeader("Connection", "close"); - const ctx = { ...defaultCtx, http: { req, res, url: parseUrl(req.url) } }; ctx.http.query = {}; @@ -68,27 +57,22 @@ module.exports = require("./Transport").compose({ return new Promise((r) => this.server.listen(this.port, r)); }, /** - * @param [options.timeoutMs=0] {number} How long to wait for the requests in flight to complete. - * After this time, or with 0, the connections of the requests that are still in flight are closed. + * @param [options.timeoutMs=0] {number} How long the requests in flight can take to complete. + * After this time, or with 0, all connections are closed, also the ones with a request in flight. */ - async stopServer({ timeoutMs = 0 } = {}) { - this._stopping = true; - const closed = new Promise((r) => this.server.close(r)); - if (this.server.closeIdleConnections) this.server.closeIdleConnections(); - - if (timeoutMs > 0 && this._requestsInFlight > 0) { - await new Promise((resolve) => { - const timer = setTimeout(resolve, timeoutMs); - this._onNoRequestsInFlight = () => { - clearTimeout(timer); - resolve(); - }; - }); - this._onNoRequestsInFlight = null; - } - - if (this.server.closeAllConnections) this.server.closeAllConnections(); - return closed; + stopServer({ timeoutMs = 0 } = {}) { + return new Promise((r) => { + if (this.server.closeIdleConnections) this.server.closeIdleConnections(); + // Stops accepting new connections. Calls r() when all connections have ended. + this.server.close(r); + if (!this.server.closeAllConnections) return; + if (timeoutMs > 0) { + const timer = setTimeout(() => this.server.closeAllConnections(), timeoutMs); + this.server.once("close", () => clearTimeout(timer)); + } else { + this.server.closeAllConnections(); + } + }); }, getProcedureName(ctx) { From c9e9c7a34495e854b5f462c149758c12aed2a650 Mon Sep 17 00:00:00 2001 From: Vadym Kurachevskyi Date: Wed, 25 Nov 2026 12:10:01 +1100 Subject: [PATCH 3/3] refactor: one timer in HTTP stop(), fewer tests, shorter README stopServer() now uses one timer for both cases: closeAllConnections() runs after timeoutMs (0 by default) and the timer is cleared when the server has closed. Removed two tests that did not check allserver's own behaviour. --- README.md | 2 +- src/server/HttpTransport.js | 16 ++++------------ test/server/HttpTransport.test.js | 22 ---------------------- 3 files changed, 5 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 15a44ce..8f78fec 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,7 @@ process.on("SIGTERM", async () => { }); ``` -The server stops accepting new connections at once and `stop()` resolves when all connections have ended. Idle keep-alive connections end after the server's `keepAliveTimeout` (5s by default). After `timeoutMs`, the server closes all connections that are still open. Keep `timeoutMs` below the time your platform gives the process to stop (for example, the ECS `stopTimeout`, 30s by default). +`stop()` resolves when all connections have ended, which can be up to `keepAliveTimeout` (5s by default) after the last request. After `timeoutMs` it closes the connections that are still open, so keep it below the time your platform gives the process to stop. #### Replying non-standard HTTP response from a procedure diff --git a/src/server/HttpTransport.js b/src/server/HttpTransport.js index c884bf4..4540f90 100644 --- a/src/server/HttpTransport.js +++ b/src/server/HttpTransport.js @@ -61,18 +61,10 @@ module.exports = require("./Transport").compose({ * After this time, or with 0, all connections are closed, also the ones with a request in flight. */ stopServer({ timeoutMs = 0 } = {}) { - return new Promise((r) => { - if (this.server.closeIdleConnections) this.server.closeIdleConnections(); - // Stops accepting new connections. Calls r() when all connections have ended. - this.server.close(r); - if (!this.server.closeAllConnections) return; - if (timeoutMs > 0) { - const timer = setTimeout(() => this.server.closeAllConnections(), timeoutMs); - this.server.once("close", () => clearTimeout(timer)); - } else { - this.server.closeAllConnections(); - } - }); + this.server.closeIdleConnections?.(); + const timer = setTimeout(() => this.server.closeAllConnections?.(), timeoutMs); + // Stops accepting new connections. Resolves when all connections have ended. + return new Promise((r) => this.server.close(r)).finally(() => clearTimeout(timer)); }, getProcedureName(ctx) { diff --git a/test/server/HttpTransport.test.js b/test/server/HttpTransport.test.js index bea8ba6..21578a9 100644 --- a/test/server/HttpTransport.test.js +++ b/test/server/HttpTransport.test.js @@ -51,27 +51,5 @@ describe("HttpTransport", () => { assert(Date.now() - start < 1000); await assert.rejects(response); }); - - it("should stop at once when no request is in flight", async () => { - const { server } = await startServer(); - - const start = Date.now(); - await server.stop({ timeoutMs: 5000 }); - - assert(Date.now() - start < 1000); - }); - - it("should stop accepting new connections", async () => { - const { server, url } = await startServer(); - const slowResponse = fetch(`${url}/slow?ms=200`); - await setTimeout(50); - - const stopped = server.stop({ timeoutMs: 1000 }); - const newResponse = fetch(`${url}/slow?ms=0`); - - await assert.rejects(newResponse); - await slowResponse; - await stopped; - }); }); });