feat: v0.7.0 — server-authoritative sim engine: tick-on-read clock (time-scale + pause via POST /api/sim), contract expiry + market spawn, analytic plane movement/finalization
This commit is contained in:
@@ -1,5 +1,19 @@
|
||||
# Changelog
|
||||
|
||||
## v0.7.0 — 2026-09-17 12:27
|
||||
- **Server-authoritative sim engine** (PLAN.md "Simulation engine" increment 2) in new `lib/sim/` — no frontend/UI changes; dispatch of planes lands next increment, but all the clock/market/finalization machinery it builds on is live and tested now
|
||||
- **Tick-on-read game clock** (`lib/sim/engine.ts`, NO background timer): every read/action endpoint calls `tickNow()` first (GET /api/state, POST /api/sim — and any future action endpoint); the tick advances `clockMs` by `(real ms since last tick) × timeScale`. New `sim_state.last_real_tick_ms` column stores the real-time anchor (seed sets it to the seed moment). **Clamp: `MAX_TICK_ELAPSED_MS = 2000`** — a single tick counts at most 2 s of real absence, chosen above a normal ~1 s poll interval (active play advances ~real time × scale) but small enough that one stale read after an absence moves game time by ≤ 2 s × scale (≤ 2 min at max scale 60), so the sim only meaningfully progresses while actively polled. While paused the clock is frozen but `lastRealTickMs` keeps tracking real time, so unpausing resumes with no catch-up jump. Ticks are serialized through a module-level promise lock (concurrent Next.js requests can't double-advance) and each tick persists via the existing sql.js atomic export
|
||||
- **Analytic movement** (`lib/sim/movement.ts`, pure functions of the sim clock — no incremental stepping): `travelDurationMs(distanceKm, speedKmh)`, `arrivalTimeFor(departureSimTime, distanceKm, speedKmh)`, `progressAt(...)` (clamped 0–1), `positionAt(fromLat, fromLon, toLat, toLon, t)` (great-circle slerp — exact endpoints, stays on the arc), `fuelAt(startFuel, burnPerKm, distanceKm, progress)` (`start − burn·distanceSoFar`, clamped at 0; range exhaustion not modeled yet). New nullable `planes.departure_sim_time` column carries the flight context (route comes from the bound contract, speed/burn from the catalog by model); while flying, `fuel` is frozen at its departure value and GET /api/state reports live lat/lon/fuel computed from the clock
|
||||
- **Arrival finalization** (in-tick): a flying plane whose `arrivalTime ≤ clock` gets its contract marked completed, the exact reward added to `account.cash`, reputation += `1 + 0.0005 × km` (rounded to 2 dp — ~1.15 rep for a 300 km hop, ~2.5 for a 3000 km leg; slow growth from the starting 10), and the plane grounded at the destination with remaining fuel + `departureSimTime = null`. Idempotent by construction: finalization leaves the 'flying' state, so an award can never be paid twice (unit-tested)
|
||||
- **Contract expiry** (in-tick): any `open` contract with `deadlineSimTime ≤ clockMs` → status `'expired'` (new enum value in schema/DDL/snapshot/OpenAPI); accepted/in-flight contracts never expire — they complete. Expired contracts leave the available set the client sees
|
||||
- **Market spawn** (in-tick, after expiry): if open contracts < `MARKET_TARGET_OPEN_CONTRACTS = 10`, new ones are generated to top it up using the SAME builder as the first-run seed — `generateContract({id, airports, rng, nowMs, deadlineOffsetMs?})` extracted from `buildSeed` (same RNG call order, reward formula, cargo flavor, 6–72h game-time deadlines; spawn uses crypto-random UUID ids and the sim clock as "now"). Injectable RNG for deterministic tests
|
||||
- **Time controls endpoint**: new `POST /api/sim` — body `{ timeScale?: number, paused?: boolean }`; unknown fields / non-number timeScale / non-boolean paused → 400; timeScale clamped to [1, 60]; ticks the clock first so the returned simState already reflects current game time. Documented in `lib/openapi.ts` (new SimControlsRequest + Error component schemas; ContractState status enum gains 'expired'; /api/state description notes tick-on-read)
|
||||
- **DB migration for existing installs**: `openGameDb()` now runs a guarded `ALTER TABLE ADD COLUMN` step (PRAGMA table_info check) adding `planes.departure_sim_time` and `sim_state.last_real_tick_ms` to pre-v0.7.0 files, then fixes up the ALTER-default `last_real_tick_ms = 0` to "now" so old DBs resume cleanly instead of taking one clamped catch-up jump
|
||||
- **e2e test hook** (test-only affordance): new `POST /api/test/expire-contract`, enabled ONLY when `FLIGHT_TEST_HOOKS=1` (set in docker-compose.yml for the e2e instance; 404 everywhere else) — with `{contractId}` it moves that open contract's deadline ~10 game-seconds out, without a body it creates a fresh short-deadline open contract; lets the suite observe expiry at scale 60 instead of waiting hours
|
||||
- Tests: unit — new `lib/sim/movement.test.ts` (duration/arrival math, progress boundaries incl. just-before-arrival, slerp endpoints/on-arc/equator-exact/same-point, fuel burn + zero clamp) and `lib/sim/engine.test.ts` (fake-timer clock advance × timeScale, pause freeze + clean resume, 1-hour-gap clamp to exactly one tick, same-ms no-op; expiry flips only open past-deadline contracts incl. the inclusive edge; finalize awards cash+rep exactly once with right remaining fuel and does nothing pre-arrival or without route info; spawn tops up to target via the shared builder — deterministic for an injected RNG); `lib/game/seed.test.ts` gains generateContract coverage (formula, window, determinism, deadlineOffsetMs, buildSeed ≡ builder output) and the simState assertion now includes lastRealTickMs; new `app/api/sim/route.test.ts` (200 shape, clamp to [1,60], pause freeze across ticks, 400 matrix); `lib/db/client.test.ts` gains a legacy-DB migration test; e2e — new `e2e/sim.spec.ts`: scale-60 clock advance bounded per tick by the clamp, exact freeze while paused, expiry of a hook-shortened deadline + market staying ≥ target (both mutate and create hook modes), POST /api/sim validation/clamping
|
||||
- **Known interaction with v0.6.0 e2e**: `e2e/state.spec.ts` restart-persistence test previously asserted the sim clock was byte-identical across a container restart — impossible under tick-on-read by design (every GET advances ≤ one clamped tick). The assertion now checks persistence properly: account/planes/contracts still byte-identical, and post-restart `clockMs ≥ before` bounded by `MAX_TICK_ELAPSED_MS × timeScale`. `e2e/api.spec.ts` endpoint list updated to four
|
||||
- Verified: unit suite 47 → 86 green; `tsc --noEmit` clean; e2e 11 → 16 green against the rebuilt compose instance (incl. restart-persistence); live curl of POST /api/sim + GET /api/state shows the clock advancing at scale 60 then frozen on pause
|
||||
|
||||
## v0.6.0 — 2026-09-17 11:49
|
||||
- Data foundation (PLAN.md "Simulation engine" increment 1): Drizzle ORM + SQLite via **sql.js (WASM)** — chosen over better-sqlite3 because it needs zero native compilation, so the existing oven/bun-alpine install stages and node:22-alpine runtime work unchanged; deps `drizzle-orm@0.45`, `sql.js@1.14` (+ dev-only `@types/sql.js`)
|
||||
- Schema (`lib/db/schema.ts`, DDL mirrored in `lib/db/client.ts`): `planes` (id, model, status available|flying, fuel/maxFuel, locationIcao, contractId?, lat/lon), `contracts` (id, origin/dest ICAO, reward, cargoType/cargoCount, deadlineSimTime, status open|accepted|completed, planeId?, createdSimTime), single-row `account` (cash, reputation) and `sim_state` (clockMs, timeScale 1–60, paused)
|
||||
|
||||
Reference in New Issue
Block a user