feat(transit): let an admin route transit search through Google

Transitous has no GTFS coverage for much of Asia, so a search between two
Osaka subway stops finds nothing — the stops are not in the feed at all.
Add Google as an optional backend behind an admin setting, reusing the
install's existing Places key, and fall back to Transitous whenever no
key resolves.

Uses the Routes API rather than the legacy Directions endpoint the
request named: every other Google call here already speaks the
v1/X-Goog-Api-Key family, and Google closed the legacy endpoint to Cloud
projects created after March 2025.

Google returns walking as turn-by-turn navigation steps where MOTIS
returns one leg per walking segment, so consecutive walk steps are
coalesced into a single leg — otherwise a finely-sliced walk pushed a
real journey past the 20-leg cap and the whole itinerary was dropped.

Both responses now name the backend that answered. The fallback is
silent by design, which left an empty result ambiguous between "no data
here" and "the provider you picked never ran", and the admin panel warns
when Google is selected but no key resolves — or when only the admin's
own key is set, which serves them and nobody else.

Cost shaped the implementation, since Google bills where Transitous does
not: both field masks are cut to the cheapest SKU tier that still
answers the question, cache TTLs are longer than the Transitous path's,
and route alternatives ride along inside the already-billed request.

Addresses #1699
This commit is contained in:
Konstantinos Thermos
2026-09-03 19:35:23 +03:00
committed by Maurice
parent 8e2840b29d
commit 2a0ceb2687
72 changed files with 2065 additions and 35 deletions
+35
View File
@@ -3,6 +3,10 @@ import { ADDON_IDS } from '../../addons';
import { DatabaseService } from '../database/database.service';
import type { Addon } from '../../types';
import { getPhotoProviderConfig } from '../memories/memories.helpers';
import { readTransitProvider, writeTransitProvider } from '../transit/transit-provider';
import { resolveApiKey, type ApiKeySource } from '../settings/instance-api-keys';
import { readEnv } from '../../app-config';
import type { TransitProvider } from '@trek/shared';
/**
* Thin wrapper around the enabled-addons + photo-provider read that the legacy
@@ -203,4 +207,35 @@ export class AddonsService {
}
updatePlacesEnrich(enabled: boolean) { return this.writeFlag('places_enrich_enabled', enabled); }
// ── Transit backend (#1699) ────────────────────────────────────────────────
// Not a flag: two named backends, so it stores the name rather than a
// boolean. The read/write pair lives in transit/transit-provider.ts because
// TransitService reads the same row on every request — one key, one reader,
// one writer.
/**
* Where the Google key would come from for this caller, or null if nowhere.
*
* Reported alongside the provider so the admin panel can say that picking
* Google changed nothing. The fallback to Transitous is deliberate and
* silent at request time (GoogleTransitProvider.isActive), which means the
* only place it can be surfaced is here, before a search is ever run.
*
* The distinction between 'instance' and 'user-row' is the one that matters:
* the resolver's last step is the caller's OWN row, so an admin holding a
* personal key gets Google while every other member silently gets Transitous
* — the #1939 shape, one layer up.
*/
private googleKeySource(userId: number): ApiKeySource | null {
return resolveApiKey(this.dbs, 'maps_api_key', userId, readEnv().maps.placesApiKey).source;
}
getTransitProvider(userId = 0) {
return { provider: readTransitProvider(this.dbs), googleKeySource: this.googleKeySource(userId) };
}
updateTransitProvider(provider: TransitProvider, userId = 0) {
return { provider: writeTransitProvider(this.dbs, provider), googleKeySource: this.googleKeySource(userId) };
}
}
+13
View File
@@ -19,6 +19,7 @@ import {
AdminNotificationPreferencesDto,
AdminDefaultUserSettingsDto,
AdminTestNotificationDto,
AdminTransitProviderDto,
} from './admin.dto';
import { PluginRuntimeService } from '../plugins/plugin-runtime.service';
import { AddonsService } from '../addons/addons.service';
@@ -255,6 +256,18 @@ export class AdminController {
return features;
}
// Which backend answers /api/transit (#1699). Transitous unless an admin
// says otherwise, and still Transitous if Google is picked without a key.
@Get('transit-provider')
getTransitProvider(@CurrentUser() user: User) { return this.addons.getTransitProvider(user.id); }
@Put('transit-provider')
updateTransitProvider(@CurrentUser() user: User, @Body() body: AdminTransitProviderDto, @Req() req: Request) {
const result = this.addons.updateTransitProvider(body.provider, user.id);
this.audit.writeAudit({ userId: user.id, action: 'admin.transit_provider', ip: getClientIp(req), details: { provider: result.provider } });
return result;
}
// ── Addons ──
@Get('addons')
listAddons() { return { addons: this.admin.listAddons() }; }
+3 -1
View File
@@ -12,6 +12,7 @@ import {
adminNotificationPreferencesRequestSchema,
adminDefaultUserSettingsRequestSchema,
adminTestNotificationRequestSchema,
adminTransitProviderRequestSchema,
} from '@trek/shared';
/**
@@ -20,7 +21,7 @@ import {
* parameter typed with one of these classes by metatype — the Zod schemas in
* shared/ remain the single source of truth for the wire contract.
*
* Twelve classes cover the twenty grandfathered AdminController body contracts:
* Thirteen classes cover the AdminController body contracts:
* the four feature toggles share AdminFeatureToggleDto and the six
* packing-template create/update routes share AdminTemplateNameDto.
*/
@@ -36,3 +37,4 @@ export class AdminCollabFeaturesDto extends createZodDto(adminCollabFeaturesRequ
export class AdminNotificationPreferencesDto extends createZodDto(adminNotificationPreferencesRequestSchema) {}
export class AdminDefaultUserSettingsDto extends createZodDto(adminDefaultUserSettingsRequestSchema) {}
export class AdminTestNotificationDto extends createZodDto(adminTestNotificationRequestSchema) {}
export class AdminTransitProviderDto extends createZodDto(adminTransitProviderRequestSchema) {}
@@ -1,5 +1,6 @@
import { DatabaseService } from '../database/database.service';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import type { ApiKeySource } from '@trek/shared';
/**
* The third-party keys that belong to the instance rather than to a person.
@@ -26,8 +27,11 @@ export const INSTANCE_API_KEY_NAMES: readonly InstanceApiKeyName[] = ['maps_api_
* Where a resolved key came from. Logged beside a provider error so "works for
* the admin, 403 for everyone else" is one line in the log rather than a
* guessing game; the key itself is never logged.
*
* Defined in @trek/shared because the admin transit-provider response (#1699)
* puts it on the wire — re-declaring the union here would fork the contract.
*/
export type ApiKeySource = 'operator-env' | 'instance' | 'user-row';
export type { ApiKeySource };
// Full statements rather than an interpolated column: the name doubles as the
// users column AND the app_settings key, and identifiers only ever come from a
@@ -0,0 +1,541 @@
import { Injectable } from '@nestjs/common';
import { readEnv } from '../../app-config';
import { DatabaseService } from '../database/database.service';
import { toApiLang } from '../maps/maps.helpers';
import { resolveApiKey, type ApiKeySource } from '../settings/instance-api-keys';
import { readTransitProvider } from './transit-provider';
import {
decodePolyline,
deriveTransitStats,
encodePolyline,
type PlanQuery,
type TransitItinerary,
type TransitLeg,
type TransitLegStop,
type TransitPlace,
} from './transit.helpers';
/**
* Google as the transit backend (#1699), for the regions Transitous has no GTFS
* for — most of Asia, where a search between two Osaka subway stops returns
* nothing because the stops are not in the feed at all.
*
* Two calls stand behind the two /api/transit routes: Places Text Search for
* the from/to picker, and the Routes API for the plan. The Routes API, not the
* legacy Directions API the request named: every other Google call in this repo
* already speaks the v1/X-Goog-Api-Key family, and Google closed the legacy
* endpoint to Cloud projects created after March 2025 — a new self-hoster
* cannot enable it.
*
* The key is the one the install already has (`maps_api_key`, operator env →
* instance → the caller's own row), so nothing new to configure.
*
* Cost is the design constraint, because unlike Transitous this one bills:
*
* - Both field masks are cut to the cheapest SKU tier that still answers the
* question. The picker deliberately does NOT reuse maps.helpers'
* SEARCH_TEXT_FIELD_MASK: its rating/website/phone fields bill Text Search at
* Enterprise, and a station picker shows none of them.
* - The cache below is much longer-lived than TransitService's 60s one. A
* station's coordinates do not move, and transit search here plans trips days
* out rather than catching the next train, so minutes-old departure times are
* the right trade for not paying twice.
* - `computeAlternativeRoutes` is on: alternatives ride along in the one
* request that was already billed.
*/
const ROUTES_ENDPOINT = 'https://routes.googleapis.com/directions/v2:computeRoutes';
const PLACES_SEARCH_ENDPOINT = 'https://places.googleapis.com/v1/places:searchText';
// Text Search at Pro: names, address, coordinates and types, and nothing that
// would push the call into the Enterprise tier.
const STATION_FIELD_MASK = 'places.displayName,places.formattedAddress,places.location,places.types';
// Routes at Pro — steps and transitDetails are what a transit itinerary IS, so
// the tier is unavoidable; everything beyond it (travelAdvisory, viewport,
// localizedValues) is left out.
const ROUTES_FIELD_MASK = [
'routes.legs.steps.travelMode',
'routes.legs.steps.staticDuration',
'routes.legs.steps.distanceMeters',
'routes.legs.steps.startLocation.latLng',
'routes.legs.steps.endLocation.latLng',
'routes.legs.steps.polyline.encodedPolyline',
'routes.legs.steps.transitDetails.stopDetails',
'routes.legs.steps.transitDetails.headsign',
'routes.legs.steps.transitDetails.stopCount',
'routes.legs.steps.transitDetails.transitLine.name',
'routes.legs.steps.transitDetails.transitLine.nameShort',
'routes.legs.steps.transitDetails.transitLine.color',
'routes.legs.steps.transitDetails.transitLine.textColor',
'routes.legs.steps.transitDetails.transitLine.agencies.name',
'routes.legs.steps.transitDetails.transitLine.vehicle.type',
].join(',');
const TIMEOUT_MS = 10_000;
const MAX_RESPONSE_BYTES = 5_000_000;
// Google encodes polylines at precision 5; MOTIS uses 6. The client reads the
// precision off the leg, so both render correctly.
const GOOGLE_POLYLINE_PRECISION = 5;
const GEOCODE_TTL = 30 * 60 * 1000;
const PLAN_TTL = 5 * 60 * 1000;
const CACHE_MAX = 200;
const cache = new Map<string, { at: number; ttl: number; data: unknown }>();
function cacheGet(key: string): unknown | null {
const hit = cache.get(key);
if (!hit) return null;
if (Date.now() - hit.at > hit.ttl) {
cache.delete(key);
return null;
}
cache.delete(key);
cache.set(key, hit);
return hit.data;
}
function cacheSet(key: string, ttl: number, data: unknown): void {
if (cache.size >= CACHE_MAX) {
const oldest = cache.keys().next().value;
if (oldest !== undefined) cache.delete(oldest);
}
cache.set(key, { at: Date.now(), ttl, data });
}
/** Exposed for tests — the cache is module-scoped for the same reason TransitService's is. */
export function clearGoogleTransitCache(): void {
cache.clear();
}
/**
* What a caller may filter by → what `transitPreferences.allowedTravelModes`
* can express. Google has five buckets; TREK offers thirteen, so ferry, cable
* and the fine-grained rail splits have no wire equivalent and are dropped from
* the request and enforced on the response instead (see `matchesRequestedModes`).
*/
const GOOGLE_TRAVEL_MODES: Record<string, string> = {
BUS: 'BUS',
COACH: 'BUS',
SUBWAY: 'SUBWAY',
TRAM: 'LIGHT_RAIL',
RAIL: 'TRAIN',
HIGHSPEED_RAIL: 'TRAIN',
LONG_DISTANCE: 'TRAIN',
NIGHT_RAIL: 'TRAIN',
REGIONAL_RAIL: 'TRAIN',
SUBURBAN: 'TRAIN',
};
/** Google's vehicle taxonomy → the mode tokens the client already has icons for. */
const VEHICLE_MODES: Record<string, string> = {
BUS: 'BUS',
INTERCITY_BUS: 'COACH',
TROLLEYBUS: 'BUS',
SHARE_TAXI: 'BUS',
TRAM: 'TRAM',
CABLE_CAR: 'TRAM',
SUBWAY: 'SUBWAY',
METRO_RAIL: 'SUBWAY',
MONORAIL: 'SUBWAY',
COMMUTER_TRAIN: 'SUBURBAN',
HEAVY_RAIL: 'RAIL',
RAIL: 'RAIL',
HIGH_SPEED_TRAIN: 'HIGHSPEED_RAIL',
LONG_DISTANCE_TRAIN: 'LONG_DISTANCE',
FERRY: 'FERRY',
FUNICULAR: 'FUNICULAR',
GONDOLA_LIFT: 'AERIAL_LIFT',
};
/** '600s' → 600. Google's Duration JSON encoding; anything else is 0. */
function parseDuration(value: unknown): number {
if (typeof value !== 'string') return 0;
const seconds = Number(value.replace(/s$/, ''));
return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds) : 0;
}
function safeColor(v: unknown): string | null {
if (typeof v !== 'string') return null;
const hex = v.trim().replace(/^#/, '');
return /^[0-9a-fA-F]{6}$/.test(hex) || /^[0-9a-fA-F]{3}$/.test(hex) ? `#${hex}` : null;
}
function parseCoord(value: string): { latitude: number; longitude: number } {
const [lat, lng] = value.split(',').map(Number);
return { latitude: lat, longitude: lng };
}
function isoOrNull(value: unknown): string | null {
if (typeof value !== 'string' || !value) return null;
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
}
function shiftIso(iso: string, seconds: number): string {
return new Date(new Date(iso).getTime() + seconds * 1000).toISOString();
}
interface GoogleLatLng { latitude?: number; longitude?: number }
interface GoogleStop { name?: string; location?: { latLng?: GoogleLatLng } }
interface GoogleStep {
travelMode?: string;
staticDuration?: string;
distanceMeters?: number;
startLocation?: { latLng?: GoogleLatLng };
endLocation?: { latLng?: GoogleLatLng };
polyline?: { encodedPolyline?: string };
transitDetails?: {
stopDetails?: {
departureStop?: GoogleStop;
arrivalStop?: GoogleStop;
departureTime?: string;
arrivalTime?: string;
};
headsign?: string;
stopCount?: number;
transitLine?: {
name?: string;
nameShort?: string;
color?: string;
textColor?: string;
agencies?: Array<{ name?: string }>;
vehicle?: { type?: string };
};
};
}
function stopFrom(stop: GoogleStop | undefined, fallback: GoogleLatLng | undefined, name: string): TransitLegStop {
return {
name: stop?.name || name,
lat: stop?.location?.latLng?.latitude ?? fallback?.latitude ?? 0,
lng: stop?.location?.latLng?.longitude ?? fallback?.longitude ?? 0,
time: null,
scheduledTime: null,
// The Routes API carries no platform/track field — MOTIS's `track` has no
// Google equivalent, so it stays null rather than being faked from headsign.
track: null,
};
}
@Injectable()
export class GoogleTransitProvider {
constructor(private readonly database: DatabaseService) {}
private resolveKey(userId: number): { key: string | null; source: ApiKeySource | null } {
return resolveApiKey(this.database, 'maps_api_key', userId, readEnv().maps.placesApiKey);
}
/**
* True only when the admin picked Google AND a key actually resolves for this
* caller. "Fall back to Transitous if no Google key is set" is the requested
* behaviour and the safe one: the alternative is every transit search 403ing
* on an install that flipped the switch before pasting a key.
*/
isActive(userId: number): boolean {
if (readTransitProvider(this.database) !== 'google') return false;
return !!this.resolveKey(userId).key;
}
private async call(endpoint: string, label: string, apiKey: string, body: unknown, fieldMask: string): Promise<unknown> {
console.debug(`[Google API] ${label} → ${endpoint}`);
const res = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Goog-Api-Key': apiKey,
'X-Goog-FieldMask': fieldMask,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
const length = Number(res.headers?.get('content-length') ?? 0);
if (length > MAX_RESPONSE_BYTES) {
const err = new Error('Transit provider error (response too large)') as Error & { status: number };
err.status = 502;
throw err;
}
const data = (await res.json()) as { error?: { message?: string } };
if (!res.ok) {
const err = new Error(data?.error?.message || `Transit provider error (HTTP ${res.status})`) as Error & {
status: number;
};
err.status = res.status === 429 ? 429 : 502;
throw err;
}
return data;
}
/** Station/place search for the from/to pickers. `near` biases results. */
async geocode(text: string, language: string | undefined, near: string | undefined, userId: number): Promise<{ results: TransitPlace[] }> {
const { key: apiKey, source } = this.resolveKey(userId);
if (!apiKey) {
const err = new Error('Transit provider error (no Google API key configured)') as Error & { status: number };
err.status = 502;
throw err;
}
const key = `g:geo:${text}|${language ?? ''}|${near ?? ''}`;
const cached = cacheGet(key);
if (cached) return cached as { results: TransitPlace[] };
const body: Record<string, unknown> = {
textQuery: text,
languageCode: toApiLang(language),
// Capped at what the picker renders — the response is smaller and the
// request bills the same either way.
pageSize: 8,
};
if (near) {
const { latitude, longitude } = parseCoord(near);
body.locationBias = { circle: { center: { latitude, longitude }, radius: 50000 } };
}
let data: { places?: Array<{ displayName?: { text?: string }; formattedAddress?: string; location?: GoogleLatLng; types?: string[] }> };
try {
data = (await this.call(PLACES_SEARCH_ENDPOINT, 'transitGeocode', apiKey, body, STATION_FIELD_MASK)) as typeof data;
} catch (err) {
console.error(`[Transit] google geocode failed userId=${userId} keySource=${source}`);
throw err;
}
const results: TransitPlace[] = (data.places || []).slice(0, 8).flatMap((place) => {
const lat = place.location?.latitude;
const lng = place.location?.longitude;
const name = place.displayName?.text;
if (typeof lat !== 'number' || typeof lng !== 'number' || !name) return [];
// MOTIS answers STOP for a station and PLACE for anything else; the picker
// renders the two differently, so map Google's type list onto the same pair.
const isStop = (place.types || []).some((t) => t.includes('station') || t.includes('transit') || t.includes('stop'));
return [{ name, lat, lng, type: isStop ? 'STOP' : 'PLACE', area: place.formattedAddress || null }];
});
const payload = { results };
cacheSet(key, GEOCODE_TTL, payload);
return payload;
}
/** Route search between two coordinates. Returns the same compact shape MOTIS is mapped to. */
async plan(q: PlanQuery, language: string | undefined, userId: number): Promise<{ itineraries: TransitItinerary[] }> {
const { key: apiKey, source } = this.resolveKey(userId);
if (!apiKey) {
const err = new Error('Transit provider error (no Google API key configured)') as Error & { status: number };
err.status = 502;
throw err;
}
const requested = (q.modes || '')
.split(',')
.map((m) => m.trim().toUpperCase())
.filter(Boolean)
.filter((m) => m !== 'TRANSIT');
const body: Record<string, unknown> = {
origin: { location: { latLng: parseCoord(q.from) } },
destination: { location: { latLng: parseCoord(q.to) } },
travelMode: 'TRANSIT',
// Free extra options inside a request that is already billed.
computeAlternativeRoutes: true,
languageCode: toApiLang(language),
};
if (q.time) {
body[q.arriveBy ? 'arrivalTime' : 'departureTime'] = new Date(q.time).toISOString();
}
const transitPreferences: Record<string, unknown> = {};
const allowed = [...new Set(requested.map((m) => GOOGLE_TRAVEL_MODES[m]).filter(Boolean))];
if (allowed.length > 0) transitPreferences.allowedTravelModes = allowed;
// Google has no maxTransfers. Asking it to prefer fewer transfers makes the
// one billed call likelier to return something the filter below keeps.
if (typeof q.maxTransfers === 'number' && q.maxTransfers <= 1) {
transitPreferences.routingPreference = 'FEWER_TRANSFERS';
}
if (Object.keys(transitPreferences).length > 0) body.transitPreferences = transitPreferences;
const key = `g:plan:${JSON.stringify(body)}`;
const cached = cacheGet(key);
if (cached) return cached as { itineraries: TransitItinerary[] };
let data: { routes?: Array<{ legs?: Array<{ steps?: GoogleStep[] }> }> };
try {
data = (await this.call(ROUTES_ENDPOINT, 'transitPlan', apiKey, body, ROUTES_FIELD_MASK)) as typeof data;
} catch (err) {
console.error(`[Transit] google plan failed userId=${userId} keySource=${source}`);
throw err;
}
const itineraries = (data.routes || [])
.flatMap((route) => {
const steps = (route.legs || []).flatMap((leg) => leg.steps || []);
const built = buildItinerary(steps);
return built ? [built] : [];
})
.filter((it) => matchesRequestedModes(it, requested))
.filter((it) => q.maxTransfers === undefined || q.maxTransfers === null || it.transfers <= q.maxTransfers)
.slice(0, 8);
const payload = { itineraries };
cacheSet(key, PLAN_TTL, payload);
return payload;
}
}
/**
* Steps → one itinerary, or null when there is nothing scheduled in it.
*
* A walk-only route is dropped for the same reason the MOTIS call passes
* `directModes=WALK`: footpath routing is already OSRM's job, and a walking
* "itinerary" in the transit picker is noise.
*/
function buildItinerary(steps: GoogleStep[]): TransitItinerary | null {
if (steps.length === 0) return null;
const legs: TransitLeg[] = steps.map((step, index) => {
const details = step.transitDetails;
const line = details?.transitLine;
const vehicle = line?.vehicle?.type;
const isFirst = index === 0;
const isLast = index === steps.length - 1;
// MOTIS labels the journey's own endpoints START/END and both the web
// client and the MCP itinerary builder swap the user's chosen names back
// in, so match that. Interior walk endpoints are left blank here and
// filled from the scheduled neighbour they touch.
const from = stopFrom(details?.stopDetails?.departureStop, step.startLocation?.latLng, isFirst ? 'START' : '');
const to = stopFrom(details?.stopDetails?.arrivalStop, step.endLocation?.latLng, isLast ? 'END' : '');
from.time = isoOrNull(details?.stopDetails?.departureTime);
from.scheduledTime = from.time;
to.time = isoOrNull(details?.stopDetails?.arrivalTime);
to.scheduledTime = to.time;
return {
mode: details ? (vehicle ? VEHICLE_MODES[vehicle] || 'RAIL' : 'RAIL') : 'WALK',
from,
to,
duration: parseDuration(step.staticDuration),
distance: typeof step.distanceMeters === 'number' ? Math.round(step.distanceMeters) : null,
headsign: details?.headsign || null,
// nameShort is the public line identifier ("M4", "JR-Y"); the long name is
// the route description and only used when there is no short one.
line: line?.nameShort || line?.name || null,
lineColor: safeColor(line?.color),
lineTextColor: safeColor(line?.textColor),
agency: line?.agencies?.[0]?.name || null,
intermediateStops: typeof details?.stopCount === 'number' ? Math.max(0, details.stopCount - 1) : 0,
geometry: step.polyline?.encodedPolyline || null,
geometryPrecision: GOOGLE_POLYLINE_PRECISION,
};
});
if (!legs.some((leg) => leg.mode !== 'WALK')) return null;
const walked = mergeWalkLegs(legs);
fillWalkGaps(walked);
const startTime = walked[0].from.time;
const endTime = walked[walked.length - 1].to.time;
if (!startTime || !endTime) return null;
return { startTime, endTime, ...deriveTransitStats(startTime, endTime, walked), legs: walked };
}
/**
* Collapse each run of consecutive walking steps into one leg.
*
* The Routes API returns walking as turn-by-turn navigation steps — "head north
* on Rue de Rivoli", "turn right" — so a two-minute walk to the platform
* arrives as half a dozen steps. MOTIS gives one leg per walking segment, and
* everything downstream is built for that shape: the panel renders a row per
* leg, and transitItinerarySchema caps an itinerary at 20 legs, so a
* finely-sliced walk would push a real journey over the limit and get the whole
* itinerary dropped at the MCP boundary.
*/
function mergeWalkLegs(legs: TransitLeg[]): TransitLeg[] {
const merged: TransitLeg[] = [];
for (const leg of legs) {
const previous = merged[merged.length - 1];
if (leg.mode !== 'WALK' || previous?.mode !== 'WALK') {
merged.push(leg);
continue;
}
previous.to = leg.to;
previous.duration += leg.duration;
previous.distance =
previous.distance === null && leg.distance === null ? null : (previous.distance ?? 0) + (leg.distance ?? 0);
previous.geometry = joinPolylines(previous.geometry, leg.geometry);
}
return merged;
}
/**
* Two step polylines into one. They cannot be concatenated as strings — each is
* delta-encoded from its own first point — so the pair is decoded, joined and
* re-encoded. Consecutive steps repeat the point where one ends and the next
* begins; that seam is dropped rather than drawn twice.
*/
function joinPolylines(head: string | null, tail: string | null): string | null {
if (!head) return tail;
if (!tail) return head;
const first = decodePolyline(head, GOOGLE_POLYLINE_PRECISION);
const second = decodePolyline(tail, GOOGLE_POLYLINE_PRECISION);
if (first.length === 0) return tail;
if (second.length === 0) return head;
const last = first[first.length - 1];
const seam = second[0][0] === last[0] && second[0][1] === last[1] ? 1 : 0;
return encodePolyline([...first, ...second.slice(seam)], GOOGLE_POLYLINE_PRECISION);
}
/**
* Only transit steps come back with a clock and a stop name. A walking step is
* anchored to the scheduled neighbour it touches — forwards from the previous
* arrival, or backwards from the next departure when the walk opens the
* journey — which is also what makes a walk read "…to Nakanoshima".
*/
function fillWalkGaps(legs: TransitLeg[]): void {
for (let i = 1; i < legs.length; i++) {
const previous = legs[i - 1].to;
const leg = legs[i];
if (!leg.from.name) leg.from.name = previous.name;
if (!leg.from.time && previous.time) {
leg.from.time = previous.time;
leg.to.time ??= shiftIso(previous.time, leg.duration);
}
}
for (let i = legs.length - 2; i >= 0; i--) {
const next = legs[i + 1].from;
const leg = legs[i];
if (!leg.to.name) leg.to.name = next.name;
if (!leg.to.time && next.time) {
leg.to.time = next.time;
leg.from.time ??= shiftIso(next.time, -leg.duration);
}
}
for (const leg of legs) {
// transitStopSchema wants a non-empty name; a walk between two unnamed
// points has nothing better to be called.
if (!leg.from.name) leg.from.name = 'Transfer';
if (!leg.to.name) leg.to.name = 'Transfer';
leg.from.scheduledTime ??= leg.from.time;
leg.to.scheduledTime ??= leg.to.time;
}
}
/**
* The response-side half of the mode filter. Ferry, funicular and the aerial
* lifts have no `allowedTravelModes` equivalent, and Google's five buckets are
* coarser than TREK's thirteen — so a user who asked for "subway only" is held
* to it here rather than being handed a bus.
*/
function matchesRequestedModes(itinerary: TransitItinerary, requested: string[]): boolean {
if (requested.length === 0) return true;
const wanted = new Set(requested);
return itinerary.legs.every((leg) => leg.mode === 'WALK' || wanted.has(leg.mode));
}
@@ -0,0 +1,38 @@
import { TRANSIT_PROVIDERS, type TransitProvider } from '@trek/shared';
import type { DatabaseService } from '../database/database.service';
/**
* Which backend answers /api/transit (#1699), stored as one `app_settings` row.
*
* Kept as plain functions rather than a service (the instance-api-keys.ts
* precedent) because two modules need the value and neither should own the
* other: AddonsService writes it from the admin panel, TransitService reads it
* per request. One reader, one writer, one key — no mirrored copy.
*/
export const TRANSIT_PROVIDER_SETTING = 'transit_provider';
/** Free, keyless, and what every install has today. Also the fallback. */
export const DEFAULT_TRANSIT_PROVIDER: TransitProvider = 'transitous';
function isTransitProvider(value: unknown): value is TransitProvider {
return typeof value === 'string' && (TRANSIT_PROVIDERS as readonly string[]).includes(value);
}
/**
* Reads fail-safe: a missing row, or a value written by a newer version that
* this one does not know, resolves to Transitous. The alternative is billing an
* admin's Google key because a string did not parse.
*/
export function readTransitProvider(db: DatabaseService): TransitProvider {
const row = db.get<{ value: string | null }>('SELECT value FROM app_settings WHERE key = ?', TRANSIT_PROVIDER_SETTING);
return isTransitProvider(row?.value) ? row.value : DEFAULT_TRANSIT_PROVIDER;
}
export function writeTransitProvider(db: DatabaseService, provider: TransitProvider): TransitProvider {
db.run(
`INSERT INTO app_settings (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
TRANSIT_PROVIDER_SETTING, provider
);
return provider;
}
+16 -5
View File
@@ -1,16 +1,24 @@
import { Controller, Get, HttpException, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { CurrentUser } from '../auth/current-user.decorator';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RateLimitService } from '../common/rate-limit.service';
import { TransitService } from './transit.service';
import type { User } from '../../types';
const RL_WINDOW = 15 * 60 * 1000;
/**
* /api/transit — public transit routing (#1065) proxied through Transitous
* (or a self-hosted MOTIS via TRANSIT_API_URL). JWT-guarded and rate-limited:
* the Transitous usage policy asks integrators to keep expensive routing
* traffic reasonable, so planning gets a tighter bucket than geocoding.
* (or a self-hosted MOTIS via TRANSIT_API_URL, or Google since #1699).
* JWT-guarded and rate-limited: the Transitous usage policy asks integrators to
* keep expensive routing traffic reasonable, so planning gets a tighter bucket
* than geocoding — and the same buckets cap what a Google-backed install can be
* made to spend.
*
* The caller's id goes to the service so the Google backend can resolve the
* install's Places key the way every other Google call does (operator env →
* instance → the caller's own row). The Transitous path ignores it.
*/
@Controller('api/transit')
@UseGuards(JwtAuthGuard)
@@ -37,11 +45,12 @@ export class TransitController {
@Query('q') q: string | undefined,
@Query('lang') lang: string | undefined,
@Query('near') near: string | undefined,
@CurrentUser() user: User,
@Req() req: Request,
) {
this.limit('transit_geocode', req, 300);
try {
return await this.transit.geocode(q || '', lang, near);
return await this.transit.geocode(q || '', lang, near, user.id);
} catch (err) { this.rethrow(err); }
}
@@ -53,6 +62,8 @@ export class TransitController {
@Query('arriveBy') arriveBy: string | undefined,
@Query('modes') modes: string | undefined,
@Query('maxTransfers') maxTransfers: string | undefined,
@Query('lang') lang: string | undefined,
@CurrentUser() user: User,
@Req() req: Request,
) {
this.limit('transit_plan', req, 60);
@@ -64,7 +75,7 @@ export class TransitController {
arriveBy: arriveBy === 'true' || arriveBy === '1',
modes,
maxTransfers: maxTransfers !== undefined && maxTransfers !== '' ? Number(maxTransfers) : undefined,
});
}, lang, user.id);
} catch (err) { this.rethrow(err); }
}
}
@@ -97,3 +97,64 @@ export function deriveTransitStats(
walkSeconds: legs.filter((leg) => leg.mode === 'WALK').reduce((total, leg) => total + leg.duration, 0),
};
}
/**
* Google-encoded polyline codec.
*
* The client carries its own decoder for drawing a journey on the map
* (client/src/components/Map/transitGeometry.ts). This pair exists for a
* different job the client never has: the Google backend receives a walk split
* across several navigation steps, each with its own polyline, and has to
* MERGE them into the single walk leg the rest of TREK expects — which needs an
* encoder to put the joined path back on the wire.
*/
export function decodePolyline(encoded: string, precision: number): [number, number][] {
const factor = 10 ** precision;
const points: [number, number][] = [];
let index = 0;
let lat = 0;
let lng = 0;
while (index < encoded.length) {
for (const axis of [0, 1] as const) {
let result = 0;
let shift = 0;
let byte = 0x20;
while (byte >= 0x20) {
if (index >= encoded.length) return points;
byte = (encoded.codePointAt(index++) ?? 0) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
}
const delta = result & 1 ? ~(result >> 1) : result >> 1;
if (axis === 0) lat += delta;
else lng += delta;
}
points.push([lat / factor, lng / factor]);
}
return points;
}
function encodeSigned(value: number): string {
let remaining = value < 0 ? ~(value << 1) : value << 1;
let out = '';
while (remaining >= 0x20) {
out += String.fromCharCode((0x20 | (remaining & 0x1f)) + 63);
remaining >>= 5;
}
return out + String.fromCharCode(remaining + 63);
}
export function encodePolyline(points: [number, number][], precision: number): string {
const factor = 10 ** precision;
let out = '';
let lastLat = 0;
let lastLng = 0;
for (const [lat, lng] of points) {
const scaledLat = Math.round(lat * factor);
const scaledLng = Math.round(lng * factor);
out += encodeSigned(scaledLat - lastLat) + encodeSigned(scaledLng - lastLng);
lastLat = scaledLat;
lastLng = scaledLng;
}
return out;
}
+3 -3
View File
@@ -90,7 +90,7 @@ export class TransitMcp {
const limited = rateLimit(ctx.userId, 'mcp_transit_geocode', 300);
if (limited) return limited;
try {
return ok(await this.transit.geocode(query, language, near ? `${near.lat},${near.lng}` : undefined));
return ok(await this.transit.geocode(query, language, near ? `${near.lat},${near.lng}` : undefined, ctx.userId));
} catch (err) {
return errorResult(err, 'Transit stop search failed.');
}
@@ -99,7 +99,7 @@ export class TransitMcp {
@Tool({
name: 'search_transit_routes',
description:
'Search scheduled public-transit routes via Transitous between two coordinates. Returns itineraries that can be passed unchanged to create_transit_journey. `dropped` counts provider itineraries that failed validation and are therefore absent from the results — a non-zero value means the provider offered routes this tool could not represent.',
'Search scheduled public-transit routes between two coordinates, via whichever backend the instance is configured for. Returns itineraries that can be passed unchanged to create_transit_journey. `dropped` counts provider itineraries that failed validation and are therefore absent from the results — a non-zero value means the provider offered routes this tool could not represent.',
inputSchema: {
from: transitPlaceSchema,
to: transitPlaceSchema,
@@ -136,7 +136,7 @@ export class TransitMcp {
arriveBy,
modes: modes?.join(','),
maxTransfers,
});
}, undefined, ctx.userId);
const itineraries = result.itineraries.flatMap((itinerary) => {
const parsed = transitItinerarySchema.safeParse(cleanTransitItineraryNames(itinerary, from.name, to.name));
if (!parsed.success) return [];
+4 -2
View File
@@ -3,13 +3,15 @@ import { Module } from '@nestjs/common';
import { TransitController } from './transit.controller';
import { TransitService } from './transit.service';
import { TransitMcp } from './transit.mcp';
import { GoogleTransitProvider } from './google-transit.provider';
import { DaysModule } from '../days/days.module';
import { ReservationsModule } from '../reservations/reservations.module';
import { AuthModule } from '../auth/auth.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
/**
* Transit domain (#1065) — the Transitous/MOTIS proxy. TransitMcp carries the
* Transit domain (#1065) — the Transitous/MOTIS proxy, with the optional
* Google backend (#1699) behind it. TransitMcp carries the
* decorator-registered MCP tools; DaysModule/ReservationsModule feed
* create_transit_journey. Exports TransitService for in-container consumers.
*/
@@ -17,7 +19,7 @@ import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
// DaysModule + ReservationsModule: TransitMcp's create_transit_journey injects both.
imports: [McpSharedModule, RateLimitModule, DaysModule, ReservationsModule, AuthModule],
controllers: [TransitController],
providers: [TransitService, TransitMcp],
providers: [TransitService, TransitMcp, GoogleTransitProvider],
exports: [TransitService],
})
export class TransitModule {}
+53 -8
View File
@@ -1,6 +1,8 @@
import { Injectable } from '@nestjs/common';
import { getAppUrl, readEnv } from '../../app-config';
import { buildUserAgent } from '../maps/maps.helpers';
import { GoogleTransitProvider } from './google-transit.provider';
import type { TransitProvider } from '@trek/shared';
import {
deriveTransitStats,
SCHEDULED_TRANSIT_MODES,
@@ -17,6 +19,19 @@ import {
* TREK's no-paid-providers rule. Self-hosters can point TRANSIT_API_URL at their
* own MOTIS instance instead.
*
* Since #1699 an admin can point the two routes at Google instead, for the
* 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.
*
* Both responses name the backend that answered. The fallback is silent by
* design, so without this an empty result is indistinguishable between "this
* provider has no data here" and "the provider you picked never ran" — which is
* exactly the guessing game a Paris search ran into when the Île-de-France feed
* ended before the trip date.
*
* This service is a thin, validating proxy: the browser never talks to
* Transitous directly (their usage policy wants an identifying User-Agent with
* contact info, which we send once from the server), and responses are mapped
@@ -139,23 +154,43 @@ function mapStop(p: MotisPlaceRaw | undefined, kind: 'departure' | 'arrival'): T
@Injectable()
export class TransitService {
/** Station/place search for the from/to pickers. `near` biases results. */
async geocode(query: string, language?: string, near?: string): Promise<{ results: TransitPlace[] }> {
constructor(private readonly google: GoogleTransitProvider) {}
/**
* Station/place search for the from/to pickers. `near` biases results.
*
* `userId` resolves the Google key (operator env → instance → own row) and is
* only read when Google is the active backend; the Transitous path is keyless
* and identical for every caller.
*/
async geocode(
query: string,
language?: string,
near?: string,
userId = 0,
): Promise<{ results: TransitPlace[]; provider: TransitProvider }> {
const text = (query || '').trim();
if (text.length < 2) return { results: [] };
// Answered before either backend is consulted, so it reports the one that
// WOULD have been asked rather than claiming nobody was.
const provider: TransitProvider = this.google.isActive(userId) ? 'google' : 'transitous';
if (text.length < 2) return { results: [], provider };
if (text.length > 200) {
const e = new Error('Query too long') as Error & { status: number };
e.status = 400;
throw e;
}
if (provider === 'google') {
return { ...(await this.google.geocode(text, language, near && isCoord(near) ? near : undefined, userId)), provider };
}
const params = new URLSearchParams({ text });
if (language) params.set('language', language.slice(0, 5));
if (near && isCoord(near)) params.set('place', near);
const key = `geo:${params.toString()}`;
const cached = cacheGet(key);
if (cached) return cached as { results: TransitPlace[] };
if (cached) return { ...(cached as { results: TransitPlace[] }), provider };
const raw = (await upstream('/api/v1/geocode', params)) as Array<{
name?: string;
@@ -173,11 +208,15 @@ export class TransitService {
const data = { results };
cacheSet(key, data);
return data;
return { ...data, provider };
}
/** Route search between two coordinates. Returns compact itineraries for the picker. */
async plan(q: PlanQuery): Promise<{ itineraries: TransitItinerary[] }> {
async plan(
q: PlanQuery,
language?: string,
userId = 0,
): Promise<{ itineraries: TransitItinerary[]; provider: TransitProvider }> {
const bad = (msg: string) => {
const e = new Error(msg) as Error & { status: number };
e.status = 400;
@@ -212,9 +251,15 @@ export class TransitService {
// "direct" connection is what the existing OSRM footpath routing is for.
params.set('directModes', 'WALK');
// After validation on purpose: whichever backend answers, the caller is held
// to the same coordinate/mode/transfer contract and gets the same 400s.
if (this.google.isActive(userId)) {
return { ...(await this.google.plan(q, language, userId)), provider: 'google' };
}
const key = `plan:${params.toString()}`;
const cached = cacheGet(key);
if (cached) return cached as { itineraries: TransitItinerary[] };
if (cached) return { ...(cached as { itineraries: TransitItinerary[] }), provider: 'transitous' };
const raw = (await upstream('/api/v6/plan', params)) as {
itineraries?: Array<{
@@ -276,6 +321,6 @@ export class TransitService {
const data = { itineraries };
cacheSet(key, data);
return data;
return { ...data, provider: 'transitous' };
}
}