feat(transit): fall back between configured public transit providers

This commit is contained in:
Raz Erlich
2026-10-28 08:01:53 +02:00
committed by Maurice
parent 9f155a3191
commit 209f8fe5cc
9 changed files with 367 additions and 16 deletions
@@ -268,6 +268,11 @@ export class GoogleTransitProvider {
return !!(await this.resolveKey(userId)).key;
}
/** Fallback may bill only an operator or instance key, never a personal key. */
async isAvailableForFallback(): Promise<boolean> {
return !!(await this.resolveKey(0)).key;
}
private async call(
endpoint: string,
label: string,
+10 -5
View File
@@ -22,7 +22,7 @@ import {
} from './transit-itinerary.helpers';
import { SCHEDULED_TRANSIT_MODES, type TransitItinerary } from './transit.helpers';
import { TransitService } from './transit.service';
import { idSchema } from '@trek/shared';
import { adminTransitProviderRequestSchema, idSchema, type TransitProvider } from '@trek/shared';
import { z } from 'zod';
@@ -178,13 +178,16 @@ export class TransitMcp {
@Tool({
name: 'create_transit_journey',
description:
'Add one itinerary returned by search_transit_routes to a trip day as a first-class automated public-transit journey.',
'Add one itinerary returned by search_transit_routes to a trip day as a first-class automated public-transit journey. Pass the search response provider unchanged so fallback routes retain their source.',
inputSchema: {
tripId: idSchema,
dayId: idSchema.describe('Trip day on which the journey departs'),
from: transitPlaceInput,
to: transitPlaceInput,
itinerary: transitItinerarySchema,
provider: adminTransitProviderRequestSchema.shape.provider
.optional()
.describe('Provider returned by search_transit_routes'),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
@@ -197,6 +200,7 @@ export class TransitMcp {
from,
to,
itinerary,
provider,
notes,
}: {
tripId: number;
@@ -206,6 +210,7 @@ export class TransitMcp {
// The schema validates exactly the wire TransitItinerary shape; its
// z.infer prints looser optionals, so name the contract type directly.
itinerary: TransitItinerary;
provider?: TransitProvider;
notes?: string;
},
ctx: McpContext,
@@ -228,11 +233,11 @@ export class TransitMcp {
isError: true,
};
}
// The itinerary came from search_transit_routes, which the active backend answered.
const provider = await this.transit.activeProvider(ctx.userId);
// New callers carry the actual search source; omission keeps legacy callers working.
const itineraryProvider = provider ?? (await this.transit.activeProvider(ctx.userId));
let reservationParts: ReturnType<typeof buildTransitReservationParts>;
try {
reservationParts = buildTransitReservationParts(from, to, cleaned, provider);
reservationParts = buildTransitReservationParts(from, to, cleaned, itineraryProvider);
} catch (err) {
return errorResult(err, 'Unable to resolve the transit journey timezones.');
}
+29 -6
View File
@@ -25,8 +25,8 @@ import type { TransitProvider } from '@trek/shared';
* regions Transitous has no feed for. This class stays the entry point and the
* validator either way: the request is checked here, then dispatched, so both
* backends are held to the same coordinate/mode/transfer contract and answer in
* the same compact shape. Transitous remains the default and the fallback —
* see GoogleTransitProvider.isActive.
* the same compact shape. Transitous remains the default. Empty plans try the
* other backend when available; Google fallback requires an admin-set key.
*
* Both responses name the backend that answered. The fallback is silent by
* design, so without this an empty result is indistinguishable between "this
@@ -159,7 +159,7 @@ export class TransitService {
@Inject(transitConfig.KEY) private readonly transitEnv: ConfigType<typeof transitConfig>,
) {}
/** The backend that answers this user's searches: Google where it is set up and keyed, Transitous otherwise. */
/** Configured primary for this user; an empty plan may be answered by the other provider. */
async activeProvider(userId = 0): Promise<TransitProvider> {
return (await this.google.isActive(userId)) ? 'google' : 'transitous';
}
@@ -264,10 +264,33 @@ export class TransitService {
// After validation on purpose: whichever backend answers, the caller is held
// to the same coordinate/mode/transfer contract and gets the same 400s.
if ((await this.activeProvider(userId)) === 'google') {
return { ...(await this.google.plan(q, language, userId)), provider: 'google' };
}
const googlePrimary = (await this.activeProvider(userId)) === 'google';
const primary = googlePrimary
? { ...(await this.google.plan(q, language, userId)), provider: 'google' as const }
: await this.planTransitous(params);
if (primary.itineraries.length > 0) return primary;
// An empty successful response alone triggers fallback. Primary errors keep
// propagating; a secondary outage must not replace a valid empty response.
try {
if (googlePrimary) {
const secondary = await this.planTransitous(params);
if (secondary.itineraries.length > 0) return secondary;
} else if (await this.google.isAvailableForFallback()) {
// Resolve again without a user id so a changed instance key can never
// cause the fallback to bill the caller's personal key.
const secondary = await this.google.plan(q, language, 0);
if (secondary.itineraries.length > 0) return { ...secondary, provider: 'google' };
}
} catch {
// Keep the primary's empty result and its provider attribution.
}
return primary;
}
private async planTransitous(
params: URLSearchParams,
): Promise<{ itineraries: TransitItinerary[]; provider: TransitProvider }> {
const key = `plan:${params.toString()}`;
const cached = cacheGet(key);
if (cached) return { ...(cached as { itineraries: TransitItinerary[] }), provider: 'transitous' };