diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.json index a326ebf69..5475a1b5b 100644 --- a/client/scripts/eslint-baseline.json +++ b/client/scripts/eslint-baseline.json @@ -35,7 +35,7 @@ }, "tests": { "@typescript-eslint/no-explicit-any": 490, - "@typescript-eslint/no-non-null-assertion": 1927, + "@typescript-eslint/no-non-null-assertion": 1917, "@typescript-eslint/no-misused-promises": 22, "@typescript-eslint/no-unused-vars": 51, "@typescript-eslint/no-floating-promises": 33, diff --git a/client/src/components/Admin/RoutingInstanceFields.tsx b/client/src/components/Admin/RoutingInstanceFields.tsx index 3353686ef..74b845b74 100644 --- a/client/src/components/Admin/RoutingInstanceFields.tsx +++ b/client/src/components/Admin/RoutingInstanceFields.tsx @@ -29,10 +29,10 @@ const ROUTERS = [ // '' is no choice of the admin: the instance then decides as before the choice existed. const PROVIDERS = [ - { value: '', label: 'settings.valhallaProviderOption.auto' }, - { value: 'trek', label: 'settings.valhallaProviderOption.trek' }, - { value: 'fossgis', label: 'settings.valhallaProviderOption.fossgis' }, - { value: 'custom', label: 'settings.valhallaProviderOption.custom' }, + { value: '', labelKey: 'settings.valhallaProviderOption.auto' }, + { value: 'trek', labelKey: 'settings.valhallaProviderOption.trek' }, + { value: 'fossgis', labelKey: 'settings.valhallaProviderOption.fossgis' }, + { value: 'custom', labelKey: 'settings.valhallaProviderOption.custom' }, ] as const // The phone screen's look, unchanged: MAdminDefaultUserSettings passes its own hint class. @@ -123,7 +123,7 @@ function RoutingProviderField({ defaults, onSave, onReset, hintClassName }: Rout diff --git a/client/src/components/Admin/ServiceIdentityPanel.tsx b/client/src/components/Admin/ServiceIdentityPanel.tsx index f4455d173..3c6d96a8f 100644 --- a/client/src/components/Admin/ServiceIdentityPanel.tsx +++ b/client/src/components/Admin/ServiceIdentityPanel.tsx @@ -1,10 +1,4 @@ -import type { - ServiceAllowance, - ServiceIdentityState, - ServiceIdentityStatus, - ServiceName, - ServiceQuotaView, -} from '@trek/shared'; +import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared'; import { RefreshCw } from 'lucide-react'; import { useRef, useState } from 'react'; import { useTranslation } from '../../i18n'; @@ -24,12 +18,6 @@ const STATE_DOT: Record = { revoked: 'bg-danger', }; -const SERVICE_LABEL: Record = { - places: 'admin.trekApi.quota.service.places', - photon: 'admin.trekApi.quota.service.photon', - valhalla: 'admin.trekApi.quota.service.valhalla', -}; - /** Below a tenth of the day left the bar turns amber, at nothing left red. */ function barTone(quota: ServiceQuotaView): string { if (quota.remaining === 0) return 'bg-danger'; @@ -95,7 +83,7 @@ function rowNote(t: TranslationFn, allowance: ServiceAllowance): string | null { */ function ServiceRow({ allowance }: { allowance: ServiceAllowance }) { const { t } = useTranslation(); - const name = t(SERVICE_LABEL[allowance.service]); + const name = t(`admin.trekApi.quota.service.${allowance.service}`); const note = rowNote(t, allowance); return ( diff --git a/client/src/components/Map/valhallaRoute.test.ts b/client/src/components/Map/valhallaRoute.test.ts index 64f63f013..a2b7c886d 100644 --- a/client/src/components/Map/valhallaRoute.test.ts +++ b/client/src/components/Map/valhallaRoute.test.ts @@ -134,9 +134,9 @@ describe('runFrom', () => { it('VALHALLA-PARSE-001: decodes the shape as polyline6 and converts km to metres', () => { const leg = total(answer()) expect(leg).not.toBeNull() - expect(leg!.coordinates).toEqual(SHAPE_POINTS) - expect(leg!.distance).toBeCloseTo(295700, 0) - expect(leg!.duration).toBe(11460) + expect(leg?.coordinates).toEqual(SHAPE_POINTS) + expect(leg?.distance).toBeCloseTo(295700, 0) + expect(leg?.duration).toBe(11460) }) it('VALHALLA-PARSE-002: carries the flags through as booleans', () => { @@ -164,15 +164,15 @@ describe('runFrom', () => { summary: { length: 150, time: 5400, has_toll: true, has_highway: true, has_ferry: false }, }, } - const run = runFrom(chain)! - expect(run.legs.map(l => l.distance)).toEqual([100000, 50000]) - expect(run.legs.map(l => l.hasToll)).toEqual([false, true]) - expect(run.total.distance).toBe(150000) - expect(run.total.duration).toBe(5400) + const run = runFrom(chain) + expect(run?.legs.map(l => l.distance)).toEqual([100000, 50000]) + expect(run?.legs.map(l => l.hasToll)).toEqual([false, true]) + expect(run?.total.distance).toBe(150000) + expect(run?.total.duration).toBe(5400) // One tolled leg makes the drive tolled. `every` here would call a day with a // single toll booth in it toll-free. - expect(run.total.hasToll).toBe(true) - expect(run.total.coordinates).toHaveLength(SHAPE_POINTS.length * 2) + expect(run?.total.hasToll).toBe(true) + expect(run?.total.coordinates).toHaveLength(SHAPE_POINTS.length * 2) }) it('VALHALLA-PARSE-007: several legs with no summaries of their own are refused', () => { @@ -228,7 +228,7 @@ describe('valhallaRouteAvoiding', () => { }) ) const leg = await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll') - expect(leg!.distance).toBeCloseTo(295700, 0) + expect(leg?.distance).toBeCloseTo(295700, 0) expect(body).toMatchObject({ costing: 'auto', costing_options: { auto: { use_tolls: 0 } }, @@ -378,8 +378,8 @@ describe('valhallaRun over a whole day', () => { const run = await valhallaRun(stops(6), 'driving', []) expect(calls).toBe(1) - expect(run!.legs).toHaveLength(5) - expect(run!.total.distance).toBe(50000) + expect(run?.legs).toHaveLength(5) + expect(run?.total.distance).toBe(50000) }) it('VALHALLA-RUN-008: forwards caller-specific costing options only when supplied', async () => { @@ -414,8 +414,8 @@ describe('valhallaRun over a whole day', () => { // takes the remaining five. Nine pairs plus four. expect(sizes).toEqual([10, 5]) // Thirteen pairs across two requests, none lost and none counted twice. - expect(run!.legs).toHaveLength(13) - expect(run!.total.distance).toBe(130000) + expect(run?.legs).toHaveLength(13) + expect(run?.total.distance).toBe(130000) }) it('VALHALLA-RUN-003: never sends more than ten locations, however long the day', async () => { @@ -464,7 +464,7 @@ describe('valhallaRun over a whole day', () => { const run = await valhallaRun(stops(14), 'driving', ['toll']) - expect(run!.legs).toHaveLength(13) + expect(run?.legs).toHaveLength(13) // First piece, second piece refused, second piece again. expect(calls).toBe(3) }) @@ -732,7 +732,7 @@ describe('through the TREK services (routing relay)', () => { ) const leg = await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll') expect(leg).not.toBeNull() - expect(leg!.distance).toBeCloseTo(295700, 0) + expect(leg?.distance).toBeCloseTo(295700, 0) expect(relayed).toHaveLength(1) expect(relayed[0].action).toBe('route') expect(relayed[0].body).toMatchObject({ costing: 'auto', costing_options: { auto: { use_tolls: 0 } } }) @@ -765,6 +765,7 @@ describe('through the TREK services (routing relay)', () => { http.post(FOSSGIS_VALHALLA, () => HttpResponse.json(answer())), ) await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll') + expect(relayCalls).toBe(1) vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(Date.now() + 11 * 60_000) expect(valhallaBase()).toBe(TREK_VALHALLA) diff --git a/client/src/components/Map/valhallaRoute.ts b/client/src/components/Map/valhallaRoute.ts index d9180a5b7..f1823ddcc 100644 --- a/client/src/components/Map/valhallaRoute.ts +++ b/client/src/components/Map/valhallaRoute.ts @@ -406,7 +406,8 @@ export function resetValhallaTurns(): void { */ async function relayCannotAnswer(response: Response): Promise { if (response.status === 400) { - const data: unknown = await response.clone().json().catch(() => null) + // A body that is not JSON cannot be Valhalla's own refusal, so it reads as the relay's. + const data: unknown = await response.clone().json().catch(() => ({})) return typeof (data as { error_code?: unknown } | null)?.error_code !== 'number' } return [401, 403, 404, 405, 413, 429].includes(response.status) || response.status >= 500 diff --git a/server/tests/unit/nest/photon.client.test.ts b/server/tests/unit/nest/photon.client.test.ts index 164e7e49c..7e657b1cd 100644 --- a/server/tests/unit/nest/photon.client.test.ts +++ b/server/tests/unit/nest/photon.client.test.ts @@ -6,6 +6,7 @@ import { deriveServices } from '../../../src/app-config/boot-derive'; import { PhotonClient } from '../../../src/nest/maps/providers/photon.client'; import { serviceIdentitySlot } from '../../../src/nest/service-identity/service-identity.interface'; +import { oneByOne } from '../../helpers/one-by-one'; import { FakeServiceIdentity, gateFeature, photonAnswer } from '../../helpers/photon'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -142,7 +143,7 @@ describe('the pause after misses in a row', () => { vi.setSystemTime(new Date('2026-10-29T10:00:00Z')); const photon = client(); fetchMock.mockImplementation(async () => photonAnswer([], 503)); - for (let i = 0; i < 4; i++) expect(await photon.search('Rostock')).toBeNull(); + expect(await oneByOne([1, 2, 3, 4], () => photon.search('Rostock'))).toEqual([null, null, null, null]); expect(fetchMock).toHaveBeenCalledTimes(4); expect(await photon.search('Rostock')).toBeNull(); @@ -158,7 +159,7 @@ describe('the pause after misses in a row', () => { fetchMock.mockImplementation(async () => photonAnswer([gateFeature()])); expect(await photon.search('Rostock')).toHaveLength(1); fetchMock.mockImplementation(async () => photonAnswer([], 503)); - for (let i = 0; i < 3; i++) expect(await photon.search('Rostock')).toBeNull(); + expect(await oneByOne([1, 2, 3], () => photon.search('Rostock'))).toEqual([null, null, null]); expect(fetchMock).toHaveBeenCalledTimes(9); }); }); diff --git a/server/tests/unit/nest/roadtrip-router.test.ts b/server/tests/unit/nest/roadtrip-router.test.ts index 3fe7ec641..f120a0173 100644 --- a/server/tests/unit/nest/roadtrip-router.test.ts +++ b/server/tests/unit/nest/roadtrip-router.test.ts @@ -2,6 +2,7 @@ import { DomainError } from '../../../src/nest/common/domain-error'; import { RoadtripRouterService, RouteRefusal } from '../../../src/nest/roadtrip/roadtrip-router.service'; import type { ValhallaRelayAnswer } from '../../../src/nest/routing-relay/routing-relay.service'; import { safeFetchAdminConfigured } from '../../../src/utils/ssrfGuard'; +import { oneByOne } from '../../helpers/one-by-one'; import { valhallaPolyline } from '../../helpers/valhalla'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -735,7 +736,7 @@ describe('server Roadtrip router through the TREK services (routing relay)', () () => Promise.resolve(answer(404, { error: 'Not Found' })), () => Promise.reject(new DomainError(503, 'The TREK routing service is not available on this instance')), ]; - for (const [userId, refusal] of refusals.entries()) { + await oneByOne([...refusals.entries()], async ([userId, refusal]) => { vi.mocked(safeFetchAdminConfigured) .mockReset() .mockResolvedValueOnce(new Response(JSON.stringify(tolled))); @@ -743,7 +744,7 @@ describe('server Roadtrip router through the TREK services (routing relay)', () const route = await settled(setup().router.route(userId, 1, 1, points.slice(0, 2), 'driving', ['toll'])); expect(route.avoidMissed).toEqual([]); expect(vi.mocked(safeFetchAdminConfigured).mock.calls[0][0]).toBe('https://valhalla1.openstreetmap.de/route'); - } + }); }); it('ROUTER-RELAY-003: reads the TREK Valhalla saying no way joins the points as a refusal, and fails on any other error', async () => { diff --git a/server/tests/unit/nest/routing-relay/routing-relay.controller.test.ts b/server/tests/unit/nest/routing-relay/routing-relay.controller.test.ts index 818380047..8603c2809 100644 --- a/server/tests/unit/nest/routing-relay/routing-relay.controller.test.ts +++ b/server/tests/unit/nest/routing-relay/routing-relay.controller.test.ts @@ -5,6 +5,7 @@ import { RoutingRelayController } from '../../../../src/nest/routing-relay/routing-relay.controller'; import type { RoutingRelayService } from '../../../../src/nest/routing-relay/routing-relay.service'; import type { User } from '../../../../src/types'; +import { oneByOne } from '../../../helpers/one-by-one'; import type { Response } from 'express'; import { describe, expect, it, vi } from 'vitest'; @@ -27,18 +28,21 @@ describe('RoutingRelayController', () => { const trace = { encoded_polyline: 'abc', costing: 'pedestrian' } as never; const height = { shape: [{ lat: 47, lon: 11 }] } as never; - for (const [call, action, body] of [ - [(res: Response) => controller.route(user, route, res), 'route', route], - [(res: Response) => controller.traceAttributes(user, trace, res), 'trace_attributes', trace], - [(res: Response) => controller.height(user, height, res), 'height', height], - ] as const) { - const res = response(); - await call(res as unknown as Response); - expect(ask).toHaveBeenLastCalledWith(4, action, body); - expect(res.status).toHaveBeenCalledWith(400); - expect(res.type).toHaveBeenCalledWith('application/json'); - expect(res.send).toHaveBeenCalledWith(answer.body); - } + await oneByOne( + [ + [(res: Response) => controller.route(user, route, res), 'route', route], + [(res: Response) => controller.traceAttributes(user, trace, res), 'trace_attributes', trace], + [(res: Response) => controller.height(user, height, res), 'height', height], + ] as const, + async ([call, action, body]) => { + const res = response(); + await call(res as unknown as Response); + expect(ask).toHaveBeenLastCalledWith(4, action, body); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.type).toHaveBeenCalledWith('application/json'); + expect(res.send).toHaveBeenCalledWith(answer.body); + }, + ); }); it('RELAY-CTRL-003: sends a Retry-After along where the answer names one', async () => { diff --git a/server/tests/unit/nest/routing-relay/routing-relay.service.test.ts b/server/tests/unit/nest/routing-relay/routing-relay.service.test.ts index 6e954122b..3be3333d1 100644 --- a/server/tests/unit/nest/routing-relay/routing-relay.service.test.ts +++ b/server/tests/unit/nest/routing-relay/routing-relay.service.test.ts @@ -14,6 +14,7 @@ import { RoutingRelayService } from '../../../../src/nest/routing-relay/routing- import { ServiceIdentityPort } from '../../../../src/nest/service-identity/service-identity.interface'; import { safeFetchAdminConfigured } from '../../../../src/utils/ssrfGuard'; import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { oneByOne } from '../../../helpers/one-by-one'; import { createTestModule, type TestModule } from '../../../helpers/test-module'; import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -38,6 +39,7 @@ const ROUTE = { costing: 'auto', costing_options: { auto: { use_tolls: 0 } }, }; +const times = (count: number) => Array.from({ length: count }, (_, i) => i); const upstream = (status: number, body: string, extra: Record = {}) => new Response(body, { status, headers: { 'content-type': 'application/json', ...extra } }); @@ -124,7 +126,7 @@ describe('RoutingRelayService.ask', () => { it('RELAY-006: holds every user to 60 questions a minute, each user apart', async () => { vi.mocked(safeFetchAdminConfigured).mockImplementation(async () => upstream(200, '{}')); - for (let i = 0; i < 60; i++) await relay.ask(1, 'height', { shape: [{ lat: 47, lon: 11 }] }); + await oneByOne(times(60), () => relay.ask(1, 'height', { shape: [{ lat: 47, lon: 11 }] })); const refused = await relay.ask(1, 'route', ROUTE).catch((err: unknown) => err); expect(refused).toBeInstanceOf(DomainError); expect(refused).toMatchObject({ status: 429, message: 'Too many routing requests, try again in a minute' }); @@ -135,8 +137,8 @@ describe('RoutingRelayService.ask', () => { it('RELAY-007: holds the whole installation to 100 questions a minute and says when to come back', async () => { vi.mocked(safeFetchAdminConfigured).mockImplementation(async () => upstream(200, '{}')); const height = { shape: [{ lat: 47, lon: 11 }] }; - for (let i = 0; i < 60; i++) await relay.ask(1, 'height', height); - for (let i = 0; i < 40; i++) await relay.ask(2, 'height', height); + await oneByOne(times(60), () => relay.ask(1, 'height', height)); + await oneByOne(times(40), () => relay.ask(2, 'height', height)); const refused = await relay.ask(3, 'route', ROUTE); expect(refused).toMatchObject({ status: 429, retryAfter: '60' }); expect(JSON.parse(refused.body.toString())).toEqual({ error: 'Too many routing requests on this instance' });