Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(maps): stop the index costing a second search, a duplicate and a lost cache

Maurice5aa36aaf3d06
diff --git a/client/src/api/client.ts b/client/src/api/client.ts
index c52fa66cf..029da7135 100644
--- a/client/src/api/client.ts
+++ b/client/src/api/client.ts
@@ -1051,6 +1051,40 @@ export const memoriesApi = {
* Only network-level failures fall through. A 4xx or 5xx means the server did
* answer and the caller has to see it.
*/
+/**
+ * The same offline treatment as `withCachedPlaces`, for the single-place lookup.
+ *
+ * Separate because the shape is different: this one is keyed by id rather than
+ * by a query, and a miss has to stay a miss — a place the cache does not hold
+ * must fail the way it did before, not answer with somebody else's record.
+ */
+async function withCachedPlace(
+ placeId: string,
+ online: () => Promise<{ place: Record<string, unknown> | null }>,
+): Promise<{ place: Record<string, unknown> | null }> {
+ const fromCache = async (): Promise<{ place: Record<string, unknown> | null } | null> => {
+ const { getCachedPlace, cachedToPlaceRecord } = await import('../sync/placePrefetcher')
+ const hit = await getCachedPlace(placeId)
+ return hit ? { place: cachedToPlaceRecord(hit) } : null
+ }
+
+ if (isEffectivelyOffline()) {
+ const cached = await fromCache()
+ if (cached) return cached
+ return online()
+ }
+ try {
+ return await online()
+ } catch (err) {
+ const e = err as { isAxiosError?: boolean; response?: unknown; code?: string } | null
+ const neverArrived = !!e && e.isAxiosError === true && e.response == null && e.code !== 'ERR_CANCELED'
+ if (!neverArrived) throw err
+ const cached = await fromCache()
+ if (!cached) throw err
+ return cached
+ }
+}
+
async function withCachedPlaces<T>(
query: string,
shape: (places: Record<string, unknown>[]) => T,
@@ -1100,7 +1134,16 @@ export const mapsApi = {
}),
() => apiClient.post('/maps/autocomplete', { input, lang, locationBias, sessionToken }, { signal }).then(r => checkInDev(mapsAutocompleteResultSchema, r.data, 'maps.autocomplete')),
),
- details: (placeId: string, lang?: string, sessionToken?: string) => apiClient.get(`/maps/details/${encodeURIComponent(placeId)}`, { params: { lang, sessionToken } }).then(r => checkInDev(mapsPlaceDetailsResultSchema, r.data, 'maps.details')),
+ // Answered from the cache when the network is not there, for the ids the
+ // offline suggestion list hands out. Without it, picking an offline
+ // suggestion failed here and the callers fell back to searching for
+ // "name, address" — which the cache matches on the folded NAME alone, so it
+ // found nothing and the user got an error toast for a place that was sitting
+ // in the cache all along.
+ details: (placeId: string, lang?: string, sessionToken?: string) =>
+ withCachedPlace(placeId, () =>
+ apiClient.get(`/maps/details/${encodeURIComponent(placeId)}`, { params: { lang, sessionToken } })
+ .then(r => checkInDev(mapsPlaceDetailsResultSchema, r.data, 'maps.details'))),
// Pictures and a description for a place that is being looked at but not yet
// saved. Fans out to several providers server-side, so it takes a signal and
// the caller is expected to abort it when the selection changes, and a longer
diff --git a/client/src/db/offlineDb.ts b/client/src/db/offlineDb.ts
index fee94142d..0da5d0373 100644
--- a/client/src/db/offlineDb.ts
+++ b/client/src/db/offlineDb.ts
@@ -447,6 +447,7 @@ export async function clearTripData(tripId: number): Promise<void> {
offlineDb.mutationQueue,
offlineDb.syncMeta,
offlineDb.blobCache,
+ offlineDb.areaPlaces,
],
async () => {
await offlineDb.days.where('trip_id').equals(tripId).delete();
@@ -462,6 +463,11 @@ export async function clearTripData(tripId: number): Promise<void> {
await offlineDb.mutationQueue.where('tripId').equals(tripId).and(m => m.status === 'failed').delete();
await offlineDb.syncMeta.where('tripId').equals(tripId).delete();
await offlineDb.blobCache.where('tripId').equals(tripId).delete();
+ // The cached places around this trip's area go with it. They are searched
+ // across every trip, so leaving them behind kept a switched-off trip
+ // answering offline searches — and nothing else ever deleted them, so they
+ // accumulated for the life of the install.
+ await offlineDb.areaPlaces.where('tripId').equals(tripId).delete();
},
);
// Remove the trip row itself outside the transaction since it's a separate table
diff --git a/client/src/hooks/useLocationBias.ts b/client/src/hooks/useLocationBias.ts
index 3e1f06fa7..292b9503c 100644
--- a/client/src/hooks/useLocationBias.ts
+++ b/client/src/hooks/useLocationBias.ts
@@ -87,7 +87,11 @@ export function pointFromBox(box: LocationBiasBox | undefined): LocationBiasPoin
return {
lat: (box.low.lat + box.high.lat) / 2,
lng: (box.low.lng + box.high.lng) / 2,
- radius: Math.round(Math.max(radiusKm(box), 5) * 1000),
+ // Google caps a Text Search bias circle at 50 km and rejects a wider one
+ // outright, so the box for a trip spread over more than that is clamped
+ // rather than sent and refused. A bias is a hint about where to look; the
+ // hint is no worse for being drawn at the largest radius the API accepts.
+ radius: Math.min(50_000, Math.round(Math.max(radiusKm(box), 5) * 1000)),
}
}
diff --git a/client/src/sync/placePrefetcher.test.ts b/client/src/sync/placePrefetcher.test.ts
index 3e104f126..3a61846d2 100644
--- a/client/src/sync/placePrefetcher.test.ts
+++ b/client/src/sync/placePrefetcher.test.ts
@@ -10,8 +10,8 @@ import { offlineDb, clearAll } from '../db/offlineDb'
import {
AREA_PLACE_LIMIT,
cachedToPlaceRecord,
- clearCachedPlaces,
foldName,
+ getCachedPlace,
prefetchPlacesForTrip,
searchCachedPlaces,
} from './placePrefetcher'
@@ -167,14 +167,25 @@ describe('searchCachedPlaces', () => {
rating: null,
})
})
-})
-describe('clearCachedPlaces', () => {
- it('FE-PLACEPRE-016: drops one trip and leaves the others', async () => {
- await prefetchPlacesForTrip(7, TRIP_PLACES)
- await offlineDb.areaPlaces.toCollection().modify({ tripId: 8 })
- await prefetchPlacesForTrip(7, TRIP_PLACES, true)
- await clearCachedPlaces(7)
- expect((await offlineDb.areaPlaces.toArray()).every((r) => r.tripId === 8)).toBe(true)
+ it('FE-PLACEPRE-016: finds a place by the id its own suggestion handed out', async () => {
+ // This closes the loop offline. The suggestion list gives out `gers:` ids;
+ // picking one calls the details lookup with exactly that string, and before
+ // this the lookup had no cache path, failed, and the callers fell back to
+ // searching for "name, address" — which matches on the folded NAME alone,
+ // so it found nothing and the user got an error for a place that was
+ // sitting in the cache.
+ const [hit] = await searchCachedPlaces('osteria')
+ const found = await getCachedPlace(`gers:${hit.gers}`)
+ expect(found?.name).toBe("L'Osteria")
+ })
+
+ it('FE-PLACEPRE-017: an id the cache does not hold is a miss, not somebody else record', async () => {
+ // A miss has to stay a miss: answering the wrong place would be worse than
+ // the failure it replaces.
+ expect(await getCachedPlace('gers:not-cached')).toBeNull()
+ // Ids from sources the cache never holds are not looked up at all.
+ expect(await getCachedPlace('node:5255005321')).toBeNull()
+ expect(await getCachedPlace('ChIJLU7jZClu5kcR4PcOOO6p3I0')).toBeNull()
})
})
diff --git a/client/src/sync/placePrefetcher.ts b/client/src/sync/placePrefetcher.ts
index 943d92131..86dabdc06 100644
--- a/client/src/sync/placePrefetcher.ts
+++ b/client/src/sync/placePrefetcher.ts
@@ -133,7 +133,18 @@ export async function prefetchPlacesForTrip(
if (rows.length) await offlineDb.areaPlaces.bulkPut(rows)
})
- if (meta) await offlineDb.syncMeta.put({ ...meta, areaPlacesKey: key })
+ // Written whether or not a sync row exists yet. Skipping it when there is
+ // none left the fingerprint unwritten for a trip cached before its first
+ // sync, so the next run re-downloaded the same area for nothing.
+ await offlineDb.syncMeta.put({
+ tripId,
+ lastSyncedAt: meta?.lastSyncedAt ?? 0,
+ status: meta?.status ?? 'idle',
+ tilesBbox: meta?.tilesBbox ?? null,
+ filesCachedCount: meta?.filesCachedCount ?? 0,
+ ...meta,
+ areaPlacesKey: key,
+ })
if (rows.length) {
console.info(
`[placePrefetch] trip ${tripId}: cached ${rows.length} places${area.truncated ? ' (area trimmed)' : ''}`,
@@ -177,6 +188,19 @@ export async function searchCachedPlaces(query: string, limit = 10): Promise<Cac
}
/** A cached row in the shape every search caller already reads. */
+/**
+ * One cached place by the id the suggestion list handed out.
+ *
+ * Takes the `gers:`-prefixed form the server puts on `osm_id`, because that is
+ * what a suggestion carries and what the details lookup is called with. Any
+ * other id shape belongs to a source the cache does not hold, and is a miss
+ * rather than an error.
+ */
+export async function getCachedPlace(placeId: string): Promise<CachedAreaPlace | null> {
+ if (!placeId.startsWith('gers:')) return null
+ return (await offlineDb.areaPlaces.get(placeId.slice('gers:'.length))) ?? null
+}
+
export function cachedToPlaceRecord(p: CachedAreaPlace): Record<string, unknown> {
return {
google_place_id: null,
@@ -193,7 +217,3 @@ export function cachedToPlaceRecord(p: CachedAreaPlace): Record<string, unknown>
}
}
-/** Drop a trip's cached area. Called when the trip leaves the offline set. */
-export async function clearCachedPlaces(tripId: number): Promise<void> {
- await offlineDb.areaPlaces.where('tripId').equals(tripId).delete()
-}
diff --git a/client/src/sync/tripSyncManager.ts b/client/src/sync/tripSyncManager.ts
index d2a4c5108..cc902656a 100644
--- a/client/src/sync/tripSyncManager.ts
+++ b/client/src/sync/tripSyncManager.ts
@@ -124,7 +124,16 @@ async function syncTrip(tripId: number): Promise<void> {
await upsertTripFiles(bundle.files)
await upsertAccommodations(bundle.accommodations || [])
await upsertTripMembers(tripId, bundle.members || [])
+ // Merged onto the existing row, not written over it: `put` replaces the whole
+ // record, and the row also carries `areaPlacesKey` — the fingerprint that says
+ // the cached places for this trip's area are still current. Losing it on every
+ // sync meant the prefetch re-downloaded the whole area (megabytes, and a bbox
+ // query upstream) on every login, every reconnect and every manual sync, for
+ // data that had not changed. The two fields below keep being reset on purpose,
+ // exactly as before.
+ const previous = await offlineDb.syncMeta.get(tripId)
await upsertSyncMeta({
+ ...previous,
tripId,
lastSyncedAt: Date.now(),
status: 'idle',
diff --git a/client/tests/unit/db/offlineDb.test.ts b/client/tests/unit/db/offlineDb.test.ts
index 904bc5311..3d5147538 100644
--- a/client/tests/unit/db/offlineDb.test.ts
+++ b/client/tests/unit/db/offlineDb.test.ts
@@ -320,6 +320,29 @@ describe('offlineDb — clearTripData', () => {
expect(await offlineDb.blobCache.get('/api/files/2/download')).toBeDefined();
});
+ it('takes the trip cached area places with it, and leaves another trip its own', async () => {
+ // They are searched across every trip, so a trip switched off for offline
+ // use kept answering offline searches from an area nobody had asked to keep
+ // — and nothing else ever deleted them, so they piled up for the life of the
+ // install.
+ await upsertTrip(makeTrip(1));
+ await upsertTrip(makeTrip(2));
+ const cached = (gers: string, tripId: number, name: string) => ({
+ gers, tripId, name, searchName: name.toLowerCase(), address: '',
+ lat: 52.5, lng: 13.4, category: null, website: null, phone: null, cachedAt: 1,
+ });
+ await offlineDb.areaPlaces.bulkPut([
+ cached('a', 1, 'Ostpol'),
+ cached('b', 1, 'Kollo'),
+ cached('c', 2, 'Sonne'),
+ ]);
+
+ await clearTripData(1);
+
+ expect(await offlineDb.areaPlaces.where('tripId').equals(1).count()).toBe(0);
+ expect(await offlineDb.areaPlaces.where('tripId').equals(2).count()).toBe(1);
+ });
+
it('preserves unsynced (pending/conflict) writes but drops dead failed ones (#1135)', async () => {
await upsertTrip(makeTrip(1));
await offlineDb.mutationQueue.bulkPut([
diff --git a/server/src/nest/maps/maps.helpers.ts b/server/src/nest/maps/maps.helpers.ts
index 1dfdafe7f..824af20d8 100644
--- a/server/src/nest/maps/maps.helpers.ts
+++ b/server/src/nest/maps/maps.helpers.ts
@@ -163,6 +163,34 @@ export function namesOverlap(a: string, b: string): boolean {
.filter((word) => word.length > 2),
);
const left = [...words(a)];
+ const right = [...words(b)];
+
+ /**
+ * Neither name has a Latin word to compare.
+ *
+ * `words()` splits on `[^a-z0-9]`, so a name written in Japanese, Korean,
+ * Chinese, Greek, Cyrillic, Arabic, Hebrew or Thai tokenises to nothing at
+ * all, and returning false there made this function blind to exactly the
+ * places the two sources most often both know: 長谷寺 came back once from the
+ * index and once from OpenStreetMap, one above the other in the same list.
+ *
+ * Compared strictly, not by overlap. Two CJK names that merely share a
+ * character are usually two different places (東京タワー and 東京駅 share
+ * 東京), and deduping the wrong pair swallows a real result — the failure this
+ * whole function is written to avoid. Identical names at the same coordinate
+ * are the case worth catching, and it is the common one, because both sources
+ * carry the official local name.
+ *
+ * NFKC folds the width and compatibility variants the two sources disagree
+ * on (タワー against タワー), which NFD, used for the Latin path above, does not.
+ */
+ if (left.length === 0 && right.length === 0) {
+ const strict = (value: string): string =>
+ value.normalize('NFKC').toLowerCase().replace(/\s+/gu, '');
+ const [sa, sb] = [strict(a), strict(b)];
+ return sa.length > 0 && sa === sb;
+ }
+
if (left.length === 0) return false;
/**
@@ -181,7 +209,7 @@ export function namesOverlap(a: string, b: string): boolean {
};
let shared = 0;
- for (const word of words(b)) {
+ for (const word of right) {
const match = left.find((candidate) => sameStem(candidate, word));
if (!match) continue;
if (Math.min(match.length, word.length) >= 4) return true;
diff --git a/server/src/nest/maps/maps.service.ts b/server/src/nest/maps/maps.service.ts
index a9d0ec070..5ca68f2bf 100644
--- a/server/src/nest/maps/maps.service.ts
+++ b/server/src/nest/maps/maps.service.ts
@@ -22,6 +22,7 @@ import {
trekPlacesNearby,
toPlaceRecord,
POI_CATEGORY_TO_TREK,
+ type TrekPlace,
} from './trek-places.client';
import {
UA,
@@ -1647,51 +1648,72 @@ export class MapsService {
// unenriched on an instance that pays for a key. It changes nothing for an
// instance without one: enrichment could never resolve anything there
// either, before this branch existed or after.
+ // Set once the OpenStreetMap half below has run, so the fallback does not ask
+ // the same question twice. `null` means it never ran.
+ let osmAnswer: Record<string, unknown>[] | null = null;
+
if (this.trekPlacesEnabled() && !(opts.googleIdentityOnly && apiKey)) {
- try {
- // Both at once. The index is a dataset of businesses and is very good
- // at those; OpenStreetMap is where the temples, bridges, riverside
- // walks and viewpoints are, and a travel search asks for those
- // constantly. Concurrently, so the pair costs the slower one rather
- // than the sum. This is the explicit search, not the keystroke path
- // Nominatim's policy rules out.
- const [found, osm] = await Promise.all([
- trekPlacesSearch(query, {
- lat: locationBias?.lat,
- lng: locationBias?.lng,
- limit: 10,
- }),
- this.searchNominatim(query, lang, 'interactive', locationBias).catch((err: unknown) => {
- console.warn('OpenStreetMap search failed, index only:', (err as Error).message);
- return [] as Record<string, unknown>[];
- }),
- ]);
- const places = mergeSearchResults(found.map(toPlaceRecord), osm);
- if (places.length > 0) {
- return {
- places,
- source: osm.length > 0 ? 'trek-places+openstreetmap' : 'trek-places',
- };
- }
- } catch (err: unknown) {
- // Logged, not surfaced: the fallback below is a working answer.
- console.warn('TREK Places search failed, falling back:', (err as Error).message);
+ // Both at once. The index is a dataset of businesses and is very good
+ // at those; OpenStreetMap is where the temples, bridges, riverside
+ // walks and viewpoints are, and a travel search asks for those
+ // constantly. Concurrently, so the pair costs the slower one rather
+ // than the sum. This is the explicit search, not the keystroke path
+ // Nominatim's policy rules out.
+ //
+ // Each side catches its own failure. A rejection reaching Promise.all
+ // would throw away the answer the other side had already produced — and
+ // the index refusing a query is ordinary traffic, not an outage: a common
+ // single word without coordinates is turned down upstream as too
+ // expensive. That used to discard ten good OpenStreetMap results and ask
+ // Nominatim the same question a second time, behind its own 1.1 s
+ // process-wide throttle.
+ const [found, osm] = await Promise.all([
+ trekPlacesSearch(query, {
+ lat: locationBias?.lat,
+ lng: locationBias?.lng,
+ limit: 10,
+ }).catch((err: unknown) => {
+ console.warn('TREK Places search failed, falling back:', (err as Error).message);
+ return [] as TrekPlace[];
+ }),
+ this.searchNominatim(query, lang, 'interactive', locationBias).catch((err: unknown) => {
+ console.warn('OpenStreetMap search failed, index only:', (err as Error).message);
+ return [] as Record<string, unknown>[];
+ }),
+ ]);
+ osmAnswer = osm;
+ const places = mergeSearchResults(found.map(toPlaceRecord), osm);
+ if (places.length > 0) {
+ return {
+ places,
+ source: osm.length > 0 ? 'trek-places+openstreetmap' : 'trek-places',
+ };
}
}
if (!apiKey) {
- const places = await this.searchNominatim(query, lang);
+ // Reuse what OpenStreetMap already said rather than asking again. The
+ // first call carried a viewbox with bounded=0, which orders results
+ // without changing which ones exist, so a second call can only return the
+ // same empty list a throttle-interval later.
+ const places = osmAnswer ?? (await this.searchNominatim(query, lang));
return { places, source: 'openstreetmap' };
}
const searchBody: Record<string, unknown> = { textQuery: query, languageCode: toApiLang(lang) };
// Bias results toward the caller's area when supplied — without it Google Text
// Search falls back to the API key's billing region, which skews foreign-region queries.
+ //
+ // Clamped, like the nearby path above: Google caps the circle at 50 km and
+ // answers a wider one with a 400 that this method throws, so a trip spread
+ // across a hundred kilometres would turn an ordinary search into an error
+ // toast. The client keeps its own ceiling; this one is here because the
+ // radius arrives over the wire and the schema cannot know Google's limit.
if (locationBias) {
searchBody.locationBias = {
circle: {
center: { latitude: locationBias.lat, longitude: locationBias.lng },
- radius: locationBias.radius ?? 50000,
+ radius: Math.min(50000, Math.max(1, locationBias.radius ?? 50000)),
},
};
}
@@ -2066,8 +2088,16 @@ export class MapsService {
// keep the details they do have (Overpass, via the plain lookup); coordinate
// pseudo-ids and legacy image URLs have no details source at all. Neither may be
// forwarded to Google, which bills the 400 INVALID_ARGUMENT it answers with.
+ //
+ // Index ids degrade the same way, for the same reason: the plain lookup has a
+ // whole record for them — name, address, contact, hours — and only the reviews
+ // and the editorial summary are Google's to add. Answering `expand=1` with a
+ // null while `expand=0` answers in full would make the richer request the
+ // poorer one.
if (!isGooglePlaceId(placeId)) {
- return OSM_PLACE_ID.test(placeId) ? this.getPlaceDetails(userId, placeId, lang) : { place: null };
+ return OSM_PLACE_ID.test(placeId) || placeId.startsWith('gers:')
+ ? this.getPlaceDetails(userId, placeId, lang)
+ : { place: null };
}
const langKey = toApiLang(lang); // 'en' default — see getPlaceDetails
diff --git a/server/tests/unit/nest/maps.merge-search.test.ts b/server/tests/unit/nest/maps.merge-search.test.ts
index 9f7f057fc..6204fdad7 100644
--- a/server/tests/unit/nest/maps.merge-search.test.ts
+++ b/server/tests/unit/nest/maps.merge-search.test.ts
@@ -80,4 +80,45 @@ describe('mergeSearchResults', () => {
const osm = [{ name: 'B', lat: null, lng: null, source: 'openstreetmap' }];
expect(mergeSearchResults(index, osm)).toHaveLength(2);
});
+
+ it('MAPS-MERGE-009: one copy of a place both sources name in the local script', () => {
+ // The word split is `[^a-z0-9]`, so a name written in any non-Latin script
+ // tokenised to nothing and the dedup could never fire — the very corpus this
+ // feature was measured on. The user saw 長谷寺 twice, one row under the other,
+ // and picking either one gave the place a different id.
+ for (const name of ['長谷寺', '東京タワー', '스타벅스', 'Ακρόπολη', 'Кремль', 'مسجد الشيخ زايد']) {
+ const index = [p(name, 35.3125, 139.5335, 'trek-places')];
+ const osm = [p(name, 35.3126, 139.5336, 'openstreetmap')];
+ const out = mergeSearchResults(index, osm);
+ expect(out, name).toHaveLength(1);
+ expect(out[0].source, name).toBe('trek-places');
+ }
+ });
+
+ it('MAPS-MERGE-010: two different places at one address stay two places', () => {
+ // The other half of the same rule, and the one that costs a real result if
+ // it goes wrong: sharing a character is not being the same thing. 東京 is in
+ // both of these, and a station is not a tower.
+ const index = [p('東京タワー', 35.6586, 139.7454, 'trek-places')];
+ const osm = [p('東京タワー駅前郵便局', 35.6587, 139.7455, 'openstreetmap')];
+ expect(mergeSearchResults(index, osm)).toHaveLength(2);
+ });
+
+ it('MAPS-MERGE-011: width variants of the same name are still the same name', () => {
+ // The two sources disagree on half-width and full-width katakana for the
+ // same official name. NFKC folds them; NFD, which the Latin path uses,
+ // does not.
+ const index = [p('東京タワー', 35.6586, 139.7454, 'trek-places')];
+ const osm = [p('東京タワー', 35.6586, 139.7454, 'openstreetmap')];
+ expect(mergeSearchResults(index, osm)).toHaveLength(1);
+ });
+
+ it('MAPS-MERGE-012: a local name and a romanised one are not merged on a guess', () => {
+ // Nothing here can tell that these are one temple, and inventing the link
+ // would swallow whichever copy the ranker put second. Two rows is the honest
+ // answer; MAPS-MERGE-001 is the case that makes it useful.
+ const index = [p('Hase-dera', 35.3125, 139.5335, 'trek-places')];
+ const osm = [p('長谷寺', 35.3125, 139.5335, 'openstreetmap')];
+ expect(mergeSearchResults(index, osm)).toHaveLength(2);
+ });
});