1
0
This repository has been archived on 2026-08-25. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
tera/server/src/app.ts
T
karti acf4d1a510 feat: the state becomes California, and the port fills with ships
**Stage 1 of one California.** The owner's complaint had two halves and this is
the first: the state board was a CROPPED SLAB. `california.ts` stopped at 38.05 N,
so the board disagreed with its own minimap about the shape of California in a
single frame, and Bug Fire's 93,733 acres burned off-frame while the panel said
all clear. Bounds now run 32.50-42.05 N / -124.50 to -114.0 W — Cape Mendocino,
the ruled Oregon parallel, the 120th-meridian corner into the Nevada diagonal.

**And it got cheaper.** 391,169 triangles to 375,351, while gaining the North
Coast, the Sacramento Valley, the Klamath knot, the Cascade arc, Shasta at 4,320 m
and Lassen at 3,190 m. Extending the bounds alone would have doubled the lattice
to 168,813 points and blown the mobile cap; coarsening cellLat 0.022 -> 0.0312 and
cellLng 0.027 -> 0.0383 holds it at ~83,800. The cell as a FRACTION of the board
moves 0.0030 -> 0.0033 — unchanged in frame — because the camera retreats to frame
whatever it is given. That argument was already written in the pack's own comment.

The second half — three boards becoming one world you zoom through — is NOT here.
Merging at Bay density would be 34.04M triangles, 13x the highest budget, and
merging at SoCal density would downgrade San Francisco from 40 m lots to 164 m.
Both delete the board every marketing still is shot from. `sf.ts` and `socal.ts`
are untouched by design.

**Aerial perspective, which the state board could not have had before.** The old
fog started at 1.15 board spans = 944 km, on a board whose longest diagonal is
820 km — so no pixel could ever be fogged. Fog now responds to camera altitude,
clamped to the authored pair as a ceiling.

`Atmosphere.aerial(env, view)` is a second pure method returning `{ near, far }`
and **deliberately no colour**. That is structural, not stylistic: it is why a
future camera-dependent term cannot reach `environmentKey()`'s colour fingerprint
and start rebuilding the PMREM cubemap on every camera step. Coarsening the
fingerprint instead would have hidden one instance and armed the mechanism. A
mutation-tested seam guard fails if anyone merges the two paths back together.

**The port.** Terminal Island rendered as a bare tan polygon with generic white
blocks while the chapter text called it the busiest port complex in the
hemisphere. Now six container yards drawn as canvas atlases, 56 gantry cranes at
varied boom angles, the 13 km San Pedro breakwater, the dredged channel. Five
buckets merging ACROSS ports the way airports.ts merges across fields, so a
second complex costs no extra draws: +11 draws and +4,377 triangles for all of it.

At vertical exaggeration 3.4 a 130 m gantry is 1.132 units tall against a 400 m
ship's 1.024 long — the crane is the taller object, and it is what makes a port
read as a port from altitude.

**Ships, and the wake carries the information.** Moored hulls have no foam,
verified at three terminals; a tug under way in the Main Channel trails a clean
Kelvin V. One hull geometry, one InstancedMesh, orientation from the BERTH rather
than the wire. The AIS gate strips sog 102.3, heading 511 and cog 360 — all mean
"not available" — with an explicit test that cog 358.7 SURVIVES, because a naive
range check on cog eats real headings near north.

"Empty or full" is not in AIS position reports and is not invented per ship. The
honest answer is at port level and is a better story: 348,691 of 460,467 boxes
left Los Angeles empty in July 2026, corroborated by FBX01 $7,491 inbound against
FBX02 $347 outbound.

**Radar and birds ship dark, and say why.** California is 0.47% wet and migration
is nocturnal and seasonal, so both layers have nothing to say on most days. The
panel reads "No radar feed is configured, so this board draws no weather. That is
a fact about this box, not about the sky."

Also recorded, and it matters beyond this commit: **the GPU on amd-server never
leaves 500 MHz of a possible 2725**, traced across 80 seconds of sustained load.
`bay-area/desktop` is fragment-bound at that clock and sits on the vsync deadline,
so a trivial change in fragment work flips it between 16.8 and 33.3 with geometry
identical to the digit. Every frame-time number measured on this box is a floor.
Two investigations reached two different wrong conclusions from single-run
comparisons before this was traced. Geometry is the gate; frame time is advisory.
No cap was raised.

Tests 1,340 -> 1,540, server 280 -> 295.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 23:35:09 -07:00

144 lines
6.3 KiB
TypeScript

