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
+27 -14
View File
@@ -1,7 +1,8 @@
/**
* Transit proxy e2e — /api/transit/geocode + /api/transit/plan through the real
* JwtAuthGuard against a temp SQLite db. The transit service is mocked; this
* focuses on auth (401), param pass-through and error propagation (#1065).
* JwtAuthGuard against a temp SQLite db. The DI-native TransitService's provider
* methods are stubbed via instance spies (no outbound HTTP); this focuses on
* auth (401), param pass-through and error propagation (#1065).
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
import request from 'supertest';
@@ -20,19 +21,28 @@ const { db } = vi.hoisted(() => {
return { db: tmp };
});
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
const { transitSvc } = vi.hoisted(() => ({ transitSvc: { geocode: vi.fn(), plan: vi.fn() } }));
vi.mock('../../src/services/transitService', () => transitSvc);
// TransitMcp (in the module graph, never invoked here) reaches _shared →
// src/websocket at import time — silence the real ws module.
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
import { TransitModule } from '../../src/nest/transit/transit.module';
import { TransitService } from '../../src/nest/transit/transit.service';
import { DatabaseModule } from '../../src/nest/database/database.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
describe('Transit proxy e2e (real auth guard + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let geocodeSpy: ReturnType<typeof vi.spyOn>;
let planSpy: ReturnType<typeof vi.spyOn>;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [TransitModule] }).compile();
const moduleRef = await Test.createTestingModule({
// DatabaseModule + RealtimeModule are @Global in the app graph;
// TransitModule's DaysModule/ReservationsModule imports need them here.
imports: [DatabaseModule, RealtimeModule, TransitModule],
}).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
@@ -44,11 +54,14 @@ describe('Transit proxy e2e (real auth guard + temp SQLite)', () => {
seedUser(db as never, { id: 1 });
app = await build();
server = app.getHttpServer();
const transit = app.get(TransitService);
geocodeSpy = vi.spyOn(transit, 'geocode') as ReturnType<typeof vi.spyOn>;
planSpy = vi.spyOn(transit, 'plan') as ReturnType<typeof vi.spyOn>;
});
beforeEach(() => {
transitSvc.geocode.mockReset();
transitSvc.plan.mockReset();
geocodeSpy.mockReset();
planSpy.mockReset();
});
afterAll(async () => { await app.close(); });
@@ -59,20 +72,20 @@ describe('Transit proxy e2e (real auth guard + temp SQLite)', () => {
});
it('geocode passes q/lang/near through and returns the service result', async () => {
transitSvc.geocode.mockResolvedValueOnce({ results: [{ name: 'Alexanderplatz' }] });
geocodeSpy.mockResolvedValueOnce({ results: [{ name: 'Alexanderplatz' }] });
const res = await request(server).get('/api/transit/geocode?q=alex&lang=de&near=52.5,13.4').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body.results[0].name).toBe('Alexanderplatz');
expect(transitSvc.geocode).toHaveBeenCalledWith('alex', 'de', '52.5,13.4');
expect(geocodeSpy).toHaveBeenCalledWith('alex', 'de', '52.5,13.4');
});
it('plan passes all params through (arriveBy + maxTransfers coerced)', async () => {
transitSvc.plan.mockResolvedValueOnce({ itineraries: [] });
planSpy.mockResolvedValueOnce({ itineraries: [] });
const res = await request(server)
.get('/api/transit/plan?from=52.5,13.4&to=52.6,13.5&time=2026-07-13T09:00:00Z&arriveBy=true&modes=BUS&maxTransfers=2')
.set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(transitSvc.plan).toHaveBeenCalledWith({
expect(planSpy).toHaveBeenCalledWith({
from: '52.5,13.4', to: '52.6,13.5', time: '2026-07-13T09:00:00Z', arriveBy: true, modes: 'BUS', maxTransfers: 2,
});
});
@@ -80,7 +93,7 @@ describe('Transit proxy e2e (real auth guard + temp SQLite)', () => {
it('service validation errors propagate with their status', async () => {
const err = new Error('from must be "lat,lng"') as Error & { status: number };
err.status = 400;
transitSvc.plan.mockRejectedValueOnce(err);
planSpy.mockRejectedValueOnce(err);
const res = await request(server).get('/api/transit/plan?from=bad&to=1,2').set('Cookie', sessionCookie(1));
expect(res.status).toBe(400);
expect(res.body.error).toContain('lat,lng');
@@ -89,7 +102,7 @@ describe('Transit proxy e2e (real auth guard + temp SQLite)', () => {
it('upstream failures surface as 502', async () => {
const err = new Error('Transit provider error (HTTP 500)') as Error & { status: number };
err.status = 502;
transitSvc.plan.mockRejectedValueOnce(err);
planSpy.mockRejectedValueOnce(err);
const res = await request(server).get('/api/transit/plan?from=1,2&to=3,4').set('Cookie', sessionCookie(1));
expect(res.status).toBe(502);
});
+5 -1
View File
@@ -29,6 +29,8 @@ import { ShareMcp } from '../../src/nest/share/share.mcp';
import { ShareService } from '../../src/nest/share/share.service';
import { TodoMcp } from '../../src/nest/todo/todo.mcp';
import { TodoService } from '../../src/nest/todo/todo.service';
import { TransitMcp } from '../../src/nest/transit/transit.mcp';
import { TransitService } from '../../src/nest/transit/transit.service';
import { FilesService } from '../../src/nest/files/files.service';
import { TripsMcp } from '../../src/nest/trips/trips.mcp';
import { TripsService } from '../../src/nest/trips/trips.service';
@@ -53,6 +55,7 @@ export function createMcpTestRegistry(): McpRegistry {
const todoService = new TodoService(dbService, permissionsService, realtimeService);
const packingService = new PackingService(dbService, permissionsService, realtimeService);
const collabService = new CollabService(dbService, permissionsService, realtimeService);
const reservationsService = new ReservationsService(dbService, permissionsService, budgetService, realtimeService);
const tripsService = new TripsService(
dbService,
todoService,
@@ -73,7 +76,7 @@ export function createMcpTestRegistry(): McpRegistry {
new TodoMcp(todoService),
new PackingMcp(packingService),
new BudgetMcp(budgetService, exchangeRatesService, dbService),
new ReservationsMcp(new ReservationsService(dbService, permissionsService, budgetService, realtimeService), daysService, budgetService),
new ReservationsMcp(reservationsService, daysService, budgetService),
new DayNotesMcp(new DayNotesService(dbService, permissionsService, realtimeService)),
new DaysMcp(daysService, dbService),
new AssignmentsMcp(new AssignmentsService(dbService, permissionsService, realtimeService), daysService),
@@ -82,6 +85,7 @@ export function createMcpTestRegistry(): McpRegistry {
new TripsMcp(tripsService, todoService, collabService),
new ShareMcp(new ShareService(dbService, new SettingsService(dbService), permissionsService)),
new MapsMcp(new MapsService(dbService)),
new TransitMcp(new TransitService(), daysService, reservationsService, dbService),
],
{ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess },
);
+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);
});
});