mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix: the findings of the final 4.3.0 audit
Every file the release touches was read once more, and what survived an independent check against the code is fixed here, with a test for each. Data and credentials - A document sync connection edited to a new address no longer carries the stored token along: a blank form under another origin is refused, the same rule the probe route already had. Dawarich and AirTrail testConnection send the stored key only to the host it was stored for. - The key rotation script now covers document_connections.secrets and trip_document_links.webhook_secret, which it had skipped. - Turning a booked night into a pause in the road trip popup asks first and says that the booking and its expense go with it. Deleting a place says the same when a night is booked there, on the desktop and on the phone. - A moved version marker over unchanged bytes no longer replaces the TREK file and its attachments; a real revision carries the attachments over. Planner - A drop in the day plan names the row it lands ahead of in the full day, so a hidden hotel stop no longer shifts it one slot early; the store sorts before it splices. Via re-anchoring, the booked-night guard and the sidebar's day membership read the stored day, the index space the server uses. - A hotel stop placed mid-day re-pins the road trip vias of that day, and the booking session receives the new stop order too. The Public API and the iCal feed list a booked hotel once. A plugin can no longer write a stay against another trip's day. Road trip and map - The route overview paces its requests to the public routers and retries a rate limit, and it says which legs it could not route instead of quietly reporting a shorter trip. A click on a via handle no longer drops a second via; handles hide when zooming out. Read-only members cannot edit the driving limits. The phone shows a way back when no day is picked and prints the night drive departure in the chosen clock format. Integrations and search - Google transit keeps conventional trains when the train chip is on. TREK_PLACES_ENABLED=false stops the details and enrichment calls too, and accepts the whole boolean family. A caller-supplied description no longer lands in the instance-wide enrichment cache. Nominatim searches carry a timeout. An OSM place id is checked for shape before it reaches Overpass. - Dawarich puts a stay on the trip whose dates hold it, the Atlas hand-off knows what the Atlas already shows, and a host change with a new key clears the old instance's state. - Document sync: a webhook address pasted by hand works on the token alone, deleting a connection unregisters its subscriptions, Nextcloud under a sub-path connects, Synology answers a name collision before uploading and verifies a move into the bin, Paperless titles are capped at 128 characters, a DNS failure reads as unreachable rather than as a policy verdict, videos from the store are accepted like uploads, and remote_missing has a way out. Conflict buttons only for the owner, a refused choice is reported, a refused credential gets a Reconnect button, disconnecting asks first on the desktop as it does on the phone, and the folder picker no longer spins forever. Release - The server holds the release notice back from a bundle that cannot draw it, so the previous shell served from the service worker cache after an update no longer shows bare keys and no longer lets a click use the notice up. - Import into an existing list gets the same body limit as a new list. Chat images say when the limit is reached and the new controls are translated. The transit backend switch reports a failed save. The Helm chart carries the Amap credentials in its Secret; the shipped templates document the Places API and Amap variables and the Overpass default. The wiki follows.
This commit is contained in:
@@ -2165,6 +2165,118 @@ describe('MapViewGL', () => {
|
||||
// in the wrong place.
|
||||
expect(layer.firstElementChild).not.toBe(handle)
|
||||
})
|
||||
|
||||
// Both GL libraries take their clicks from the canvas container, and the handle sits
|
||||
// inside it, right on the route's hit band. Stopping pointerdown does not stop the click
|
||||
// that follows, so a click on a handle also read as a click on the road under it and
|
||||
// dropped a second via exactly there.
|
||||
it('FE-COMP-MAPVIEWGL-VIA-003: a click on a via handle is the handle\'s, not the road\'s', async () => {
|
||||
loadOnAttach()
|
||||
glCanvasContainer.replaceChildren()
|
||||
glMap.project.mockReturnValue({ x: 100, y: 80 })
|
||||
glMap.getLayer.mockImplementation((id: string) => (id === 'trip-route-hit' ? { id } : null))
|
||||
const onRouteClick = vi.fn()
|
||||
|
||||
const stored = { id: 5, day_id: 1, after_order_index: 0, sequence: 0, lat: 48.1, lng: 2.1 }
|
||||
render(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
fitKey={1}
|
||||
glProvider="maplibre-gl"
|
||||
roadtripVias={{ 1: [stored] }}
|
||||
onMoveVia={() => {}}
|
||||
onRouteClick={onRouteClick}
|
||||
/>,
|
||||
)
|
||||
await flushFrames()
|
||||
|
||||
const layer = glCanvasContainer.firstElementChild as HTMLElement
|
||||
const handle = layer.firstElementChild as HTMLElement
|
||||
|
||||
const reachedMap = vi.fn()
|
||||
glCanvasContainer.addEventListener('click', reachedMap)
|
||||
try {
|
||||
act(() => { handle.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
||||
expect(reachedMap).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
glCanvasContainer.removeEventListener('click', reachedMap)
|
||||
}
|
||||
|
||||
// And the road's own handler leaves a click that came through the handle alone.
|
||||
const roadClick = layerHandler('click', 'trip-route-hit')
|
||||
expect(roadClick).toBeTypeOf('function')
|
||||
act(() => { roadClick({ lngLat: { lat: 48.1, lng: 2.1 }, point: { x: 100, y: 80 }, originalEvent: { target: handle } }) })
|
||||
expect(onRouteClick).not.toHaveBeenCalled()
|
||||
act(() => { roadClick({ lngLat: { lat: 48.1, lng: 2.1 }, point: { x: 100, y: 80 }, originalEvent: { target: glCanvasContainer } }) })
|
||||
expect(onRouteClick).toHaveBeenCalledWith(48.1, 2.1)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEWGL-VIA-004: a right-click on a via handle removes it and opens nothing underneath', async () => {
|
||||
loadOnAttach()
|
||||
glCanvasContainer.replaceChildren()
|
||||
glMap.project.mockReturnValue({ x: 100, y: 80 })
|
||||
const onRemoveVia = vi.fn()
|
||||
|
||||
const stored = { id: 5, day_id: 1, after_order_index: 0, sequence: 0, lat: 48.1, lng: 2.1 }
|
||||
render(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
fitKey={1}
|
||||
glProvider="maplibre-gl"
|
||||
roadtripVias={{ 1: [stored] }}
|
||||
onMoveVia={() => {}}
|
||||
onRemoveVia={onRemoveVia}
|
||||
/>,
|
||||
)
|
||||
await flushFrames()
|
||||
|
||||
const layer = glCanvasContainer.firstElementChild as HTMLElement
|
||||
const handle = layer.firstElementChild as HTMLElement
|
||||
|
||||
// The map's contextmenu is the add-place gesture; it must not fire for the spot the
|
||||
// via has just been removed from.
|
||||
const reachedMap = vi.fn()
|
||||
glCanvasContainer.addEventListener('contextmenu', reachedMap)
|
||||
try {
|
||||
act(() => { handle.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })) })
|
||||
} finally {
|
||||
glCanvasContainer.removeEventListener('contextmenu', reachedMap)
|
||||
}
|
||||
|
||||
expect(onRemoveVia).toHaveBeenCalledWith(1, 5)
|
||||
expect(reachedMap).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEWGL-VIA-005: the handles go away below the zoom a via can be aimed at', async () => {
|
||||
loadOnAttach()
|
||||
glCanvasContainer.replaceChildren()
|
||||
glMap.project.mockReturnValue({ x: 100, y: 80 })
|
||||
// Country scale: a day's vias collapse into a heap of dots over one town, and a
|
||||
// short drag on one of them moves the route by kilometres.
|
||||
vi.mocked(glMap.getZoom).mockReturnValue(8)
|
||||
try {
|
||||
const stored = { id: 5, day_id: 1, after_order_index: 0, sequence: 0, lat: 48.1, lng: 2.1 }
|
||||
render(
|
||||
<MapViewGL places={[]} fitKey={1} glProvider="maplibre-gl" roadtripVias={{ 1: [stored] }} onMoveVia={() => {}} />,
|
||||
)
|
||||
await flushFrames()
|
||||
|
||||
const layer = glCanvasContainer.firstElementChild as HTMLElement
|
||||
const handle = layer.firstElementChild as HTMLElement
|
||||
expect(handle.style.display).toBe('none')
|
||||
|
||||
// Back in close enough, the zoom that settles brings them back.
|
||||
vi.mocked(glMap.getZoom).mockReturnValue(12)
|
||||
act(() => {
|
||||
glMap.on.mock.calls
|
||||
.filter(c => c[0] === 'zoomend' && typeof c[1] === 'function')
|
||||
.forEach(c => (c[1] as () => void)())
|
||||
})
|
||||
expect(handle.style.display).toBe('block')
|
||||
} finally {
|
||||
vi.mocked(glMap.getZoom).mockReturnValue(10)
|
||||
}
|
||||
})
|
||||
// ── Satellite ───────────────────────────────────────────────────────────────
|
||||
//
|
||||
// Leaflet has had the imagery for a while and swaps its whole tile layer for it.
|
||||
|
||||
@@ -845,15 +845,17 @@ export function MapViewGL({
|
||||
const VIA_MIN_ZOOM = 9
|
||||
const applyViaZoom = () => {
|
||||
const on = map.getZoom() >= VIA_MIN_ZOOM
|
||||
for (const pin of viaPinsRef.current) {
|
||||
const node = (pin as { getElement?: () => HTMLElement | null }).getElement?.()
|
||||
if (node) node.style.display = on ? '' : 'none'
|
||||
}
|
||||
// `el` is the one handle both pin paths expose; the library marker's own accessor
|
||||
// does not exist on the hand-positioned pin, so reading that left every handle on.
|
||||
for (const pin of viaPinsRef.current) pin.el.style.display = on ? 'block' : 'none'
|
||||
}
|
||||
|
||||
for (const via of vias) {
|
||||
const el = document.createElement('span')
|
||||
el.style.cssText = 'display:block;width:12px;height:12px;border-radius:9999px;background:#0a84ff;border:2.5px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.45);cursor:grab;touch-action:none'
|
||||
// Marks the handle for the map's own click handlers: the drive's hit band runs
|
||||
// right under it, and a click that lands here is the handle's, not the road's.
|
||||
el.dataset.viaHandle = ''
|
||||
const pin = attachPin(map, gl, pinLayerRef.current, el, via.lng, via.lat)
|
||||
viaPinsRef.current.push(pin)
|
||||
if (!viasDraggable) continue
|
||||
@@ -918,6 +920,10 @@ export function MapViewGL({
|
||||
}
|
||||
const onContext = (e: MouseEvent) => {
|
||||
e.preventDefault()
|
||||
// Stopped here as well: both GL libraries listen on the canvas container the
|
||||
// handle sits in, and the map's own contextmenu opens the add-place form at
|
||||
// the very spot the via has just been removed from.
|
||||
e.stopPropagation()
|
||||
viaHandlersRef.current.onRemoveVia?.(via.day_id, via.id)
|
||||
}
|
||||
el.addEventListener('pointerdown', onDown)
|
||||
@@ -928,6 +934,10 @@ export function MapViewGL({
|
||||
el.addEventListener('mousedown', swallow)
|
||||
el.addEventListener('touchstart', swallow, { passive: true })
|
||||
el.addEventListener('dblclick', swallow)
|
||||
// Stopping pointerdown does not stop the click that follows it, and the handle sits
|
||||
// on the route's hit band: the map's click landed on the road and dropped a second
|
||||
// via exactly under the one that was clicked.
|
||||
el.addEventListener('click', swallow)
|
||||
viaCleanupRef.current.push(() => {
|
||||
el.removeEventListener('pointerdown', onDown)
|
||||
el.removeEventListener('pointermove', onMove)
|
||||
@@ -937,6 +947,7 @@ export function MapViewGL({
|
||||
el.removeEventListener('mousedown', swallow)
|
||||
el.removeEventListener('touchstart', swallow)
|
||||
el.removeEventListener('dblclick', swallow)
|
||||
el.removeEventListener('click', swallow)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1072,8 +1083,19 @@ export function MapViewGL({
|
||||
useEffect(() => {
|
||||
const map = mapRef.current
|
||||
if (!map || !mapReady || !onRouteClick) return
|
||||
const onClick = (e: { lngLat: { lat: number; lng: number }; point?: { x: number; y: number }; preventDefault?: () => void }) => {
|
||||
const onClick = (e: {
|
||||
lngLat: { lat: number; lng: number }
|
||||
point?: { x: number; y: number }
|
||||
originalEvent?: { target?: EventTarget | null }
|
||||
preventDefault?: () => void
|
||||
}) => {
|
||||
e.preventDefault?.()
|
||||
// A layer handler only asks what is drawn under the point, not what element the
|
||||
// click came through. A via handle sits on the band by definition, and a click on
|
||||
// it must not read as a click on the road under it; the map-level handler below
|
||||
// filters markers the same way.
|
||||
const target = e.originalEvent?.target
|
||||
if (target instanceof Element && target.closest('[data-via-handle], .mapboxgl-marker, .maplibregl-marker')) return
|
||||
// Layer handlers are independent: MapLibre evaluates each registration
|
||||
// against the same click, so a point that hits both the offered-route band
|
||||
// and the current-route band fires both. Every alternative starts and ends
|
||||
|
||||
@@ -87,4 +87,39 @@ describe('TripRouteOverviewPanel', () => {
|
||||
const { container } = render(<TripRouteOverviewPanel overview={overview({ days: [], totalDistance: 0 })} unit="metric" />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-MAP-TROU-009: says when legs could not be routed, and marks the day that is short', () => {
|
||||
// A refused leg stays a straight line and adds nothing to the sum, so a total shown
|
||||
// without a word about it reads as the whole trip when it is not.
|
||||
const days = overview().days
|
||||
const short = overview({
|
||||
days: [{ ...days[0], unroutedLegs: 1 }, { ...days[1], unroutedLegs: 0 }],
|
||||
unroutedLegs: 1,
|
||||
})
|
||||
render(<TripRouteOverviewPanel overview={short} unit="metric" />)
|
||||
|
||||
expect(screen.getByTestId('trip-overview-unrouted')).toHaveTextContent('map.overview.unrouted')
|
||||
expect(screen.getAllByRole('img', { name: 'map.overview.dayUnrouted' })).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-MAP-TROU-010: does not call a leg unrouted while the round is still running', () => {
|
||||
// Every leg still waiting is unrouted too; the ellipsis already says the number grows.
|
||||
const days = overview().days
|
||||
const running = overview({
|
||||
days: [{ ...days[0], unroutedLegs: 1 }, { ...days[1], unroutedLegs: 1 }],
|
||||
unroutedLegs: 2,
|
||||
loading: true,
|
||||
})
|
||||
render(<TripRouteOverviewPanel overview={running} unit="metric" />)
|
||||
|
||||
expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull()
|
||||
expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-MAP-TROU-011: a fully routed trip carries no warning at all', () => {
|
||||
render(<TripRouteOverviewPanel overview={overview({ unroutedLegs: 0 })} unit="metric" />)
|
||||
|
||||
expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull()
|
||||
expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Route } from 'lucide-react'
|
||||
import { AlertTriangle, Route } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { profileIcon } from '../Planner/DayPlanSidebarRouteConnector'
|
||||
@@ -66,6 +66,9 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
if (!overview.days.length) return null
|
||||
// Only once the round is over: while it runs every leg still waiting is unrouted too,
|
||||
// and the ellipsis on the total already says the number is growing.
|
||||
const unrouted = overview.loading ? 0 : (overview.unroutedLegs ?? 0)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -95,9 +98,23 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
{overview.loading && <span className="text-content-muted" style={{ fontWeight: 400 }}>{' '}…</span>}
|
||||
</span>
|
||||
</div>
|
||||
{/* A leg the router refused stays a straight line and adds nothing to the sum, so
|
||||
the total is short by however much road those legs are. Said in words rather than
|
||||
left to the reader to notice, because the number is what a fuel estimate starts from. */}
|
||||
{unrouted > 0 && (
|
||||
<div
|
||||
data-testid="trip-overview-unrouted"
|
||||
className="text-warning"
|
||||
style={{ display: 'flex', alignItems: 'flex-start', gap: 6, padding: '0 14px 8px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}
|
||||
>
|
||||
<AlertTriangle size={12} style={{ flexShrink: 0, marginTop: 1 }} aria-hidden />
|
||||
<span>{t('map.overview.unrouted', { count: unrouted })}</span>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ maxHeight: 220, overflowY: 'auto', borderTop: '1px solid var(--border-primary)' }}>
|
||||
{overview.days.map(day => {
|
||||
const label = day.title || t('dayplan.dayN', { n: day.dayNumber })
|
||||
const dayUnrouted = overview.loading ? 0 : (day.unroutedLegs ?? 0)
|
||||
const row = (
|
||||
<>
|
||||
<span style={{ width: 8, height: 8, borderRadius: 999, background: day.color.line, flexShrink: 0 }} aria-hidden />
|
||||
@@ -110,6 +127,17 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
return <Icon key={mode} size={12} strokeWidth={2} aria-hidden />
|
||||
})}
|
||||
</span>
|
||||
{/* The day's own share of the shortfall, so the reader knows which figure
|
||||
to distrust rather than only that one of them is off. */}
|
||||
{dayUnrouted > 0 && (
|
||||
<AlertTriangle
|
||||
size={12}
|
||||
className="text-warning"
|
||||
style={{ flexShrink: 0 }}
|
||||
role="img"
|
||||
aria-label={t('map.overview.dayUnrouted', { count: dayUnrouted })}
|
||||
/>
|
||||
)}
|
||||
<span className="text-content-muted" style={{ flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>
|
||||
{formatDistance(day.distance / 1000, unit)}
|
||||
</span>
|
||||
|
||||
@@ -9,7 +9,7 @@ vi.mock('./RouteCalculator', async (importActual) => {
|
||||
return { ...actual, calculateRouteWithLegs: vi.fn() }
|
||||
})
|
||||
|
||||
const { calculateRouteWithLegs } = await import('./RouteCalculator')
|
||||
const { calculateRouteWithLegs, RoutingRefusedError } = await import('./RouteCalculator')
|
||||
|
||||
const leg = (distance: number): RouteSegment => ({
|
||||
mid: [0, 0], from: [0, 0], to: [0, 0], distance, duration: 600,
|
||||
@@ -104,4 +104,112 @@ describe('tripRouteGeometry', () => {
|
||||
|
||||
await expect(pending).resolves.toMatchObject({ totalDistance: 0 })
|
||||
})
|
||||
|
||||
// The public OSRM hosts allow about one request a second. Every leg of every day at
|
||||
// once is exactly the burst they answer with 429 from the second second on, and each
|
||||
// refused leg used to stay a straight line with no distance and no word about it.
|
||||
it('FE-MAP-TRG-007: asks the router one leg at a time, a second apart', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
// A round trip takes time; only a network answer is paced, a cache hit is not.
|
||||
vi.mocked(calculateRouteWithLegs).mockImplementation(() => new Promise(resolve => {
|
||||
setTimeout(() => resolve({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] }), 100)
|
||||
}))
|
||||
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
|
||||
|
||||
// The second day waits for the first to answer...
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
// ...and then for the gap the shared hosts need between two requests.
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(1100)
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
const summary = await pending
|
||||
expect(summary.totalDistance).toBe(20000)
|
||||
expect(summary.unroutedLegs).toBe(0)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-MAP-TRG-008: a rate limit is waited out and the leg asked for again', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.mocked(calculateRouteWithLegs)
|
||||
.mockRejectedValueOnce(new RoutingRefusedError(429, null))
|
||||
.mockResolvedValue({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] })
|
||||
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1500)
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
|
||||
await vi.advanceTimersByTimeAsync(1100)
|
||||
const summary = await pending
|
||||
|
||||
// Both days routed: the refused leg answered on its second try.
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(3)
|
||||
expect(summary.totalDistance).toBe(20000)
|
||||
expect(summary.unroutedLegs).toBe(0)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-MAP-TRG-009: a host that says how long to wait is given that long', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.mocked(calculateRouteWithLegs)
|
||||
.mockRejectedValueOnce(new RoutingRefusedError(429, 6000))
|
||||
.mockResolvedValue({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] })
|
||||
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
|
||||
|
||||
// The own first backoff would be 1500 ms; asking then is just a second refusal.
|
||||
await vi.advanceTimersByTimeAsync(2000)
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(4000)
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1100)
|
||||
await expect(pending).resolves.toMatchObject({ totalDistance: 20000 })
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-MAP-TRG-010: a refusal the host meant is not repeated, and the leg is counted as unrouted', async () => {
|
||||
// A 400 objects to these coordinates; the same request earns the same answer.
|
||||
vi.mocked(calculateRouteWithLegs)
|
||||
.mockRejectedValueOnce(new RoutingRefusedError(400, null))
|
||||
.mockResolvedValue({ coordinates: [[45.76, 4.83], [45.80, 4.90]], distance: 10000, duration: 600, legs: [leg(10000)] })
|
||||
|
||||
const summary = await routeTrip(input, { profile: 'driving', tripId: 7 })
|
||||
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
|
||||
// The first day keeps its straight line and adds nothing to the sum...
|
||||
expect(summary.lines[0]).toEqual([[48.86, 2.35], [48.90, 2.42]])
|
||||
expect(summary.days[0].distance).toBe(0)
|
||||
expect(summary.totalDistance).toBe(10000)
|
||||
// ...and says so, per day and for the trip, so the total is not mistaken for complete.
|
||||
expect(summary.days.map(d => d.unroutedLegs)).toEqual([1, 0])
|
||||
expect(summary.unroutedLegs).toBe(1)
|
||||
})
|
||||
|
||||
it('FE-MAP-TRG-011: a rate limit that never lifts gives up after the retries and is counted', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.mocked(calculateRouteWithLegs).mockRejectedValue(new RoutingRefusedError(429, null))
|
||||
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
|
||||
|
||||
// Two backoffs per leg, a gap between the legs, then it stops asking.
|
||||
await vi.advanceTimersByTimeAsync(20000)
|
||||
const summary = await pending
|
||||
|
||||
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(6)
|
||||
expect(summary.totalDistance).toBe(0)
|
||||
expect(summary.unroutedLegs).toBe(2)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { calculateRouteWithLegs, type RouteProfileKey } from './RouteCalculator'
|
||||
import { calculateRouteWithLegs, RoutingRefusedError, type RouteProfileKey } from './RouteCalculator'
|
||||
import { buildDayRouteRuns, type DayRouteInputs, type DayRoutePoint } from './dayRoutePlan'
|
||||
import { resolveLegMode } from '../Planner/legMode'
|
||||
import { dayColor } from '../Roadtrip/dayColors'
|
||||
@@ -21,6 +21,12 @@ export interface TripOverviewDay {
|
||||
duration: number
|
||||
/** The modes this day is actually travelled in, first use first. */
|
||||
modes: string[]
|
||||
/**
|
||||
* Legs drawn as a straight line because the router gave no road for them: not asked
|
||||
* yet while the round is running, refused or cut off by the deadline once it is over.
|
||||
* Those legs add nothing to `distance`, so a day with any of them reads too short.
|
||||
*/
|
||||
unroutedLegs?: number
|
||||
}
|
||||
|
||||
export interface TripRouteSummary {
|
||||
@@ -34,6 +40,8 @@ export interface TripRouteSummary {
|
||||
focusPoints: [number, number][]
|
||||
totalDistance: number
|
||||
totalDuration: number
|
||||
/** `unroutedLegs` over every day: above zero, `totalDistance` is a partial sum. */
|
||||
unroutedLegs?: number
|
||||
}
|
||||
|
||||
/** Neighbouring legs of one run that resolve to the same mode travel as one request,
|
||||
@@ -44,6 +52,8 @@ interface Chunk { points: DayRoutePoint[]; mode: string }
|
||||
export interface TripRoutePlanDay { day: Day; runs: Chunk[][] }
|
||||
|
||||
type Answer = { coordinates: [number, number][]; legs: RouteSegment[] } | null
|
||||
/** Every leg's answer so far, indexed like the plan: day, run, chunk. */
|
||||
export type TripRouteAnswers = Answer[][][]
|
||||
|
||||
/** The palette entry a day keeps, whatever else is added to the trip around it. */
|
||||
export const dayRouteColor = (day: Day): { line: string; casing: string } =>
|
||||
@@ -90,10 +100,12 @@ export function assembleTripRoute(plan: TripRoutePlanDay[], routed: Answer[][][]
|
||||
return plan.map(({ day, runs }, d) => {
|
||||
const lines: [number, number][][] = []
|
||||
const segments: RouteSegment[] = []
|
||||
let unroutedLegs = 0
|
||||
runs.forEach((chunks, r) => {
|
||||
const polyline: [number, number][] = []
|
||||
chunks.forEach((chunk, c) => {
|
||||
const answer = routed[d]?.[r]?.[c]
|
||||
if (!answer) unroutedLegs++
|
||||
const coords = answer && answer.coordinates.length >= 2 ? answer.coordinates : straight(chunk.points)
|
||||
for (const point of coords) {
|
||||
// Drop the point shared with the previous chunk so concatenated legs
|
||||
@@ -119,6 +131,7 @@ export function assembleTripRoute(plan: TripRoutePlanDay[], routed: Answer[][][]
|
||||
distance: segments.reduce((sum, s) => sum + s.distance, 0),
|
||||
duration: segments.reduce((sum, s) => sum + s.duration, 0),
|
||||
modes,
|
||||
unroutedLegs,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -133,18 +146,49 @@ export function summariseTripRoute(days: TripOverviewDay[]): TripRouteSummary {
|
||||
focusPoints: lines.flat(),
|
||||
totalDistance: days.reduce((sum, d) => sum + d.distance, 0),
|
||||
totalDuration: days.reduce((sum, d) => sum + d.duration, 0),
|
||||
unroutedLegs: days.reduce((sum, d) => sum + (d.unroutedLegs ?? 0), 0),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the router for every leg of every day, a few at a time.
|
||||
* Gap between two routing requests. The public OSRM hosts TREK ships with state one
|
||||
* request per second; the overview asks for every leg of every day, so without spacing
|
||||
* the first handful answer and the rest come back 429 (the road trip rail learnt this
|
||||
* first and paces itself the same way).
|
||||
*/
|
||||
const REQUEST_SPACING_MS = 1100
|
||||
/** Anything answered faster than this came out of RouteCalculator's cache, not the network. */
|
||||
const CACHE_HIT_MS = 60
|
||||
/** How often a rate-limited leg is tried again, and how long after. */
|
||||
const RETRY_DELAYS_MS = [1500, 4000]
|
||||
|
||||
const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
|
||||
new Promise(resolve => {
|
||||
if (signal?.aborted || ms <= 0) { resolve(); return }
|
||||
const timer = setTimeout(done, ms)
|
||||
function done(): void {
|
||||
clearTimeout(timer)
|
||||
signal?.removeEventListener('abort', done)
|
||||
resolve()
|
||||
}
|
||||
signal?.addEventListener('abort', done, { once: true })
|
||||
})
|
||||
|
||||
/**
|
||||
* Ask the router for every leg of every day, one at a time.
|
||||
*
|
||||
* A fortnight is dozens of legs and the routing host is usually a shared OSRM, so the
|
||||
* pool is deliberately small — the same one the sidebar connectors use. RouteCalculator's
|
||||
* cache is shared with the day route, so a day already drawn on screen costs nothing.
|
||||
* A fortnight is dozens of legs and the routing host is usually a shared OSRM that
|
||||
* refuses a burst, so the legs go out one after another with a pause between them, and
|
||||
* a rate limit is waited out (for as long as the host asks, when it says) and asked
|
||||
* again. Only what actually went to the network is paced: RouteCalculator's cache is
|
||||
* shared with the day route, so a day already drawn on screen costs nothing and waits
|
||||
* for nothing.
|
||||
*
|
||||
* A leg the router refuses keeps its straight line and contributes no distance, exactly
|
||||
* as a failed leg of a day route does. Nothing here throws.
|
||||
* A leg the router still refuses keeps its straight line and contributes no distance,
|
||||
* exactly as a failed leg of a day route does; `assembleTripRoute` counts it so the
|
||||
* caller can say the total is short. A refusal the host meant (these coordinates, this
|
||||
* profile) is not repeated, because the same request earns the same answer. Nothing
|
||||
* here throws.
|
||||
*/
|
||||
export async function routeTripLegs(
|
||||
plan: TripRoutePlanDay[],
|
||||
@@ -161,26 +205,37 @@ export async function routeTripLegs(
|
||||
runs.forEach((chunks, r) => {
|
||||
chunks.forEach((chunk, c) => {
|
||||
tasks.push(async () => {
|
||||
try {
|
||||
const answer = await calculateRouteWithLegs(
|
||||
chunk.points.map(p => ({ lat: p.lat, lng: p.lng })),
|
||||
{ signal, profile: chunk.mode, tripId, dayId: day.id },
|
||||
)
|
||||
routed[d][r][c] = { coordinates: answer.coordinates, legs: answer.legs }
|
||||
onAnswer?.(routed)
|
||||
} catch {
|
||||
// Refused (usually a rate limit) — the straight line stands.
|
||||
const waypoints = chunk.points.map(p => ({ lat: p.lat, lng: p.lng }))
|
||||
for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
|
||||
if (signal?.aborted) return
|
||||
try {
|
||||
const answer = await calculateRouteWithLegs(
|
||||
waypoints,
|
||||
{ signal, profile: chunk.mode, tripId, dayId: day.id },
|
||||
)
|
||||
routed[d][r][c] = { coordinates: answer.coordinates, legs: answer.legs }
|
||||
onAnswer?.(routed)
|
||||
return
|
||||
} catch (err) {
|
||||
if (signal?.aborted) return
|
||||
const rateLimit = err instanceof RoutingRefusedError && err.isRateLimit ? err : null
|
||||
if (!rateLimit || attempt === RETRY_DELAYS_MS.length) return
|
||||
// When the host says how long to wait, waiting less is just a second refusal.
|
||||
await sleep(Math.max(RETRY_DELAYS_MS[attempt], rateLimit.retryAfterMs ?? 0), signal)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
while (next < tasks.length && !signal?.aborted) await tasks[next++]()
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
if (signal?.aborted) break
|
||||
const startedAt = performance.now()
|
||||
await tasks[i]()
|
||||
const wasNetwork = performance.now() - startedAt > CACHE_HIT_MS
|
||||
if (wasNetwork && i < tasks.length - 1) await sleep(REQUEST_SPACING_MS, signal)
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(6, tasks.length) }, worker))
|
||||
return routed
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { dayColor } from '../Roadtrip/dayColors'
|
||||
import { useTripRouteOverview } from './useTripRouteOverview'
|
||||
@@ -10,7 +10,9 @@ vi.mock('./RouteCalculator', async (importActual) => {
|
||||
return { ...actual, calculateRouteWithLegs: vi.fn() }
|
||||
})
|
||||
|
||||
const { calculateRouteWithLegs } = await import('./RouteCalculator')
|
||||
const { calculateRouteWithLegs, RoutingRefusedError } = await import('./RouteCalculator')
|
||||
|
||||
type RouteAnswer = Awaited<ReturnType<typeof calculateRouteWithLegs>>
|
||||
|
||||
const leg = (distance: number, duration: number): RouteSegment => ({
|
||||
mid: [0, 0], from: [0, 0], to: [0, 0],
|
||||
@@ -136,4 +138,76 @@ describe('useTripRouteOverview', () => {
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
expect(vi.mocked(calculateRouteWithLegs).mock.calls.length).toBe(calls)
|
||||
})
|
||||
|
||||
it('FE-MAP-TRO-009: a leg the router refused outright is counted, so the total is not taken for complete', async () => {
|
||||
// A 400 objects to these coordinates; the leg stays a straight line with no distance.
|
||||
vi.mocked(calculateRouteWithLegs).mockRejectedValueOnce(new RoutingRefusedError(400, null))
|
||||
const { result } = render()
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false), { timeout: 3000 })
|
||||
expect(result.current.days.map(d => d.unroutedLegs)).toEqual([1, 0])
|
||||
expect(result.current.unroutedLegs).toBe(1)
|
||||
expect(result.current.totalDistance).toBe(12000)
|
||||
})
|
||||
|
||||
it('FE-MAP-TRO-010: each day is drawn as soon as its road answers, not when the round is over', async () => {
|
||||
// The legs go to the router one at a time with a pause between them, so a cold trip
|
||||
// takes a second per leg; roads filling in one by one is what makes that read as
|
||||
// progress rather than as a hang.
|
||||
const answer: RouteAnswer = {
|
||||
coordinates: [[48.86, 2.35], [48.87, 2.355], [48.88, 2.36]],
|
||||
distance: 12000, duration: 900,
|
||||
legs: [leg(12000, 900)],
|
||||
}
|
||||
const answers: Array<(value: RouteAnswer) => void> = []
|
||||
vi.mocked(calculateRouteWithLegs).mockImplementation(
|
||||
() => new Promise<RouteAnswer>(resolve => { answers.push(resolve) }),
|
||||
)
|
||||
const { result } = render()
|
||||
|
||||
// Only the first leg has been asked for.
|
||||
expect(answers).toHaveLength(1)
|
||||
await act(async () => { answers[0](answer) })
|
||||
|
||||
// Its day is on the map while the second is still waiting.
|
||||
expect(result.current.loading).toBe(true)
|
||||
expect(result.current.days[0].distance).toBe(12000)
|
||||
expect(result.current.days[1].distance).toBe(0)
|
||||
|
||||
await waitFor(() => expect(answers).toHaveLength(2), { timeout: 3000 })
|
||||
await act(async () => { answers[1](answer) })
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
expect(result.current.totalDistance).toBe(24000)
|
||||
})
|
||||
|
||||
it('FE-MAP-TRO-011: keeps the frame it set on the straight lines until the round is over', async () => {
|
||||
// A fresh `focusPoints` array is what tells the map to fit the camera. One per
|
||||
// answering leg would take the map back from wherever the reader has panned to, so
|
||||
// the frame changes exactly twice: on the straight lines, and on the finished roads.
|
||||
const answer: RouteAnswer = {
|
||||
coordinates: [[48.86, 2.35], [48.87, 2.355], [48.88, 2.36]],
|
||||
distance: 12000, duration: 900,
|
||||
legs: [leg(12000, 900)],
|
||||
}
|
||||
const answers: Array<(value: RouteAnswer) => void> = []
|
||||
vi.mocked(calculateRouteWithLegs).mockImplementation(
|
||||
() => new Promise<RouteAnswer>(resolve => { answers.push(resolve) }),
|
||||
)
|
||||
const { result } = render()
|
||||
const frame = result.current.focusPoints
|
||||
expect(frame.length).toBeGreaterThan(0)
|
||||
|
||||
await act(async () => { answers[0](answer) })
|
||||
// The road is drawn, the camera stays put.
|
||||
expect(result.current.days[0].distance).toBe(12000)
|
||||
expect(result.current.focusPoints).toBe(frame)
|
||||
|
||||
await waitFor(() => expect(answers).toHaveLength(2), { timeout: 3000 })
|
||||
await act(async () => { answers[1](answer) })
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
// The finished result frames the roads themselves, which have more points than the
|
||||
// straight lines had.
|
||||
expect(result.current.focusPoints).not.toBe(frame)
|
||||
expect(result.current.focusPoints.length).toBeGreaterThan(frame.length)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { type RouteProfileKey } from './RouteCalculator'
|
||||
import {
|
||||
assembleTripRoute, emptyAnswers, planTripRoute, routeTripLegs, summariseTripRoute,
|
||||
type TripRouteSummary,
|
||||
type TripRouteAnswers, type TripRouteSummary,
|
||||
} from './tripRouteGeometry'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import type { Accommodation, AssignmentsMap, Day, Reservation } from '../../types'
|
||||
@@ -66,12 +66,25 @@ export function useTripRouteOverview(
|
||||
|
||||
// Straight lines first so the shape of the trip is on screen immediately, then the
|
||||
// real roads replace them — the same two-step the single-day route draws with.
|
||||
setResult({ ...summariseTripRoute(assembleTripRoute(plan, emptyAnswers(plan))), loading: true })
|
||||
const first = summariseTripRoute(assembleTripRoute(plan, emptyAnswers(plan)))
|
||||
setResult({ ...first, loading: true })
|
||||
|
||||
routeTripLegs(plan, { tripId, signal: controller.signal }).then(routed => {
|
||||
// Published leg by leg: the legs go to the router one at a time with a pause between
|
||||
// them, so a cold trip takes a second per leg, and roads that fill in as they answer
|
||||
// read as progress where straight lines that all flip at once read as a hang.
|
||||
//
|
||||
// The frame is the exception. A fresh `focusPoints` array is what tells the map to
|
||||
// fit the camera, and a fit every second would take the map back from wherever the
|
||||
// reader has panned to. The frame set on the straight lines therefore holds until
|
||||
// the round is over, and only the finished result brings a new one, exactly the two
|
||||
// fits the overview made when every answer landed at once.
|
||||
const publish = (routed: TripRouteAnswers, loading: boolean): void => {
|
||||
if (controller.signal.aborted) return
|
||||
setResult({ ...summariseTripRoute(assembleTripRoute(plan, routed)), loading: false })
|
||||
})
|
||||
const next = summariseTripRoute(assembleTripRoute(plan, routed))
|
||||
setResult({ ...next, focusPoints: loading ? first.focusPoints : next.focusPoints, loading })
|
||||
}
|
||||
routeTripLegs(plan, { tripId, signal: controller.signal, onAnswer: routed => publish(routed, true) })
|
||||
.then(routed => publish(routed, false))
|
||||
|
||||
return () => controller.abort()
|
||||
// planKey is derived from the same inputs as plan, so keying on the string is
|
||||
|
||||
Reference in New Issue
Block a user