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

Exp: HTTP/2 #2099

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from 14 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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@
"ansis": "^3.2.0",
"node-mocks-http": "^1.16.1",
"openapi3-ts": "^4.4.0",
"ramda": "^0.30.1"
"ramda": "^0.30.1",
"spdy-fixes": "^4.0.5"
},
"peerDependencies": {
"@types/compression": "^1.7.5",
Expand Down
5 changes: 3 additions & 2 deletions src/config-type.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type compression from "compression";
import { IRouter, Request, RequestHandler } from "express";
import type fileUpload from "express-fileupload";
import { ServerOptions } from "node:https";
import type https from "node:https";
import { BuiltinLoggerConfig } from "./builtin-logger";
import { AbstractEndpoint } from "./endpoint";
import { AbstractLogger, ActualLogger } from "./logger-helpers";
Expand Down Expand Up @@ -146,7 +146,7 @@ export interface HttpConfig {

interface HttpsConfig extends HttpConfig {
/** @desc At least "cert" and "key" options required. */
options: ServerOptions;
options: https.ServerOptions;
}

export interface ServerConfig<TAG extends string = string>
Expand All @@ -155,6 +155,7 @@ export interface ServerConfig<TAG extends string = string>
http?: HttpConfig;
/** @desc HTTPS server configuration. */
https?: HttpsConfig;
http2?: boolean;
/**
* @desc Custom JSON parser.
* @default express.json()
Expand Down
3 changes: 2 additions & 1 deletion src/graceful-shutdown.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import http from "node:http";
import https from "node:https";
import http2 from "node:http2";
import { setInterval } from "node:timers/promises";
import type { Socket } from "node:net";
import type { ActualLogger } from "./logger-helpers";
Expand All @@ -12,7 +13,7 @@ import {
} from "./graceful-helpers";

export const monitor = (
servers: Array<http.Server | https.Server>,
servers: Array<http.Server | https.Server | http2.Http2SecureServer>,
{ timeout = 1e3, logger }: { timeout?: number; logger?: ActualLogger } = {},
) => {
let pending: Promise<PromiseSettledResult<void>[]> | undefined;
Expand Down
30 changes: 25 additions & 5 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import express from "express";
import type compression from "compression";
import http from "node:http";
import https from "node:https";
import http2 from "node:http2";
import spdy from "spdy-fixes";
import { BuiltinLogger } from "./builtin-logger";
import {
AppConfig,
Expand Down Expand Up @@ -97,18 +99,36 @@ export const createServer = async (config: ServerConfig, routing: Routing) => {
app.use(parserFailureHandler, notFoundHandler);

const makeStarter =
(server: http.Server | https.Server, subject: HttpConfig["listen"]) => () =>
(
server: http.Server | https.Server | http2.Http2SecureServer,
subject: HttpConfig["listen"],
) =>
() =>
server.listen(subject, () => rootLogger.info("Listening", subject));

const created: Array<http.Server | https.Server> = [];
const starters: Array<() => http.Server | https.Server> = [];
const created: Array<http.Server | https.Server | http2.Http2SecureServer> =
[];
const starters: Array<
() => http.Server | https.Server | http2.Http2SecureServer
> = [];
if (config.http) {
const httpServer = http.createServer(app);
const httpServer = config.http2
? spdy.createServer(
http.Server,
{ spdy: { protocols: ["h2", "http/1.1"] } },
app,
)
: http.createServer(app);
created.push(httpServer);
starters.push(makeStarter(httpServer, config.http.listen));
}
if (config.https) {
const httpsServer = https.createServer(config.https.options, app);
const httpsServer = config.http2
? spdy.createServer(
{ ...config.https.options, spdy: { protocols: ["h2", "http/1.1"] } },
app,
)
: https.createServer(config.https.options, app);
created.push(httpsServer);
starters.push(makeStarter(httpsServer, config.https.listen));
}
Expand Down
5 changes: 5 additions & 0 deletions tests/express-mock.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { makeRequestMock, makeResponseMock } from "../src/testing";

const expressJsonMock = vi.fn();
const expressRawMock = vi.fn();
const compressionMock = vi.fn();
Expand Down Expand Up @@ -25,6 +27,9 @@ const expressMock = () => appMock;
expressMock.json = () => expressJsonMock;
expressMock.raw = () => expressRawMock;
expressMock.static = staticMock;
expressMock.application = appMock;
expressMock.request = makeRequestMock();
expressMock.response = makeResponseMock();

vi.mock("express", () => ({ default: expressMock }));

Expand Down
28 changes: 28 additions & 0 deletions tests/system/http2.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createConfig, createServer } from "../../src";
import { givePort, signCert } from "../helpers";
import { fetch, Agent } from "undici";

describe("HTTP2", async () => {
const port = givePort();
const config = createConfig({
https: { listen: port, options: signCert() },
http2: true,
cors: true,
startupLogo: false,
logger: { level: "info" },
});
const {
servers: [server],
} = await createServer(config, {});
await vi.waitFor(() => assert(server.listening), { timeout: 1e4 });

test("should handle requests", async () => {
const response = await fetch(`https://localhost:${port}`, {
dispatcher: new Agent({
connect: { rejectUnauthorized: false },
allowH2: true,
}),
});
console.log(response);
});
});
36 changes: 35 additions & 1 deletion tests/unit/graceful-shutdown.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import http from "node:http";
import https from "node:https";
import http2 from "node:http2";
import { Agent, fetch } from "undici";
import { setTimeout } from "node:timers/promises";
import { monitor } from "../../src/graceful-shutdown";
import { givePort, signCert } from "../helpers";

describe("monitor()", () => {
const cert = signCert();

const makeHttpServer = (handler: http.RequestListener) =>
new Promise<[http.Server, number]>((resolve) => {
const subject = http.createServer(handler);
Expand All @@ -15,7 +18,16 @@ describe("monitor()", () => {

const makeHttpsServer = (handler: http.RequestListener) =>
new Promise<[https.Server, number]>((resolve) => {
const subject = https.createServer(signCert(), handler);
const subject = https.createServer(cert, handler);
const port = givePort();
subject.listen(port, () => resolve([subject, port]));
});

const makeHttp2Server = (
handler: Parameters<(typeof http2)["createSecureServer"]>[1],
) =>
new Promise<[http2.Http2SecureServer, number]>((resolve) => {
const subject = http2.createSecureServer(cert, handler);
const port = givePort();
subject.listen(port, () => resolve([subject, port]));
});
Expand Down Expand Up @@ -168,6 +180,28 @@ describe("monitor()", () => {
},
);

test("terminates http2 server", { timeout: 500 }, async () => {
const handler = (async (req, res) => {
expect(req.httpVersion).toBe("2.0");
await setTimeout(350);
res.end("foo");
}) as Parameters<typeof makeHttp2Server>[0];
const [httpsServer, port] = await makeHttp2Server(handler);
const graceful = monitor([httpsServer], { timeout: 150 });
void fetch(`https://localhost:${port}`, {
dispatcher: new Agent({
connect: { rejectUnauthorized: false },
allowH2: true,
}),
}).catch(vi.fn());
await setTimeout(50);
expect(graceful.sockets.size).toBeGreaterThan(0);
void graceful.shutdown();
await setTimeout(150);
expect(graceful.sockets.size).toBe(0);
await graceful.shutdown();
});

test(
"closes immediately after in-flight connections are closed (#16)",
{ timeout: 1e3 },
Expand Down
Loading
Loading