/**
* The one server.
*
* One Fastify instance on `127.0.0.1:8431` serving `/api/v1/*`, behind Caddy,
* with one systemd unit and one Caddy snippet. Three separate backends were
* designed for this box — three ports, three frameworks, three deploy files that
* would have overwritten each other — and this is the one that replaces them.
* Weather, flights, markers and offices are route modules here, not services on
* ports of their own. CONTRACT.md §5.
*
* `buildApp` never listens. Tests build one and use `inject()`; `index.ts` builds
* one and binds it.
*/
import Fastify, { type FastifyError, type FastifyInstance } from "fastify";
import { createBirdsService } from "./birds/index.ts";
import { registerCachePolicy } from "./cache.ts";
import { loadConfig, type Config } from "./config.ts";
import { createRadarService } from "./radar/index.ts";
import { registerBirds } from "./routes/birds.ts";
import { registerDevices } from "./routes/devices.ts";
import { registerFires } from "./routes/fires.ts";
import { registerFlights } from "./routes/flights.ts";
import { registerHealth } from "./routes/health.ts";
import { registerMarkers } from "./routes/markers.ts";
import { registerMedia } from "./routes/media.ts";
import { registerOffices } from "./routes/offices.ts";
import { registerPresence } from "./routes/presence.ts";
import { registerRadar } from "./routes/radar.ts";
import { registerRealtime } from "./routes/realtime.ts";
import { registerSatellites } from "./routes/satellites.ts";
import { registerSession } from "./routes/session.ts";
import { registerWeather } from "./routes/weather.ts";
import { createServices } from "./services.ts";
import type { ErrorBody } from "../../src/server/wire.ts";
export function buildApp(config: Config = loadConfig()): FastifyInstance {
const app = Fastify({
logger: { level: config.logLevel },
// Caddy is the only thing that talks to this socket, so its X-Forwarded-For
// is the client address. Nothing else can reach the port to forge one.
trustProxy: true,
});
// One loud line per demotion, at boot, before anything can be served. The
// health body carries the same list for anyone without log access.
for (const line of config.degraded) {
app.log.warn(`TERA DEGRADED: ${line}`);
}
registerCachePolicy(app);
registerCors(app, config.corsOrigins);
const services = createServices(config, app.log);
registerHealth(app, services);
registerFlights(app, services);
registerSatellites(app, services);
registerFires(app, services);
// The two sky feeds are constructed here rather than on `Services`. They own
// their own cache and their own failure behaviour exactly as every other
// service does, and neither can throw at a route. `sources.radar` and
// `sources.birds` are on the health body — `routes/health.ts` reads them off
// the config rather than off a service, which is what every line in that route
// does and is why it still touches no upstream.
registerRadar(app, createRadarService(config, app.log));
registerBirds(app, createBirdsService(config, app.log));
registerWeather(app, services);
registerMarkers(app, services);
registerMedia(app, services);
registerOffices(app, services);
registerPresence(app, services);
registerDevices(app, services);
registerRealtime(app, services);
registerSession(app, services);
app.setNotFoundHandler(async (_req, reply) => {
const body: ErrorBody = { error: "not_found", message: "No such route." };
return reply.code(404).send(body);
});
/**
* The one error handler, and the one place a client's mistake is told apart
* from ours.
*
* It used to answer 500 to everything, which was right for the only thing
* that reached it at the time — a route that threw. It stopped being right
* the moment a route accepted a body: Fastify raises its own errors for a
* payload that is not JSON, a content type it was not offered and a body over
* a route's `bodyLimit`, and every one of those is the caller's mistake,
* carries a 4xx `statusCode`, and was being reported as "something went wrong
* on the server". An operator watching error rates cannot tell a broken box
* from somebody POSTing nonsense at it, and the caller is told to retry
* something that will never work.
*
* So a 4xx from the framework is passed through with its own status and the
* `ErrorBody` shape every other refusal here uses; anything else is still a
* 500 with nothing in it, because the inside of an exception is not a thing
* to hand to the internet.
*/
app.setErrorHandler(async (err: FastifyError, req, reply) => {
const status = typeof err.statusCode === "number" ? err.statusCode : 500;
if (status >= 400 && status < 500) {
req.log.info({ err: err.message, status }, "refused a malformed request");
const body: ErrorBody =
status === 404
? { error: "not_found", message: "No such route." }
: { error: "bad_request", message: "That request could not be read." };
return reply.code(status).send(body);
}
app.log.error({ err }, "unhandled error");
const body: ErrorBody = { error: "internal", message: "Something went wrong." };
return reply.code(500).send(body);
});
return app;
}
/**
* CORS, by hand.
*
* The default is an empty allowlist — the browser build is served from the same
* origin through Caddy, so nothing needs this until somebody runs the dev server
* on a different port and sets `TERA_CORS_ORIGIN`. A plugin whose entire job is
* fifteen lines of header-setting is not worth the dependency, and the fifteen
* lines being visible here is worth something on a route that decides who may
* read the API from where.
*/
function registerCors(app: FastifyInstance, allowed: string[]): void {
if (allowed.length === 0) return;
app.addHook("onRequest", async (req, reply) => {
const origin = req.headers.origin;
if (typeof origin !== "string" || !allowed.includes(origin)) return;
reply.header("access-control-allow-origin", origin);
reply.header("access-control-allow-headers", "authorization, content-type");
reply.header("access-control-allow-methods", "GET, POST, OPTIONS");
// Whatever the response ends up being, it depended on the Origin header.
reply.header("vary", "Origin");
if (req.method === "OPTIONS") await reply.code(204).send();
});
}