mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
feat(transit): fall back between configured public transit providers
This commit is contained in:
@@ -146,6 +146,21 @@ async function withHarness(userId: number, scopes: string[] | null, fn: (harness
|
||||
}
|
||||
|
||||
describe('MCP transit tools', () => {
|
||||
it.each(['google', 'transitous'] as const)('preserves the %s route provider', async (provider) => {
|
||||
const { user } = createUser(testDb);
|
||||
planMock.mockResolvedValue({ itineraries: [itinerary], provider });
|
||||
await withHarness(user.id, ['geo:read'], async (harness) => {
|
||||
const routes = parseToolResult(
|
||||
await harness.client.callTool({
|
||||
name: 'search_transit_routes',
|
||||
arguments: { from, to },
|
||||
}),
|
||||
) as { provider: string; itineraries: unknown[]; dropped: number };
|
||||
expect(routes.provider).toBe(provider);
|
||||
expect(routes.itineraries).toHaveLength(1);
|
||||
expect(routes.dropped).toBe(0);
|
||||
});
|
||||
});
|
||||
it('registers search tools for geo scope and create tool for reservations scope', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, ['geo:read'], async (harness) => {
|
||||
@@ -266,6 +281,66 @@ describe('MCP transit tools', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['google', 'transitous'] as const)(
|
||||
'saves the %s fallback source from search rather than the configured primary',
|
||||
async (provider) => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' });
|
||||
const day = await dayOf(trip.id, '2026-12-03');
|
||||
const primary = provider === 'google' ? 'transitous' : 'google';
|
||||
const active = vi.spyOn(TransitService.prototype, 'activeProvider').mockResolvedValue(primary);
|
||||
planMock.mockResolvedValue({ provider, itineraries: [itinerary] });
|
||||
try {
|
||||
await withHarness(user.id, ['geo:read', 'reservations:write'], async (harness) => {
|
||||
const routes = parseToolResult(
|
||||
await harness.client.callTool({
|
||||
name: 'search_transit_routes',
|
||||
arguments: { from, to },
|
||||
}),
|
||||
) as { provider: typeof provider; itineraries: (typeof itinerary)[] };
|
||||
const result = parseToolResult(
|
||||
await harness.client.callTool({
|
||||
name: 'create_transit_journey',
|
||||
arguments: {
|
||||
tripId: trip.id,
|
||||
dayId: day.id,
|
||||
from,
|
||||
to,
|
||||
itinerary: routes.itineraries[0],
|
||||
provider: routes.provider,
|
||||
},
|
||||
}),
|
||||
) as { reservation: { metadata: string } };
|
||||
expect(JSON.parse(result.reservation.metadata).transit.provider).toBe(provider);
|
||||
});
|
||||
expect(active).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
active.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects an unknown itinerary provider before creating a journey', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' });
|
||||
const day = await dayOf(trip.id, '2026-12-03');
|
||||
await withHarness(user.id, ['reservations:write'], async (harness) => {
|
||||
const result = await harness.client.callTool({
|
||||
name: 'create_transit_journey',
|
||||
arguments: {
|
||||
tripId: trip.id,
|
||||
dayId: day.id,
|
||||
from,
|
||||
to,
|
||||
itinerary,
|
||||
provider: 'unknown',
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(await transitCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects dateless, mismatched, and out-of-range journey dates', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const datelessTrip = createTrip(testDb, user.id);
|
||||
|
||||
@@ -44,14 +44,16 @@ const GOOGLE_SETTINGS = { transit_provider: 'google', maps_api_key: 'test-key' }
|
||||
* `GoogleTransitProvider` no longer takes a `DatabaseService` at all. The
|
||||
* settings object already carries exactly the instance-tier value every test
|
||||
* here configures, so `appSettingsStub.getValue` wraps it directly; the
|
||||
* per-user fallback tier was never exercised by this file (none of these
|
||||
* cases seed a per-user row), so it always answers null.
|
||||
* optional personal key exercises the last tier without reading another user.
|
||||
*/
|
||||
function makeProvider(settings: Record<string, string | undefined>): GoogleTransitProvider {
|
||||
function makeProvider(
|
||||
settings: Record<string, string | undefined>,
|
||||
personalKey: string | null = null,
|
||||
): GoogleTransitProvider {
|
||||
const appSettingsStub = {
|
||||
getValue: async (key: string) => settings[key] ?? null,
|
||||
} as unknown as AppSettingsRepository;
|
||||
const usersStub = { getApiKeyColumn: async () => null } as unknown as UsersRepository;
|
||||
const usersStub = { getApiKeyColumn: async () => personalKey } as unknown as UsersRepository;
|
||||
return new GoogleTransitProvider(appSettingsStub, usersStub, noGoogleQuota);
|
||||
}
|
||||
|
||||
@@ -180,6 +182,26 @@ function subwayRoute(): FixtureRoutes {
|
||||
}
|
||||
|
||||
describe('activation', () => {
|
||||
it('allows an instance key for fallback without selecting Google', async () => {
|
||||
expect(await makeProvider({ maps_api_key: 'test-key' }).isAvailableForFallback()).toBe(true);
|
||||
expect(await makeProvider({}).isAvailableForFallback()).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses personal-only fallback but preserves personal keys for Google primary', async () => {
|
||||
const provider = makeProvider({ transit_provider: 'google' }, 'personal-key');
|
||||
expect(await provider.isAvailableForFallback()).toBe(false);
|
||||
expect(await provider.isActive(1)).toBe(true);
|
||||
});
|
||||
|
||||
it('checks quota before making Google available for fallback', async () => {
|
||||
const provider = makeProvider({ maps_api_key: 'test-key' });
|
||||
const exhausted = vi.spyOn(noGoogleQuota, 'exhausted').mockResolvedValue(true);
|
||||
try {
|
||||
expect(await provider.isAvailableForFallback()).toBe(false);
|
||||
} finally {
|
||||
exhausted.mockRestore();
|
||||
}
|
||||
});
|
||||
it('GTRANSIT-001: stays off while the instance is on Transitous, even with a key', async () => {
|
||||
const provider = makeProvider({ maps_api_key: 'test-key' });
|
||||
expect(await provider.isActive(1)).toBe(false);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { GoogleTransitProvider } from '../../../src/nest/transit/google-transit.
|
||||
import { deriveTransitStats, type TransitLeg } from '../../../src/nest/transit/transit.helpers';
|
||||
import { TransitService } from '../../../src/nest/transit/transit.service';
|
||||
import { noGoogleQuota } from '../../helpers/google-quota';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
@@ -290,3 +291,103 @@ describe('upstream base URL', () => {
|
||||
expect(String(fetchMock.mock.calls[0][0])).toMatch(/^https:\/\/api\.transitous\.org\/api\/v1\/geocode\?/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('empty route fallback', () => {
|
||||
let queryNo = 0;
|
||||
const route = { startTime: '2026-07-13T08:00:00Z', endTime: '2026-07-13T08:30:00Z', legs: [] };
|
||||
|
||||
describe.each(['google', 'transitous'] as const)('%s primary', (primary) => {
|
||||
it.each(['primary-success', 'primary-error', 'empty', 'secondary-error', 'unavailable'])('%s', async (outcome) => {
|
||||
const googlePrimary = primary === 'google';
|
||||
const google = {
|
||||
isActive: vi.fn().mockResolvedValue(googlePrimary),
|
||||
isAvailableForFallback: vi.fn().mockResolvedValue(true),
|
||||
plan: vi.fn(),
|
||||
};
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
TransitService,
|
||||
{ provide: GoogleTransitProvider, useValue: google },
|
||||
{ provide: transitConfig.KEY, useValue: transitConfig() },
|
||||
],
|
||||
}).compile();
|
||||
try {
|
||||
const service = module.get(TransitService);
|
||||
google.plan.mockReset();
|
||||
fetchMock.mockReset();
|
||||
google.isAvailableForFallback.mockClear().mockResolvedValue(outcome !== 'unavailable');
|
||||
const q = { from: `50.${queryNo++},13`, to: '52,14' };
|
||||
const error = new Error('provider unavailable');
|
||||
const primaryData = { itineraries: outcome === 'primary-success' ? [route] : [] };
|
||||
if (googlePrimary) {
|
||||
if (outcome === 'primary-error') google.plan.mockRejectedValue(error);
|
||||
else google.plan.mockResolvedValue(primaryData);
|
||||
if (outcome === 'secondary-error') fetchMock.mockRejectedValue(error);
|
||||
else fetchMock.mockResolvedValue(okJson({ itineraries: [] }));
|
||||
} else {
|
||||
if (outcome === 'primary-error') fetchMock.mockRejectedValue(error);
|
||||
else fetchMock.mockResolvedValue(okJson(primaryData));
|
||||
if (outcome === 'secondary-error') google.plan.mockRejectedValue(error);
|
||||
else google.plan.mockResolvedValue({ itineraries: [] });
|
||||
}
|
||||
if (outcome === 'primary-error') {
|
||||
await expect(service.plan(q)).rejects.toBe(error);
|
||||
} else {
|
||||
const result = await service.plan(q);
|
||||
expect(result.provider).toBe(primary);
|
||||
expect(result.itineraries).toHaveLength(outcome === 'primary-success' ? 1 : 0);
|
||||
}
|
||||
if (outcome.startsWith('primary-')) {
|
||||
expect(googlePrimary ? fetchMock : google.plan).not.toHaveBeenCalled();
|
||||
}
|
||||
if (!googlePrimary && outcome === 'unavailable') expect(google.plan).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await module.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['google', 'transitous'] as const)('falls back from %s and preserves request options', async (primary) => {
|
||||
const google = {
|
||||
isActive: vi.fn().mockResolvedValue(primary === 'google'),
|
||||
isAvailableForFallback: vi.fn().mockResolvedValue(true),
|
||||
plan: vi.fn().mockResolvedValue({ itineraries: primary === 'google' ? [] : [route] }),
|
||||
};
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
TransitService,
|
||||
{ provide: GoogleTransitProvider, useValue: google },
|
||||
{ provide: transitConfig.KEY, useValue: transitConfig() },
|
||||
],
|
||||
}).compile();
|
||||
try {
|
||||
fetchMock.mockResolvedValue(okJson({ itineraries: primary === 'google' ? [route] : [] }));
|
||||
const q = {
|
||||
from: `51.${queryNo++},13`,
|
||||
to: '52,14',
|
||||
time: '2026-07-13T08:00:00Z',
|
||||
arriveBy: true,
|
||||
modes: 'BUS',
|
||||
maxTransfers: 2,
|
||||
};
|
||||
const service = module.get(TransitService);
|
||||
const result = await service.plan(q, 'de', 42);
|
||||
expect(result.provider).toBe(primary === 'google' ? 'transitous' : 'google');
|
||||
expect(result.itineraries).toHaveLength(1);
|
||||
expect(google.plan).toHaveBeenCalledWith(q, 'de', primary === 'google' ? 42 : 0);
|
||||
const params = new URL(String(fetchMock.mock.calls[0][0])).searchParams;
|
||||
expect(Object.fromEntries(params)).toMatchObject({
|
||||
fromPlace: q.from,
|
||||
toPlace: q.to,
|
||||
arriveBy: 'true',
|
||||
transitModes: 'BUS',
|
||||
maxTransfers: '2',
|
||||
time: '2026-07-13T08:00:00.000Z',
|
||||
});
|
||||
await service.plan(q, 'de', 42);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await module.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user