diff --git a/CMakeLists.txt b/CMakeLists.txt index 0624868e1..9b1480dc4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -200,4 +200,7 @@ if(ONE_TESTS) add_subdirectory(test/unit/self) endif() add_subdirectory(test/cli) + if(ONE_SERVER) + add_subdirectory(test/cli/http) + endif() endif() diff --git a/src/http/include/sourcemeta/one/http_server.h b/src/http/include/sourcemeta/one/http_server.h index 9de0081f6..3a17ff698 100644 --- a/src/http/include/sourcemeta/one/http_server.h +++ b/src/http/include/sourcemeta/one/http_server.h @@ -14,6 +14,7 @@ #include // std::latch #include // std::unique_ptr, std::make_unique #include // std::mutex, std::scoped_lock +#include // std::string #include // std::string_view #include // std::thread, std::thread::hardware_concurrency #include // write, STDERR_FILENO @@ -36,8 +37,11 @@ class HTTPServer { template HTTPServer(const std::uint16_t port, RequestHandler on_request, - ListenCallback on_listen, ErrorCallback on_error) { - HTTPServer::concurrency = std::max(1u, std::thread::hardware_concurrency()); + ListenCallback on_listen, ErrorCallback on_error, + const std::string &host = {}) { + // An ephemeral listener has one bound port to report. + HTTPServer::concurrency = + port == 0 ? 1u : std::max(1u, std::thread::hardware_concurrency()); HTTPServer::round_robin.store(0, std::memory_order_relaxed); HTTPServer::should_stop.store(false, std::memory_order_relaxed); HTTPServer::workers_alive.store(HTTPServer::concurrency, @@ -89,8 +93,8 @@ class HTTPServer { threads.reserve(HTTPServer::concurrency); for (unsigned int index{0}; index < HTTPServer::concurrency; ++index) { threads.emplace_back(std::make_unique( - [index, port, &on_request, &on_listen, &on_error, &setup_barrier, - &setup_mutex]() -> void { + [index, port, &host, &on_request, &on_listen, &on_error, + &setup_barrier, &setup_mutex]() -> void { // uWS provides slow-loris protection out of the box, so // we don't have to configure any of it ourselves. uWS::SocketContextOptions options{}; @@ -118,7 +122,7 @@ class HTTPServer { { std::scoped_lock guard{setup_mutex}; app->listen( - static_cast(port), + host, static_cast(port), [port, &on_listen, &on_error](us_listen_socket_t *const socket) -> void { if (socket) { @@ -127,7 +131,7 @@ class HTTPServer { true, reinterpret_cast(socket)))}; assert(bound_port > 0); - assert(port == bound_port); + assert(port == 0 || port == bound_port); on_listen(bound_port); } else { on_error(port); diff --git a/test/cli/http/CMakeLists.txt b/test/cli/http/CMakeLists.txt new file mode 100644 index 000000000..fc52b7db6 --- /dev/null +++ b/test/cli/http/CMakeLists.txt @@ -0,0 +1,11 @@ +find_program(NODE_BIN NAMES node REQUIRED) + +sourcemeta_executable(NAMESPACE sourcemeta PROJECT one NAME http + VARIANT wire_echo SOURCES echo.cc) +target_link_libraries(sourcemeta_one_http_wire_echo + PRIVATE sourcemeta::one::http) + +add_test(NAME one.http.wire COMMAND "${NODE_BIN}" + "${CMAKE_CURRENT_SOURCE_DIR}/wire.test.cjs" + "$") +set_tests_properties(one.http.wire PROPERTIES TIMEOUT 30) diff --git a/test/cli/http/README.md b/test/cli/http/README.md new file mode 100644 index 000000000..e104929f6 --- /dev/null +++ b/test/cli/http/README.md @@ -0,0 +1,35 @@ +# HTTP/1.1 wire tests + +The CTest target `one.http.wire` starts a test-only echo handler using +One's HTTPServer, HTTPRequest, and HTTPResponse. It binds IPv4 loopback +at an OS-selected port and announces the port on stdout. The runner waits +for the announcement, bounds socket and process operations, and shuts down +the child on success and failure. The existing Docker CTest run picks up +this test when ONE_TESTS and ONE_SERVER are enabled. + +Run from a One build configured with `ONE_TESTS=ON` and `ONE_SERVER=ON`, +with Node available: + +```sh +cmake --build build --target sourcemeta_one_http_wire_echo +ctest --test-dir build -R '^one.http.wire$' --output-on-failure +``` + +The cases are independently written from RFC 9112 and motivated by the +reviewed categories in the [h1spec revision pinned by uWebSockets v20.81.0](https://github.com/uNetworking/h1spec/tree/f0a5650a20c575fbea0f7179a3a9cfa50f20ba6e). +The test takes no runtime dependency on h1spec or Deno. + +| Case | Expected outcome | Basis | +| --- | --- | --- | +| Origin-form GET and a request split across writes | 200 and exact path | RFC 9112 sections 2.2 and 3.2.1 | +| Fixed-length binary body | 200 and exact bytes | RFC 9112 section 6.3 | +| Chunked body | 200 and decoded bytes | RFC 9112 section 7.1 | +| Missing Host | 400 | RFC 9112 section 3.2 | +| Bodies of 64 and 65 bytes | Exact echo at the cap and 413 above it | One HTTPRequest::body fixture policy | + +The remaining h1spec cases are outside this initial subset. In particular, +this gate excludes timeout-only cases, special method or interim-response +handling, and cases whose broad status ranges need separate RFC review. +The split-write checks complete the requests and verify the response. +TCP is a byte stream, so the test does not assume that each client write +maps to a separate server read. diff --git a/test/cli/http/echo.cc b/test/cli/http/echo.cc new file mode 100644 index 000000000..0a70d190e --- /dev/null +++ b/test/cli/http/echo.cc @@ -0,0 +1,43 @@ +#include + +#include + +#include // std::uint16_t +#include // std::exception_ptr +#include // std::cout, std::endl +#include // std::string + +auto main() -> int { + using namespace sourcemeta::one; + const HTTPServer server{ + 0, + [](HTTPRequest &request, HTTPResponse &response) { + if (request.method() == "get") { + response.send(request, request.path(), Encoding::Identity); + } else { + request.body( + [](HTTPRequest &snapshot, HTTPResponse &reply, std::string body, + const bool too_big) { + if (too_big) { + reply.write_status( + sourcemeta::core::HTTP_STATUS_CONTENT_TOO_LARGE); + reply.send_without_content(); + } else { + reply.send(snapshot, body, Encoding::Identity); + } + }, + [](HTTPRequest &, HTTPResponse &reply, std::exception_ptr) { + reply.write_status( + sourcemeta::core::HTTP_STATUS_INTERNAL_SERVER_ERROR); + reply.send_without_content(); + }, + 64); + } + }, + [](const std::uint16_t port) { std::cout << port << std::endl; }, + [](const std::uint16_t port) { + std::cerr << "Failed to listen on 127.0.0.1:" << port << '\n'; + }, + "127.0.0.1"}; + return server.stopped_gracefully() ? 0 : 1; +} diff --git a/test/cli/http/wire.test.cjs b/test/cli/http/wire.test.cjs new file mode 100644 index 000000000..88b2bd8b1 --- /dev/null +++ b/test/cli/http/wire.test.cjs @@ -0,0 +1,122 @@ +const assert = require("node:assert/strict"); +const { spawn } = require("node:child_process"); +const { once } = require("node:events"); +const { createConnection } = require("node:net"); +const { createInterface } = require("node:readline"); +const { setTimeout: delay } = require("node:timers/promises"); + +const HOST = "127.0.0.1"; +const DEADLINE = 3000; + +function request(port, parts) { + return new Promise((resolve, reject) => { + const socket = createConnection({ host: HOST, port }); + const chunks = []; + const deadline = setTimeout(() => socket.destroy(new Error("Response deadline exceeded")), DEADLINE); + socket.on("data", (chunk) => chunks.push(chunk)); + socket.once("error", reject); + socket.once("close", (failed) => { + clearTimeout(deadline); + if (!failed) resolve(Buffer.concat(chunks)); + }); + socket.once("connect", async () => { + try { + for (const [index, part] of parts.entries()) { + if (index > 0) { + await delay(40); + assert.equal(chunks.length, 0, "response arrived before the request was complete"); + assert.equal(socket.destroyed, false, "connection closed before the request was complete"); + } + socket.write(part); + } + } catch (error) { + socket.destroy(error); + } + }); + }); +} + +function checkResponse(raw, status, expectedBody) { + const split = raw.indexOf("\r\n\r\n"); + assert.ok(split > 0, "expected a complete response header block"); + const [line, ...headers] = raw.subarray(0, split).toString("latin1").split("\r\n"); + assert.equal(Number(/^HTTP\/1\.1 (\d{3})(?: |$)/.exec(line)?.[1]), status, line); + if (expectedBody !== undefined) { + const body = Buffer.from(expectedBody); + assert.deepEqual(raw.subarray(split + 4), body); + assert.deepEqual(headers.filter((header) => /^content-length:/i.test(header)) + .map((header) => header.split(":")[1].trim()), [String(body.length)]); + } +} + +async function run(port) { + const get = "GET /example?query=1 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; + const post = "POST /echo HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"; + const binary = Buffer.from([0, 0x41, 0xff, 0x0a]); + // These cases re-express behaviors covered by h1spec. See README.md. + const cases = [ + ["GET request target", [get], 200, "/example"], + ["request line and header split across writes", [get.slice(0, 9), get.slice(9, 30), get.slice(30)], 200, "/example"], + ["fixed-length binary body", [post + "Content-Length: 4\r\n\r\n", binary], 200, binary], + ["chunked body", [post + "Transfer-Encoding: chunked\r\n\r\n2\r\nhe\r\n3\r\nllo\r\n0\r\n\r\n"], 200, "hello"], + ["missing Host", ["GET /example HTTP/1.1\r\nConnection: close\r\n\r\n"], 400], + // The body limit is specific to the test fixture and exercises One's wrapper. + ["body at the limit", [post + "Content-Length: 64\r\n\r\n" + "a".repeat(64)], 200, "a".repeat(64)], + ["body above the limit", [post + "Content-Length: 65\r\n\r\n" + "a".repeat(65)], 413], + ]; + for (const [name, parts, status, body] of cases) { + try { + checkResponse(await request(port, parts), status, body); + console.log("PASS " + name); + } catch (error) { + throw new Error(name + ": " + error.message, { cause: error }); + } + } +} + +async function main() { + const child = spawn(process.argv[2], [], { stdio: ["ignore", "pipe", "inherit"] }); + const lines = createInterface({ input: child.stdout }); + const ready = once(lines, "line").then(([line]) => Number(line)); + const closed = once(child, "close"); + let timeout; + let failed = false; + const readinessDeadline = new Promise((_, reject) => { + timeout = setTimeout(() => reject(new Error( + "Echo server did not announce readiness before the deadline" + )), DEADLINE); + }); + try { + const port = await Promise.race([ + ready, + readinessDeadline, + closed.then(([code, signal]) => { throw new Error("Echo server exited before readiness: " + (signal || code)); }), + ]); + clearTimeout(timeout); + assert.ok(Number.isInteger(port) && port > 0 && port <= 65535, "expected an ephemeral port"); + await run(port); + } catch (error) { + failed = true; + throw error; + } finally { + clearTimeout(timeout); + lines.close(); + child.kill("SIGTERM"); + const kill = setTimeout(() => child.kill("SIGKILL"), DEADLINE); + try { + const [code, signal] = await closed; + assert.equal(signal, null, "echo server terminated by " + signal); + assert.equal(code, 0, "expected a graceful server exit"); + } catch (shutdownError) { + if (!failed) throw shutdownError; + console.error("Echo server cleanup also failed:", shutdownError.message); + } finally { + clearTimeout(kill); + } + } +} + +main().catch((error) => { + console.error(error); + process.exitCode = 1; +});