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.

perf(maps): search a corridor with one query per box, not one per category

Maurice6aa788487497
diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx
index 585ce36f7..ddae9a2f7 100644
--- a/client/src/components/Map/MapView.tsx
+++ b/client/src/components/Map/MapView.tsx
@@ -170,14 +170,15 @@ function createPoiIcon(category: string, brandWikidata?: string | null) {
const cat = POI_CATEGORY_BY_KEY[category]
const color = cat?.color || '#6b7280'
const svg = cat ? renderIconMarkup(createElement(cat.Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : ''
- // onerror empties the wrapper: the route answers 204 for a brand Wikidata has no
- // logo for, and an empty circle in the category colour is the right fallback.
- const inner = brand
- ? `<img src="/api/maps/brand-logo/${brand}" alt="" width="18" height="18" style="display:block;object-fit:contain;" onerror="this.remove()" />`
- : svg
+ // The logo lies over the category pin and only becomes visible once it has loaded, so
+ // a brand Wikidata has no logo for (the route answers 204), a failed request and one
+ // still in flight all leave the pin exactly as it would be without a brand.
+ const logo = brand
+ ? `<img src="/api/maps/brand-logo/${brand}" alt="" style="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:0;" onload="this.style.opacity=1" onerror="this.remove()" />`
+ : ''
const icon = L.divIcon({
className: '',
- html: `<div style="width:26px;height:26px;border-radius:50%;background:${brand ? '#fff' : color};border:2px solid ${brand ? color : 'white'};box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden;">${inner}</div>`,
+ html: `<div style="position:relative;width:26px;height:26px;border-radius:50%;background:${color};border:2px solid white;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden;">${svg}${logo}</div>`,
iconSize: [26, 26],
iconAnchor: [13, 13],
tooltipAnchor: [0, -14],
diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsx
index 81bf73d64..e0022f6eb 100644
--- a/client/src/components/Map/MapViewGL.test.tsx
+++ b/client/src/components/Map/MapViewGL.test.tsx
@@ -1855,4 +1855,33 @@ describe('MapViewGL', () => {
expect(glMap.off).toHaveBeenCalledWith('moveend', expect.any(Function))
expect(glMap.off).toHaveBeenCalledWith('zoomend', expect.any(Function))
})
+
+ it('FE-COMP-MAPVIEWGL-071: POI suggestions ride the map render clock instead of the pointer', async () => {
+ // Same drift the planned-place pins had: a library Marker repositions on every
+ // `move` event — one per pointer sample — while the canvas draws once a frame, so
+ // the suggestions swam over the map during a drag and snapped back on release.
+ loadOnAttach()
+ glCanvasContainer.replaceChildren()
+ glMap.project.mockReturnValue({ x: 100, y: 80 })
+
+ render(
+ <MapViewGL
+ places={[]}
+ fitKey={1}
+ glProvider="maplibre-gl"
+ pois={[{ osm_id: 'node:1', name: 'Aral', lat: 48.1, lng: 2.1, category: 'fuel', source: 'openstreetmap' } as never]}
+ />,
+ )
+ await flushFrames()
+
+ const layer = glCanvasContainer.firstElementChild as HTMLElement
+ expect(layer.children.length).toBe(1)
+ const pin = layer.firstElementChild as HTMLElement
+ expect(pin.style.transform).toContain('translate(100px, 80px)')
+
+ glMap.project.mockReturnValue({ x: 140, y: 60 })
+ act(() => { mapHandler('render')() })
+
+ expect(pin.style.transform).toContain('translate(140px, 60px)')
+ })
})
diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx
index 077aa6c2a..847eb5c28 100644
--- a/client/src/components/Map/MapViewGL.tsx
+++ b/client/src/components/Map/MapViewGL.tsx
@@ -356,6 +356,20 @@ function makePlacePin(map: any, layer: HTMLElement, el: HTMLElement, lng: number
}
}
+/**
+ * Puts an element on the map as a pin.
+ *
+ * `layer` is only ever set under MapLibre (that is where it gets created), so passing it
+ * along is the whole provider decision: with a layer we position the element ourselves on
+ * the map's render clock, without one the library's own Marker does it.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function attachPin(map: any, gl: any, layer: HTMLElement | null, el: HTMLElement, lng: number, lat: number): PlacePin {
+ return layer
+ ? makePlacePin(map, layer, el, lng, lat)
+ : libraryPin(new gl.Marker({ element: el, anchor: 'center' }).setLngLat([lng, lat]).addTo(map))
+}
+
// Tone dot for a plugin marker — visual twin of MapPluginMarkers' divIcon.
function createPluginMarkerElement(tone: PluginMapMarker['tone']): HTMLDivElement {
const color = PLUGIN_TONE_COLORS[tone] ?? PLUGIN_TONE_COLORS.default
@@ -404,22 +418,21 @@ function createPoiMarkerElement(category: string, brandWikidata?: string | null)
const svg = cat ? renderIconMarkup(createElement(cat.Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : ''
const el = document.createElement('div')
el.style.cssText = 'width:26px;height:26px;cursor:pointer;will-change:transform;'
- const inner = brandLogoMarkup(brandWikidata) || svg
- const background = brandWikidata ? '#fff' : color
- el.innerHTML = `<div style="width:26px;height:26px;border-radius:50%;background:${background};border:2px solid ${color};box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;box-sizing:border-box;overflow:hidden;">${inner}</div>`
+ el.innerHTML = `<div style="position:relative;width:26px;height:26px;border-radius:50%;background:${color};border:2px solid #fff;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;box-sizing:border-box;overflow:hidden;">${svg}${brandLogoMarkup(brandWikidata)}</div>`
return el
}
/**
- * The <img> for a brand logo, or '' when there is no brand.
+ * The <img> for a brand logo, laid over the category pin, or '' when there is no brand.
*
- * `onerror` empties the wrapper rather than leaving a broken-image glyph: the route
- * answers 204 for a brand Wikidata has no logo for, and an empty circle in the
- * category colour is the right fallback.
+ * It starts invisible and is only shown once it has loaded, so the pin underneath stays
+ * exactly as it would be without a brand until there is really something to show. That
+ * covers all three ways this can go: a brand Wikidata has no logo for (the route answers
+ * 204), a request that fails, and one that simply has not arrived yet.
*/
-function brandLogoMarkup(brandWikidata?: string | null): string {
+export function brandLogoMarkup(brandWikidata?: string | null): string {
if (!brandWikidata || !/^Q[1-9][0-9]{0,11}$/.test(brandWikidata)) return ''
- return `<img src="/api/maps/brand-logo/${brandWikidata}" alt="" width="18" height="18" style="display:block;object-fit:contain;" onerror="this.remove()" />`
+ return `<img src="/api/maps/brand-logo/${brandWikidata}" alt="" style="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:0;" onload="this.style.opacity=1" onerror="this.remove()" />`
}
export function MapViewGL({
@@ -497,25 +510,27 @@ export function MapViewGL({
const markersRef = useRef<Map<number, PlacePin>>(new Map())
// Own layer for the hand-positioned place pins (MapLibre path, see makePlacePin).
const pinLayerRef = useRef<HTMLDivElement | null>(null)
- const repositionPins = useCallback(() => {
- markersRef.current.forEach(pin => pin.reposition())
- }, [])
const locationMarkerRef = useRef<LocationMarkerHandle | null>(null)
const reservationOverlayRef = useRef<ReservationMapboxOverlay | null>(null)
// Refs so the reservation overlay always sees the latest callback /
// options without forcing a full overlay rebuild on every prop change.
const onReservationClickRef = useRef(onReservationClick)
onReservationClickRef.current = onReservationClick
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const poiMarkersRef = useRef<any[]>([])
+ const poiMarkersRef = useRef<PlacePin[]>([])
// Plugin map contributions — data fetched per trip, elements owned imperatively
// like the POI markers so they survive the React render cycle.
const [pluginMarkers, setPluginMarkers] = useState<PluginMapMarker[]>([])
const [pluginLayers, setPluginLayers] = useState<PluginMapLayer[]>([])
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const pluginMarkersRef = useRef<any[]>([])
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const routeViaMarkersRef = useRef<any[]>([])
+ const pluginMarkersRef = useRef<PlacePin[]>([])
+ const routeViaMarkersRef = useRef<PlacePin[]>([])
+ // Every hand-positioned pin, whichever set it belongs to. They all have to be written
+ // in the same frame the canvas draws, or the ones left out swim against the ones in.
+ const repositionPins = useCallback(() => {
+ markersRef.current.forEach(pin => pin.reposition())
+ poiMarkersRef.current.forEach(pin => pin.reposition())
+ pluginMarkersRef.current.forEach(pin => pin.reposition())
+ routeViaMarkersRef.current.forEach(pin => pin.reposition())
+ }, [])
// Single reusable hover popup for POI markers. Planned places use the
// cursor-following React tooltip below so they match the Leaflet map.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1185,12 +1200,7 @@ export function MapViewGL({
// pitch. Tried `pitchAlignment: 'map'` to snap markers onto terrain,
// but it rotates the element by the pitch angle and visually offsets
// the anchor by ~100px at 45° tilt, which caused the observed drift.
- const pin = isMapLibre && pinLayerRef.current
- ? makePlacePin(map, pinLayerRef.current, el, place.lng, place.lat)
- : libraryPin(new gl.Marker({ element: el, anchor: 'center' })
- .setLngLat([place.lng, place.lat])
- .addTo(map))
- markersRef.current.set(place.id, pin)
+ markersRef.current.set(place.id, attachPin(map, gl, pinLayerRef.current, el, place.lng, place.lat))
})
}
@@ -1257,8 +1267,7 @@ export function MapViewGL({
})
el.addEventListener('mouseleave', () => { popupRef.current?.remove() })
el.addEventListener('click', (ev) => { ev.stopPropagation(); onPoiClickRef.current?.(poi) })
- const m = new gl.Marker({ element: el, anchor: 'center' }).setLngLat([poi.lng, poi.lat]).addTo(map)
- poiMarkersRef.current.push(m)
+ poiMarkersRef.current.push(attachPin(map, gl, pinLayerRef.current, el, poi.lng, poi.lat))
}
}, [pois, mapReady, glProvider])
@@ -1304,8 +1313,7 @@ export function MapViewGL({
popupRef.current?.setLngLat([v.lng, v.lat]).setText(text).addTo(map)
})
}
- const m = new gl.Marker({ element: el, anchor: 'center' }).setLngLat([v.lng, v.lat]).addTo(map)
- routeViaMarkersRef.current.push(m)
+ routeViaMarkersRef.current.push(attachPin(map, gl, pinLayerRef.current, el, v.lng, v.lat))
}
}, [routeVias, mapReady, glProvider])
@@ -1323,7 +1331,7 @@ export function MapViewGL({
popupRef.current?.setLngLat([mk.lng, mk.lat]).setDOMContent(buildPluginMarkerPopup(mk)).addTo(map)
})
}
- const m = new gl.Marker({ element: el, anchor: 'center' }).setLngLat([mk.lng, mk.lat]).addTo(map)
+ const m = attachPin(map, gl, pinLayerRef.current, el, mk.lng, mk.lat)
pluginMarkersRef.current.push(m)
}
}, [pluginMarkers, mapReady, glProvider])
diff --git a/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx b/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx
index d22f5cf8d..f43412073 100644
--- a/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx
+++ b/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx
@@ -32,11 +32,39 @@ const CATEGORY_META: Record<string, { labelKey: string; Icon: LucideIcon }> = {
const LABEL = 'text-caption font-medium text-content-faint uppercase tracking-wide'
+/**
+ * The brand's logo ahead of its name, falling back to the category icon.
+ *
+ * Same picture as the map pin: a corridor is mostly chains, and the logo is what the eye
+ * finds first. The image lies over the icon and only appears once it has loaded, so a
+ * brand without a logo — or a slow one — shows the icon rather than a hole in the row.
+ */
+function ResultBadge({ poi }: { poi: CorridorPoi }): React.ReactElement {
+ const meta = CATEGORY_META[poi.category]
+ const Icon = meta?.Icon ?? MapPin
+ const brand = poi.brand_wikidata && /^Q[1-9][0-9]{0,11}$/.test(poi.brand_wikidata) ? poi.brand_wikidata : null
+ return (
+ <span className="relative grid h-7 w-7 shrink-0 place-items-center overflow-hidden rounded-lg bg-surface-tertiary">
+ <Icon size={14} className="text-content-faint" aria-hidden />
+ {brand ? (
+ <img
+ src={`/api/maps/brand-logo/${brand}`}
+ alt=""
+ className="absolute inset-0 h-full w-full object-cover opacity-0 transition-opacity"
+ onLoad={e => { e.currentTarget.style.opacity = '1' }}
+ onError={e => e.currentTarget.remove()}
+ />
+ ) : null}
+ </span>
+ )
+}
+
function ResultRow({ poi, onAdd }: { poi: CorridorPoi; onAdd?: () => void }): React.ReactElement {
const { t } = useTranslation()
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
return (
<li className="group flex items-center gap-2.5 rounded-xl px-2.5 py-2 hover:bg-surface-hover">
+ <ResultBadge poi={poi} />
<div className="min-w-0 flex-1">
<div className="truncate text-body text-content">{poi.name}</div>
<div className="text-caption text-content-faint tabular-nums">
diff --git a/client/src/components/Roadtrip/useCorridorPois.ts b/client/src/components/Roadtrip/useCorridorPois.ts
index b7d5134f3..2858bbf1d 100644
--- a/client/src/components/Roadtrip/useCorridorPois.ts
+++ b/client/src/components/Roadtrip/useCorridorPois.ts
@@ -31,9 +31,9 @@ export interface CorridorSearch {
*/
const MAX_TILES = 16
/** Gap after a request before the same worker starts the next — the mirrors are shared. */
-const REQUEST_SPACING_MS = 400
+const REQUEST_SPACING_MS = 250
/** How many boxes are in flight at once. */
-const CONCURRENT_REQUESTS = 3
+const CONCURRENT_REQUESTS = 5
const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
new Promise(resolve => {
@@ -98,10 +98,13 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
setError(false)
setResults([])
setLoading(true)
- setProgress({ done: 0, total: tiles.length * categories.length })
+ setProgress({ done: 0, total: tiles.length })
- const jobs: { tile: Bbox; category: string }[] = []
- for (const tile of tiles) for (const category of categories) jobs.push({ tile, category })
+ // All the wanted kinds in one query per box. Asking per kind was the same answer for
+ // four times the requests, and every extra request is another chance for a shared
+ // mirror to time out — which is what made a search both slow and patchy.
+ const wanted = categories.join(',')
+ const jobs = [...tiles]
void (async () => {
const seen = new Map<string, CorridorPoi>()
@@ -109,38 +112,57 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
let done = 0
let next = 0
- // A few at a time, staggered. Following the real road rather than the line between
- // stops means more boxes to cover the same drive, and asking for them strictly one
- // after another turned a search into half a minute of waiting. The server races
- // several Overpass mirrors and caches what comes back, so a small pool is fair use.
+ // Several at a time. Following the real road rather than the line between stops
+ // means more boxes to cover the same drive, and asking for them one after another
+ // made a search take the better part of a minute. The server races several
+ // Overpass mirrors per request and caches what comes back, so the boxes overlap
+ // cheaply; the small gap afterwards keeps one worker from queueing straight up.
+ const collect = async (tile: Bbox): Promise<boolean> => {
+ try {
+ const data = await mapsApi.pois(wanted, tile, locale, controller.signal)
+ for (const poi of data.pois) {
+ if (seen.has(poi.osm_id)) continue
+ const hit = projectOntoRoute({ lat: poi.lat, lng: poi.lng }, spine)
+ if (!hit || hit.offRouteKm > widthKm) continue
+ seen.set(poi.osm_id, { ...poi, offRouteKm: hit.offRouteKm, alongKm: hit.alongKm })
+ }
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ const publish = (): void => {
+ setProgress({ done, total: jobs.length })
+ setResults([...seen.values()].sort((a, b) => a.alongKm - b.alongKm))
+ }
+
+ const retryable: Bbox[] = []
const worker = async (): Promise<void> => {
while (next < jobs.length) {
if (controller.signal.aborted || runId !== runIdRef.current) return
- const { tile, category } = jobs[next++]
- try {
- const data = await mapsApi.pois(category, tile, locale, controller.signal)
- for (const poi of data.pois) {
- if (seen.has(poi.osm_id)) continue
- const hit = projectOntoRoute({ lat: poi.lat, lng: poi.lng }, spine)
- if (!hit || hit.offRouteKm > widthKm) continue
- seen.set(poi.osm_id, { ...poi, offRouteKm: hit.offRouteKm, alongKm: hit.alongKm })
- }
- } catch {
- // One dead mirror or one clamped box must not empty the whole search; the run
- // is only called a failure if every request failed.
- failures++
- setFailedAreas(failures)
- }
+ const job = jobs[next++]
+ if (!(await collect(job))) retryable.push(job)
done++
if (controller.signal.aborted || runId !== runIdRef.current) return
- setProgress({ done, total: jobs.length })
- setResults([...seen.values()].sort((a, b) => a.alongKm - b.alongKm))
+ publish()
await sleep(REQUEST_SPACING_MS, controller.signal)
}
}
await Promise.all(Array.from({ length: Math.min(CONCURRENT_REQUESTS, jobs.length) }, worker))
if (controller.signal.aborted || runId !== runIdRef.current) return
+
+ // One more pass over what did not answer. Overpass mirrors time out under load far
+ // more often than they are truly empty, and reporting "4 stretches went unsearched"
+ // when a second ask would have answered them is the wrong end of the trade.
+ for (const job of retryable) {
+ if (controller.signal.aborted || runId !== runIdRef.current) return
+ if (await collect(job)) continue
+ failures++
+ setFailedAreas(failures)
+ }
+ publish()
setError(failures === jobs.length && failures > 0)
setLoading(false)
})()
diff --git a/server/src/nest/maps/maps.helpers.ts b/server/src/nest/maps/maps.helpers.ts
index 76ff4d9e1..588f419e5 100644
--- a/server/src/nest/maps/maps.helpers.ts
+++ b/server/src/nest/maps/maps.helpers.ts
@@ -305,6 +305,26 @@ export const CATEGORY_OSM_FILTERS: Record<string, string[]> = {
export const POI_CATEGORY_KEYS = Object.keys(CATEGORY_OSM_FILTERS);
+/** How many categories one POI query may carry, so a caller can't fan out the mirrors. */
+export const MAX_POI_CATEGORIES = 8;
+
+/**
+ * Reads the `category` parameter, which is either one key or a comma-separated list.
+ *
+ * Asking for several kinds at once is one Overpass round-trip instead of one per kind —
+ * the road trip corridor searches four categories over a dozen boxes, and as separate
+ * requests that is four times the load on a shared mirror for the same answer.
+ */
+export function parsePoiCategories(raw: string): string[] {
+ const seen = new Set<string>();
+ for (const part of raw.split(',')) {
+ const key = part.trim();
+ if (key) seen.add(key);
+ if (seen.size >= MAX_POI_CATEGORIES) break;
+ }
+ return [...seen];
+}
+
// Public Overpass mirrors, queried in PARALLEL (first valid response wins).
// Reachability and load vary a lot by network/region — the canonical instance is
// frequently overloaded (504s) and some community mirrors are unreachable from
diff --git a/server/src/nest/maps/maps.mcp.ts b/server/src/nest/maps/maps.mcp.ts
index 6b1b126d1..ef5c939e1 100644
--- a/server/src/nest/maps/maps.mcp.ts
+++ b/server/src/nest/maps/maps.mcp.ts
@@ -1,6 +1,6 @@
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../nest-mcp';
import { z } from 'zod';
-import { POI_CATEGORY_KEYS } from './maps.helpers';
+import { POI_CATEGORY_KEYS, MAX_POI_CATEGORIES } from './maps.helpers';
import { MapsService } from './maps.service';
/**
@@ -91,7 +91,10 @@ export class MapsMcp {
name: 'search_pois',
description: 'List points of interest of one category inside a map rectangle, with address, opening hours, website, phone and cuisine wherever the source carries them. Answers from the TREK place index where it can and from OpenStreetMap otherwise; each result names which one it came from in its `source` field. This is the discovery tool: use it to answer "what is around here" for a neighbourhood or a whole city district. Prefer search_place when the user already named the place they mean. Never calls Google, so it costs nothing and works on an instance with no Places key.',
inputSchema: {
- category: z.enum(POI_CATEGORY_KEYS).describe('Which kind of place to look for'),
+ category: z.union([
+ z.enum(POI_CATEGORY_KEYS),
+ z.array(z.enum(POI_CATEGORY_KEYS)).min(1).max(MAX_POI_CATEGORIES),
+ ]).describe('Which kind of place to look for. Pass several to cover them in one query rather than one request per kind'),
bbox: z.object({
south: z.number().min(-90).max(90).describe('Southern edge, latitude'),
west: z.number().min(-180).max(180).describe('Western edge, longitude'),
@@ -105,14 +108,14 @@ export class MapsMcp {
})
async searchPois(
{ category, bbox, lang }: {
- category: string;
+ category: string | string[];
bbox: { south: number; west: number; north: number; east: number };
lang?: string;
},
_ctx: McpContext,
) {
try {
- return ok(await this.maps.pois(category, bbox, lang));
+ return ok(await this.maps.pois(Array.isArray(category) ? category.join(',') : category, bbox, lang));
} catch {
// Overpass is a set of public mirrors; an outage there is not a bad request.
return errorResult('POI search failed.');
diff --git a/server/src/nest/maps/maps.service.ts b/server/src/nest/maps/maps.service.ts
index a0fdfbb3c..8fd19fbaa 100644
--- a/server/src/nest/maps/maps.service.ts
+++ b/server/src/nest/maps/maps.service.ts
@@ -7,6 +7,7 @@ import type {
MapsReverseResult,
MapsResolveUrlResult,
} from '@trek/shared';
+import { Jimp } from 'jimp';
import { readEnv, getAppUrl } from '../../app-config';
import { safeFetchFollow, SsrfBlockedError } from '../../utils/ssrfGuard';
import { discardBody, exceedsDeclaredLength, readCappedText } from '../../utils/cappedFetch';
@@ -35,6 +36,7 @@ import {
isGooglePlaceId,
OSM_PLACE_ID,
CATEGORY_OSM_FILTERS,
+ parsePoiCategories,
resolveOverpassEndpoints,
resolveOverpassTimeoutMs,
stripWikiMarkup,
@@ -394,7 +396,10 @@ const BRAND_LOGO_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
const BRAND_LOGO_CACHE_MAX = 300;
/** Well past any logo; a Commons original can be a multi-megabyte SVG or print-res PNG. */
const BRAND_LOGO_MAX_BYTES = 512 * 1024;
-const BRAND_LOGO_WIDTH = 96;
+const BRAND_LOGO_WIDTH = 128;
+/** The square the logo is centred in, and the breathing room around it. */
+const BRAND_LOGO_CANVAS = 96;
+const BRAND_LOGO_PADDING = 8;
const WIKIDATA_ID_RE = /^Q[1-9][0-9]{0,11}$/;
export interface BrandLogo {
@@ -402,6 +407,72 @@ export interface BrandLogo {
contentType: string;
}
+/**
+ * Puts a logo on a background it can actually be seen against.
+ *
+ * Half the fuel brands ship a white wordmark with a transparent background —
+ * TotalEnergies, Esso and JET among them — and on the white pill the marker used to
+ * draw they were invisible. Which background is right is a property of the image, not
+ * of the brand, so it is measured: the mean brightness of the pixels that are actually
+ * opaque decides between a white and a near-black backdrop.
+ *
+ * Returns the flattened PNG, or null when the bytes cannot be read at all — the pin
+ * then keeps its category icon, which is a fine outcome.
+ */
+async function flattenBrandLogo(bytes: Buffer): Promise<BrandLogo | null> {
+ try {
+ const image = await Jimp.read(bytes);
+ const width = image.bitmap.width;
+ const height = image.bitmap.height;
+ if (!width || !height) return null;
+
+ let sum = 0;
+ let opaque = 0;
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const idx = (y * width + x) * 4;
+ const alpha = image.bitmap.data[idx + 3];
+ // Half-transparent pixels are anti-aliasing, not the mark itself.
+ if (alpha < 128) continue;
+ const r = image.bitmap.data[idx];
+ const g = image.bitmap.data[idx + 1];
+ const b = image.bitmap.data[idx + 2];
+ sum += 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ opaque++;
+ }
+ }
+ // A logo with nothing opaque in it is not a logo.
+ if (opaque === 0) return null;
+
+ // Square, with the logo scaled to fit inside it. Most brand marks are wide wordmarks
+ // — TotalEnergies is three times as wide as it is tall — and a round pin showing the
+ // middle of one is unreadable. Fitting it into a square means the pin can crop to a
+ // circle without ever cutting the mark itself.
+ const scale = Math.min(
+ (BRAND_LOGO_CANVAS - 2 * BRAND_LOGO_PADDING) / width,
+ (BRAND_LOGO_CANVAS - 2 * BRAND_LOGO_PADDING) / height,
+ );
+ // Never upscale: a 16-pixel favicon blown up to 96 looks worse than a small one.
+ if (scale < 1) image.scale(scale);
+
+ const light = sum / opaque > 150;
+ const canvas = new Jimp({
+ width: BRAND_LOGO_CANVAS,
+ height: BRAND_LOGO_CANVAS,
+ color: light ? 0x111827ff : 0xffffffff,
+ });
+ canvas.composite(
+ image,
+ Math.round((BRAND_LOGO_CANVAS - image.bitmap.width) / 2),
+ Math.round((BRAND_LOGO_CANVAS - image.bitmap.height) / 2),
+ );
+ const out = await canvas.getBuffer('image/png');
+ return { bytes: Buffer.from(out), contentType: 'image/png' };
+ } catch {
+ return null;
+ }
+}
+
// Tighter than the wiki calls, because this one sits at the FRONT of a chain:
// identity, then sitelinks, then the extract. Nominatim answers a bounded
// search in 0.2-0.7s in practice, so anything past a couple of seconds is a bad
@@ -486,6 +557,12 @@ const POI_CACHE_TTL_MS = 5 * 60 * 1000;
// Cap the number of cached areas so panning across the globe can't grow the map
// without bound (entries are evicted oldest-first once the cap is reached).
const POI_CACHE_MAX = 500;
+/**
+ * Hard ceiling on one POI answer, however many categories it carries. A corridor search
+ * asks for four kinds at once; without a ceiling a dense city box would return a payload
+ * nobody reads and every mirror pays for.
+ */
+const POI_RESULT_CAP = 240;
// POST the query to all mirrors at once and return the first one that answers with
// valid JSON. Throws {status:502} only if every mirror fails. Racing (rather than
@@ -725,7 +802,7 @@ export class MapsService {
const contentType = imgRes.headers.get('content-type') ?? '';
if (!contentType.startsWith('image/')) return remember(null);
- return remember({ bytes, contentType });
+ return remember(await flattenBrandLogo(bytes));
} catch (err) {
if (err instanceof SsrfBlockedError) return remember(null);
return remember(null);
@@ -1092,8 +1169,20 @@ export class MapsService {
lang?: string,
limit = 60,
): Promise<PoiSearchResult> {
- const filters = CATEGORY_OSM_FILTERS[category];
- if (!filters) throw Object.assign(new Error('Unknown POI category'), { status: 400 });
+ // One or several categories in one query. Each OSM selector belongs to exactly one
+ // category, so a hit can still be labelled with the category it answered.
+ const categories = parsePoiCategories(category);
+ if (!categories.length) throw Object.assign(new Error('Unknown POI category'), { status: 400 });
+ const categoryOfFilter = new Map<string, string>();
+ for (const key of categories) {
+ const own = CATEGORY_OSM_FILTERS[key];
+ if (!own) throw Object.assign(new Error('Unknown POI category'), { status: 400 });
+ for (const f of own) categoryOfFilter.set(f, key);
+ }
+ const filters = [...categoryOfFilter.keys()];
+ // Each category gets its own share of the cap, or a mixed search would spend the
+ // whole budget on whichever kind happens to be densest.
+ const cap = Math.min(limit * categories.length, POI_RESULT_CAP);
// Clamp an oversized viewport to a centred window so the query stays cheap and
// returns fast at any zoom, instead of timing out / 502-ing on a huge area.
@@ -1120,7 +1209,7 @@ export class MapsService {
const osmLang = toApiLang(lang).split('-')[0].toLowerCase();
// Serve repeat pans/toggles of the same area straight from the cache.
- const cacheKey = `${category}|${osmLang}|${south.toFixed(2)},${west.toFixed(2)},${north.toFixed(2)},${east.toFixed(2)}|${limit}`;
+ const cacheKey = `${[...categories].sort().join('+')}|${osmLang}|${south.toFixed(2)},${west.toFixed(2)},${north.toFixed(2)},${east.toFixed(2)}|${cap}`;
const cached = POI_CACHE.get(cacheKey);
if (cached && Date.now() - cached.at < POI_CACHE_TTL_MS) return cached.value;
if (cached) POI_CACHE.delete(cacheKey); // expired — drop it before refetching
@@ -1135,7 +1224,7 @@ export class MapsService {
.join('\n');
// `out center tags <n>` returns ways/relations with a computed center and caps
// the result count in one round-trip.
- const query = `[out:json][timeout:20];\n(\n${selectors}\n);\nout center tags ${limit + 25};`;
+ const query = `[out:json][timeout:20];\n(\n${selectors}\n);\nout center tags ${cap + 25};`;
const elements = await overpassFetch(query);
@@ -1172,7 +1261,7 @@ export class MapsService {
name,
lat,
lng,
- category,
+ category: categoryOfFilter.get(matched) ?? categories[0],
poi_type: matched,
address: addr,
website: tags.website || tags['contact:website'] || null,
@@ -1186,8 +1275,8 @@ export class MapsService {
source: 'openstreetmap',
});
}
- const truncated = pois.length > limit;
- const value: PoiSearchResult = { pois: pois.slice(0, limit), source: 'openstreetmap', truncated, clamped };
+ const truncated = pois.length > cap;
+ const value: PoiSearchResult = { pois: pois.slice(0, cap), source: 'openstreetmap', truncated, clamped };
// FIFO eviction: a Map preserves insertion order, so the first key is the oldest.
if (POI_CACHE.size >= POI_CACHE_MAX) POI_CACHE.delete(POI_CACHE.keys().next().value as string);
POI_CACHE.set(cacheKey, { at: Date.now(), value });
diff --git a/server/tests/unit/nest/maps.service.test.ts b/server/tests/unit/nest/maps.service.test.ts
index ac4e4e041..a78b437e1 100644
--- a/server/tests/unit/nest/maps.service.test.ts
+++ b/server/tests/unit/nest/maps.service.test.ts
@@ -27,6 +27,7 @@ import {
} from '../../../src/nest/maps/maps.helpers';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
+import { Jimp } from 'jimp';
// The seams below stand in for real collaborators, so they are typed from those
// collaborators' signatures rather than from their own default implementations.
@@ -2503,6 +2504,69 @@ describe('resolveOverpassTimeoutMs', () => {
});
});
+// ── searchOverpassPois with several categories at once (#1797) ────────────────
+
+describe('searchOverpassPois multi-category', () => {
+ const bbox = (n: number) => ({ south: 50 + n / 100, west: 8, north: 50.2 + n / 100, east: 8.2 });
+
+ it('MAPS-155: asks Overpass once for every category and labels each hit with its own', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ elements: [
+ { type: 'node', id: 1, lat: 50.1, lon: 8.1, tags: { name: 'Aral', amenity: 'fuel' } },
+ { type: 'node', id: 2, lat: 50.11, lon: 8.11, tags: { name: 'Ionity', amenity: 'charging_station' } },
+ { type: 'node', id: 3, lat: 50.12, lon: 8.12, tags: { name: 'Rasthof Taunus', highway: 'services' } },
+ ],
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ // One category first, to learn what a single box costs (the service races mirrors).
+ await svc.searchOverpassPois('fuel', bbox(9), 'en-US');
+ const single = fetchMock.mock.calls.length;
+ fetchMock.mockClear();
+
+ const { pois } = await svc.searchOverpassPois('fuel,charging,rest_area', bbox(1), 'en-US');
+
+ // Three categories cost exactly what one does — the whole point of the batching.
+ expect(fetchMock.mock.calls.length).toBe(single);
+ // The query goes out form-encoded, so read it back the way Overpass will.
+ const body = decodeURIComponent(String(fetchMock.mock.calls[0][1]?.body ?? ''));
+ expect(body).toContain('amenity"="fuel');
+ expect(body).toContain('amenity"="charging_station');
+ expect(body).toContain('highway"="services');
+ expect(pois.map(p => [p.name, p.category])).toEqual([
+ ['Aral', 'fuel'],
+ ['Ionity', 'charging'],
+ ['Rasthof Taunus', 'rest_area'],
+ ]);
+ });
+
+ it('MAPS-156: refuses the whole query when one of the categories is not a category', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(svc.searchOverpassPois('fuel,unicorns', bbox(2))).rejects.toMatchObject({ status: 400 });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('MAPS-157: a repeat of the same set is served from the cache whatever the order', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ elements: [{ type: 'node', id: 9, lat: 50.3, lon: 8.3, tags: { name: 'Shell', amenity: 'fuel' } }] }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await svc.searchOverpassPois('fuel,campsite', bbox(3), 'en-US');
+ const asked = fetchMock.mock.calls.length;
+ await svc.searchOverpassPois('campsite,fuel', bbox(3), 'en-US');
+
+ // Same set, written the other way round: the second ask costs nothing.
+ expect(fetchMock.mock.calls.length).toBe(asked);
+ });
+});
+
// ── searchOverpassPois error path (all endpoints down, #1309) ──────────────────
describe('searchOverpassPois all-endpoints-down', () => {
@@ -3270,23 +3334,71 @@ describe('brandLogo', () => {
arrayBuffer: async () => new ArrayBuffer(bytes),
});
- it('MAPS-147: reads the logo claim and serves the bytes Commons returns', async () => {
+ /** A real PNG — the flattening path decodes what it is given, so a fake buffer won't do. */
+ const pngBytes = async (width: number, height: number, color: number): Promise<ArrayBuffer> => {
+ const buf = await new Jimp({ width, height, color }).getBuffer('image/png');
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;
+ };
+
+ const pngResponse = (bytes: ArrayBuffer) => ({
+ ok: true,
+ headers: new Headers({ 'content-type': 'image/png', 'content-length': String(bytes.byteLength) }),
+ arrayBuffer: async () => bytes,
+ });
+
+ it('MAPS-147: reads the logo claim and flattens the returned bytes onto a square', async () => {
+ // A wide, dark wordmark — the shape that used to arrive as a plain white pin.
const fetchMock = vi.fn()
.mockResolvedValueOnce(claimResponse('Aral Logo.svg'))
- .mockResolvedValueOnce(imageResponse(2278));
+ .mockResolvedValueOnce(pngResponse(await pngBytes(120, 40, 0x1a3d8fff)));
vi.stubGlobal('fetch', fetchMock);
const logo = await service().brandLogo('Q565734');
- expect(logo?.bytes.byteLength).toBe(2278);
expect(logo?.contentType).toBe('image/png');
+ const out = await Jimp.read(Buffer.from(logo!.bytes));
+ // Square, so the round pin can crop it without ever cutting the mark.
+ expect(out.bitmap.width).toBe(96);
+ expect(out.bitmap.height).toBe(96);
+ // A dark mark gets a light ground, and the padding stays clear of it: the whole
+ // wordmark is visible instead of the pin showing its middle.
+ expect(out.getPixelColor(2, 2)).toBe(0xffffffff);
+ expect(out.getPixelColor(4, 48)).toBe(0xffffffff);
+ expect(out.getPixelColor(48, 48)).toBe(0x1a3d8fff);
+
const [claimUrl] = fetchMock.mock.calls[0];
expect(claimUrl).toContain('wbgetclaims');
expect(claimUrl).toContain('property=P154');
const [fileUrl] = fetchMock.mock.calls[1];
// Special:FilePath renders the thumbnail and redirects, so the width rides along.
expect(fileUrl).toContain('Special:FilePath/Aral%20Logo.svg');
- expect(fileUrl).toContain('width=96');
+ expect(fileUrl).toContain('width=128');
+ });
+
+ it('MAPS-153: a near-white logo gets a dark ground instead of vanishing', async () => {
+ // TotalEnergies, Esso and JET all read as white marks; on a white pin they were gone.
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(claimResponse('JET logo.svg'))
+ .mockResolvedValueOnce(pngResponse(await pngBytes(64, 64, 0xfafafaff)));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const out = await Jimp.read(Buffer.from((await service().brandLogo('Q568940'))!.bytes));
+
+ expect(out.getPixelColor(2, 2)).toBe(0x111827ff);
+ expect(out.getPixelColor(48, 48)).toBe(0xfafafaff);
+ });
+
+ it('MAPS-154: a logo smaller than the canvas is left at its own size, not blown up', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(claimResponse('Tiny.png'))
+ .mockResolvedValueOnce(pngResponse(await pngBytes(16, 16, 0x203040ff)));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const out = await Jimp.read(Buffer.from((await service().brandLogo('Q1'))!.bytes));
+
+ // Centred on the 96px canvas: the 16px mark occupies 40..56, the rest is ground.
+ expect(out.getPixelColor(48, 48)).toBe(0x203040ff);
+ expect(out.getPixelColor(30, 48)).toBe(0xffffffff);
});
it('MAPS-148: asks Wikidata nothing when the id is not one', async () => {