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
+68 -76
View File
@@ -1,10 +1,10 @@
import { Place } from '../../types';
import fs from 'fs';
import path from 'path';
import zlib from 'zlib';
import {
assetPath,
createFeatureSplitter,
admin1AssetPath,
getCountryFromCoords,
isPointInCountryBox,
loadAdmin0Gz,
@@ -17,7 +17,7 @@ import { cacheKeyFor, getCached, nominatimFetch, setCached } from '../geo/nomina
// ── Pure geo machinery for the atlas domain ─────────────────────────────────
//
// Plain module on purpose (same class as maps.helpers.ts / tripAccess): no DI,
// no DB access, no Nest imports. The caches below (admin1 per-country store,
// no DB access, no Nest imports. The caches below (parsed admin1 region features,
// geocode/region caches, the shared Nominatim throttle and the geocodingInFlight
// dedup set) are file-scoped so their lifetime stays process-global no matter how
// many AtlasService instances exist (container singleton + test helpers) —
@@ -37,10 +37,10 @@ export { getCountryFromCoords, isPointInCountryBox };
//
// Neither parsed bundle is cached. admin0 (~145MB) and admin1 (~260MB) parsed at once are
// what exhausted a 512MB host while using Atlas (#1576). Instead we retain only compact
// derivatives: the raw admin0 .gz bytes for direct serving, a Float64Array poly/box index
// for server-side point-in-polygon (see buildCountryIndexes in utils/country-borders.ts),
// and admin1 pre-split per country into ready-to-serve GeoJSON strings, built by
// streaming the gz so the full bundle is never materialised in one piece.
// derivatives: the raw admin0 .gz bytes for direct serving and a Float64Array poly/box
// index for server-side point-in-polygon (see buildCountryIndexes in
// utils/country-borders.ts). admin1 ships as one gzipped file per country, which is
// served from disk as it is and read one country at a time for region lookups.
/** admin-0 country borders as gzipped GeoJSON bytes, served to the client map with
* Content-Encoding: gzip so the server never holds the parsed FeatureCollection. */
@@ -57,75 +57,68 @@ export function getCountryGeo(): any {
return JSON.parse(zlib.gunzipSync(gz).toString('utf8'));
}
export async function getRegionGeo(countryCodes: string[]): Promise<any> {
const store = await getAdmin1Store();
const seen = new Set<string>();
const parts: string[] = [];
for (const code of countryCodes) {
const c = code.toUpperCase();
if (seen.has(c)) continue;
seen.add(c);
const s = store.get(c);
if (s) parts.push(s);
// A country's admin-1 file, or null for anything that is not a two-letter code, so
// nothing a client sends can name a path outside the folder. A country without a file
// has no regions; the whole folder missing is a broken install, said once.
let admin1Checked = false;
function admin1File(countryCode: string): string | null {
const cc = countryCode.toUpperCase();
if (!/^[A-Z]{2}$/.test(cc)) return null;
const file = admin1AssetPath(cc);
if (!admin1Checked) {
admin1Checked = true;
if (!fs.existsSync(path.dirname(file))) {
console.warn(`[Atlas] admin1 region files missing — run \`node scripts/build-atlas-geo.mjs\``);
}
}
if (parts.length === 0) return { type: 'FeatureCollection', features: [] };
// Each stored value is that country's features as comma-joined GeoJSON text; wrap the
// requested subset into one FeatureCollection and parse only that (per-viewport, small).
return JSON.parse(`{"type":"FeatureCollection","features":[${parts.join(',')}]}`);
return file;
}
// admin1 regions, pre-split per ISO_A2 into comma-joined feature text. Built once by
// streaming the gz through a brace-depth splitter that emits one Feature at a time, so the
// ~260MB full parse never happens (it OOMs a 512MB host). Concurrent first-callers share
// one in-flight build via admin1Building.
let admin1Store: Map<string, string> | null = null;
let admin1Building: Promise<Map<string, string>> | null = null;
function getAdmin1Store(): Promise<Map<string, string>> {
if (admin1Store) return Promise.resolve(admin1Store);
// `=== null`, not `!admin1Building`: a Promise in a boolean condition is what
// no-misused-promises/checksConditionals exists to catch, and the distinction
// matters once every DB-touching method returns one.
if (admin1Building === null) {
admin1Building = buildAdmin1Store().then((s) => {
admin1Store = s;
admin1Building = null;
return s;
});
// A country's admin-1 FeatureCollection as JSON bytes, or null when the bundle has no
// regions for it. Synchronous like the parse that follows it; one country is a small file.
function readAdmin1Json(countryCode: string): Buffer | null {
const file = admin1File(countryCode);
if (!file) return null;
try {
return zlib.gunzipSync(fs.readFileSync(file));
} catch {
return null;
}
return admin1Building;
}
function buildAdmin1Store(): Promise<Map<string, string>> {
const file = assetPath('admin1');
if (!fs.existsSync(file)) {
console.warn(`[Atlas] admin1.geojson.gz missing — run \`node scripts/build-atlas-geo.mjs\``);
return Promise.resolve(new Map());
/** One country's admin-1 regions as gzipped GeoJSON bytes, served to the client map with
* Content-Encoding: gzip like getCountryGeoGz, so the server never parses them. */
export async function getRegionGeoGz(countryCode: string): Promise<Buffer | null> {
const file = admin1File(countryCode);
if (!file) return null;
try {
return await fs.promises.readFile(file);
} catch {
return null;
}
// Concatenate each country's features straight into the store as we stream, rather than
// collecting arrays and joining at the end (that doubling, plus the source bundle's
// whitespace, peaked high enough to OOM a 512MB host on the first build). Re-serialising
// each feature via JSON drops the source formatting (~114MB → ~68MB retained) and the
// parse/stringify garbage is per-feature and short-lived.
const store = new Map<string, string>();
const split = createFeatureSplitter((text) => {
const f = JSON.parse(text);
const code = f.properties?.iso_a2?.toUpperCase();
if (!code) return; // features with a null iso_a2 are skipped, matching the old filter
const compact = JSON.stringify(f);
const prev = store.get(code);
store.set(code, prev ? prev + ',' + compact : compact);
});
return new Promise((resolve, reject) => {
fs.createReadStream(file)
.pipe(zlib.createGunzip())
.on('data', (chunk: Buffer) => split(chunk.toString('utf8')))
.on('end', () => {
console.log(`[Atlas] Indexed admin1 GeoJSON: ${store.size} countries`);
resolve(store);
})
.on('error', reject);
});
}
// How build-atlas-geo.mjs writes every per-country file; atlasBundle.test.ts holds it to that.
const FC_HEAD = '{"type":"FeatureCollection","features":[';
const FC_TAIL = ']}';
/**
* Several countries' regions as one FeatureCollection, for clients that still ask
* /regions/geo?countries=… from before the map fetched one country per request. Each
* file's features are cut out and joined as bytes, never parsed (#1576).
*/
export function getRegionGeoJson(countryCodes: string[]): Buffer {
const parts: Buffer[] = [Buffer.from(FC_HEAD)];
let first = true;
for (const cc of new Set(countryCodes.map((c) => c.toUpperCase()))) {
const json = readAdmin1Json(cc);
if (!json) continue;
if (!first) parts.push(Buffer.from(','));
parts.push(json.subarray(FC_HEAD.length, json.length - FC_TAIL.length));
first = false;
}
parts.push(Buffer.from(FC_TAIL));
return Buffer.concat(parts);
}
// ── Country names, for the address fallback ─────────────────────────────────
@@ -524,9 +517,9 @@ const regionCache = new Map<string, RegionInfo | null>();
// getCountryFromCoords does for admin0 (#1331) — sidesteps the whole class of bug: the
// stored region_code/region_name are then guaranteed to equal a bundle feature.
//
// The admin1 bundle is streamed and held as per-country GeoJSON text (never parsed whole,
// #1576), so a country's region features are parsed and flattened to CompactGeom on first
// use and cached — only visited countries ever pay the parse.
// The admin1 regions ship as one file per country (never parsed whole, #1576), so a
// country's region features are read, parsed and flattened to CompactGeom on first use
// and cached — only visited countries ever pay the parse.
type RegionFeature = { code: string; name: string; nameEn: string; geom: CompactGeom; boxes: Box[] };
const regionFeatureCache = new Map<string, RegionFeature[]>();
@@ -534,15 +527,14 @@ async function getRegionFeatures(countryCode: string): Promise<RegionFeature[]>
const cc = countryCode.toUpperCase();
const cached = regionFeatureCache.get(cc);
if (cached) return cached;
const store = await getAdmin1Store();
const text = store.get(cc);
if (!text) {
const json = readAdmin1Json(cc);
if (!json) {
regionFeatureCache.set(cc, []);
return [];
}
let features: { properties?: Record<string, string>; geometry?: { type: string; coordinates: unknown } }[];
try {
features = JSON.parse(`{"type":"FeatureCollection","features":[${text}]}`).features ?? [];
features = JSON.parse(json.toString('utf8')).features ?? [];
} catch {
regionFeatureCache.set(cc, []);
return [];
+33 -8
View File
@@ -1,6 +1,8 @@
import type { User } from '../../types';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import { getRegionGeoGz, getRegionGeoJson } from './atlas-geo';
import { AtlasWritesService } from './atlas-writes.service';
import { AtlasMarkRegionDto, AtlasCreateBucketItemDto, AtlasUpdateBucketItemDto } from './atlas.dto';
import { AtlasService, BucketItemExistsError } from './atlas.service';
@@ -20,7 +22,8 @@ import {
Res,
UseGuards,
} from '@nestjs/common';
import type { AtlasLocateResponse, RegionGeo } from '@trek/shared';
import { regionGeoParamsSchema } from '@trek/shared';
import type { AtlasLocateResponse, RegionGeoParams } from '@trek/shared';
import type { Response } from 'express';
@@ -78,20 +81,42 @@ export class AtlasController {
return this.atlas.locate(latNum, lngNum);
}
// Kept for clients from before the map asked for one country at a time (below). They
// get the same FeatureCollection as before, joined from the per-country files without
// a parse; drop it once those clients are gone.
@Get('regions/geo')
async regionGeo(
@Query('countries') countries: string | undefined,
@Res({ passthrough: true }) res: Response,
): Promise<RegionGeo> {
regionGeo(@Query('countries') countries: string | undefined, @Res() res: Response): void {
const list = (countries || '').split(',').filter(Boolean);
if (list.length === 0) {
return { type: 'FeatureCollection', features: [] };
res.json({ type: 'FeatureCollection', features: [] });
return;
}
const geo = await this.atlas.regionGeo(list);
const json = getRegionGeoJson(list);
// Cache only a non-empty result, matching the legacy route (the empty
// short-circuit above sends no Cache-Control header).
res.setHeader('Cache-Control', 'public, max-age=86400');
return geo;
res.type('application/json').send(json);
}
// response-contract-exempt: sends a gzipped file through @Res() as it is, there is no JSON body to check.
@Get('regions/geo/:code')
async regionGeoForCountry(
@Param(new ZodValidationPipe(regionGeoParamsSchema)) params: RegionGeoParams,
@Res() res: Response,
): Promise<void> {
// One country's pre-gzipped admin-1 file, served the way countries/geo is: the server
// never parses or holds it (#1576), and the browser caches every country on its own. A
// country the bundle has no regions for gets an empty FeatureCollection, cached the
// same, so it is not asked again; a code that is not two letters is a 400.
const gz = await getRegionGeoGz(params.code);
res.setHeader('Cache-Control', 'public, max-age=86400');
if (!gz) {
res.json({ type: 'FeatureCollection', features: [] });
return;
}
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Content-Encoding', 'gzip');
res.send(gz);
}
@Get('countries/geo')
-5
View File
@@ -28,7 +28,6 @@ import {
getCountryFromCoords,
getCountryGeoGz,
getRegionFromCoords,
getRegionGeo,
geocodingInFlight,
resolveCountryCodeSync,
resolveRegionFromBundle,
@@ -877,10 +876,6 @@ export class AtlasService {
};
}
regionGeo(countries: string[]) {
return getRegionGeo(countries);
}
countryGeoGz(): Buffer | null {
return getCountryGeoGz();
}
+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,