mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 08:53:13 +00:00
fix(tours): paddle data reads stream, queue safely and keep their coverage during a refresh
The PBF reader streams the extract and refuses a varint longer than ten bytes; the block offsets are read as the plain int64 the format defines. Region reads queue without loose promises: a region queued while another is read is still picked up, removing a region calls its read off, a shutdown stops the read under way and the next boot queues it again and clears the download folder. The admin list shows how far a read has come. Geofabrik is asked only on its own servers, redirects included, and an outage of its list answers 502 instead of an unknown region. Nested ids such as us/texas are accepted. A region being read again or after a failed read still counts with the data it holds, a region without a boundary spans its objects, and an object two overlapping regions hold is answered once. Stored geometry, tags and boundaries go through the JSON column declarations. An obstacle is related to the route both ways, so a long weir passed in its middle and a route inside an area count. Tests cover the reader with extracts written in the test, the tag rules, the extraction and lock grouping, the geo helpers, the Geofabrik client, the region queue, the read side, both controllers, the job, the repositories and the HTTP routes; the domain gets its coverage entry.
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
paddleAccessOf,
|
||||
paddleFeatureSchema,
|
||||
paddleGeometrySchema,
|
||||
paddleObstaclesQuerySchema,
|
||||
paddleObstaclesResponseSchema,
|
||||
} from './paddle-obstacles.schema';
|
||||
import {
|
||||
paddleRegionBoundarySchema,
|
||||
paddleRegionCatalogQuerySchema,
|
||||
paddleRegionRequestSchema,
|
||||
paddleRegionSchema,
|
||||
} from './paddle-regions.schema';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const weir = {
|
||||
ref: 'way/29256405',
|
||||
kind: 'weir',
|
||||
group_key: null,
|
||||
name: 'Wehr Lindenmühle',
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[12.1301, 49.1231],
|
||||
[12.1315, 49.124],
|
||||
],
|
||||
},
|
||||
tags: { waterway: 'weir' },
|
||||
tag_hash: 'abc',
|
||||
region_id: 'oberpfalz',
|
||||
};
|
||||
|
||||
describe('paddle obstacle contracts (PAD-05A)', () => {
|
||||
it('a weir stays a line, never only a point', () => {
|
||||
expect(paddleFeatureSchema.parse(weir).geometry.type).toBe('LineString');
|
||||
expect(paddleGeometrySchema.safeParse({ type: 'LineString', coordinates: [[12, 49]] }).success).toBe(false);
|
||||
expect(
|
||||
paddleGeometrySchema.safeParse({
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
[0, 0],
|
||||
],
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(paddleGeometrySchema.safeParse({ type: 'Point', coordinates: [Number.NaN, 1] }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a kind TREK does not know', () => {
|
||||
expect(paddleFeatureSchema.safeParse({ ...weir, kind: 'castle' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('the box query is four numbers', () => {
|
||||
expect(paddleObstaclesQuerySchema.safeParse({ bbox: '49.1,12.1,49.2,12.2' }).success).toBe(true);
|
||||
expect(paddleObstaclesQuerySchema.safeParse({ bbox: '-34,-71,-33.5,-70.5' }).success).toBe(true);
|
||||
expect(paddleObstaclesQuerySchema.safeParse({ bbox: '49.1,12.1,49.2' }).success).toBe(false);
|
||||
expect(paddleObstaclesQuerySchema.safeParse({ bbox: '49.1,12.1,49.2,abc' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('an answer carries its coverage and whether it was cut', () => {
|
||||
const answer = { features: [weir], coverage: { state: 'partial', regions: [] }, truncated: false };
|
||||
expect(paddleObstaclesResponseSchema.safeParse(answer).success).toBe(true);
|
||||
expect(
|
||||
paddleObstaclesResponseSchema.safeParse({ ...answer, coverage: { state: 'free', regions: [] } }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('paddleAccessOf', () => {
|
||||
it('reads canoe before boat and boat before access', () => {
|
||||
expect(paddleAccessOf({ canoe: 'yes', boat: 'no', access: 'private' })).toMatchObject({
|
||||
value: 'yes',
|
||||
source: 'canoe',
|
||||
});
|
||||
expect(paddleAccessOf({ boat: 'no', access: 'yes' })).toMatchObject({
|
||||
value: 'no',
|
||||
source: 'boat',
|
||||
forbidden: true,
|
||||
});
|
||||
expect(paddleAccessOf({ access: 'private' })).toMatchObject({ value: 'private', source: 'access', private: true });
|
||||
});
|
||||
|
||||
it('keeps a condition as written and never reads a missing value as permission', () => {
|
||||
expect(paddleAccessOf({ 'canoe:conditional': 'no @ (Nov-Mar)' })).toEqual({
|
||||
value: null,
|
||||
source: null,
|
||||
condition: 'no @ (Nov-Mar)',
|
||||
forbidden: false,
|
||||
private: false,
|
||||
});
|
||||
expect(paddleAccessOf({ 'boat:conditional': 'yes @ (sunrise-sunset)' }).condition).toBe('yes @ (sunrise-sunset)');
|
||||
expect(paddleAccessOf({})).toEqual({
|
||||
value: null,
|
||||
source: null,
|
||||
condition: null,
|
||||
forbidden: false,
|
||||
private: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('paddle region contracts (PAD-05A)', () => {
|
||||
it("takes Geofabrik's ids, nested ones included, and nothing that could name a path", () => {
|
||||
for (const id of ['oberpfalz', 'mecklenburg-vorpommern', 'us/texas']) {
|
||||
expect(paddleRegionRequestSchema.safeParse({ id }).success).toBe(true);
|
||||
}
|
||||
for (const id of ['', 'a', 'Oberpfalz', '../etc', 'us//texas', '/texas', 'us/', 'a b']) {
|
||||
expect(paddleRegionRequestSchema.safeParse({ id }).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('a catalogue query is two to eighty characters once trimmed', () => {
|
||||
expect(paddleRegionCatalogQuerySchema.parse({ q: ' ober ' }).q).toBe('ober');
|
||||
expect(paddleRegionCatalogQuerySchema.safeParse({ q: ' o ' }).success).toBe(false);
|
||||
expect(paddleRegionCatalogQuerySchema.safeParse({ q: 'x'.repeat(81) }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('a region carries its read, and the progress of one under way', () => {
|
||||
const region = {
|
||||
id: 'oberpfalz',
|
||||
name: 'Oberpfalz',
|
||||
status: 'importing',
|
||||
source_timestamp: null,
|
||||
imported_at: null,
|
||||
feature_count: 0,
|
||||
error: null,
|
||||
progress: { phase: 'download', fraction: 0.4 },
|
||||
};
|
||||
expect(paddleRegionSchema.safeParse(region).success).toBe(true);
|
||||
expect(paddleRegionSchema.safeParse({ ...region, progress: { phase: 'read', fraction: null } }).success).toBe(true);
|
||||
expect(paddleRegionSchema.safeParse({ ...region, progress: { phase: 'read', fraction: 2 } }).success).toBe(false);
|
||||
expect(paddleRegionSchema.safeParse({ ...region, status: 'done' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('a boundary is a polygon or several', () => {
|
||||
const square = [
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
[1, 1],
|
||||
[0, 0],
|
||||
];
|
||||
expect(paddleRegionBoundarySchema.safeParse({ type: 'Polygon', coordinates: [square] }).success).toBe(true);
|
||||
expect(paddleRegionBoundarySchema.safeParse({ type: 'MultiPolygon', coordinates: [[square]] }).success).toBe(true);
|
||||
expect(paddleRegionBoundarySchema.safeParse({ type: 'Point', coordinates: [0, 0] }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { z } from 'zod';
|
||||
/**
|
||||
* PAD-05A, the admin side: the regions TREK reads paddle data for. Each is
|
||||
* one of Geofabrik's regional OpenStreetMap extracts, chosen by its id there
|
||||
* (`germany/bayern/oberpfalz`); TREK downloads it, reads the paddle objects
|
||||
* (`oberpfalz`, `us/california`); TREK downloads it, reads the paddle objects
|
||||
* out and keeps nothing else of it. A region is read again every month.
|
||||
*/
|
||||
|
||||
@@ -21,6 +21,17 @@ export const paddleRegionSchema = z.object({
|
||||
feature_count: z.number().int(),
|
||||
/** Why the last read failed, as plain text; null otherwise. */
|
||||
error: z.string().nullable(),
|
||||
/**
|
||||
* How far the read under way has come: the download, then the reading of
|
||||
* the file, each with the share done (null while the size is unknown).
|
||||
* Null unless the region is being read.
|
||||
*/
|
||||
progress: z
|
||||
.object({
|
||||
phase: z.enum(['download', 'read']),
|
||||
fraction: z.number().min(0).max(1).nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
export type PaddleRegion = z.infer<typeof paddleRegionSchema>;
|
||||
|
||||
@@ -39,13 +50,21 @@ export const paddleRegionCatalogQuerySchema = z.object({ q: z.string().trim().mi
|
||||
export const paddleRegionCatalogResponseSchema = z.object({ regions: z.array(paddleRegionCatalogEntrySchema) });
|
||||
export type PaddleRegionCatalogResponse = z.infer<typeof paddleRegionCatalogResponseSchema>;
|
||||
|
||||
/** Geofabrik's region ids: lower case words, digits and dashes. */
|
||||
/** Geofabrik's region ids: lower case words, digits and dashes, a few of them nested with a slash (`us/texas`). */
|
||||
export const paddleRegionIdSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(2)
|
||||
.max(120)
|
||||
.regex(/^[a-z0-9-]+$/);
|
||||
.regex(/^[a-z0-9-]+(\/[a-z0-9-]+)*$/);
|
||||
|
||||
/** A region's boundary as Geofabrik draws it: a polygon or several, rings of [lng, lat]. */
|
||||
const boundaryRing = z.array(z.tuple([z.number(), z.number()]));
|
||||
export const paddleRegionBoundarySchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('Polygon'), coordinates: z.array(boundaryRing) }),
|
||||
z.object({ type: z.literal('MultiPolygon'), coordinates: z.array(z.array(boundaryRing)) }),
|
||||
]);
|
||||
export type PaddleRegionBoundary = z.infer<typeof paddleRegionBoundarySchema>;
|
||||
|
||||
export const paddleRegionRequestSchema = z.object({ id: paddleRegionIdSchema });
|
||||
export type PaddleRegionRequest = z.infer<typeof paddleRegionRequestSchema>;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { PaddleFeature, PaddleGeometry } from './paddle-obstacles.schema';
|
||||
import { NEAR_M, ON_ROUTE_M, relateObstaclesToRoute } from './paddle-route-relation';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/** Metres north and east of 49.1°N 12.1°E, near enough for these distances. */
|
||||
const M_PER_DEG_LAT = 111_195;
|
||||
const M_PER_DEG_LNG = 111_195 * Math.cos((49.1 * Math.PI) / 180);
|
||||
const at = (north: number, east: number): [number, number] => [
|
||||
49.1 + north / M_PER_DEG_LAT,
|
||||
12.1 + east / M_PER_DEG_LNG,
|
||||
];
|
||||
const lngLat = (north: number, east: number): [number, number] => {
|
||||
const [lat, lng] = at(north, east);
|
||||
return [lng, lat];
|
||||
};
|
||||
|
||||
function feature(ref: string, geometry: PaddleGeometry): PaddleFeature {
|
||||
return { ref, kind: 'weir', group_key: null, name: null, geometry, tags: {}, tag_hash: ref, region_id: 'oberpfalz' };
|
||||
}
|
||||
|
||||
/** A route due east along the river, 2 km long. */
|
||||
const route = [at(0, 0), at(0, 1000), at(0, 2000)];
|
||||
|
||||
describe('relateObstaclesToRoute', () => {
|
||||
it('relates nothing to a route of fewer than two points', () => {
|
||||
const weir = feature('node/1', { type: 'Point', coordinates: lngLat(0, 500) });
|
||||
expect(relateObstaclesToRoute([], [weir])).toEqual([]);
|
||||
expect(relateObstaclesToRoute([at(0, 0)], [weir])).toEqual([]);
|
||||
});
|
||||
|
||||
it('puts a weir the route crosses on the route, where it crosses', () => {
|
||||
const weir = feature('way/29256405', {
|
||||
type: 'LineString',
|
||||
coordinates: [lngLat(-40, 1200), lngLat(40, 1200)],
|
||||
});
|
||||
expect(relateObstaclesToRoute(route, [weir])).toEqual([
|
||||
{ feature: weir, relation: 'on_route', distanceM: 0, alongM: 1200 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('a point within ON_ROUTE_M is on the route, within NEAR_M near, farther off not related', () => {
|
||||
const on = feature('node/1', { type: 'Point', coordinates: lngLat(ON_ROUTE_M - 5, 300) });
|
||||
const near = feature('node/2', { type: 'Point', coordinates: lngLat(100, 700) });
|
||||
const far = feature('node/3', { type: 'Point', coordinates: lngLat(NEAR_M + 30, 900) });
|
||||
const related = relateObstaclesToRoute(route, [near, far, on]);
|
||||
expect(related.map((entry) => [entry.feature.ref, entry.relation, entry.distanceM, entry.alongM])).toEqual([
|
||||
['node/1', 'on_route', 20, 300],
|
||||
['node/2', 'near', 100, 700],
|
||||
]);
|
||||
});
|
||||
|
||||
it('measures from the route to a long line too, so passing its middle counts', () => {
|
||||
// A dam 60 m north of the route, running 1 km parallel to it: its ends are far, its middle is not.
|
||||
const dam = feature('way/7', { type: 'LineString', coordinates: [lngLat(60, -2000), lngLat(60, 4000)] });
|
||||
const [related] = relateObstaclesToRoute(route, [dam]);
|
||||
expect(related).toMatchObject({ relation: 'near', distanceM: 60, alongM: 0 });
|
||||
});
|
||||
|
||||
it('a route running inside an area meets it, even without crossing its outline', () => {
|
||||
const basin = feature('way/9', {
|
||||
type: 'Polygon',
|
||||
coordinates: [[lngLat(-500, -500), lngLat(-500, 2500), lngLat(500, 2500), lngLat(500, -500), lngLat(-500, -500)]],
|
||||
});
|
||||
expect(relateObstaclesToRoute(route, [basin])).toEqual([
|
||||
{ feature: basin, relation: 'on_route', distanceM: 0, alongM: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('a route inside a hole of an area does not meet it there', () => {
|
||||
const ring = feature('way/10', {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[lngLat(-900, -900), lngLat(-900, 2900), lngLat(900, 2900), lngLat(900, -900), lngLat(-900, -900)],
|
||||
[lngLat(-600, -600), lngLat(-600, 2600), lngLat(600, 2600), lngLat(600, -600), lngLat(-600, -600)],
|
||||
],
|
||||
});
|
||||
expect(relateObstaclesToRoute(route, [ring])).toEqual([]);
|
||||
});
|
||||
|
||||
it('orders the related objects as the route reaches them', () => {
|
||||
const late = feature('node/late', { type: 'Point', coordinates: lngLat(0, 1800) });
|
||||
const early = feature('node/early', { type: 'Point', coordinates: lngLat(0, 200) });
|
||||
expect(relateObstaclesToRoute(route, [late, early]).map((entry) => entry.feature.ref)).toEqual([
|
||||
'node/early',
|
||||
'node/late',
|
||||
]);
|
||||
});
|
||||
|
||||
it('an object on the next arm of the river, 120 m off, stays near and so uncertain', () => {
|
||||
const otherArm = feature('way/11', { type: 'LineString', coordinates: [lngLat(100, 500), lngLat(160, 500)] });
|
||||
expect(relateObstaclesToRoute(route, [otherArm])[0]).toMatchObject({ relation: 'near', distanceM: 100 });
|
||||
});
|
||||
});
|
||||
@@ -54,28 +54,112 @@ function crosses(a: Local, b: Local, c: Local, d: Local): number | null {
|
||||
return t >= 0 && t <= 1 && u >= 0 && u <= 1 ? t : null;
|
||||
}
|
||||
|
||||
/** The object's outline as segments (a point is one segment of length zero). */
|
||||
function segmentsOf(geometry: PaddleGeometry, project: (lat: number, lng: number) => Local): Array<[Local, Local]> {
|
||||
const line =
|
||||
geometry.type === 'Point'
|
||||
? [geometry.coordinates, geometry.coordinates]
|
||||
: geometry.type === 'LineString'
|
||||
? geometry.coordinates
|
||||
: (geometry.coordinates[0] ?? []);
|
||||
const points = line.map(([lng, lat]) => project(lat, lng));
|
||||
/** The rings of an object: a point is one ring of one point, a line one open ring, an area its outline and holes. */
|
||||
function ringsOf(geometry: PaddleGeometry): ReadonlyArray<ReadonlyArray<readonly [number, number]>> {
|
||||
if (geometry.type === 'Point') return [[geometry.coordinates, geometry.coordinates]];
|
||||
if (geometry.type === 'LineString') return [geometry.coordinates];
|
||||
return geometry.coordinates;
|
||||
}
|
||||
|
||||
function segmentsOf(rings: ReadonlyArray<readonly Local[]>): Array<[Local, Local]> {
|
||||
const segments: Array<[Local, Local]> = [];
|
||||
for (let i = 1; i < points.length; i++) {
|
||||
const a = points[i - 1];
|
||||
const b = points[i];
|
||||
if (a && b) segments.push([a, b]);
|
||||
for (const ring of rings) {
|
||||
for (let i = 1; i < ring.length; i++) {
|
||||
const a = ring[i - 1];
|
||||
const b = ring[i];
|
||||
if (a && b) segments.push([a, b]);
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
function inRing(p: Local, ring: readonly Local[]): boolean {
|
||||
let inside = false;
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
||||
const a = ring[i] as Local;
|
||||
const b = ring[j] as Local;
|
||||
if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/** Inside an area: within its outline and in none of its holes. */
|
||||
function inArea(p: Local, rings: readonly (readonly Local[])[]): boolean {
|
||||
const [outer, ...holes] = rings;
|
||||
return !!outer && inRing(p, outer) && !holes.some((hole) => inRing(p, hole));
|
||||
}
|
||||
|
||||
interface Bounds {
|
||||
minX: number;
|
||||
minY: number;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
}
|
||||
|
||||
function boundsOf(points: readonly Local[], margin: number): Bounds {
|
||||
const bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
|
||||
for (const p of points) {
|
||||
bounds.minX = Math.min(bounds.minX, p.x - margin);
|
||||
bounds.minY = Math.min(bounds.minY, p.y - margin);
|
||||
bounds.maxX = Math.max(bounds.maxX, p.x + margin);
|
||||
bounds.maxY = Math.max(bounds.maxY, p.y + margin);
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
function overlaps(a: Bounds, b: Bounds): boolean {
|
||||
return a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
|
||||
}
|
||||
|
||||
/**
|
||||
* The closest the route comes to one object: the distance and how far along
|
||||
* the route that is. A route that crosses the outline, or runs inside an
|
||||
* area, meets it at distance 0, at the first place it does.
|
||||
*/
|
||||
function closestApproach(
|
||||
path: readonly Local[],
|
||||
along: readonly number[],
|
||||
rings: readonly (readonly Local[])[],
|
||||
isArea: boolean,
|
||||
): { distance: number; alongM: number } {
|
||||
const outline = segmentsOf(rings);
|
||||
const reach = boundsOf(rings.flat(), NEAR_M);
|
||||
let best = { distance: Number.POSITIVE_INFINITY, alongM: 0 };
|
||||
const consider = (distance: number, alongM: number) => {
|
||||
if (distance < best.distance || (distance === best.distance && alongM < best.alongM)) best = { distance, alongM };
|
||||
};
|
||||
path.forEach((p, i) => {
|
||||
if (isArea && inArea(p, rings)) consider(0, along[i] ?? 0);
|
||||
});
|
||||
for (let i = 1; i < path.length; i++) {
|
||||
const a = path[i - 1] as Local;
|
||||
const b = path[i] as Local;
|
||||
if (!overlaps(boundsOf([a, b], 0), reach)) continue;
|
||||
const start = along[i - 1] ?? 0;
|
||||
const length = (along[i] ?? start) - start;
|
||||
for (const [c, d] of outline) {
|
||||
const hit = crosses(a, b, c, d);
|
||||
if (hit !== null) {
|
||||
consider(0, start + hit * length);
|
||||
continue;
|
||||
}
|
||||
for (const p of [c, d]) {
|
||||
const near = closestOnSegment(p, a, b);
|
||||
consider(near.distance, start + near.t * length);
|
||||
}
|
||||
consider(closestOnSegment(a, c, d).distance, start);
|
||||
consider(closestOnSegment(b, c, d).distance, start + length);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* The obstacles on or near a route, in the order the route reaches them. The
|
||||
* route is `[lat, lng]` pairs as the planner draws it; an empty or one-point
|
||||
* route relates nothing.
|
||||
* route relates nothing. The distance is measured both ways, from the route
|
||||
* to the object's outline and from the object to the route, so a long weir
|
||||
* passed in its middle and a route inside an area both count.
|
||||
*/
|
||||
export function relateObstaclesToRoute(
|
||||
route: readonly LatLng[],
|
||||
@@ -90,27 +174,12 @@ export function relateObstaclesToRoute(
|
||||
const b = path[i] as Local;
|
||||
along.push((along[i - 1] ?? 0) + Math.hypot(b.x - a.x, b.y - a.y));
|
||||
}
|
||||
const routeBounds = boundsOf(path, NEAR_M);
|
||||
const related: RelatedObstacle[] = [];
|
||||
for (const feature of features) {
|
||||
let best = { distance: Number.POSITIVE_INFINITY, alongM: 0 };
|
||||
const outline = segmentsOf(feature.geometry, project);
|
||||
for (let i = 1; i < path.length; i++) {
|
||||
const a = path[i - 1] as Local;
|
||||
const b = path[i] as Local;
|
||||
const start = along[i - 1] ?? 0;
|
||||
const length = (along[i] ?? start) - start;
|
||||
for (const [c, d] of outline) {
|
||||
const hit = crosses(a, b, c, d);
|
||||
if (hit !== null) {
|
||||
if (best.distance > 0 || start + hit * length < best.alongM) best = { distance: 0, alongM: start + hit * length };
|
||||
continue;
|
||||
}
|
||||
for (const p of [c, d]) {
|
||||
const near = closestOnSegment(p, a, b);
|
||||
if (near.distance < best.distance) best = { distance: near.distance, alongM: start + near.t * length };
|
||||
}
|
||||
}
|
||||
}
|
||||
const rings = ringsOf(feature.geometry).map((ring) => ring.map(([lng, lat]) => project(lat, lng)));
|
||||
if (!overlaps(boundsOf(rings.flat(), 0), routeBounds)) continue;
|
||||
const best = closestApproach(path, along, rings, feature.geometry.type === 'Polygon');
|
||||
if (best.distance > NEAR_M) continue;
|
||||
related.push({
|
||||
feature,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
estimatePaddleTime,
|
||||
paddleLayoutOfPoints,
|
||||
@@ -11,12 +9,19 @@ import {
|
||||
import { tourPaddlePlanRequestSchema, trackMarksSchema } from './paddle-plan.schema';
|
||||
import { tourCreateRequestSchema } from './tours.schema';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/** A point `km` kilometres east of 53°N 13°E along the parallel, near enough for these sums. */
|
||||
function east(km: number): { lat: number; lng: number } {
|
||||
return { lat: 53, lng: 13 + km / (111.19493 * Math.cos((53 * Math.PI) / 180)) };
|
||||
}
|
||||
|
||||
function leg(kind: 'free' | 'portage', from: { lat: number; lng: number }, to: { lat: number; lng: number }, extra?: number) {
|
||||
function leg(
|
||||
kind: 'free' | 'portage',
|
||||
from: { lat: number; lng: number },
|
||||
to: { lat: number; lng: number },
|
||||
extra?: number,
|
||||
) {
|
||||
return {
|
||||
kind,
|
||||
geometry: [
|
||||
@@ -155,7 +160,13 @@ describe('paddle plan (PAD-03, PAD-07)', () => {
|
||||
name: 'Carry',
|
||||
route_geometry: route,
|
||||
waypoints: [
|
||||
{ lat: 53, lng: 13, role: 'start', sequence: 0, fixed_leg: leg('portage', { lat: 53, lng: 13 }, { lat: 53, lng: 13.01 }) },
|
||||
{
|
||||
lat: 53,
|
||||
lng: 13,
|
||||
role: 'start',
|
||||
sequence: 0,
|
||||
fixed_leg: leg('portage', { lat: 53, lng: 13 }, { lat: 53, lng: 13.01 }),
|
||||
},
|
||||
{ lat: 53, lng: 13.01, role: 'end', sequence: 1, lock: { wait_minutes: 5, transit_minutes: 5 } },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -142,7 +142,8 @@ export function paddleLayoutOfTrack(totalM: number, marks: TrackMarks | null | u
|
||||
});
|
||||
cursor = mark.to_m;
|
||||
}
|
||||
if (totalM > cursor) stretches.push({ kind: 'water', fromM: cursor, toM: totalM, extraMinutes: null, startIndex: null });
|
||||
if (totalM > cursor)
|
||||
stretches.push({ kind: 'water', fromM: cursor, toM: totalM, extraMinutes: null, startIndex: null });
|
||||
const locks = (marks?.locks ?? [])
|
||||
.filter((lock) => lock.at_m <= totalM)
|
||||
.map((lock) => ({
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { paddleLockSchema, paddleStopMinutesSchema, portageSpeedKmhSchema, trackMarksSchema } from './paddle-plan.schema';
|
||||
import {
|
||||
paddleLockSchema,
|
||||
paddleStopMinutesSchema,
|
||||
portageSpeedKmhSchema,
|
||||
trackMarksSchema,
|
||||
} from './paddle-plan.schema';
|
||||
import { tourOriginSchema, tourProvenanceSchema } from './tour-provenance.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
@@ -340,7 +345,8 @@ function tourTypeIssues(value: {
|
||||
(value.waypoints ?? []).forEach((point, index) => {
|
||||
if (point.fixed_leg?.kind === 'portage')
|
||||
issues.push({ path: ['waypoints', index, 'fixed_leg'], message: 'a portage belongs to a paddle tour' });
|
||||
if (point.lock != null) issues.push({ path: ['waypoints', index, 'lock'], message: 'a lock belongs to a paddle tour' });
|
||||
if (point.lock != null)
|
||||
issues.push({ path: ['waypoints', index, 'lock'], message: 'a lock belongs to a paddle tour' });
|
||||
});
|
||||
return issues;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { COMPASS_POINTS, compassPointOf, windForecastResponseSchema, windQuerySchema } from './wind.schema';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('windQuerySchema (PAD-08)', () => {
|
||||
it('reads the place from the query string and wants a day', () => {
|
||||
expect(windQuerySchema.parse({ lat: '47.55', lng: '9.68', date: '2026-10-18' })).toEqual({
|
||||
lat: 47.55,
|
||||
lng: 9.68,
|
||||
date: '2026-10-18',
|
||||
});
|
||||
expect(windQuerySchema.safeParse({ lat: '47.55', lng: '9.68' }).success).toBe(false);
|
||||
expect(windQuerySchema.safeParse({ lat: '91', lng: '9.68', date: '2026-10-18' }).success).toBe(false);
|
||||
expect(windQuerySchema.safeParse({ lat: '47.55', lng: '9.68', date: '18.10.2026' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('windForecastResponseSchema', () => {
|
||||
it('a day without a forecast carries its status and no figures; a missing value stays null, never zero', () => {
|
||||
const past = {
|
||||
status: 'past',
|
||||
date: '2026-10-01',
|
||||
lat: 47.55,
|
||||
lng: 9.68,
|
||||
timezone: null,
|
||||
source: 'Open-Meteo',
|
||||
fetched_at: '2026-10-16T10:00:00.000Z',
|
||||
horizon_days: 16,
|
||||
hours: [],
|
||||
day: null,
|
||||
};
|
||||
expect(windForecastResponseSchema.safeParse(past).success).toBe(true);
|
||||
const hour = { hour: 9, speed_kmh: 12, gusts_kmh: null, direction_deg: null };
|
||||
expect(windForecastResponseSchema.safeParse({ ...past, status: 'forecast', hours: [hour] }).success).toBe(true);
|
||||
expect(windForecastResponseSchema.safeParse({ ...past, source: 'Climate' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('compassPointOf', () => {
|
||||
it('names the sixteen points, wrapping around north', () => {
|
||||
expect(compassPointOf(0)).toBe('N');
|
||||
expect(compassPointOf(11)).toBe('N');
|
||||
expect(compassPointOf(12)).toBe('NNE');
|
||||
expect(compassPointOf(90)).toBe('E');
|
||||
expect(compassPointOf(225)).toBe('SW');
|
||||
expect(compassPointOf(349)).toBe('N');
|
||||
expect(compassPointOf(-90)).toBe('W');
|
||||
expect(compassPointOf(720 + 180)).toBe('S');
|
||||
expect(COMPASS_POINTS).toHaveLength(16);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user