chore: move transit backend to proper DI

Includes the quirk-repair pass (upstream timeout + size cap, LRU cache, NaN-duration guard) that maps landed as a sibling fix commit.
This commit is contained in:
jubnl
2026-07-29 21:39:51 +02:00
parent a7cb4eb880
commit f4bf7cf3dc
17 changed files with 813 additions and 623 deletions
+17 -14
View File
@@ -28,30 +28,32 @@ const { testDb, dbMock } = vi.hoisted(() => {
return { testDb: db, dbMock: mock };
});
const { geocodeMock, planMock, broadcastMock, notifyBookingChangeMock } = vi.hoisted(() => ({
geocodeMock: vi.fn(),
planMock: vi.fn(),
const { broadcastMock } = vi.hoisted(() => ({
broadcastMock: vi.fn(),
notifyBookingChangeMock: vi.fn(),
}));
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/services/transitService', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/services/transitService')>()),
geocode: geocodeMock,
plan: planMock,
}));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/nest/reservations/reservations.bridge', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/nest/reservations/reservations.bridge')>()),
notifyBookingChange: notifyBookingChangeMock,
}));
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { ReservationsService } from '../../../src/nest/reservations/reservations.service';
import { TransitService } from '../../../src/nest/transit/transit.service';
// The transit tools live on the DI-discovered transit.mcp.ts since the transit
// fold; the test registry builds a real TransitService (and injects a real
// ReservationsService over the mocked db proxy), so stub the provider methods
// on the prototype (no auto-restore in the vitest config — these survive
// across tests, exactly like the old module mocks did).
const geocodeMock = vi.spyOn(TransitService.prototype, 'geocode');
const planMock = vi.spyOn(TransitService.prototype, 'plan');
const notifyBookingChangeMock = vi
.spyOn(ReservationsService.prototype, 'notifyBookingChange')
.mockImplementation(() => {});
const from = { name: 'Namba', lat: 34.667, lng: 135.501 };
const to = { name: 'Umeda', lat: 34.702, lng: 135.496 };
const itinerary = {
@@ -118,7 +120,8 @@ beforeEach(() => {
geocodeMock.mockReset();
planMock.mockReset();
broadcastMock.mockReset();
notifyBookingChangeMock.mockReset();
// mockReset would fall back to the real notification write — keep it stubbed.
notifyBookingChangeMock.mockReset().mockImplementation(() => {});
delete process.env.DEMO_MODE;
invalidatePermissionsCache();
});
@@ -1,9 +1,16 @@
/**
* Unit tests for transitService — TRANSIT-SVC-001..010.
* The Transitous/MOTIS proxy (#1065): input validation, mode whitelist,
* response mapping (colors, walk time, wall-clock duration) and caching.
* Unit tests for the DI-native TransitService — TRANSIT-SVC-001..011, moved
* 1:1 from the legacy tests/unit/services/transitService.test.ts when the
* transit domain went DI-native. The Transitous/MOTIS proxy (#1065): input
* validation, mode whitelist, response mapping (colors, walk time, wall-clock
* duration) and caching.
*
* The response cache is deliberately MODULE-scoped (shared by every
* TransitService instance), so it persists across the tests in this file —
* every case uses its own coordinates/query to stay isolated.
*/
import { deriveTransitStats, geocode, plan, type TransitLeg } from '../../../src/services/transitService';
import { deriveTransitStats, type TransitLeg } from '../../../src/nest/transit/transit.helpers';
import { TransitService } from '../../../src/nest/transit/transit.service';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
@@ -14,6 +21,7 @@ vi.mock('../../../src/app-config', async (importOriginal) => {
vi.mock('../../../src/nest/maps/maps.helpers', () => ({ buildUserAgent: () => 'TREK-Test-UA' }));
const fetchMock = vi.fn();
const svc = new TransitService();
beforeEach(() => {
vi.stubGlobal('fetch', fetchMock);
@@ -21,13 +29,17 @@ beforeEach(() => {
});
afterEach(() => vi.unstubAllGlobals());
function okJson(data: unknown) {
return { ok: true, json: async () => data };
function okJson(data: unknown, contentLength: number | null = null) {
return {
ok: true,
headers: { get: () => (contentLength === null ? null : String(contentLength)) },
json: async () => data,
};
}
describe('geocode', () => {
it('TRANSIT-SVC-001: returns [] without calling upstream for short queries', async () => {
const r = await geocode('a');
const r = await svc.geocode('a');
expect(r.results).toEqual([]);
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -39,7 +51,7 @@ describe('geocode', () => {
{ name: 'no-coords' },
]),
);
const r = await geocode('alexanderplatz-u1');
const r = await svc.geocode('alexanderplatz-u1');
expect(r.results).toEqual([{ name: 'Alexanderplatz', lat: 52.52, lng: 13.41, type: 'STOP', area: 'Berlin' }]);
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toContain('/api/v1/geocode?');
@@ -48,30 +60,30 @@ describe('geocode', () => {
it('TRANSIT-SVC-003: ignores an invalid near bias instead of forwarding it', async () => {
fetchMock.mockResolvedValueOnce(okJson([]));
await geocode('hauptbahnhof-x1', undefined, 'not,coords');
await svc.geocode('hauptbahnhof-x1', undefined, 'not,coords');
expect(String(fetchMock.mock.calls[0][0])).not.toContain('place=');
});
});
describe('plan validation', () => {
it('TRANSIT-SVC-004: rejects malformed coordinates with 400', async () => {
await expect(plan({ from: 'x', to: '52.5,13.4' })).rejects.toMatchObject({ status: 400 });
await expect(plan({ from: '95,13.4', to: '52.5,13.4' })).rejects.toMatchObject({ status: 400 });
await expect(svc.plan({ from: 'x', to: '52.5,13.4' })).rejects.toMatchObject({ status: 400 });
await expect(svc.plan({ from: '95,13.4', to: '52.5,13.4' })).rejects.toMatchObject({ status: 400 });
expect(fetchMock).not.toHaveBeenCalled();
});
it('TRANSIT-SVC-005: rejects modes outside the whitelist', async () => {
await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', modes: 'BUS,CAR' })).rejects.toMatchObject({
await expect(svc.plan({ from: '52.50,13.40', to: '52.51,13.41', modes: 'BUS,CAR' })).rejects.toMatchObject({
status: 400,
});
expect(fetchMock).not.toHaveBeenCalled();
});
it('TRANSIT-SVC-006: rejects out-of-range maxTransfers and bad time', async () => {
await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', maxTransfers: 99 })).rejects.toMatchObject({
await expect(svc.plan({ from: '52.50,13.40', to: '52.51,13.41', maxTransfers: 99 })).rejects.toMatchObject({
status: 400,
});
await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', time: 'not-a-date' })).rejects.toMatchObject({
await expect(svc.plan({ from: '52.50,13.40', to: '52.51,13.41', time: 'not-a-date' })).rejects.toMatchObject({
status: 400,
});
});
@@ -126,7 +138,7 @@ describe('plan mapping', () => {
it('TRANSIT-SVC-007: maps legs compactly, normalises GTFS colors and counts walk seconds', async () => {
fetchMock.mockResolvedValueOnce(okJson(motisResponse));
const r = await plan({ from: '52.5000,13.4000', to: '52.5100,13.4100' });
const r = await svc.plan({ from: '52.5000,13.4000', to: '52.5100,13.4100' });
expect(r.itineraries).toHaveLength(1);
const it = r.itineraries[0];
// Wall-clock 08:00→08:30, not the reported 999s.
@@ -173,7 +185,7 @@ describe('plan mapping', () => {
],
}),
);
const r = await plan({ from: '49.0090,8.4004', to: '50.0510,8.5706' });
const r = await svc.plan({ from: '49.0090,8.4004', to: '50.0510,8.5706' });
const [longDistance, regional] = r.itineraries[0].legs;
expect(longDistance.line).toBe('ICE 72');
// Feeds that only supply routeShortName keep working.
@@ -182,7 +194,7 @@ describe('plan mapping', () => {
it('TRANSIT-SVC-008: forwards only whitelisted params and pins directModes=WALK', async () => {
fetchMock.mockResolvedValueOnce(okJson({ itineraries: [] }));
await plan({
await svc.plan({
from: '48.1000,11.5000',
to: '48.2000,11.6000',
modes: 'BUS,TRAM',
@@ -200,13 +212,55 @@ describe('plan mapping', () => {
it('TRANSIT-SVC-009: identical plans hit the cache (single upstream call)', async () => {
fetchMock.mockResolvedValue(okJson({ itineraries: [] }));
await plan({ from: '40.0000,-3.0000', to: '40.1000,-3.1000' });
await plan({ from: '40.0000,-3.0000', to: '40.1000,-3.1000' });
await svc.plan({ from: '40.0000,-3.0000', to: '40.1000,-3.1000' });
await svc.plan({ from: '40.0000,-3.0000', to: '40.1000,-3.1000' });
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('TRANSIT-SVC-010: upstream failure surfaces as a 502-style error', async () => {
fetchMock.mockResolvedValueOnce({ ok: false, status: 500 });
await expect(plan({ from: '41.0000,2.0000', to: '41.1000,2.1000' })).rejects.toMatchObject({ status: 502 });
await expect(svc.plan({ from: '41.0000,2.0000', to: '41.1000,2.1000' })).rejects.toMatchObject({ status: 502 });
});
});
describe('quirk repairs (DI fold fix pass)', () => {
it('TRANSIT-SVC-012: upstream requests carry an abort-timeout signal', async () => {
fetchMock.mockResolvedValueOnce(okJson([]));
await svc.geocode('timeout-probe-station');
const [, init] = fetchMock.mock.calls[0];
expect(init.signal).toBeInstanceOf(AbortSignal);
});
it('TRANSIT-SVC-013: unparseable provider timestamps yield duration 0, not NaN', () => {
const stats = deriveTransitStats('not-a-date', 'also-not-a-date', []);
expect(stats.duration).toBe(0);
// Parseable dates keep the wall-clock behaviour.
expect(deriveTransitStats('2026-07-13T08:00:00Z', '2026-07-13T08:30:00Z', []).duration).toBe(1800);
});
it('TRANSIT-SVC-014: an oversized upstream response is refused as a provider error', async () => {
fetchMock.mockResolvedValueOnce(okJson([], 6_000_000));
await expect(svc.geocode('oversize-probe-station')).rejects.toMatchObject({
status: 502,
message: 'Transit provider error (response too large)',
});
});
it('TRANSIT-SVC-015: the cache is LRU — a re-read entry survives eviction pressure', async () => {
fetchMock.mockResolvedValue(okJson([]));
// Flush whatever earlier tests cached: 205 distinct fillers guarantee the
// 200-entry Map holds only fillers afterwards.
for (let i = 0; i < 205; i++) await svc.geocode(`lru-fill-${i}`);
// Insert the probe, then age it to the oldest position with 199 more inserts.
await svc.geocode('lru-probe-station');
for (let i = 0; i < 199; i++) await svc.geocode(`lru-age-${i}`);
const fetchesBeforeTouch = fetchMock.mock.calls.length;
// Touch the probe (cache hit — no fetch) so LRU moves it off the eviction edge…
await svc.geocode('lru-probe-station');
expect(fetchMock.mock.calls.length).toBe(fetchesBeforeTouch);
// …then trigger one eviction. FIFO would evict the probe; LRU evicts lru-age-0.
await svc.geocode('lru-evictor-station');
await svc.geocode('lru-probe-station');
expect(fetchMock.mock.calls.length).toBe(fetchesBeforeTouch + 1);
});
});