feat(tours): paddle portages and locks, paddle time, wind at the start and obstacle data from OpenStreetMap

PAD-03 portages and locks on planned tours and recorded tracks, PAD-07 paddle time with portage and lock stops, PAD-08 wind forecast for the start, PAD-05A regional obstacle import from Geofabrik extracts with admin endpoints and a monthly refresh, PAD-05B first cut of the obstacle layer on Leaflet, GL and 3D. Work in progress: checklist (PAD-06), check bench (PAD-09), admin UI, translations and tests follow.
This commit is contained in:
Maurice
2026-10-16 23:44:51 +02:00
parent d705bd9dd0
commit 2c3b20bb57
117 changed files with 7043 additions and 199 deletions
@@ -0,0 +1,54 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PaddleFeaturesRepository } from '../repositories/PaddleFeatures.repository';
import { PaddleRegions } from './PaddleRegions.entity';
export class PaddleFeatures {
[EntityRepositoryType]?: PaddleFeaturesRepository;
id!: number & Opt;
region!: Ref<PaddleRegions>;
region_id!: string;
osm_ref!: string;
kind!: string;
group_key?: string | null;
name?: string | null;
geometry!: string;
tags!: string;
tag_hash!: string;
min_lat!: number;
min_lng!: number;
max_lat!: number;
max_lng!: number;
}
export const PaddleFeaturesSchema = defineEntity({
class: PaddleFeatures,
repository: () => PaddleFeaturesRepository,
indexes: [
{
name: 'idx_paddle_features_box',
properties: ['min_lat', 'max_lat', 'min_lng', 'max_lng'],
},
],
uniques: [
{
name: 'idx_paddle_features_region_ref',
properties: ['region_id', 'osm_ref'],
},
],
properties: {
id: p.integer().primary(),
region: () => p.manyToOne(PaddleRegions).ref().deleteRule('cascade').hidden(),
region_id: p.text().persist(false),
osm_ref: p.text(),
kind: p.text(),
group_key: p.text().nullable(),
name: p.text().nullable(),
geometry: p.text(),
tags: p.text(),
tag_hash: p.text(),
min_lat: p.double(),
min_lng: p.double(),
max_lat: p.double(),
max_lng: p.double(),
},
});
@@ -0,0 +1,52 @@
import { Collection, EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core';
import { PaddleRegionsRepository } from '../repositories/PaddleRegions.repository';
import { DbTimestampType } from '../types';
import { PaddleFeatures } from './PaddleFeatures.entity';
export class PaddleRegions {
[EntityRepositoryType]?: PaddleRegionsRepository;
id!: string;
name!: string;
boundary?: string | null;
min_lat?: number | null;
min_lng?: number | null;
max_lat?: number | null;
max_lng?: number | null;
status: TPaddleRegionsStatus & Opt = PaddleRegionsStatus.QUEUED;
source_timestamp?: string | null;
imported_at?: string | null;
feature_count: number & Opt = 0;
error?: string | null;
created_at?: string | null;
paddle_features_collection = new Collection<PaddleFeatures>(this);
}
export const PaddleRegionsStatus = {
QUEUED: 'queued',
IMPORTING: 'importing',
READY: 'ready',
FAILED: 'failed',
} as const;
export type TPaddleRegionsStatus = (typeof PaddleRegionsStatus)[keyof typeof PaddleRegionsStatus];
export const PaddleRegionsSchema = defineEntity({
class: PaddleRegions,
repository: () => PaddleRegionsRepository,
properties: {
id: p.text().primary(),
name: p.text(),
boundary: p.text().nullable(),
min_lat: p.double().nullable(),
min_lng: p.double().nullable(),
max_lat: p.double().nullable(),
max_lng: p.double().nullable(),
status: p.enum(() => PaddleRegionsStatus).default('queued'),
source_timestamp: p.text().nullable(),
imported_at: p.type(DbTimestampType).nullable(),
feature_count: p.integer().default(0),
error: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
paddle_features_collection: () => p.oneToMany(PaddleFeatures).mappedBy('region').hidden(),
},
});
@@ -0,0 +1,46 @@
import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TourObstacleReviewsRepository } from '../repositories/TourObstacleReviews.repository';
import { DbTimestampType } from '../types';
import { Tours } from './Tours.entity';
export class TourObstacleReviews {
[EntityRepositoryType]?: TourObstacleReviewsRepository;
[PrimaryKeyProp]?: ['place', 'obstacle_key'];
place!: Ref<Tours>;
place_id!: number;
obstacle_key!: string;
decision!: TTourObstacleReviewsDecision;
note?: string | null;
route_fingerprint!: string;
source_fingerprint!: string;
obstacle_snapshot!: string;
decided_at!: string;
decided_by?: number | null;
}
export const TourObstacleReviewsDecision = {
PASS: 'pass',
PORTAGE: 'portage',
REROUTE: 'reroute',
NOT_AFFECTED: 'not_affected',
} as const;
export type TTourObstacleReviewsDecision = (typeof TourObstacleReviewsDecision)[keyof typeof TourObstacleReviewsDecision];
export const TourObstacleReviewsSchema = defineEntity({
class: TourObstacleReviews,
repository: () => TourObstacleReviewsRepository,
uniques: [{ properties: ['place', 'obstacle_key'] }],
properties: {
place: () => p.manyToOne(Tours).primary().ref().name('place_id').deleteRule('cascade').hidden(),
place_id: p.integer().persist(false),
obstacle_key: p.text().primary(),
decision: p.enum(() => TourObstacleReviewsDecision),
note: p.text().nullable(),
route_fingerprint: p.text(),
source_fingerprint: p.text(),
obstacle_snapshot: p.text(),
decided_at: p.type(DbTimestampType),
decided_by: p.integer().nullable(),
},
});
@@ -12,6 +12,7 @@ export class TourWaypoints {
role!: string;
sequence!: number;
fixed_leg?: string | null;
lock?: string | null;
}
export const TourWaypointsSchema = defineEntity({
@@ -27,5 +28,6 @@ export const TourWaypointsSchema = defineEntity({
role: p.text(),
sequence: p.integer(),
fixed_leg: p.text().nullable(),
lock: p.text().nullable(),
},
});
+7
View File
@@ -1,6 +1,7 @@
import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { ToursRepository } from '../repositories/Tours.repository';
import { Places } from './Places.entity';
import { TourObstacleReviews } from './TourObstacleReviews.entity';
import { TourSources } from './TourSources.entity';
import { TourTypes } from './TourTypes.entity';
import { TourWaypoints } from './TourWaypoints.entity';
@@ -30,7 +31,10 @@ export class Tours {
boat_type?: TToursBoatType | null;
water_context?: TToursWaterContext | null;
paddle_speed_kmh?: number | null;
portage_speed_kmh?: number | null;
track_marks?: string | null;
tourTypeRef!: Ref<TourTypes>;
tour_obstacle_reviews_collection = new Collection<TourObstacleReviews>(this);
tour_sources: Ref<TourSources> | null = null;
tour_waypoints_collection = new Collection<TourWaypoints>(this);
}
@@ -92,7 +96,10 @@ export const ToursSchema = defineEntity({
boat_type: p.enum(() => ToursBoatType).nullable(),
water_context: p.enum(() => ToursWaterContext).nullable(),
paddle_speed_kmh: p.double().nullable(),
portage_speed_kmh: p.double().nullable(),
track_marks: p.text().nullable(),
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
tour_obstacle_reviews_collection: () => p.oneToMany(TourObstacleReviews).mappedBy('place').hidden(),
tour_sources: () => p.oneToOne(TourSources).ref().mappedBy('place').hidden(),
tour_waypoints_collection: () => p.oneToMany(TourWaypoints).mappedBy('place').hidden(),
},
+6
View File
@@ -61,6 +61,8 @@ import { PackingItemsSchema } from './PackingItems.entity';
import { PackingTemplateCategoriesSchema } from './PackingTemplateCategories.entity';
import { PackingTemplateItemsSchema } from './PackingTemplateItems.entity';
import { PackingTemplatesSchema } from './PackingTemplates.entity';
import { PaddleFeaturesSchema } from './PaddleFeatures.entity';
import { PaddleRegionsSchema } from './PaddleRegions.entity';
import { PasswordResetTokensSchema } from './PasswordResetTokens.entity';
import { PhotoProviderFieldsSchema } from './PhotoProviderFields.entity';
import { PhotoProvidersSchema } from './PhotoProviders.entity';
@@ -103,6 +105,7 @@ import { ShareTokensSchema } from './ShareTokens.entity';
import { TagsSchema } from './Tags.entity';
import { TodoCategoryAssigneesSchema } from './TodoCategoryAssignees.entity';
import { TodoItemsSchema } from './TodoItems.entity';
import { TourObstacleReviewsSchema } from './TourObstacleReviews.entity';
import { TourSourcesSchema } from './TourSources.entity';
import { TourTypesSchema } from './TourTypes.entity';
import { TourWaypointsSchema } from './TourWaypoints.entity';
@@ -198,6 +201,8 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
PackingTemplateCategoriesSchema,
PackingTemplateItemsSchema,
PackingTemplatesSchema,
PaddleFeaturesSchema,
PaddleRegionsSchema,
PasswordResetTokensSchema,
PhotoProviderFieldsSchema,
PhotoProvidersSchema,
@@ -240,6 +245,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TagsSchema,
TodoCategoryAssigneesSchema,
TodoItemsSchema,
TourObstacleReviewsSchema,
TourSourcesSchema,
TourTypesSchema,
TourWaypointsSchema,
+32 -1
View File
@@ -1,5 +1,15 @@
import type { JsonColumn } from '../utils/json-column';
import { FERRATAS_RESULT_CAP, ferrataSchema, tourFixedLegSchema, type Ferrata, type TourFixedLeg } from '@trek/shared';
import {
FERRATAS_RESULT_CAP,
ferrataSchema,
paddleLockSchema,
tourFixedLegSchema,
trackMarksSchema,
type Ferrata,
type PaddleLock,
type TourFixedLeg,
type TrackMarks,
} from '@trek/shared';
import { z } from 'zod';
@@ -135,3 +145,24 @@ export const TOUR_WAYPOINT_FIXED_LEG: JsonColumn<TourFixedLeg | null> = {
schema: tourFixedLegSchema.nullable(),
fallback: () => null,
};
/**
* PAD-07: a lock at a control point of a paddle tour, with the times the
* paddler expects there. A row that does not decode reads as no lock, so the
* estimate names nothing it cannot read.
*/
export const TOUR_WAYPOINT_LOCK: JsonColumn<PaddleLock | null> = {
column: 'tour_waypoints.lock',
schema: paddleLockSchema.nullable(),
fallback: () => null,
};
/**
* PAD-03: portages and locks laid onto a recorded track. A row that does not
* decode reads as no marks; the track itself is untouched either way.
*/
export const TOUR_TRACK_MARKS: JsonColumn<TrackMarks | null> = {
column: 'tours.track_marks',
schema: trackMarksSchema.nullable(),
fallback: () => null,
};
@@ -0,0 +1,19 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface PaddleFeaturesTable {
id: InsertOptional<number>;
region_id: string;
osm_ref: string;
kind: string;
group_key: InsertOptional<string | null>;
name: InsertOptional<string | null>;
geometry: string;
tags: string;
tag_hash: string;
min_lat: number;
min_lng: number;
max_lat: number;
max_lng: number;
}
@@ -0,0 +1,19 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface PaddleRegionsTable {
id: string;
name: string;
boundary: InsertOptional<string | null>;
min_lat: InsertOptional<number | null>;
min_lng: InsertOptional<number | null>;
max_lat: InsertOptional<number | null>;
max_lng: InsertOptional<number | null>;
status: InsertOptional<string>;
source_timestamp: InsertOptional<string | null>;
imported_at: InsertOptional<string | null>;
feature_count: InsertOptional<number>;
error: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
}
@@ -0,0 +1,15 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface TourObstacleReviewsTable {
place_id: number;
obstacle_key: string;
decision: string;
note: InsertOptional<string | null>;
route_fingerprint: string;
source_fingerprint: string;
obstacle_snapshot: string;
decided_at: string;
decided_by: InsertOptional<number | null>;
}
@@ -10,4 +10,5 @@ export interface TourWaypointsTable {
role: string;
sequence: number;
fixed_leg: InsertOptional<string | null>;
lock: InsertOptional<string | null>;
}
+2
View File
@@ -23,4 +23,6 @@ export interface ToursTable {
boat_type: InsertOptional<string | null>;
water_context: InsertOptional<string | null>;
paddle_speed_kmh: InsertOptional<number | null>;
portage_speed_kmh: InsertOptional<number | null>;
track_marks: InsertOptional<string | null>;
}
+6
View File
@@ -66,6 +66,8 @@ import type { PackingItemsTable } from './PackingItems.table';
import type { PackingTemplateCategoriesTable } from './PackingTemplateCategories.table';
import type { PackingTemplateItemsTable } from './PackingTemplateItems.table';
import type { PackingTemplatesTable } from './PackingTemplates.table';
import type { PaddleFeaturesTable } from './PaddleFeatures.table';
import type { PaddleRegionsTable } from './PaddleRegions.table';
import type { PasswordResetTokensTable } from './PasswordResetTokens.table';
import type { PhotoProviderFieldsTable } from './PhotoProviderFields.table';
import type { PhotoProvidersTable } from './PhotoProviders.table';
@@ -109,6 +111,7 @@ import type { ShareTokensTable } from './ShareTokens.table';
import type { TagsTable } from './Tags.table';
import type { TodoCategoryAssigneesTable } from './TodoCategoryAssignees.table';
import type { TodoItemsTable } from './TodoItems.table';
import type { TourObstacleReviewsTable } from './TourObstacleReviews.table';
import type { TourSourcesTable } from './TourSources.table';
import type { TourTypesTable } from './TourTypes.table';
import type { TourWaypointsTable } from './TourWaypoints.table';
@@ -209,6 +212,8 @@ export interface DB {
packing_template_categories: PackingTemplateCategoriesTable;
packing_template_items: PackingTemplateItemsTable;
packing_templates: PackingTemplatesTable;
paddle_features: PaddleFeaturesTable;
paddle_regions: PaddleRegionsTable;
password_reset_tokens: PasswordResetTokensTable;
photo_provider_fields: PhotoProviderFieldsTable;
photo_providers: PhotoProvidersTable;
@@ -252,6 +257,7 @@ export interface DB {
tags: TagsTable;
todo_category_assignees: TodoCategoryAssigneesTable;
todo_items: TodoItemsTable;
tour_obstacle_reviews: TourObstacleReviewsTable;
tour_sources: TourSourcesTable;
tour_types: TourTypesTable;
tour_waypoints: TourWaypointsTable;
@@ -0,0 +1,23 @@
import { Migration } from '@mikro-orm/migrations';
/**
* PAD-03 and PAD-07: a paddle tour's portages, locks and carrying speed.
*
* A planned tour marks a portage on the leg itself (`fixed_leg` kind
* `portage`, no column needed) and a lock on the control point it sits at:
* `tour_waypoints.lock` is the JSON of the times the paddler expects there.
* A recorded track has no control points to mark, and is never redrawn, so
* `tours.track_marks` holds its portages and locks as distances along it.
* `tours.portage_speed_kmh` is the carrying speed the paddler chose; NULL
* means the starting value applies. Every existing row reads NULL: nothing
* carried, no lock, nothing changes its meaning.
*/
export class Migration20200101044000_a_paddle_tour_plans_its_portages_and_locks extends Migration {
override name = 'Migration20200101044000_a_paddle_tour_plans_its_portages_and_locks';
override up(): void {
this.addSql('ALTER TABLE tour_waypoints ADD COLUMN lock TEXT');
this.addSql('ALTER TABLE tours ADD COLUMN portage_speed_kmh REAL');
this.addSql('ALTER TABLE tours ADD COLUMN track_marks TEXT');
}
}
@@ -0,0 +1,63 @@
import { Migration } from '@mikro-orm/migrations';
/**
* PAD-05A: the paddle obstacles TREK reads out of regional OpenStreetMap
* extracts (Geofabrik), held per region.
*
* `paddle_regions` is one extract an admin chose: its Geofabrik id, its name
* and boundary (the area the data covers, so a tour outside every region is
* told so rather than shown as free of obstacles), the state of the last read
* and the date of the data in it.
*
* `paddle_features` is one OSM object the read kept: its OSM reference
* (`node/…`, `way/…`) within its region, what kind of obstacle or access it
* is, the objects of one lock grouped under a shared key, its own geometry as
* JSON (a weir across a river stays a line), the tags it was judged by and a
* hash of them, so a later read can tell a changed object from an unchanged
* one. The bounding box columns let a map view ask for its area without
* reading the JSON. A region's rows go with it.
*/
export class Migration20200101044100_paddle_obstacles_from_openstreetmap extends Migration {
override name = 'Migration20200101044100_paddle_obstacles_from_openstreetmap';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS paddle_regions (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
boundary TEXT,
min_lat REAL,
min_lng REAL,
max_lat REAL,
max_lng REAL,
status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'importing', 'ready', 'failed')),
source_timestamp TEXT,
imported_at DATETIME,
feature_count INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql(`
CREATE TABLE IF NOT EXISTS paddle_features (
id INTEGER PRIMARY KEY,
region_id TEXT NOT NULL REFERENCES paddle_regions(id) ON DELETE CASCADE,
osm_ref TEXT NOT NULL,
kind TEXT NOT NULL,
group_key TEXT,
name TEXT,
geometry TEXT NOT NULL,
tags TEXT NOT NULL,
tag_hash TEXT NOT NULL,
min_lat REAL NOT NULL,
min_lng REAL NOT NULL,
max_lat REAL NOT NULL,
max_lng REAL NOT NULL
)
`);
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)');
}
}
@@ -0,0 +1,36 @@
import { Migration } from '@mikro-orm/migrations';
/**
* PAD-06: what the paddler decided about an obstacle on a tour, and against
* what. `obstacle_key` names the obstacle (its OSM reference, or the shared
* key of a lock's objects); `decision` is pass, portage, reroute or
* not_affected. A decision holds only for the line and the obstacle it was
* made on: `route_fingerprint` is the tour's line near the obstacle and
* `source_fingerprint` the obstacle's data, both as they were then. When
* either differs now the decision is shown again as one to review, never
* silently carried over or dropped. `obstacle_snapshot` keeps the obstacle's
* name and kind at the time, so a decision about an object the data no
* longer holds still says what it was about. `decided_by` names who decided,
* kept as a plain id: a decision outlives its author, who then reads as
* unknown. It goes with its tour.
*/
export class Migration20200101044200_a_paddle_tour_records_its_obstacle_decisions extends Migration {
override name = 'Migration20200101044200_a_paddle_tour_records_its_obstacle_decisions';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS tour_obstacle_reviews (
place_id INTEGER NOT NULL REFERENCES tours(place_id) ON DELETE CASCADE,
obstacle_key TEXT NOT NULL,
decision TEXT NOT NULL CHECK (decision IN ('pass', 'portage', 'reroute', 'not_affected')),
note TEXT,
route_fingerprint TEXT NOT NULL,
source_fingerprint TEXT NOT NULL,
obstacle_snapshot TEXT NOT NULL,
decided_at DATETIME NOT NULL,
decided_by INTEGER,
PRIMARY KEY (place_id, obstacle_key)
)
`);
}
}
@@ -0,0 +1,80 @@
import type { PaddleFeatures } from '../entities/PaddleFeatures.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** One stored paddle object, its geometry and tags still JSON text. */
export interface PaddleFeatureRow {
region_id: string;
osm_ref: string;
kind: string;
group_key: string | null;
name: string | null;
geometry: string;
tags: string;
tag_hash: string;
min_lat: number;
min_lng: number;
max_lat: number;
max_lng: number;
}
/** A box in degrees, south to north and west to east. */
export interface Box {
south: number;
west: number;
north: number;
east: number;
}
/** Rows written per statement, kept well under SQLite's bound-parameter limit. */
const INSERT_CHUNK = 200;
/**
* `paddle_features`: the paddle objects TREK read out of a region's extract
* (PAD-05A). A region's rows are only ever replaced whole, inside the
* transaction the import holds, so a reader never sees half a region.
*/
export class PaddleFeaturesRepository extends TrekRepository<PaddleFeatures> {
private db() {
return this.kysely<Pick<DB, 'paddle_features'>>();
}
/** The objects whose box reaches into `box`, at most `limit` of them, in a stable order. */
async findInBox(box: Box, limit: number): Promise<PaddleFeatureRow[]> {
return await this.db()
.selectFrom('paddle_features')
.select([
'region_id',
'osm_ref',
'kind',
'group_key',
'name',
'geometry',
'tags',
'tag_hash',
'min_lat',
'min_lng',
'max_lat',
'max_lng',
])
.where('min_lat', '<=', box.north)
.where('max_lat', '>=', box.south)
.where('min_lng', '<=', box.east)
.where('max_lng', '>=', box.west)
.orderBy('id', 'asc')
.limit(limit)
.execute();
}
/** 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();
}
}
}
@@ -0,0 +1,115 @@
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';
export type PaddleRegionStatus = 'queued' | 'importing' | 'ready' | 'failed';
/** One region an admin chose, as stored; the boundary is still GeoJSON text. */
export interface PaddleRegionRow {
id: string;
name: string;
boundary: string | null;
min_lat: number | null;
min_lng: number | null;
max_lat: number | null;
max_lng: number | null;
status: PaddleRegionStatus;
source_timestamp: string | null;
imported_at: string | null;
feature_count: number;
error: string | null;
}
/** `status` narrowed to the four values the column's CHECK constraint allows. */
type RegionsDB = {
paddle_regions: Omit<DB['paddle_regions'], 'status'> & { status: PaddleRegionStatus };
};
const COLUMNS = [
'id',
'name',
'boundary',
'min_lat',
'min_lng',
'max_lat',
'max_lng',
'status',
'source_timestamp',
'imported_at',
'feature_count',
'error',
] as const;
/** `paddle_regions`: the regional extracts an admin chose for paddle data (PAD-05A). */
export class PaddleRegionsRepository extends TrekRepository<PaddleRegions> {
private db() {
return this.kysely<RegionsDB>();
}
async list(): Promise<PaddleRegionRow[]> {
return await this.db().selectFrom('paddle_regions').select(COLUMNS).orderBy('name', 'asc').execute();
}
async findById(id: string): Promise<PaddleRegionRow | undefined> {
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[]> {
return await this.db()
.selectFrom('paddle_regions')
.select(COLUMNS)
.where('status', '=', 'ready')
.where('min_lat', '<=', box.north)
.where('max_lat', '>=', box.south)
.where('min_lng', '<=', box.east)
.where('max_lng', '>=', box.west)
.execute();
}
/** The first region waiting for its read, oldest first. */
async nextQueued(): Promise<PaddleRegionRow | undefined> {
return await this.db()
.selectFrom('paddle_regions')
.select(COLUMNS)
.where('status', '=', 'queued')
.orderBy('created_at', 'asc')
.executeTakeFirst();
}
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 })
.onConflict((oc) => oc.column('id').doNothing())
.execute();
}
async updateRegion(
id: string,
patch: Partial<Pick<PaddleRegionRow, 'status' | 'source_timestamp' | 'imported_at' | 'feature_count' | 'error'>>,
): 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. */
async queueReady(): Promise<number> {
const result = await this.db()
.updateTable('paddle_regions')
.set({ status: 'queued' })
.where('status', 'in', ['ready', 'failed'])
.executeTakeFirst();
return Number(result.numUpdatedRows ?? 0);
}
/** A region left half read by a restart goes back to the queue. */
async requeueInterrupted(): Promise<void> {
await this.db().updateTable('paddle_regions').set({ status: 'queued' }).where('status', '=', 'importing').execute();
}
async deleteRegion(id: string): Promise<boolean> {
const result = await this.db().deleteFrom('paddle_regions').where('id', '=', id).executeTakeFirst();
return Number(result.numDeletedRows ?? 0) > 0;
}
}
@@ -0,0 +1,4 @@
import type { TourObstacleReviews } from '../entities/TourObstacleReviews.entity';
import { TrekRepository } from './_shared/trek-repository';
export class TourObstacleReviewsRepository extends TrekRepository<TourObstacleReviews> {}
@@ -1,9 +1,9 @@
import { decodeJson, encodeJson } from '../../utils/json-column';
import type { TourWaypoints } from '../entities/TourWaypoints.entity';
import { TOUR_WAYPOINT_FIXED_LEG } from '../json-columns';
import { TOUR_WAYPOINT_FIXED_LEG, TOUR_WAYPOINT_LOCK } from '../json-columns';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
import type { TourFixedLeg } from '@trek/shared';
import type { PaddleLock, TourFixedLeg } from '@trek/shared';
/** One saved routing control point of a tour, in route order. */
export interface TourWaypointRow {
@@ -13,6 +13,8 @@ export interface TourWaypointRow {
sequence: number;
/** The leg to the next waypoint as a fixed line; absent for a routed leg. */
fixed_leg?: TourFixedLeg | null;
/** A lock at this point of a paddle tour; absent where there is none. */
lock?: PaddleLock | null;
}
/** The row as stored, the fixed leg still JSON text. */
@@ -22,12 +24,14 @@ interface StoredWaypoint {
role: TourWaypointRow['role'];
sequence: number;
fixed_leg: string | null;
lock: string | null;
}
/** A stored row as callers read it: the fixed leg decoded, and left out entirely for a routed leg. */
function readWaypoint({ fixed_leg, ...point }: StoredWaypoint): TourWaypointRow {
/** A stored row as callers read it: the fixed leg and the lock decoded, each left out entirely where there is none. */
function readWaypoint({ fixed_leg, lock, ...point }: StoredWaypoint): TourWaypointRow {
const leg = decodeJson(TOUR_WAYPOINT_FIXED_LEG, fixed_leg, 'tour waypoint');
return leg ? { ...point, fixed_leg: leg } : point;
const stop = decodeJson(TOUR_WAYPOINT_LOCK, lock, 'tour waypoint');
return { ...point, ...(leg ? { fixed_leg: leg } : {}), ...(stop ? { lock: stop } : {}) };
}
/** {@link TourWaypointRow} plus the tour it belongs to, as the trip copy reads it. */
@@ -50,11 +54,11 @@ export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
return this.kysely<TourWaypointsKyselyDB>();
}
/** TW1 — `SELECT lat, lng, role, sequence, fixed_leg FROM tour_waypoints WHERE place_id = ? ORDER BY sequence`. */
/** TW1 — `SELECT lat, lng, role, sequence, fixed_leg, lock FROM tour_waypoints WHERE place_id = ? ORDER BY sequence`. */
async listForPlace(place_id: number): Promise<TourWaypointRow[]> {
const rows = await this.db()
.selectFrom('tour_waypoints')
.select(['lat', 'lng', 'role', 'sequence', 'fixed_leg'])
.select(['lat', 'lng', 'role', 'sequence', 'fixed_leg', 'lock'])
.where('place_id', '=', place_id)
.orderBy('sequence', 'asc')
.execute();
@@ -66,7 +70,7 @@ export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
const rows = await this.db()
.selectFrom('tour_waypoints as tw')
.innerJoin('places as p', 'p.id', 'tw.place_id')
.select(['tw.place_id', 'tw.lat', 'tw.lng', 'tw.role', 'tw.sequence', 'tw.fixed_leg'])
.select(['tw.place_id', 'tw.lat', 'tw.lng', 'tw.role', 'tw.sequence', 'tw.fixed_leg', 'tw.lock'])
.where('p.trip_id', '=', trip_id)
.orderBy('tw.place_id', 'asc')
.orderBy('tw.sequence', 'asc')
@@ -75,7 +79,7 @@ export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
}
/**
* TW3 — `INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence, fixed_leg)
* TW3 — `INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence, fixed_leg, lock)
* VALUES (...)` for each point. The caller owns the transaction: a create
* writes the tour first, an edit clears the old points first.
*/
@@ -89,6 +93,7 @@ export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
role: w.role,
sequence: w.sequence,
fixed_leg: w.fixed_leg ? encodeJson(TOUR_WAYPOINT_FIXED_LEG, w.fixed_leg) : null,
lock: w.lock ? encodeJson(TOUR_WAYPOINT_LOCK, w.lock) : null,
})),
);
}
@@ -31,6 +31,9 @@ export interface TourListRow {
boat_type: string | null;
water_context: string | null;
paddle_speed_kmh: number | null;
portage_speed_kmh: number | null;
/** The marks laid onto a recorded track, still JSON text. */
track_marks: string | null;
has_recorded_track: number;
planned: number;
has_waypoints: number;
@@ -58,6 +61,8 @@ export interface TourRow {
boat_type: string | null;
water_context: string | null;
paddle_speed_kmh: number | null;
portage_speed_kmh: number | null;
track_marks: string | null;
}
const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
@@ -77,6 +82,7 @@ export interface TourInsert {
boat_type?: PaddleBoatType | null;
water_context?: PaddleWaterContext | null;
paddle_speed_kmh?: number | null;
portage_speed_kmh?: number | null;
}
/** What a route edit replaces on an existing tour: the type and everything that belongs to it. */
@@ -88,14 +94,24 @@ export type TourUpdate = Omit<
| 'boat_type'
| 'water_context'
| 'paddle_speed_kmh'
| 'portage_speed_kmh'
> & {
planned_duration_minutes?: number | null;
break_additional_minutes?: number | null;
boat_type: PaddleBoatType | null;
water_context: PaddleWaterContext | null;
paddle_speed_kmh: number | null;
portage_speed_kmh: number | null;
};
/** A recorded track's paddle plan (PAD-03, PAD-07): its speeds, its marks and the time they make. */
export interface TourPaddlePlanUpdate {
paddle_speed_kmh: number | null;
portage_speed_kmh: number | null;
track_marks: string | null;
duration: number | null;
}
type ToursKyselyDB = Pick<DB, 'tours' | 'places' | 'day_assignments' | 'tour_waypoints' | 'tour_sources' | 'days'>;
/** One day a tour of the trip sits on, in the order of the trip. */
@@ -173,6 +189,8 @@ export class ToursRepository extends TrekRepository<Tours> {
't.boat_type as boat_type',
't.water_context as water_context',
't.paddle_speed_kmh as paddle_speed_kmh',
't.portage_speed_kmh as portage_speed_kmh',
't.track_marks as track_marks',
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
eb
.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id'))
@@ -359,6 +377,7 @@ export class ToursRepository extends TrekRepository<Tours> {
derived_from_place_id?: number | null;
origin?: TToursOrigin;
origin_file_name?: string | null;
track_marks?: string | null;
},
): Promise<void> {
await this.insert({
@@ -380,6 +399,8 @@ export class ToursRepository extends TrekRepository<Tours> {
boat_type: input.boat_type ?? null,
water_context: input.water_context ?? null,
paddle_speed_kmh: input.paddle_speed_kmh ?? null,
portage_speed_kmh: input.portage_speed_kmh ?? null,
track_marks: input.track_marks ?? null,
});
}
@@ -430,6 +451,27 @@ export class ToursRepository extends TrekRepository<Tours> {
boat_type: input.boat_type,
water_context: input.water_context,
paddle_speed_kmh: input.paddle_speed_kmh,
portage_speed_kmh: input.portage_speed_kmh,
})
.where('place_id', '=', place_id)
.where('place_id', 'in', (eb) => eb.selectFrom('places').select('id').where('trip_id', '=', trip_id))
.executeTakeFirst();
return Number(result.numUpdatedRows ?? 0) > 0;
}
/**
* The paddle plan of a recorded track of the trip: its speeds, the marks
* laid onto it and the moving time they make. The track itself is not
* touched. Returns whether a row of that trip was updated.
*/
async updatePaddlePlanInTrip(trip_id: number, place_id: number, input: TourPaddlePlanUpdate): Promise<boolean> {
const result = await this.db()
.updateTable('tours')
.set({
paddle_speed_kmh: input.paddle_speed_kmh,
portage_speed_kmh: input.portage_speed_kmh,
track_marks: input.track_marks,
duration: input.duration,
})
.where('place_id', '=', place_id)
.where('place_id', 'in', (eb) => eb.selectFrom('places').select('id').where('trip_id', '=', trip_id))
+2
View File
@@ -43,6 +43,7 @@ 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';
@@ -155,6 +156,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
ToursModule,
WandererModule,
FerratasModule,
PaddleObstaclesModule,
TripsModule,
CollabModule,
FilesModule,
@@ -0,0 +1,101 @@
import { readCappedJson } from '../../utils/cappedFetch';
import { regionBoundarySchema, type RegionBoundary } from './paddle-geo';
import { Injectable } from '@nestjs/common';
import { z } from 'zod';
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';
/**
* 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.
*/
export const GEOFABRIK_HOST = 'https://download.geofabrik.de/';
const INDEX_URL = `${GEOFABRIK_HOST}index-v1.json`;
const INDEX_TIMEOUT_MS = 20_000;
/** The list is a few megabytes; far more means it is not the list. */
const MAX_INDEX_BYTES = 32 * 1024 * 1024;
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 indexSchema = z.object({
features: z.array(
z.object({
properties: z.object({
id: z.string(),
parent: z.string().optional(),
name: z.string(),
urls: z.object({ pbf: z.string().optional() }).passthrough(),
}),
geometry: z.unknown(),
}),
),
});
export interface GeofabrikRegion {
id: string;
name: string;
parent: string | null;
pbfUrl: string;
boundary: RegionBoundary | null;
}
@Injectable()
export class GeofabrikClient {
private index: { regions: Map<string, GeofabrikRegion>; fetchedAt: number } | null = null;
/** 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) });
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 regions = new Map<string, GeofabrikRegion>();
for (const feature of parsed.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 });
}
this.index = { regions, fetchedAt: now };
return regions;
}
/**
* 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.
*/
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) });
if (!response.ok || !response.body) {
await response.body?.cancel().catch(() => undefined);
throw new Error(`Geofabrik download ${response.status}`);
}
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);
},
});
try {
await pipeline(Readable.fromWeb(response.body as unknown as WebReadableStream), counter, createWriteStream(target));
} catch (err) {
await unlink(target).catch(() => undefined);
throw err;
}
}
}
@@ -0,0 +1,317 @@
import { open } from 'node:fs/promises';
import { inflateSync } from 'node:zlib';
/**
* A reader for OpenStreetMap's PBF format, as Geofabrik's regional extracts
* come: the file is a run of blobs, each a length-prefixed header and a
* (usually zlib-compressed) block. A block holds its own string table and
* groups of nodes (packed as "dense" nodes) and ways. Relations are not read:
* every object PAD-05A evaluates is a node or a way.
*
* Only what the paddle data needs is decoded, and nothing is kept between
* blocks, so a region of any size is read in the memory of one block (a few
* megabytes). The format: https://wiki.openstreetmap.org/wiki/PBF_Format
*/
/** 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;
export interface OsmNode {
id: number;
lat: number;
lon: number;
tags: Record<string, string>;
}
export interface OsmWay {
id: number;
refs: number[];
tags: Record<string, string>;
}
export interface OsmBlockVisitor {
/** Every node of the block, tagged or not; `tags` is empty for most. */
node?: (node: OsmNode) => void;
way?: (way: OsmWay) => void;
}
/** A protobuf field walker over one buffer, enough for the OSM schema. */
class Proto {
pos: number;
constructor(
private readonly buf: Buffer,
start = 0,
private readonly end = buf.length,
) {
this.pos = start;
}
get done(): boolean {
return this.pos >= this.end;
}
/** An unsigned varint as a number: exact up to 2^53, which every OSM id and offset stays under. */
varint(): number {
let result = 0;
let scale = 1;
for (;;) {
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;
}
}
/** A zigzag-encoded signed varint. */
svarint(): number {
const raw = this.varint();
return raw % 2 === 0 ? raw / 2 : -(raw + 1) / 2;
}
/** The next field's number and wire type, or null at the end. */
key(): { field: number; wire: number } | null {
if (this.done) return null;
const key = this.varint();
return { field: Math.floor(key / 8), wire: key % 8 };
}
/** The bounds of a length-delimited field, consumed. */
span(): [number, number] {
const length = this.varint();
const start = this.pos;
this.pos += length;
if (this.pos > this.end) throw new Error('Truncated field');
return [start, this.pos];
}
bytes(): Buffer {
const [start, stop] = this.span();
return this.buf.subarray(start, stop);
}
skip(wire: number): void {
if (wire === 0) this.varint();
else if (wire === 1) this.pos += 8;
else if (wire === 2) this.span();
else if (wire === 5) this.pos += 4;
else throw new Error(`Unsupported wire type ${wire}`);
}
/** A packed field of varints (or zigzag varints), decoded whole. */
packed(signed: boolean): number[] {
const [start, stop] = this.span();
const inner = new Proto(this.buf, start, stop);
const values: number[] = [];
while (!inner.done) values.push(signed ? inner.svarint() : inner.varint());
return values;
}
}
/** The fields of a blob header: its type ("OSMHeader" or "OSMData") and the size of the blob after it. */
function readBlobHeader(buf: Buffer): { type: string; size: number } {
const p = new Proto(buf);
let type = '';
let size = 0;
for (let key = p.key(); key; key = p.key()) {
if (key.field === 1 && key.wire === 2) type = p.bytes().toString('utf8');
else if (key.field === 3 && key.wire === 0) size = p.varint();
else p.skip(key.wire);
}
return { type, size };
}
/** A blob's contents, inflated: the format allows raw or zlib data, and TREK reads those two. */
function readBlob(buf: Buffer): Buffer {
const p = new Proto(buf);
let raw: Buffer | null = null;
let zlib: Buffer | null = null;
for (let key = p.key(); key; key = p.key()) {
if (key.field === 1 && key.wire === 2) raw = p.bytes();
else if (key.field === 3 && key.wire === 2) zlib = p.bytes();
else p.skip(key.wire);
}
if (raw) return raw;
if (zlib) return inflateSync(zlib, { maxOutputLength: MAX_BLOB_BYTES });
throw new Error('Unsupported blob compression');
}
/**
* The replication timestamp of an extract, from its header block: the moment
* the data is current to, in seconds. Null when the header carries none.
*/
export function readHeaderTimestamp(block: Buffer): number | null {
const p = new Proto(block);
for (let key = p.key(); key; key = p.key()) {
if (key.field === 32 && key.wire === 0) return p.varint();
p.skip(key.wire);
}
return null;
}
interface BlockContext {
strings: string[];
granularity: number;
latOffset: number;
lonOffset: number;
}
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];
if (value !== undefined) tags[strings[key] ?? ''] = strings[value] ?? '';
});
return tags;
}
function readDense(buf: Buffer, ctx: BlockContext, visit: (node: OsmNode) => void): void {
const p = new Proto(buf);
let ids: number[] = [];
let lats: number[] = [];
let lons: number[] = [];
let keysVals: number[] = [];
for (let key = p.key(); key; key = p.key()) {
if (key.field === 1) ids = p.packed(true);
else if (key.field === 8) lats = p.packed(true);
else if (key.field === 9) lons = p.packed(true);
else if (key.field === 10) keysVals = p.packed(false);
else p.skip(key.wire);
}
let id = 0;
let lat = 0;
let lon = 0;
let kv = 0;
ids.forEach((delta, index) => {
id += delta;
lat += lats[index] ?? 0;
lon += lons[index] ?? 0;
const tags: Record<string, string> = {};
// keys_vals runs key, value, key, value ... with a 0 closing each node.
while (kv < keysVals.length && keysVals[kv] !== 0) {
tags[ctx.strings[keysVals[kv] as number] ?? ''] = ctx.strings[keysVals[kv + 1] as number] ?? '';
kv += 2;
}
kv += 1;
visit({
id,
lat: (ctx.latOffset + ctx.granularity * lat) * 1e-9,
lon: (ctx.lonOffset + ctx.granularity * lon) * 1e-9,
tags,
});
});
}
function readNode(buf: Buffer, ctx: BlockContext): OsmNode {
const p = new Proto(buf);
let id = 0;
let lat = 0;
let lon = 0;
let keys: number[] = [];
let values: number[] = [];
for (let key = p.key(); key; key = p.key()) {
if (key.field === 1) id = p.svarint();
else if (key.field === 2) keys = p.packed(false);
else if (key.field === 3) values = p.packed(false);
else if (key.field === 8) lat = p.svarint();
else if (key.field === 9) lon = p.svarint();
else p.skip(key.wire);
}
return {
id,
lat: (ctx.latOffset + ctx.granularity * lat) * 1e-9,
lon: (ctx.lonOffset + ctx.granularity * lon) * 1e-9,
tags: tagsOf(keys, values, ctx.strings),
};
}
function readWay(buf: Buffer, strings: readonly string[]): OsmWay {
const p = new Proto(buf);
let id = 0;
let keys: number[] = [];
let values: number[] = [];
let deltas: number[] = [];
for (let key = p.key(); key; key = p.key()) {
if (key.field === 1) id = p.varint();
else if (key.field === 2) keys = p.packed(false);
else if (key.field === 3) values = p.packed(false);
else if (key.field === 8) deltas = p.packed(true);
else p.skip(key.wire);
}
let ref = 0;
const refs = deltas.map((delta) => (ref += delta));
return { id, refs, tags: tagsOf(keys, values, strings) };
}
/** One data block: its string table, then each group's nodes and ways handed to the visitor. */
export function readDataBlock(block: Buffer, visitor: OsmBlockVisitor): void {
const p = new Proto(block);
const strings: string[] = [];
const groups: Buffer[] = [];
const ctx: BlockContext = { strings, granularity: 100, latOffset: 0, lonOffset: 0 };
for (let key = p.key(); key; key = p.key()) {
if (key.field === 1 && key.wire === 2) {
const table = new Proto(p.bytes());
for (let entry = table.key(); entry; entry = table.key()) {
if (entry.field === 1 && entry.wire === 2) strings.push(table.bytes().toString('utf8'));
else table.skip(entry.wire);
}
} 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 p.skip(key.wire);
}
for (const group of groups) {
const g = new Proto(group);
for (let key = g.key(); key; key = g.key()) {
if (key.field === 1 && key.wire === 2 && visitor.node) visitor.node(readNode(g.bytes(), ctx));
else if (key.field === 2 && key.wire === 2 && visitor.node) readDense(g.bytes(), ctx, visitor.node);
else if (key.field === 3 && key.wire === 2 && visitor.way) visitor.way(readWay(g.bytes(), strings));
else g.skip(key.wire);
}
}
}
/**
* 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.
*/
export async function readPbfFile(
path: string,
visitor: OsmBlockVisitor,
onBlock?: (bytesRead: number) => Promise<void> | void,
): Promise<{ timestamp: number | null }> {
const file = await open(path, 'r');
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);
}
} finally {
await file.close();
}
return { timestamp };
}
@@ -0,0 +1,189 @@
import { readPbfFile, type OsmWay } from './osm-pbf.reader';
import { keptTags, paddleKindOf, paddleNameOf } from './paddle-tags';
import type { PaddleGeometry, PaddleObstacleKind } from '@trek/shared';
import { createHash } from 'node:crypto';
/**
* PAD-05A: the paddle objects of one regional extract, read in two passes.
* The first keeps every tagged node that is one, and the ways that are, with
* the ids of their nodes; the second looks those nodes' positions up. Only
* the nodes a kept way needs are held, so a region is read in bounded memory.
*/
/** A way longer than this keeps every n-th node so its line stays readable; its ends are always kept. */
const MAX_WAY_NODES = 2000;
/** Lock chambers and gates closer than this, in metres, belong to one lock. */
const LOCK_GROUP_M = 250;
export interface ExtractedFeature {
osm_ref: string;
kind: PaddleObstacleKind;
name: string | null;
geometry: PaddleGeometry;
tags: Record<string, string>;
tag_hash: string;
group_key: string | null;
min_lat: number;
min_lng: number;
max_lat: number;
max_lng: number;
}
interface PendingWay {
way: OsmWay;
kind: PaddleObstacleKind;
}
function hashOf(tags: Record<string, string>, geometry: PaddleGeometry): string {
const sorted = Object.keys(tags)
.sort()
.map((key) => [key, tags[key]]);
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);
}
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;
let maxLng = -180;
for (const [lng, lat] of points) {
minLat = Math.min(minLat, lat);
maxLat = Math.max(maxLat, lat);
minLng = Math.min(minLng, lng);
maxLng = Math.max(maxLng, lng);
}
return { min_lat: minLat, min_lng: minLng, max_lat: maxLat, max_lng: maxLng };
}
function thinned(refs: readonly number[]): number[] {
if (refs.length <= MAX_WAY_NODES) return [...refs];
const step = Math.ceil(refs.length / MAX_WAY_NODES);
const kept = refs.filter((_, index) => index % step === 0);
const last = refs[refs.length - 1];
if (last !== undefined && kept[kept.length - 1] !== last) kept.push(last);
return kept;
}
function build(
osmRef: string,
kind: PaddleObstacleKind,
rawTags: Record<string, string>,
geometry: PaddleGeometry,
points: ReadonlyArray<readonly [number, number]>,
): ExtractedFeature {
const tags = keptTags(rawTags);
return {
osm_ref: osmRef,
kind,
name: paddleNameOf(rawTags),
geometry,
tags,
tag_hash: hashOf(tags, geometry),
group_key: null,
...boxOf(points),
};
}
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] : [];
});
if (points.length < 2) return null;
const first = points[0] as readonly [number, number];
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 };
return build(`way/${pending.way.id}`, pending.kind, pending.way.tags, geometry, points);
}
function centreOf(feature: ExtractedFeature): [number, number] {
return [(feature.min_lat + feature.max_lat) / 2, (feature.min_lng + feature.max_lng) / 2];
}
function metresBetween(a: [number, number], b: [number, number]): number {
const cos = Math.cos((((a[0] + b[0]) / 2) * Math.PI) / 180);
return Math.hypot((b[0] - a[0]) * 111_195, (b[1] - a[1]) * 111_195 * cos);
}
/**
* The chambers and gates of one lock share a key, so the checklist asks
* about the lock once and not about each gate. Parts closer than
* LOCK_GROUP_M join a group; separate locks stay apart.
*/
export function groupLockParts(features: ExtractedFeature[]): void {
const parts = features.filter((feature) => feature.kind === 'lock' || feature.kind === 'lock_gate');
const parent = new Map<ExtractedFeature, ExtractedFeature>(parts.map((part) => [part, part]));
const root = (part: ExtractedFeature): ExtractedFeature => {
let current = part;
while (parent.get(current) !== current) current = parent.get(current) as ExtractedFeature;
return current;
};
// Sorted by longitude, so each part is only compared with its neighbours within reach.
const sorted = [...parts].sort((a, b) => centreOf(a)[1] - centreOf(b)[1]);
sorted.forEach((part, index) => {
const centre = centreOf(part);
for (let j = index + 1; j < sorted.length; j++) {
const other = sorted[j] as ExtractedFeature;
const otherCentre = centreOf(other);
if ((otherCentre[1] - centre[1]) * 111_195 * Math.cos((centre[0] * Math.PI) / 180) > LOCK_GROUP_M) break;
if (metresBetween(centre, otherCentre) <= LOCK_GROUP_M) parent.set(root(other), root(part));
}
});
const groups = new Map<ExtractedFeature, ExtractedFeature[]>();
for (const part of parts) groups.set(root(part), [...(groups.get(root(part)) ?? []), part]);
for (const members of groups.values()) {
if (members.length < 2) continue;
const key = `lock:${members.map((member) => member.osm_ref).sort()[0]}`;
for (const member of members) member.group_key = key;
}
}
/** Every paddle object of the extract at `path`, and the date its data is current to. */
export async function extractPaddleFeatures(
path: string,
onProgress?: (bytesRead: number) => Promise<void> | void,
): Promise<{ timestamp: number | null; features: ExtractedFeature[] }> {
const features: ExtractedFeature[] = [];
const pending: PendingWay[] = [];
const needed = new Set<number>();
const { timestamp } = await readPbfFile(
path,
{
node: (node) => {
if (Object.keys(node.tags).length === 0) return;
const kind = paddleKindOf(node.tags);
if (!kind) return;
const point: [number, number] = [node.lon, node.lat];
features.push(build(`node/${node.id}`, kind, node.tags, { type: 'Point', coordinates: point }, [point]));
},
way: (way) => {
const kind = paddleKindOf(way.tags);
if (!kind) return;
const refs = thinned(way.refs);
pending.push({ way: { ...way, refs }, kind });
for (const ref of refs) needed.add(ref);
},
},
onProgress,
);
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]);
},
});
for (const way of pending) {
const feature = wayFeature(way, coords);
if (feature) features.push(feature);
}
}
groupLockParts(features);
return { timestamp, features };
}
@@ -0,0 +1,90 @@
import type { Box } from '../../db/repositories/PaddleFeatures.repository';
import { PADDLE_OBSTACLES_MAX_SPAN_DEG, type PaddleCoverageState } from '@trek/shared';
import { z } from 'zod';
/** 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>;
/** `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 {
const [south, west, north, east] = text.split(',').map(Number);
if ([south, west, north, east].some((value) => value === undefined || !Number.isFinite(value))) return null;
const box = { south: south as number, west: west as number, north: north as number, east: east as number };
if (box.south > box.north || box.west > box.east) return null;
if (Math.abs(box.south) > 90 || Math.abs(box.north) > 90 || Math.abs(box.west) > 180 || Math.abs(box.east) > 180)
return null;
if (box.north - box.south > PADDLE_OBSTACLES_MAX_SPAN_DEG || box.east - box.west > PADDLE_OBSTACLES_MAX_SPAN_DEG)
return null;
return box;
}
/** Read as plain values: this workspace compiles without strict mode, where the schema's tuples are "maybe two". */
function inRing(points: ReadonlyArray<ReadonlyArray<unknown>>, lat: number, lng: number): boolean {
let inside = false;
for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
const xi = Number(points[i]?.[0]);
const yi = Number(points[i]?.[1]);
const xj = Number(points[j]?.[0]);
const yj = Number(points[j]?.[1]);
if (yi > lat !== yj > lat && lng < ((xj - xi) * (lat - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
/** Whether a point lies inside a region's boundary: in an outer ring and in none of its holes. */
export function boundaryContains(boundary: RegionBoundary, lat: number, lng: number): boolean {
const polygons = boundary.type === 'Polygon' ? [boundary.coordinates] : boundary.coordinates;
return polygons.some(
([outer, ...holes]) => !!outer && inRing(outer, lat, lng) && !holes.some((hole) => inRing(hole, lat, lng)),
);
}
/** The points a box is checked at: its corners and its middle. */
function samplesOf(box: Box): Array<[number, number]> {
const midLat = (box.south + box.north) / 2;
const midLng = (box.west + box.east) / 2;
return [
[box.south, box.west],
[box.south, box.east],
[box.north, box.west],
[box.north, box.east],
[midLat, midLng],
];
}
/**
* How far TREK's data reaches over a box whose area some region's box
* reaches into: covered when every sample point lies inside a region's
* boundary, partial otherwise; without such a region, none. A region whose
* boundary is unknown counts by its box alone.
*/
export function coverageOf(box: Box, boundaries: ReadonlyArray<RegionBoundary | null>): PaddleCoverageState {
if (boundaries.length === 0) return 'none';
const inside = samplesOf(box).map(([lat, lng]) =>
boundaries.some((boundary) => boundary === null || boundaryContains(boundary, lat, lng)),
);
// A region's box reaching in without any sample inside its boundary still touches the area at an edge.
return inside.every(Boolean) ? 'covered' : 'partial';
}
/** The box around a boundary, for the region's row. */
export function boxOfBoundary(boundary: RegionBoundary): Box {
const polygons = boundary.type === 'Polygon' ? [boundary.coordinates] : boundary.coordinates;
const box = { south: 90, west: 180, north: -90, east: -180 };
for (const polygon of polygons) {
for (const point of polygon[0] ?? []) {
const lng = Number(point[0]);
const lat = Number(point[1]);
box.south = Math.min(box.south, lat);
box.north = Math.max(box.north, lat);
box.west = Math.min(box.west, lng);
box.east = Math.max(box.east, lng);
}
}
return box;
}
@@ -0,0 +1,81 @@
import { ADDON_IDS } from '../../addons';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { AdminGuard } from '../auth-core/admin.guard';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { PaddleObstaclesQueryDto, PaddleRegionCatalogQueryDto, PaddleRegionRequestDto } from './paddle-obstacles.dto';
import { PaddleObstaclesService } from './paddle-obstacles.service';
import { PaddleRegionsService } from './paddle-regions.service';
import { Body, Controller, Get, HttpCode, Post, Query, UseGuards } from '@nestjs/common';
import {
paddleObstaclesResponseSchema,
paddleRegionCatalogResponseSchema,
paddleRegionListResponseSchema,
paddleRegionSchema,
successResponseSchema,
} from '@trek/shared';
/**
* GET /api/paddle/obstacles?bbox=: the paddle objects of a map area and its
* coverage (PAD-05A), for anyone signed in while Tours is on. The data is
* OpenStreetMap's, read from regional extracts, not trip data.
*/
@Controller('api/paddle')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class PaddleObstaclesController {
constructor(private readonly obstacles: PaddleObstaclesService) {}
@Get('obstacles')
@ResponseContract(paddleObstaclesResponseSchema)
async inBox(@Query() query: PaddleObstaclesQueryDto) {
return await this.obstacles.inBox(query.bbox);
}
}
/**
* /api/admin/paddle-regions: which regions TREK reads paddle data for. The
* list, Geofabrik's catalogue to pick from, adding (which starts the first
* read), reading again and removing. Ids travel in the body or the query:
* Geofabrik's are plain words, but a route segment is no place for a choice
* that names an outside source.
*/
@Controller('api/admin/paddle-regions')
@UseGuards(JwtAuthGuard, AdminGuard)
export class PaddleRegionsController {
constructor(private readonly regions: PaddleRegionsService) {}
@Get()
@ResponseContract(paddleRegionListResponseSchema)
async list() {
return { regions: await this.regions.list() };
}
@Get('catalog')
@ResponseContract(paddleRegionCatalogResponseSchema)
async catalog(@Query() query: PaddleRegionCatalogQueryDto) {
return { regions: await this.regions.catalog(query.q) };
}
@Post()
@ResponseContract(paddleRegionSchema)
async add(@Body() body: PaddleRegionRequestDto) {
return await this.regions.add(body.id);
}
@Post('refresh')
@HttpCode(200)
@ResponseContract(paddleRegionSchema)
async refresh(@Body() body: PaddleRegionRequestDto) {
return await this.regions.refresh(body.id);
}
@Post('remove')
@HttpCode(200)
@ResponseContract(successResponseSchema)
async remove(@Body() body: PaddleRegionRequestDto) {
await this.regions.remove(body.id);
return { success: true as const };
}
}
@@ -0,0 +1,7 @@
import { paddleObstaclesQuerySchema, paddleRegionCatalogQuerySchema, paddleRegionRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class PaddleObstaclesQueryDto extends createZodDto(paddleObstaclesQuerySchema) {}
export class PaddleRegionCatalogQueryDto extends createZodDto(paddleRegionCatalogQuerySchema) {}
export class PaddleRegionRequestDto extends createZodDto(paddleRegionRequestSchema) {}
@@ -0,0 +1,25 @@
import { PaddleFeatures } from '../../db/entities/PaddleFeatures.entity';
import { PaddleRegions } from '../../db/entities/PaddleRegions.entity';
import { AddonsModule } from '../addons/addons.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { GeofabrikClient } from './geofabrik.client';
import { PaddleObstaclesController, PaddleRegionsController } from './paddle-obstacles.controller';
import { PaddleObstaclesService } from './paddle-obstacles.service';
import { PaddleRegionsJob } from './paddle-regions.job';
import { PaddleRegionsService } from './paddle-regions.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/**
* PAD-05A: paddle obstacles from OpenStreetMap. The regions an admin chose,
* their background reads from Geofabrik's extracts, and the objects of a map
* area for the planner. PaddleObstaclesService is exported for the tours
* domain's route checks (PAD-06, PAD-09).
*/
@Module({
imports: [AddonsModule, SchedulingModule, MikroOrmModule.forFeature([PaddleRegions, PaddleFeatures])],
controllers: [PaddleObstaclesController, PaddleRegionsController],
providers: [GeofabrikClient, PaddleObstaclesService, PaddleRegionsService, PaddleRegionsJob],
exports: [PaddleObstaclesService],
})
export class PaddleObstaclesModule {}
@@ -0,0 +1,86 @@
import { PaddleFeatures } from '../../db/entities/PaddleFeatures.entity';
import { PaddleRegions } from '../../db/entities/PaddleRegions.entity';
import type { Box, PaddleFeatureRow, PaddleFeaturesRepository } from '../../db/repositories/PaddleFeatures.repository';
import type { PaddleRegionsRepository } from '../../db/repositories/PaddleRegions.repository';
import { logWarn } from '../audit/audit-log.logger';
import { badRequest } from '../common/domain-error';
import { coverageOf, parseBox, regionBoundarySchema, type RegionBoundary } from './paddle-geo';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
PADDLE_OBSTACLES_CAP,
paddleFeatureSchema,
type PaddleFeature,
type PaddleObstaclesResponse,
} from '@trek/shared';
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.
}
logWarn(`[Paddle] stored object ${row.region_id}/${row.osm_ref} does not read; left out`);
return null;
}
/**
* 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.
*/
@Injectable()
export class PaddleObstaclesService {
constructor(
@InjectRepository(PaddleFeatures) private readonly features: PaddleFeaturesRepository,
@InjectRepository(PaddleRegions) private readonly regions: PaddleRegionsRepository,
) {}
async inBox(bbox: string): Promise<PaddleObstaclesResponse> {
const box = parseBox(bbox);
if (!box) throw badRequest(PADDLE_BOX_INVALID_MESSAGE);
return await this.read(box);
}
/** The same answer for a box already known to be valid, for the server's own route checks. */
async read(box: Box): Promise<PaddleObstaclesResponse> {
const [rows, regions] = await Promise.all([
this.features.findInBox(box, PADDLE_OBSTACLES_CAP + 1),
this.regions.readyInBox(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;
}
});
return {
features: rows.slice(0, PADDLE_OBSTACLES_CAP).flatMap((row) => featureOf(row) ?? []),
coverage: {
state: coverageOf(box, boundaries),
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`,
})),
},
truncated: rows.length > PADDLE_OBSTACLES_CAP,
};
}
}
@@ -0,0 +1,33 @@
import { logError, logInfo } from '../audit/audit-log.logger';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { PaddleRegionsService } from './paddle-regions.service';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
/**
* PAD-05A: paddle data stays current. On boot a read a restart cut short is
* queued again; on the 3rd of every month at 04:20 every region with data is
* read again from Geofabrik's newest extract (they are rebuilt daily). The
* reads run one after another in the background.
*/
@Injectable()
export class PaddleRegionsJob implements OnApplicationBootstrap {
constructor(
private readonly regions: PaddleRegionsService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
void this.registrar.runOnBoot('paddle-regions-resume', () => this.regions.resumeAfterRestart());
this.registrar.register('paddle-regions-refresh', '20 4 3 * *', () => this.tick());
}
async tick(): Promise<void> {
try {
const queued = await this.regions.queueRefresh();
if (queued > 0) logInfo(`[Paddle] monthly refresh: ${queued} region(s) queued`);
} catch (err) {
logError(`[Paddle] monthly refresh: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
@@ -0,0 +1,196 @@
import { PaddleFeatures } from '../../db/entities/PaddleFeatures.entity';
import { PaddleRegions } from '../../db/entities/PaddleRegions.entity';
import type { PaddleFeatureRow, PaddleFeaturesRepository } from '../../db/repositories/PaddleFeatures.repository';
import type { PaddleRegionRow, PaddleRegionsRepository } from '../../db/repositories/PaddleRegions.repository';
import { dbNow } from '../../db/types';
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 { 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 type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
import { mkdir, 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';
function toRegion(row: PaddleRegionRow): 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`,
feature_count: row.feature_count,
error: row.error,
};
}
function toRow(feature: ExtractedFeature): PaddleFeatureRow {
return {
region_id: '',
osm_ref: feature.osm_ref,
kind: feature.kind,
group_key: feature.group_key,
name: feature.name,
geometry: JSON.stringify(feature.geometry),
tags: JSON.stringify(feature.tags),
tag_hash: feature.tag_hash,
min_lat: feature.min_lat,
min_lng: feature.min_lng,
max_lat: feature.max_lat,
max_lng: feature.max_lng,
};
}
/**
* 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.
*/
@Injectable()
export class PaddleRegionsService {
private running: Promise<void> | null = null;
constructor(
private readonly geofabrik: GeofabrikClient,
private readonly paths: DataPathsService,
private readonly uow: UnitOfWork,
private readonly orm: MikroORM,
@InjectRepository(PaddleRegions) private readonly regions: PaddleRegionsRepository,
@InjectRepository(PaddleFeatures) private readonly features: PaddleFeaturesRepository,
) {}
async list(): Promise<PaddleRegion[]> {
return (await this.regions.list()).map(toRegion);
}
/** 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 needle = query.toLowerCase();
const path = (id: string | null): string[] => {
const names: string[] = [];
for (let at = id; at; at = all.get(at)?.parent ?? null) names.unshift(all.get(at)?.name ?? at);
return names;
};
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)))
.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. */
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' } });
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.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);
}
async refresh(id: string): Promise<PaddleRegion> {
const row = await this.regions.findById(id);
if (!row) throw new DomainError(404, 'Region not found');
await this.regions.updateRegion(id, { status: 'queued', error: null });
this.kick();
return toRegion({ ...row, status: 'queued', error: null });
}
async remove(id: string): Promise<void> {
if (!(await this.regions.deleteRegion(id))) throw new DomainError(404, 'Region not found');
}
/** Every region with data queued again, for the monthly refresh; the reads follow in the background. */
async queueRefresh(): Promise<number> {
const queued = await this.regions.queueReady();
if (queued > 0) this.kick();
return queued;
}
/** A restart left a read unfinished: it goes back to the queue, and the queue starts. */
async resumeAfterRestart(): Promise<void> {
await this.regions.requeueInterrupted();
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;
}
private async drain(): Promise<void> {
for (let next = await this.regions.nextQueued(); next; next = await this.regions.nextQueued()) {
await this.importRegion(next);
}
}
/** @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`);
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.features.replaceRegion(region.id, features.map(toRow));
await this.regions.updateRegion(region.id, {
status: 'ready',
feature_count: features.length,
source_timestamp: timestamp === null ? null : new Date(timestamp * 1000).toISOString(),
imported_at: dbNow(),
error: null,
});
});
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) });
} finally {
await unlink(file).catch(() => undefined);
}
}
}
@@ -0,0 +1,86 @@
import type { PaddleObstacleKind } from '@trek/shared';
/**
* PAD-05A: which OpenStreetMap objects are paddle obstacles, places to get
* in and out, portage ways or access rules, and which of their tags are kept.
* The tag variants read are listed here and nowhere else:
*
* - waterway=weir, dam, lock_gate, waterfall; lock=yes on a waterway (a lock chamber)
* - rapids: whitewater=rapid, waterway=rapids
* - hazard: whitewater=hazard, and hazard=* or obstacle=* on a waterway
* - put-in and egress: canoe=put_in / egress, whitewater=put_in / egress / put_in;egress
* (the older whitewater scheme), leisure=slipway as a slipway
* - portage: canoe=portage, portage=yes, whitewater=portage_way
* - access: a waterway (river, canal, stream) whose canoe, boat or their
* conditional variants say who may paddle it
*
* Relations (a multipolygon lock basin) are not read; their member ways are.
*/
const WATERWAYS = new Set(['river', 'canal', 'stream', 'fairway', 'tidal_channel']);
const PUT_IN = new Set(['put_in', 'put_in;egress', 'egress;put_in']);
/** The kind an object is, or null when it is none of PAD-05A's. */
export function paddleKindOf(tags: Readonly<Record<string, string>>): PaddleObstacleKind | null {
const waterway = tags.waterway;
const whitewater = tags.whitewater;
const canoe = tags.canoe;
if (waterway === 'weir') return 'weir';
if (waterway === 'dam') return 'dam';
if (waterway === 'lock_gate') return 'lock_gate';
if (waterway === 'waterfall') return 'waterfall';
if (tags.lock === 'yes' && (waterway === undefined || WATERWAYS.has(waterway))) return 'lock';
if (whitewater === 'rapid' || waterway === 'rapids') return 'rapids';
if (whitewater === 'hazard') return 'hazard';
if (canoe === 'portage' || tags.portage === 'yes' || whitewater === 'portage_way') return 'portage';
if (canoe === 'put_in' || (whitewater !== undefined && PUT_IN.has(whitewater))) return 'put_in';
if (canoe === 'egress' || whitewater === 'egress') return 'egress';
if (tags.leisure === 'slipway') return 'slipway';
if (waterway !== undefined && WATERWAYS.has(waterway)) {
if (tags.hazard !== undefined || tags.obstacle !== undefined) return 'hazard';
const ruled = ['canoe', 'boat', 'canoe:conditional', 'boat:conditional'].some((key) => tags[key] !== undefined);
if (ruled) return 'access';
}
return null;
}
const KEPT = new Set([
'name',
'lock_name',
'ref',
'waterway',
'lock',
'whitewater',
'canoe',
'boat',
'access',
'portage',
'hazard',
'obstacle',
'leisure',
'height',
'width',
'operator',
'opening_hours',
'seasonal',
'description',
'note',
'fee',
'website',
'motorboat',
]);
const KEPT_PREFIXES = ['canoe:', 'boat:', 'whitewater:', 'portage:', 'lock:', 'access:'];
/** The tags an object is judged and shown by; everything else of OSM's is left behind. */
export function keptTags(tags: Readonly<Record<string, string>>): Record<string, string> {
const kept: Record<string, string> = {};
for (const [key, value] of Object.entries(tags)) {
if (KEPT.has(key) || KEPT_PREFIXES.some((prefix) => key.startsWith(prefix))) kept[key] = value;
}
return kept;
}
/** The name a paddler knows it by: its own, else the lock's. */
export function paddleNameOf(tags: Readonly<Record<string, string>>): string | null {
return tags.name ?? tags.lock_name ?? null;
}
@@ -0,0 +1,5 @@
import { tourPaddlePlanRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class TourPaddlePlanDto extends createZodDto(tourPaddlePlanRequestSchema) {}
@@ -0,0 +1,110 @@
import { Places } from '../../db/entities/Places.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 { ToursRepository } from '../../db/repositories/Tours.repository';
import { encodeJson } from '../../utils/json-column';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { PlacesService } from '../places/places.service';
import { computeTourMetrics, parseRouteGeometry } from './tours.helpers';
import { ToursService } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import {
estimatePaddleTime,
paddleLayoutOfTrack,
paddleMovingSeconds,
recommendedPaddleSpeedKmh,
type PaddleBoatType,
type TourDetailResponse,
type TourPaddlePlanRequest,
} from '@trek/shared';
/** A mark may sit this far past the end of the track it was laid on, for rounding along the line. */
const TRACK_END_TOLERANCE_M = 1;
/**
* PAD-03 and PAD-07 for a recorded track: a GPX import keeps the line it was
* recorded with, so its portages and locks are laid onto it as distances
* rather than drawn into it, and nothing redraws the track. A planned tour
* carries the same plan in its legs and control points and saves it with its
* route; this service is for the tracks only.
*
* The moving time the plan makes is stored as the tour's duration, reckoned
* with the one estimate the planner and the detail view show.
*/
@Injectable()
export class TourPaddlePlanService {
private readonly logger = new Logger(TourPaddlePlanService.name);
constructor(
private readonly uow: UnitOfWork,
private readonly places: PlacesService,
private readonly tours: ToursService,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
) {}
async update(
tripId: string,
placeId: string,
input: TourPaddlePlanRequest,
socketId?: string,
): Promise<TourDetailResponse> {
const tid = toRowId(tripId);
const pid = toRowId(placeId);
if (tid === null || pid === null) throw new NotFoundException('Tour not found');
await this.uow.transactional(async () => {
const row = await this.toursRepo.findInTrip(tid, pid);
if (!row) throw new NotFoundException('Tour not found');
if (row.tour_type !== 'kayak') {
throw new DomainError(400, 'Only a paddle tour has a paddle plan', {
code: 'not_a_paddle_tour',
details: { code: 'not_a_paddle_tour' },
});
}
if (row.has_waypoints) {
throw new DomainError(400, 'A planned tour saves its portages and locks with its route', {
code: 'planned_tour',
details: { code: 'planned_tour' },
});
}
const place = await this.placesRepo.findInTrip(pid, tid);
const totalM = computeTourMetrics(parseRouteGeometry(place?.route_geometry)).distanceKm * 1000;
const marks = input.track_marks;
const beyond = [...marks.portages.map((mark) => mark.to_m), ...marks.locks.map((lock) => lock.at_m)].some(
(at) => at > totalM + TRACK_END_TOLERANCE_M,
);
if (beyond)
throw new DomainError(400, 'A mark lies beyond the end of the track', {
code: 'mark_beyond_track',
details: { code: 'mark_beyond_track' },
});
const estimate = estimatePaddleTime(paddleLayoutOfTrack(totalM, marks), {
paddleSpeedKmh: input.paddle_speed_kmh ?? recommendedPaddleSpeedKmh(row.boat_type as PaddleBoatType | null),
portageSpeedKmh: input.portage_speed_kmh,
breakMinutes: null,
});
const moving = paddleMovingSeconds(estimate);
const empty = marks.portages.length === 0 && marks.locks.length === 0;
await this.toursRepo.updatePaddlePlanInTrip(tid, pid, {
paddle_speed_kmh: input.paddle_speed_kmh,
portage_speed_kmh: input.portage_speed_kmh,
track_marks: empty ? null : encodeJson(TOUR_TRACK_MARKS, marks),
duration: moving === null ? null : Math.round(moving / 60),
});
});
const result = await this.tours.getTour(tripId, placeId);
try {
this.places.broadcast(tripId, 'tours:changed', { placeIds: [pid] }, socketId);
} catch {
this.logger.warn(`Committed paddle plan of tour ${placeId}: realtime invalidation failed`);
}
return result;
}
}
+22 -1
View File
@@ -5,6 +5,8 @@ import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { TourCopyDto, TourCreateDto } from './dto/tour-create.dto';
import { TourPaddlePlanDto } from './dto/tour-paddle-plan.dto';
import { TourPaddlePlanService } from './tour-paddle-plan.service';
import { ToursService } from './tours.service';
import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, UseGuards } from '@nestjs/common';
import { tourCreateResponseSchema, tourDetailResponseSchema } from '@trek/shared';
@@ -20,7 +22,10 @@ import { tourCreateResponseSchema, tourDetailResponseSchema } from '@trek/shared
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class ToursController {
constructor(private readonly tours: ToursService) {}
constructor(
private readonly tours: ToursService,
private readonly paddlePlans: TourPaddlePlanService,
) {}
@Get()
async list(@Param('tripId') tripId: string) {
@@ -66,6 +71,22 @@ export class ToursController {
return await this.tours.copyTour(tripId, placeId, body.name, socketId);
}
/**
* PAD-03/PAD-07: the portages, locks and speeds of a recorded paddle track,
* laid onto it without redrawing it. A planned tour saves these with its route.
*/
@RequirePermission('place_edit')
@Put(':placeId/paddle-plan')
@ResponseContract(tourDetailResponseSchema)
async updatePaddlePlan(
@Param('tripId') tripId: string,
@Param('placeId') placeId: string,
@Body() body: TourPaddlePlanDto,
@Headers('x-socket-id') socketId?: string,
) {
return await this.paddlePlans.update(tripId, placeId, body, socketId);
}
/** Takes an import planned over in place back to its recorded track; the planning is dropped. */
@RequirePermission('place_edit')
@Post(':placeId/restore-recorded')
+2 -1
View File
@@ -9,6 +9,7 @@ import { PlaceImportModule } from '../place-import/place-import.module';
import { PlacesModule } from '../places/places.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { WandererModule } from '../wanderer/wanderer.module';
import { TourPaddlePlanService } from './tour-paddle-plan.service';
import { ToursImportController } from './tours-import.controller';
import { ToursWandererController } from './tours-wanderer.controller';
import { ToursWandererService } from './tours-wanderer.service';
@@ -38,6 +39,6 @@ import { Module } from '@nestjs/common';
MikroOrmModule.forFeature([Tours, TourTypes, TourWaypoints, TourSources, Places]),
],
controllers: [ToursController, ToursImportController, ToursWandererController],
providers: [ToursService, ToursWandererService, ToursMcp],
providers: [ToursService, TourPaddlePlanService, ToursWandererService, ToursMcp],
})
export class ToursModule {}
+10
View File
@@ -12,6 +12,8 @@ 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';
import { UnitOfWork } from '../database/unit-of-work';
@@ -95,6 +97,8 @@ export class ToursService {
boat_type: r.boat_type as PaddleBoatType | null,
water_context: r.water_context as PaddleWaterContext | null,
paddle_speed_kmh: r.paddle_speed_kmh,
portage_speed_kmh: r.portage_speed_kmh,
track_marks: decodeJson(TOUR_TRACK_MARKS, r.track_marks, 'tour'),
has_recorded_track: Boolean(r.has_recorded_track),
planned: Boolean(r.planned),
caution: r.match_confidence !== null && r.match_confidence < LOW_CONFIDENCE_THRESHOLD,
@@ -125,6 +129,7 @@ export class ToursService {
boat_type: input.boat_type ?? null,
water_context: input.water_context ?? null,
paddle_speed_kmh: input.paddle_speed_kmh ?? null,
portage_speed_kmh: input.portage_speed_kmh ?? null,
};
}
@@ -336,6 +341,7 @@ export class ToursService {
boat_type: row.boat_type as PaddleBoatType | null,
water_context: row.water_context as PaddleWaterContext | null,
paddle_speed_kmh: row.paddle_speed_kmh,
portage_speed_kmh: row.portage_speed_kmh,
});
await this.waypointsRepo.deleteForPlace(pid);
await this.toursRepo.clearRecordedTrack(pid);
@@ -397,6 +403,8 @@ export class ToursService {
boat_type: source.boat_type as PaddleBoatType | null,
water_context: source.water_context as PaddleWaterContext | null,
paddle_speed_kmh: source.paddle_speed_kmh,
portage_speed_kmh: source.portage_speed_kmh,
track_marks: source.track_marks,
wanderer_ref: source.wanderer_ref,
difficulty: source.difficulty,
derived_from_place_id: pid,
@@ -544,6 +552,8 @@ export class ToursService {
max_hiking_difficulty: null,
derived_from_place_id: null,
origin: 'gpx',
portage_speed_kmh: null,
track_marks: null,
has_recorded_track: 0,
planned: 0,
has_waypoints: 0,
@@ -0,0 +1,5 @@
import { windQuerySchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class WindQueryDto extends createZodDto(windQuerySchema) {}
+19 -2
View File
@@ -1,8 +1,11 @@
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
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 type { WeatherResult } from '@trek/shared';
import { windForecastResponseSchema, type WeatherResult, type WindForecastResponse } from '@trek/shared';
/**
* /api/weather — first migrated leaf module (the pilot).
@@ -19,7 +22,21 @@ import type { WeatherResult } from '@trek/shared';
@Controller('api/weather')
@UseGuards(JwtAuthGuard)
export class WeatherController {
constructor(private readonly weather: WeatherService) {}
constructor(
private readonly weather: WeatherService,
private readonly wind: WindService,
) {}
/**
* PAD-08: the wind forecast for one place and day, with gusts and direction.
* Forecast only: a past day or one beyond the forecast's reach answers with
* its status and no figures, and a failed request is a 502 of its own.
*/
@Get('wind')
@ResponseContract(windForecastResponseSchema)
async getWind(@Query() query: WindQueryDto): Promise<WindForecastResponse> {
return await this.wind.forecast(query);
}
@Get()
async getWeather(
+2 -1
View File
@@ -2,11 +2,12 @@ import { WeatherController } from './weather.controller';
import { WeatherMcp } from './weather.mcp';
import { WeatherRpc } from './weather.rpc';
import { WeatherService } from './weather.service';
import { WindService } from './wind.service';
import { Module } from '@nestjs/common';
/** Weather domain (pilot leaf module). Registered in AppModule. */
@Module({
controllers: [WeatherController],
providers: [WeatherService, WeatherMcp, WeatherRpc],
providers: [WeatherService, WindService, WeatherMcp, WeatherRpc],
})
export class WeatherModule {}
+145
View File
@@ -0,0 +1,145 @@
import { readCappedJson } from '../../utils/cappedFetch';
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. */
const WIND_TIMEOUT_MS = 8000;
const MAX_WIND_BYTES = 256 * 1024;
/** A forecast is rerun every few hours; half an hour keeps it fresh without asking for every pan. */
const CACHE_TTL_MS = 30 * 60 * 1000;
const CACHE_MAX_ENTRIES = 500;
const DAY_MS = 24 * 60 * 60 * 1000;
const series = z.array(z.number().nullable());
/** The part of Open-Meteo's answer the wind is read from; anything else in it is ignored. */
const openMeteoWindSchema = z.object({
timezone: z.string(),
hourly: z.object({
time: z.array(z.string()),
wind_speed_10m: series,
wind_gusts_10m: series.optional(),
wind_direction_10m: series.optional(),
}),
daily: z.object({
wind_speed_10m_max: series,
wind_gusts_10m_max: series.optional(),
wind_direction_10m_dominant: series.optional(),
}),
});
export const WIND_UNAVAILABLE_MESSAGE = 'The wind forecast is not available right now';
/** Rounded to a whole km/h or degree; a missing value stays missing. */
function whole(value: number | null | undefined): number | null {
return value === null || value === undefined || !Number.isFinite(value) ? null : Math.round(value);
}
/**
* PAD-08: the wind for a place on one day, from the Open-Meteo forecast TREK's
* weather already uses. Only the forecast is asked: a day in the past or
* beyond the forecast's reach answers with its status and no figures, so a
* climate value is never passed off as the day's wind. A failed request is a
* 502 the client can tell from "no forecast yet", never an empty answer.
*/
@Injectable()
export class WindService {
private readonly cache = new Map<string, { value: WindForecastResponse; expiresAt: number }>();
private readonly pending = new Map<string, Promise<WindForecastResponse>>();
async forecast(query: WindQuery, now: number = Date.now()): Promise<WindForecastResponse> {
const status = statusOf(query.date, now);
if (status !== 'forecast') return empty(query, status, now);
const key = `${query.lat.toFixed(2)}_${query.lng.toFixed(2)}_${query.date}`;
const hit = this.cache.get(key);
if (hit && hit.expiresAt > now) return hit.value;
const running = this.pending.get(key);
if (running) return running;
const request = this.fetchDay(query, now)
.then((value) => {
this.remember(key, value, now);
return value;
})
.finally(() => this.pending.delete(key));
this.pending.set(key, request);
return request;
}
private remember(key: string, value: WindForecastResponse, now: number): void {
if (this.cache.size >= CACHE_MAX_ENTRIES) {
const oldest = this.cache.keys().next().value;
if (oldest !== undefined) this.cache.delete(oldest);
}
this.cache.set(key, { value, expiresAt: now + CACHE_TTL_MS });
}
private async fetchDay(query: WindQuery, now: number): Promise<WindForecastResponse> {
const url =
`https://api.open-meteo.com/v1/forecast?latitude=${query.lat}&longitude=${query.lng}` +
'&hourly=wind_speed_10m,wind_gusts_10m,wind_direction_10m' +
'&daily=wind_speed_10m_max,wind_gusts_10m_max,wind_direction_10m_dominant' +
`&timezone=auto&wind_speed_unit=kmh&start_date=${query.date}&end_date=${query.date}`;
let parsed: z.infer<typeof openMeteoWindSchema>;
try {
const response = await fetch(url, { signal: AbortSignal.timeout(WIND_TIMEOUT_MS) });
if (!response.ok) {
await response.body?.cancel().catch(() => undefined);
throw new Error(`Open-Meteo ${response.status}`);
}
parsed = openMeteoWindSchema.parse(await readCappedJson<unknown>(response, MAX_WIND_BYTES));
} catch (err) {
logWarn(`[Wind] forecast for ${query.date} failed: ${err instanceof Error ? err.message : String(err)}`);
throw new DomainError(502, WIND_UNAVAILABLE_MESSAGE, {
code: 'wind_unavailable',
details: { code: 'wind_unavailable' },
});
}
const { hourly, daily } = parsed;
return {
status: 'forecast',
date: query.date,
lat: query.lat,
lng: query.lng,
timezone: parsed.timezone,
source: 'Open-Meteo',
fetched_at: new Date(now).toISOString(),
horizon_days: WIND_FORECAST_DAYS,
hours: hourly.time.slice(0, 24).map((time, index) => ({
hour: Number(time.slice(11, 13)) || index,
speed_kmh: whole(hourly.wind_speed_10m[index]),
gusts_kmh: whole(hourly.wind_gusts_10m?.[index]),
direction_deg: whole(hourly.wind_direction_10m?.[index]),
})),
day: {
speed_max_kmh: whole(daily.wind_speed_10m_max[0]),
gusts_max_kmh: whole(daily.wind_gusts_10m_max?.[0]),
direction_dominant_deg: whole(daily.wind_direction_10m_dominant?.[0]),
},
};
}
}
/** Past, within the forecast's reach, or beyond it, counted in whole days from today (UTC). */
function statusOf(date: string, now: number): WindForecastStatus {
const today = Date.parse(new Date(now).toISOString().slice(0, 10));
const days = Math.round((Date.parse(date) - today) / DAY_MS);
if (!Number.isFinite(days) || days < 0) return 'past';
return days >= WIND_FORECAST_DAYS ? 'beyond_horizon' : 'forecast';
}
function empty(query: WindQuery, status: WindForecastStatus, now: number): WindForecastResponse {
return {
status,
date: query.date,
lat: query.lat,
lng: query.lng,
timezone: null,
source: 'Open-Meteo',
fetched_at: new Date(now).toISOString(),
horizon_days: WIND_FORECAST_DAYS,
hours: [],
day: null,
};
}