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);