Skip to content

t1k:gamebackend:game-server:rest-contract-port

FieldValue
Modulegame-server
Version1.10.3
Effortmedium
Tools—

Keywords: contract fixture tests, mock backend to worker, offline backend port, port mock rest contract, rest contract fixtures

/t1k:gamebackend:game-server:rest-contract-port
<client mock backend path | route family>

Port a client’s mock REST contract to a Worker

Section titled “Port a client’s mock REST contract to a Worker”

The client already speaks a contract (an offline mock, or a shipped app’s API). The Worker must reproduce it byte-for-byte in shape while the storage underneath changes to the per-player Durable Object of t1k-gamebackend-game-server-architecture. The client is not touched. Worked example: the SteelBorn warship-idle server/ (a Worker port of its OfflineBackend mock; code under review at the time of writing, so cite it by name, not by path).

IntentGo to
“Which routes exist and in what shape?”1. Extract the contract
“How do I prove the Worker matches?”2. Contract fixtures
“What goes in the DO, what stays in the Worker?”3. Layering
“My guard test is green, is it real?”5. Mutation proofs
“Which route-level holes did review find?”references/route-hardening.md
“How many requests will 1M players send?”6. Request volume

Read the mock’s routing, handlers and DTOs file by file; do not guess from traffic.

  • Routes and verbs: the mock’s RegisterRoutes-style table pins each path and method.
  • Wire naming: check for a custom naming policy or enum converter on the models. In the SteelBorn case none existed, so enums serialize as numbers (ErrorCodes) and every property is emitted in PascalCase. Verify this per project; never assume camelCase.
  • Error envelope and numeric code table: port the table as data; keep the same HTTP status per code.
  • Routes the mock does not serve (for example a token endpoint the mock seeds into save state): their request shape comes from the shipped app’s real API, not from the mock. Say so at the top of that test file.
  • Never port a mock’s lenient auth. The offline mock accepted any /connect/token; the first Worker port minted a token for any DeviceId (account takeover, shown by the reviewer with an executed proof). A mock that ignores credentials is a spec gap, not a spec. Read the REAL client flow first (its AuthService / credential store): SteelBorn calls POST /connect/signup, stores the server-issued Login + Password, then uses the password grant on /connect/token; DeviceId / idfa are optional and not a credential. Design: t1k-gamebackend-game-server-auth-iap -> references/account-signup.md.
  • Anything unimplemented answers the mock’s own 404 envelope (EntityNotFound), not a Hono or framework default. A client that parses the envelope must not see a different 404.

A contract fixture is the expected JSON recorded from the client contract, asserted against the Worker’s response with deep equality. See references/contract-fixtures.md for how to record one and what to write beside it.

  • One fixture per route family, with the source file and method that pinned it named in the test header.
  • Assert the error states too (missing/undecryptable receipt, overdraft, stale version), not only the happy path.
  • Record where each fixture came from and its limits (here: read from the mock’s source because the IL2CPP-reconstructed C# has no in-process harness). A fixture you cannot trace is decoration.
ConcernLives inRule
Bearer verificationWorker middlewareruns BEFORE any route handler, so a bad token never instantiates a PlayerDO (assert it)
Form/JSON parsing, envelopes, status mappingWorkertolerate the client’s key spellings (DeviceId, deviceId, device_id)
Player state, idempotency, version checkPlayerDOone JSON state row with an unindexed version; append-only ledger on plain INTEGER PRIMARY KEY
Domain failurePlayerDO resultreturn {ok:false,code}; do not throw across the RPC boundary
Retry / overloadWorker client wrapper.retryable -> bounded retry on a fresh stub; .overloaded -> 503 + Retry-After, never retried

Idempotency and concurrency (SteelBorn coins route): an Idempotency-Key header makes a repeated Earn a no-op that returns the stored result; an If-Match header carries the expected version and a stale one answers 409. Offline earnings and daily resets are computed lazily from a timestamp on read: no alarm, timer, waitUntil.

Do not port the mock’s habits: deep-cloning the whole player state as a rollback checkpoint on every request including GETs; persisting on every 2xx including GETs that only touch a sync timestamp.

4. Numeric and encoding traps found in the port

Section titled “4. Numeric and encoding traps found in the port”
  • Token view-model numeric ids must fit 53 bits (Number.isSafeInteger): a 64-bit mask produced ids the client’s JSON stack mangled. Pin it with a test that fails when the mask widens.
  • Port a client-side cipher or receipt scheme 1:1 and test both the decrypt-fail path (InvalidCoinsEncryption) and the overdraft rollback (NotEnoughCoins rolls the whole write back).
  • The receipt cipher is obfuscation (the key is the client’s own token): the server must decide currency amounts with caps, gross-gain windows and operation fingerprints. references/currency-receipts.md.
  • Unit mix-ups in lazy time maintenance: see Gotchas (nowSeconds).

A green suite proves the assertions run, not that they are true. For every guard write a companion mutation and record the failure it produced in a RED-PROOFS.md beside the tests (references/red-proofs.md has the table shape and the nine SteelBorn proofs and the review lessons). Every security test is mutation-proven and the RED table lives in the repo. Pin the failure state, not only the happy path (the DO registry growing for an unauthenticated request; sqlite_sequence appearing). Run suites with a worker cap: bunx vitest run --maxWorkers=4; a test must never spawn a script that re-runs its own suite.

6. Measure request volume before trusting any cost figure

Section titled “6. Measure request volume before trusting any cost figure”

A cost model is only as good as requests-per-DAU. The first SteelBorn estimate assumed 100 per DAU per day; a read of the client’s call sites found 560 to 1,800 (structural, not captured traffic; 30-min sessions, 4 per day). Procedure and fixes: references/request-volume.md, and core t1k-datastore-cost -> request-volume-audit.md. Add a per-route counter to the mock or staging router and play a real session before quoting a number; label any estimate modelled.

  • cf deploy refuses to build without a declared dev-server plugin (@cloudflare/vite-plugin), even for a pure API Worker; see t1k-gamebackend-game-server-template-bootstrap.

  • cf deploy --dry-run does not surface bindings.secret() values: it proves build and config resolve, not that secrets are set in the target account.

  • A tamper test that flips the LAST base64url char of a 64-byte ES256 signature can leave the decoded bytes unchanged (only 2 significant bits), so the “tampered” token verifies. Flip the FIRST char (6 significant bits).

  • Mutate the OUTER guard: a mutation inside a branch that a surrounding catch remaps to the same status stays green.

  • Lazy time maintenance (offline income, daily reset) fed Date.now() milliseconds to a function that takes unix seconds (periods 60 and 86,400), so a player earned income every 60 ms. Name time parameters with the unit (nowSeconds, nowMs) and test with a fake clock that advances by known seconds (reported, SteelBorn lazy-clock test). The same bug at the ROUTE stayed 256/256 green: assert exp - iat === 1800 on every token-minting route (references/route-hardening.md).

  • Shared workstation, swap pressure: routed hops died with exit 137 / NOT-STARTED. Brief every lane to run ONE vitest suite at a time with --maxWorkers=2, and to wait while another vitest is running (pgrep -f vitest) before starting.

t1k-gamebackend-game-server-architecture (decision, invariants), t1k-gamebackend-game-server-auth-iap (token and receipts), rule gamebackend-game-server-invariants, core t1k-datastore-cost, t1k-cloudflare.