mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 02:34:21 +00:00
feat(ski-routing): plan ski tours on the piste graphs of TREK Places
A new Nest domain plans the legs of a ski and winter tour on the runs, lifts, cross-country trails, ski touring and winter paths the Places host builds from OpenStreetMap, one SGR1 graph per ski area. TREK fetches the index once, downloads an area by its id when a planner first plans in it, checks it against the index's SHA-256 and keeps it in data/ski; no clicked point ever leaves the server. A leg whose area is slower than two seconds answers loading, and an older copy stands in while the host is down. The reader decodes the writer's golden file byte for byte, including the two edge flags it added (area_has_run, type_unknown). The search is A* in a worker thread over a profile per discipline (alpine, snowboard, cross-country by technique, touring, snowshoe, winter hike) with the times and penalties of the cost model, up to five snap candidates per point, lift stations as entry points, legs that go on from each other, pieces of a split network stitched by their boundary nodes, other ways by the penalty method, and a failed leg explained by relaxing one rule at a time (difficulty, lift class, technique, riding down, uphill) without ever handing out the relaxed line. POST /api/trips/:tripId/ski/route, GET .../ski/area-near and GET .../ski/network/:areaId sit behind Tours and the trip, with plan_ski_route as their MCP twin. A daily job looks for a new build and sweeps areas unused for 90 days. The admin switch ski_routing_enabled is on wherever TREK Places is.
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* Piste router e2e (spec 12.5): `POST /api/trips/:tripId/ski/route`,
|
||||
* `GET .../ski/area-near` and `GET .../ski/network/:areaId` through the real
|
||||
* AddonGuard, JwtAuthGuard and TripAccessGuard, the Zod pipe and the response
|
||||
* contracts, over the real services and router on a migrated temp SQLite db.
|
||||
* The Places host is a stub serving one area drawn by the test, so nothing
|
||||
* leaves the test; its client is covered in trek-places.winter.test.ts.
|
||||
*/
|
||||
import { AppConfigModule } from '../../src/nest/app-config/app-config.module';
|
||||
import { DataPathsService } from '../../src/nest/app-config/data-paths.service';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { TrekPlacesWinterService } from '../../src/nest/maps/trek-places-winter.service';
|
||||
import { SkiRoutingModule } from '../../src/nest/ski-routing/ski-routing.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { setAddonEnabled, setAppSetting } from '../helpers/factories/settings';
|
||||
import { addTripMember, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { SkiWorld } from '../helpers/ski-world';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { skiAreaNearResponseSchema, skiNetworkResponseSchema, skiRouteResponseSchema } from '@trek/shared';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
|
||||
const OWNER = 1;
|
||||
const MEMBER = 2;
|
||||
const STRANGER = 3;
|
||||
let tripId: number;
|
||||
let orm: TestOrm;
|
||||
let server: Server;
|
||||
let dir: string;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
/** Testalp: a chair up, a red run down. */
|
||||
const testalp = new SkiWorld();
|
||||
const valley = testalp.node(0, 0, 1200);
|
||||
const top = testalp.node(0, 2000, 2200);
|
||||
testalp.lift(valley, top, { name: 'Sonnenbahn', sec: 420 });
|
||||
testalp.run(top, valley, 2, { name: 'Rote Eins', via: [[300, 1000]] });
|
||||
const GZ = testalp.gz();
|
||||
const sha = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');
|
||||
const south = testalp.at(-500, -500);
|
||||
const north = testalp.at(500, 2500);
|
||||
const ROW = {
|
||||
id: 'w:1',
|
||||
name: 'Testalp',
|
||||
kind: 'resort',
|
||||
country: 'CH',
|
||||
colourScheme: 'europe' as const,
|
||||
bbox: [south.lng, south.lat, north.lng, north.lat] as [number, number, number, number],
|
||||
counts: { runsKm: 2.1, nordicKm: 0, lifts: 1, skitourKm: 0, hikeKm: 0 },
|
||||
bytes: GZ.length,
|
||||
sha256: sha(GZ),
|
||||
};
|
||||
const INDEX = { build: '2026-11-02', format: 1, areas: [ROW] };
|
||||
const INDEX_SHA = sha(JSON.stringify(INDEX));
|
||||
|
||||
const winter = {
|
||||
enabled: vi.fn(() => true),
|
||||
meta: vi.fn(async () => ({
|
||||
build: '2026-11-02',
|
||||
format: 1,
|
||||
areas: 1,
|
||||
indexSha: INDEX_SHA,
|
||||
sourceTimestamp: null,
|
||||
attribution: { data: '© OpenStreetMap contributors, ODbL', terrain: 'Terrain: Mapzen Terrarium' },
|
||||
})),
|
||||
index: vi.fn(async () => ({ status: 'ok' as const, index: INDEX, sha256: INDEX_SHA, dropped: 0 })),
|
||||
area: vi.fn(async () => ({ status: 'ok' as const, bytes: GZ, etag: ROW.sha256 })),
|
||||
};
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
AppConfigModule,
|
||||
SkiRoutingModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(DataPathsService)
|
||||
.useValue({ dataDir: dir, tmpDir: dir })
|
||||
.overrideProvider(TrekPlacesWinterService)
|
||||
.useValue(winter)
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const route = (body: unknown, userId?: number, trip = tripId) => {
|
||||
const req = request(server)
|
||||
.post(`/api/trips/${trip}/ski/route`)
|
||||
.send(body as object);
|
||||
return userId === undefined ? req : req.set({ Cookie: sessionCookie(userId) });
|
||||
};
|
||||
const down = { from: testalp.at(0, 2000), to: testalp.at(0, 0) };
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), 'trek-ski-routing-e2e-'));
|
||||
orm = await createTestOrm(db);
|
||||
await makeUser(orm, { id: OWNER, email: 'owner@example.test' });
|
||||
await makeUser(orm, { id: MEMBER, email: 'member@example.test' });
|
||||
await makeUser(orm, { id: STRANGER, email: 'stranger@example.test' });
|
||||
tripId = (await makeTrip(orm, OWNER)).id;
|
||||
await addTripMember(orm, tripId, MEMBER);
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
await setAppSetting(orm, 'ski_routing_enabled', 'true');
|
||||
winter.enabled.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
db.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('POST /api/trips/:tripId/ski/route', () => {
|
||||
it('SKIROUTE-E2E-001: 404 while Tours is off; 401 without a session', async () => {
|
||||
await setAddonEnabled(orm, 'tours', false);
|
||||
const off = await route({ legs: [down], discipline: 'alpine' }, OWNER);
|
||||
expect(off.status).toBe(404);
|
||||
expect(off.body).toEqual({ error: 'Tours addon is not enabled' });
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
expect((await route({ legs: [down], discipline: 'alpine' })).status).toBe(401);
|
||||
});
|
||||
|
||||
it('SKIROUTE-E2E-002: a trip the caller is not on answers 404, as one that does not exist', async () => {
|
||||
expect((await route({ legs: [down], discipline: 'alpine' }, STRANGER)).status).toBe(404);
|
||||
expect((await route({ legs: [down], discipline: 'alpine' }, OWNER, 999_999)).status).toBe(404);
|
||||
});
|
||||
|
||||
it('SKIROUTE-E2E-003: refuses a request off the contract with 400', async () => {
|
||||
// One after another: supertest binds the unstarted server per request, and requests at once reset each other.
|
||||
const answers = [
|
||||
await route({ legs: [down] }, OWNER),
|
||||
await route({ legs: [], discipline: 'alpine' }, OWNER),
|
||||
await route({ legs: [{ from: { lat: 95, lng: 0 }, to: down.to }], discipline: 'alpine' }, OWNER),
|
||||
await route({ legs: [down], discipline: 'alpine', options: { colour: 'red' } }, OWNER),
|
||||
await route({ legs: [down], discipline: 'sledge' }, OWNER),
|
||||
];
|
||||
expect(answers.map((res) => res.status)).toEqual([400, 400, 400, 400, 400]);
|
||||
});
|
||||
|
||||
it('SKIROUTE-E2E-004: owner and member get the leg planned down the red run, on the contract', async () => {
|
||||
const answers = [
|
||||
await route({ legs: [down], discipline: 'alpine' }, OWNER),
|
||||
await route({ legs: [down], discipline: 'alpine' }, MEMBER),
|
||||
];
|
||||
for (const res of answers) {
|
||||
expect(res.status).toBe(200);
|
||||
const answer = skiRouteResponseSchema.parse(res.body);
|
||||
const [leg] = answer.legs;
|
||||
if (leg?.status !== 'ok') throw new Error('not planned');
|
||||
expect(leg.segments.map((segment) => segment.name)).toEqual(['Rote Eins']);
|
||||
expect(answer).toMatchObject({ build: '2026-11-02', stale: false, area_names: ['Testalp'] });
|
||||
}
|
||||
// The area was downloaded once, by its id; no point ever went to the host.
|
||||
expect(winter.area).toHaveBeenCalledTimes(1);
|
||||
expect(winter.area).toHaveBeenCalledWith('w:1', null);
|
||||
});
|
||||
|
||||
it('SKIROUTE-E2E-005: the admin switch off answers disabled; TREK Places off answers unavailable', async () => {
|
||||
await setAppSetting(orm, 'ski_routing_enabled', 'false');
|
||||
const off = await route({ legs: [down], discipline: 'alpine' }, OWNER);
|
||||
expect(off.status).toBe(200);
|
||||
expect(off.body.legs[0]).toMatchObject({ status: 'failed', code: 'disabled', hint: { free_draw: true } });
|
||||
await setAppSetting(orm, 'ski_routing_enabled', 'true');
|
||||
winter.enabled.mockReturnValue(false);
|
||||
const none = await route({ legs: [down], discipline: 'alpine' }, OWNER);
|
||||
expect(none.body.legs[0]).toMatchObject({ code: 'places_unavailable' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/trips/:tripId/ski/area-near and /network/:areaId', () => {
|
||||
it('SKIROUTE-E2E-010: names the area at a point and its state; none off every area; 400 off the globe', async () => {
|
||||
const at = testalp.at(0, 1000);
|
||||
const near = await request(server)
|
||||
.get(`/api/trips/${tripId}/ski/area-near`)
|
||||
.query({ lat: at.lat, lng: at.lng })
|
||||
.set({ Cookie: sessionCookie(MEMBER) });
|
||||
expect(near.status).toBe(200);
|
||||
expect(skiAreaNearResponseSchema.parse(near.body).area).toMatchObject({ id: 'w:1', name: 'Testalp' });
|
||||
const nowhere = await request(server)
|
||||
.get(`/api/trips/${tripId}/ski/area-near`)
|
||||
.query({ lat: 53.5, lng: 10 })
|
||||
.set({ Cookie: sessionCookie(MEMBER) });
|
||||
expect(nowhere.body).toEqual({ area: null });
|
||||
const bad = await request(server)
|
||||
.get(`/api/trips/${tripId}/ski/area-near`)
|
||||
.query({ lat: 95, lng: 10 })
|
||||
.set({ Cookie: sessionCookie(MEMBER) });
|
||||
expect(bad.status).toBe(400);
|
||||
});
|
||||
|
||||
it('SKIROUTE-E2E-011: an area lines for the map, tagged with its checksum; an unknown area 404', async () => {
|
||||
const lines = await request(server)
|
||||
.get(`/api/trips/${tripId}/ski/network/w:1`)
|
||||
.set({ Cookie: sessionCookie(OWNER) });
|
||||
expect(lines.status).toBe(200);
|
||||
expect(lines.headers.etag).toBe(`"${ROW.sha256}"`);
|
||||
const network = skiNetworkResponseSchema.parse(lines.body);
|
||||
expect(network.features.map((feature) => feature.kind).sort()).toEqual(['lift', 'run']);
|
||||
const unknown = await request(server)
|
||||
.get(`/api/trips/${tripId}/ski/network/w:404`)
|
||||
.set({ Cookie: sessionCookie(OWNER) });
|
||||
expect(unknown.status).toBe(404);
|
||||
expect(unknown.body).toEqual({ error: 'Ski area not found' });
|
||||
});
|
||||
});
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
{
|
||||
"sha256": "9dd044605b8edf85c7fcc83e9f3bdb857f1e6451d09da7238d7f3071cf6c4b67",
|
||||
"bytes": 1728,
|
||||
"header": {
|
||||
"format": 1,
|
||||
"build": "2026-11-02",
|
||||
"areaId": "w:100",
|
||||
"name": "Sonnenbahn",
|
||||
"kind": "resort",
|
||||
"country": null,
|
||||
"colourScheme": "europe",
|
||||
"bbox": [
|
||||
7.0,
|
||||
45.999,
|
||||
7.005,
|
||||
46.0052
|
||||
],
|
||||
"counts": {
|
||||
"runsKm": 1.19,
|
||||
"nordicKm": 0.53,
|
||||
"lifts": 1,
|
||||
"skitourKm": 0.0,
|
||||
"hikeKm": 0.0
|
||||
},
|
||||
"nodeCount": 12,
|
||||
"edgeCount": 14,
|
||||
"geomCount": 33,
|
||||
"stringBytes": 43,
|
||||
"crc32": 2370316388
|
||||
},
|
||||
"strings": {
|
||||
"0": "Rote Eins",
|
||||
"10": "1",
|
||||
"12": "Blaue Zwei",
|
||||
"23": "Talloipe",
|
||||
"32": "Sonnenbahn"
|
||||
},
|
||||
"nodeLatE7": [
|
||||
460052000,
|
||||
460015000,
|
||||
460006075,
|
||||
460049894,
|
||||
460000000,
|
||||
459990000,
|
||||
460000000,
|
||||
460000000,
|
||||
460050000,
|
||||
460000000,
|
||||
460050000,
|
||||
460005000
|
||||
],
|
||||
"nodeLngE7": [
|
||||
70002000,
|
||||
70006000,
|
||||
70002430,
|
||||
70000266,
|
||||
70030000,
|
||||
70050000,
|
||||
70019000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000000,
|
||||
70008000
|
||||
],
|
||||
"nodeEle": [
|
||||
1645,
|
||||
1542,
|
||||
1517,
|
||||
1639,
|
||||
1500,
|
||||
1472,
|
||||
1500,
|
||||
1500,
|
||||
1639,
|
||||
1500,
|
||||
1639,
|
||||
1514
|
||||
],
|
||||
"nodeFlags": [
|
||||
0,
|
||||
8,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
16,
|
||||
16,
|
||||
1,
|
||||
1,
|
||||
0
|
||||
],
|
||||
"nodeOsm": [
|
||||
10.0,
|
||||
14.0,
|
||||
-4.0,
|
||||
-3.0,
|
||||
20.0,
|
||||
22.0,
|
||||
24.0,
|
||||
-1.0,
|
||||
-2.0,
|
||||
1.0,
|
||||
2.0,
|
||||
13.0
|
||||
],
|
||||
"edgeA": [
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
9,
|
||||
8,
|
||||
3,
|
||||
10,
|
||||
2,
|
||||
11,
|
||||
6
|
||||
],
|
||||
"edgeB": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
5,
|
||||
4,
|
||||
4,
|
||||
8,
|
||||
7,
|
||||
10,
|
||||
11,
|
||||
3,
|
||||
9,
|
||||
2,
|
||||
11
|
||||
],
|
||||
"edgeLen": [
|
||||
429.64385986328125,
|
||||
103.00074005126953,
|
||||
26.973962783813477,
|
||||
265.6802673339844,
|
||||
265.68304443359375,
|
||||
84.96685028076172,
|
||||
555.9754028320312,
|
||||
0.0,
|
||||
0.0,
|
||||
558.4176635742188,
|
||||
2.3661956787109375,
|
||||
70.11087799072266,
|
||||
44.65337371826172,
|
||||
101.54007720947266
|
||||
],
|
||||
"edgeUp": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
28,
|
||||
0,
|
||||
139,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
3,
|
||||
14
|
||||
],
|
||||
"edgeDown": [
|
||||
103,
|
||||
25,
|
||||
6,
|
||||
28,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
125,
|
||||
0,
|
||||
17,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"edgeKind": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
5,
|
||||
5,
|
||||
9,
|
||||
1,
|
||||
3,
|
||||
4,
|
||||
0,
|
||||
11,
|
||||
0,
|
||||
11,
|
||||
11
|
||||
],
|
||||
"edgeFwdUses": [
|
||||
65,
|
||||
65,
|
||||
65,
|
||||
24,
|
||||
24,
|
||||
1017,
|
||||
2,
|
||||
514,
|
||||
514,
|
||||
65,
|
||||
577,
|
||||
65,
|
||||
577,
|
||||
1017
|
||||
],
|
||||
"edgeBackUses": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
24,
|
||||
24,
|
||||
1017,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
577,
|
||||
0,
|
||||
577,
|
||||
1017
|
||||
],
|
||||
"edgeDiff": [
|
||||
2,
|
||||
2,
|
||||
1,
|
||||
255,
|
||||
255,
|
||||
255,
|
||||
255,
|
||||
255,
|
||||
255,
|
||||
1,
|
||||
255,
|
||||
2,
|
||||
255,
|
||||
255
|
||||
],
|
||||
"edgeGroom": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
3,
|
||||
3,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"edgeLift": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4,
|
||||
4,
|
||||
4,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"edgeLiftSec": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
360,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"edgeLiftCap": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
2400,
|
||||
2400,
|
||||
2400,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"edgeFlags": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
33024,
|
||||
33024,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
16,
|
||||
0,
|
||||
16,
|
||||
16
|
||||
],
|
||||
"edgeName": [
|
||||
0,
|
||||
0,
|
||||
12,
|
||||
23,
|
||||
23,
|
||||
4294967295,
|
||||
32,
|
||||
32,
|
||||
32,
|
||||
12,
|
||||
4294967295,
|
||||
0,
|
||||
4294967295,
|
||||
4294967295
|
||||
],
|
||||
"edgeRef": [
|
||||
10,
|
||||
10,
|
||||
4294967295,
|
||||
4294967295,
|
||||
4294967295,
|
||||
4294967295,
|
||||
4294967295,
|
||||
4294967295,
|
||||
4294967295,
|
||||
4294967295,
|
||||
4294967295,
|
||||
10,
|
||||
4294967295,
|
||||
4294967295
|
||||
],
|
||||
"edgeWay": [
|
||||
200.0,
|
||||
200.0,
|
||||
201.0,
|
||||
300.0,
|
||||
300.0,
|
||||
301.0,
|
||||
100.0,
|
||||
0.0,
|
||||
0.0,
|
||||
201.0,
|
||||
0.0,
|
||||
200.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"edgeGeomOff": [
|
||||
0,
|
||||
3,
|
||||
5,
|
||||
7,
|
||||
10,
|
||||
13,
|
||||
15,
|
||||
18,
|
||||
20,
|
||||
22,
|
||||
25,
|
||||
27,
|
||||
29,
|
||||
31,
|
||||
33
|
||||
],
|
||||
"geomLatE7": [
|
||||
460052000,
|
||||
460030000,
|
||||
460015000,
|
||||
460015000,
|
||||
460006075,
|
||||
460052000,
|
||||
460049894,
|
||||
460000000,
|
||||
460000000,
|
||||
459990000,
|
||||
459990000,
|
||||
459990000,
|
||||
460000000,
|
||||
460000000,
|
||||
460000000,
|
||||
460000000,
|
||||
460025000,
|
||||
460050000,
|
||||
460000000,
|
||||
460000000,
|
||||
460050000,
|
||||
460050000,
|
||||
460049894,
|
||||
460035000,
|
||||
460005000,
|
||||
460050000,
|
||||
460049894,
|
||||
460006075,
|
||||
460000000,
|
||||
460005000,
|
||||
460006075,
|
||||
460000000,
|
||||
460005000
|
||||
],
|
||||
"geomLngE7": [
|
||||
70002000,
|
||||
70012000,
|
||||
70006000,
|
||||
70006000,
|
||||
70002430,
|
||||
70002000,
|
||||
70000266,
|
||||
70030000,
|
||||
70050000,
|
||||
70050000,
|
||||
70050000,
|
||||
70030000,
|
||||
70030000,
|
||||
70019000,
|
||||
70030000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000000,
|
||||
70000266,
|
||||
69988000,
|
||||
70008000,
|
||||
70000000,
|
||||
70000266,
|
||||
70002430,
|
||||
70000000,
|
||||
70008000,
|
||||
70002430,
|
||||
70019000,
|
||||
70008000
|
||||
],
|
||||
"geomEle": [
|
||||
1645,
|
||||
1583,
|
||||
1542,
|
||||
1542,
|
||||
1517,
|
||||
1645,
|
||||
1639,
|
||||
1500,
|
||||
1500,
|
||||
1472,
|
||||
1472,
|
||||
1472,
|
||||
1500,
|
||||
1500,
|
||||
1500,
|
||||
1500,
|
||||
1570,
|
||||
1639,
|
||||
1500,
|
||||
1500,
|
||||
1639,
|
||||
1639,
|
||||
1639,
|
||||
1597,
|
||||
1514,
|
||||
1639,
|
||||
1639,
|
||||
1517,
|
||||
1500,
|
||||
1514,
|
||||
1517,
|
||||
1500,
|
||||
1514
|
||||
]
|
||||
}
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Planning legs on test worlds the way the service does: the request through
|
||||
* its contract, the profile as the service resolves it, the legs of one job
|
||||
* each going on from the one before.
|
||||
*/
|
||||
import { SkiRouter } from '../../src/nest/ski-routing/engine/plan';
|
||||
import { stitchGraphs } from '../../src/nest/ski-routing/engine/stitch';
|
||||
import { profileOf } from '../../src/nest/ski-routing/ski-routing.service';
|
||||
import type { SkiWorld } from './ski-world';
|
||||
import {
|
||||
skiRouteRequestSchema,
|
||||
type SkiDiscipline,
|
||||
type SkiRouteLeg,
|
||||
type SkiRouteOptionsInput,
|
||||
type SkiTechnique,
|
||||
} from '@trek/shared';
|
||||
|
||||
export type Point = { lat: number; lng: number };
|
||||
|
||||
export interface PlanOptions {
|
||||
discipline?: SkiDiscipline;
|
||||
options?: SkiRouteOptionsInput;
|
||||
technique?: SkiTechnique | null;
|
||||
alternatives?: number;
|
||||
/** Whether each leg goes on from where the one before ended (the default), as the service sends them. */
|
||||
chained?: boolean;
|
||||
}
|
||||
|
||||
export function planOn(
|
||||
worlds: SkiWorld | SkiWorld[],
|
||||
legs: Array<[Point, Point]>,
|
||||
{ discipline = 'alpine', options = {}, technique = null, alternatives = 0, chained = true }: PlanOptions = {},
|
||||
): SkiRouteLeg[] {
|
||||
const all = Array.isArray(worlds) ? worlds : [worlds];
|
||||
const router = new SkiRouter(stitchGraphs(all.map((world) => world.graph())));
|
||||
const request = skiRouteRequestSchema.parse({
|
||||
legs: legs.map(([from, to]) => ({ from, to })),
|
||||
discipline,
|
||||
technique,
|
||||
options,
|
||||
alternatives,
|
||||
});
|
||||
const input = request.legs.map((leg, index) => ({ from: leg.from, to: leg.to, continues: chained && index > 0 }));
|
||||
return router.plan({ legs: input, profile: profileOf(request), alternatives: request.alternatives }, ['w:1']);
|
||||
}
|
||||
|
||||
/** The leg as planned, or a failure that says why it was not. */
|
||||
export function okLeg(leg: SkiRouteLeg | undefined): Extract<SkiRouteLeg, { status: 'ok' }> {
|
||||
if (leg?.status !== 'ok') throw new Error(`leg not planned: ${JSON.stringify(leg)}`);
|
||||
return leg;
|
||||
}
|
||||
|
||||
export function failedLeg(leg: SkiRouteLeg | undefined): Extract<SkiRouteLeg, { status: 'failed' }> {
|
||||
if (leg?.status !== 'failed') throw new Error(`leg planned, a failure was expected`);
|
||||
return leg;
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* Ski areas drawn by a test: nodes set in metres east and north of an origin,
|
||||
* runs, trails and lifts between them, written out as SGR1 exactly as the
|
||||
* Places host's writer lays it out (`winter/sgr.py`): magic, head, sections
|
||||
* padded to 8 bytes, string pool, CRC-32 over everything after the head. The
|
||||
* golden file pins the reader against the real writer; this builds the
|
||||
* networks the router tests need without a planet.
|
||||
*/
|
||||
import { decodeSkiGraph } from '../../src/nest/ski-routing/ski-graph';
|
||||
import {
|
||||
DIFF_UNKNOWN,
|
||||
ELE_MISSING,
|
||||
Kind,
|
||||
Lift,
|
||||
NO_STRING,
|
||||
NodeFlag,
|
||||
Use,
|
||||
type SkiGraphData,
|
||||
} from '../../src/nest/ski-routing/ski-graph.contract';
|
||||
|
||||
import { crc32, gzipSync } from 'node:zlib';
|
||||
|
||||
const M_PER_DEG = 111_195;
|
||||
|
||||
export interface WorldNode {
|
||||
x: number;
|
||||
y: number;
|
||||
ele: number | null;
|
||||
osm: number;
|
||||
flags: number;
|
||||
}
|
||||
|
||||
export interface WorldEdge {
|
||||
a: number;
|
||||
b: number;
|
||||
kind: number;
|
||||
fwd: number;
|
||||
back: number;
|
||||
diff: number;
|
||||
groom: number;
|
||||
lift: number;
|
||||
liftSec: number;
|
||||
liftCap: number;
|
||||
flags: number;
|
||||
name: string | null;
|
||||
ref: string | null;
|
||||
way: number;
|
||||
via: Array<[number, number]>;
|
||||
}
|
||||
|
||||
export type EdgeOptions = Partial<Omit<WorldEdge, 'a' | 'b'>>;
|
||||
|
||||
interface WorldPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
ele: number | null;
|
||||
}
|
||||
|
||||
/** The length of a line of points in metres. */
|
||||
function lineLength(points: readonly WorldPoint[]): number {
|
||||
let total = 0;
|
||||
for (let i = 1; i < points.length; i++) {
|
||||
const a = points[i - 1] as WorldPoint;
|
||||
const b = points[i] as WorldPoint;
|
||||
total += Math.hypot(b.x - a.x, b.y - a.y);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Both directions downhill-only runs carry: a skier down, a ski tourer down. */
|
||||
export const RUN_DOWN = Use.DOWNHILL | Use.SKITOUR_DOWN;
|
||||
export const NORDIC_BOTH = Use.NORDIC_CLASSIC | Use.NORDIC_SKATING;
|
||||
|
||||
export class SkiWorld {
|
||||
readonly nodes: WorldNode[] = [];
|
||||
readonly edges: WorldEdge[] = [];
|
||||
private nextOsm = 1;
|
||||
private nextSynthetic = -1;
|
||||
private nextWay = 1;
|
||||
|
||||
constructor(
|
||||
readonly origin = { lat: 46, lng: 7 },
|
||||
readonly head: { areaId: string; build: string; name: string; colourScheme?: string } = {
|
||||
areaId: 'w:1',
|
||||
build: '2026-11-02',
|
||||
name: 'Testalp',
|
||||
},
|
||||
) {}
|
||||
|
||||
/** A point `x` metres east and `y` metres north of the origin. */
|
||||
at(x: number, y: number): { lat: number; lng: number } {
|
||||
return {
|
||||
lat: this.origin.lat + y / M_PER_DEG,
|
||||
lng: this.origin.lng + x / (M_PER_DEG * Math.cos((this.origin.lat * Math.PI) / 180)),
|
||||
};
|
||||
}
|
||||
|
||||
node(x: number, y: number, ele: number | null, options: { flags?: number; osm?: number } = {}): number {
|
||||
const synthetic = options.flags !== undefined && (options.flags & NodeFlag.LIFT_INTERNAL) !== 0;
|
||||
const osm = options.osm ?? (synthetic ? this.nextSynthetic-- : this.nextOsm++);
|
||||
this.nodes.push({ x, y, ele, osm, flags: options.flags ?? 0 });
|
||||
return this.nodes.length - 1;
|
||||
}
|
||||
|
||||
edge(a: number, b: number, options: EdgeOptions = {}): number {
|
||||
this.edges.push({
|
||||
a,
|
||||
b,
|
||||
kind: Kind.RUN,
|
||||
fwd: 0,
|
||||
back: 0,
|
||||
diff: DIFF_UNKNOWN,
|
||||
groom: 0,
|
||||
lift: Lift.NONE,
|
||||
liftSec: 0,
|
||||
liftCap: 0,
|
||||
flags: 0,
|
||||
name: null,
|
||||
ref: null,
|
||||
way: this.nextWay++,
|
||||
via: [],
|
||||
...options,
|
||||
});
|
||||
return this.edges.length - 1;
|
||||
}
|
||||
|
||||
/** A run skied from a to b only. */
|
||||
run(a: number, b: number, diff: number, options: EdgeOptions = {}): number {
|
||||
return this.edge(a, b, { kind: Kind.RUN, fwd: RUN_DOWN, back: 0, diff, ...options });
|
||||
}
|
||||
|
||||
/** A cross-country trail, both ways, groomed as given. */
|
||||
nordic(a: number, b: number, options: EdgeOptions = {}): number {
|
||||
return this.edge(a, b, { kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: 3, ...options });
|
||||
}
|
||||
|
||||
/** A short link the data does not hold, walked or skied either way. */
|
||||
link(a: number, b: number, options: EdgeOptions = {}): number {
|
||||
const uses = Use.WALK | Use.DOWNHILL | Use.SKITOUR_DOWN;
|
||||
return this.edge(a, b, { kind: Kind.LINK, fwd: uses, back: uses, way: 0, ...options });
|
||||
}
|
||||
|
||||
/**
|
||||
* A lift from a bottom ground node to a top one: its own two ride nodes, a
|
||||
* board edge at the bottom, the ride, an alight edge at the top, as the
|
||||
* writer lays a lift out. `down` lets it be ridden down as well.
|
||||
*/
|
||||
lift(
|
||||
bottom: number,
|
||||
top: number,
|
||||
options: { type?: number; name?: string; sec?: number; cap?: number; down?: boolean } = {},
|
||||
): { ride: number; board: number; alight: number } {
|
||||
const lift = options.type ?? Lift.CHAIR_DETACHABLE;
|
||||
const name = options.name ?? null;
|
||||
const from = this.nodes[bottom] as WorldNode;
|
||||
const to = this.nodes[top] as WorldNode;
|
||||
const rideBottom = this.node(from.x, from.y, from.ele, { flags: NodeFlag.LIFT_INTERNAL });
|
||||
const rideTop = this.node(to.x, to.y, to.ele, { flags: NodeFlag.LIFT_INTERNAL });
|
||||
from.flags |= NodeFlag.STATION;
|
||||
to.flags |= NodeFlag.STATION;
|
||||
const down = options.down ? Use.LIFT_DOWN : 0;
|
||||
const way = this.nextWay++;
|
||||
const common = { lift, name, liftCap: options.cap ?? 0, way };
|
||||
const board = this.edge(bottom, rideBottom, { ...common, kind: Kind.BOARD, fwd: Use.WALK | Use.LIFT_UP });
|
||||
const kind = lift === Lift.FUNICULAR || lift === Lift.RACK ? Kind.RAIL : Kind.LIFT;
|
||||
const liftSec = options.sec ?? 0;
|
||||
const ride = this.edge(rideBottom, rideTop, { ...common, kind, fwd: Use.LIFT_UP, back: down, liftSec });
|
||||
const alight = this.edge(rideTop, top, { ...common, kind: Kind.ALIGHT, fwd: Use.WALK | Use.LIFT_UP });
|
||||
if (options.down) {
|
||||
// Ridden down: boarded at the top, left at the bottom.
|
||||
this.edge(top, rideTop, { ...common, kind: Kind.BOARD, fwd: Use.WALK | Use.LIFT_DOWN });
|
||||
this.edge(rideBottom, bottom, { ...common, kind: Kind.ALIGHT, fwd: Use.WALK | Use.LIFT_DOWN });
|
||||
}
|
||||
return { ride, board, alight };
|
||||
}
|
||||
|
||||
/** An edge's points, its heights straight between its ends where both are known. */
|
||||
private line(e: WorldEdge): WorldPoint[] {
|
||||
const a = this.nodes[e.a] as WorldNode;
|
||||
const b = this.nodes[e.b] as WorldNode;
|
||||
const points: WorldPoint[] = [a, ...e.via.map(([x, y]) => ({ x, y, ele: null })), b];
|
||||
return points.map((p, i) => {
|
||||
if (i === 0 || i === points.length - 1) return { x: p.x, y: p.y, ele: p.ele };
|
||||
const share = i / (points.length - 1);
|
||||
return { x: p.x, y: p.y, ele: a.ele !== null && b.ele !== null ? a.ele + (b.ele - a.ele) * share : null };
|
||||
});
|
||||
}
|
||||
|
||||
private point(x: number, y: number): [number, number] {
|
||||
const { lat, lng } = this.at(x, y);
|
||||
return [lat, lng];
|
||||
}
|
||||
|
||||
/** The graph as the reader would hand it over, through the bytes, so the writer's layout is exercised. */
|
||||
graph(): SkiGraphData {
|
||||
return decodeSkiGraph(this.sgr());
|
||||
}
|
||||
|
||||
gz(): Buffer {
|
||||
return gzipSync(this.sgr());
|
||||
}
|
||||
|
||||
/** The SGR1 bytes of the world. */
|
||||
sgr(): Buffer {
|
||||
const pool: Buffer[] = [];
|
||||
const offsets = new Map<string, number>();
|
||||
let poolBytes = 0;
|
||||
const sid = (text: string | null): number => {
|
||||
if (!text) return NO_STRING;
|
||||
const known = offsets.get(text);
|
||||
if (known !== undefined) return known;
|
||||
const bytes = Buffer.from(`${text}\0`, 'utf8');
|
||||
offsets.set(text, poolBytes);
|
||||
pool.push(bytes);
|
||||
poolBytes += bytes.length;
|
||||
return poolBytes - bytes.length;
|
||||
};
|
||||
const ele = (value: number | null) => (value === null ? ELE_MISSING : Math.round(value));
|
||||
const n = this.nodes.length;
|
||||
const m = this.edges.length;
|
||||
const geometry = this.edges.map((e) => this.line(e));
|
||||
const g = geometry.reduce((sum, points) => sum + points.length, 0);
|
||||
|
||||
const sections: Buffer[] = [];
|
||||
const add = (view: ArrayBufferView) => {
|
||||
const raw = Buffer.from(view.buffer, view.byteOffset, view.byteLength);
|
||||
sections.push(raw, Buffer.alloc((8 - (raw.length % 8)) % 8));
|
||||
};
|
||||
add(Int32Array.from(this.nodes, (p) => Math.round(this.point(p.x, p.y)[0] * 1e7)));
|
||||
add(Int32Array.from(this.nodes, (p) => Math.round(this.point(p.x, p.y)[1] * 1e7)));
|
||||
add(Int16Array.from(this.nodes, (p) => ele(p.ele)));
|
||||
add(Uint16Array.from(this.nodes, (p) => p.flags | (p.ele === null ? NodeFlag.ELE_MISSING : 0)));
|
||||
add(Float64Array.from(this.nodes, (p) => p.osm));
|
||||
add(Uint32Array.from(this.edges, (e) => e.a));
|
||||
add(Uint32Array.from(this.edges, (e) => e.b));
|
||||
add(Float32Array.from(geometry, (points) => lineLength(points)));
|
||||
const rise = (e: WorldEdge, up: boolean) => {
|
||||
const a = (this.nodes[e.a] as WorldNode).ele;
|
||||
const b = (this.nodes[e.b] as WorldNode).ele;
|
||||
if (a === null || b === null) return 0;
|
||||
return Math.max(0, Math.round(up ? b - a : a - b));
|
||||
};
|
||||
add(Uint16Array.from(this.edges, (e) => rise(e, true)));
|
||||
add(Uint16Array.from(this.edges, (e) => rise(e, false)));
|
||||
add(Uint8Array.from(this.edges, (e) => e.kind));
|
||||
add(Uint16Array.from(this.edges, (e) => e.fwd));
|
||||
add(Uint16Array.from(this.edges, (e) => e.back));
|
||||
add(Uint8Array.from(this.edges, (e) => e.diff));
|
||||
add(Uint8Array.from(this.edges, (e) => e.groom));
|
||||
add(Uint8Array.from(this.edges, (e) => e.lift));
|
||||
add(Uint16Array.from(this.edges, (e) => e.liftSec));
|
||||
add(Uint16Array.from(this.edges, (e) => e.liftCap));
|
||||
add(Uint32Array.from(this.edges, (e) => e.flags));
|
||||
add(Uint32Array.from(this.edges, (e) => sid(e.name)));
|
||||
add(Uint32Array.from(this.edges, (e) => sid(e.ref)));
|
||||
add(Float64Array.from(this.edges, (e) => e.way));
|
||||
const offsetsOfGeometry = new Uint32Array(m + 1);
|
||||
for (let i = 0; i < m; i++) {
|
||||
offsetsOfGeometry[i + 1] = (offsetsOfGeometry[i] as number) + (geometry[i] as WorldPoint[]).length;
|
||||
}
|
||||
add(offsetsOfGeometry);
|
||||
const flat = geometry.flat();
|
||||
add(Int32Array.from(flat, (p) => Math.round(this.point(p.x, p.y)[0] * 1e7)));
|
||||
add(Int32Array.from(flat, (p) => Math.round(this.point(p.x, p.y)[1] * 1e7)));
|
||||
add(Int16Array.from(flat, (p) => ele(p.ele)));
|
||||
const strings = Buffer.concat(pool);
|
||||
sections.push(strings, Buffer.alloc((8 - (strings.length % 8)) % 8));
|
||||
const body = Buffer.concat(sections);
|
||||
|
||||
const lats = this.nodes.map((p) => this.point(p.x, p.y)[0]);
|
||||
const lngs = this.nodes.map((p) => this.point(p.x, p.y)[1]);
|
||||
const bbox = [Math.min(...lngs), Math.min(...lats), Math.max(...lngs), Math.max(...lats)];
|
||||
const header = {
|
||||
format: 1,
|
||||
build: this.head.build,
|
||||
areaId: this.head.areaId,
|
||||
name: this.head.name,
|
||||
kind: 'resort',
|
||||
country: null,
|
||||
colourScheme: this.head.colourScheme ?? 'europe',
|
||||
bbox,
|
||||
counts: { runsKm: 0, nordicKm: 0, lifts: 0, skitourKm: 0, hikeKm: 0 },
|
||||
nodeCount: n,
|
||||
edgeCount: m,
|
||||
geomCount: g,
|
||||
stringBytes: strings.length,
|
||||
crc32: crc32(body) >>> 0,
|
||||
};
|
||||
const json = Buffer.from(JSON.stringify(header), 'utf8');
|
||||
const prefix = Buffer.concat([Buffer.from('SGR1', 'latin1'), Buffer.alloc(4), json]);
|
||||
prefix.writeUInt32LE(json.length, 4);
|
||||
return Buffer.concat([prefix, Buffer.alloc((8 - (prefix.length % 8)) % 8), body]);
|
||||
}
|
||||
}
|
||||
@@ -455,6 +455,15 @@ describe('AddonsService addon/feature flags', () => {
|
||||
expect((await svc.list()).toursHikingMap).toBe(true);
|
||||
});
|
||||
|
||||
it('the piste router under Tours is on until an admin switches it off', async () => {
|
||||
expect(await svc.getToursSkiRouting()).toEqual({ enabled: true }); // absent row → ON
|
||||
expect(await svc.updateToursSkiRouting(false)).toEqual({ enabled: false });
|
||||
expect(await storedAppSetting('ski_routing_enabled')).toEqual({ key: 'ski_routing_enabled', value: 'false' });
|
||||
expect(await svc.getToursSkiRouting()).toEqual({ enabled: false });
|
||||
expect(await svc.updateToursSkiRouting(true)).toEqual({ enabled: true });
|
||||
expect(await svc.getToursSkiRouting()).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it('getCollabFeatures is opt-out: absent rows default ON, only false disables', async () => {
|
||||
await setAppSetting('collab_chat_enabled', 'false');
|
||||
await setAppSetting('collab_polls_enabled', 'true');
|
||||
|
||||
@@ -50,6 +50,8 @@ const addonsStub = () =>
|
||||
updateToursHikingMap: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getToursCycleMap: vi.fn(() => ({ enabled: true })),
|
||||
updateToursCycleMap: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getToursSkiRouting: vi.fn(() => ({ enabled: true })),
|
||||
updateToursSkiRouting: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getPlacesPhotos: vi.fn(() => ({ enabled: false })),
|
||||
updatePlacesPhotos: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getPlacesAutocomplete: vi.fn(() => ({ enabled: false })),
|
||||
@@ -498,6 +500,11 @@ describe('AdminController feature toggles', () => {
|
||||
[() => c.updateToursWanderer(user, { enabled: true }, req), 'admin.tours_wanderer', 'updateToursWanderer'],
|
||||
[() => c.updateToursHikingMap(user, { enabled: true }, req), 'admin.tours_hiking_map', 'updateToursHikingMap'],
|
||||
[() => c.updateToursCycleMap(user, { enabled: true }, req), 'admin.tours_cycle_map', 'updateToursCycleMap'],
|
||||
[
|
||||
() => c.updateToursSkiRouting(user, { enabled: true }, req),
|
||||
'admin.tours_ski_routing',
|
||||
'updateToursSkiRouting',
|
||||
],
|
||||
[() => c.updatePlacesPhotos(user, { enabled: true }, req), 'admin.places_photos', 'updatePlacesPhotos'],
|
||||
[
|
||||
() => c.updatePlacesAutocomplete(user, { enabled: true }, req),
|
||||
@@ -521,6 +528,7 @@ describe('AdminController feature toggles', () => {
|
||||
expect(await c.getToursWanderer()).toEqual({ enabled: false });
|
||||
expect(await c.getToursHikingMap()).toEqual({ enabled: true });
|
||||
expect(await c.getToursCycleMap()).toEqual({ enabled: true });
|
||||
expect(await c.getToursSkiRouting()).toEqual({ enabled: true });
|
||||
expect(await c.getPlacesPhotos()).toEqual({ enabled: false });
|
||||
expect(await c.getPlacesAutocomplete()).toEqual({ enabled: false });
|
||||
expect(await c.getPlacesDetails()).toEqual({ enabled: false });
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Why a leg is not planned (spec 7.6): each rule relaxed in turn names the
|
||||
* reason and the one change that would plan it; the way a relaxed search found
|
||||
* is never handed out as the leg. A point off every run, and two runs nothing
|
||||
* joins, are said as such.
|
||||
*/
|
||||
import { Kind, Lift, Use } from '../../../../src/nest/ski-routing/ski-graph.contract';
|
||||
import { failedLeg, planOn } from '../../../helpers/ski-plan';
|
||||
import { NORDIC_BOTH, SkiWorld } from '../../../helpers/ski-world';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/** A chair up and only a black run down. */
|
||||
function steepAlp() {
|
||||
const world = new SkiWorld();
|
||||
const valley = world.node(0, 0, 1200);
|
||||
const top = world.node(0, 2000, 2200);
|
||||
world.lift(valley, top, { name: 'Sonnenbahn', sec: 420 });
|
||||
world.run(top, valley, 3, { name: 'Schwarze Wand', via: [[-300, 1000]] });
|
||||
return { world, valley: world.at(0, 0), top: world.at(0, 2000) };
|
||||
}
|
||||
|
||||
describe('a leg one rule keeps from being planned', () => {
|
||||
it('SKIEXPLAIN-001: only a harder run joins the points: the level it needs and the run, never its line', () => {
|
||||
const { world, top, valley } = steepAlp();
|
||||
const leg = failedLeg(planOn(world, [[top, valley]])[0]);
|
||||
expect(leg).toEqual({
|
||||
status: 'failed',
|
||||
code: 'blocked_by_difficulty',
|
||||
at: null,
|
||||
hint: { raise_difficulty: 'advanced' },
|
||||
detail: { name: 'Schwarze Wand' },
|
||||
});
|
||||
expect(leg).not.toHaveProperty('geometry');
|
||||
});
|
||||
|
||||
it('SKIEXPLAIN-002: only an avoided lift joins them: the class to allow, and the lift', () => {
|
||||
const { world, top, valley } = steepAlp();
|
||||
const leg = failedLeg(planOn(world, [[valley, top]], { options: { avoid_lifts: ['open_chair'] } })[0]);
|
||||
expect(leg).toMatchObject({
|
||||
code: 'blocked_by_lift_avoid',
|
||||
hint: { allow_lift: 'open_chair' },
|
||||
detail: { name: 'Sonnenbahn' },
|
||||
});
|
||||
});
|
||||
|
||||
it('SKIEXPLAIN-003: only a trail of the other technique joins them: any technique will do', () => {
|
||||
const world = new SkiWorld();
|
||||
const a = world.node(0, 0, 1200);
|
||||
const b = world.node(2000, 0, 1210);
|
||||
world.edge(a, b, { kind: Kind.NORDIC, fwd: Use.NORDIC_SKATING, back: Use.NORDIC_SKATING, groom: 2 });
|
||||
const leg = failedLeg(
|
||||
planOn(world, [[world.at(0, 0), world.at(2000, 0)]], { discipline: 'cross_country', technique: 'classic' })[0],
|
||||
);
|
||||
expect(leg).toMatchObject({ code: 'blocked_by_technique', hint: { technique: 'unknown' } });
|
||||
// With either technique the same leg is planned.
|
||||
const either = planOn(world, [[world.at(0, 0), world.at(2000, 0)]], { discipline: 'cross_country' });
|
||||
expect(either[0]?.status).toBe('ok');
|
||||
});
|
||||
|
||||
it('SKIEXPLAIN-004: only riding the gondola down joins them: allow it', () => {
|
||||
const world = new SkiWorld();
|
||||
const foot = world.node(0, 0, 1600);
|
||||
const summit = world.node(0, 1500, 2500);
|
||||
world.lift(foot, summit, { type: Lift.GONDOLA, name: 'Gondel', down: true });
|
||||
const leg = failedLeg(
|
||||
planOn(world, [[world.at(0, 1500), world.at(0, 0)]], { options: { allow_lift_down: false } })[0],
|
||||
);
|
||||
expect(leg).toMatchObject({ code: 'needs_ride_down', hint: { allow_lift_down: true }, detail: { name: 'Gondel' } });
|
||||
});
|
||||
|
||||
it('SKIEXPLAIN-005: no way up without a lift: ski touring would go', () => {
|
||||
const world = new SkiWorld();
|
||||
const top = world.node(0, 2000, 2200);
|
||||
const valley = world.node(0, 0, 1200);
|
||||
world.run(top, valley, 1, { name: 'Talabfahrt' });
|
||||
const leg = failedLeg(planOn(world, [[world.at(0, 0), world.at(0, 2000)]])[0]);
|
||||
expect(leg).toMatchObject({ code: 'uphill_only', hint: { discipline: 'touring' } });
|
||||
// A ski tourer may climb a run only where asked to.
|
||||
const tour = planOn(world, [[world.at(0, 0), world.at(0, 2000)]], {
|
||||
discipline: 'touring',
|
||||
options: { touring_uphill_on_pistes: true },
|
||||
});
|
||||
expect(tour[0]).toMatchObject({ status: 'ok' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('a leg nothing joins', () => {
|
||||
it('SKIEXPLAIN-010: two runs that never meet: where the search stopped nearest the target', () => {
|
||||
const world = new SkiWorld();
|
||||
world.run(world.node(0, 2000, 2000), world.node(0, 1000, 1600), 1, { name: 'Links' });
|
||||
world.run(world.node(2000, 1000, 1600), world.node(2000, 0, 1200), 1, { name: 'Rechts' });
|
||||
const leg = failedLeg(planOn(world, [[world.at(0, 2000), world.at(2000, 0)]])[0]);
|
||||
expect(leg.code).toBe('disconnected');
|
||||
expect(leg.hint).toBeNull();
|
||||
expect(leg.at?.lat).toBeCloseTo(world.at(0, 1000).lat, 6);
|
||||
});
|
||||
|
||||
it('SKIEXPLAIN-011: a point off every run says how far the nearest one is, and which', () => {
|
||||
const world = new SkiWorld();
|
||||
world.run(world.node(0, 2000, 2000), world.node(0, 1000, 1600), 1, { name: 'Gipfelhang' });
|
||||
const far = world.at(0, 3000);
|
||||
const leg = failedLeg(planOn(world, [[far, world.at(0, 1000)]])[0]);
|
||||
expect(leg).toEqual({
|
||||
status: 'failed',
|
||||
code: 'not_on_piste',
|
||||
at: far,
|
||||
hint: null,
|
||||
detail: { name: 'Gipfelhang', distance_m: 1000 },
|
||||
});
|
||||
const nowhere = world.at(0, 9000);
|
||||
expect(failedLeg(planOn(world, [[world.at(0, 2000), nowhere]])[0])).toMatchObject({
|
||||
code: 'not_on_piste',
|
||||
at: nowhere,
|
||||
detail: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('SKIEXPLAIN-012: a cross-country trail both ways still plans either way', () => {
|
||||
const world = new SkiWorld();
|
||||
world.nordic(world.node(0, 0, 1200), world.node(1000, 0, 1205), { fwd: NORDIC_BOTH, back: NORDIC_BOTH });
|
||||
const there = planOn(world, [[world.at(0, 0), world.at(1000, 0)]], { discipline: 'cross_country' });
|
||||
const back = planOn(world, [[world.at(1000, 0), world.at(0, 0)]], { discipline: 'cross_country' });
|
||||
expect([there[0]?.status, back[0]?.status]).toEqual(['ok', 'ok']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* The invariant sweep (spec 12.3): random point pairs on every area at hand,
|
||||
* for every discipline. Whatever the points, a leg is planned or failed, never
|
||||
* thrown; and a planned leg only uses an edge in a direction its uses allow,
|
||||
* enters a lift by its boarding and leaves it by its exit, keeps to the
|
||||
* difficulty limit, never climbs a run, takes no link longer than 120 m, runs
|
||||
* as one line from stretch to stretch, and its totals are its stretches added
|
||||
* up.
|
||||
*/
|
||||
import { SkiRouter } from '../../../../src/nest/ski-routing/engine/plan';
|
||||
import { compileProfile, Mode } from '../../../../src/nest/ski-routing/engine/profile';
|
||||
import { LEG_TIME_MS, searchPath, type Step } from '../../../../src/nest/ski-routing/engine/router';
|
||||
import { SNAP_RADIUS_M, snapPoint } from '../../../../src/nest/ski-routing/engine/snap';
|
||||
import { stitchGraphs, type SkiNet } from '../../../../src/nest/ski-routing/engine/stitch';
|
||||
import { decodeSkiGraph } from '../../../../src/nest/ski-routing/ski-graph';
|
||||
import { Kind, Lift } from '../../../../src/nest/ski-routing/ski-graph.contract';
|
||||
import { profileOf } from '../../../../src/nest/ski-routing/ski-routing.service';
|
||||
import { SkiWorld } from '../../../helpers/ski-world';
|
||||
import { SKI_DISCIPLINES, skiRouteRequestSchema, type SkiRouteLeg } from '@trek/shared';
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const PAIRS = 500;
|
||||
|
||||
/** A small, fixed random sequence, so a failing pair can be found again. */
|
||||
function random(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = state;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/** A resort of everything: lifts of three kinds, runs of every grade, a link, a nordic loop, a winter path. */
|
||||
function resort(): SkiNet {
|
||||
const world = new SkiWorld();
|
||||
const valley = world.node(0, 0, 1200);
|
||||
const mid = world.node(400, 1200, 1700);
|
||||
const top = world.node(0, 2400, 2300);
|
||||
const shoulder = world.node(-600, 1600, 1900);
|
||||
const lake = world.node(1500, 100, 1210);
|
||||
const village = world.node(2600, 0, 1215);
|
||||
world.lift(valley, mid, { name: 'Talbahn', type: Lift.GONDOLA, down: true, cap: 2400 });
|
||||
world.lift(mid, top, { name: 'Gipfelsessel', type: Lift.CHAIR_DETACHABLE });
|
||||
world.lift(shoulder, top, { name: 'Schlepper', type: Lift.TBAR });
|
||||
world.run(top, mid, 2, { name: 'Rote' });
|
||||
world.run(top, shoulder, 4, { name: 'Expert' });
|
||||
world.run(shoulder, valley, 1, { name: 'Blaue', via: [[-400, 800]] });
|
||||
world.run(mid, valley, 0, { name: 'Kinderland' });
|
||||
world.run(top, valley, 5, { name: 'Freeride', via: [[-900, 1200]] });
|
||||
const gap = world.node(30, 0, 1201);
|
||||
world.link(valley, gap);
|
||||
world.nordic(gap, lake, { name: 'Seeloipe' });
|
||||
world.nordic(lake, village, { name: 'Dorfloipe' });
|
||||
world.edge(lake, mid, { kind: Kind.HIKE, fwd: 0x380, back: 0x380, name: 'Winterweg' });
|
||||
return stitchGraphs([world.graph()]);
|
||||
}
|
||||
|
||||
function golden(): SkiNet {
|
||||
return stitchGraphs([decodeSkiGraph(readFileSync(join(__dirname, '../../../fixtures/ski/golden-v1.sgr')))]);
|
||||
}
|
||||
|
||||
function box(net: SkiNet) {
|
||||
let minLat = 90;
|
||||
let minLng = 180;
|
||||
let maxLat = -90;
|
||||
let maxLng = -180;
|
||||
for (let i = 0; i < net.nodeCount; i++) {
|
||||
minLat = Math.min(minLat, net.nodeLat[i] as number);
|
||||
maxLat = Math.max(maxLat, net.nodeLat[i] as number);
|
||||
minLng = Math.min(minLng, net.nodeLng[i] as number);
|
||||
maxLng = Math.max(maxLng, net.nodeLng[i] as number);
|
||||
}
|
||||
const pad = 0.001;
|
||||
return { minLat: minLat - pad, minLng: minLng - pad, maxLat: maxLat + pad, maxLng: maxLng + pad };
|
||||
}
|
||||
|
||||
const RIDE: ReadonlySet<number> = new Set([Kind.LIFT, Kind.RAIL]);
|
||||
const INTO_RIDE: ReadonlySet<number> = new Set([Kind.BOARD, Kind.LIFT, Kind.RAIL]);
|
||||
const OUT_OF_RIDE: ReadonlySet<number> = new Set([Kind.ALIGHT, Kind.LIFT, Kind.RAIL]);
|
||||
const HARD: ReadonlySet<string | null> = new Set(['expert', 'freeride', 'extreme']);
|
||||
|
||||
/** The step-level rules of a found path, as the search left it. */
|
||||
function checkSteps(net: SkiNet, steps: readonly Step[], modeOf: (step: Step) => number, limit: number): void {
|
||||
const moving = steps.filter((step) => step.from !== step.to);
|
||||
moving.forEach((step, index) => {
|
||||
const mode = modeOf(step);
|
||||
const uses = step.dir === 0 ? net.edgeFwd[step.edge] : net.edgeBack[step.edge];
|
||||
expect(mode).not.toBe(Mode.NONE);
|
||||
const kind = net.edgeKind[step.edge] as number;
|
||||
// A walker crosses a short run whichever way it is drawn; every other way needs its uses.
|
||||
if (mode !== Mode.WALK || (kind !== Kind.RUN && kind !== Kind.AREA)) expect(uses).toBeGreaterThan(0);
|
||||
if (RIDE.has(kind)) {
|
||||
const before = moving[index - 1];
|
||||
const after = moving[index + 1];
|
||||
expect(before !== undefined && INTO_RIDE.has(net.edgeKind[before.edge] as number)).toBe(true);
|
||||
expect(after !== undefined && OUT_OF_RIDE.has(net.edgeKind[after.edge] as number)).toBe(true);
|
||||
}
|
||||
if (mode === Mode.DOWNHILL) {
|
||||
const climb = step.dir === 0 ? net.edgeUp[step.edge] : net.edgeDown[step.edge];
|
||||
expect(climb).toBeLessThanOrEqual(15);
|
||||
const diff = net.edgeDiff[step.edge] as number;
|
||||
if (kind === Kind.RUN || kind === Kind.AREA) expect(diff === 255 || diff <= limit).toBe(true);
|
||||
}
|
||||
if (kind === Kind.LINK) expect(net.edgeLen[step.edge]).toBeLessThanOrEqual(120);
|
||||
});
|
||||
}
|
||||
|
||||
/** The contract-level rules of an answered leg. */
|
||||
function checkLeg(leg: SkiRouteLeg | undefined): void {
|
||||
expect(['ok', 'failed']).toContain(leg?.status);
|
||||
if (leg?.status !== 'ok') return;
|
||||
const total = leg.seconds.ski + leg.seconds.lift + leg.seconds.wait + leg.seconds.walk;
|
||||
const summed = leg.segments.reduce((sum, segment) => sum + segment.seconds + segment.wait_seconds, 0);
|
||||
expect(Math.abs(total - summed)).toBeLessThan(1);
|
||||
for (let i = 1; i < leg.segments.length; i++) {
|
||||
expect(leg.segments[i]?.from).toBe(leg.segments[i - 1]?.to);
|
||||
}
|
||||
for (const segment of leg.segments) {
|
||||
expect(segment.from).toBeLessThanOrEqual(segment.to);
|
||||
expect(segment.to).toBeLessThan(leg.geometry.length);
|
||||
}
|
||||
expect(leg.segments.some((s) => s.kind === 'run' && HARD.has(s.difficulty))).toBe(false);
|
||||
}
|
||||
|
||||
describe.each([
|
||||
['the golden area', golden],
|
||||
['a resort of everything', resort],
|
||||
])('the invariant sweep on %s', (_name, build) => {
|
||||
it.each(SKI_DISCIPLINES.map((discipline) => [discipline]))(
|
||||
'SKIINV-001: %s, random pairs: planned or failed, and every planned leg keeps the rules',
|
||||
(discipline) => {
|
||||
const net = build();
|
||||
const router = new SkiRouter(net);
|
||||
const area = box(net);
|
||||
const next = random(discipline.length * 7919 + net.edgeCount);
|
||||
const point = () => ({
|
||||
lat: area.minLat + (area.maxLat - area.minLat) * next(),
|
||||
lng: area.minLng + (area.maxLng - area.minLng) * next(),
|
||||
});
|
||||
const request = skiRouteRequestSchema.parse({ legs: [{ from: point(), to: point() }], discipline });
|
||||
const profile = profileOf(request);
|
||||
const costs = compileProfile(profile, net);
|
||||
const modeOf = (step: Step) =>
|
||||
(step.dir === 0 ? costs.modeFwd[step.edge] : costs.modeBack[step.edge]) as number;
|
||||
let planned = 0;
|
||||
for (let pair = 0; pair < PAIRS; pair++) {
|
||||
const from = point();
|
||||
const to = point();
|
||||
const [leg] = router.plan({ legs: [{ from, to, continues: false }], profile, alternatives: 0 }, ['w:1']);
|
||||
checkLeg(leg);
|
||||
if (leg?.status !== 'ok') continue;
|
||||
planned++;
|
||||
const radius = SNAP_RADIUS_M[discipline];
|
||||
const starts = snapPoint(net, costs, from.lat, from.lng, radius, 'from');
|
||||
const ends = snapPoint(net, costs, to.lat, to.lng, radius, 'to');
|
||||
const budget = { maxSettled: 400_000, deadline: Date.now() + LEG_TIME_MS };
|
||||
const found = searchPath(net, costs, starts, ends, to, budget);
|
||||
expect(found.status).toBe('ok');
|
||||
if (found.status === 'ok') checkSteps(net, found.path.steps, modeOf, 2);
|
||||
}
|
||||
// The sweep would prove nothing if no pair were ever planned.
|
||||
if (discipline === 'alpine') expect(planned).toBeGreaterThan(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,321 @@
|
||||
/**
|
||||
* The cost model of the piste router (spec 8): which discipline may travel an
|
||||
* edge in which direction, how long it takes, and what the search weighs it
|
||||
* at. Every case is one edge of a world drawn for it, read through the
|
||||
* network the router searches.
|
||||
*/
|
||||
import {
|
||||
boardWaitSeconds,
|
||||
compileProfile,
|
||||
difficultyAllowed,
|
||||
dismountSeconds,
|
||||
edgeCost,
|
||||
edgeSeconds,
|
||||
liftAllowed,
|
||||
liftClassOf,
|
||||
liftDownAllowed,
|
||||
Mode,
|
||||
travelMode,
|
||||
type SkiProfile,
|
||||
} from '../../../../src/nest/ski-routing/engine/profile';
|
||||
import { stitchGraphs, type SkiNet } from '../../../../src/nest/ski-routing/engine/stitch';
|
||||
import { EdgeFlag, Groom, Kind, Lift, NodeFlag, Use } from '../../../../src/nest/ski-routing/ski-graph.contract';
|
||||
import { profileOf } from '../../../../src/nest/ski-routing/ski-routing.service';
|
||||
import { NORDIC_BOTH, RUN_DOWN, SkiWorld, type EdgeOptions } from '../../../helpers/ski-world';
|
||||
import { skiRouteRequestSchema, type SkiDiscipline, type SkiRouteOptionsInput, type SkiTechnique } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const P = { lat: 46, lng: 7 };
|
||||
|
||||
function profile(discipline: SkiDiscipline, options: SkiRouteOptionsInput = {}, technique: SkiTechnique | null = null) {
|
||||
const request = skiRouteRequestSchema.parse({ legs: [{ from: P, to: P }], discipline, technique, options });
|
||||
return profileOf(request);
|
||||
}
|
||||
|
||||
/** One edge from a node `ele0` high to one 1000 m north and `ele1` high, with the options given. */
|
||||
function oneEdge(options: EdgeOptions, ele0 = 1500, ele1 = 1400, nodeFlags = 0): SkiNet {
|
||||
const world = new SkiWorld();
|
||||
const a = world.node(0, 0, ele0);
|
||||
const b = world.node(0, 1000, ele1, { flags: nodeFlags });
|
||||
world.edge(a, b, options);
|
||||
return stitchGraphs([world.graph()]);
|
||||
}
|
||||
|
||||
const run = (diff: number, extra: EdgeOptions = {}) =>
|
||||
oneEdge({ kind: Kind.RUN, fwd: RUN_DOWN, back: 0, diff, ...extra });
|
||||
|
||||
describe('who may travel an edge (spec 8.3)', () => {
|
||||
it('SKIPROF-001: a downhill skier skis a run down within the limit, never up, and walks a link either way', () => {
|
||||
const alpine = profile('alpine');
|
||||
expect(travelMode(alpine, run(2), 0, 0)).toBe(Mode.DOWNHILL);
|
||||
expect(travelMode(alpine, run(2), 0, 1)).toBe(Mode.NONE);
|
||||
expect(travelMode(alpine, run(3), 0, 0)).toBe(Mode.NONE);
|
||||
expect(travelMode(profile('alpine', { max_difficulty: 'advanced' }), run(3), 0, 0)).toBe(Mode.DOWNHILL);
|
||||
const link = oneEdge({ kind: Kind.LINK, fwd: Use.WALK, back: Use.WALK });
|
||||
expect(travelMode(alpine, link, 0, 1)).toBe(Mode.WALK);
|
||||
const track = oneEdge({ kind: Kind.HIKE, fwd: Use.WALK | Use.WINTER_HIKE, back: Use.WALK | Use.WINTER_HIKE });
|
||||
expect(travelMode(alpine, track, 0, 0)).toBe(Mode.NONE);
|
||||
// Only while explaining: walking up a run tells "no way up" from "no way".
|
||||
expect(travelMode({ ...alpine, walkUphill: true }, run(2), 0, 1)).toBe(Mode.WALK);
|
||||
});
|
||||
|
||||
it('SKIPROF-002: a run of unknown difficulty is allowed, freeride and extreme only when switched on', () => {
|
||||
const base = profile('alpine').options;
|
||||
expect(difficultyAllowed(base, 255)).toBe(true);
|
||||
expect(difficultyAllowed(base, 5)).toBe(false);
|
||||
expect(difficultyAllowed({ ...base, allow_freeride: true }, 6)).toBe(true);
|
||||
expect(difficultyAllowed({ ...base, max_difficulty: 'novice' }, 1)).toBe(false);
|
||||
expect(difficultyAllowed({ ...base, max_difficulty: 'expert' }, 4)).toBe(true);
|
||||
});
|
||||
|
||||
it('SKIPROF-003: lifts by class, the rider and the discipline', () => {
|
||||
const types = [Lift.NONE, Lift.CABLE_CAR, Lift.GONDOLA, Lift.MIXED, Lift.CHAIR_FIXED, Lift.TBAR, Lift.MAGIC_CARPET];
|
||||
expect([...types, Lift.RACK].map(liftClassOf)).toEqual([
|
||||
null,
|
||||
'cable_car',
|
||||
'gondola',
|
||||
'gondola',
|
||||
'open_chair',
|
||||
'drag',
|
||||
'drag',
|
||||
'rail',
|
||||
]);
|
||||
const alpine = profile('alpine');
|
||||
expect(liftAllowed(alpine, 'drag')).toBe(true);
|
||||
expect(liftAllowed(profile('alpine', { avoid_lifts: ['drag'] }), 'drag')).toBe(false);
|
||||
expect(liftAllowed(profile('alpine', { use_lifts: false }), 'gondola')).toBe(false);
|
||||
expect(liftAllowed(alpine, null)).toBe(false);
|
||||
const nordic = profile('cross_country', { use_lifts: true });
|
||||
expect(liftAllowed(nordic, 'gondola')).toBe(true);
|
||||
expect(liftAllowed(nordic, 'open_chair')).toBe(false);
|
||||
expect(liftAllowed(profile('cross_country'), 'gondola')).toBe(false);
|
||||
const walker = profile('winter_hike', { use_lifts: true });
|
||||
expect(liftAllowed(walker, 'open_chair')).toBe(true);
|
||||
expect(liftAllowed(walker, 'drag')).toBe(false);
|
||||
expect(liftDownAllowed(alpine, 'gondola')).toBe(true);
|
||||
expect(liftDownAllowed(alpine, 'drag')).toBe(false);
|
||||
expect(liftDownAllowed(profile('alpine', { allow_lift_down: false }), 'gondola')).toBe(false);
|
||||
});
|
||||
|
||||
it('SKIPROF-004: a lift, its boarding and its exit are ridden up, and down only where allowed', () => {
|
||||
const world = new SkiWorld();
|
||||
const valley = world.node(0, 0, 1200);
|
||||
const top = world.node(0, 1500, 2000);
|
||||
const { ride, board, alight } = world.lift(valley, top, { type: Lift.GONDOLA, down: true });
|
||||
const net = stitchGraphs([world.graph()]);
|
||||
const alpine = profile('alpine');
|
||||
expect(travelMode(alpine, net, ride, 0)).toBe(Mode.LIFT);
|
||||
expect(travelMode(alpine, net, ride, 1)).toBe(Mode.LIFT_DOWN);
|
||||
expect(travelMode(alpine, net, board, 0)).toBe(Mode.BOARD);
|
||||
expect(travelMode(alpine, net, alight, 0)).toBe(Mode.ALIGHT);
|
||||
expect(travelMode(alpine, net, board, 1)).toBe(Mode.NONE);
|
||||
// The boarding at the top and the exit at the bottom, of the ride down.
|
||||
expect(travelMode(alpine, net, 3, 0)).toBe(Mode.BOARD_DOWN);
|
||||
expect(travelMode(alpine, net, 4, 0)).toBe(Mode.ALIGHT_DOWN);
|
||||
expect(travelMode(profile('alpine', { allow_lift_down: false }), net, ride, 1)).toBe(Mode.NONE);
|
||||
expect(travelMode(profile('touring'), net, ride, 0)).toBe(Mode.NONE);
|
||||
});
|
||||
|
||||
it('SKIPROF-005: a cross-country skier keeps to the technique, the grooming and the lights asked for', () => {
|
||||
const skatingOnly = oneEdge({ kind: Kind.NORDIC, fwd: Use.NORDIC_SKATING, back: Use.NORDIC_SKATING, groom: 2 });
|
||||
expect(travelMode(profile('cross_country', {}, 'classic'), skatingOnly, 0, 0)).toBe(Mode.NONE);
|
||||
expect(travelMode(profile('cross_country', {}, 'skating'), skatingOnly, 0, 0)).toBe(Mode.NORDIC);
|
||||
expect(travelMode(profile('cross_country', {}, 'unknown'), skatingOnly, 0, 1)).toBe(Mode.NORDIC);
|
||||
const wild = oneEdge({ kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: Groom.BACKCOUNTRY });
|
||||
expect(travelMode(profile('cross_country', { groomed_only: true }), wild, 0, 0)).toBe(Mode.NONE);
|
||||
expect(travelMode(profile('cross_country'), wild, 0, 0)).toBe(Mode.NORDIC);
|
||||
const dark = oneEdge({ kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: 3 });
|
||||
expect(travelMode(profile('cross_country', { lit_only: true }), dark, 0, 0)).toBe(Mode.NONE);
|
||||
const lit = oneEdge({ kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: 3, flags: EdgeFlag.LIT });
|
||||
expect(travelMode(profile('cross_country', { lit_only: true }), lit, 0, 0)).toBe(Mode.NORDIC);
|
||||
const link = oneEdge({ kind: Kind.LINK, fwd: Use.WALK, back: Use.WALK });
|
||||
expect(travelMode(profile('cross_country'), link, 0, 0)).toBe(Mode.WALK);
|
||||
expect(travelMode(profile('cross_country'), run(1), 0, 0)).toBe(Mode.NONE);
|
||||
});
|
||||
|
||||
it('SKIPROF-006: a ski tourer climbs skitour ways, skis runs down and climbs a piste only when asked to', () => {
|
||||
const touring = profile('touring');
|
||||
const both = Use.SKITOUR_UP | Use.SKITOUR_DOWN;
|
||||
const climb = oneEdge({ kind: Kind.SKITOUR, fwd: both, back: Use.SKITOUR_UP }, 1500, 1900);
|
||||
expect(travelMode(touring, climb, 0, 0)).toBe(Mode.SKITOUR_UP);
|
||||
expect(travelMode(touring, climb, 0, 1)).toBe(Mode.SKITOUR_UP);
|
||||
const descent = oneEdge({ kind: Kind.SKITOUR, fwd: both, back: 0 }, 1900, 1500);
|
||||
expect(travelMode(touring, descent, 0, 0)).toBe(Mode.SKITOUR_DOWN);
|
||||
expect(travelMode(touring, run(2), 0, 0)).toBe(Mode.SKITOUR_DOWN);
|
||||
expect(travelMode(touring, run(2), 0, 1)).toBe(Mode.NONE);
|
||||
expect(travelMode(profile('touring', { touring_uphill_on_pistes: true }), run(2), 0, 1)).toBe(Mode.UPHILL_PISTE);
|
||||
expect(travelMode(touring, run(4), 0, 0)).toBe(Mode.NONE);
|
||||
const snowshoeTrail = oneEdge({ kind: Kind.HIKE, fwd: Use.SNOWSHOE, back: Use.SNOWSHOE });
|
||||
expect(travelMode(touring, snowshoeTrail, 0, 1)).toBe(Mode.SKITOUR_UP);
|
||||
});
|
||||
|
||||
it('SKIPROF-007: snowshoes and boots keep to their trails and cross a run only where it is short', () => {
|
||||
const onFoot = Use.SNOWSHOE | Use.WINTER_HIKE;
|
||||
const trail = oneEdge({ kind: Kind.HIKE, fwd: onFoot, back: onFoot });
|
||||
expect(travelMode(profile('snowshoe'), trail, 0, 1)).toBe(Mode.SNOWSHOE);
|
||||
expect(travelMode(profile('winter_hike'), trail, 0, 1)).toBe(Mode.HIKE);
|
||||
const shoeOnly = oneEdge({ kind: Kind.HIKE, fwd: Use.SNOWSHOE, back: Use.SNOWSHOE });
|
||||
expect(travelMode(profile('winter_hike'), shoeOnly, 0, 0)).toBe(Mode.NONE);
|
||||
// The world's edges are 1000 m long: too long to cross on foot.
|
||||
expect(travelMode(profile('snowshoe'), run(1), 0, 0)).toBe(Mode.NONE);
|
||||
const world = new SkiWorld();
|
||||
world.run(world.node(0, 0, 1500), world.node(0, 60, 1495), 1);
|
||||
const short = stitchGraphs([world.graph()]);
|
||||
expect(travelMode(profile('snowshoe'), short, 0, 1)).toBe(Mode.WALK);
|
||||
expect(travelMode(profile('winter_hike'), short, 0, 0)).toBe(Mode.WALK);
|
||||
const link = oneEdge({ kind: Kind.LINK, fwd: Use.WALK, back: Use.WALK });
|
||||
expect(travelMode(profile('winter_hike'), link, 0, 0)).toBe(Mode.WALK);
|
||||
expect(travelMode(profile('snowshoe'), link, 0, 0)).toBe(Mode.WALK);
|
||||
});
|
||||
});
|
||||
|
||||
describe('how long it takes (spec 8.1)', () => {
|
||||
it('SKIPROF-010: a run by its difficulty, moguls, open slopes, the pace and the board', () => {
|
||||
const alpine = profile('alpine');
|
||||
expect(edgeSeconds(alpine, run(2), 0, 0, Mode.DOWNHILL)).toBeCloseTo(1000 / 8.5, 3);
|
||||
expect(edgeSeconds(alpine, run(0), 0, 0, Mode.DOWNHILL)).toBeCloseTo(250, 3);
|
||||
expect(edgeSeconds(alpine, run(255), 0, 0, Mode.DOWNHILL)).toBeCloseTo(1000 / 7, 3);
|
||||
expect(edgeSeconds(alpine, run(2, { groom: Groom.MOGUL }), 0, 0, Mode.DOWNHILL)).toBeCloseTo(1000 / 6.8, 3);
|
||||
const area = oneEdge({ kind: Kind.AREA, fwd: RUN_DOWN, back: 0, diff: 1 });
|
||||
expect(edgeSeconds(alpine, area, 0, 0, Mode.DOWNHILL)).toBeCloseTo(1000 / 5.6, 3);
|
||||
expect(edgeSeconds(profile('alpine', { pace: 'sporty' }), run(1), 0, 0, Mode.DOWNHILL)).toBeCloseTo(1000 / 9.1, 3);
|
||||
expect(edgeSeconds(profile('snowboard'), run(1), 0, 0, Mode.DOWNHILL)).toBeCloseTo(1000 / 6.65, 3);
|
||||
const flat = run(1, { flags: EdgeFlag.FLAT_FOR_BOARD });
|
||||
expect(edgeSeconds(profile('snowboard'), flat, 0, 0, Mode.DOWNHILL)).toBeCloseTo(1000 / 1.5, 3);
|
||||
});
|
||||
|
||||
it('SKIPROF-011: a lift by its ride time, else by its speed; the wait by type and capacity; 15 s to get off', () => {
|
||||
const alpine = profile('alpine');
|
||||
const timed = oneEdge({ kind: Kind.LIFT, fwd: Use.LIFT_UP, lift: Lift.GONDOLA, liftSec: 300 });
|
||||
expect(edgeSeconds(alpine, timed, 0, 0, Mode.LIFT)).toBe(300);
|
||||
const fixed = oneEdge({ kind: Kind.LIFT, fwd: Use.LIFT_UP, lift: Lift.CHAIR_FIXED });
|
||||
expect(edgeSeconds(alpine, fixed, 0, 0, Mode.LIFT)).toBeCloseTo(1000 / 2.3, 3);
|
||||
expect(boardWaitSeconds(Lift.CHAIR_DETACHABLE, 0)).toBe(120);
|
||||
expect(boardWaitSeconds(Lift.GONDOLA, 2400)).toBe(90);
|
||||
expect(boardWaitSeconds(Lift.CABLE_CAR, 3000)).toBe(240);
|
||||
expect(boardWaitSeconds(Lift.FUNICULAR, 0)).toBe(240);
|
||||
expect(boardWaitSeconds(Lift.TBAR, 0)).toBe(60);
|
||||
expect(boardWaitSeconds(Lift.MAGIC_CARPET, 0)).toBe(30);
|
||||
expect(edgeSeconds(alpine, fixed, 0, 0, Mode.ALIGHT)).toBe(15);
|
||||
});
|
||||
|
||||
it('SKIPROF-012: cross-country by technique and gradient, walking with its climb, touring and hiking', () => {
|
||||
const flatTrail = oneEdge({ kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: 3 }, 1500, 1500);
|
||||
// On the flat Tobler's factor is 1.
|
||||
expect(edgeSeconds(profile('cross_country', {}, 'classic'), flatTrail, 0, 0, Mode.NORDIC)).toBeCloseTo(400, 3);
|
||||
expect(edgeSeconds(profile('cross_country', {}, 'skating'), flatTrail, 0, 0, Mode.NORDIC)).toBeCloseTo(
|
||||
1000 / 3.3,
|
||||
3,
|
||||
);
|
||||
const steep = oneEdge({ kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: 3 }, 1500, 1600);
|
||||
const up = edgeSeconds(profile('cross_country', {}, 'classic'), steep, 0, 0, Mode.NORDIC);
|
||||
const down = edgeSeconds(profile('cross_country', {}, 'classic'), steep, 0, 1, Mode.NORDIC);
|
||||
expect(up).toBeGreaterThan(400);
|
||||
expect(down).toBeLessThan(up);
|
||||
const walk = oneEdge({ kind: Kind.LINK, fwd: Use.WALK, back: Use.WALK }, 1500, 1530);
|
||||
expect(edgeSeconds(profile('alpine'), walk, 0, 0, Mode.WALK)).toBeCloseTo(1000 / 0.7 + 360, 3);
|
||||
const climb = oneEdge({ kind: Kind.SKITOUR, fwd: Use.SKITOUR_UP, back: Use.SKITOUR_UP }, 1500, 1850);
|
||||
// DIN 33466: 900 s for the kilometre, 3600 s for the 350 m: the longer plus half the shorter.
|
||||
expect(edgeSeconds(profile('touring'), climb, 0, 0, Mode.SKITOUR_UP)).toBeCloseTo(3600 + 450, 3);
|
||||
expect(edgeSeconds(profile('touring'), climb, 0, 1, Mode.SKITOUR_DOWN)).toBeCloseTo(1000 / 3, 3);
|
||||
expect(edgeSeconds(profile('touring'), run(1), 0, 0, Mode.SKITOUR_DOWN)).toBeCloseTo(1000 / 7, 3);
|
||||
const shoe = oneEdge({ kind: Kind.HIKE, fwd: Use.SNOWSHOE, back: Use.SNOWSHOE }, 1500, 1750);
|
||||
expect(edgeSeconds(profile('snowshoe'), shoe, 0, 0, Mode.SNOWSHOE)).toBeCloseTo(3600 + 600, 3);
|
||||
const path = oneEdge({ kind: Kind.HIKE, fwd: Use.WINTER_HIKE, back: Use.WINTER_HIKE }, 1500, 1500);
|
||||
expect(edgeSeconds(profile('winter_hike'), path, 0, 0, Mode.HIKE)).toBeCloseTo(900 / 0.85, 3);
|
||||
expect(edgeSeconds(profile('alpine'), path, 0, 0, Mode.NONE)).toBe(Infinity);
|
||||
});
|
||||
|
||||
it('SKIPROF-013: getting out of the bindings where the map says so adds to the edge arriving there', () => {
|
||||
const always = oneEdge({ kind: Kind.LINK, fwd: Use.WALK, back: Use.WALK }, 1500, 1500, NodeFlag.DISMOUNT_YES);
|
||||
expect(dismountSeconds(always, 1)).toBe(30);
|
||||
expect(dismountSeconds(always, 0)).toBe(0);
|
||||
const sometimes = oneEdge({ kind: Kind.LINK }, 1500, 1500, NodeFlag.DISMOUNT_SOMETIMES);
|
||||
expect(dismountSeconds(sometimes, 1)).toBe(10);
|
||||
const costs = compileProfile(profile('alpine'), always);
|
||||
expect(costs.timeFwd[0]).toBeCloseTo(1000 / 0.7 + 30, 3);
|
||||
expect(costs.timeBack[0]).toBeCloseTo(1000 / 0.7, 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('what the search weighs (spec 8.2)', () => {
|
||||
const cost = (p: SkiProfile, net: SkiNet, dir: 0 | 1 = 0) => {
|
||||
const mode = travelMode(p, net, 0, dir);
|
||||
return edgeCost(p, net, 0, dir, mode, 100);
|
||||
};
|
||||
|
||||
it('SKIPROF-020: penalties: a guessed link, riding down, the wrong way, a slope with a run, an untyped way', () => {
|
||||
const alpine = profile('alpine');
|
||||
const shortLink = oneEdge({ kind: Kind.LINK, fwd: Use.WALK, back: Use.WALK, flags: EdgeFlag.INFERRED_LINK });
|
||||
expect(cost(alpine, shortLink)).toBe(260);
|
||||
expect(cost(profile('alpine', { avoid_inferred_links: true }), shortLink)).toBe(1300);
|
||||
const world = new SkiWorld();
|
||||
world.link(world.node(0, 0, 1500), world.node(0, 30, 1500), { flags: EdgeFlag.INFERRED_LINK });
|
||||
expect(cost(alpine, stitchGraphs([world.graph()]))).toBe(130);
|
||||
const gondola = oneEdge({ kind: Kind.LIFT, fwd: Use.LIFT_UP, back: Use.LIFT_DOWN, lift: Lift.GONDOLA });
|
||||
expect(cost(alpine, gondola, 1)).toBe(300);
|
||||
const conflict = oneEdge({ kind: Kind.RUN, fwd: RUN_DOWN, back: RUN_DOWN, diff: 1, flags: EdgeFlag.DIR_CONFLICT });
|
||||
expect(cost(alpine, conflict, 0)).toBe(100);
|
||||
expect(cost(alpine, conflict, 1)).toBe(150);
|
||||
const area = oneEdge({ kind: Kind.AREA, fwd: RUN_DOWN, back: 0, diff: 1, flags: EdgeFlag.AREA_HAS_RUN });
|
||||
expect(cost(alpine, area)).toBeCloseTo(130, 6);
|
||||
const untyped = oneEdge({ kind: Kind.CONNECTION, fwd: Use.WALK | Use.DOWNHILL, flags: EdgeFlag.TYPE_UNKNOWN });
|
||||
expect(cost(alpine, untyped)).toBe(150);
|
||||
});
|
||||
|
||||
it('SKIPROF-021: a snowboarder avoids flats and surface lifts, a nordic skier the wrong way and the wild', () => {
|
||||
const board = profile('snowboard');
|
||||
expect(cost(board, run(1, { flags: EdgeFlag.FLAT_FOR_BOARD }))).toBe(300);
|
||||
const world = new SkiWorld();
|
||||
const { board: tbarBoard } = world.lift(world.node(0, 0, 1500), world.node(0, 600, 1700), { type: Lift.TBAR });
|
||||
const tbar = stitchGraphs([world.graph()]);
|
||||
expect(edgeCost(board, tbar, tbarBoard, 0, Mode.BOARD, 60)).toBe(660);
|
||||
expect(edgeCost(profile('alpine'), tbar, tbarBoard, 0, Mode.BOARD, 60)).toBe(60);
|
||||
const nordic = { kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: 1 };
|
||||
const soft = oneEdge({ ...nordic, flags: EdgeFlag.NORDIC_SOFT_ONEWAY });
|
||||
expect(cost(profile('cross_country'), soft, 1)).toBeCloseTo(110, 6);
|
||||
const wild = oneEdge({ kind: Kind.NORDIC, fwd: NORDIC_BOTH, back: NORDIC_BOTH, groom: Groom.BACKCOUNTRY });
|
||||
expect(cost(profile('cross_country', {}, 'classic'), wild)).toBe(200);
|
||||
expect(cost(profile('cross_country', {}, 'skating'), wild)).toBe(300);
|
||||
const assumed = oneEdge({ ...nordic, flags: EdgeFlag.TECHNIQUE_ASSUMED });
|
||||
expect(cost(profile('cross_country'), assumed)).toBeCloseTo(110, 6);
|
||||
const shoe = oneEdge({ kind: Kind.HIKE, fwd: Use.SNOWSHOE, back: Use.SNOWSHOE });
|
||||
expect(cost(profile('snowshoe'), shoe)).toBe(80);
|
||||
expect(cost(profile('touring', { touring_uphill_on_pistes: true }), run(1), 1)).toBe(150);
|
||||
});
|
||||
|
||||
it('SKIPROF-022: priorities: most skiing makes runs cheap and lifts dear, easiest makes the harder runs dear', () => {
|
||||
const most = profile('alpine', { priority: 'most_skiing' });
|
||||
expect(cost(most, run(1))).toBeCloseTo(100 / 1.8, 6);
|
||||
const lift = oneEdge({ kind: Kind.LIFT, fwd: Use.LIFT_UP, lift: Lift.GONDOLA });
|
||||
expect(cost(most, lift)).toBeCloseTo(120, 6);
|
||||
const easiest = profile('alpine', { priority: 'easiest', max_difficulty: 'advanced' });
|
||||
expect(cost(easiest, run(3))).toBeCloseTo(180, 6);
|
||||
expect(cost(easiest, run(2))).toBeCloseTo(150, 6);
|
||||
expect(cost(easiest, run(1))).toBeCloseTo(120, 6);
|
||||
expect(cost(easiest, run(0))).toBeCloseTo(100, 6);
|
||||
expect(cost(easiest, run(255))).toBeCloseTo(150, 6);
|
||||
});
|
||||
|
||||
it('SKIPROF-023: every edge compiled both ways, a forbidden one at Infinity, the heuristic under every edge', () => {
|
||||
const world = new SkiWorld();
|
||||
const top = world.node(0, 0, 2000);
|
||||
const valley = world.node(0, -1000, 1500);
|
||||
world.run(top, valley, 2);
|
||||
world.lift(valley, top, { sec: 200 });
|
||||
const net = stitchGraphs([world.graph()]);
|
||||
const costs = compileProfile(profile('alpine'), net);
|
||||
expect(costs.modeFwd[0]).toBe(Mode.DOWNHILL);
|
||||
expect(costs.costBack[0]).toBe(Infinity);
|
||||
for (let e = 0; e < net.edgeCount; e++) {
|
||||
for (const [cost, length] of [
|
||||
[costs.costFwd[e] as number, net.edgeLen[e] as number],
|
||||
[costs.costBack[e] as number, net.edgeLen[e] as number],
|
||||
]) {
|
||||
if (Number.isFinite(cost) && length > 0) expect(length / cost).toBeLessThanOrEqual(costs.maxSpeed);
|
||||
}
|
||||
}
|
||||
expect(costs.maxSpeed).toBeGreaterThan(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* The piste router on drawn ski areas (spec 7.4, 7.5, 12.2): runs one way,
|
||||
* lifts only through their stations, a start inside a run, the reachable one
|
||||
* of two parallel runs, legs that go on from each other, pieces of a split
|
||||
* network stitched, other ways, and the notes a planned leg carries.
|
||||
*/
|
||||
import { compileProfile } from '../../../../src/nest/ski-routing/engine/profile';
|
||||
import { searchPath } from '../../../../src/nest/ski-routing/engine/router';
|
||||
import { LIFT_SNAP_M, MAX_SNAPS, snapPoint } from '../../../../src/nest/ski-routing/engine/snap';
|
||||
import { stitchGraphs } from '../../../../src/nest/ski-routing/engine/stitch';
|
||||
import { EdgeFlag, Lift, NodeFlag } from '../../../../src/nest/ski-routing/ski-graph.contract';
|
||||
import { profileOf } from '../../../../src/nest/ski-routing/ski-routing.service';
|
||||
import { failedLeg, okLeg, planOn } from '../../../helpers/ski-plan';
|
||||
import { SkiWorld } from '../../../helpers/ski-world';
|
||||
import { skiRouteRequestSchema, skiRouteResponseSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* Testalp: a chair from the valley to the top, a red run to the middle
|
||||
* station and a blue one on down, and a black run straight down beside them.
|
||||
*/
|
||||
function testalp() {
|
||||
const world = new SkiWorld();
|
||||
const valley = world.node(0, 0, 1200);
|
||||
const top = world.node(0, 2000, 2200);
|
||||
const mid = world.node(600, 1000, 1700);
|
||||
world.lift(valley, top, { name: 'Sonnenbahn', sec: 420, cap: 2400 });
|
||||
world.run(top, mid, 2, { name: 'Rote Eins', ref: '1' });
|
||||
world.run(mid, valley, 1, { name: 'Blaue Zwei' });
|
||||
world.run(top, valley, 3, { name: 'Schwarze Wand', via: [[-300, 1000]] });
|
||||
return { world, valley: world.at(0, 0), top: world.at(0, 2000), mid: world.at(600, 1000) };
|
||||
}
|
||||
|
||||
const RED_M = Math.hypot(600, 1000);
|
||||
|
||||
describe('runs and lifts', () => {
|
||||
it('SKIROUTE-001: skis the runs within the limit, the harder one left out, at the times of the cost model', () => {
|
||||
const { world, top, valley } = testalp();
|
||||
const leg = okLeg(planOn(world, [[top, valley]])[0]);
|
||||
expect(leg.segments.map((s) => [s.kind, s.name, s.difficulty])).toEqual([
|
||||
['run', 'Rote Eins', 'intermediate'],
|
||||
['run', 'Blaue Zwei', 'easy'],
|
||||
]);
|
||||
expect(leg.segments[0]?.ref).toBe('1');
|
||||
expect(leg.distance_m).toBeCloseTo(2 * RED_M, 0);
|
||||
expect(leg.descent_m).toBe(1000);
|
||||
expect(leg.climb_m).toBe(0);
|
||||
expect(leg.seconds.ski).toBeCloseTo(RED_M / 8.5 + RED_M / 7, 3);
|
||||
expect(leg.seconds).toMatchObject({ lift: 0, wait: 0, walk: 0 });
|
||||
expect(leg.geometry[0]?.[0]).toBeCloseTo(top.lat, 6);
|
||||
expect(leg.geometry[leg.geometry.length - 1]?.[1]).toBeCloseTo(valley.lng, 6);
|
||||
expect(leg.geometry[0]?.[2]).toBe(2200);
|
||||
expect(leg.snapped_m).toEqual({ from: 0, to: 0 });
|
||||
expect(leg.area_ids).toEqual(['w:1']);
|
||||
expect(skiRouteResponseSchema.shape.legs.element.safeParse(leg).success).toBe(true);
|
||||
});
|
||||
|
||||
it('SKIROUTE-002: takes the black run once the limit allows it, it being quicker', () => {
|
||||
const { world, top, valley } = testalp();
|
||||
const leg = okLeg(planOn(world, [[top, valley]], { options: { max_difficulty: 'advanced' } })[0]);
|
||||
expect(leg.segments.map((s) => s.name)).toEqual(['Schwarze Wand']);
|
||||
expect(leg.segments[0]?.difficulty).toBe('advanced');
|
||||
});
|
||||
|
||||
it('SKIROUTE-003: goes up by the lift, boarded and left at its stations, with its wait and its ride', () => {
|
||||
const { world, top, valley } = testalp();
|
||||
const leg = okLeg(planOn(world, [[valley, top]])[0]);
|
||||
expect(leg.segments).toHaveLength(1);
|
||||
expect(leg.segments[0]).toMatchObject({
|
||||
kind: 'lift',
|
||||
name: 'Sonnenbahn',
|
||||
lift_type: 'chair_detachable',
|
||||
seconds: 435,
|
||||
wait_seconds: 90,
|
||||
difficulty: null,
|
||||
});
|
||||
expect(leg.seconds).toEqual({ ski: 0, lift: 435, wait: 90, walk: 0 });
|
||||
expect(leg.climb_m).toBe(1000);
|
||||
});
|
||||
|
||||
it('SKIROUTE-004: a start inside a run goes on down it from there, never up', () => {
|
||||
const { world, valley } = testalp();
|
||||
const halfway = world.at(300, 1500);
|
||||
const leg = okLeg(planOn(world, [[halfway, valley]])[0]);
|
||||
expect(leg.segments.map((s) => s.name)).toEqual(['Rote Eins', 'Blaue Zwei']);
|
||||
expect(leg.segments[0]?.length_m).toBeCloseTo(RED_M / 2, 0);
|
||||
expect(leg.snapped_m.from).toBeLessThan(1);
|
||||
expect(leg.geometry[0]?.[0]).toBeCloseTo(halfway.lat, 6);
|
||||
});
|
||||
|
||||
it('SKIROUTE-005: a click right beside a lift line means the lift, a click at a station that station', () => {
|
||||
const { world, valley, top } = testalp();
|
||||
const net = stitchGraphs([world.graph()]);
|
||||
const request = skiRouteRequestSchema.parse({ legs: [{ from: top, to: top }], discipline: 'alpine' });
|
||||
const costs = compileProfile(profileOf(request), net);
|
||||
const beside = world.at(25, 1000);
|
||||
expect(LIFT_SNAP_M).toBe(40);
|
||||
const from = snapPoint(net, costs, beside.lat, beside.lng, 150, 'from');
|
||||
expect(from).toHaveLength(1);
|
||||
expect(from[0]).toMatchObject({ edge: -1, startCost: 0 });
|
||||
expect(from[0]?.lat).toBeCloseTo(valley.lat, 6);
|
||||
const to = snapPoint(net, costs, beside.lat, beside.lng, 150, 'to');
|
||||
expect(to[0]?.lat).toBeCloseTo(top.lat, 6);
|
||||
const leg = okLeg(planOn(world, [[beside, top]])[0]);
|
||||
expect(leg.segments.map((s) => s.kind)).toEqual(['lift']);
|
||||
expect(leg.snapped_m.from).toBeCloseTo(Math.hypot(25, 1000), -1);
|
||||
expect(MAX_SNAPS).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('where a leg joins the network', () => {
|
||||
/** Two parallel runs 60 m apart: Ost reaches the valley station, West ends 200 m above it. */
|
||||
function parallel() {
|
||||
const world = new SkiWorld();
|
||||
const eastTop = world.node(0, 1000, 1800);
|
||||
const station = world.node(0, 0, 1300);
|
||||
const westTop = world.node(60, 1000, 1800);
|
||||
const westEnd = world.node(60, 200, 1400);
|
||||
world.run(eastTop, station, 1, { name: 'Ost' });
|
||||
world.run(westTop, westEnd, 1, { name: 'West' });
|
||||
return { world, station: world.at(0, 0) };
|
||||
}
|
||||
|
||||
it('SKIROUTE-010: of two parallel runs, the one that gets there, though the click is nearer the other', () => {
|
||||
const { world, station } = parallel();
|
||||
const leg = okLeg(planOn(world, [[world.at(35, 600), station]])[0]);
|
||||
expect(leg.segments.map((s) => s.name)).toEqual(['Ost']);
|
||||
expect(leg.snapped_m.from).toBeCloseTo(35, 0);
|
||||
});
|
||||
|
||||
it('SKIROUTE-011: a leg goes on from where the one before ended, not from wherever its point is nearest', () => {
|
||||
const { world, station } = parallel();
|
||||
const between = world.at(35, 500);
|
||||
const legs = planOn(world, [
|
||||
[world.at(35, 900), between],
|
||||
[between, station],
|
||||
]);
|
||||
// The first leg ends on West, the nearer run; from there no run reaches the station.
|
||||
expect(okLeg(legs[0]).segments.map((s) => s.name)).toEqual(['West']);
|
||||
expect(failedLeg(legs[1]).code).toBe('disconnected');
|
||||
// Planned on its own, the second leg finds Ost.
|
||||
const alone = planOn(world, [[between, station]]);
|
||||
expect(okLeg(alone[0]).segments.map((s) => s.name)).toEqual(['Ost']);
|
||||
const unchained = planOn(
|
||||
world,
|
||||
[
|
||||
[world.at(35, 900), between],
|
||||
[between, station],
|
||||
],
|
||||
{ chained: false },
|
||||
);
|
||||
expect(okLeg(unchained[1]).segments.map((s) => s.name)).toEqual(['Ost']);
|
||||
});
|
||||
|
||||
it('SKIROUTE-012: both ends on one run plan the stretch between them; ends at one spot, a leg of no length', () => {
|
||||
const { world } = parallel();
|
||||
const leg = okLeg(planOn(world, [[world.at(0, 900), world.at(0, 300)]])[0]);
|
||||
expect(leg.segments).toHaveLength(1);
|
||||
expect(leg.segments[0]?.length_m).toBeCloseTo(600, 0);
|
||||
const still = okLeg(planOn(world, [[world.at(0, 500), world.at(0, 500)]])[0]);
|
||||
expect(still.distance_m).toBe(0);
|
||||
expect(still.geometry).toHaveLength(2);
|
||||
expect(still.segments).toEqual([expect.objectContaining({ kind: 'walk', seconds: 0, length_m: 0 })]);
|
||||
expect(still.snapped_m).toEqual({ from: 0, to: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('a network in pieces (spec 6.6)', () => {
|
||||
it('SKIROUTE-020: joins pieces at their shared boundary nodes, the halo copy of an edge kept once', () => {
|
||||
const upper = new SkiWorld({ lat: 46, lng: 7 }, { areaId: 'w:5-a', build: '2026-11-02', name: 'Nordnetz' });
|
||||
const x = upper.node(0, 2000, 2000, { osm: 101 });
|
||||
const y = upper.node(0, 1000, 1600, { osm: 102, flags: NodeFlag.BOUNDARY });
|
||||
const z = upper.node(0, 0, 1200, { osm: 103, flags: NodeFlag.BOUNDARY });
|
||||
upper.run(x, y, 1, { name: 'Oben', way: 1 });
|
||||
upper.run(y, z, 1, { name: 'Unten', way: 2, flags: EdgeFlag.HALO });
|
||||
const lower = new SkiWorld({ lat: 46, lng: 7 }, { areaId: 'w:5-b', build: '2026-11-02', name: 'Nordnetz' });
|
||||
const y2 = lower.node(0, 1000, 1600, { osm: 102, flags: NodeFlag.BOUNDARY });
|
||||
const z2 = lower.node(0, 0, 1200, { osm: 103, flags: NodeFlag.BOUNDARY });
|
||||
lower.run(y2, z2, 1, { name: 'Unten', way: 2 });
|
||||
const net = stitchGraphs([upper.graph(), lower.graph()]);
|
||||
expect(net.nodeCount).toBe(3);
|
||||
expect(net.edgeCount).toBe(2);
|
||||
expect(net.areaIds).toEqual(['w:5-a', 'w:5-b']);
|
||||
// The copy without the halo flag is the one kept.
|
||||
expect(Array.from(net.edgeFlags).some((flags) => (flags & EdgeFlag.HALO) !== 0)).toBe(false);
|
||||
const leg = okLeg(planOn([upper, lower], [[upper.at(0, 2000), upper.at(0, 0)]])[0]);
|
||||
expect(leg.segments.map((s) => s.name)).toEqual(['Oben', 'Unten']);
|
||||
});
|
||||
|
||||
it('SKIROUTE-021: never joins synthetic nodes, nor nodes of one piece alone', () => {
|
||||
const world = new SkiWorld();
|
||||
const a = world.node(0, 0, 1500, { osm: -5, flags: NodeFlag.BOUNDARY });
|
||||
const b = world.node(0, -500, 1400, { osm: -5, flags: NodeFlag.BOUNDARY });
|
||||
world.run(a, b, 1);
|
||||
expect(stitchGraphs([world.graph()]).nodeCount).toBe(2);
|
||||
expect(stitchGraphs([world.graph(), world.graph()]).nodeCount).toBe(4);
|
||||
expect(() => stitchGraphs([])).toThrow('No graph to stitch');
|
||||
});
|
||||
});
|
||||
|
||||
describe('other ways and notes', () => {
|
||||
it('SKIROUTE-030: offers a second way that shares little with the first and is not much slower', () => {
|
||||
const world = new SkiWorld();
|
||||
const top = world.node(0, 2000, 2200);
|
||||
const valley = world.node(0, 0, 1200);
|
||||
const east = world.node(300, 1000, 1700);
|
||||
const west = world.node(-310, 1000, 1700);
|
||||
world.run(top, east, 1, { name: 'Ostabfahrt' });
|
||||
world.run(east, valley, 1, { name: 'Ostabfahrt' });
|
||||
world.run(top, west, 1, { name: 'Westabfahrt' });
|
||||
world.run(west, valley, 1, { name: 'Westabfahrt' });
|
||||
const leg = okLeg(planOn(world, [[world.at(0, 2000), world.at(0, 0)]], { alternatives: 2 })[0]);
|
||||
expect(leg.segments.map((s) => s.name)).toEqual(['Ostabfahrt']);
|
||||
expect(leg.alternatives).toHaveLength(1);
|
||||
expect(leg.alternatives[0]?.segments.map((s) => s.name)).toEqual(['Westabfahrt']);
|
||||
expect(leg.alternatives[0]?.seconds_total).toBeGreaterThan(leg.seconds.ski);
|
||||
expect(okLeg(planOn(world, [[world.at(0, 2000), world.at(0, 0)]])[0]).alternatives).toEqual([]);
|
||||
});
|
||||
|
||||
it('SKIROUTE-031: notes a harder run it kept clear of when that would have been clearly quicker', () => {
|
||||
const world = new SkiWorld();
|
||||
const top = world.node(0, 2000, 2200);
|
||||
const valley = world.node(0, 0, 1200);
|
||||
world.run(top, valley, 3, { name: 'Schwarze Wand' });
|
||||
world.run(top, valley, 1, { name: 'Umweg', via: [[1500, 1000]] });
|
||||
const leg = okLeg(planOn(world, [[world.at(0, 2000), world.at(0, 0)]])[0]);
|
||||
expect(leg.segments.map((s) => s.name)).toEqual(['Umweg']);
|
||||
const avoided = leg.why.find((note) => note.kind === 'avoided_difficulty');
|
||||
expect(avoided).toMatchObject({ kind: 'avoided_difficulty', level: 'advanced', name: 'Schwarze Wand' });
|
||||
expect(avoided?.kind === 'avoided_difficulty' ? avoided.saved_seconds : 0).toBeGreaterThan(200);
|
||||
// With the limit at expert nothing was avoided.
|
||||
const expert = { options: { max_difficulty: 'expert' as const } };
|
||||
const free = okLeg(planOn(world, [[world.at(0, 2000), world.at(0, 0)]], expert)[0]);
|
||||
expect(free.why.some((note) => note.kind === 'avoided_difficulty')).toBe(false);
|
||||
});
|
||||
|
||||
it('SKIROUTE-032: counts the flagged stretches a leg rests on: a guessed link, a direction from the terrain', () => {
|
||||
const world = new SkiWorld();
|
||||
const top = world.node(0, 2000, 2200);
|
||||
const gap = world.node(0, 1000, 1700);
|
||||
const after = world.node(0, 990, 1699);
|
||||
const valley = world.node(0, 0, 1200);
|
||||
world.run(top, gap, 1, { name: 'Oben', flags: EdgeFlag.DIR_FROM_DEM });
|
||||
world.link(gap, after, { flags: EdgeFlag.INFERRED_LINK });
|
||||
world.run(after, valley, 255, { name: 'Unten' });
|
||||
const leg = okLeg(planOn(world, [[world.at(0, 2000), world.at(0, 0)]])[0]);
|
||||
expect(leg.segments.map((s) => s.kind)).toEqual(['run', 'link', 'run']);
|
||||
expect(leg.segments[1]?.flags).toEqual(['inferred_link']);
|
||||
expect(leg.why).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ kind: 'flag', flag: 'dir_from_dem', count: 1 },
|
||||
{ kind: 'flag', flag: 'inferred_link', count: 1 },
|
||||
{ kind: 'flag', flag: 'difficulty_unknown', count: 1 },
|
||||
]),
|
||||
);
|
||||
expect(leg.seconds.walk).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('SKIROUTE-033: rides a funicular as rail, and a gondola down only where allowed', () => {
|
||||
const world = new SkiWorld();
|
||||
const valley = world.node(0, 0, 1600);
|
||||
const top = world.node(0, 1500, 2300);
|
||||
world.lift(valley, top, { type: Lift.FUNICULAR, name: 'Sunnegga', sec: 180 });
|
||||
const up = okLeg(planOn(world, [[world.at(0, 0), world.at(0, 1500)]])[0]);
|
||||
expect(up.segments[0]).toMatchObject({ kind: 'rail', lift_type: 'funicular', wait_seconds: 240 });
|
||||
|
||||
const gondola = new SkiWorld();
|
||||
const foot = gondola.node(0, 0, 1600);
|
||||
const summit = gondola.node(0, 1500, 2500);
|
||||
gondola.lift(foot, summit, { type: Lift.GONDOLA, name: 'Gondel', down: true });
|
||||
const down = okLeg(planOn(gondola, [[gondola.at(0, 1500), gondola.at(0, 0)]])[0]);
|
||||
expect(down.segments[0]).toMatchObject({ kind: 'lift_down', name: 'Gondel' });
|
||||
expect(down.segments[0]?.flags).toContain('ride_down');
|
||||
expect(down.why).toContainEqual({ kind: 'flag', flag: 'ride_down', count: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('the search budget', () => {
|
||||
it('SKIROUTE-040: answers timeout once it settled more nodes than allowed, and none where nothing joins', () => {
|
||||
const { world, top, valley } = testalp();
|
||||
const net = stitchGraphs([world.graph()]);
|
||||
const request = skiRouteRequestSchema.parse({ legs: [{ from: top, to: valley }], discipline: 'alpine' });
|
||||
const costs = compileProfile(profileOf(request), net);
|
||||
const starts = snapPoint(net, costs, top.lat, top.lng, 150, 'from');
|
||||
const ends = snapPoint(net, costs, valley.lat, valley.lng, 150, 'to');
|
||||
const budget = { maxSettled: 0, deadline: Date.now() + 1000 };
|
||||
expect(searchPath(net, costs, starts, ends, valley, budget).status).toBe('timeout');
|
||||
// A ski tourer rides no lift and climbs no run: from the valley nothing leads up.
|
||||
const touring = skiRouteRequestSchema.parse({ legs: [{ from: valley, to: top }], discipline: 'touring' });
|
||||
const climb = compileProfile(profileOf(touring), net);
|
||||
const none = searchPath(net, climb, ends, starts, top, { maxSettled: 100, deadline: Date.now() + 1000 });
|
||||
expect(none).toMatchObject({ status: 'none' });
|
||||
expect(none.status === 'none' ? none.nearest?.lat : null).toBeCloseTo(valley.lat, 6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* The daily look at the winter layer (spec 7.2): registered on the cron
|
||||
* registrar only, sweeping unused area files, fetching the index when the
|
||||
* host serves a new build, and fetching the kept areas whose graph changed.
|
||||
*/
|
||||
import type { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { SkiAreasJob } from '../../../../src/nest/ski-routing/ski-areas.job';
|
||||
import type { SkiAreasService, SkiIndex } from '../../../../src/nest/ski-routing/ski-areas.service';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const row = (id: string, sha: string) => ({
|
||||
row: { id, sha256: sha.repeat(64) },
|
||||
minLat: 0,
|
||||
minLng: 0,
|
||||
maxLat: 0,
|
||||
maxLng: 0,
|
||||
});
|
||||
|
||||
function setup(refreshed: 'updated' | 'unchanged' | 'refused' = 'updated') {
|
||||
const index = { areas: [row('w:1', 'a'), row('w:2', 'b'), row('w:3', 'c')] } as unknown as SkiIndex;
|
||||
const areas = {
|
||||
sweep: vi.fn().mockResolvedValue(2),
|
||||
enabled: vi.fn(() => true),
|
||||
refresh: vi.fn().mockResolvedValue(refreshed),
|
||||
index: vi.fn().mockResolvedValue(index),
|
||||
keptAreas: vi.fn().mockResolvedValue([
|
||||
{ id: 'w:1', sha8: 'aaaaaaaa' },
|
||||
{ id: 'w:2', sha8: '00000000' },
|
||||
]),
|
||||
ensureArea: vi.fn().mockResolvedValue({ file: 'x', stale: false }),
|
||||
};
|
||||
const registrar = { isEnabled: vi.fn(() => true), register: vi.fn() };
|
||||
const job = new SkiAreasJob(areas as unknown as SkiAreasService, registrar as unknown as CronRegistrarService);
|
||||
return { job, areas, registrar };
|
||||
}
|
||||
|
||||
describe('SkiAreasJob', () => {
|
||||
it('SKIJOB-001: registers once a day at 04:40, and not where the registrar runs nothing', () => {
|
||||
const { job, registrar } = setup();
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).toHaveBeenCalledWith('ski-areas', '40 4 * * *', expect.any(Function));
|
||||
registrar.register.mockClear();
|
||||
registrar.isEnabled.mockReturnValue(false);
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('SKIJOB-002: sweeps, takes a new build and fetches the kept areas it changed', async () => {
|
||||
const { job, areas } = setup('updated');
|
||||
await job.tick();
|
||||
expect(areas.sweep).toHaveBeenCalled();
|
||||
expect(areas.refresh).toHaveBeenCalled();
|
||||
expect(areas.ensureArea).toHaveBeenCalledTimes(1);
|
||||
expect(areas.ensureArea).toHaveBeenCalledWith({ id: 'w:2', sha256: 'b'.repeat(64) });
|
||||
});
|
||||
|
||||
it('SKIJOB-003: fetches nothing when the build is the same, or TREK Places is off; a failure is logged', async () => {
|
||||
const same = setup('unchanged');
|
||||
await same.job.tick();
|
||||
expect(same.areas.ensureArea).not.toHaveBeenCalled();
|
||||
const off = setup();
|
||||
off.areas.enabled.mockReturnValue(false);
|
||||
await off.job.tick();
|
||||
expect(off.areas.refresh).not.toHaveBeenCalled();
|
||||
const broken = setup();
|
||||
broken.areas.refresh.mockRejectedValue(new Error('TREK Places API 503'));
|
||||
await expect(broken.job.tick()).resolves.toBeUndefined();
|
||||
const lost = setup();
|
||||
lost.areas.index.mockResolvedValue(null);
|
||||
await lost.job.tick();
|
||||
expect(lost.areas.keptAreas).not.toHaveBeenCalled();
|
||||
const failing = setup();
|
||||
failing.areas.ensureArea.mockRejectedValue(new Error('no'));
|
||||
await expect(failing.job.tick()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* The ski areas the piste router plans on (spec 7.2, 7.3, 11): the index of
|
||||
* the Places host kept in the data folder and fetched only when its checksum
|
||||
* changed, each area's graph downloaded once however many ask, checked
|
||||
* against the index before it is kept, an older copy used while the host is
|
||||
* down, and files nobody used for 90 days swept. The host is a stub here;
|
||||
* its client is tested in trek-places.winter.test.ts.
|
||||
*/
|
||||
import { DataPathsService } from '../../../../src/nest/app-config/data-paths.service';
|
||||
import { TrekPlacesWinterService } from '../../../../src/nest/maps/trek-places-winter.service';
|
||||
import {
|
||||
areasAt,
|
||||
buildIndex,
|
||||
pickAreas,
|
||||
SkiAreasService,
|
||||
UNUSED_FOR_MS,
|
||||
} from '../../../../src/nest/ski-routing/ski-areas.service';
|
||||
import { SkiWorld } from '../../../helpers/ski-world';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { WinterIndex, WinterIndexRow, WinterMeta } from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { mkdir, mkdtemp, readdir, rm, utimes, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const sha = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');
|
||||
|
||||
const world = new SkiWorld();
|
||||
world.run(world.node(0, 1000, 1800), world.node(0, 0, 1300), 1, { name: 'Talabfahrt' });
|
||||
const GZ = world.gz();
|
||||
|
||||
function row(id: string, bbox: [number, number, number, number], bytes = GZ): WinterIndexRow {
|
||||
return {
|
||||
id,
|
||||
name: `Gebiet ${id}`,
|
||||
kind: 'resort',
|
||||
country: null,
|
||||
colourScheme: 'europe',
|
||||
bbox,
|
||||
counts: { runsKm: 1, nordicKm: 0, lifts: 0, skitourKm: 0, hikeKm: 0 },
|
||||
bytes: bytes.length,
|
||||
sha256: sha(bytes),
|
||||
};
|
||||
}
|
||||
|
||||
const ROW = row('w:100', [6.99, 45.99, 7.01, 46.01]);
|
||||
|
||||
function hosted(rows: WinterIndexRow[], build = '2026-11-02') {
|
||||
const index: WinterIndex = { build, format: 1, areas: rows };
|
||||
const json = Buffer.from(JSON.stringify(index));
|
||||
const meta: WinterMeta = {
|
||||
build,
|
||||
format: 1,
|
||||
areas: rows.length,
|
||||
indexSha: sha(json),
|
||||
sourceTimestamp: null,
|
||||
attribution: { data: '© OpenStreetMap contributors, ODbL', terrain: 'Terrain: Mapzen Terrarium' },
|
||||
};
|
||||
return { index, meta, sha256: meta.indexSha };
|
||||
}
|
||||
|
||||
let dir: string;
|
||||
let host: ReturnType<typeof hosted>;
|
||||
const winter = {
|
||||
enabled: vi.fn(() => true),
|
||||
meta: vi.fn(),
|
||||
index: vi.fn(),
|
||||
area: vi.fn(),
|
||||
};
|
||||
|
||||
async function service(): Promise<SkiAreasService> {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
SkiAreasService,
|
||||
{ provide: DataPathsService, useValue: { dataDir: dir } },
|
||||
{ provide: TrekPlacesWinterService, useValue: winter },
|
||||
],
|
||||
}).compile();
|
||||
return moduleRef.get(SkiAreasService);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), 'trek-ski-areas-'));
|
||||
host = hosted([ROW]);
|
||||
winter.enabled.mockReset().mockReturnValue(true);
|
||||
winter.meta.mockReset().mockImplementation(async () => host.meta);
|
||||
winter.index
|
||||
.mockReset()
|
||||
.mockImplementation(async () => ({ status: 'ok', index: host.index, sha256: host.sha256, dropped: 0 }));
|
||||
winter.area.mockReset().mockImplementation(async () => ({ status: 'ok', bytes: GZ, etag: ROW.sha256 }));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('the index of ski areas', () => {
|
||||
it('SKIAREA-001: fetched once and kept on disk; a later start reads it from there without asking', async () => {
|
||||
const areas = await service();
|
||||
const index = await areas.index();
|
||||
expect(index?.build).toBe('2026-11-02');
|
||||
expect(index?.areas.map((area) => area.row.id)).toEqual(['w:100']);
|
||||
expect(index?.attribution).toBe('© OpenStreetMap contributors, ODbL. Terrain: Mapzen Terrarium');
|
||||
await areas.index();
|
||||
expect(winter.meta).toHaveBeenCalledTimes(1);
|
||||
expect(await readdir(join(dir, 'ski'))).toEqual([`index-${host.meta.indexSha.slice(0, 8)}.json`]);
|
||||
|
||||
const later = await service();
|
||||
expect((await later.index())?.indexSha).toBe(host.meta.indexSha);
|
||||
expect(winter.meta).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('SKIAREA-002: none without TREK Places or the host, a broken kept file skipped', async () => {
|
||||
winter.enabled.mockReturnValue(false);
|
||||
expect(await (await service()).index()).toBeNull();
|
||||
winter.enabled.mockReturnValue(true);
|
||||
winter.meta.mockRejectedValue(new Error('TREK Places API 503'));
|
||||
expect(await (await service()).index()).toBeNull();
|
||||
await mkdir(join(dir, 'ski'), { recursive: true });
|
||||
await writeFile(join(dir, 'ski', 'index-broken00.json'), '{not json');
|
||||
expect(await (await service()).index()).toBeNull();
|
||||
});
|
||||
|
||||
it('SKIAREA-003: takes a new index only with its announced checksum and a format it reads', async () => {
|
||||
const areas = await service();
|
||||
await areas.index();
|
||||
expect(await areas.refresh()).toBe('unchanged');
|
||||
|
||||
const next = hosted([ROW, row('w:200', [8, 46, 8.01, 46.01])], '2026-11-09');
|
||||
winter.meta.mockResolvedValue(next.meta);
|
||||
winter.index.mockResolvedValueOnce({ status: 'ok', index: next.index, sha256: 'f'.repeat(64), dropped: 0 });
|
||||
expect(await areas.refresh()).toBe('refused');
|
||||
expect((await areas.index())?.build).toBe('2026-11-02');
|
||||
|
||||
winter.meta.mockResolvedValueOnce({ ...next.meta, format: 2 });
|
||||
expect(await areas.refresh()).toBe('refused');
|
||||
|
||||
winter.index.mockResolvedValueOnce({ status: 'not_modified' });
|
||||
expect(await areas.refresh()).toBe('unchanged');
|
||||
|
||||
winter.index.mockResolvedValueOnce({ status: 'ok', index: next.index, sha256: next.sha256, dropped: 1 });
|
||||
expect(await areas.refresh()).toBe('updated');
|
||||
expect((await areas.index())?.areas).toHaveLength(2);
|
||||
expect(winter.index).toHaveBeenLastCalledWith(host.meta.indexSha);
|
||||
expect(await readdir(join(dir, 'ski'))).toEqual([`index-${next.meta.indexSha.slice(0, 8)}.json`]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('an area graph', () => {
|
||||
it('SKIAREA-010: downloaded once however many ask at once, then read from disk', async () => {
|
||||
const areas = await service();
|
||||
const [a, b] = await Promise.all([areas.ensureArea(ROW), areas.ensureArea(ROW)]);
|
||||
expect(a).toEqual({ file: areas.fileOf(ROW), stale: false });
|
||||
expect(b).toEqual(a);
|
||||
expect(winter.area).toHaveBeenCalledTimes(1);
|
||||
expect(winter.area).toHaveBeenCalledWith('w:100', null);
|
||||
expect(areas.fileOf(ROW)).toMatch(/w_100@[0-9a-f]{8}\.sgr\.gz$/);
|
||||
expect(await areas.ensureArea(ROW)).toEqual(a);
|
||||
expect(winter.area).toHaveBeenCalledTimes(1);
|
||||
expect(areas.stateOf(ROW)).toBe('ready');
|
||||
});
|
||||
|
||||
it('SKIAREA-011: refuses a graph whose checksum is not the index one, and keeps nothing of it', async () => {
|
||||
const areas = await service();
|
||||
winter.area.mockResolvedValueOnce({ status: 'ok', bytes: Buffer.from('not the graph'), etag: null });
|
||||
await expect(areas.ensureArea(ROW)).rejects.toThrow("does not match the index's checksum");
|
||||
expect(existsSync(areas.fileOf(ROW))).toBe(false);
|
||||
expect(areas.stateOf(ROW)).toBe('unavailable');
|
||||
});
|
||||
|
||||
it('SKIAREA-012: an older copy stands in while the host is down; without one the download fails', async () => {
|
||||
const areas = await service();
|
||||
await areas.ensureArea(ROW);
|
||||
const changed = { ...ROW, sha256: sha('a newer build') };
|
||||
winter.area.mockRejectedValueOnce(Object.assign(new Error('TREK Places API 503'), { status: 503 }));
|
||||
expect(await areas.ensureArea(changed)).toEqual({ file: areas.fileOf(ROW), stale: true });
|
||||
const unknown = row('w:300', [8, 46, 8.01, 46.01]);
|
||||
winter.area.mockRejectedValueOnce(Object.assign(new Error('TREK Places API 404'), { status: 404 }));
|
||||
await expect(areas.ensureArea(unknown)).rejects.toThrow('TREK Places API 404');
|
||||
// An id the host does not know sends TREK for a fresh index.
|
||||
await vi.waitFor(() => expect(winter.meta).toHaveBeenCalled());
|
||||
winter.area.mockResolvedValueOnce({ status: 'not_modified' });
|
||||
await expect(areas.ensureArea(unknown)).rejects.toThrow('sent no graph');
|
||||
});
|
||||
|
||||
it('SKIAREA-013: an area loading, ready or unavailable, and unavailable while TREK Places is off', async () => {
|
||||
const areas = await service();
|
||||
let release: (value: unknown) => void = () => undefined;
|
||||
winter.area.mockImplementationOnce(
|
||||
() => new Promise((resolve) => (release = () => resolve({ status: 'ok', bytes: GZ, etag: null }))),
|
||||
);
|
||||
expect(areas.stateOf(ROW)).toBe('loading');
|
||||
const pending = areas.ensureArea(ROW);
|
||||
expect(areas.stateOf(ROW)).toBe('loading');
|
||||
release(undefined);
|
||||
await pending;
|
||||
expect(areas.stateOf(ROW)).toBe('ready');
|
||||
winter.enabled.mockReturnValue(false);
|
||||
expect(areas.enabled()).toBe(false);
|
||||
expect(areas.stateOf(row('w:400', [9, 46, 9.01, 46.01]))).toBe('unavailable');
|
||||
});
|
||||
|
||||
it('SKIAREA-014: lists the areas kept, and sweeps half writes and files unused for 90 days', async () => {
|
||||
const areas = await service();
|
||||
await areas.ensureArea(ROW);
|
||||
const old = join(dir, 'ski', 'areas', 'w_9@deadbeef.sgr.gz');
|
||||
await writeFile(old, GZ);
|
||||
const long = new Date(Date.now() - UNUSED_FOR_MS - 60_000);
|
||||
await utimes(old, long, long);
|
||||
await writeFile(join(dir, 'ski', 'areas', 'w_1@00000000.sgr.gz.tmp'), 'half');
|
||||
await writeFile(join(dir, 'ski', 'index-00000000.json.tmp'), 'half');
|
||||
expect((await areas.keptAreas()).map((kept) => kept.id).sort()).toEqual(['w:100', 'w:9']);
|
||||
expect(await areas.sweep(Date.now(), { tempOnly: true })).toBe(2);
|
||||
expect(existsSync(old)).toBe(true);
|
||||
expect(await areas.sweep(Date.now())).toBe(1);
|
||||
expect(existsSync(old)).toBe(false);
|
||||
expect(existsSync(areas.fileOf(ROW))).toBe(true);
|
||||
await areas.onApplicationBootstrap();
|
||||
await rm(join(dir, 'ski'), { recursive: true, force: true });
|
||||
expect(await areas.sweep(Date.now())).toBe(0);
|
||||
expect(await areas.keptAreas()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the areas a leg is planned on', () => {
|
||||
const index = buildIndex(
|
||||
{ build: 'b', indexSha: 'x', attribution: { data: 'd', terrain: 't' } },
|
||||
{
|
||||
build: 'b',
|
||||
format: 1,
|
||||
areas: [
|
||||
row('w:1', [7, 46, 7.02, 46.02]),
|
||||
row('w:2', [7.03, 46, 7.05, 46.02]),
|
||||
row('w:3-a', [8, 46, 8.02, 46.02]),
|
||||
row('w:3-b', [8.015, 46, 8.04, 46.02]),
|
||||
row('w:4', [7.001, 46.001, 7.003, 46.003]),
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
it('SKIAREA-020: the area holding both ends, the smaller one nearer first where two hold a point', () => {
|
||||
expect(areasAt(index, { lat: 46.002, lng: 7.002 }).map((area) => area.row.id)).toEqual(['w:4', 'w:1']);
|
||||
const pick = pickAreas(index, { from: { lat: 46.01, lng: 7.01 }, to: { lat: 46.012, lng: 7.012 } });
|
||||
expect(pick.status === 'ok' && pick.areas.map((area) => area.row.id)).toEqual(['w:1']);
|
||||
});
|
||||
|
||||
it('SKIAREA-021: no area at an end, and two areas that do not touch, are said as such', () => {
|
||||
expect(pickAreas(index, { from: { lat: 50, lng: 7 }, to: { lat: 46.01, lng: 7.01 } })).toEqual({
|
||||
status: 'no_area',
|
||||
at: { lat: 50, lng: 7 },
|
||||
});
|
||||
expect(pickAreas(index, { from: { lat: 46.01, lng: 7.01 }, to: { lat: 50, lng: 7 } }).status).toBe('no_area');
|
||||
expect(pickAreas(index, { from: { lat: 46.01, lng: 7.005 }, to: { lat: 46.01, lng: 7.045 } })).toEqual({
|
||||
status: 'cross_area',
|
||||
at: { lat: 46.01, lng: 7.045 },
|
||||
});
|
||||
});
|
||||
|
||||
it('SKIAREA-022: the pieces of one split network that touch are planned on together', () => {
|
||||
const pick = pickAreas(index, { from: { lat: 46.01, lng: 8.005 }, to: { lat: 46.01, lng: 8.035 } });
|
||||
expect(pick.status === 'ok' && pick.areas.map((area) => area.row.id)).toEqual(['w:3-a', 'w:3-b']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* SGR1, the graph format the Places host writes and TREK reads (spec 4). The
|
||||
* golden file is the writer's own (trek-places-api tests/fixtures/winter),
|
||||
* byte for byte, with every array written out beside it in golden-v1.json:
|
||||
* the reader must give exactly those arrays, the writer's two edge flags
|
||||
* beyond the first draft (17 area_has_run, 18 type_unknown) among the
|
||||
* constants, and refuse a file that is damaged, cut or of another format.
|
||||
*/
|
||||
import { stitchGraphs } from '../../../../src/nest/ski-routing/engine/stitch';
|
||||
import {
|
||||
decodeSkiGraph,
|
||||
decodeSkiGraphGz,
|
||||
poolString,
|
||||
SkiGraphFormatError,
|
||||
} from '../../../../src/nest/ski-routing/ski-graph';
|
||||
import {
|
||||
EdgeFlag,
|
||||
Kind,
|
||||
Lift,
|
||||
NO_STRING,
|
||||
SGR_FORMAT,
|
||||
Use,
|
||||
type SkiGraphData,
|
||||
} from '../../../../src/nest/ski-routing/ski-graph.contract';
|
||||
import { SkiWorld } from '../../../helpers/ski-world';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { crc32, gzipSync } from 'node:zlib';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const FIXTURES = join(__dirname, '../../../fixtures/ski');
|
||||
const GOLDEN = readFileSync(join(FIXTURES, 'golden-v1.sgr'));
|
||||
const VECTORS = JSON.parse(readFileSync(join(FIXTURES, 'golden-v1.json'), 'utf8')) as Record<string, unknown> & {
|
||||
sha256: string;
|
||||
bytes: number;
|
||||
header: Record<string, unknown>;
|
||||
strings: Record<string, string>;
|
||||
};
|
||||
/** The checksum the writer's test pins (GOLDEN_SHA256 in tests/test_winter_sgr.py). */
|
||||
const GOLDEN_SHA256 = '9dd044605b8edf85c7fcc83e9f3bdb857f1e6451d09da7238d7f3071cf6c4b67';
|
||||
|
||||
const ARRAYS: ReadonlyArray<keyof Omit<SkiGraphData, 'header' | 'strings'>> = [
|
||||
'nodeLatE7',
|
||||
'nodeLngE7',
|
||||
'nodeEle',
|
||||
'nodeFlags',
|
||||
'nodeOsm',
|
||||
'edgeA',
|
||||
'edgeB',
|
||||
'edgeLen',
|
||||
'edgeUp',
|
||||
'edgeDown',
|
||||
'edgeKind',
|
||||
'edgeFwdUses',
|
||||
'edgeBackUses',
|
||||
'edgeDiff',
|
||||
'edgeGroom',
|
||||
'edgeLift',
|
||||
'edgeLiftSec',
|
||||
'edgeLiftCap',
|
||||
'edgeFlags',
|
||||
'edgeName',
|
||||
'edgeRef',
|
||||
'edgeWay',
|
||||
'edgeGeomOff',
|
||||
'geomLatE7',
|
||||
'geomLngE7',
|
||||
'geomEle',
|
||||
];
|
||||
|
||||
/** The golden file with its head rewritten, the body as it was. */
|
||||
function withHead(change: (head: Record<string, unknown>) => void): Buffer {
|
||||
const length = GOLDEN.readUInt32LE(4);
|
||||
const head = JSON.parse(GOLDEN.toString('utf8', 8, 8 + length)) as Record<string, unknown>;
|
||||
change(head);
|
||||
const json = Buffer.from(JSON.stringify(head), 'utf8');
|
||||
const prefix = Buffer.concat([Buffer.from('SGR1', 'latin1'), Buffer.alloc(4), json]);
|
||||
prefix.writeUInt32LE(json.length, 4);
|
||||
const body = GOLDEN.subarray((8 + length + 7) & ~7);
|
||||
return Buffer.concat([prefix, Buffer.alloc((8 - (prefix.length % 8)) % 8), body]);
|
||||
}
|
||||
|
||||
/** Where the sections of a file start. */
|
||||
const bodyStart = (bytes: Buffer): number => (8 + bytes.readUInt32LE(4) + 7) & ~7;
|
||||
|
||||
/** A file whose body was changed, with its head's checksum made to fit again. */
|
||||
function reseal(bytes: Buffer): Buffer {
|
||||
const length = bytes.readUInt32LE(4);
|
||||
const head = JSON.parse(bytes.toString('utf8', 8, 8 + length)) as Record<string, unknown>;
|
||||
head.crc32 = crc32(bytes.subarray(bodyStart(bytes))) >>> 0;
|
||||
const json = Buffer.from(JSON.stringify(head), 'utf8');
|
||||
const prefix = Buffer.concat([Buffer.from('SGR1', 'latin1'), Buffer.alloc(4), json]);
|
||||
prefix.writeUInt32LE(json.length, 4);
|
||||
return Buffer.concat([prefix, Buffer.alloc((8 - (prefix.length % 8)) % 8), bytes.subarray(bodyStart(bytes))]);
|
||||
}
|
||||
|
||||
describe('the golden SGR1 file', () => {
|
||||
it('SKIGRAPH-001: is the writer file byte for byte', () => {
|
||||
expect(GOLDEN.length).toBe(VECTORS.bytes);
|
||||
expect(createHash('sha256').update(GOLDEN).digest('hex')).toBe(GOLDEN_SHA256);
|
||||
expect(VECTORS.sha256).toBe(GOLDEN_SHA256);
|
||||
});
|
||||
|
||||
it('SKIGRAPH-002: decodes to exactly the head and every array the writer wrote out', () => {
|
||||
const graph = decodeSkiGraph(GOLDEN);
|
||||
expect(graph.header).toEqual(VECTORS.header);
|
||||
for (const name of ARRAYS) {
|
||||
expect(Array.from(graph[name] as ArrayLike<number>), name).toEqual(VECTORS[name]);
|
||||
}
|
||||
expect(graph.header.format).toBe(SGR_FORMAT);
|
||||
expect(graph.header.areaId).toBe('w:100');
|
||||
});
|
||||
|
||||
it('SKIGRAPH-003: reads every string of the pool at its offset, and none for the empty offset', () => {
|
||||
const graph = decodeSkiGraph(GOLDEN);
|
||||
for (const [offset, text] of Object.entries(VECTORS.strings)) {
|
||||
expect(poolString(graph.strings, Number(offset))).toBe(text);
|
||||
}
|
||||
expect(poolString(graph.strings, NO_STRING)).toBeNull();
|
||||
expect(poolString(graph.strings, graph.strings.length + 4)).toBeNull();
|
||||
const names = new Set(Array.from(graph.edgeName, (offset) => poolString(graph.strings, offset)));
|
||||
expect(names).toEqual(new Set(['Rote Eins', 'Blaue Zwei', 'Talloipe', 'Sonnenbahn', null]));
|
||||
});
|
||||
|
||||
it('SKIGRAPH-004: holds the lift as board, ride and alight, and the use bits the contract names', () => {
|
||||
const graph = decodeSkiGraph(GOLDEN);
|
||||
const kinds = Array.from(graph.edgeKind);
|
||||
const board = kinds.indexOf(Kind.BOARD);
|
||||
const ride = kinds.indexOf(Kind.LIFT);
|
||||
const alight = kinds.indexOf(Kind.ALIGHT);
|
||||
expect(graph.edgeFwdUses[board]).toBe(Use.WALK | Use.LIFT_UP);
|
||||
expect(graph.edgeFwdUses[ride]).toBe(Use.LIFT_UP);
|
||||
expect(graph.edgeBackUses[ride]).toBe(0);
|
||||
expect(graph.edgeLift[ride]).toBe(Lift.CHAIR_DETACHABLE);
|
||||
expect(graph.edgeB[board]).toBe(graph.edgeA[ride]);
|
||||
expect(graph.edgeA[alight]).toBe(graph.edgeB[ride]);
|
||||
// Every link of the golden area is one the data does not hold.
|
||||
kinds.forEach((kind, e) => {
|
||||
if (kind === Kind.LINK) expect((graph.edgeFlags[e] as number) & EdgeFlag.INFERRED_LINK).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
it('SKIGRAPH-005: names the writer edge flags beyond the first draft', () => {
|
||||
expect(EdgeFlag.HALO).toBe(1 << 16);
|
||||
expect(EdgeFlag.AREA_HAS_RUN).toBe(1 << 17);
|
||||
expect(EdgeFlag.TYPE_UNKNOWN).toBe(1 << 18);
|
||||
});
|
||||
|
||||
it('SKIGRAPH-006: reads the file gzip-packed, as the Places host sends it', () => {
|
||||
expect(decodeSkiGraphGz(gzipSync(GOLDEN)).header).toEqual(VECTORS.header);
|
||||
expect(() => decodeSkiGraphGz(GOLDEN)).toThrow('SGR1 file is not gzip');
|
||||
});
|
||||
});
|
||||
|
||||
describe('a damaged or foreign file', () => {
|
||||
it('SKIGRAPH-010: refuses another magic, a cut file, a flipped byte and a head that is no JSON', () => {
|
||||
expect(() => decodeSkiGraph(Buffer.concat([Buffer.from('SGR2'), GOLDEN.subarray(4)]))).toThrow('Not an SGR1 file');
|
||||
expect(() => decodeSkiGraph(GOLDEN.subarray(0, 6))).toThrow('Not an SGR1 file');
|
||||
const flipped = Buffer.from(GOLDEN);
|
||||
flipped[flipped.length - 9] = (flipped[flipped.length - 9] as number) ^ 0xff;
|
||||
expect(() => decodeSkiGraph(flipped)).toThrow('SGR1 checksum differs');
|
||||
expect(() => decodeSkiGraph(GOLDEN.subarray(0, Math.floor(GOLDEN.length / 2)))).toThrow(SkiGraphFormatError);
|
||||
const longHead = Buffer.from(GOLDEN);
|
||||
longHead.writeUInt32LE(GOLDEN.length, 4);
|
||||
expect(() => decodeSkiGraph(longHead)).toThrow('SGR1 head runs past the end of the file');
|
||||
const notJson = Buffer.from(GOLDEN);
|
||||
notJson.write('{', 8 + 1, 'latin1');
|
||||
expect(() => decodeSkiGraph(notJson)).toThrow('SGR1 head is not JSON');
|
||||
});
|
||||
|
||||
it('SKIGRAPH-011: a newer format is refused as such, so the graph kept before stays in use', () => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
decodeSkiGraph(withHead((head) => (head.format = 2)));
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(SkiGraphFormatError);
|
||||
expect((caught as SkiGraphFormatError).unknownFormat).toBe(true);
|
||||
expect((caught as Error).message).toBe('SGR1 format 2 is not 1');
|
||||
});
|
||||
|
||||
it('SKIGRAPH-012: refuses a head without its counts and a body shorter than the head says', () => {
|
||||
const noNodes = withHead((head) => delete head.nodeCount);
|
||||
expect(() => decodeSkiGraph(noNodes)).toThrow('SGR1 head has no valid node count');
|
||||
expect(() => decodeSkiGraph(withHead((head) => (head.crc32 = -1)))).toThrow('SGR1 head has no valid checksum');
|
||||
expect(() => decodeSkiGraph(withHead((head) => (head.geomCount = 9_999)))).toThrow(SkiGraphFormatError);
|
||||
expect(() => decodeSkiGraph(withHead((head) => (head.stringBytes = 9_999)))).toThrow(
|
||||
'SGR1 string pool runs past the end',
|
||||
);
|
||||
});
|
||||
|
||||
it('SKIGRAPH-013: refuses an edge that names a node or points that do not exist', () => {
|
||||
const world = new SkiWorld();
|
||||
const a = world.node(0, 0, 1500);
|
||||
const b = world.node(0, -500, 1400);
|
||||
world.run(a, b, 2);
|
||||
const bytes = world.sgr();
|
||||
// Two nodes and one edge: nodeLatE7, nodeLngE7, nodeEle, nodeFlags, nodeOsm and edgeA, each padded to 8.
|
||||
const edgeB = bodyStart(bytes) + 8 + 8 + 8 + 8 + 16 + 8;
|
||||
expect(bytes.readUInt32LE(edgeB)).toBe(1);
|
||||
const foreignNode = Buffer.from(bytes);
|
||||
foreignNode.writeUInt32LE(7, edgeB);
|
||||
expect(() => decodeSkiGraph(reseal(foreignNode))).toThrow('SGR1 edge 0 names a node that does not exist');
|
||||
// edgeGeomOff follows edgeB, edgeLen, edgeUp, edgeDown, edgeKind, the two use sections, edgeDiff, edgeGroom,
|
||||
// edgeLift, edgeLiftSec, edgeLiftCap, edgeFlags, edgeName, edgeRef and edgeWay, each of one edge, padded to 8.
|
||||
const geomOff = edgeB + 8 * 15 + 8;
|
||||
expect(bytes.readUInt32LE(geomOff + 4)).toBe(2);
|
||||
const onePoint = Buffer.from(bytes);
|
||||
onePoint.writeUInt32LE(1, geomOff + 4);
|
||||
expect(() => decodeSkiGraph(reseal(onePoint))).toThrow('SGR1 edge 0 has no line of its own');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the test world writer', () => {
|
||||
it('SKIGRAPH-020: writes what the reader reads back, names, heights and missing heights included', () => {
|
||||
const world = new SkiWorld();
|
||||
const top = world.node(0, 0, 2000);
|
||||
const valley = world.node(0, -1000, null);
|
||||
world.run(top, valley, 1, { name: 'Talabfahrt', ref: '3', via: [[100, -500]] });
|
||||
const graph = world.graph();
|
||||
expect(graph.header.nodeCount).toBe(2);
|
||||
expect(Array.from(graph.edgeGeomOff)).toEqual([0, 3]);
|
||||
expect(poolString(graph.strings, graph.edgeName[0] as number)).toBe('Talabfahrt');
|
||||
expect(poolString(graph.strings, graph.edgeRef[0] as number)).toBe('3');
|
||||
expect(graph.nodeEle[1]).toBe(-32768);
|
||||
const net = stitchGraphs([graph]);
|
||||
expect(net.nodeEle[0]).toBe(2000);
|
||||
expect(Number.isNaN(net.nodeEle[1])).toBe(true);
|
||||
expect(net.edgeName[0]).toBe('Talabfahrt');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Where the piste router runs (spec 7.2): the networks a thread keeps
|
||||
* decoded within its budget, the runner on the calling thread, the router
|
||||
* thread's own script, and the runner that talks to a thread, here with
|
||||
* small threads written by the test that answer, fail, hang or die. Also the
|
||||
* area's lines for the map (spec 10.4).
|
||||
*/
|
||||
import { networkFeatures, simplifyLine } from '../../../../src/nest/ski-routing/engine/network';
|
||||
import { stitchGraphs } from '../../../../src/nest/ski-routing/engine/stitch';
|
||||
import { Lift } from '../../../../src/nest/ski-routing/ski-graph.contract';
|
||||
import {
|
||||
InlineSkiRouterRunner,
|
||||
NetCache,
|
||||
NETWORK_BUDGET_BYTES,
|
||||
type SkiRouteJob,
|
||||
} from '../../../../src/nest/ski-routing/ski-router-runner';
|
||||
import { profileOf } from '../../../../src/nest/ski-routing/ski-routing.service';
|
||||
import {
|
||||
answerTimeoutMs,
|
||||
MAX_WAITING_JOBS,
|
||||
WorkerSkiRouterRunner,
|
||||
} from '../../../../src/nest/ski-routing/worker-router-runner';
|
||||
import { decodePolyline } from '../../../../src/utils/polyline';
|
||||
import { SkiWorld } from '../../../helpers/ski-world';
|
||||
import { skiRouteRequestSchema } from '@trek/shared';
|
||||
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/** The router thread's port, as its script sees it: messages in, messages out. */
|
||||
const port = vi.hoisted(() => {
|
||||
const listeners: Array<(message: unknown) => void> = [];
|
||||
return {
|
||||
on: (event: string, listener: (message: unknown) => void) => {
|
||||
if (event === 'message') listeners.push(listener);
|
||||
},
|
||||
emit: (_event: 'message', message: unknown) => listeners.forEach((listener) => listener(message)),
|
||||
postMessage: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock('node:worker_threads', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('node:worker_threads')>()),
|
||||
parentPort: port,
|
||||
}));
|
||||
|
||||
let dir: string;
|
||||
let file: string;
|
||||
const world = new SkiWorld();
|
||||
const valley = world.node(0, 0, 1200);
|
||||
const top = world.node(0, 2000, 2200);
|
||||
world.lift(valley, top, { name: 'Sonnenbahn', type: Lift.CHAIR_DETACHABLE, sec: 420 });
|
||||
world.run(top, valley, 1, { name: 'Talabfahrt', via: [[200, 1000]] });
|
||||
|
||||
const job = (files: string[]): SkiRouteJob => {
|
||||
const request = skiRouteRequestSchema.parse({
|
||||
legs: [{ from: world.at(0, 2000), to: world.at(0, 0) }],
|
||||
discipline: 'alpine',
|
||||
});
|
||||
return {
|
||||
kind: 'route',
|
||||
files,
|
||||
areaIds: ['w:1'],
|
||||
legs: [{ from: world.at(0, 2000), to: world.at(0, 0), continues: false }],
|
||||
profile: profileOf(request),
|
||||
alternatives: 0,
|
||||
};
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), 'trek-ski-runner-'));
|
||||
file = join(dir, 'w_1@aaaaaaaa.sgr.gz');
|
||||
await writeFile(file, world.gz());
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('the decoded networks and the runner on the calling thread', () => {
|
||||
it('SKIRUN-001: decodes a network once, drops the oldest past the budget, forgets on request', async () => {
|
||||
const cache = new NetCache();
|
||||
const first = await cache.get([file]);
|
||||
expect(await cache.get([file])).toBe(first);
|
||||
const copy = join(dir, 'w_1@bbbbbbbb.sgr.gz');
|
||||
await writeFile(copy, world.gz());
|
||||
// A budget of one byte keeps only the network loaded last.
|
||||
const small = new NetCache(1);
|
||||
const a = await small.get([file]);
|
||||
await small.get([copy]);
|
||||
await vi.waitFor(async () => expect(await small.get([file])).not.toBe(a));
|
||||
cache.forget(file);
|
||||
expect(await cache.get([file])).not.toBe(first);
|
||||
await expect(cache.get([join(dir, 'missing.sgr.gz')])).rejects.toThrow();
|
||||
cache.clear();
|
||||
expect(NETWORK_BUDGET_BYTES).toBe(256 * 1024 * 1024);
|
||||
});
|
||||
|
||||
it('SKIRUN-002: the inline runner plans a job and draws the lines of an area', async () => {
|
||||
const runner = new InlineSkiRouterRunner();
|
||||
const [leg] = await runner.run(job([file]));
|
||||
expect(leg).toMatchObject({ status: 'ok', area_ids: ['w:1'] });
|
||||
const lines = await runner.run({ kind: 'network', files: [file] });
|
||||
expect(lines.features.map((feature) => feature.kind).sort()).toEqual(['lift', 'run']);
|
||||
runner.forget(file);
|
||||
await expect(runner.close()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('SKIROUTE-WORKER-001: the thread answers a job, forgets on request, answers a failure as a message', async () => {
|
||||
await import('../../../../src/nest/ski-routing/ski-router.worker');
|
||||
port.emit('message', { id: 1, job: job([file]) });
|
||||
await vi.waitFor(() =>
|
||||
expect(port.postMessage).toHaveBeenCalledWith({ id: 1, result: [expect.objectContaining({ status: 'ok' })] }),
|
||||
);
|
||||
port.emit('message', { id: 0, forget: file });
|
||||
port.emit('message', { id: 2 });
|
||||
port.emit('message', { id: 3, job: job([join(dir, 'nowhere.sgr.gz')]) });
|
||||
await vi.waitFor(() =>
|
||||
expect(port.postMessage).toHaveBeenCalledWith({ id: 3, error: expect.stringContaining('nowhere.sgr.gz') }),
|
||||
);
|
||||
expect(port.postMessage).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the lines of an area for the map', () => {
|
||||
it('SKIRUN-010: runs and lifts as lines with names, grades, types and one-way; links and stations left out', () => {
|
||||
const net = stitchGraphs([world.graph()]);
|
||||
const { features, simplified_m } = networkFeatures(net);
|
||||
expect(simplified_m).toBe(5);
|
||||
const run = features.find((feature) => feature.kind === 'run');
|
||||
expect(run).toMatchObject({ name: 'Talabfahrt', difficulty: 'easy', lift_type: null, oneway: true });
|
||||
const lift = features.find((feature) => feature.kind === 'lift');
|
||||
expect(lift).toMatchObject({ name: 'Sonnenbahn', lift_type: 'chair_detachable', oneway: true, difficulty: null });
|
||||
const line = decodePolyline(run?.line ?? '', 5);
|
||||
expect(line).toHaveLength(3);
|
||||
expect(line[0]?.[0]).toBeCloseTo(world.at(0, 2000).lat, 4);
|
||||
expect(features).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('SKIRUN-011: drops the points within the tolerance of the line, the ends always kept', () => {
|
||||
const straight: Array<[number, number]> = [
|
||||
[46, 7],
|
||||
[46.0005, 7.00001],
|
||||
[46.001, 7],
|
||||
];
|
||||
expect(simplifyLine(straight, 5)).toEqual([
|
||||
[46, 7],
|
||||
[46.001, 7],
|
||||
]);
|
||||
const bent: Array<[number, number]> = [
|
||||
[46, 7],
|
||||
[46.0005, 7.001],
|
||||
[46.001, 7],
|
||||
];
|
||||
expect(simplifyLine(bent, 5)).toHaveLength(3);
|
||||
expect(simplifyLine([[46, 7]], 5)).toEqual([[46, 7]]);
|
||||
});
|
||||
});
|
||||
|
||||
/** A thread script the runner can start: plain JS, so it runs without the server's loader. */
|
||||
async function script(name: string, body: string): Promise<string> {
|
||||
const path = join(dir, `${name}.cjs`);
|
||||
await writeFile(path, `const { parentPort } = require('node:worker_threads');\n${body}\n`);
|
||||
return path;
|
||||
}
|
||||
|
||||
describe('WorkerSkiRouterRunner', () => {
|
||||
it('SKIRUN-020: hands a job to its thread and answers its result; a failure the thread reports rejects', async () => {
|
||||
const entry = await script(
|
||||
'answers',
|
||||
`parentPort.on('message', (m) => {
|
||||
if (m.forget) return;
|
||||
if (m.job.files[0] === 'bad') parentPort.postMessage({ id: m.id, error: 'graph broken' });
|
||||
else if (m.job.files[0] === 'silent') parentPort.postMessage({ id: m.id });
|
||||
else parentPort.postMessage({ id: m.id, result: [{ status: 'failed', code: 'disconnected' }] });
|
||||
});`,
|
||||
);
|
||||
const runner = new WorkerSkiRouterRunner(entry);
|
||||
await expect(runner.run(job(['good']))).resolves.toEqual([{ status: 'failed', code: 'disconnected' }]);
|
||||
await expect(runner.run(job(['bad']))).rejects.toThrow('graph broken');
|
||||
await expect(runner.run(job(['silent']))).rejects.toThrow('router failed');
|
||||
runner.forget('good');
|
||||
await runner.close();
|
||||
});
|
||||
|
||||
it('SKIRUN-021: a thread that dies fails what it held, and the next job gets a fresh thread', async () => {
|
||||
const entry = await script(
|
||||
'dies',
|
||||
`parentPort.on('message', (m) => {
|
||||
if (m.job.files[0] === 'crash') process.exit(3);
|
||||
parentPort.postMessage({ id: m.id, result: [] });
|
||||
});`,
|
||||
);
|
||||
const runner = new WorkerSkiRouterRunner(entry);
|
||||
await expect(runner.run(job(['crash']))).rejects.toThrow('router thread ended');
|
||||
await expect(runner.run(job(['fine']))).resolves.toEqual([]);
|
||||
await runner.close();
|
||||
});
|
||||
|
||||
it('SKIRUN-022: a thread that throws fails its jobs; closing fails what is still waiting', async () => {
|
||||
const entry = await script(
|
||||
'throws',
|
||||
`parentPort.on('message', (m) => {
|
||||
if (m.job.files[0] === 'throw') setTimeout(() => { throw new Error('boom'); });
|
||||
});`,
|
||||
);
|
||||
const runner = new WorkerSkiRouterRunner(entry);
|
||||
await expect(runner.run(job(['throw']))).rejects.toThrow('boom');
|
||||
const waiting = runner.run(job(['never'])).catch((err: Error) => err.message);
|
||||
await runner.close();
|
||||
expect(await waiting).toBe('closed');
|
||||
});
|
||||
|
||||
it('SKIRUN-023: a job left unanswered times out, the thread is started over; a full queue is busy', async () => {
|
||||
const entry = await script('hangs', `parentPort.on('message', () => undefined);`);
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
try {
|
||||
const runner = new WorkerSkiRouterRunner(entry);
|
||||
const waiting = Array.from({ length: MAX_WAITING_JOBS }, () =>
|
||||
runner.run(job(['hang'])).catch((err: Error) => err.message),
|
||||
);
|
||||
await expect(runner.run(job(['hang']))).rejects.toThrow('busy');
|
||||
await vi.advanceTimersByTimeAsync(answerTimeoutMs(job(['hang'])));
|
||||
expect(await Promise.all(waiting)).toEqual(Array.from({ length: MAX_WAITING_JOBS }, () => 'timeout'));
|
||||
await runner.close();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('SKIRUN-024: a job of many legs waits longer for its answer, never beyond a minute', () => {
|
||||
const one = job(['x']);
|
||||
expect(answerTimeoutMs(one)).toBe(8000);
|
||||
expect(answerTimeoutMs({ ...one, legs: [...one.legs, ...one.legs, ...one.legs] })).toBe(16_000);
|
||||
const leg = one.legs[0] as SkiRouteJob['legs'][number];
|
||||
expect(answerTimeoutMs({ ...one, legs: Array.from({ length: 40 }, () => leg) })).toBe(60_000);
|
||||
expect(answerTimeoutMs({ kind: 'network', files: ['x'] })).toBe(8000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* The REST routes and the MCP tool of the piste router over a stub service:
|
||||
* the routes' guards, statuses and contracts, the tool's gate, scope and
|
||||
* input, and that both hand the same request to the same service. The answers
|
||||
* through the real guards are pinned in the e2e suite.
|
||||
*/
|
||||
import { ADDON_IDS } from '../../../../src/addons';
|
||||
import type { McpContext, McpTextResult, ToolOptions } from '../../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
|
||||
import { AddonGuard } from '../../../../src/nest/addons/addon.guard';
|
||||
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';
|
||||
import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
|
||||
import { TripAccessGuard } from '../../../../src/nest/permissions/trip-access.guard';
|
||||
import { SkiRoutingController } from '../../../../src/nest/ski-routing/ski-routing.controller';
|
||||
import { SkiRoutingMcp } from '../../../../src/nest/ski-routing/ski-routing.mcp';
|
||||
import type { SkiRoutingService } from '../../../../src/nest/ski-routing/ski-routing.service';
|
||||
import type { TripAccessService } from '../../../../src/nest/trip-membership/trip-access.service';
|
||||
import { RequestMethod } from '@nestjs/common';
|
||||
import { GUARDS_METADATA, HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
|
||||
import {
|
||||
skiAreaNearResponseSchema,
|
||||
skiNetworkResponseSchema,
|
||||
skiRouteRequestSchema,
|
||||
skiRouteResponseSchema,
|
||||
type SkiRouteResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
import type { Response } from 'express';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { z } from 'zod';
|
||||
|
||||
const A = { lat: 45.98, lng: 7.75 };
|
||||
const B = { lat: 45.97, lng: 7.74 };
|
||||
|
||||
const ANSWER: SkiRouteResponse = {
|
||||
build: '2026-11-02',
|
||||
stale: false,
|
||||
area_names: ['Testalp'],
|
||||
colour_scheme: 'europe',
|
||||
attribution: '© OpenStreetMap contributors, ODbL. Terrain: Mapzen Terrarium',
|
||||
legs: [
|
||||
{
|
||||
status: 'ok',
|
||||
geometry: [
|
||||
[A.lat, A.lng, 2500],
|
||||
[B.lat, B.lng, 1600],
|
||||
],
|
||||
segments: [
|
||||
{
|
||||
kind: 'run',
|
||||
from: 0,
|
||||
to: 1,
|
||||
name: 'Rote Eins',
|
||||
ref: '1',
|
||||
difficulty: 'intermediate',
|
||||
lift_type: null,
|
||||
grooming: [],
|
||||
seconds: 300,
|
||||
wait_seconds: 0,
|
||||
length_m: 2500,
|
||||
flags: [],
|
||||
osm_way: 12,
|
||||
},
|
||||
],
|
||||
distance_m: 2500,
|
||||
climb_m: 0,
|
||||
descent_m: 900,
|
||||
seconds: { ski: 300, lift: 0, wait: 0, walk: 0 },
|
||||
snapped_m: { from: 3, to: 0 },
|
||||
area_ids: ['w:1'],
|
||||
why: [],
|
||||
alternatives: [],
|
||||
},
|
||||
{ status: 'failed', code: 'no_area', at: B, hint: null, detail: null },
|
||||
],
|
||||
};
|
||||
|
||||
function service() {
|
||||
return {
|
||||
route: vi.fn<SkiRoutingService['route']>().mockResolvedValue(ANSWER),
|
||||
areaNear: vi.fn<SkiRoutingService['areaNear']>().mockResolvedValue({ area: null }),
|
||||
network: vi.fn<SkiRoutingService['network']>().mockResolvedValue({
|
||||
area_id: 'w:1',
|
||||
build: '2026-11-02',
|
||||
colour_scheme: 'europe',
|
||||
simplified_m: 5,
|
||||
features: [],
|
||||
sha256: 'a'.repeat(64),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe('SkiRoutingController', () => {
|
||||
it('SKICTL-001: the routes sit behind Tours, the session and the trip, each on its contract', () => {
|
||||
expect(Reflect.getMetadata(PATH_METADATA, SkiRoutingController)).toBe('api/trips/:tripId/ski');
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, SkiRoutingController)).toEqual([
|
||||
AddonGuard,
|
||||
JwtAuthGuard,
|
||||
TripAccessGuard,
|
||||
]);
|
||||
expect(Reflect.getMetadata(REQUIRE_ADDON, SkiRoutingController)).toEqual({ addonId: 'tours', label: 'Tours' });
|
||||
const { route, areaNear, network } = SkiRoutingController.prototype;
|
||||
expect(Reflect.getMetadata(METHOD_METADATA, route)).toBe(RequestMethod.POST);
|
||||
expect(Reflect.getMetadata(PATH_METADATA, route)).toBe('route');
|
||||
expect(Reflect.getMetadata(HTTP_CODE_METADATA, route)).toBe(200);
|
||||
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, route)).toBe(skiRouteResponseSchema);
|
||||
expect(Reflect.getMetadata(METHOD_METADATA, areaNear)).toBe(RequestMethod.GET);
|
||||
expect(Reflect.getMetadata(PATH_METADATA, areaNear)).toBe('area-near');
|
||||
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, areaNear)).toBe(skiAreaNearResponseSchema);
|
||||
expect(Reflect.getMetadata(PATH_METADATA, network)).toBe('network/:areaId');
|
||||
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, network)).toBe(skiNetworkResponseSchema);
|
||||
});
|
||||
|
||||
it('SKICTL-002: hands the parsed request to the service and answers what it planned', async () => {
|
||||
const routing = service();
|
||||
const controller = new SkiRoutingController(routing as unknown as SkiRoutingService);
|
||||
const body = skiRouteRequestSchema.parse({ legs: [{ from: A, to: B }], discipline: 'snowboard' });
|
||||
await expect(controller.route(body)).resolves.toBe(ANSWER);
|
||||
expect(routing.route).toHaveBeenCalledWith(body);
|
||||
await expect(controller.areaNear({ lat: 46, lng: 7 })).resolves.toEqual({ area: null });
|
||||
expect(routing.areaNear).toHaveBeenCalledWith(46, 7);
|
||||
});
|
||||
|
||||
it('SKICTL-003: the lines of an area go out tagged with its checksum, the checksum not in the body', async () => {
|
||||
const routing = service();
|
||||
const controller = new SkiRoutingController(routing as unknown as SkiRoutingService);
|
||||
const setHeader = vi.fn();
|
||||
const body = await controller.network('w:1', { setHeader } as unknown as Response);
|
||||
expect(body).toEqual({
|
||||
area_id: 'w:1',
|
||||
build: '2026-11-02',
|
||||
colour_scheme: 'europe',
|
||||
simplified_m: 5,
|
||||
features: [],
|
||||
});
|
||||
expect(setHeader).toHaveBeenCalledWith('ETag', `"${'a'.repeat(64)}"`);
|
||||
expect(setHeader).toHaveBeenCalledWith('Cache-Control', 'private, max-age=3600');
|
||||
});
|
||||
});
|
||||
|
||||
const ctx = { userId: 7, scopes: null, isStaticToken: false } as McpContext;
|
||||
|
||||
function toolOptions(): ToolOptions {
|
||||
const entry = getEntry(SkiRoutingMcp as unknown as ClassRef, 'planSkiRoute');
|
||||
if (!entry || entry.kind !== 'tool') throw new Error('plan_ski_route is not registered');
|
||||
return entry.options;
|
||||
}
|
||||
|
||||
function makeMcp(accessible: boolean) {
|
||||
const routing = service();
|
||||
const access = { findAccessible: vi.fn().mockResolvedValue(accessible ? { id: 3 } : null) };
|
||||
const mcp = new SkiRoutingMcp(
|
||||
routing as unknown as SkiRoutingService,
|
||||
access as unknown as TripAccessService,
|
||||
{} as AddonsService,
|
||||
);
|
||||
return { mcp, routing, access };
|
||||
}
|
||||
|
||||
describe('SkiRoutingMcp', () => {
|
||||
it('SKIMCP-001: plan_ski_route is read only, gated on Tours and scoped to reading trips', () => {
|
||||
const options = toolOptions();
|
||||
expect(options.name).toBe('plan_ski_route');
|
||||
expect(options.annotations?.readOnlyHint).toBe(true);
|
||||
expect(options.access).toEqual({ group: 'trips', mode: 'read' });
|
||||
const isAddonEnabled = vi.fn((id: string) => id === ADDON_IDS.TOURS);
|
||||
const self = { addons: { isAddonEnabled } } as unknown as SkiRoutingMcp;
|
||||
expect(options.when?.(ctx, self)).toBe(true);
|
||||
expect(isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.TOURS);
|
||||
});
|
||||
|
||||
it('SKIMCP-002: takes the REST contract plus the trip, with the same defaults and limits', () => {
|
||||
const input = z.object(toolOptions().inputSchema as z.ZodRawShape);
|
||||
expect(input.safeParse({ tripId: 3, legs: [{ from: A, to: B }], discipline: 'alpine' }).success).toBe(true);
|
||||
expect(input.safeParse({ tripId: 3, legs: [], discipline: 'alpine' }).success).toBe(false);
|
||||
expect(input.safeParse({ tripId: 3, legs: [{ from: A, to: B }] }).success).toBe(false);
|
||||
const three = { tripId: 3, legs: [{ from: A, to: B }], discipline: 'alpine', alternatives: 3 };
|
||||
expect(input.safeParse(three).success).toBe(false);
|
||||
expect(input.safeParse({ legs: [{ from: A, to: B }], discipline: 'alpine' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('SKIMCP-003: plans for a trip the caller sees, the same request as REST, legs without their points', async () => {
|
||||
const { mcp, routing, access } = makeMcp(true);
|
||||
const asked = { tripId: 3, legs: [{ from: A, to: B }], discipline: 'alpine' as const };
|
||||
const result = (await mcp.planSkiRoute(asked, ctx)) as McpTextResult;
|
||||
expect(access.findAccessible).toHaveBeenCalledWith(3, 7);
|
||||
const { tripId: _trip, ...asRest } = asked;
|
||||
expect(routing.route).toHaveBeenCalledWith(skiRouteRequestSchema.parse(asRest));
|
||||
expect(result.isError).toBeUndefined();
|
||||
expect(JSON.parse(result.content[0].text)).toEqual({
|
||||
build: '2026-11-02',
|
||||
stale: false,
|
||||
area_names: ['Testalp'],
|
||||
colour_scheme: 'europe',
|
||||
attribution: '© OpenStreetMap contributors, ODbL. Terrain: Mapzen Terrarium',
|
||||
legs: [
|
||||
{
|
||||
status: 'ok',
|
||||
distance_m: 2500,
|
||||
climb_m: 0,
|
||||
descent_m: 900,
|
||||
seconds: { ski: 300, lift: 0, wait: 0, walk: 0 },
|
||||
snapped_m: { from: 3, to: 0 },
|
||||
points: 2,
|
||||
segments: [
|
||||
{
|
||||
kind: 'run',
|
||||
name: 'Rote Eins',
|
||||
ref: '1',
|
||||
difficulty: 'intermediate',
|
||||
lift_type: null,
|
||||
seconds: 300,
|
||||
wait_seconds: 0,
|
||||
length_m: 2500,
|
||||
flags: [],
|
||||
},
|
||||
],
|
||||
why: [],
|
||||
alternatives: 0,
|
||||
},
|
||||
{ status: 'failed', code: 'no_area', at: B, hint: null, detail: null },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('SKIMCP-004: a trip the caller cannot see is refused before anything is planned', async () => {
|
||||
const { mcp, routing } = makeMcp(false);
|
||||
const asked = { tripId: 9, legs: [{ from: A, to: B }], discipline: 'alpine' as const };
|
||||
const result = (await mcp.planSkiRoute(asked, ctx)) as McpTextResult;
|
||||
expect(result.isError).toBe(true);
|
||||
expect(routing.route).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* The piste router service (spec 7, 11): what it answers when TREK Places or
|
||||
* the admin switch is off, while an index or an area is still on its way, on
|
||||
* an area kept from an older build, when the router's thread is busy or slow,
|
||||
* and with every leg planned on the areas that hold its ends. The Places host
|
||||
* is a stub; the areas are kept in a temp folder and planned on the calling
|
||||
* thread.
|
||||
*/
|
||||
import { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import { DataPathsService } from '../../../../src/nest/app-config/data-paths.service';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { TrekPlacesWinterService } from '../../../../src/nest/maps/trek-places-winter.service';
|
||||
import { SkiAreasService } from '../../../../src/nest/ski-routing/ski-areas.service';
|
||||
import { InlineSkiRouterRunner, SKI_ROUTER_RUNNER } from '../../../../src/nest/ski-routing/ski-router-runner';
|
||||
import {
|
||||
LOADING_MS,
|
||||
profileOf,
|
||||
settleWithin,
|
||||
SkiRoutingService,
|
||||
} from '../../../../src/nest/ski-routing/ski-routing.service';
|
||||
import { SkiWorld } from '../../../helpers/ski-world';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { skiRouteRequestSchema, skiRouteResponseSchema, type SkiRouteInput, type WinterIndexRow } from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const sha = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');
|
||||
|
||||
/** Testalp, a run and a lift; Nachbaralp 20 km east, a run of its own. */
|
||||
const testalp = new SkiWorld({ lat: 46, lng: 7 }, { areaId: 'w:1', build: '2026-11-02', name: 'Testalp' });
|
||||
const valley = testalp.node(0, 0, 1200);
|
||||
const top = testalp.node(0, 2000, 2200);
|
||||
testalp.lift(valley, top, { name: 'Sonnenbahn', sec: 420 });
|
||||
testalp.run(top, valley, 1, { name: 'Talabfahrt', via: [[300, 1000]] });
|
||||
const nachbar = new SkiWorld({ lat: 46, lng: 7.26 }, { areaId: 'w:2', build: '2026-11-02', name: 'Nachbaralp' });
|
||||
nachbar.run(nachbar.node(0, 1000, 1800), nachbar.node(0, 0, 1300), 1, { name: 'Nachbarpiste' });
|
||||
|
||||
function rowOf(world: SkiWorld, id: string, name: string): WinterIndexRow {
|
||||
const gz = world.gz();
|
||||
const south = world.at(-500, -500);
|
||||
const north = world.at(500, 2500);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
kind: 'resort',
|
||||
country: null,
|
||||
colourScheme: 'europe',
|
||||
bbox: [south.lng, south.lat, north.lng, north.lat],
|
||||
counts: { runsKm: 2, nordicKm: 0, lifts: 1, skitourKm: 0, hikeKm: 0 },
|
||||
bytes: gz.length,
|
||||
sha256: sha(gz),
|
||||
};
|
||||
}
|
||||
|
||||
const ROWS = [rowOf(testalp, 'w:1', 'Testalp'), rowOf(nachbar, 'w:2', 'Nachbaralp')];
|
||||
const GZ: Record<string, Buffer> = { 'w:1': testalp.gz(), 'w:2': nachbar.gz() };
|
||||
|
||||
let dir: string;
|
||||
const winter = { enabled: vi.fn(), meta: vi.fn(), index: vi.fn(), area: vi.fn() };
|
||||
const addons = { getToursSkiRouting: vi.fn() };
|
||||
const runner = { run: vi.fn(), forget: vi.fn(), close: vi.fn() };
|
||||
|
||||
async function build(inline = true) {
|
||||
const inlineRunner = new InlineSkiRouterRunner();
|
||||
runner.run.mockImplementation((job) => inlineRunner.run(job));
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
SkiRoutingService,
|
||||
SkiAreasService,
|
||||
{ provide: DataPathsService, useValue: { dataDir: dir } },
|
||||
{ provide: TrekPlacesWinterService, useValue: winter },
|
||||
{ provide: AddonsService, useValue: addons },
|
||||
{ provide: SKI_ROUTER_RUNNER, useValue: inline ? inlineRunner : runner },
|
||||
],
|
||||
}).compile();
|
||||
return { routing: moduleRef.get(SkiRoutingService), areas: moduleRef.get(SkiAreasService) };
|
||||
}
|
||||
|
||||
const request = (input: Partial<SkiRouteInput> & Pick<SkiRouteInput, 'legs'>) =>
|
||||
skiRouteRequestSchema.parse({ discipline: 'alpine', ...input });
|
||||
|
||||
const down = { from: testalp.at(0, 2000), to: testalp.at(0, 0) };
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), 'trek-ski-routing-'));
|
||||
const json = Buffer.from(JSON.stringify({ build: '2026-11-02', format: 1, areas: ROWS }));
|
||||
const meta = {
|
||||
build: '2026-11-02',
|
||||
format: 1,
|
||||
areas: ROWS.length,
|
||||
indexSha: sha(json),
|
||||
sourceTimestamp: null,
|
||||
attribution: { data: '© OpenStreetMap contributors, ODbL', terrain: 'Terrain: Mapzen Terrarium' },
|
||||
};
|
||||
winter.enabled.mockReset().mockReturnValue(true);
|
||||
winter.meta.mockReset().mockResolvedValue(meta);
|
||||
winter.index.mockReset().mockResolvedValue({
|
||||
status: 'ok',
|
||||
index: { build: '2026-11-02', format: 1, areas: ROWS },
|
||||
sha256: meta.indexSha,
|
||||
dropped: 0,
|
||||
});
|
||||
winter.area.mockReset().mockImplementation(async (id: string) => ({ status: 'ok', bytes: GZ[id], etag: null }));
|
||||
addons.getToursSkiRouting.mockReset().mockResolvedValue({ enabled: true });
|
||||
runner.run.mockReset();
|
||||
runner.close.mockReset();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('when nothing can be planned here', () => {
|
||||
it('SKISVC-001: TREK Places switched off: every leg drawn freely, nothing asked of the host', async () => {
|
||||
winter.enabled.mockReturnValue(false);
|
||||
const { routing } = await build();
|
||||
const answer = await routing.route(request({ legs: [down, down] }));
|
||||
expect(answer.legs).toEqual([
|
||||
{ status: 'failed', code: 'places_unavailable', at: null, hint: { free_draw: true }, detail: null },
|
||||
{ status: 'failed', code: 'places_unavailable', at: null, hint: { free_draw: true }, detail: null },
|
||||
]);
|
||||
expect(answer).toMatchObject({ build: null, stale: false, area_names: [] });
|
||||
expect(winter.meta).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('SKISVC-002: the admin switched piste routing off: disabled, drawn freely', async () => {
|
||||
addons.getToursSkiRouting.mockResolvedValue({ enabled: false });
|
||||
const { routing } = await build();
|
||||
const answer = await routing.route(request({ legs: [down] }));
|
||||
expect(answer.legs[0]).toMatchObject({ status: 'failed', code: 'disabled', hint: { free_draw: true } });
|
||||
expect(skiRouteResponseSchema.parse(answer)).toEqual(answer);
|
||||
});
|
||||
|
||||
it('SKISVC-003: no index to be had: places unavailable; an index slower than the wait: loading', async () => {
|
||||
winter.meta.mockRejectedValue(new Error('TREK Places API 503'));
|
||||
const { routing } = await build();
|
||||
expect((await routing.route(request({ legs: [down] }))).legs[0]).toMatchObject({ code: 'places_unavailable' });
|
||||
|
||||
winter.meta.mockImplementation(() => new Promise(() => undefined));
|
||||
const slow = await build();
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
const pending = slow.routing.route(request({ legs: [down] }));
|
||||
await vi.waitFor(() => expect(vi.getTimerCount()).toBe(1));
|
||||
await vi.advanceTimersByTimeAsync(LOADING_MS);
|
||||
expect((await pending).legs[0]).toMatchObject({ status: 'failed', code: 'loading', hint: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('legs on the areas that hold them', () => {
|
||||
it('SKISVC-010: plans a leg on its area, with the build, the area name and the attribution', async () => {
|
||||
const { routing } = await build();
|
||||
const answer = await routing.route(request({ legs: [down] }));
|
||||
expect(answer.legs[0]).toMatchObject({ status: 'ok', area_ids: ['w:1'] });
|
||||
expect(answer).toMatchObject({
|
||||
build: '2026-11-02',
|
||||
stale: false,
|
||||
area_names: ['Testalp'],
|
||||
attribution: '© OpenStreetMap contributors, ODbL. Terrain: Mapzen Terrarium',
|
||||
});
|
||||
expect(skiRouteResponseSchema.parse(answer)).toEqual(answer);
|
||||
expect(winter.area).toHaveBeenCalledWith('w:1', null);
|
||||
});
|
||||
|
||||
it('SKISVC-011: answers each leg on its own: off every area, across two areas, on the next area', async () => {
|
||||
const { routing } = await build();
|
||||
const lowland = { lat: 53.5, lng: 10 };
|
||||
const answer = await routing.route(
|
||||
request({
|
||||
legs: [
|
||||
{ from: lowland, to: testalp.at(0, 0) },
|
||||
{ from: testalp.at(0, 2000), to: nachbar.at(0, 0) },
|
||||
{ from: nachbar.at(0, 1000), to: nachbar.at(0, 0) },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(answer.legs[0]).toEqual({ status: 'failed', code: 'no_area', at: lowland, hint: null, detail: null });
|
||||
expect(answer.legs[1]).toMatchObject({ status: 'failed', code: 'cross_area' });
|
||||
expect(answer.legs[2]).toMatchObject({ status: 'ok', area_ids: ['w:2'] });
|
||||
expect(answer.area_names).toEqual(['Nachbaralp']);
|
||||
});
|
||||
|
||||
it('SKISVC-012: a leg goes on from the leg before it on the same area', async () => {
|
||||
const { routing } = await build();
|
||||
const answer = await routing.route(
|
||||
request({
|
||||
legs: [
|
||||
{ from: testalp.at(0, 0), to: testalp.at(0, 2000) },
|
||||
{ from: testalp.at(0, 2000), to: testalp.at(0, 0) },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(answer.legs.map((leg) => leg.status)).toEqual(['ok', 'ok']);
|
||||
const [up, run] = answer.legs;
|
||||
if (up?.status !== 'ok' || run?.status !== 'ok') throw new Error('not planned');
|
||||
expect(up.segments.map((s) => s.kind)).toEqual(['lift']);
|
||||
expect(run.segments.map((s) => s.name)).toEqual(['Talabfahrt']);
|
||||
});
|
||||
|
||||
it('SKISVC-013: an area slower than the wait: loading, named; one that cannot be had: drawn freely', async () => {
|
||||
winter.area.mockImplementation(() => new Promise(() => undefined));
|
||||
const { routing, areas } = await build();
|
||||
// The index is here already; only the area is on its way.
|
||||
await areas.index();
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
const pending = routing.route(request({ legs: [down] }));
|
||||
await vi.waitFor(() => expect(vi.getTimerCount()).toBe(1));
|
||||
await vi.advanceTimersByTimeAsync(LOADING_MS);
|
||||
expect((await pending).legs[0]).toMatchObject({ code: 'loading', detail: { name: 'Testalp' } });
|
||||
vi.useRealTimers();
|
||||
|
||||
winter.area.mockRejectedValue(Object.assign(new Error('TREK Places API 503'), { status: 503 }));
|
||||
const fresh = await build();
|
||||
expect((await fresh.routing.route(request({ legs: [down] }))).legs[0]).toMatchObject({
|
||||
code: 'places_unavailable',
|
||||
hint: { free_draw: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('SKISVC-014: plans on an older copy of the area while the host is down, and says so', async () => {
|
||||
const { routing, areas } = await build();
|
||||
await routing.route(request({ legs: [down] }));
|
||||
const index = await areas.index();
|
||||
const kept = index?.areas[0];
|
||||
if (!kept) throw new Error('no index');
|
||||
kept.row = { ...kept.row, sha256: sha('a newer build') };
|
||||
winter.area.mockRejectedValue(Object.assign(new Error('TREK Places API 503'), { status: 503 }));
|
||||
const answer = await routing.route(request({ legs: [down] }));
|
||||
expect(answer.legs[0]).toMatchObject({ status: 'ok' });
|
||||
expect(answer.stale).toBe(true);
|
||||
});
|
||||
|
||||
it('SKISVC-015: a busy or slow thread answers busy or timeout; a graph it cannot read, drawn freely', async () => {
|
||||
const { routing } = await build(false);
|
||||
runner.run.mockRejectedValueOnce(new Error('busy'));
|
||||
expect((await routing.route(request({ legs: [down] }))).legs[0]).toMatchObject({ code: 'busy', hint: null });
|
||||
runner.run.mockRejectedValueOnce(new Error('timeout'));
|
||||
expect((await routing.route(request({ legs: [down] }))).legs[0]).toMatchObject({ code: 'timeout' });
|
||||
runner.run.mockRejectedValueOnce(new Error('SGR1 format 2 is not 1'));
|
||||
expect((await routing.route(request({ legs: [down] }))).legs[0]).toMatchObject({
|
||||
code: 'places_unavailable',
|
||||
hint: { free_draw: true },
|
||||
});
|
||||
await routing.onApplicationShutdown();
|
||||
expect(runner.close).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the area at a point and its lines', () => {
|
||||
it('SKISVC-020: the area at a point, its download started, ready once here; none off every area', async () => {
|
||||
const { routing } = await build();
|
||||
const near = await routing.areaNear(46.005, 7.001);
|
||||
expect(near.area).toMatchObject({ id: 'w:1', name: 'Testalp', kind: 'resort', colour_scheme: 'europe' });
|
||||
expect(['loading', 'ready']).toContain(near.area?.state);
|
||||
await vi.waitFor(async () => expect((await routing.areaNear(46.005, 7.001)).area?.state).toBe('ready'));
|
||||
expect(await routing.areaNear(53.5, 10)).toEqual({ area: null });
|
||||
addons.getToursSkiRouting.mockResolvedValue({ enabled: false });
|
||||
expect((await routing.areaNear(46.005, 7.001)).area?.state).toBe('unavailable');
|
||||
// TREK Places off: the area kept from before is named, but nothing is fetched for it.
|
||||
winter.enabled.mockReturnValue(false);
|
||||
const off = await build();
|
||||
expect((await off.routing.areaNear(46.005, 7.001)).area?.state).toBe('unavailable');
|
||||
});
|
||||
|
||||
it('SKISVC-021: an area lines for the map with its checksum; an unknown one 404, none to be had 503', async () => {
|
||||
const { routing } = await build();
|
||||
const lines = await routing.network('w:1');
|
||||
expect(lines).toMatchObject({ area_id: 'w:1', build: '2026-11-02', colour_scheme: 'europe', simplified_m: 5 });
|
||||
expect(lines.sha256).toBe(ROWS[0]?.sha256);
|
||||
expect(lines.features.map((feature) => feature.name).sort()).toEqual(['Sonnenbahn', 'Talabfahrt']);
|
||||
await expect(routing.network('w:999')).rejects.toMatchObject({ status: 404 });
|
||||
winter.area.mockRejectedValue(Object.assign(new Error('TREK Places API 503'), { status: 503 }));
|
||||
await expect(routing.network('w:2')).rejects.toBeInstanceOf(DomainError);
|
||||
addons.getToursSkiRouting.mockResolvedValue({ enabled: false });
|
||||
await expect(routing.network('w:1')).rejects.toMatchObject({ status: 503 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('helpers', () => {
|
||||
it('SKISVC-030: settleWithin tells done, failed and pending, and leaves no failure unhandled', async () => {
|
||||
expect(await settleWithin(Promise.resolve(4), 10)).toEqual({ status: 'done', value: 4 });
|
||||
const error = new Error('no');
|
||||
expect(await settleWithin(Promise.reject(error), 10)).toEqual({ status: 'failed', error });
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
let fail: (err: Error) => void = () => undefined;
|
||||
const late = new Promise<number>((_resolve, reject) => (fail = reject));
|
||||
const settled = settleWithin(late, 50);
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(await settled).toEqual({ status: 'pending' });
|
||||
fail(new Error('later'));
|
||||
});
|
||||
|
||||
it('SKISVC-031: a technique only for cross-country, either when none was named, lifts by discipline', () => {
|
||||
const legs = [down];
|
||||
expect(profileOf(request({ legs, technique: 'classic' })).technique).toBeNull();
|
||||
expect(profileOf(request({ legs, discipline: 'cross_country' })).technique).toBe('unknown');
|
||||
expect(profileOf(request({ legs, discipline: 'cross_country', technique: 'skating' })).technique).toBe('skating');
|
||||
expect(profileOf(request({ legs })).useLifts).toBe(true);
|
||||
expect(profileOf(request({ legs, discipline: 'touring' })).useLifts).toBe(false);
|
||||
expect(profileOf(request({ legs, options: { groomed_only: true } })).options.groomed_only).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* The winter layer of the TREK Places client (spec 7.2, 3.5): what it asks
|
||||
* (never a coordinate), its caps and timeouts, the ETag it holds, the answers
|
||||
* it refuses, and the operator's opt-out and the circuit breaker it shares
|
||||
* with the place search. fetch is stubbed; the service is not reached.
|
||||
*/
|
||||
import { TrekPlacesWinterService } from '../../../src/nest/maps/trek-places-winter.service';
|
||||
import {
|
||||
resetTrekPlacesBreaker,
|
||||
trekPlacesWinterArea,
|
||||
trekPlacesWinterIndex,
|
||||
trekPlacesWinterMeta,
|
||||
} from '../../../src/nest/maps/trek-places.client';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { env } = vi.hoisted(() => ({
|
||||
env: { maps: { trekPlacesUrl: 'https://places.example.net', trekPlacesEnabled: true } },
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/app-config', () => ({
|
||||
readEnv: () => env,
|
||||
getAppUrl: () => 'https://trip.example.org',
|
||||
}));
|
||||
|
||||
interface Call {
|
||||
url: string;
|
||||
init: RequestInit & { headers: Record<string, string> };
|
||||
}
|
||||
let calls: Call[] = [];
|
||||
|
||||
/** One answer of the service: a status, a body as bytes (streamed or not) and its headers. */
|
||||
function answer(status: number, body: Buffer | string = '', headers: Record<string, string> = {}, stream = true) {
|
||||
const bytes = typeof body === 'string' ? Buffer.from(body) : body;
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: { get: (name: string) => headers[name.toLowerCase()] ?? null },
|
||||
body: stream
|
||||
? new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(bytes));
|
||||
controller.close();
|
||||
},
|
||||
})
|
||||
: null,
|
||||
arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
function stub(...answers: Response[]) {
|
||||
calls = [];
|
||||
const queue = [...answers];
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (url: URL | string, init: Call['init']) => {
|
||||
calls.push({ url: String(url), init });
|
||||
const next = queue.shift();
|
||||
if (!next) throw new Error('no answer left');
|
||||
return next;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const SHA = 'c'.repeat(64);
|
||||
const META = {
|
||||
build: '2026-11-02',
|
||||
format: 1,
|
||||
areas: 1,
|
||||
indexSha: SHA,
|
||||
sourceTimestamp: '2026-11-01T00:00:00Z',
|
||||
attribution: { data: '© OpenStreetMap contributors, ODbL', terrain: 'Terrain: Mapzen Terrarium', note: 'x' },
|
||||
};
|
||||
const ROW = {
|
||||
id: 'w:100',
|
||||
name: 'Sonnenbahn',
|
||||
kind: 'resort',
|
||||
country: null,
|
||||
colourScheme: 'europe',
|
||||
bbox: [7.0, 45.999, 7.005, 46.0052],
|
||||
counts: { runsKm: 1.19, nordicKm: 0.53, lifts: 1, skitourKm: 0, hikeKm: 0 },
|
||||
bytes: 900,
|
||||
sha256: SHA,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetTrekPlacesBreaker();
|
||||
env.maps.trekPlacesEnabled = true;
|
||||
env.maps.trekPlacesUrl = 'https://places.example.net';
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('the winter meta', () => {
|
||||
it('PLACESWINTER-001: asks /v1/winter/meta without any parameter, and reads the build and checksum', async () => {
|
||||
stub(answer(200, JSON.stringify(META)));
|
||||
expect(await trekPlacesWinterMeta()).toMatchObject({ build: '2026-11-02', indexSha: SHA, format: 1 });
|
||||
const url = new URL(calls[0]?.url ?? '');
|
||||
expect(url.origin + url.pathname).toBe('https://places.example.net/v1/winter/meta');
|
||||
expect(url.search).toBe('');
|
||||
expect(calls[0]?.init.signal).toBeInstanceOf(AbortSignal);
|
||||
expect(calls[0]?.init.headers['X-TREK-Instance']).toMatch(/^trek-/);
|
||||
expect(calls[0]?.init.headers['If-None-Match']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('PLACESWINTER-002: refuses an answer off the contract, too large, or not JSON', async () => {
|
||||
stub(answer(200, JSON.stringify({ ...META, indexSha: 'short' })));
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow();
|
||||
stub(answer(200, 'x'.repeat(70 * 1024)));
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('TREK Places API response too large');
|
||||
stub(answer(200, '<html>'));
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow(SyntaxError);
|
||||
stub(answer(304, ''));
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('TREK Places API 304');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the winter index', () => {
|
||||
it('PLACESWINTER-010: sends the checksum it holds as the ETag, and reads nothing new on a 304', async () => {
|
||||
stub(answer(304, '', { etag: `"${SHA}"` }));
|
||||
expect(await trekPlacesWinterIndex(SHA)).toEqual({ status: 'not_modified' });
|
||||
expect(calls[0]?.init.headers['If-None-Match']).toBe(`"${SHA}"`);
|
||||
});
|
||||
|
||||
it('PLACESWINTER-011: reads the index, checksums it as read, and drops a row that does not read', async () => {
|
||||
const json = JSON.stringify({ build: '2026-11-02', format: 1, areas: [ROW, { ...ROW, id: '../x' }] });
|
||||
stub(answer(200, json, { etag: '"abc"' }, false));
|
||||
const read = await trekPlacesWinterIndex(null);
|
||||
if (read.status !== 'ok') throw new Error('not read');
|
||||
expect(read.index.areas.map((row) => row.id)).toEqual(['w:100']);
|
||||
expect(read.dropped).toBe(1);
|
||||
expect(read.sha256).toBe(createHash('sha256').update(json).digest('hex'));
|
||||
expect(calls[0]?.init.headers['If-None-Match']).toBeUndefined();
|
||||
stub(answer(200, JSON.stringify({ build: '', format: 1, areas: [] })));
|
||||
await expect(trekPlacesWinterIndex(null)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('an area graph', () => {
|
||||
it('PLACESWINTER-020: asks for the area by its id, the bytes as sent with their tag', async () => {
|
||||
const bytes = Buffer.from([0x1f, 0x8b, 8, 0, 1, 2, 3]);
|
||||
stub(answer(200, bytes, { etag: `W/"${SHA}"` }));
|
||||
expect(await trekPlacesWinterArea('w:100', null)).toEqual({ status: 'ok', bytes, etag: SHA });
|
||||
expect(new URL(calls[0]?.url ?? '').pathname).toBe('/v1/winter/area/w%3A100');
|
||||
expect(calls[0]?.init.headers.Accept).toBe('application/vnd.trek.sgraph');
|
||||
stub(answer(304, ''));
|
||||
expect(await trekPlacesWinterArea('r:5-1a', SHA)).toEqual({ status: 'not_modified' });
|
||||
stub(answer(200, bytes, {}));
|
||||
expect(await trekPlacesWinterArea('w:100', null)).toMatchObject({ etag: null });
|
||||
});
|
||||
|
||||
it('PLACESWINTER-021: refuses an id that is not one before asking, and a 404 as a 404', async () => {
|
||||
stub();
|
||||
await expect(trekPlacesWinterArea('../../etc/passwd', null)).rejects.toThrow('Not a ski area id');
|
||||
expect(calls).toHaveLength(0);
|
||||
stub(answer(404, 'no such area'));
|
||||
await expect(trekPlacesWinterArea('w:9', null)).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('the opt-out and the breaker', () => {
|
||||
it('PLACESWINTER-030: nothing leaves when TREK Places is off, and the provider says so', async () => {
|
||||
env.maps.trekPlacesEnabled = false;
|
||||
stub();
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('switched off');
|
||||
await expect(trekPlacesWinterIndex(null)).rejects.toThrow('switched off');
|
||||
expect(calls).toHaveLength(0);
|
||||
const winter = new TrekPlacesWinterService();
|
||||
expect(winter.enabled()).toBe(false);
|
||||
env.maps.trekPlacesEnabled = true;
|
||||
expect(winter.enabled()).toBe(true);
|
||||
});
|
||||
|
||||
it('PLACESWINTER-031: four failures open the breaker for the winter layer too; a 404 does not count', async () => {
|
||||
stub(answer(404), answer(500), answer(500), answer(500), answer(500));
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('TREK Places API 404');
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('TREK Places API 500');
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('TREK Places API 500');
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('TREK Places API 500');
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('TREK Places API 500');
|
||||
await expect(trekPlacesWinterMeta()).rejects.toThrow('not retrying yet');
|
||||
expect(calls).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('PLACESWINTER-032: the provider hands each call to the client', async () => {
|
||||
const winter = new TrekPlacesWinterService();
|
||||
stub(answer(200, JSON.stringify(META)), answer(304, ''), answer(304, ''));
|
||||
expect((await winter.meta()).build).toBe('2026-11-02');
|
||||
expect(await winter.index(SHA)).toEqual({ status: 'not_modified' });
|
||||
expect(await winter.area('w:1', SHA)).toEqual({ status: 'not_modified' });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user