Skip to content

feat(mock): scaffold the docs mock server - #598

Open
uniqueg wants to merge 5 commits into
devfrom
feat/588-mock-server-scaffold
Open

uniqueg wants to merge 5 commits into
devfrom
feat/588-mock-server-scaffold

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Scaffold of the mock backend for the docs previews (parent #419): a new
workspace apps/mock-server with the server and its tests, no API stubs yet.
The stubs (Service Registry #589, TRS #590, WES #591) follow in their own
pull requests.

  • Router with a JSON 404 default (GA4GH error format
    {"msg": ..., "status_code": ...}), HttpError for handler errors, 500
    without details for anything else
  • CORS: any origin, GET, POST, PUT, DELETE, OPTIONS, preflight answers
    (204) on any path, echoing the requested headers
  • GET /healthz, port from PORT (default 8080), one log line per request
    (without the query string; aborted if the client left first), HEAD as
    GET, graceful stop on SIGINT/SIGTERM
  • In-memory store: each fixtures/<collection>.json is loaded on start, never
    written; created items are kept apart from the fixtures; a restart or
    reset() drops them; list/find/create hand out copies
  • Abuse limits: request bodies above 1 MiB get 413 (by Content-Length, and
    while 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 in
    memory), at most 100 open connections, 30 s request timeout
  • Docs: "Mock server" section on the Contributing page; one line in the README
  • turbo.json: PORT declared for the dev task (required by the
    turbo/no-undeclared-env-vars lint rule)

Tech choices (for @anuragxxd)

Kept as small as I could; happy to change any of these:

  • Deployed server rather than MSW: this follows the plan proposed in Create Mock APIs for All Services in Documentation and Demo Pages #419.
    If you prefer MSW there, this PR becomes moot (the stubs would move into the
    docs app) and I'll close it.
  • No framework, no runtime dependencies: Node's built-in http module and
    a ~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.
  • TypeScript without a build step: Node strips the types
    (--experimental-strip-types; enabled by default from Node 22.18/23.6, the
    flag keeps the repo's floor 22.12 working). tsc --noEmit type-checks in
    the lint script, so the existing lint job covers it. The image (build(mock): release the mock server image #592)
    can run src/main.ts directly.
  • Tests with node:test (no extra test runner): integration tests start
    the server on a free port and send real HTTP requests with fetch. They run
    through the workspace's test script, so the existing test job and the
    CI passed gate include them. Coverage isn't collected for this workspace
    (Codecov only reads packages/*/coverage); can be added later if wanted.

Verification

  • npm test in apps/mock-server: 45 tests pass (repeated runs stable) (health, CORS preflight and
    headers 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, at
    the limit and the 1 MiB default, aborted requests, HEAD, fixtures, item
    and size caps, copies, reset on restart,
    store unit tests, PORT parsing)
  • npm run test -- --coverage (as CI passes it through turbo) also passes
  • npx turbo run test lint --filter=ecc-mock-server: both tasks pass
  • npm run lint at the root (all workspaces, includes the build): 22/22 tasks
    successful
  • Smoke test: PORT=18588 npm start, curl /healthz → {"status":"ok"},
    OPTIONS /x → 204 with the CORS headers, one log line each
  • Sourcery's 10 findings fixed in bb85a5d (crash on a client leaving while an
    oversized 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 (before bb85a5d): CI passed green (Lint, Test on Node 22 and 24, CodeQL, Read the Docs
    preview); the Node 24 job ran the mock server's tests with CI's
    --coverage passthrough (all pass)
  • Not run locally: the browser tests of the other packages (no Playwright
    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:

  • Collect coverage for the mock server (Codecov): CI's --coverage
    passthrough is harmless here (all tests pass with it), and wiring Node's
    coverage into the shared Collect coverage step changes CI for one small
    app; documented on the Contributing page instead. Can follow if wanted.
  • Large package-lock.json diff: npm's own re-hoisting for the new
    workspace. 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).
  • PORT in turbo.json: required by the turbo/no-undeclared-env-vars
    lint rule of the shared eslint config; declaring it beats disabling the
    rule.
  • No prettier config: the shared @elixir-cloud eslint config already
    enforces 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:

  • Add a new Node.js/TypeScript mock server workspace for documentation previews, including health checks, routing, CORS handling, structured errors, request logging, graceful shutdown, and configurable port support.
  • Add an in-memory fixture-backed store with isolated created data, reset behavior, defensive copies, and collection size limits.

Enhancements:

  • Add safeguards for request bodies, connections, timeouts, and created-data growth for safe use by public preview deployments.

Build:

  • Register the mock-server workspace and declare its PORT environment variable for Turbo tasks.

Documentation:

  • Document the mock server’s purpose, usage, behavior, limitations, and development workflow in the README and Contributing guide.

Tests:

  • Add comprehensive unit and integration coverage for server behavior, routing, errors, limits, logging, fixtures, and store semantics.

uniqueg and others added 3 commits November 18, 2026 02:54
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>
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Data structures

Add the in-memory collection store that loads fixture arrays, keeps created items separate, enforces per-collection caps, and returns copies to callers.

  • apps/mock-server/src/store.ts L1-162

API

Define the handler context, replies, HTTP errors, JSON parsing helper, and route-matching interface used by API stubs.

  • apps/mock-server/src/http.ts L1-53
  • apps/mock-server/src/router.ts L1-79

Uses of the API

Provide the central route-registration list where API stubs can be added as they are implemented.

  • apps/mock-server/src/routes/index.ts L1-7

Implementation

Implement the HTTP server behavior, including CORS, request limits, routing, error replies, and request logging.

  • apps/mock-server/src/server.ts L1-215

Load fixtures, start the server on the configured port, and handle graceful shutdown signals.

  • apps/mock-server/src/main.ts L1-26

Parse and validate the optional port environment setting, defaulting to port 8080.

  • apps/mock-server/src/config.ts L1-15

Configuration

Configure the mock-server workspace scripts and development dependencies, TypeScript checking, and ESLint settings.

  • apps/mock-server/.eslintrc L1-8
  • apps/mock-server/package.json L1-22
  • apps/mock-server/tsconfig.json L1-16
  • turbo.json L30-31

Documentation

Document the mock server's purpose, operation, limits, fixture workflow, and extension points for API stubs.

  • README.md L88-90
  • apps/documentation/pages/docs/contributing.mdx L74-128

Tests

Add unit and integration tests for port parsing, server behavior, fixture loading, and store semantics, along with test-only fixture data and helpers.

  • apps/mock-server/test/config.test.ts L1-23
  • apps/mock-server/test/fixtures/things.json L1-4
  • apps/mock-server/test/helpers.ts L1-59
  • apps/mock-server/test/server.test.ts L1-406
  • apps/mock-server/test/store.test.ts L1-172

Lock files and vendored code

Update the npm lockfile to record the new workspace and its dependency resolution.

  • package-lock.json L1188-1333, L14333-14349, L17349-17364 (+24 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@read-the-docs-community

read-the-docs-community Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 cloud-components | 🛠️ Build #36057457 | 📁 Comparing f291ad7 against latest (fd4653a)

  🔍 Preview build  

3 files changed
± docs/contributing/index.html
± docs/providers/index.html
± docs/trs/components/tools/index.html

@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.12%. Comparing base (86bd628) to head (f291ad7).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@uniqueg
uniqueg requested a review from anuragxxd November 18, 2026 03:34
@uniqueg
uniqueg marked this pull request as ready for review November 18, 2026 03:34
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit f291ad7

#588 feat(mock): scaffold the docs mock server · 6 of 6 met

# Requirement Status Notes
1 Add an apps/mock-server workspace using TypeScript, Node >= 22, and Node's built-in HTTP server. ✅ Met The workspace uses Node's http module and its scripts use Node's type stripping; the root engine range is >=22.12.0.
2 Provide a JSON 404 default, open CORS and preflight answers, GET /healthz, PORT with default 8080, and one log line per request. ✅ Met The server implements these behaviors, including CORS on error responses and request logs that omit the query string.
3 Load deterministic fixtures into an in-memory store, never write them to disk, and reset created data on restart. ✅ Met The store loads fixture files at startup, keeps created items separately, and the tests cover that fixtures are not written and created data resets.
4 Limit request bodies and created items per collection; drop the oldest created item while keeping fixtures. ✅ Met The server enforces the body limit, and the store caps created items while preserving fixtures and dropping the oldest created items.
5 Add node:test integration tests, run them through the workspace test script and existing CI test job, and lint through the existing lint job. ✅ Met The workspace defines test and lint scripts, and the root workspace and Turbo configuration include workspace tasks in the existing commands.
6 Document the mock server on the Contributing page, including its purpose, local use, fixture additions, lack of authentication, and prohibition on real data. ✅ Met The new “Mock server” section covers these points and documents the scaffold and its limits.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread apps/mock-server/src/server.ts Resolved
Comment thread apps/mock-server/src/server.ts Resolved
Comment thread apps/mock-server/src/server.ts Resolved
Comment thread apps/mock-server/src/store.ts Resolved
Comment thread apps/mock-server/src/server.ts Resolved
Comment thread apps/mock-server/src/server.ts Resolved
Comment thread apps/mock-server/src/main.ts Resolved
Comment thread apps/mock-server/src/server.ts Resolved
Comment thread apps/mock-server/src/server.ts Resolved
Comment thread apps/mock-server/package.json Resolved
- 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>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sourcery assessment

Approved.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(mock): scaffold the docs mock server

1 participant