Repository navigation
Conversation
Add the workspace apps/mock-server: a TypeScript HTTP server on Node's built-in http module, without a build step (Node strips the types) and without runtime dependencies. It has a router with a JSON 404 default, open CORS with preflight answers, GET /healthz, PORT (default 8080), one log line per request, a 1 MiB body limit (413) and an in-memory store loaded from fixture files, with at most 100 created items per collection. The API stubs follow in their own pull requests. Integration tests with node:test start the server on a free port and send real HTTP requests; the workspace's test and lint scripts run in the existing CI jobs. The Contributing page documents the server. Closes #588 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cap the created items of each collection also by their total size as JSON (default 4 MiB), dropping the oldest but never the newest, since parsed bodies take many times their size in memory. Log requests whose client closed the connection first as "aborted" instead of as server errors. Answer HEAD with the GET routes. Note in the code that store items are not copies and that new methods need CORS too; document the changes and that Codecov doesn't cover the mock server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Hand out copies from the store, so that handlers can't change stored items or grow them past the size cap. Skip the error log only for clients that closed the connection while sending the body, and still log unexpected errors after a disconnect. Wait for the log line of an aborted request instead of a fixed delay; rewrap the docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reviewer's GuideData structuresAdd the in-memory collection store that loads fixture arrays, keeps created items separate, enforces per-collection caps, and returns copies to callers.
APIDefine the handler context, replies, HTTP errors, JSON parsing helper, and route-matching interface used by API stubs.
Uses of the APIProvide the central route-registration list where API stubs can be added as they are implemented.
ImplementationImplement the HTTP server behavior, including CORS, request limits, routing, error replies, and request logging.
Load fixtures, start the server on the configured port, and handle graceful shutdown signals.
Parse and validate the optional port environment setting, defaulting to port 8080.
ConfigurationConfigure the mock-server workspace scripts and development dependencies, TypeScript checking, and ESLint settings.
DocumentationDocument the mock server's purpose, operation, limits, fixture workflow, and extension points for API stubs.
TestsAdd unit and integration tests for port parsing, server behavior, fixture loading, and store semantics, along with test-only fixture data and helpers.
Lock files and vendored codeUpdate the npm lockfile to record the new workspace and its dependency resolution.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Documentation build overview
3 files changed± docs/contributing/index.html± docs/providers/index.html± docs/trs/components/tools/index.html |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #598 +/- ##
==========================================
+ Coverage 77.02% 77.12% +0.09%
==========================================
Files 73 73
Lines 18787 18787
Branches 1178 1178
==========================================
+ Hits 14471 14489 +18
+ Misses 4295 4282 -13
+ Partials 21 16 -5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit f291ad7 #588 feat(mock): scaffold the docs mock server · 6 of 6 met
|
There was a problem hiding this comment.
Hey - I've found 10 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="apps/mock-server/src/server.ts" line_range="47" />
<code_context>
+ const tooLarge = () =>
+ new HttpError(413, `The request body exceeds ${limit} bytes`);
+ if (Number(req.headers["content-length"]) > limit) {
+ req.resume();
+ reject(tooLarge());
+ return;
</code_context>
<issue_to_address>
**Oversized disconnects crash server**
When a client disconnects while an oversized request body is being drained, `readBody` calls `req.resume()` and rejects before attaching the request error listener, so the disconnect emits an unhandled stream error and terminates the server process.
Attach the request error listener before resuming or draining the oversized body.
</issue_to_address>
### Comment 2
<location path="apps/mock-server/src/server.ts" line_range="65" />
<code_context>
+ reject(tooLarge());
+ return;
+ }
+ chunks.push(chunk);
+ });
+ req.on("end", () => resolve(Buffer.concat(chunks)));
</code_context>
<issue_to_address>
**Concurrent uploads exhaust memory**
When many anonymous clients upload bodies concurrently, `readBody` buffers up to 1 MiB independently for every request, while the server has no global concurrency or connection limit; enough simultaneous uploads therefore consume unbounded aggregate memory and can take the public mock server down.
Add a global limit on concurrent body reads or enforce an equivalent aggregate request limit at the server's ingress.
</issue_to_address>
### Comment 3
<location path="apps/mock-server/src/server.ts" line_range="113" />
<code_context>
+ queryString: string
+ ): Promise<Reply> => {
+ const method = req.method ?? "GET";
+ if (method === "OPTIONS") {
+ // Preflight: allow whatever headers the client asks for, for a day
+ const requested = req.headers["access-control-request-headers"];
</code_context>
<issue_to_address>
**Oversized preflights bypass body limit**
When an unauthenticated client sends an OPTIONS request with a body larger than the configured limit, `handle` returns the preflight reply before `readBody` enforces `maxBodyBytes` or closes oversized connections, so the request bypasses the limit, keeps connections occupied while the body is received, and can exhaust server resources.
Enforce the body-size limit for OPTIONS requests before returning a preflight reply, and close connections for oversized bodies.
</issue_to_address>
### Comment 4
<location path="apps/mock-server/src/store.ts" line_range="145-147" />
<code_context>
+ collection.created.push({ item: structuredClone(item), size });
+ collection.bytes += size;
+ while (
+ collection.created.length > 1 &&
+ (collection.created.length > this.maxCreated ||
+ collection.bytes > this.maxCreatedBytes)
+ ) {
+ const [oldest] = collection.created.splice(0, 1);
</code_context>
<issue_to_address>
**Stored data exceeds advertised memory cap**
When a route handler passes `Store.create` an item whose JSON size alone exceeds the configured byte cap, `Store.create` keeps the newest item when it alone exceeds `maxCreatedBytes`, so a route handler can leave a collection over the documented 4 MiB limit and defeat that memory bound.
Reject an item larger than the byte cap instead of retaining it, or revise the contract and provide a separate hard memory bound.
</issue_to_address>
### Comment 5
<location path="apps/mock-server/src/server.ts" line_range="180" />
<code_context>
+ send(res, errorReply(error.status, error.message));
+ return;
+ }
+ log(`Unexpected error: ${error}`);
+ send(res, errorReply(500, "Internal server error"));
+ });
</code_context>
<issue_to_address>
**Some thrown values bypass 500 handling**
When a handler throws a `Symbol` or a value whose string conversion throws, interpolating a thrown `Symbol` (or an object whose string conversion throws) raises a new error inside the catch callback, so it never sends the promised generic `500` and can leave the request unanswered.
Make error formatting non-throwing, or avoid converting arbitrary thrown values before sending the generic `500`.
</issue_to_address>
### Comment 6
<location path="apps/mock-server/src/server.ts" line_range="91" />
<code_context>
+ .writeHead(reply.status, {
+ "Content-Type": "application/json; charset=utf-8",
+ })
+ .end(JSON.stringify(reply.body));
+};
+
</code_context>
<issue_to_address>
**Invalid reply body hangs request**
When a route returns a body that cannot be JSON-serialized, such as one containing a BigInt or a circular reference, `send` writes the response headers before `JSON.stringify(reply.body)` runs. If serialization throws, the error handler's second call to `send` returns because `res.headersSent` is true, leaving the original response unfinished and the caller waiting.
Serialize the reply body before writing headers, so serialization failures can be converted into a completed 500 response.
</issue_to_address>
### Comment 7
<location path="apps/mock-server/src/main.ts" line_range="21" />
<code_context>
+for (const signal of ["SIGINT", "SIGTERM"] as const) {
+ process.once(signal, () => {
+ server.close(() => process.exit(0));
+ server.closeAllConnections();
+ });
+}
</code_context>
<issue_to_address>
**Shutdown aborts active requests**
When SIGINT or SIGTERM arrives while requests are in flight, `server.close()` stops accepting connections, but the immediate `server.closeAllConnections()` call destroys active sockets before their responses finish, so callers receive failed requests.
Let `server.close()` drain active connections and remove the immediate `server.closeAllConnections()` call.
</issue_to_address>
### Comment 8
<location path="apps/mock-server/src/server.ts" line_range="180" />
<code_context>
+ send(res, errorReply(error.status, error.message));
+ return;
+ }
+ log(`Unexpected error: ${error}`);
+ send(res, errorReply(500, "Internal server error"));
+ });
</code_context>
<issue_to_address>
**Unexpected failures produce duplicate logs**
When a handler throws an error other than `HttpError`, the catch branch logs the unexpected error, then `send` closes the response and the `close` listener logs the request, producing two lines for one request instead of the documented one-line format.
Include unexpected-error details in the per-request log instead of emitting a separate error line.
</issue_to_address>
### Comment 9
<location path="apps/mock-server/src/server.ts" line_range="33" />
<code_context>
+
+// The methods of the `Router` helpers; add any other method that a stub
+// uses here, too
+const ALLOWED_METHODS = "GET, POST, PUT, DELETE, OPTIONS";
+
+// The client closed the connection while sending the body: nothing to
</code_context>
<issue_to_address>
**Cross-origin HEAD requests are blocked**
When a browser sends a cross-origin HEAD request with a non-safelisted header, `ALLOWED_METHODS` omits `HEAD` even though the router maps `HEAD` to `GET`; a browser preflighting a cross-origin HEAD request with a non-safelisted header rejects it before it reaches the handler.
Include HEAD in the preflight allowed-methods list if HEAD is intended to work cross-origin.
Also at `apps/mock-server/src/router.ts:57`.
</issue_to_address>
### Comment 10
<location path="apps/mock-server/package.json" line_range="8" />
<code_context>
+ "license": "Apache-2.0",
+ "type": "module",
+ "scripts": {
+ "dev": "node --experimental-strip-types --disable-warning=ExperimentalWarning --watch src/main.ts",
+ "start": "node --experimental-strip-types --disable-warning=ExperimentalWarning src/main.ts",
+ "test": "node --experimental-strip-types --disable-warning=ExperimentalWarning --test \"test/**/*.test.ts\"",
</code_context>
<issue_to_address>
**Fixture edits stay stale**
When a developer edits or adds a fixture while `npm run dev` is running, node’s `--watch` does not track fixture files read by `Store.load`, so editing or adding a fixture does not restart the dev server and it continues serving the old fixture data.
Watch the fixtures directory and restart or reload the store when its files change.
</issue_to_address>Sourcery assessment
Approval pending. 10 findings to address first.
Blocking findings: apps/mock-server/src/server.ts:47, apps/mock-server/src/server.ts:65, apps/mock-server/src/server.ts:113, apps/mock-server/src/store.ts:147, apps/mock-server/src/server.ts:180, and 5 more
- Listen for request errors before draining an oversized body, so that a client leaving then can't crash the server - Cap open connections (default 100), bounding the memory of bodies - Apply the body limit to preflight requests, too - Reject a created item larger than the collection's size cap (413) - Answer 500 for any thrown value and for bodies that aren't serializable (serialize before writing the head) - Log unexpected errors in the request's line, not a second one - Allow HEAD in CORS preflights - Let requests in flight finish on SIGTERM (at most 10 s) - Restart `npm run dev` on fixture changes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Scaffold of the mock backend for the docs previews (parent #419): a new
workspace
apps/mock-serverwith the server and its tests, no API stubs yet.The stubs (Service Registry #589, TRS #590, WES #591) follow in their own
pull requests.
404default (GA4GH error format{"msg": ..., "status_code": ...}),HttpErrorfor handler errors,500without details for anything else
GET, POST, PUT, DELETE, OPTIONS, preflight answers(
204) on any path, echoing the requested headersGET /healthz, port fromPORT(default 8080), one log line per request(without the query string;
abortedif the client left first),HEADasGET, graceful stop onSIGINT/SIGTERMfixtures/<collection>.jsonis loaded on start, neverwritten; created items are kept apart from the fixtures; a restart or
reset()drops them;list/find/createhand out copies413(byContent-Length, andwhile reading chunked bodies), at most 100 created items per collection
and at most 4 MiB of them as JSON (oldest created dropped, fixtures stay;
a single larger item gets
413; parsed JSON takes many times its size inmemory), at most 100 open connections, 30 s request timeout
turbo.json:PORTdeclared for thedevtask (required by theturbo/no-undeclared-env-varslint rule)Tech choices (for @anuragxxd)
Kept as small as I could; happy to change any of these:
If you prefer MSW there, this PR becomes moot (the stubs would move into the
docs app) and I'll close it.
httpmodule anda ~70-line router. The API surface is a handful of GA4GH endpoints with
in-memory data; Express/Fastify/json-server would add dependencies (and
Dependabot PRs) to a public service without buying much. Dev dependencies
only:
typescript,eslint,@types/node, the shared eslint config.(
--experimental-strip-types; enabled by default from Node 22.18/23.6, theflag keeps the repo's floor 22.12 working).
tsc --noEmittype-checks inthe
lintscript, so the existinglintjob covers it. The image (build(mock): release the mock server image #592)can run
src/main.tsdirectly.node:test(no extra test runner): integration tests startthe server on a free port and send real HTTP requests with
fetch. They runthrough the workspace's
testscript, so the existingtestjob and theCI passedgate include them. Coverage isn't collected for this workspace(Codecov only reads
packages/*/coverage); can be added later if wanted.Verification
npm testinapps/mock-server: 45 tests pass (repeated runs stable) (health, CORS preflight andheaders on errors, 404 for unknown paths and methods, path parameters,
malformed encodings, handler errors, 500, 204, invalid JSON, one log line
per request without the query, body limit by
Content-Length, chunked, atthe limit and the 1 MiB default, aborted requests, HEAD, fixtures, item
and size caps, copies, reset on restart,
store unit tests,
PORTparsing)npm run test -- --coverage(as CI passes it through turbo) also passesnpx turbo run test lint --filter=ecc-mock-server: both tasks passnpm run lintat the root (all workspaces, includes the build): 22/22 taskssuccessful
PORT=18588 npm start,curl /healthz→{"status":"ok"},OPTIONS /x→204with the CORS headers, one log line eachoversized body is drained, connection cap, body limit for preflights, hard
size cap, 500 for odd thrown values and unserializable bodies, single log
line with the error, HEAD in CORS, graceful shutdown, fixture watching),
each with a test where it changes behaviour
CI passedgreen (Lint, Test on Node 22 and 24, CodeQL, Read the Docspreview); the Node 24 job ran the mock server's tests with CI's
--coveragepassthrough (all pass)browsers installed; unchanged by this PR) — CI runs them.
Declined review findings
Two rounds of adversarial and quality review; fixed: memory budget (size cap),
logging of aborted requests, HEAD, copies from the store, real errors after a
disconnect, a timer-based test, comments and docs wrapping. Declined:
--coveragepassthrough is harmless here (all tests pass with it), and wiring Node's
coverage into the shared
Collect coveragestep changes CI for one smallapp; documented on the Contributing page instead. Can follow if wanted.
package-lock.jsondiff: npm's own re-hoisting for the newworkspace. The workspace needs eslint 8 (the root hoists eslint 7), like the
other workspaces that nest their own copy; the docs app builds and lints
unchanged (root
npm run lint, which builds everything, passes).PORTinturbo.json: required by theturbo/no-undeclared-env-varslint rule of the shared eslint config; declaring it beats disabling the
rule.
@elixir-cloudeslint config alreadyenforces prettier (
prettier/prettier: error).Open questions
None.
Closes #588
🤖 Generated with Claude Code
Summary by Sourcery
Establish the fixture-backed mock server foundation for documentation live previews, ready for API-specific stubs in follow-up changes.
New Features:
Enhancements:
Build:
Documentation:
Tests: