Skip to content

Rewriting a server in another language found bugs the original had missed ​

· genever · idempotency-keys · All posts

leyman has an OpenAPI demo: a notes API (add a note, read one, list the newest) with a spec, a TypeScript client, a Hono server and a Postgres schema, at 100% coverage, with integration tests against a real database. On November 17 I added a second client and server, in Go, built from the same openapi.json, and changed the TypeScript server's integration tests to run every request against both servers. Agents wrote most of that code, under my direction. Building the Go side found three bugs in the TypeScript server, which was passing its own tests, and each was found a different way:

  • ajv-formats accepts urn:uuid:… as a uuid, so a note id with that prefix went to Postgres, which refused it, and the client got a 500. The Go validator asserts the strict form, which showed the difference.
  • Hono keeps a query escape that isn't UTF-8 (%ff) as the literal text %ff, where the URL standard reads it as U+FFFD. The shared suite caught this one.
  • Neither server required exp in an access token, so a token without one was good forever. No test caught it; it came up while fixing the Go server's token checks.

The versions throughout are Hono 4.13.17, ajv-formats 3.0.1 and jose 6.2.14 on the TypeScript side, and Go 1.26, jwx v3.4.0 and santhosh-tekuri/jsonschema v6.0.3 on the Go side.

The Go server could share the TypeScript server's tests because those tests check behaviour (what goes over HTTP, judged against what the document and the standards say) and nothing about how either server produces it.

I wanted the Go side for two reasons. I'd been porting leyman's libraries to Go (genever and idempotency-keys among them) and wanted to prove they work in practice, in a real application. And the repo had no demo of running a whole Go application, only small libraries.

Test the behaviour, not the implementation ​

The TypeScript server's suite checked statuses, headers and bodies through HTTP, retries with an Idempotency-Key, and JWTs from a real issuer, and its property test draws notes from the document's own NewNote schema with juniper-arbitrary. So the tests were behavioural in form, but they were written alongside the server, and their cases were picked from what the server already handled, which left out all three above.

The way out is to test behaviour instead of implementation, so the tests don't reinforce whatever the implementation already does wrong. Had the suite asserted whatever the TypeScript server answered to a search for %ff wool, it would have passed while asserting Hono's mistake. A test of behaviour states what the caller should get, and takes the answer from the contract (the OpenAPI document, the URL standard, an RFC).

A second implementation of the same contract comes at that from the other side: it's written separately, on other libraries, and a place where the two answer differently is a bug in one of them, a gap in the contract, or a difference both are allowed (listed under "Where the servers still differ").

Both servers read the same openapi.json ​

Neither server lists the API by hand. The spec package writes one openapi.json, and both servers read it: the TypeScript server compiles Ajv validators from it, and the Go module embeds the same bytes (//go:embed out/openapi.json) and validates with santhosh-tekuri/jsonschema. Routes, scopes, parameters, schemas and the statuses each operation documents all come from the document, and the Go types are generated from it by genever-go. So the servers can only disagree where their validators read a schema differently, where the parts no document describes (authentication, idempotency, a 404 for an unknown path) differ, or where a handler does something the document doesn't say.

The integration suites for notes, idempotency keys and JWTs became one loop over both implementations. The TypeScript server runs in-process, and the Go server is its notes-server binary, built once per run and started per test on port 0, with its URL read from stdout. Simplified, from notes.spec.ts:

js
// Black-box tests, through HTTP alone, so each server is held to the same expectations
for (const implementation of implementations) {
    suite(`Notes API on ${implementation.name}`, () => {
        const withServer = withDatabase().beforeEach(async ({ database }) => {
            const served = await implementation.start({ databaseUrl: database.url, authentication: { tokens } });
            return { served, client: new NotesClient({ baseUrl: served.url, token }) };
        });
        // ...every test from before, unchanged
    });
}

Each test gets its own database cloned from a template (pg-dolly), so both servers start from the same empty state. Tests that reach into the TypeScript server's internals (handlers swapped for broken ones, a store that fails on purpose) can't run against a binary, so they stay in suites marked TypeScript alone. There are 6 of those, against 68 that run on both. Those 6 are useful (they check that a handler breaking the contract gets caught), but they're about this implementation.

The interop tests cross between servers: a createNote retried with the same Idempotency-Key against the other server on the same database replays the first note, which works because both follow one specification for the key's fingerprint and row, and the Go client runs its own tests against each server.

What it found, in order ​

The UUID came first, before the suites were even shared. JSON Schema's uuid format is RFC 4122's string form, with no prefix, and that's what the Go validator asserts. ajv-formats also accepts urn:uuid:00000000-0000-4000-8000-000000000000, so the TypeScript server's getNote passed that to Postgres's uuid column, Postgres refused it, and the client got a 500 for what should have been a 400. The fix overrides the format in both of the server's Ajv instances with the strict pattern (commit), and both servers now answer 400.

The query string turned up differences in both directions, and the first was a bug in the Go server: Go's url.ParseQuery drops a pair containing a ; or a broken escape, so /notes?limit=1;x=1 listed 20 notes and /notes?q=%zz listed every note, where the TypeScript server answered 400 to the first and searched for the literal %zz in the second. The URL standard's parser sides with Hono there (pairs split on & alone, and a % without two hex digits is kept as it is), so the Go server now parses the raw query that way (commit). But the same comparison caught %ff, where Hono keeps the escape as text and the standard decodes it as U+FFFD, which is what Go did. So a search for %ff wool matched a note titled %ff wool on the TypeScript server and � wool on the Go server, and only Go's was right. That test was left out of the shared suite until the TypeScript server read the query with URLSearchParams, keeping Hono's other choices (the first of a repeated parameter wins, a pair without a name is ignored) (commit).

RFC 9068 requires exp in a JWT access token, but jose and jwx only check it when it's there, and both servers relied on the library, so they agreed and the shared suite had nothing to flag. It came up during a run of fixes to the Go server's token checks, and now the JWT suite signs its own token without exp and expects a 401 from both servers (commit).

The Go server picked up its own fixes along the way, mostly from places where Go's defaults differ from what the TypeScript server already did: jwx requires a kid when verifying against a key set where jose tries every key that fits, net/http recovers a panicking handler by dropping the connection instead of answering 500, and Go's ServeMux answers a missing method with a plain-text 405 of its own. Those are listed in the Go README.

Neither server decided which answer was right ​

The UUID fix links JSON Schema's definition of uuid in a comment. The query tests carry comments linking the URL standard's percent-decoding and urlencoded parsing sections, and they went against the TypeScript server once (%ff) and against the Go server twice (; and %zz). The exp test follows RFC 9068, against both servers at once (its commit cites the section). If "whatever the TypeScript server does" had been the reference, the Go server would have copied Hono's %ff bug to pass, and if it had been the Go server, the TypeScript server would have copied Go's ; bug.

Where the servers still differ ​

Each server's message for a request that doesn't match the document comes from its own validator and is allowed to differ, so the shared tests check the status and the error code, and not the text. Go's ServeMux answers a path that isn't clean (/notes/../notes) with a 307 to the cleaned path before authentication, while the TypeScript server resolves dot segments as the URL standard does, and that's listed under the Go README's Not covered. jwx also refuses a token whose iat is in the future, which jose doesn't check.

The cost is a second server to maintain. The Go server, its binary and its reading of the document come to about 2,300 lines without tests or generated types, against about 1,100 in the TypeScript server's source. Neither hand-codes an operation, so a spec change still reaches both at once.

When I'd write the second one ​

Not always, but in general I try to solve a problem in a language-agnostic way, because that keeps the focus on the problem rather than on one solution to it. The exception is a solution that only makes sense in one language: the TypeScript client here takes its types from the YAML document through a TypeScript content mapper at compile time, which has no Go equivalent, so Go gets committed, generated types instead, and there's nothing to compare.

To run both servers through the suite, in a leyman checkout (the devcontainer has Go and the Postgres sidecar):

sh
nx run @leyman/demo-openapi-server:test

The Go side has its own tests too, with nx run @leyman/demo-openapi-go:verify.