fix(tours): paddle data reads stream, queue safely and keep their coverage during a refresh

The PBF reader streams the extract and refuses a varint longer than ten bytes; the block offsets are read as the plain int64 the format defines. Region reads queue without loose promises: a region queued while another is read is still picked up, removing a region calls its read off, a shutdown stops the read under way and the next boot queues it again and clears the download folder. The admin list shows how far a read has come.

Geofabrik is asked only on its own servers, redirects included, and an outage of its list answers 502 instead of an unknown region. Nested ids such as us/texas are accepted.

A region being read again or after a failed read still counts with the data it holds, a region without a boundary spans its objects, and an object two overlapping regions hold is answered once. Stored geometry, tags and boundaries go through the JSON column declarations. An obstacle is related to the route both ways, so a long weir passed in its middle and a route inside an area count.

Tests cover the reader with extracts written in the test, the tag rules, the extraction and lock grouping, the geo helpers, the Geofabrik client, the region queue, the read side, both controllers, the job, the repositories and the HTTP routes; the domain gets its coverage entry.
This commit is contained in:
Maurice
2026-10-16 22:27:29 +00:00
parent 2c3b20bb57
commit 89ad4ec56a
40 changed files with 3307 additions and 234 deletions
+25
View File
@@ -2,11 +2,15 @@ import type { JsonColumn } from '../utils/json-column';
import {
FERRATAS_RESULT_CAP,
ferrataSchema,
paddleGeometrySchema,
paddleLockSchema,
paddleRegionBoundarySchema,
tourFixedLegSchema,
trackMarksSchema,
type Ferrata,
type PaddleGeometry,
type PaddleLock,
type PaddleRegionBoundary,
type TourFixedLeg,
type TrackMarks,
} from '@trek/shared';
@@ -166,3 +170,24 @@ export const TOUR_TRACK_MARKS: JsonColumn<TrackMarks | null> = {
schema: trackMarksSchema.nullable(),
fallback: () => null,
};
/** A paddle object's own geometry (PAD-05A). A broken row has none, and the object is left out rather than drawn anywhere. */
export const PADDLE_FEATURE_GEOMETRY: JsonColumn<PaddleGeometry | null> = {
column: 'paddle_features.geometry',
schema: paddleGeometrySchema.nullable(),
fallback: () => null,
};
/** The OSM tags a paddle object was judged by. A broken row shows none. */
export const PADDLE_FEATURE_TAGS: JsonColumn<Record<string, string>> = {
column: 'paddle_features.tags',
schema: z.record(z.string(), z.string()),
fallback: () => ({}),
};
/** The boundary of a region TREK reads paddle data for. A broken row has none, and the region counts by its box. */
export const PADDLE_REGION_BOUNDARY: JsonColumn<PaddleRegionBoundary | null> = {
column: 'paddle_regions.boundary',
schema: paddleRegionBoundarySchema.nullable(),
fallback: () => null,
};
@@ -58,6 +58,8 @@ export class Migration20200101044100_paddle_obstacles_from_openstreetmap extends
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_paddle_features_region_ref ON paddle_features(region_id, osm_ref)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_paddle_features_box ON paddle_features(min_lat, max_lat, min_lng, max_lng)');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_paddle_features_box ON paddle_features(min_lat, max_lat, min_lng, max_lng)',
);
}
}
@@ -69,12 +69,17 @@ export class PaddleFeaturesRepository extends TrekRepository<PaddleFeatures> {
/** Drops a region's objects and writes the new read in their place; the caller holds the transaction. */
async replaceRegion(regionId: string, rows: readonly PaddleFeatureRow[]): Promise<void> {
await this.db().deleteFrom('paddle_features').where('region_id', '=', regionId).execute();
for (let start = 0; start < rows.length; start += INSERT_CHUNK) {
await this.db()
.insertInto('paddle_features')
.values(rows.slice(start, start + INSERT_CHUNK).map((row) => ({ ...row, region_id: regionId })))
.onConflict((oc) => oc.columns(['region_id', 'osm_ref']).doNothing())
.execute();
}
await this.insertFrom(regionId, rows, 0);
}
/** The rows from `start` on, a chunk per statement, one after another on the transaction's connection. */
private async insertFrom(regionId: string, rows: readonly PaddleFeatureRow[], start: number): Promise<void> {
if (start >= rows.length) return;
await this.db()
.insertInto('paddle_features')
.values(rows.slice(start, start + INSERT_CHUNK).map((row) => ({ ...row, region_id: regionId })))
.onConflict((oc) => oc.columns(['region_id', 'osm_ref']).doNothing())
.execute();
await this.insertFrom(regionId, rows, start + INSERT_CHUNK);
}
}
@@ -1,7 +1,7 @@
import type { PaddleRegions } from '../entities/PaddleRegions.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
import type { Box } from './PaddleFeatures.repository';
import { TrekRepository } from './_shared/trek-repository';
export type PaddleRegionStatus = 'queued' | 'importing' | 'ready' | 'failed';
@@ -55,16 +55,21 @@ export class PaddleRegionsRepository extends TrekRepository<PaddleRegions> {
return await this.db().selectFrom('paddle_regions').select(COLUMNS).where('id', '=', id).executeTakeFirst();
}
/** The regions with data whose box reaches into `box`. */
async readyInBox(box: Box): Promise<PaddleRegionRow[]> {
/**
* The regions holding data whose box reaches into `box`, by name. A region
* read again, or whose last read failed, still holds the data of the read
* before, so it counts until it is removed.
*/
async withDataInBox(box: Box): Promise<PaddleRegionRow[]> {
return await this.db()
.selectFrom('paddle_regions')
.select(COLUMNS)
.where('status', '=', 'ready')
.where('imported_at', 'is not', null)
.where('min_lat', '<=', box.north)
.where('max_lat', '>=', box.south)
.where('min_lng', '<=', box.east)
.where('max_lng', '>=', box.west)
.orderBy('name', 'asc')
.execute();
}
@@ -78,7 +83,9 @@ export class PaddleRegionsRepository extends TrekRepository<PaddleRegions> {
.executeTakeFirst();
}
async insertRegion(row: Pick<PaddleRegionRow, 'id' | 'name' | 'boundary' | 'min_lat' | 'min_lng' | 'max_lat' | 'max_lng'>): Promise<void> {
async insertRegion(
row: Pick<PaddleRegionRow, 'id' | 'name' | 'boundary' | 'min_lat' | 'min_lng' | 'max_lat' | 'max_lng'>,
): Promise<void> {
await this.db()
.insertInto('paddle_regions')
.values({ ...row, status: 'queued', feature_count: 0 })
@@ -88,16 +95,29 @@ export class PaddleRegionsRepository extends TrekRepository<PaddleRegions> {
async updateRegion(
id: string,
patch: Partial<Pick<PaddleRegionRow, 'status' | 'source_timestamp' | 'imported_at' | 'feature_count' | 'error'>>,
patch: Partial<
Pick<
PaddleRegionRow,
| 'status'
| 'source_timestamp'
| 'imported_at'
| 'feature_count'
| 'error'
| 'min_lat'
| 'min_lng'
| 'max_lat'
| 'max_lng'
>
>,
): Promise<void> {
await this.db().updateTable('paddle_regions').set(patch).where('id', '=', id).execute();
}
/** Queues every region that has data again, for the monthly refresh; returns how many. */
/** Queues every region that has data or a failed read again, for the monthly refresh; returns how many. */
async queueReady(): Promise<number> {
const result = await this.db()
.updateTable('paddle_regions')
.set({ status: 'queued' })
.set({ status: 'queued', error: null })
.where('status', 'in', ['ready', 'failed'])
.executeTakeFirst();
return Number(result.numUpdatedRows ?? 0);
+1 -1
View File
@@ -43,7 +43,6 @@ import { DaysModule } from './days/days.module';
import { DocSyncModule } from './doc-sync/doc-sync.module';
import { FeedsModule } from './feeds/feeds.module';
import { FerratasModule } from './ferratas/ferratas.module';
import { PaddleObstaclesModule } from './paddle-obstacles/paddle-obstacles.module';
import { FilesModule } from './files/files.module';
import { GeoModule } from './geo/geo.module';
import { GoogleQuotaModule } from './google-quota/google-quota.module';
@@ -62,6 +61,7 @@ import { NotificationsModule } from './notifications/notifications.module';
import { OauthModule } from './oauth/oauth.module';
import { OidcModule } from './oidc/oidc.module';
import { PackingModule } from './packing/packing.module';
import { PaddleObstaclesModule } from './paddle-obstacles/paddle-obstacles.module';
import { PermissionsModule } from './permissions/permissions.module';
import { PhotosModule } from './photos/photos.module';
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
@@ -1,18 +1,20 @@
import { readCappedJson } from '../../utils/cappedFetch';
import { regionBoundarySchema, type RegionBoundary } from './paddle-geo';
import type { RegionBoundary } from './paddle-geo';
import { Injectable } from '@nestjs/common';
import { z } from 'zod';
import { paddleRegionBoundarySchema } from '@trek/shared';
import { createWriteStream } from 'node:fs';
import { unlink } from 'node:fs/promises';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import type { ReadableStream as WebReadableStream } from 'node:stream/web';
import { z } from 'zod';
/**
* The outbound half of PAD-05A: Geofabrik's list of regional extracts and the
* download of one. Only Geofabrik's own host is ever asked, at addresses its
* list names, so an admin choosing a region can point TREK nowhere else.
* list names, so an admin choosing a region can point TREK nowhere else. A
* redirect is followed only to another address of Geofabrik's.
*/
export const GEOFABRIK_HOST = 'https://download.geofabrik.de/';
@@ -24,6 +26,7 @@ const INDEX_FRESH_MS = 24 * 60 * 60 * 1000;
/** A whole country is a few gigabytes; a regional extract far less. More than this is refused. */
export const MAX_EXTRACT_BYTES = 4 * 1024 * 1024 * 1024;
const DOWNLOAD_TIMEOUT_MS = 60 * 60 * 1000;
const MAX_REDIRECTS = 3;
const indexSchema = z.object({
features: z.array(
@@ -47,6 +50,32 @@ export interface GeofabrikRegion {
boundary: RegionBoundary | null;
}
/** An address on Geofabrik's own servers, over https. */
function isGeofabrikUrl(url: URL): boolean {
return url.protocol === 'https:' && (url.hostname === 'geofabrik.de' || url.hostname.endsWith('.geofabrik.de'));
}
/** An extract the list names: Geofabrik's host, a `-latest.osm.pbf` file. */
export function isExtractUrl(url: string): boolean {
return url.startsWith(GEOFABRIK_HOST) && url.endsWith('-latest.osm.pbf');
}
/**
* `fetch` that follows a redirect only while it stays on Geofabrik's servers.
* A redirect anywhere else is refused, so the list's addresses are the only
* ones TREK ever reads an extract from.
*/
async function fetchFromGeofabrik(url: string, signal: AbortSignal, hops = 0): Promise<Response> {
const response = await fetch(url, { signal, redirect: 'manual' });
if (response.status < 300 || response.status >= 400) return response;
await response.body?.cancel().catch(() => undefined);
const location = response.headers.get('location');
const next = location ? new URL(location, url) : null;
if (!next || !isGeofabrikUrl(next)) throw new Error('Geofabrik redirected away from its own servers');
if (hops >= MAX_REDIRECTS) throw new Error('Geofabrik redirected too often');
return await fetchFromGeofabrik(next.href, signal, hops + 1);
}
@Injectable()
export class GeofabrikClient {
private index: { regions: Map<string, GeofabrikRegion>; fetchedAt: number } | null = null;
@@ -54,18 +83,25 @@ export class GeofabrikClient {
/** Every region the list names that has an extract on Geofabrik's host, by id. */
async regions(now: number = Date.now()): Promise<Map<string, GeofabrikRegion>> {
if (this.index && now - this.index.fetchedAt < INDEX_FRESH_MS) return this.index.regions;
const response = await fetch(INDEX_URL, { signal: AbortSignal.timeout(INDEX_TIMEOUT_MS) });
const response = await fetchFromGeofabrik(INDEX_URL, AbortSignal.timeout(INDEX_TIMEOUT_MS));
if (!response.ok) {
await response.body?.cancel().catch(() => undefined);
throw new Error(`Geofabrik index ${response.status}`);
}
const parsed = indexSchema.parse(await readCappedJson<unknown>(response, MAX_INDEX_BYTES));
const parsed = indexSchema.safeParse(await readCappedJson<unknown>(response, MAX_INDEX_BYTES));
if (!parsed.success) throw new Error('Geofabrik index is not the list of extracts');
const regions = new Map<string, GeofabrikRegion>();
for (const feature of parsed.features) {
for (const feature of parsed.data.features) {
const { id, name, parent, urls } = feature.properties;
if (!urls.pbf?.startsWith(GEOFABRIK_HOST) || !urls.pbf.endsWith('-latest.osm.pbf')) continue;
const boundary = regionBoundarySchema.safeParse(feature.geometry);
regions.set(id, { id, name, parent: parent ?? null, pbfUrl: urls.pbf, boundary: boundary.success ? boundary.data : null });
if (!urls.pbf || !isExtractUrl(urls.pbf)) continue;
const boundary = paddleRegionBoundarySchema.safeParse(feature.geometry);
regions.set(id, {
id,
name,
parent: parent ?? null,
pbfUrl: urls.pbf,
boundary: boundary.success ? boundary.data : null,
});
}
this.index = { regions, fetchedAt: now };
return regions;
@@ -73,26 +109,49 @@ export class GeofabrikClient {
/**
* One region's extract written to `target`. The address must be one the
* list named; the body is counted as it streams and cut at
* MAX_EXTRACT_BYTES, and the file goes when the download fails.
* list named; the body is counted as it streams and cut at `maxBytes`
* (MAX_EXTRACT_BYTES unless the caller allows less), and the file goes when
* the download fails or `signal` calls it off. `onProgress` hears the share
* received so far when the server said how much there is.
*/
async download(url: string, target: string): Promise<void> {
if (!url.startsWith(GEOFABRIK_HOST) || !url.endsWith('-latest.osm.pbf')) throw new Error('Not a Geofabrik extract');
const response = await fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
async download(
url: string,
target: string,
options: { signal?: AbortSignal; onProgress?: (fraction: number) => void; maxBytes?: number } = {},
): Promise<void> {
const maxBytes = Math.min(options.maxBytes ?? MAX_EXTRACT_BYTES, MAX_EXTRACT_BYTES);
if (!isExtractUrl(url)) throw new Error('Not a Geofabrik extract');
const deadline = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);
const signal = options.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
const response = await fetchFromGeofabrik(url, signal);
if (!response.ok || !response.body) {
await response.body?.cancel().catch(() => undefined);
throw new Error(`Geofabrik download ${response.status}`);
}
const declared = Number(response.headers.get('content-length') ?? 0);
if (declared > maxBytes) {
await response.body.cancel().catch(() => undefined);
throw new Error('Extract larger than allowed');
}
let received = 0;
const counter = new Transform({
transform(chunk: Buffer, _encoding, done) {
received += chunk.length;
if (received > MAX_EXTRACT_BYTES) done(new Error('Extract larger than allowed'));
else done(null, chunk);
if (received > maxBytes) {
done(new Error('Extract larger than allowed'));
return;
}
if (declared > 0) options.onProgress?.(Math.min(1, received / declared));
done(null, chunk);
},
});
try {
await pipeline(Readable.fromWeb(response.body as unknown as WebReadableStream), counter, createWriteStream(target));
await pipeline(
Readable.fromWeb(response.body as unknown as WebReadableStream),
counter,
createWriteStream(target),
{ signal },
);
} catch (err) {
await unlink(target).catch(() => undefined);
throw err;
@@ -1,4 +1,4 @@
import { open } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import { inflateSync } from 'node:zlib';
/**
@@ -13,9 +13,15 @@ import { inflateSync } from 'node:zlib';
* megabytes). The format: https://wiki.openstreetmap.org/wiki/PBF_Format
*/
/** A varint is at most ten bytes; more means the data is not protobuf. */
const MAX_VARINT_BYTES = 10;
const TWO_POW_63 = 2 ** 63;
const TWO_POW_64 = 2 ** 64;
/** A blob's size may not exceed this, by the format's own rule. */
const MAX_BLOB_BYTES = 32 * 1024 * 1024;
const MAX_HEADER_BYTES = 64 * 1024;
/** Read a quarter megabyte at a time: a block or two, so no chunk holds the event loop for long. */
const READ_CHUNK_BYTES = 256 * 1024;
export interface OsmNode {
id: number;
@@ -56,13 +62,20 @@ class Proto {
varint(): number {
let result = 0;
let scale = 1;
for (;;) {
for (let read = 0; read < MAX_VARINT_BYTES; read++) {
if (this.pos >= this.end) throw new Error('Truncated varint');
const byte = this.buf[this.pos++] as number;
result += (byte & 0x7f) * scale;
if (byte < 0x80) return result;
scale *= 128;
}
throw new Error('Malformed varint');
}
/** A plain (not zigzag) signed 64-bit varint: a negative value is written as its two's complement. */
int64(): number {
const raw = this.varint();
return raw >= TWO_POW_63 ? raw - TWO_POW_64 : raw;
}
/** A zigzag-encoded signed varint. */
@@ -94,12 +107,17 @@ class Proto {
skip(wire: number): void {
if (wire === 0) this.varint();
else if (wire === 1) this.pos += 8;
else if (wire === 1) this.advance(8);
else if (wire === 2) this.span();
else if (wire === 5) this.pos += 4;
else if (wire === 5) this.advance(4);
else throw new Error(`Unsupported wire type ${wire}`);
}
private advance(bytes: number): void {
this.pos += bytes;
if (this.pos > this.end) throw new Error('Truncated field');
}
/** A packed field of varints (or zigzag varints), decoded whole. */
packed(signed: boolean): number[] {
const [start, stop] = this.span();
@@ -158,7 +176,11 @@ interface BlockContext {
lonOffset: number;
}
function tagsOf(keys: readonly number[], values: readonly number[], strings: readonly string[]): Record<string, string> {
function tagsOf(
keys: readonly number[],
values: readonly number[],
strings: readonly string[],
): Record<string, string> {
const tags: Record<string, string> = {};
keys.forEach((key, index) => {
const value = values[index];
@@ -260,8 +282,8 @@ export function readDataBlock(block: Buffer, visitor: OsmBlockVisitor): void {
}
} else if (key.field === 2 && key.wire === 2) groups.push(p.bytes());
else if (key.field === 17 && key.wire === 0) ctx.granularity = p.varint();
else if (key.field === 19 && key.wire === 0) ctx.latOffset = p.svarint();
else if (key.field === 20 && key.wire === 0) ctx.lonOffset = p.svarint();
else if (key.field === 19 && key.wire === 0) ctx.latOffset = p.int64();
else if (key.field === 20 && key.wire === 0) ctx.lonOffset = p.int64();
else p.skip(key.wire);
}
for (const group of groups) {
@@ -276,42 +298,86 @@ export function readDataBlock(block: Buffer, visitor: OsmBlockVisitor): void {
}
/**
* Every block of a PBF file in order, read from disk one at a time. The
* header block is answered with its timestamp; data blocks go to the visitor.
* `onBlock` is told the bytes read so far, for progress and to give way to
* other work between blocks.
* The bytes read from a file and not yet taken as a blob, kept as the chunks
* they arrived in and joined only when a blob reaches across chunks.
*/
class ByteQueue {
private chunks: Buffer[] = [];
length = 0;
push(chunk: Buffer): void {
this.chunks.push(chunk);
this.length += chunk.length;
}
/** The first `n` bytes, left in the queue; null while fewer have arrived. */
peek(n: number): Buffer | null {
if (this.length < n) return null;
const first = this.chunks[0];
if (first && first.length >= n) return first.subarray(0, n);
const joined = Buffer.concat(this.chunks);
this.chunks = [joined];
return joined.subarray(0, n);
}
/** Takes the first `n` bytes off the queue; the caller has peeked at least that many. */
drop(n: number): void {
let left = n;
while (left > 0) {
const first = this.chunks[0] as Buffer;
if (first.length <= left) {
this.chunks.shift();
left -= first.length;
} else {
this.chunks[0] = first.subarray(left);
left = 0;
}
}
this.length -= n;
}
}
/** The next whole blob at the head of the queue, taken off it; null while it has not all arrived. */
function nextBlob(queue: ByteQueue): { type: string; data: Buffer } | null {
const prefix = queue.peek(4);
if (!prefix) return null;
const headerLength = prefix.readUInt32BE(0);
if (headerLength > MAX_HEADER_BYTES) throw new Error('Blob header too large');
const head = queue.peek(4 + headerLength);
if (!head) return null;
const header = readBlobHeader(head.subarray(4));
if (header.size > MAX_BLOB_BYTES) throw new Error('Blob too large');
const whole = queue.peek(4 + headerLength + header.size);
if (!whole) return null;
queue.drop(whole.length);
return { type: header.type, data: whole.subarray(4 + headerLength) };
}
/**
* Every block of a PBF file in order, streamed from disk. The header block is
* answered with its timestamp; data blocks go to the visitor. The blocks of
* one chunk are read at once, and the event loop gets its turn between
* chunks. `onProgress` is told the bytes read so far.
*/
export async function readPbfFile(
path: string,
visitor: OsmBlockVisitor,
onBlock?: (bytesRead: number) => Promise<void> | void,
onProgress?: (bytesRead: number) => void,
): Promise<{ timestamp: number | null }> {
const file = await open(path, 'r');
const queue = new ByteQueue();
let timestamp: number | null = null;
try {
let offset = 0;
const lengthBuf = Buffer.alloc(4);
for (;;) {
const { bytesRead } = await file.read(lengthBuf, 0, 4, offset);
if (bytesRead === 0) break;
if (bytesRead < 4) throw new Error('Truncated blob length');
const headerLength = lengthBuf.readUInt32BE(0);
if (headerLength > MAX_HEADER_BYTES) throw new Error('Blob header too large');
const headerBuf = Buffer.alloc(headerLength);
await file.read(headerBuf, 0, headerLength, offset + 4);
const header = readBlobHeader(headerBuf);
if (header.size > MAX_BLOB_BYTES) throw new Error('Blob too large');
const blobBuf = Buffer.alloc(header.size);
const read = await file.read(blobBuf, 0, header.size, offset + 4 + headerLength);
if (read.bytesRead < header.size) throw new Error('Truncated blob');
const block = readBlob(blobBuf);
if (header.type === 'OSMHeader') timestamp = readHeaderTimestamp(block);
else if (header.type === 'OSMData') readDataBlock(block, visitor);
offset += 4 + headerLength + header.size;
await onBlock?.(offset);
let bytesRead = 0;
for await (const chunk of createReadStream(path, { highWaterMark: READ_CHUNK_BYTES })) {
const bytes = chunk as Buffer;
queue.push(bytes);
bytesRead += bytes.length;
for (let blob = nextBlob(queue); blob; blob = nextBlob(queue)) {
const block = readBlob(blob.data);
if (blob.type === 'OSMHeader') timestamp = readHeaderTimestamp(block);
else if (blob.type === 'OSMData') readDataBlock(block, visitor);
}
} finally {
await file.close();
onProgress?.(bytesRead);
}
if (queue.length > 0) throw new Error('Truncated blob');
return { timestamp };
}
@@ -3,6 +3,7 @@ import { keptTags, paddleKindOf, paddleNameOf } from './paddle-tags';
import type { PaddleGeometry, PaddleObstacleKind } from '@trek/shared';
import { createHash } from 'node:crypto';
import { stat } from 'node:fs/promises';
/**
* PAD-05A: the paddle objects of one regional extract, read in two passes.
@@ -42,10 +43,12 @@ function hashOf(tags: Record<string, string>, geometry: PaddleGeometry): string
const rounded = JSON.stringify(geometry, (_key, value: unknown) =>
typeof value === 'number' ? Math.round(value * 1e6) / 1e6 : value,
);
return createHash('sha1').update(JSON.stringify(sorted)).update(rounded).digest('hex').slice(0, 16);
return createHash('sha256').update(JSON.stringify(sorted)).update(rounded).digest('hex').slice(0, 16);
}
function boxOf(points: ReadonlyArray<readonly [number, number]>): Pick<ExtractedFeature, 'min_lat' | 'min_lng' | 'max_lat' | 'max_lng'> {
function boxOf(
points: ReadonlyArray<readonly [number, number]>,
): Pick<ExtractedFeature, 'min_lat' | 'min_lng' | 'max_lat' | 'max_lng'> {
let minLat = 90;
let minLng = 180;
let maxLat = -90;
@@ -88,7 +91,10 @@ function build(
};
}
function wayFeature(pending: PendingWay, coords: ReadonlyMap<number, readonly [number, number]>): ExtractedFeature | null {
function wayFeature(
pending: PendingWay,
coords: ReadonlyMap<number, readonly [number, number]>,
): ExtractedFeature | null {
const points = pending.way.refs.flatMap((ref) => {
const at = coords.get(ref);
return at ? [at] : [];
@@ -98,7 +104,9 @@ function wayFeature(pending: PendingWay, coords: ReadonlyMap<number, readonly [n
const last = points[points.length - 1] as readonly [number, number];
const closed = points.length >= 4 && first[0] === last[0] && first[1] === last[1];
const line = points.map(([lng, lat]) => [lng, lat] as [number, number]);
const geometry: PaddleGeometry = closed ? { type: 'Polygon', coordinates: [line] } : { type: 'LineString', coordinates: line };
const geometry: PaddleGeometry = closed
? { type: 'Polygon', coordinates: [line] }
: { type: 'LineString', coordinates: line };
return build(`way/${pending.way.id}`, pending.kind, pending.way.tags, geometry, points);
}
@@ -144,11 +152,18 @@ export function groupLockParts(features: ExtractedFeature[]): void {
}
}
/** Every paddle object of the extract at `path`, and the date its data is current to. */
/**
* Every paddle object of the extract at `path`, and the date its data is
* current to. `onProgress` hears the share of the work done: the first pass
* is the first half, the lookup of the ways' nodes the second.
*/
export async function extractPaddleFeatures(
path: string,
onProgress?: (bytesRead: number) => Promise<void> | void,
onProgress?: (fraction: number) => void,
): Promise<{ timestamp: number | null; features: ExtractedFeature[] }> {
const { size } = await stat(path);
const progressOf = (pass: number) => (bytesRead: number) =>
onProgress?.(size > 0 ? (pass + Math.min(1, bytesRead / size)) / 2 : 1);
const features: ExtractedFeature[] = [];
const pending: PendingWay[] = [];
const needed = new Set<number>();
@@ -170,20 +185,25 @@ export async function extractPaddleFeatures(
for (const ref of refs) needed.add(ref);
},
},
onProgress,
progressOf(0),
);
if (pending.length > 0) {
const coords = new Map<number, readonly [number, number]>();
await readPbfFile(path, {
node: (node) => {
if (needed.has(node.id)) coords.set(node.id, [node.lon, node.lat]);
await readPbfFile(
path,
{
node: (node) => {
if (needed.has(node.id)) coords.set(node.id, [node.lon, node.lat]);
},
},
});
progressOf(1),
);
for (const way of pending) {
const feature = wayFeature(way, coords);
if (feature) features.push(feature);
}
}
onProgress?.(1);
groupLockParts(features);
return { timestamp, features };
}
@@ -1,14 +1,11 @@
import type { Box } from '../../db/repositories/PaddleFeatures.repository';
import { PADDLE_OBSTACLES_MAX_SPAN_DEG, type PaddleCoverageState } from '@trek/shared';
import { z } from 'zod';
import {
PADDLE_OBSTACLES_MAX_SPAN_DEG,
type PaddleCoverageState,
type PaddleRegionBoundary as RegionBoundary,
} from '@trek/shared';
/** Geofabrik's region boundaries: a polygon or several, rings of [lng, lat]. */
const ring = z.array(z.tuple([z.number(), z.number()]));
export const regionBoundarySchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('Polygon'), coordinates: z.array(ring) }),
z.object({ type: z.literal('MultiPolygon'), coordinates: z.array(z.array(ring)) }),
]);
export type RegionBoundary = z.infer<typeof regionBoundarySchema>;
export type { RegionBoundary };
/** `south,west,north,east` as a box, or null when it is not one or wider than a request may ask. */
export function parseBox(text: string): Box | null {
@@ -1,15 +1,18 @@
import { PaddleFeatures } from '../../db/entities/PaddleFeatures.entity';
import { PaddleRegions } from '../../db/entities/PaddleRegions.entity';
import { PADDLE_FEATURE_GEOMETRY, PADDLE_FEATURE_TAGS, PADDLE_REGION_BOUNDARY } from '../../db/json-columns';
import type { Box, PaddleFeatureRow, PaddleFeaturesRepository } from '../../db/repositories/PaddleFeatures.repository';
import type { PaddleRegionsRepository } from '../../db/repositories/PaddleRegions.repository';
import { utcSuffix } from '../../db/types';
import { decodeJson } from '../../utils/json-column';
import { logWarn } from '../audit/audit-log.logger';
import { badRequest } from '../common/domain-error';
import { coverageOf, parseBox, regionBoundarySchema, type RegionBoundary } from './paddle-geo';
import { coverageOf, parseBox } from './paddle-geo';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
PADDLE_OBSTACLES_CAP,
paddleFeatureSchema,
paddleObstacleKindSchema,
type PaddleFeature,
type PaddleObstaclesResponse,
} from '@trek/shared';
@@ -17,29 +20,31 @@ import {
export const PADDLE_BOX_INVALID_MESSAGE = 'bbox must be south,west,north,east and at most one degree a side';
function featureOf(row: PaddleFeatureRow): PaddleFeature | null {
try {
const parsed = paddleFeatureSchema.safeParse({
ref: row.osm_ref,
kind: row.kind,
group_key: row.group_key,
name: row.name,
geometry: JSON.parse(row.geometry),
tags: JSON.parse(row.tags),
tag_hash: row.tag_hash,
region_id: row.region_id,
});
if (parsed.success) return parsed.data;
} catch {
// Unreadable JSON falls through to the log line below.
const context = `${row.region_id}/${row.osm_ref}`;
const kind = paddleObstacleKindSchema.safeParse(row.kind);
const geometry = decodeJson(PADDLE_FEATURE_GEOMETRY, row.geometry, context);
if (!kind.success || !geometry) {
logWarn(`[Paddle] stored object ${context} does not read; left out`);
return null;
}
logWarn(`[Paddle] stored object ${row.region_id}/${row.osm_ref} does not read; left out`);
return null;
return {
ref: row.osm_ref,
kind: kind.data,
group_key: row.group_key,
name: row.name,
geometry,
tags: decodeJson(PADDLE_FEATURE_TAGS, row.tags, context),
tag_hash: row.tag_hash,
region_id: row.region_id,
};
}
/**
* PAD-05A, the reading side: the paddle objects inside a map area and how far
* TREK's data covers it. An area outside every region answers `none`, not an
* empty list read as "no obstacles"; one cut at the cap says so.
* empty list read as "no obstacles"; one cut at the cap says so. Where two
* regions overlap (a country and one of its states), an object both hold is
* answered once.
*/
@Injectable()
export class PaddleObstaclesService {
@@ -58,29 +63,29 @@ export class PaddleObstaclesService {
async read(box: Box): Promise<PaddleObstaclesResponse> {
const [rows, regions] = await Promise.all([
this.features.findInBox(box, PADDLE_OBSTACLES_CAP + 1),
this.regions.readyInBox(box),
this.regions.withDataInBox(box),
]);
const boundaries = regions.map((region): RegionBoundary | null => {
if (!region.boundary) return null;
try {
const parsed = regionBoundarySchema.safeParse(JSON.parse(region.boundary));
return parsed.success ? parsed.data : null;
} catch {
return null;
}
const seen = new Set<string>();
const unique = rows.filter((row) => {
if (seen.has(row.osm_ref)) return false;
seen.add(row.osm_ref);
return true;
});
return {
features: rows.slice(0, PADDLE_OBSTACLES_CAP).flatMap((row) => featureOf(row) ?? []),
features: unique.slice(0, PADDLE_OBSTACLES_CAP).flatMap((row) => featureOf(row) ?? []),
coverage: {
state: coverageOf(box, boundaries),
state: coverageOf(
box,
regions.map((region) => decodeJson(PADDLE_REGION_BOUNDARY, region.boundary, region.id)),
),
regions: regions.map((region) => ({
id: region.id,
name: region.name,
source_timestamp: region.source_timestamp,
imported_at: region.imported_at === null ? null : `${region.imported_at.replace(' ', 'T')}Z`,
imported_at: utcSuffix(region.imported_at),
})),
},
truncated: rows.length > PADDLE_OBSTACLES_CAP,
truncated: unique.length > PADDLE_OBSTACLES_CAP,
};
}
}
@@ -16,12 +16,22 @@ export class PaddleRegionsJob implements OnApplicationBootstrap {
private readonly registrar: CronRegistrarService,
) {}
/** @txIndependent the boot resume and the monthly tick are two separate runs, never one sequence of writes */
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
void this.registrar.runOnBoot('paddle-regions-resume', () => this.regions.resumeAfterRestart());
void this.registrar.runOnBoot('paddle-regions-resume', () => this.resume());
this.registrar.register('paddle-regions-refresh', '20 4 3 * *', () => this.tick());
}
/** The boot's half: a failure is logged, never thrown at the boot. */
async resume(): Promise<void> {
try {
await this.regions.resumeAfterRestart();
} catch (err) {
logError(`[Paddle] resuming the reads after a restart: ${err instanceof Error ? err.message : String(err)}`);
}
}
async tick(): Promise<void> {
try {
const queued = await this.regions.queueRefresh();
@@ -1,38 +1,47 @@
import { PaddleFeatures } from '../../db/entities/PaddleFeatures.entity';
import { PaddleRegions } from '../../db/entities/PaddleRegions.entity';
import { PADDLE_FEATURE_GEOMETRY, PADDLE_FEATURE_TAGS, PADDLE_REGION_BOUNDARY } from '../../db/json-columns';
import type { PaddleFeatureRow, PaddleFeaturesRepository } from '../../db/repositories/PaddleFeatures.repository';
import type { PaddleRegionRow, PaddleRegionsRepository } from '../../db/repositories/PaddleRegions.repository';
import { dbNow } from '../../db/types';
import { dbNow, utcSuffix } from '../../db/types';
import { encodeJson } from '../../utils/json-column';
import { DataPathsService } from '../app-config/data-paths.service';
import { logError, logInfo } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { withRequestContext } from '../database/request-context';
import { UnitOfWork } from '../database/unit-of-work';
import { GeofabrikClient } from './geofabrik.client';
import { GeofabrikClient, type GeofabrikRegion } from './geofabrik.client';
import { extractPaddleFeatures, type ExtractedFeature } from './paddle-extract';
import { boxOfBoundary } from './paddle-geo';
import { MikroORM } from '@mikro-orm/core';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { Injectable, type OnApplicationShutdown } from '@nestjs/common';
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
import { mkdir, unlink } from 'node:fs/promises';
import { mkdir, rm, unlink } from 'node:fs/promises';
import { join } from 'node:path';
const CATALOG_LIMIT = 25;
export const REGION_UNKNOWN_MESSAGE = 'Geofabrik has no extract by that id';
export const CATALOG_UNAVAILABLE_MESSAGE = 'The list of regions cannot be fetched right now';
export const REGION_NOT_FOUND_MESSAGE = 'Region not found';
const REMOVED_WHILE_READ = 'removed while it was read; nothing kept';
const STOPPED_AT_SHUTDOWN = 'stopped by the shutdown; read again on the next start';
function toRegion(row: PaddleRegionRow): PaddleRegion {
/** What the region being read is doing, for the admin list; held in memory, as one process reads. */
type ReadProgress = NonNullable<PaddleRegion['progress']>;
function toRegion(row: PaddleRegionRow, progress: ReadProgress | null = null): PaddleRegion {
return {
id: row.id,
name: row.name,
status: row.status,
source_timestamp: row.source_timestamp,
imported_at: row.imported_at === null ? null : `${row.imported_at.replace(' ', 'T')}Z`,
imported_at: utcSuffix(row.imported_at),
feature_count: row.feature_count,
error: row.error,
progress: row.status === 'importing' ? progress : null,
};
}
@@ -43,8 +52,8 @@ function toRow(feature: ExtractedFeature): PaddleFeatureRow {
kind: feature.kind,
group_key: feature.group_key,
name: feature.name,
geometry: JSON.stringify(feature.geometry),
tags: JSON.stringify(feature.tags),
geometry: encodeJson(PADDLE_FEATURE_GEOMETRY, feature.geometry),
tags: encodeJson(PADDLE_FEATURE_TAGS, feature.tags),
tag_hash: feature.tag_hash,
min_lat: feature.min_lat,
min_lng: feature.min_lng,
@@ -53,17 +62,41 @@ function toRow(feature: ExtractedFeature): PaddleFeatureRow {
};
}
/** The box around a read's objects, for a region whose boundary Geofabrik does not give. */
function extentOf(
features: readonly ExtractedFeature[],
): Pick<PaddleRegionRow, 'min_lat' | 'min_lng' | 'max_lat' | 'max_lng'> {
if (features.length === 0) return { min_lat: null, min_lng: null, max_lat: null, max_lng: null };
const box = { min_lat: 90, min_lng: 180, max_lat: -90, max_lng: -180 };
for (const feature of features) {
box.min_lat = Math.min(box.min_lat, feature.min_lat);
box.min_lng = Math.min(box.min_lng, feature.min_lng);
box.max_lat = Math.max(box.max_lat, feature.max_lat);
box.max_lng = Math.max(box.max_lng, feature.max_lng);
}
return box;
}
function messageOf(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/**
* PAD-05A: the regions TREK holds paddle data for. An admin picks a region
* from Geofabrik's list; TREK downloads its extract into the data folder's
* temporary space, reads the paddle objects out of it, replaces the region's
* rows in one transaction and deletes the file. Regions are read one at a
* time, in the background, never on a request's path; a failed read keeps the
* region's previous data and says why.
* region's previous data and says why. Removing a region while it is read
* calls the read off.
*/
@Injectable()
export class PaddleRegionsService {
export class PaddleRegionsService implements OnApplicationShutdown {
private running: Promise<void> | null = null;
/** A region was queued after the running reads last looked at the queue. */
private again = false;
private current: { id: string; abort: AbortController; progress: ReadProgress } | null = null;
private stopping = false;
constructor(
private readonly geofabrik: GeofabrikClient,
@@ -75,18 +108,12 @@ export class PaddleRegionsService {
) {}
async list(): Promise<PaddleRegion[]> {
return (await this.regions.list()).map(toRegion);
return (await this.regions.list()).map((row) => toRegion(row, this.progressOf(row.id)));
}
/** Regions of Geofabrik's list whose name or id matches, with the regions they lie in. */
async catalog(query: string): Promise<PaddleRegionCatalogEntry[]> {
let all: Awaited<ReturnType<GeofabrikClient['regions']>>;
try {
all = await this.geofabrik.regions();
} catch (err) {
logError(`[Paddle] Geofabrik index: ${err instanceof Error ? err.message : String(err)}`);
throw new DomainError(502, CATALOG_UNAVAILABLE_MESSAGE, { code: 'catalog_unavailable', details: { code: 'catalog_unavailable' } });
}
const all = await this.catalogue();
const needle = query.toLowerCase();
const path = (id: string | null): string[] => {
const names: string[] = [];
@@ -95,42 +122,61 @@ export class PaddleRegionsService {
};
return [...all.values()]
.filter((region) => region.name.toLowerCase().includes(needle) || region.id.includes(needle))
.sort((a, b) => Number(!a.name.toLowerCase().startsWith(needle)) - Number(!b.name.toLowerCase().startsWith(needle)))
.sort(
(a, b) => Number(!a.name.toLowerCase().startsWith(needle)) - Number(!b.name.toLowerCase().startsWith(needle)),
)
.slice(0, CATALOG_LIMIT)
.map((region) => ({ id: region.id, name: region.name, path: path(region.parent) }));
}
/** Adds a region and queues its first read; a region already there is queued again. */
/** Adds a region and queues its first read; a region already there is read again, as `refresh` does. */
async add(id: string): Promise<PaddleRegion> {
const region = (await this.geofabrik.regions().catch(() => new Map())).get(id);
if (!region) throw new DomainError(400, REGION_UNKNOWN_MESSAGE, { code: 'unknown_region', details: { code: 'unknown_region' } });
if (await this.regions.findById(id)) return await this.refresh(id);
const region = (await this.catalogue()).get(id);
if (!region)
throw new DomainError(400, REGION_UNKNOWN_MESSAGE, {
code: 'unknown_region',
details: { code: 'unknown_region' },
});
const box = region.boundary ? boxOfBoundary(region.boundary) : null;
await this.regions.insertRegion({
id,
name: region.name,
boundary: region.boundary ? JSON.stringify(region.boundary) : null,
min_lat: box?.south ?? null,
min_lng: box?.west ?? null,
max_lat: box?.north ?? null,
max_lng: box?.east ?? null,
await this.uow.transactional(async () => {
await this.regions.insertRegion({
id,
name: region.name,
boundary: region.boundary ? encodeJson(PADDLE_REGION_BOUNDARY, region.boundary) : null,
min_lat: box?.south ?? null,
min_lng: box?.west ?? null,
max_lat: box?.north ?? null,
max_lng: box?.east ?? null,
});
await this.regions.updateRegion(id, { status: 'queued', error: null });
});
await this.regions.updateRegion(id, { status: 'queued', error: null });
this.kick();
const row = await this.regions.findById(id);
if (!row) throw new Error('Added region could not be read back');
return toRegion(row);
}
/** Queues a region's read again; one already waiting or being read is left as it is. */
async refresh(id: string): Promise<PaddleRegion> {
const row = await this.regions.findById(id);
if (!row) throw new DomainError(404, 'Region not found');
if (!row) throw new DomainError(404, REGION_NOT_FOUND_MESSAGE);
if (row.status === 'queued' || row.status === 'importing') return toRegion(row, this.progressOf(id));
await this.regions.updateRegion(id, { status: 'queued', error: null });
this.kick();
return toRegion({ ...row, status: 'queued', error: null });
}
/** Removes a region and its objects; a read of it under way is called off. */
async remove(id: string): Promise<void> {
if (!(await this.regions.deleteRegion(id))) throw new DomainError(404, 'Region not found');
if (!(await this.regions.deleteRegion(id))) throw new DomainError(404, REGION_NOT_FOUND_MESSAGE);
if (this.current?.id === id) this.current.abort.abort(REMOVED_WHILE_READ);
}
/** A read under way stops with the process; the boot after it queues the region again. */
onApplicationShutdown(): void {
this.stopping = true;
this.current?.abort.abort(STOPPED_AT_SHUTDOWN);
}
/** Every region with data queued again, for the monthly refresh; the reads follow in the background. */
@@ -140,41 +186,103 @@ export class PaddleRegionsService {
return queued;
}
/** A restart left a read unfinished: it goes back to the queue, and the queue starts. */
/**
* A restart left a read unfinished: it goes back to the queue, the file it
* was reading is cleared away, and the queue starts.
*/
async resumeAfterRestart(): Promise<void> {
await this.regions.requeueInterrupted();
await rm(this.downloadDir(), { recursive: true, force: true });
this.kick();
}
/** Starts the background reads unless they already run; the promise is for tests to wait on. */
kick(): Promise<void> {
if (!this.running) {
this.running = withRequestContext(this.orm, () => this.drain()).finally(() => {
this.running = null;
});
}
return this.running;
/**
* Starts the background reads unless they already run. A region queued
* while they run is still picked up: the run looks at the queue again
* before it ends.
*
* @txStandalone the reads run detached, later, each region's rows in a transaction of their own; no caller's transaction could hold them
*/
kick(): void {
this.again = true;
if (this.running !== null || this.stopping) return;
this.running = this.run().finally(() => {
this.running = null;
if (this.again) this.kick();
});
}
private async drain(): Promise<void> {
for (let next = await this.regions.nextQueued(); next; next = await this.regions.nextQueued()) {
await this.importRegion(next);
/** Resolves once the queue is empty and nothing reads; for tests and an orderly shutdown. */
async idle(): Promise<void> {
if (this.running === null) return;
await this.running;
await this.idle();
}
/** Where extracts are downloaded to while they are read; nothing in it outlives its read. */
private downloadDir(): string {
return join(this.paths.tmpDir, 'paddle');
}
private progressOf(id: string): ReadProgress | null {
return this.current?.id === id ? { ...this.current.progress } : null;
}
private async catalogue(): Promise<Map<string, GeofabrikRegion>> {
try {
return await this.geofabrik.regions();
} catch (err) {
logError(`[Paddle] Geofabrik index: ${messageOf(err)}`);
throw new DomainError(502, CATALOG_UNAVAILABLE_MESSAGE, {
code: 'catalog_unavailable',
details: { code: 'catalog_unavailable' },
});
}
}
private async run(): Promise<void> {
this.again = false;
try {
await withRequestContext(this.orm, () => this.drain());
} catch (err) {
logError(`[Paddle] the read queue stopped: ${messageOf(err)}`);
}
}
/** The queued regions, one after another, oldest first. */
private async drain(): Promise<void> {
if (this.stopping) return;
const next = await this.regions.nextQueued();
if (!next) return;
await this.importRegion(next);
await this.drain();
}
/** @txIndependent the download and the read sit between the status writes; only the swap of rows is one transaction. */
private async importRegion(region: PaddleRegionRow): Promise<void> {
await this.regions.updateRegion(region.id, { status: 'importing', error: null });
const dir = join(this.paths.tmpDir, 'paddle');
const file = join(dir, `${region.id}-${Date.now()}.osm.pbf`);
const abort = new AbortController();
const current = { id: region.id, abort, progress: { phase: 'download', fraction: null } as ReadProgress };
this.current = current;
const dir = this.downloadDir();
// Some of Geofabrik's ids are nested (`us/texas`); the file stays in the one folder.
const file = join(dir, `${region.id.replaceAll('/', '_')}-${Date.now()}.osm.pbf`);
try {
const known = (await this.geofabrik.regions()).get(region.id);
if (!known) throw new Error(REGION_UNKNOWN_MESSAGE);
await mkdir(dir, { recursive: true });
const started = Date.now();
await this.geofabrik.download(known.pbfUrl, file);
const { timestamp, features } = await extractPaddleFeatures(file);
await this.uow.transactional(async () => {
await this.geofabrik.download(known.pbfUrl, file, {
signal: abort.signal,
onProgress: (fraction) => (current.progress = { phase: 'download', fraction }),
});
current.progress = { phase: 'read', fraction: 0 };
const { timestamp, features } = await extractPaddleFeatures(file, (fraction) => {
current.progress = { phase: 'read', fraction };
});
abort.signal.throwIfAborted();
const kept = await this.uow.transactional(async () => {
if (!(await this.regions.findById(region.id))) return false;
await this.features.replaceRegion(region.id, features.map(toRow));
await this.regions.updateRegion(region.id, {
status: 'ready',
@@ -182,14 +290,26 @@ export class PaddleRegionsService {
source_timestamp: timestamp === null ? null : new Date(timestamp * 1000).toISOString(),
imported_at: dbNow(),
error: null,
// Without a boundary the region covers what its objects span, so the map can still tell it is covered.
...(known.boundary ? {} : extentOf(features)),
});
return true;
});
logInfo(`[Paddle] ${region.id}: ${features.length} objects read in ${Math.round((Date.now() - started) / 1000)} s`);
if (!kept) throw new Error(REMOVED_WHILE_READ);
logInfo(
`[Paddle] ${region.id}: ${features.length} objects read in ${Math.round((Date.now() - started) / 1000)} s`,
);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logError(`[Paddle] ${region.id}: ${message}`);
await this.regions.updateRegion(region.id, { status: 'failed', error: message.slice(0, 500) });
if (abort.signal.aborted) {
logInfo(`[Paddle] ${region.id}: ${String(abort.signal.reason)}`);
} else if (messageOf(err) === REMOVED_WHILE_READ) {
logInfo(`[Paddle] ${region.id}: ${REMOVED_WHILE_READ}`);
} else {
logError(`[Paddle] ${region.id}: ${messageOf(err)}`);
await this.regions.updateRegion(region.id, { status: 'failed', error: messageOf(err).slice(0, 500) });
}
} finally {
if (this.current === current) this.current = null;
await unlink(file).catch(() => undefined);
}
}
+1 -1
View File
@@ -2,6 +2,7 @@ import { Places } from '../../db/entities/Places.entity';
import { TourTypes } from '../../db/entities/TourTypes.entity';
import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
import { Tours } from '../../db/entities/Tours.entity';
import { TOUR_TRACK_MARKS } from '../../db/json-columns';
import type { PlacesRepository } from '../../db/repositories/Places.repository';
import type { TourTypesRepository } from '../../db/repositories/TourTypes.repository';
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
@@ -12,7 +13,6 @@ import type {
ToursRepository,
TourUpdate,
} from '../../db/repositories/Tours.repository';
import { TOUR_TRACK_MARKS } from '../../db/json-columns';
import { decodeJson } from '../../utils/json-column';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
@@ -1,9 +1,9 @@
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { WindQueryDto } from './dto/wind-query.dto';
import { ApiError } from './weather.impl';
import { WeatherService } from './weather.service';
import { WindQueryDto } from './dto/wind-query.dto';
import { WindService } from './wind.service';
import { ResponseContract } from '../common/response-contract';
import { Controller, Get, HttpException, Query, UseGuards } from '@nestjs/common';
import { windForecastResponseSchema, type WeatherResult, type WindForecastResponse } from '@trek/shared';
+2 -1
View File
@@ -3,6 +3,7 @@ import { logWarn } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { Injectable } from '@nestjs/common';
import { WIND_FORECAST_DAYS, type WindForecastResponse, type WindForecastStatus, type WindQuery } from '@trek/shared';
import { z } from 'zod';
/** Open-Meteo on the request path: a deadline and a size cap, as the weather calls have. */
@@ -56,7 +57,7 @@ export class WindService {
const hit = this.cache.get(key);
if (hit && hit.expiresAt > now) return hit.value;
const running = this.pending.get(key);
if (running) return running;
if (running !== undefined) return running;
const request = this.fetchDay(query, now)
.then((value) => {
this.remember(key, value, now);