places: a picture another installation contributed shows on the next edit

Two gaps kept it out. The service writes absolute picture URLs on its own
host, and the community service only took relative paths, so every picture
was dropped; it now takes the path of a URL on the configured service and
nothing from another host. And a saved place opened for editing sends no
details, so no community version, and the cached answer kept for a week; for
an index or OSM place the details are now read before the cache, so a new
version is a new answer.
This commit is contained in:
Maurice
2026-10-30 23:13:47 +01:00
parent 330644e88b
commit e2756dab22
4 changed files with 72 additions and 6 deletions
+21 -1
View File
@@ -13,6 +13,26 @@ export function communityKeyOf(placeId: string): string | null {
return match ? `osm:${match[1]}/${match[2]}` : null;
}
/**
* The picture store path of a URL the service gave out: as it is when relative,
* the path when absolute on the configured service, null for anything else.
* The service writes absolute URLs once TREK_CONTRIB_PUBLIC_URL is set.
*/
function storePath(url: unknown): string | null {
if (typeof url !== 'string') return null;
let path = url;
if (!url.startsWith('/')) {
try {
const parsed = new URL(url);
if (parsed.origin !== new URL(trekPlacesBaseUrl()).origin || parsed.search) return null;
path = parsed.pathname;
} catch {
return null;
}
}
return IMAGE_PATH.test(path) ? path : null;
}
/**
* The pictures the TREK community published for a place, read from the TREK
* Places API: which ones (cover first, then the order review set) and their
@@ -37,7 +57,7 @@ export class TrekCommunityService {
}
if (!Array.isArray(images)) return [];
const ordered = [...images.filter((i) => i?.cover), ...images.filter((i) => !i?.cover)];
return ordered.map((i) => i?.url).filter((u): u is string => typeof u === 'string' && IMAGE_PATH.test(u));
return ordered.map((i) => storePath(i?.url)).filter((u): u is string => u !== null);
}
/**
@@ -173,8 +173,13 @@ interface CachePayload extends CachedEnrichment {
* A sender who puts another number here only makes their own request compute
* afresh: nothing of the record is what gets cached.
*/
/** Whether the TREK Places API can hold community values for the place: an index place or an OSM element. */
function isCommunityPlace(placeId: string): boolean {
return placeId.startsWith('gers:') || communityKeyOf(placeId) !== null;
}
function communityVersion(placeId: string, details: Record<string, unknown> | null | undefined): number | null {
if (!placeId.startsWith('gers:') && !communityKeyOf(placeId)) return null;
if (!isCommunityPlace(placeId)) return null;
const version = details?.community_version;
return typeof version === 'number' && Number.isInteger(version) && version >= 0 ? version : null;
}
@@ -403,7 +408,12 @@ export class PlaceEnrichmentService {
const placeId = req.placeId?.trim() || `coords:${req.lat}:${req.lng}`;
const lang = req.lang;
const served = communityVersion(placeId, req.details);
// A saved place being edited comes without details, so without the community
// version: read them first for a place that has one, or a picture another
// installation contributed since would wait a week behind the cached answer.
const communityPlace = isCommunityPlace(placeId);
const early = !req.details && communityPlace ? await this.readDetails(userId, placeId, lang) : null;
const served = communityVersion(placeId, req.details ?? early);
const cached = await this.readCache(placeId, lang, served);
if (cached) return cached;
@@ -414,7 +424,7 @@ export class PlaceEnrichmentService {
// The dialog already fetched this when the user picked the result, so it
// comes along with the request. Refetching cost 12.8 seconds on a large
// OSM relation, and it ran in parallel with the client's own lookup.
const details = req.details ?? (await this.readDetails(userId, placeId, lang));
const details = req.details ?? (communityPlace ? early : await this.readDetails(userId, placeId, lang));
const identity = await this.resolveIdentity(req, details);
const [photos, description] = await Promise.all([
@@ -594,8 +604,8 @@ export class PlaceEnrichmentService {
// they show the place as someone who was there saw it. Then Google, whose
// pictures are of the business itself.
// Only index and OSM places have any; off means nothing leaves for the API.
const communityPlace = placeId.startsWith('gers:') || communityKeyOf(placeId) !== null;
const community = communityPlace && this.maps.trekPlacesEnabled() ? await this.community.photoPaths(placeId) : [];
const community =
isCommunityPlace(placeId) && this.maps.trekPlacesEnabled() ? await this.community.photoPaths(placeId) : [];
const pending: PendingCandidate[] = [
...community.map((path) => ({
identity: `community:${path}`,
@@ -771,6 +771,29 @@ describe('result cache', () => {
expect(JSON.parse(written.payload_json).cv).toBe(2);
});
it('ENRICH-027b: an OSM place opened for editing, without details, reads its version and drops a stale answer', async () => {
// Installation A cached the place before installation B's picture was approved (version 1 -> 2).
const row = {
payload_json: JSON.stringify({ photos: [], description: null, facts: [], v: 4, cv: 1 }),
fetched_at: Date.now(),
};
const maps = mapsStub({
details: vi.fn(async () => ({
place: { source: 'openstreetmap', name: 'Helgas Kitchen', community_version: 2 },
})),
photoPaths: vi.fn(async () => ['/v1/contrib/img/0123456789abcdef.webp']),
imageBytes: vi.fn(async () => Buffer.from([7, 8, 9])),
});
mockFindEntry.mockResolvedValue(row);
const out = await make(maps, cacheStub()).enrich(1, OSM_REQ);
expect(maps.details).toHaveBeenCalledTimes(1);
expect(out.photos.map((p) => p.source)).toEqual(['community']);
const [written] = mockUpsertEntry.mock.calls.at(-1) as [{ payload_json: string }];
expect(JSON.parse(written.payload_json).cv).toBe(2);
});
it('ENRICH-028: any other place keeps its week, whatever a request says about versions', async () => {
const maps = mapsStub();
mockFindEntry.mockResolvedValue({
@@ -51,6 +51,19 @@ describe('TrekCommunityService.photoPaths', () => {
expect(await new TrekCommunityService().photoPaths('node:1')).toEqual([A]);
});
it('TCOM-003b: takes an absolute URL on the configured service as its path, never another host', async () => {
byKeys.mockResolvedValue({
'osm:node/2': {
images: [
{ url: `https://places.example${A}`, cover: true },
{ url: `https://other.example${B}` },
{ url: `https://places.example${B}?x=1` },
],
},
});
expect(await new TrekCommunityService().photoPaths('node:2')).toEqual([A]);
});
it('TCOM-004: nothing for another kind of place, or when the service fails', async () => {
expect(await new TrekCommunityService().photoPaths('ChIJgoogle')).toEqual([]);
byId.mockRejectedValue(new Error('down'));