serve each country's regions from its own file, so the server no longer holds them all

The Atlas server no longer keeps the admin-1 regions of every country in memory. Each country's regions are now a pre-gzipped file of their own, sent to the map as they are.

**Why:** `GET /addons/atlas/regions/geo?countries=…` built `admin1Store` (every country's region text, kept until restart), then joined the requested countries, `JSON.parse`d them, and Nest stringified them again. On the 512 MB – 1 GB boxes TREK runs on, the first z≥5 view could OOM the server (same shape as #1576).

**What changes:**
- `server/assets/atlas/admin1/<ISO_A2>.geojson.gz`: 198 files, 14.85 MB, the same 3,447 features as `admin1.geojson.gz`.
- New `GET /addons/atlas/regions/geo/:code` with a Zod contract (`regionGeoParamsSchema` in `@trek/shared`: two letters, any case). It sends the country's file as it is, with `Content-Encoding: gzip` and the current 1-day `Cache-Control`, as `countries/geo` does. A country without regions gets an empty FeatureCollection. Anything that is not two letters gets a 400.
- `useAtlas.ts` fetches one URL per uncached country and still rebuilds the layer once. Each country has a stable URL, so a country evicted by `REGION_CACHE_MAX` comes back from the browser cache.
- `getRegionFeatures` reads only the country it needs. `admin1Store` is removed.
- `?countries=` keeps working for cached PWA clients. It joins the per-country files as bytes, without a parse.
- The migrations are untouched. `admin1.geojson.gz` still ships, only for `Migration20200101021500` and `Migration20200101031500`. This costs ~15 MB of disk in the image and no RAM. `build-atlas-geo.mjs` writes both, and ATLAS-BUNDLE-008 keeps them equal.

**Memory** (real `atlas-geo` module, first z≥5 view over Europe = 49 country codes, JS heap + Buffers):

| | peak | kept after |
|---|---|---|
| before, first view (builds the store) | +372 MB | +61 MB |
| before, later views | +115 MB | 0 |
| after, `/regions/geo/:code` | +4.7 MB | 0 |
| after, legacy `?countries=` | +59 MB | 0 |

**Tests:**
- New: `atlas-region-files.test.ts` (moved from `atlas.service.test.ts`, plus join and dedupe cases), the `regionGeoParamsSchema` spec, ATLAS-BUNDLE-007 (the file format the byte join depends on), ATLAS-BUNDLE-008 (bundle and per-country files are equal), ATLAS-016/017/018 (the new route over HTTP, including the 400).
- The `getVisitedRegions` tests (ATLAS-UNIT-019..024) used to pass only when `getRegionGeo`'s `beforeAll` had built the store first. They now also pass on their own.
- The shared, server and client gates pass. Baselines go down only where this change removed code (`no-console`, `no-explicit-any`, `no-swallowed-catch`, file sizes).

**Trade-offs:**
- A first zoom over Europe sends ~49 small parallel requests instead of 1. Over HTTP/1.1 the browser queues them 6 at a time. The total bytes are the same (4.4 MB gz).
- The per-country URLs are unversioned and cached for a day, like `countries/geo`. After an upgrade that changes a country's regions, a browser can show the old shapes for up to 24 h.

Approved on Discord in #github-pr: <paste the thread link here>
Related: #1576, #2559

- [x] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

- [ ] I have read the [Contributing Guidelines](https://github.com/liketrek/TREK/wiki/Contributing)
- [ ] My branch is [up to date with `dev`](https://github.com/liketrek/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date)
- [x] This PR targets the `dev` branch, not `main` *(wiki-only PRs are exempt)*
- [x] I have tested my changes locally
- [x] I have added/updated tests that prove my fix is effective or that my feature works
- [x] I have updated documentation if needed
This commit is contained in:
Vini
2026-10-26 20:08:57 +01:00
committed by Maurice
parent 70f27085b9
commit 7277e35a96
220 changed files with 360 additions and 185 deletions
+14 -7
View File
@@ -11,8 +11,8 @@ import zlib from 'zlib';
// for the country an index suggestion names. Importing it from atlas tied maps into
// an import cycle with atlas (lint:boundaries).
//
// atlas-geo builds its admin-1 region index on the asset path, the feature splitter
// and the ring test exported here. The admin0 gz bytes and the country poly/box
// atlas-geo resolves admin-1 regions with the per-country asset path and the ring test
// exported here. The admin0 gz bytes and the country poly/box
// indexes below are file-scoped for the reason atlas-geo gives: their lifetime stays
// process-global however many callers there are, so the indexes are built once per
// process, which the #1576 OOM fix depends on.
@@ -20,18 +20,24 @@ import zlib from 'zlib';
// ── Bundled boundary GeoJSON (admin-0 countries + admin-1 regions) ─────────
//
// Sourced from geoBoundaries (CC BY 4.0), normalized + quantized offline by
// scripts/build-atlas-geo.mjs into gzipped FeatureCollections under server/assets.
// They are read + decompressed once and cached in memory — no network at runtime.
// scripts/build-atlas-geo.mjs into gzipped FeatureCollections under server/assets:
// admin0 as one file, admin1 as one file per country (the whole admin1 bundle ships
// too, for two migrations that read it). No network at runtime.
// (Replaces the previous runtime fetch of Natural Earth, which was stale for recent
// sub-national reforms and depicts some contested borders in unwanted ways.)
//
// __dirname is server/dist/utils at runtime and server/src/utils under vitest;
// both resolve ../../assets to server/assets.
export function assetPath(name: 'admin0' | 'admin1'): string {
function assetPath(name: 'admin0'): string {
return path.join(__dirname, '..', '..', 'assets', 'atlas', `${name}.geojson.gz`);
}
/** One country's admin-1 regions, a FeatureCollection of its own, named by ISO_A2. */
export function admin1AssetPath(countryCode: string): string {
return path.join(__dirname, '..', '..', 'assets', 'atlas', 'admin1', `${countryCode}.geojson.gz`);
}
let admin0Gz: Buffer | null | undefined;
export function loadAdmin0Gz(): Buffer | null {
if (admin0Gz !== undefined) return admin0Gz;
@@ -46,13 +52,14 @@ export function loadAdmin0Gz(): Buffer | null {
// Feed arbitrary gunzip chunks; invokes onFeature(text) once per top-level Feature object
// inside "features":[ … ]. `pending` holds only the unconsumed tail (at most one partial
// feature + the current chunk), keeping memory flat regardless of bundle size.
export function createFeatureSplitter(onFeature: (text: string) => void): (chunk: string) => void {
function createFeatureSplitter(onFeature: (text: string) => void): (chunk: string) => void {
let pending = '';
let started = false;
// Scan progress is carried across chunks so each character is examined exactly once.
// A large Feature (e.g. Canada, ~5.5MB) spans hundreds of gunzip chunks; re-scanning the
// accumulated partial from the start on every chunk was O(n²) per feature and pushed the
// one-time admin1 build past the 15s test timeout under coverage/CI (#1576-followup).
// one-time admin1 build (since replaced by per-country files) past the 15s test timeout
// under coverage/CI (#1576-followup).
let scanning = false; // currently inside a Feature object?
let depth = 0,
inStr = false,