From ca14954636e0c9a9776bddff7fe674b913ddc543 Mon Sep 17 00:00:00 2001 From: Byrd-IT <189950726+Byrd-IT@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:27:32 -0600 Subject: [PATCH 01/18] fix(recent-imagery): take the short arc when a box is dragged across the dateline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A drag across ±180° was turned into a min/max box about 360° wide and refused as "Box is 38,332 km wide", and validateBox() refused any west > east box. A drag whose corners are more than 180° apart is now the short box (west > east), and the layer handles it end to end: - model: lonSpanDeg() and nonCrossingBoxes(); validateBox, boxSideKm, boxCentre, boxFromPin and coverageFor read a west > east box as the short arc. - catalog: CMR reads a west > east bounding_box as the short box, so the box is sent as it is. - rendering: the slot drapes one imagery layer per side of ±180°. - Worldview Snapshots rejects a west > east BBOX, so snapshot URLs, EXPORT and get_recent_imagery refuse a dateline box and request nothing; thumbnail and Data-Present probes use the box's wider side. --- docs/CURRENT-STATE.md | 6 +- src/layers/recentImagery/catalog.test.mjs | 20 +++- src/layers/recentImagery/index.test.mjs | 15 +++ src/layers/recentImagery/model.js | 106 +++++++++++++---- src/layers/recentImagery/model.test.mjs | 125 ++++++++++++++++++-- src/layers/recentImagery/rendering.js | 63 +++++++--- src/layers/recentImagery/rendering.test.mjs | 60 ++++++++++ src/layers/recentImagery/source.js | 19 ++- src/layers/recentImagery/source.test.mjs | 37 ++++++ src/tools/queries/imagery.js | 12 +- src/tools/queries/imagery.test.mjs | 23 +++- src/ui/imageryBoxTool.js | 17 ++- src/ui/imageryBoxTool.test.mjs | 29 +++++ src/ui/recentImagery.js | 9 +- src/ui/recentImagery.test.mjs | 20 ++++ src/ui/recentImageryNotice.test.mjs | 12 +- 16 files changed, 503 insertions(+), 70 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 9a530406c7..cf1141a940 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7276,10 +7276,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool, pins and share links already supply complete boxes. - The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. -- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. -- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, a box across the dateline sent as one bounding box with west > east, which CMR reads as the short box, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT and `get_recent_imagery` refuse a dateline box (`Select one side of the dateline`) without requesting one, and its thumbnails and Data-Present probes use the box's wider side. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. -- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Rendering.** `rendering.js` owns at most two slots (a dateline box drapes two GIBS layers in its slot, one each side of ±180) on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. - **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once. - **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). diff --git a/src/layers/recentImagery/catalog.test.mjs b/src/layers/recentImagery/catalog.test.mjs index 462e262162..4866384829 100644 --- a/src/layers/recentImagery/catalog.test.mjs +++ b/src/layers/recentImagery/catalog.test.mjs @@ -239,10 +239,10 @@ test('an invalid box or clock is refused before any request', async () => { }; await assert.rejects( searchHls({ - box: { west: 179, south: 0, east: -179, north: 1 }, + box: { west: -181, south: 0, east: -179, north: 1 }, fetchImpl, }), - /dateline/, + /±180/, ); await assert.rejects( searchHls({ box: BOX, now: 'never', fetchImpl }), @@ -251,6 +251,22 @@ test('an invalid box or clock is refused before any request', async () => { assert.equal(called, false); }); +test('a dateline box goes to CMR as it is: CMR reads west > east as the short box', async () => { + const calls = []; + const result = await searchHls({ + box: { west: 179, south: 0, east: -179, north: 1 }, + days: 2, + now: '2026-09-21T00:00:00Z', + fetchImpl: async (url) => { + calls.push(url); + return response({ json: { hits: 1, items: [ummItem({})] } }); + }, + }); + assert.equal(calls.length, 2, 'one search per product'); + assert.ok(calls.every((url) => url.includes('bounding_box=179,0,-179,1'))); + assert.ok(result.candidates.some((candidate) => candidate.product === 'S30')); +}); + test('CMR pages follow the CMR-Search-After cursor up to 2,000 records and truncation stays honest', async () => { const items = (count) => Array.from({ length: count }, (_, i) => ummItem({ conceptId: `G-${i}` })); diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 90dbf3a528..913d5a1a6a 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -1395,3 +1395,18 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy assert.equal(f.snap().searching, false); assert.equal(f.snap().notice, 'Search cancelled'); }); + +test('a box dragged across the dateline is searched, listed and draped as one box', async () => { + const f = fixture(); + const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 }; + f.layer.enable(); + assert.equal(f.layer.setBox(box), true); + assert.equal(f.snap().boxError, null); + assert.deepEqual(f.catalog.searches.at(-1).request.box, box); + f.catalog.resolveLast(); + await settle(); + assert.equal(f.snap().candidates.length, 4); + assert.equal(f.snap().preview.key, S18); + assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped'); + assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°'); +}); diff --git a/src/layers/recentImagery/model.js b/src/layers/recentImagery/model.js index 3fbcf11239..2f1add85b2 100644 --- a/src/layers/recentImagery/model.js +++ b/src/layers/recentImagery/model.js @@ -76,8 +76,8 @@ const pad2 = (value) => String(value).padStart(2, '0'); /** * Coerce a box to `{ west, south, east, north }` with south ≤ north. West and - * east are not swapped: west > east crosses the dateline and `validateBox` - * rejects it. Null when any edge is nonfinite. + * east are not swapped: west > east is the short arc across the dateline. + * Null when any edge is nonfinite. */ /** A box edge as a number, or null when it is missing, blank or not numeric. */ function edgeNumber(value) { @@ -105,8 +105,39 @@ function normalizeBox(box) { } /** - * Side lengths of a box in km: the box's own longitude span (never the - * shorter way round the globe) at its mid-latitude, and its latitude span. + * Degrees of longitude from `west` to `east`. A west > east box is the short + * arc across the antimeridian. A west <= east box is unchanged, even when + * that span is the long way round. + * @param {number} west Degrees. + * @param {number} east Degrees. + * @returns {number} + */ +export function lonSpanDeg(west, east) { + return east >= west ? east - west : east + 360 - west; +} + +/** + * One or two boxes with west <= east that cover the same area. A dateline + * box is split at ±180 so each side is a plain rectangle for a draped layer + * or a Worldview request. An invalid box is []. + * @param {object} box Degrees box. + * @returns {Array} + */ +export function nonCrossingBoxes(box) { + const normalized = normalizeBox(box); + if (!normalized) return []; + const { west, south, east, north } = normalized; + if (!(west > east)) return [normalized]; + const parts = []; + if (west < 180) parts.push({ west, south, east: 180, north }); + if (east > -180) parts.push({ west: -180, south, east, north }); + return parts; +} + +/** + * Side lengths of a box in km: the longitude span at its mid-latitude (the + * short arc when the box crosses the dateline; a west <= east box is not + * shortened), and its latitude span. * @param {object} box Degrees box. * @returns {{ width: number, height: number }} */ @@ -116,7 +147,7 @@ export function boxSideKm(box) { const midLat = (normalized.south + normalized.north) / 2; return { width: - (normalized.east - normalized.west) * + lonSpanDeg(normalized.west, normalized.east) * KM_PER_DEG_LAT * Math.cos(toRadians(midLat)), height: (normalized.north - normalized.south) * KM_PER_DEG_LAT, @@ -126,9 +157,11 @@ export function boxSideKm(box) { const refuse = (reason, message) => ({ ok: false, reason, message }); /** - * Validate a selection box for the catalog and the tile providers. + * Validate a selection box for the catalog and the tile providers. A box + * with west > east is the short arc across the dateline and is accepted + * when that arc is under the size cap. * @param {object} box Degrees box. - * @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }} + * @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }} */ export function validateBox(box) { const normalized = normalizeBox(box); @@ -136,8 +169,6 @@ export function validateBox(box) { const { west, south, east, north } = normalized; if (Math.abs(west) > 180 || Math.abs(east) > 180) return refuse('invalid', msg('Longitudes must be within ±180°')); - if (west > east) - return refuse('dateline', msg('Select one side of the dateline')); if ( Math.abs(south) > MERCATOR_LAT_LIMIT || Math.abs(north) > MERCATOR_LAT_LIMIT @@ -146,7 +177,7 @@ export function validateBox(box) { 'polar', `Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`, ); - if (east === west || north === south) + if (lonSpanDeg(west, east) === 0 || north === south) return refuse('degenerate', msg('Box must enclose an area')); const { width, height } = boxSideKm(normalized); if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM) @@ -183,22 +214,28 @@ export function fitViewHeightM({ width, height, fovy } = {}) { } /** - * The centre of a box that does not cross the dateline, in degrees. + * The centre of a box, in degrees. A dateline box (west > east) is centred + * on the short arc, not the arithmetic mean, which would be the other side + * of the globe. * @param {object} box Degrees box. * @returns {{ lon: number, lat: number } | null} */ export function boxCentre(box) { const normalized = normalizeBox(box); if (!normalized) return null; + let lon = normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2; + if (lon > 180) lon -= 360; return { - lon: (normalized.west + normalized.east) / 2, + lon, lat: (normalized.south + normalized.north) / 2, }; } /** * A square box centred on a pin, `sideKm` on the ground (the east–west extent - * widens by 1/cos(lat)); null when the result would not validate. + * widens by 1/cos(lat)); null when the result would not validate. A pin whose + * box passes ±180 gets the short-arc box (west > east), the same convention + * as a dragged dateline box, with edges wrapped into ±180. * @param {number} lon Degrees. * @param {number} lat Degrees. * @param {number} [sideKm] @@ -207,16 +244,21 @@ export function boxCentre(box) { export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) { if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0) return null; + if (Math.abs(lon) > 180) return null; const cosLat = Math.cos(toRadians(lat)); if (cosLat <= 0) return null; const halfLat = sideKm / 2 / KM_PER_DEG_LAT; const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat); + // A half-width of 90° or more is not a short arc; refuse rather than wrap. + if (halfLon >= 90) return null; + const wrapLon = (value) => + value > 180 ? value - 360 : value < -180 ? value + 360 : value; const clampLat = (value) => Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value)); const result = validateBox({ - west: lon - halfLon, + west: wrapLon(lon - halfLon), south: clampLat(lat - halfLat), - east: lon + halfLon, + east: wrapLon(lon + halfLon), north: clampLat(lat + halfLat), }); return result.ok ? result.box : null; @@ -444,15 +486,33 @@ export function coverageFor(candidate, box) { .filter((ring) => Array.isArray(ring) && ring.length >= 3); if (!normalized || !footprints.length) return 'unknown'; const { west, south, east, north } = normalized; + const centre = boxCentre(normalized); + // A dateline box is one continuous range starting at its west edge. A + // longitude on the east side (at or past ±180) shifts by 360. One just + // outside the west corner stays put: shifting every value below west would + // send that corner the long way round and miss a footprint that covers it. + const crossing = west > east; + const project = (lon) => { + if (!crossing) return lon; + if (lon >= west) return lon; + if (lon <= east) return lon + 360; + return west - lon <= lon - east ? lon : lon + 360; + }; const samples = [ - [west, south], - [east, south], - [east, north], - [west, north], - [(west + east) / 2, (south + north) / 2], + [project(west), south], + [project(east), south], + [project(east), north], + [project(west), north], + [project(centre.lon), centre.lat], ]; return samples.every(([lon, lat]) => - footprints.some((ring) => pointInPolygon(lon, lat, ring)), + footprints.some((ring) => + pointInPolygon( + lon, + lat, + crossing ? ring.map(([x, y]) => [project(x), y]) : ring, + ), + ), ) ? 'full' : 'partial'; @@ -601,6 +661,10 @@ export function wvsSnapshotUrl({ const normalized = normalizeBox(box); if (!spec) throw new TypeError(`Unknown imagery product: ${product}`); if (!normalized) throw new TypeError('A finite box is required'); + // Worldview Snapshots rejects a BBOX whose west is greater than its east + // (HTTP 200, XML "Invalid value for BBOX"). Callers split or refuse. + if (normalized.west > normalized.east) + throw new TypeError('A snapshot cannot cross the dateline'); const bbox = [ normalized.south, normalized.west, diff --git a/src/layers/recentImagery/model.test.mjs b/src/layers/recentImagery/model.test.mjs index 7de9e0e7cb..42c1efdc0c 100644 --- a/src/layers/recentImagery/model.test.mjs +++ b/src/layers/recentImagery/model.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import { boxFromPin, + lonSpanDeg, + nonCrossingBoxes, boxFromRectangle, boxSideKm, coverageFor, @@ -51,11 +53,20 @@ function hls(product, day, clouds, extra = {}) { return { ...groupGranulesByDay(granules)[0], ...extra }; } -test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => { +test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => { const reason = (box) => validateBox(box).reason; + const dateline = validateBox({ west: 179, south: 0, east: -179, north: 1 }); + assert.equal(dateline.ok, true); + assert.equal(dateline.box.west, 179); + assert.equal(dateline.box.east, -179); assert.equal( - reason({ west: 179, south: 0, east: -179, north: 1 }), - 'dateline', + reason({ west: 170, south: 0, east: -170, north: 1 }), + 'too-large', + 'a 20° dateline arc is still over the 1,000 km cap', + ); + assert.equal( + reason({ west: 180, south: 0, east: -180, north: 1 }), + 'degenerate', ); assert.equal( reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }), @@ -70,10 +81,6 @@ test('validateBox refuses dateline, polar, degenerate, invalid and oversized box validateBox({ west: 0, south: 84, east: 0.5, north: 85.05111 }).message, 'Imagery stops at ±85.05° latitude', ); - assert.equal( - validateBox({ west: 179, south: 0, east: -179, north: 1 }).message, - 'Select one side of the dateline', - ); assert.equal( validateBox({ west: 0, south: 84.9, east: 0.05, north: 85 }).ok, true, @@ -137,10 +144,14 @@ test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400 lon: 10, lat: 5, }); + assert.deepEqual(boxCentre({ west: 179, south: 0, east: -179, north: 2 }), { + lon: 180, + lat: 1, + }); assert.equal(boxCentre(null), null); }); -test('box width is the longitude span at the mid-latitude, never the shortest arc', () => { +test('box width is the longitude span at the mid-latitude; a dateline box uses the short arc', () => { const equator = boxSideKm({ west: 0, south: -0.5, east: 1, north: 0.5 }); assert.ok(Math.abs(equator.width - 111.32) < 1e-6); assert.ok(Math.abs(equator.height - 111.32) < 1e-6); @@ -149,6 +160,13 @@ test('box width is the longitude span at the mid-latitude, never the shortest ar const nearlyGlobal = { west: -179.9, south: 30, east: 179.9, north: 30.1 }; assert.ok(boxSideKm(nearlyGlobal).width > 30000); assert.equal(validateBox(nearlyGlobal).reason, 'too-large'); + const crossing = boxSideKm({ + west: 179, + south: -0.5, + east: -179, + north: 0.5, + }); + assert.ok(Math.abs(crossing.width - 222.64) < 0.01, String(crossing.width)); }); test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => { @@ -167,7 +185,12 @@ test('boxFromPin builds a 10 km square within 2% at any latitude and refuses wha assert.ok(Math.abs(boxSideKm(boxFromPin(10, 10, 50)).width - 50) < 1); assert.equal(boxFromPin(NaN, 0), null); assert.equal(boxFromPin(0, 0, 5000), null, 'over the cap'); - assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline'); + assert.equal(boxFromPin(181, 0), null, 'longitude out of range'); + assert.equal( + boxFromPin(0, 0, 400000), + null, + 'half-width of 90 degrees or more', + ); assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box'); assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid'); }); @@ -298,6 +321,34 @@ test('coverage samples the box corners and centre against the union of footprint assert.equal(coverageFor(withRings(null), BOX), 'unknown'); }); +test('coverage of a dateline box uses the short arc, not the long way', () => { + const box = { west: 179, south: 0, east: -179, north: 1 }; + const ring = (west, east, south = -0.1, north = 1.1) => [ + [west, south], + [east, south], + [east, north], + [west, north], + ]; + const withRings = (...rings) => ({ + granules: rings.map((footprint) => granule({ footprint })), + }); + assert.equal( + coverageFor(withRings(ring(178.5, -178.5)), box), + 'full', + 'one footprint that crosses ±180', + ); + assert.equal( + coverageFor(withRings(ring(178.9, 180.1), ring(-180.1, -178.9)), box), + 'full', + 'a pair split at ±180', + ); + assert.equal( + coverageFor(withRings(ring(179, 180)), box), + 'partial', + 'one side does not cover the other', + ); +}); + test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => { const candidates = [ hls('S30', '2026-09-20', [10, null]), @@ -429,6 +480,17 @@ test('GIBS templates put y before x; Worldview snapshots take south,west,north,e () => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }), TypeError, ); + assert.throws( + () => + wvsSnapshotUrl({ + product: 'S30', + day: '2026-09-18', + box: { west: 179, south: 0, east: -179, north: 1 }, + width: 64, + height: 64, + }), + /snapshot cannot cross the dateline/, + ); }); test('thumbnails load the focused card, then the visible cards outward, then the margins', () => { @@ -437,3 +499,48 @@ test('thumbnails load the focused card, then the visible cards outward, then the assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]); assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []); }); + +test('boxFromPin returns the short-arc box for a pin near the dateline', () => { + const near = (a, b) => Math.abs(a - b) < 1e-6; + const half = 5 / 111.32; // 5 km in degrees at the equator, about 0.04492 + const spanOk = (box) => { + const { width, height } = boxSideKm(box); + assert.ok(Math.abs(width - 10) < 0.2, `width ${width}`); + assert.ok(Math.abs(height - 10) < 0.2, `height ${height}`); + assert.ok(lonSpanDeg(box.west, box.east) < 1, 'never a ~360 degree span'); + }; + // 179.9 and -179.9 are 0.1 degrees from the line: a 10 km box stays on one side. + for (const lon of [179.9, -179.9]) { + const box = boxFromPin(lon, 0); + spanOk(box); + assert.ok(box.west < box.east, `no wrap needed at ${lon}`); + assert.ok(near((box.west + box.east) / 2, lon)); + } + // A pin on the line, or close enough that the box passes it, wraps. + for (const lon of [180, -180, 179.99, -179.99]) { + const box = boxFromPin(lon, 0); + spanOk(box); + assert.ok(box.west > box.east, `crossing at ${lon}`); + assert.ok(box.west <= 180 && box.east >= -180, 'edges stay within +-180'); + assert.ok( + near( + box.west, + (lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half, + ), + ); + assert.equal(nonCrossingBoxes(box).length, 2, 'splits for tiling and CMR'); + assert.ok( + Math.abs( + Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon), + ) < 1e-6, + ); + } + // 0 is an ordinary box. + const mid = boxFromPin(0, 0); + spanOk(mid); + assert.ok(mid.west < mid.east && near(mid.west, -half)); + // Off the equator the east-west extent widens but stays a short arc. + const high = boxFromPin(-179.99, 60); + spanOk(high); + assert.ok(high.west > high.east); +}); diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index b241d0f52b..96b2bc1c1d 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -1,13 +1,16 @@ /** - * Draped-imagery renderer for the Recent Imagery layer: at most two GIBS - * imagery layers (slot `a`, left of a swipe; slot `b`, right) on whichever - * host the map stack offers. Against the basemap slot `a` splits left and - * slot `b` stays empty. Every layer is removed from the collection that owns it, so a - * host switch or a replaced image never strands one. Tile requests pass a - * small semaphore of our own; Cesium's global request limits stay untouched. + * Draped-imagery renderer for the Recent Imagery layer: at most two slots + * (slot `a`, left of a swipe; slot `b`, right) on whichever host the map + * stack offers. A box that crosses the dateline drapes two imagery layers + * in that slot, one on each side of ±180, each a plain west <= east + * rectangle (see `nonCrossingBoxes`). Against the + * basemap slot `a` splits left and slot `b` stays empty. Every layer is + * removed from the collection that owns it, so a host switch or a replaced + * image never strands one. Tile requests pass a small semaphore of our own; + * Cesium's global request limits stay untouched. */ import * as Cesium from 'cesium'; -import { PRODUCTS, gibsTemplate } from './model.js'; +import { PRODUCTS, gibsTemplate, nonCrossingBoxes } from './model.js'; const SLOT_IDS = ['a', 'b']; const SPLIT_ENUM = { left: 'LEFT', right: 'RIGHT', none: 'NONE' }; @@ -80,7 +83,7 @@ export function createRecentImageryRenderer({ let host = NO_HOST; let destroyed = false; const admission = { limit: maxTileRequests, inFlight: 0 }; - /** @type {Record<'a'|'b', null | { layer: object, collection: object, candidate: object, box: object, alpha: number, split: string }>} */ + /** @type {Record<'a'|'b', null | { layers: Array, collection: object, candidate: object, box: object, alpha: number, split: string }>} */ const owned = { a: null, b: null }; // One timer for both slots: any number of upstream deferrals while it is @@ -124,26 +127,48 @@ export function createRecentImageryRenderer({ const record = owned[slotId]; if (!record) return false; owned[slotId] = null; - try { - record.collection.remove(record.layer, true); - } catch { - /* the collection is already gone */ + for (const layer of record.layers) { + try { + record.collection.remove(layer, true); + } catch { + /* the collection is already gone */ + } } return true; } function applyLook(record) { - record.layer.alpha = record.alpha; - record.layer.splitDirection = + const alpha = record.alpha; + const splitDirection = cesium.SplitDirection?.[SPLIT_ENUM[record.split] || 'NONE'] ?? 0; + for (const layer of record.layers) { + layer.alpha = alpha; + layer.splitDirection = splitDirection; + } } function mount(slotId, { candidate, box, alpha, split }) { - const layer = host.collection.addImageryProvider( - createProvider(candidate, box), - ); + const rectangles = nonCrossingBoxes(box); + const parts = rectangles.length ? rectangles : [box]; + // Build every provider before adding any layer, so a throw on the second + // half of a dateline box cannot leave the first layer untracked. + const providers = parts.map((part) => createProvider(candidate, part)); + const layers = []; + try { + for (const provider of providers) + layers.push(host.collection.addImageryProvider(provider)); + } catch (error) { + for (const layer of layers) { + try { + host.collection.remove(layer, true); + } catch { + /* the collection is already gone */ + } + } + throw error; + } owned[slotId] = { - layer, + layers, collection: host.collection, candidate, box, @@ -248,7 +273,7 @@ export function createRecentImageryRenderer({ return out; }, - /** Number of layers this renderer owns (never above two). */ + /** Number of slots this renderer owns (never above two). A dateline box uses two imagery layers in its slot. */ ownedCount() { return SLOT_IDS.filter((slotId) => owned[slotId]).length; }, diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index c1d38cacc8..636a6cc71c 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -227,3 +227,63 @@ test('replacement imagery uses source-owned tile URLs and credit and tears down assert.equal(globe.layers.length, 0); assert.equal(layer.destroyed, true); }); + +test('a dateline box drapes one layer on each side of ±180 and removes both', () => { + const { renderer, globe } = fixture(); + const box = { west: 179, south: 0, east: -179, north: 1 }; + assert.equal( + renderer.showSlot('a', S30, box, { alpha: 0.4, splitDirection: 'left' }), + true, + ); + assert.equal(renderer.ownedCount(), 1); + assert.equal(globe.layers.length, 2); + assert.deepEqual( + globe.layers.map((item) => item.provider.options.rectangle), + [ + { west: 179, south: 0, east: 180, north: 1 }, + { west: -180, south: 0, east: -179, north: 1 }, + ], + ); + assert.equal(globe.layers[0].alpha, 0.4); + assert.equal(globe.layers[1].alpha, 0.4); + assert.equal(globe.layers[0].splitDirection, -1); + assert.equal(globe.layers[1].splitDirection, -1); + renderer.setAlpha('a', 0.2); + assert.equal(globe.layers[0].alpha, 0.2); + assert.equal(globe.layers[1].alpha, 0.2); + renderer.showSlot('a', S30, box, { alpha: 0.2 }); + assert.equal(globe.layers.length, 2, 'the same box does not remount'); + renderer.hideSlot('a'); + assert.equal(globe.layers.length, 0); +}); + +test('a dateline provider that fails on the second half adds no layer', () => { + let built = 0; + const base = fakeCesium(); + const Provider = base.UrlTemplateImageryProvider; + base.UrlTemplateImageryProvider = class extends Provider { + constructor(options) { + built += 1; + if (built === 2) throw new Error('provider failed'); + super(options); + } + }; + const renderer = createRecentImageryRenderer({ + cesium: base, + requestRender: () => {}, + }); + const globe = fakeCollection(); + renderer.rebind({ collection: globe, kind: 'globe' }); + assert.throws( + () => + renderer.showSlot('a', S30, { + west: 179, + south: 0, + east: -179, + north: 1, + }), + /provider failed/, + ); + assert.equal(globe.layers.length, 0); + assert.equal(renderer.ownedCount(), 0); +}); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 9e6749cb72..2f3c2ae641 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -1,5 +1,20 @@ import { searchHls } from './catalog.js'; -import { gibsTemplate, wvsSnapshotUrl } from './model.js'; +import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js'; + +/** + * Worldview Snapshots rejects a BBOX with west > east, so a dateline box is + * probed on its wider side. That is enough for the Data-Present answer, and + * the thumbnail shows that side. + */ +function requestBox(box) { + if (!(box?.west > box?.east)) return box; + const halves = nonCrossingBoxes(box); + return halves.reduce( + (wider, half) => + half.east - half.west > wider.east - wider.west ? half : wider, + halves[0] ?? box, + ); +} /** * NASA-compatible imagery acquisition; transport and URL builders are replaceable. @@ -22,7 +37,7 @@ export function createRecentImagerySource({ thumbnailUrl({ product: candidate.product, day: candidate.day, - box, + box: requestBox(box), width: size, height: size, }), diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index d3cafc5b0d..72b488828f 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -40,3 +40,40 @@ test('cancelled thumbnail acquisition does not return stale responses or retry', await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' }); assert.equal(calls, 1); }); + +test('a dateline thumbnail is requested for the wider side, never as a crossing BBOX', async () => { + const requested = []; + const source = createRecentImagerySource({ + thumbnailUrl: ({ box }) => { + requested.push(box); + return 'https://imagery.example/thumbnail'; + }, + fetchImpl: async () => new Response('image'), + }); + const candidate = { product: 'S30', day: '2026-10-01' }; + await source.getThumbnail(candidate, { + west: 179.9, + south: 0, + east: -179, + north: 1, + }); + assert.deepEqual(requested.at(-1), { + west: -180, + south: 0, + east: -179, + north: 1, + }); + await source.getThumbnail(candidate, { + west: 179, + south: 0, + east: -179.9, + north: 1, + }); + assert.deepEqual(requested.at(-1), { + west: 179, + south: 0, + east: 180, + north: 1, + }); + assert.ok(requested.every((box) => box.west <= box.east)); +}); diff --git a/src/tools/queries/imagery.js b/src/tools/queries/imagery.js index 310f270569..dbb3743473 100644 --- a/src/tools/queries/imagery.js +++ b/src/tools/queries/imagery.js @@ -31,11 +31,6 @@ export const getRecentImagery = defineTool({ requires: ['imagery'], async run(args, { services, signal }) { const area = await resolveArea(args.area, { services, signal }); - if (area.west > area.east) - throw new ToolError( - 'invalid_arguments', - 'The area must not cross the antimeridian', - ); if ( Math.abs(area.south) > MAX_LATITUDE || Math.abs(area.north) > MAX_LATITUDE @@ -55,6 +50,13 @@ export const getRecentImagery = defineTool({ east: area.east, north: area.north, }; + // Worldview Snapshots rejects a west > east BBOX, so a dateline area can + // never produce the image this tool returns: refuse before searching. + if (box.west > box.east) + throw new ToolError( + 'invalid_arguments', + 'A snapshot cannot cross the dateline', + ); let latest; try { latest = await services.imagery.latest({ box, signal }); diff --git a/src/tools/queries/imagery.test.mjs b/src/tools/queries/imagery.test.mjs index 75ef94312d..77574b7eb1 100644 --- a/src/tools/queries/imagery.test.mjs +++ b/src/tools/queries/imagery.test.mjs @@ -82,8 +82,29 @@ test('overview fallback, empty results and invalid areas are reported', async () ); await assert.rejects( none.call('get_recent_imagery', { area: { bbox: [170, 0, -170, 5] } }), - /antimeridian/, + /too large for imagery/, ); + const crossing = imagery({ + candidate: { + product: 'S30', + day: '2026-10-01', + cloud: { min: 1, max: 2 }, + coverage: 'full', + }, + reason: 'clear', + errors: [], + }); + const wrapped = composeCatalog({ + tools: coreTools, + services: { imagery: crossing }, + }); + await assert.rejects( + wrapped.call('get_recent_imagery', { + area: { bbox: [179, 0, -179, 1] }, + }), + /snapshot cannot cross the dateline/, + ); + assert.equal(crossing.snapshots.length, 0); await assert.rejects( none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }), /±85° latitude/, diff --git a/src/ui/imageryBoxTool.js b/src/ui/imageryBoxTool.js index 5bd58a4144..e510776de3 100644 --- a/src/ui/imageryBoxTool.js +++ b/src/ui/imageryBoxTool.js @@ -23,6 +23,8 @@ export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box'; * @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps * `onEscape` runs before the tool cancels on Escape; returning `true` claims * the key (it is still consumed) and leaves the tool armed. + * A drag whose corners are more than 180 degrees of longitude apart is the + * short box across the dateline, returned with west > east. * @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise } | null} */ export function initImageryBoxTool({ @@ -48,13 +50,20 @@ export function initImageryBoxTool({ let savedDoubleClick = null; let savedCameraInputs = null; - const dragBox = () => - anchor && { - west: Math.min(anchor.lon, corner.lon), + const dragBox = () => { + if (!anchor) return null; + const lo = Math.min(anchor.lon, corner.lon); + const hi = Math.max(anchor.lon, corner.lon); + // Corners more than half the globe apart are the short way round, over + // the dateline: west is the eastern corner and east the western one. + const crosses = hi - lo > 180; + return { + west: crosses ? hi : lo, south: Math.min(anchor.lat, corner.lat), - east: Math.max(anchor.lon, corner.lon), + east: crosses ? lo : hi, north: Math.max(anchor.lat, corner.lat), }; + }; const dataSource = new cesium.CustomDataSource( 'gev-recent-imagery-box-preview', diff --git a/src/ui/imageryBoxTool.test.mjs b/src/ui/imageryBoxTool.test.mjs index e84938ed7d..d8b2664887 100644 --- a/src/ui/imageryBoxTool.test.mjs +++ b/src/ui/imageryBoxTool.test.mjs @@ -152,3 +152,32 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the assert.equal(f.tool.start(), false); assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null); }); + +test('a drag across the dateline is the short box, not a box round the world', async () => { + const pickWorld = (_viewer, nx, ny) => + ny < 0.05 ? null : { lon: nx < 0.5 ? 179.99 : -179.99, lat: ny }; + const f = fixture({ pickWorld }); + f.tool.start(); + f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } }); + f.fire('LEFT_UP', { position: { x: 800, y: 250 } }); + assert.deepEqual(f.cancels, []); + assert.equal(f.boxes.length, 1); + const { west, east } = f.boxes[0]; + assert.ok(west > east, `west ${west} is east of east ${east}`); + assert.ok(Math.abs(east + 360 - west - 0.02) < 1e-9, 'a 0.02 degree span'); + await f.tool.destroy(); +}); + +test('a drag whose short arc is still over the size limit is refused as too large', async () => { + const pickWorld = (_viewer, nx, ny) => ({ + lon: nx < 0.5 ? 100 : -100, + lat: ny, + }); + const f = fixture({ pickWorld }); + f.tool.start(); + f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } }); + f.fire('LEFT_UP', { position: { x: 800, y: 250 } }); + assert.equal(f.boxes.length, 0); + assert.equal(f.cancels.at(-1)[0], 'too-large'); + await f.tool.destroy(); +}); diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.js index 307a3c5180..289c35d4d9 100644 --- a/src/ui/recentImagery.js +++ b/src/ui/recentImagery.js @@ -22,6 +22,7 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue'; import { PRODUCTS, hhmm, + lonSpanDeg, wvsSnapshotUrl, } from '../layers/recentImagery/model.js'; import { displayDay, displayMetres } from '../layers/recentImagery/display.js'; @@ -766,13 +767,19 @@ export function createRecentImageryPanel({ const candidate = exportTarget(slotId); if (destroyed || !candidate || !snapshot.box || exporting.has(slotId)) return false; + // Worldview Snapshots rejects a west > east BBOX: say so, request nothing. + if (snapshot.box.west > snapshot.box.east) { + exportError = t('Select one side of the dateline'); + preserveScroll(paint); + return false; + } exporting.add(slotId); exportError = null; preserveScroll(paint); // The snapshot is plate carrée: keep the box's degree aspect, with the // longer side at the size limit. const size = longerSideKm(snapshot.boxSizeKm) > 25 ? 2048 : 1024; - const spanLon = Math.abs(snapshot.box.east - snapshot.box.west) || 1; + const spanLon = lonSpanDeg(snapshot.box.west, snapshot.box.east) || 1; const spanLat = Math.abs(snapshot.box.north - snapshot.box.south) || 1; const width = Math.max( 1, diff --git a/src/ui/recentImagery.test.mjs b/src/ui/recentImagery.test.mjs index 5ed0b6bbad..1e716d1aff 100644 --- a/src/ui/recentImagery.test.mjs +++ b/src/ui/recentImagery.test.mjs @@ -968,6 +968,26 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX await settle(); assert.equal(await f.readout.exportImage('a'), true); assert.match(f.fetches.at(-1), /WIDTH=1024&HEIGHT=512/); + // A dateline box is drawn on the map, but Worldview rejects a crossing BBOX. + const before = f.fetches.length; + f.layer.setBox({ west: 179, south: 0, east: -179, north: 1 }); + f.catalog.resolveLast(); + await settle(); + assert.notEqual( + f.byId('ri-notice-text').textContent, + 'Select one side of the dateline', + 'the drawn box is not a warning until an export is tried', + ); + assert.equal(await f.readout.exportImage('a'), false); + assert.equal( + f.byId('ri-notice-text').textContent, + 'Select one side of the dateline', + ); + assert.equal( + f.fetches.length, + before, + 'export does not request a crossing BBOX', + ); f.layer.setMode('ab'); assert.deepEqual( [ diff --git a/src/ui/recentImageryNotice.test.mjs b/src/ui/recentImageryNotice.test.mjs index 4fc1e3d0e7..67bcea040e 100644 --- a/src/ui/recentImageryNotice.test.mjs +++ b/src/ui/recentImageryNotice.test.mjs @@ -14,7 +14,7 @@ const REFUSALS = [ 'Point the camera at the ground to use the view', // layers/recentImagery/index.js 'That point cannot anchor a box', // layers/recentImagery/index.js ...[ - { west: 170, south: 10, east: -170, north: 20 }, // dateline + { west: 170, south: 10, east: -170, north: 20 }, // too large (dateline arc) { west: 10, south: 80, east: 20, north: 89 }, // polar { west: 10, south: 10, east: 10, north: 20 }, // degenerate { west: 10, south: 10, east: 200, north: 20 }, // longitude range @@ -37,8 +37,14 @@ const SHOWN_EN = new Map([ test('en: refusals stay English', () => { setLocale('en'); - for (const text of REFUSALS) - assert.equal(localizeNotice(text), SHOWN_EN.get(text) ?? text); + for (const text of REFUSALS) { + const shown = localizeNotice(text); + // Size refusals are rewritten with a non-breaking space before the unit. + const expected = / km wide/.test(text) + ? text.replaceAll(' km', '\u00a0km') + : (SHOWN_EN.get(text) ?? text); + assert.equal(shown, expected); + } assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude')); }); From 9a34d63f1d9595cf414923eb875719e300cbea66 Mon Sep 17 00:00:00 2001 From: Byrd-IT <189950726+Byrd-IT@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:04:40 -0600 Subject: [PATCH 02/18] docs: changelog fragment for the Recent Imagery dateline fix (#1540) --- changelog.d/1540-recent-imagery-dateline.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 changelog.d/1540-recent-imagery-dateline.md diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md new file mode 100644 index 0000000000..c8e8451b1c --- /dev/null +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -0,0 +1,6 @@ +- Recent Imagery takes a box dragged across the dateline. The drag was turned + into a box about 360° wide and refused as too large; it is now the short box + across ±180°, which lists the days for that box and drapes a pinned day on + both sides. Worldview Snapshots cannot draw a box that crosses ±180°, so EXPORT + and the `get_recent_imagery` tool say so instead of requesting one (Byrd-IT, + #1540). From d60f2420f42c766005e2dd68ed885c90acc1e821 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Thu, 5 Nov 2026 00:25:08 -0600 Subject: [PATCH 03/18] fix(recent-imagery): address dateline review (halves availability, voice guard, export, renderer fallback) --- changelog.d/1540-recent-imagery-dateline.md | 7 +- src/layers/recentImagery/rendering.js | 8 +- src/layers/recentImagery/rendering.test.mjs | 10 ++ src/layers/recentImagery/source.js | 66 +++++++++---- src/layers/recentImagery/source.test.mjs | 103 +++++++++++++++++--- src/ui/recentImagery.js | 14 ++- src/ui/recentImagery.test.mjs | 4 + src/voice/imageryActions.js | 20 ++-- src/voice/imageryActions.test.mjs | 31 +++++- 9 files changed, 209 insertions(+), 54 deletions(-) diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md index c8e8451b1c..2ff5c9b39b 100644 --- a/changelog.d/1540-recent-imagery-dateline.md +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -1,6 +1,7 @@ - Recent Imagery takes a box dragged across the dateline. The drag was turned into a box about 360° wide and refused as too large; it is now the short box across ±180°, which lists the days for that box and drapes a pinned day on - both sides. Worldview Snapshots cannot draw a box that crosses ±180°, so EXPORT - and the `get_recent_imagery` tool say so instead of requesting one (Byrd-IT, - #1540). + both sides. Availability probes both sides of ±180° (a day counts as present when either + side has data), voice accepts named areas across the dateline, and EXPORT is + disabled up front with the reason, since Worldview Snapshots cannot draw a + box that crosses ±180° (Byrd-IT, #1540). diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index 96b2bc1c1d..9f151d571b 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -148,8 +148,9 @@ export function createRecentImageryRenderer({ } function mount(slotId, { candidate, box, alpha, split }) { - const rectangles = nonCrossingBoxes(box); - const parts = rectangles.length ? rectangles : [box]; + // [] means "not a box": add no layer rather than drape the raw box. + const parts = nonCrossingBoxes(box); + if (!parts.length) return false; // Build every provider before adding any layer, so a throw on the second // half of a dateline box cannot leave the first layer untracked. const providers = parts.map((part) => createProvider(candidate, part)); @@ -176,6 +177,7 @@ export function createRecentImageryRenderer({ split, }; applyLook(owned[slotId]); + return true; } return { @@ -215,7 +217,7 @@ export function createRecentImageryRenderer({ return true; } removeOwned(slotId); - mount(slotId, { candidate, box, ...look }); + if (!mount(slotId, { candidate, box, ...look })) return false; requestRender('recent-imagery-show'); return true; }, diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index 636a6cc71c..74890c4222 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -287,3 +287,13 @@ test('a dateline provider that fails on the second half adds no layer', () => { assert.equal(globe.layers.length, 0); assert.equal(renderer.ownedCount(), 0); }); + +test('a box that is not a box adds no layer and drapes nothing', () => { + const { renderer, globe, renders } = fixture(); + for (const bad of [{ west: NaN, south: 0, east: 1, north: 1 }, { west: 0 }]) { + assert.equal(renderer.showSlot('a', S30, bad), false); + } + assert.equal(globe.layers.length, 0); + assert.equal(renderer.ownedCount(), 0); + assert.deepEqual(renders, []); +}); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 2f3c2ae641..d82e4dbda0 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -3,17 +3,34 @@ import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js'; /** * Worldview Snapshots rejects a BBOX with west > east, so a dateline box is - * probed on its wider side. That is enough for the Data-Present answer, and - * the thumbnail shows that side. + * probed as its two non-crossing halves, wider first. Granules do not cross + * +/-180, so a day has data when either half does. */ -function requestBox(box) { - if (!(box?.west > box?.east)) return box; +function requestBoxes(box) { + if (!(box?.west > box?.east)) return [box]; const halves = nonCrossingBoxes(box); - return halves.reduce( - (wider, half) => - half.east - half.west > wider.east - wider.west ? half : wider, - halves[0] ?? box, - ); + if (!halves.length) return [box]; + return [...halves].sort((a, b) => b.east - b.west - (a.east - a.west)); +} + +const isPresent = (response) => dataPresent(response) === 'true'; + +const dataPresent = (response) => + response?.ok + ? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase() + : ''; + +/** + * One answer for a crossing box: the first half that has data (the wider side + * wins a tie, so the thumbnail shows it); both confirmed empty is empty; any + * other mix (a failed or unreadable half) is returned as that half's response + * so the day is never called empty on partial evidence. + */ +function combineHalves(responses) { + const present = responses.find(isPresent); + if (present) return present; + const unproven = responses.find((r) => dataPresent(r) !== 'false'); + return unproven ?? responses[0]; } /** @@ -33,18 +50,29 @@ export function createRecentImagerySource({ searchHls: (query) => search({ ...query, fetchImpl }), async getThumbnail(candidate, box, { size = 256, signal } = {}) { signal?.throwIfAborted(); - const response = await fetchImpl( - thumbnailUrl({ - product: candidate.product, - day: candidate.day, - box: requestBox(box), - width: size, - height: size, - }), - { signal }, + const settled = await Promise.allSettled( + requestBoxes(box).map((half) => + fetchImpl( + thumbnailUrl({ + product: candidate.product, + day: candidate.day, + box: half, + width: size, + height: size, + }), + { signal }, + ), + ), ); signal?.throwIfAborted(); - return response; + const responses = settled + .filter((result) => result.status === 'fulfilled') + .map((result) => result.value); + // A half that data proves present settles the day; otherwise a + // rejected half is an error, never an empty day. + if (responses.length < settled.length && !responses.some(isPresent)) + throw settled.find((result) => result.status === 'rejected').reason; + return responses.length > 1 ? combineHalves(responses) : responses[0]; }, getTileTemplate: (product, day) => tileTemplate(product, day), }; diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index 72b488828f..415fb5ea33 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -41,7 +41,7 @@ test('cancelled thumbnail acquisition does not return stale responses or retry', assert.equal(calls, 1); }); -test('a dateline thumbnail is requested for the wider side, never as a crossing BBOX', async () => { +test('a dateline thumbnail is requested as two non-crossing halves, never as a crossing BBOX', async () => { const requested = []; const source = createRecentImagerySource({ thumbnailUrl: ({ box }) => { @@ -57,23 +57,100 @@ test('a dateline thumbnail is requested for the wider side, never as a crossing east: -179, north: 1, }); - assert.deepEqual(requested.at(-1), { - west: -180, - south: 0, - east: -179, - north: 1, - }); + assert.deepEqual(requested, [ + { west: -180, south: 0, east: -179, north: 1 }, + { west: 179.9, south: 0, east: 180, north: 1 }, + ]); + requested.length = 0; await source.getThumbnail(candidate, { west: 179, south: 0, east: -179.9, north: 1, }); - assert.deepEqual(requested.at(-1), { - west: 179, - south: 0, - east: 180, - north: 1, - }); + assert.deepEqual(requested[0], { west: 179, south: 0, east: 180, north: 1 }); + assert.equal(requested.length, 2); assert.ok(requested.every((box) => box.west <= box.east)); }); + +const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 }; +const dated = (present, body = 'image') => + new Response(body, { headers: { 'Data-Present': present } }); +function halvesSource(answers) { + const requested = []; + const source = createRecentImagerySource({ + thumbnailUrl: ({ box }) => `https://imagery.example/${box.west}/${box.east}`, + fetchImpl: async (url) => { + requested.push(url); + const answer = answers[url.split('imagery.example/')[1]]; + if (answer instanceof Error) throw answer; + return answer.clone ? answer : answer(); + }, + }); + return { source, requested }; +} +const candidate = { product: 'S30', day: '2026-10-01' }; + +test('a crossing box probes both halves and is present when only the narrow half has data', async () => { + const { source, requested } = halvesSource({ + '-180/-179': dated('false'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(requested.length, 2); + assert.equal(response.headers.get('Data-Present'), 'true'); + assert.equal(await response.text(), 'narrow'); +}); + +test('a crossing box with data only on the wider half is present and shows the wider side', async () => { + const { source } = halvesSource({ + '-180/-179': dated('true', 'wide'), + '179.9/180': dated('false'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(await response.text(), 'wide'); +}); + +test('a crossing box is empty only when both halves are confirmed empty', async () => { + const { source } = halvesSource({ + '-180/-179': dated('false'), + '179.9/180': dated('false'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(response.headers.get('Data-Present'), 'false'); +}); + +test('a crossing box is not called empty when the other half failed', async () => { + const { source } = halvesSource({ + '-180/-179': dated('false'), + '179.9/180': () => new Response('x', { status: 503 }), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(response.ok, false); +}); + +test('a crossing box with both halves present shows the wider half', async () => { + const { source } = halvesSource({ + '-180/-179': dated('true', 'wide'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(await response.text(), 'wide'); +}); + +test('a rejected half does not hide data on the other half, and never reads as empty', async () => { + const { source } = halvesSource({ + '-180/-179': new Error('network'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(await response.text(), 'narrow'); + const failing = halvesSource({ + '-180/-179': new Error('network'), + '179.9/180': dated('false'), + }); + await assert.rejects( + failing.source.getThumbnail(candidate, NARROW_WEST), + /network/, + ); +}); diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.js index 289c35d4d9..66c2172bfb 100644 --- a/src/ui/recentImagery.js +++ b/src/ui/recentImagery.js @@ -523,6 +523,10 @@ export function createRecentImageryPanel({ function exportsView() { const ab = snapshot.mode === 'ab'; + // Worldview Snapshots rejects a crossing BBOX: say so up front. + const crossing = Boolean( + snapshot.box && snapshot.box.west > snapshot.box.east, + ); return [ { id: 'export', @@ -532,10 +536,12 @@ export function createRecentImageryPanel({ label: ab ? t('EXPORT {slot}', { slot: slotId.toUpperCase() }) : t('EXPORT'), - title: ab - ? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() }) - : t('Download the image as a PNG'), - disabled: !exportTarget(slotId) || exporting.has(slotId), + title: crossing + ? t('Select one side of the dateline') + : ab + ? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() }) + : t('Download the image as a PNG'), + disabled: crossing || !exportTarget(slotId) || exporting.has(slotId), reserved: slotId === 'b' ? !ab : undefined, onClick: () => void exportImage(slotId), })), diff --git a/src/ui/recentImagery.test.mjs b/src/ui/recentImagery.test.mjs index 1e716d1aff..f4a59208b9 100644 --- a/src/ui/recentImagery.test.mjs +++ b/src/ui/recentImagery.test.mjs @@ -978,6 +978,10 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX 'Select one side of the dateline', 'the drawn box is not a warning until an export is tried', ); + const crossingExport = f.byAction('export-a'); + assert.equal(crossingExport.disabled, true, 'EXPORT is off up front'); + assert.equal(crossingExport.title, 'Select one side of the dateline'); + // The exportImage guard stays as a backstop. assert.equal(await f.readout.exportImage('a'), false); assert.equal( f.byId('ri-notice-text').textContent, diff --git a/src/voice/imageryActions.js b/src/voice/imageryActions.js index 50d361f8f6..6c0aa3ff85 100644 --- a/src/voice/imageryActions.js +++ b/src/voice/imageryActions.js @@ -17,7 +17,12 @@ * @module voice/imageryActions */ -import { PRODUCTS, rankLatest } from '../layers/recentImagery/model.js'; +import { + PRODUCTS, + boxCentre, + lonSpanDeg, + rankLatest, +} from '../layers/recentImagery/model.js'; import { displacedLayerResult, watchExplicitLayerOff, @@ -203,19 +208,18 @@ export async function findImagery( `No area "${args.areaId}" on this page — call resolve_area again.`, ); const [west, south, east, north] = record.bbox; - if (west > east) - return fail( - 'DATELINE', - `${record.name} crosses the date line; the imagery box needs one side of it.`, - ); // 30 m pixels over a landmark-sized area show a handful of blobs: a small // area gets the layer's own 10 km box around its centre instead. + // west > east is the short arc across the date line: measure and centre + // it with the layer's own helpers, never (west + east) / 2. const small = (north - south) * 111 < 5 && - (east - west) * 111 * Math.cos((((north + south) / 2) * Math.PI) / 180) < + lonSpanDeg(west, east) * + 111 * + Math.cos((((north + south) / 2) * Math.PI) / 180) < 5; box = small - ? { pin: { lon: (west + east) / 2, lat: (south + north) / 2 } } + ? { pin: boxCentre({ west, south, east, north }) } : { west, south, east, north }; areaName = record.name; } else if (where === 'point') { diff --git a/src/voice/imageryActions.test.mjs b/src/voice/imageryActions.test.mjs index 8c80fb32c8..12a1162714 100644 --- a/src/voice/imageryActions.test.mjs +++ b/src/voice/imageryActions.test.mjs @@ -236,7 +236,7 @@ test('an area handle searches its bounding box; the view and pointer have their assert.equal(unknown.code, 'AREA_UNKNOWN'); }); -test('a mixed antimeridian area gets the deliberate imagery date-line refusal', async () => { +test('a mixed antimeridian area is searched as its short-arc box', async () => { const square = (w, s, e, n) => [ [w, s], [e, s], @@ -251,6 +251,7 @@ test('a mixed antimeridian area gets the deliberate imagery date-line refusal', [178, 1], [178, 0], ]; + const layer = fakeLayer(); const store = createAreaStore(); const area = store.put({ geometry: [[crossing], [square(-176, 0.2, -174, 0.8)]], @@ -258,11 +259,33 @@ test('a mixed antimeridian area gets the deliberate imagery date-line refusal', source: 'osm', }); assert.deepEqual(area.bbox, [178, 0, -174, 1]); - const result = await findImagery(deps(fakeLayer(), { area }).value, { + const result = await findImagery(deps(layer, { area }).value, { areaId: area.areaId, }); - assert.equal(result.ok, false); - assert.equal(result.code, 'DATELINE'); + assert.equal(result.ok, true, 'the guard is lifted'); + assert.deepEqual(layer.calls.find((c) => c[0] === 'setBox')[1], { + west: 178, + south: 0, + east: -174, + north: 1, + }); +}); + +test('a small area across the date line is pinned at its short-arc centre', async () => { + const layer = fakeLayer(); + await findImagery( + deps(layer, { + area: { + areaId: 'd', + name: 'Dateline Islet', + bbox: [179.998, 0, -179.998, 0.01], + }, + }).value, + { areaId: 'd' }, + ); + const [, lon, lat] = layer.calls.find((c) => c[0] === 'boxFromPinAt'); + assert.ok(Math.abs(Math.abs(lon) - 180) < 1e-9, `pin lon ${lon}, not 0`); + assert.equal(lat, 0.005); }); test('a box the layer refuses is refused with its reason, and the layer is turned on first', async () => { From 9924cb15eb02fe85709566cba8c667047645fdd7 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Tue, 10 Nov 2026 12:35:37 -0600 Subject: [PATCH 04/18] fix(recent-imagery): preserve dateline half availability --- changelog.d/1540-recent-imagery-dateline.md | 7 +- .../recentImagery/dateline-halves.test.mjs | 676 ++++++++++++++++++ src/layers/recentImagery/index.js | 4 + src/layers/recentImagery/rendering.js | 32 +- src/layers/recentImagery/source.js | 190 ++++- src/layers/recentImagery/source.test.mjs | 60 +- src/layers/recentImagery/thumbnails.js | 9 +- src/layers/recentImagery/thumbnails.test.mjs | 1 + 8 files changed, 936 insertions(+), 43 deletions(-) create mode 100644 src/layers/recentImagery/dateline-halves.test.mjs diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md index 2ff5c9b39b..11f35f95bc 100644 --- a/changelog.d/1540-recent-imagery-dateline.md +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -2,6 +2,11 @@ into a box about 360° wide and refused as too large; it is now the short box across ±180°, which lists the days for that box and drapes a pinned day on both sides. Availability probes both sides of ±180° (a day counts as present when either - side has data), voice accepts named areas across the dateline, and EXPORT is + side has data, and only the sides the probe proved present are draped — a + side confirmed empty never lands on the map), each side is bounded by its + own deadline and both sides' answers are heard — sides proven present all + drape, a side that stalls only bounds the day for its deadline instead of + being cancelled, and a side whose transport ignores abort is timed out at + the deadline itself, voice accepts named areas across the dateline, and EXPORT is disabled up front with the reason, since Worldview Snapshots cannot draw a box that crosses ±180° (Byrd-IT, #1540). diff --git a/src/layers/recentImagery/dateline-halves.test.mjs b/src/layers/recentImagery/dateline-halves.test.mjs new file mode 100644 index 0000000000..5d987f82a3 --- /dev/null +++ b/src/layers/recentImagery/dateline-halves.test.mjs @@ -0,0 +1,676 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createRecentImagerySource } from './source.js'; +import { createThumbnailLoader } from './thumbnails.js'; +import { createRecentImageryRenderer } from './rendering.js'; +import { createRecentImageryLayer } from './index.js'; +import { nonCrossingBoxes } from './model.js'; + +/** Wait, briefly, for an async chain (search → probe → drape) to land. */ +async function until(condition, tries = 200, gapMs = 5) { + for (let i = 0; i < tries; i += 1) { + if (condition()) return true; + await new Promise((resolve) => setTimeout(resolve, gapMs)); + } + return false; +} +/** + * PR #1540 review, P1 + P2: a dateline box is probed as its two halves, and + * per-half availability must survive the whole walk to the map — + * `getThumbnail` (early settle on the first present half, per-half deadline, + * caller cancellation) → the loader's day state → `showSlot`, which drapes + * only the halves the probe proved present. VIIRS is a JPEG product with no + * alpha, so a draped confirmed-empty half is a black rectangle on the map. + */ + +// Fiji across the antimeridian: east side (-180 … -177) is the wider half. +const FIJI_BOX = { west: 179, south: -18, east: -177, north: -17 }; +const FIJI_DAY = '2026-11-04'; +const FIJI_CANDIDATE = { + key: `VIIRS:${FIJI_DAY}`, + product: 'VIIRS', + day: FIJI_DAY, + granules: [], + cloud: null, + timeRange: null, + availability: 'unknown', + coverage: 'full', +}; +const HALVES = nonCrossingBoxes(FIJI_BOX); // [west(179…180), east(-180…-177)] +const WEST_HALF = HALVES[0]; // narrow, empty +const EAST_HALF = HALVES[1]; // wider, has data +const bbox = (box) => [box.south, box.west, box.north, box.east].join(','); +const halfOf = (url) => + nonCrossingBoxes({ + west: Number(new URL(url).searchParams.get('BBOX').split(',')[1]), + south: Number(new URL(url).searchParams.get('BBOX').split(',')[0]), + east: Number(new URL(url).searchParams.get('BBOX').split(',')[3]), + north: Number(new URL(url).searchParams.get('BBOX').split(',')[2]), + })[0]; +const sameBox = (a, b) => + a.west === b.west && + a.south === b.south && + a.east === b.east && + a.north === b.north; + +function snapshot({ + present, + acquisitionTime = null, + delay = 0, + hangsForever = false, + reject = null, +} = {}) { + /** A Worldview snapshot shaped like fetch's: it honours the caller's signal. */ + return (signal) => + new Promise((resolve, rejectPromise) => { + const stop = (why) => + rejectPromise( + why ?? signal?.reason ?? new DOMException('Aborted', 'AbortError'), + ); + if (reject !== null) { + const timer = setTimeout(() => rejectPromise(reject), delay); + signal?.addEventListener( + 'abort', + () => { + clearTimeout(timer); + stop(signal.reason); + }, + { once: true }, + ); + return; + } + if (signal?.aborted) { + stop(); + return; + } + if (signal) + signal.addEventListener('abort', () => stop(signal.reason), { + once: true, + }); + if (hangsForever) return; // never settles unless aborted + const timer = setTimeout(() => { + resolve({ + ok: true, + headers: { + get: (name) => + name === 'Data-Present' + ? String(present) + : name === 'Acquisition-Time' + ? acquisitionTime + : null, + }, + blob: async () => new Blob([present ? 'viirs' : 'empty']), + }); + }, delay); + if (signal) + signal.addEventListener( + 'abort', + () => { + clearTimeout(timer); + stop(signal.reason); + }, + { once: true }, + ); + }); +} + +function timedFetch(answers) { + const calls = []; + const stopped = new Set(); + const fetchImpl = (url, { signal } = {}) => { + calls.push(String(url)); + const half = halfOf(url); + const side = sameBox(half, EAST_HALF) ? 'east' : 'west'; + signal?.addEventListener('abort', () => stopped.add(side), { once: true }); + return answers[side](signal); + }; + return { calls, fetchImpl, stopped }; +} + +const answer = (options) => snapshot(options); + +const neverSettles = () => new Promise(() => {}); // ignores abort entirely + +// ---- source level ------------------------------------------------------ + +test('a dateline day with a stalled half settles bounded: the present half survives, the stall is bounded by the deadline', async () => { + const fetch = timedFetch({ + east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), + west: answer({ hangsForever: true }), + }); + const source = createRecentImagerySource({ + fetchImpl: fetch.fetchImpl, + halfDeadlineMs: 30, + }); + const started = Date.now(); + const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + const elapsed = Date.now() - started; + + assert.ok( + elapsed >= 25, + `the stalled half was bounded, not dropped (${elapsed} ms)`, + ); + assert.ok(elapsed < 2000, `bounded by the deadline (${elapsed} ms)`); + assert.equal(response.headers.get('Data-Present'), 'true'); + assert.equal( + response.headers.get('Acquisition-Time'), + `${FIJI_DAY}T22:10:00Z`, + ); + assert.equal([...fetch.calls].length, 2, 'both halves were requested'); +}); + +test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => { + const calls = []; + const source = createRecentImagerySource({ + thumbnailUrl: ({ box }) => { + calls.push(box); + return 'https://imagery.example/thumbnail'; + }, + fetchImpl: neverSettles, + halfDeadlineMs: 10, + }); + const started = Date.now(); + await assert.rejects( + source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), + (error) => error?.name === 'TimeoutError', + ); + assert.ok(Date.now() - started < 1000, 'the deadline fired without abort'); + assert.equal(calls.length, 2, 'both halves were requested'); +}); + +test("the caller's cancellation rejects even when a transport ignores AbortSignal", async () => { + const source = createRecentImagerySource({ + fetchImpl: neverSettles, + halfDeadlineMs: 60_000, + }); + const controller = new AbortController(); + const settled = source + .getThumbnail(FIJI_CANDIDATE, FIJI_BOX, { signal: controller.signal }) + .then( + () => 'resolved', + (error) => error, + ); + controller.abort(new DOMException('stopped', 'AbortError')); + const outcome = await settled; + assert.equal(outcome?.name, 'AbortError', 'the day rejected with the stop'); +}); + +test('both present halves are preserved: presentBoxes carries every data half and the blob stays readable', async () => { + const fetch = timedFetch({ + east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T21:00:00Z` }), + west: answer({ present: true, acquisitionTime: `${FIJI_DAY}T20:00:00Z` }), + }); + const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); + const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + + assert.equal(response.presentBoxes.length, 2, 'every present half survives'); + const drapes = response.presentBoxes.map((half) => + [EAST_HALF, WEST_HALF].find((h) => sameBox(h, half)), + ); + assert.deepEqual( + drapes.length, + 2, + 'each present half maps to one probe half', + ); + assert.ok(response.blob, 'the answer stays a readable response'); + const blob = await response.blob(); + assert.ok(blob.size > 0, 'the blob reads after presentBoxes is attached'); +}); + +test('a successful probe leaves no deadline timer behind', async () => { + const timers = new Set(); + let cleared = []; + const fetch = timedFetch({ + east: answer({ present: true }), + west: answer({ present: false }), + }); + const source = createRecentImagerySource({ + fetchImpl: fetch.fetchImpl, + setTimeoutImpl: (fn, ms) => { + const id = timers.size + 1; + timers.add(id); + return id; + }, + clearTimeoutImpl: (id) => { + cleared.push(id); + timers.delete(id); + }, + }); + await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + assert.notEqual(fetch, undefined); + assert.equal(timers.size, 0, 'every live deadline timer was cleared'); + assert.ok(cleared.length > 0, 'clearTimeout ran at least once'); +}); + +test('a hung half is bounded by the per-half deadline: the day errors instead of holding a loader slot forever', async () => { + const fetch = timedFetch({ + east: answer({ hangsForever: true }), + west: answer({ hangsForever: true }), + }); + const source = createRecentImagerySource({ + fetchImpl: fetch.fetchImpl, + halfDeadlineMs: 20, + }); + const started = Date.now(); + await assert.rejects( + source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), + (error) => error?.name === 'TimeoutError', + ); + assert.ok(Date.now() - started < 500, 'the deadline fired promptly'); +}); + +test('per-half availability is carried on the response: one present half, one confirmed empty', async () => { + const fetch = timedFetch({ + east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), + west: answer({ present: false }), + }); + const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); + const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + // P1: which half has data survives past combineHalves. + assert.deepEqual(response.presentBoxes, [EAST_HALF]); + assert.notEqual(response.blob, undefined); +}); + +test('both halves confirmed empty keep the day empty; a single non-crossing half reports its own box', async () => { + const fetch = timedFetch({ + east: answer({ present: false }), + west: answer({ present: false }), + }); + const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); + const empty = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + assert.equal(empty.headers.get('Data-Present'), 'false', 'the day is empty'); + assert.deepEqual(empty.presentBoxes, []); + + const plainBox = nonCrossingBoxes({ + west: -97.8, + south: 30.2, + east: -97.7, + north: 30.3, + })[0]; + const plainSource = createRecentImagerySource({ + fetchImpl: (url, { signal } = {}) => + answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` })( + signal, + ), + }); + const plainResponse = await plainSource.getThumbnail( + FIJI_CANDIDATE, + plainBox, + ); + assert.equal( + plainResponse.presentBoxes.length, + 1, + 'the plain box proves itself', + ); + assert.ok(sameBox(plainResponse.presentBoxes[0], plainBox)); +}); + +test('a half that fails or stalls after the other half proved data does not unseat the day; a failed half never reads as empty', async () => { + const fetch = timedFetch({ + east: answer({ hangsForever: true }), + west: answer({ present: true, acquisitionTime: `${FIJI_DAY}T20:00:00Z` }), + }); + const source = createRecentImagerySource({ + fetchImpl: fetch.fetchImpl, + halfDeadlineMs: 30, + }); + const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + assert.equal(response.headers.get('Data-Present'), 'true'); + assert.deepEqual( + response.presentBoxes, + [EAST_HALF, WEST_HALF], + 'the unproven half is not called empty', + ); + + const failing = timedFetch({ + east: answer({ present: false }), + west: answer({ reject: new Error('snapshot failed'), delay: 5 }), + }); + const strict = createRecentImagerySource({ fetchImpl: failing.fetchImpl }); + await assert.rejects( + strict.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), + /snapshot failed/, + 'a failed half is an error, never an empty day', + ); +}); + +test("the caller's cancellation rejects promptly and touches every half", async () => { + const fetch = timedFetch({ + east: answer({ hangsForever: true }), + west: answer({ hangsForever: true }), + }); + const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); + const controller = new AbortController(); + const settled = source + .getThumbnail(FIJI_CANDIDATE, FIJI_BOX, { signal: controller.signal }) + .then( + () => 'resolved', + (error) => error, + ); + controller.abort(new DOMException('stopped', 'AbortError')); + const outcome = await settled; + assert.equal(outcome?.name, 'AbortError', 'the day rejected with the stop'); + assert.ok( + fetch.stopped.has('east') && fetch.stopped.has('west'), + 'each half was cancelled', + ); +}); + +// ---- loader level (real loader over the real source) ------------------- + +test('the loader proves a dateline day present from one half and hands the present half onward', async () => { + const fetch = timedFetch({ + east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), + west: answer({ present: false }), + }); + const loader = createThumbnailLoader({ + fetchImpl: fetch.fetchImpl, + size: 256, + }); + const notified = new Promise((resolve) => { + const off = loader.subscribe((key) => { + if (key === FIJI_CANDIDATE.key) { + off(); + resolve(); + } + }); + }); + loader.request(FIJI_CANDIDATE, FIJI_BOX); + await notified; + const day = loader.get(FIJI_CANDIDATE.key); + assert.equal(day.status, 'present', 'one half with data proves the day'); + assert.equal( + day.acquisitionTime, + `${FIJI_DAY}T22:10:00Z`, + 'the present half’s sensing time', + ); + assert.ok(day.objectUrl); + assert.deepEqual( + day.availableBoxes, + [EAST_HALF], + 'per-half availability rides along', + ); + loader.destroy(); +}); + +test('a hung half does not strand the loader day at "checking" when the deadline bounds it', async () => { + const fetch = timedFetch({ + east: answer({ hangsForever: true }), + west: answer({ hangsForever: true }), + }); + const loader = createThumbnailLoader({ fetchImpl: fetch.fetchImpl }); + const source = createRecentImagerySource({ + fetchImpl: fetch.fetchImpl, + halfDeadlineMs: 20, + }); + const hungLoader = createThumbnailLoader({ + requestThumbnail: source.getThumbnail, + }); + const notified = new Promise((resolve) => + hungLoader.subscribe(() => resolve()), + ); + hungLoader.request(FIJI_CANDIDATE, FIJI_BOX); + await notified; + assert.equal( + hungLoader.get(FIJI_CANDIDATE.key).status, + 'error', + 'a deadline is an error, not "checking" forever', + ); + hungLoader.destroy(); + loader.destroy(); +}); + +// ---- renderer level ---------------------------------------------------- + +function fakeCesium() { + class Provider { + constructor(options) { + this.options = options; + } + requestImage() { + return new Promise(() => {}); + } + } + return { + UrlTemplateImageryProvider: Provider, + WebMercatorTilingScheme: class {}, + Rectangle: { + fromDegrees: (west, south, east, north) => ({ west, south, east, north }), + }, + SplitDirection: { LEFT: -1, NONE: 0, RIGHT: 1 }, + }; +} + +function fakeCollection() { + const layers = []; + return { + layers, + addImageryProvider(provider) { + const layer = { provider, alpha: 1, splitDirection: 0 }; + layers.push(layer); + return layer; + }, + remove(layer, destroy) { + layers.splice(layers.indexOf(layer), 1); + layer.destroyed = destroy; + }, + }; +} + +const rectangles = (collection) => + collection.layers.map((layer) => layer.provider.options.rectangle); + +test('the renderer drapes only the halves the probe proved present, and rebind keeps that choice', () => { + const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); + const globe = fakeCollection(); + renderer.rebind({ collection: globe, kind: 'globe' }); + + assert.equal( + renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { + availableBoxes: [EAST_HALF], + }), + true, + ); + const draped = rectangles(globe); + assert.equal(draped.length, 1, 'only the data-present half is draped'); + assert.ok(sameBox(draped[0], EAST_HALF)); + for (const rect of draped) + assert.ok(rect.west <= rect.east, 'every draped rectangle is plain'); + + // A dateline day that both halves proved present drapes both halves. + renderer.showSlot('b', FIJI_CANDIDATE, FIJI_BOX, { + availableBoxes: [EAST_HALF, WEST_HALF], + }); + assert.equal( + globe.layers.length, + 3, + 'a day proven on both halves drapes both halves (plus slot a)', + ); + + // A host switch rebuilds on the same evidence. + const globe2 = fakeCollection(); + renderer.rebind({ collection: globe2, kind: 'globe' }); + assert.ok( + sameBox(rectangles(globe2)[0], EAST_HALF), + 'rebind re-mounts the present half', + ); + + // Without availability the whole box is still draped (any proven day, HLS). + renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX); + assert.equal( + globe2.layers.length, + 4, + 'unlimited by evidence, both halves drape (slot b keeps its both-half evidence)', + ); + renderer.destroy(); + assert.equal(globe2.layers.length, 0, 'destroy tears the layers down'); +}); + +test('an empty day with no proven half drapes nothing; a stale half never drapes either', () => { + const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); + const globe = fakeCollection(); + renderer.rebind({ collection: globe, kind: 'globe' }); + assert.equal( + renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { availableBoxes: [] }), + false, + 'no proven half, no drape', + ); + assert.equal(globe.layers.length, 0); + const elsewhere = nonCrossingBoxes({ + west: -97.8, + south: 30.2, + east: -97.7, + north: 30.3, + })[0]; + assert.equal( + renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { + availableBoxes: [elsewhere], + }), + false, + 'proven halves of another box do not drape this one', + ); + assert.equal(globe.layers.length, 0); +}); + +// ---- the whole layer (real source → loader → renderer) ------------------ + +test('a VIIRS dateline day with data on one half drapes only that half through the real layer', async () => { + const fetch = timedFetch({ + east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), + west: answer({ present: false }), + }); + const loader = createThumbnailLoader({ fetchImpl: fetch.fetchImpl }); + const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); + const globe = fakeCollection(); + const catalog = { + searchHls: async () => ({ + candidates: [FIJI_CANDIDATE], + truncated: false, + errors: [], + }), + }; + const layer = createRecentImageryLayer({ + catalog, + renderer, + thumbnails: loader, + host: () => ({ collection: globe, kind: 'globe' }), + now: () => new Date(`${FIJI_DAY}T15:00:00Z`), + }); + layer.init({ camera: {} }); + layer.setSources({ viirs: true }); + layer.enable(); + assert.equal(layer.setBox(FIJI_BOX), true, 'the dateline box validates'); + + // The probe fetched both halves, wider first, and the layer draped the + // winner on its own notify. + await until(() => rectangles(globe).length > 0); + const snapshot = layer.getSnapshot(); + const draped = rectangles(globe); + assert.equal(fetch.calls.length, 2, 'one probe per half'); + const probed = fetch.calls.map((url) => halfOf(url)); + assert.ok(sameBox(probed[0], EAST_HALF), 'the wider half is probed first'); + assert.ok(sameBox(probed[1], WEST_HALF)); + + assert.equal(draped.length, 1, 'only the data-present half hit the map'); + assert.ok(sameBox(draped[0], EAST_HALF)); + + // The day stays present and listed after draping. + assert.equal(loader.get(FIJI_CANDIDATE.key).status, 'present'); + assert.equal(snapshot.candidates[0].thumbnail.status, 'present'); + assert.equal(snapshot.candidates[0].drapable, true); + assert.equal( + snapshot.auto?.key, + FIJI_CANDIDATE.key, + 'START HERE keeps the day', + ); + + layer.destroy(); + loader.destroy(); + assert.equal( + globe.layers.length, + 0, + 'tearing the layer down takes the imagery with it', + ); +}); + +test('a dateline day both halves confirm empty never drapes and leaves the strip when hidden', async () => { + const fetch = timedFetch({ + east: answer({ present: false }), + west: answer({ present: false }), + }); + const loader = createThumbnailLoader({ fetchImpl: fetch.fetchImpl }); + const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); + const globe = fakeCollection(); + const catalog = { + searchHls: async () => ({ + candidates: [FIJI_CANDIDATE], + truncated: false, + errors: [], + }), + }; + const layer = createRecentImageryLayer({ + catalog, + renderer, + thumbnails: loader, + host: () => ({ collection: globe, kind: 'globe' }), + now: () => new Date(`${FIJI_DAY}T15:00:00Z`), + }); + layer.init({ camera: {} }); + layer.setSources({ viirs: true }); + layer.enable(); + layer.setBox(FIJI_BOX); + await new Promise((resolve) => { + const off = loader.subscribe(() => { + off(); + resolve(); + }); + layer.subscribe(() => { + /* the layer is the one that reacts */ + }); + }); + await until(() => loader.get(FIJI_CANDIDATE.key).status === 'empty'); + assert.equal(globe.layers.length, 0, 'a confirmed-empty day never drapes'); + layer.destroy(); + loader.destroy(); +}); + +test('a failed half is not mistaken for confirmed empty when the other is present', async () => { + const fetch = timedFetch({ + east: answer({ present: true }), + west: answer({ reject: new Error('offline') }), + }); + const source = createRecentImagerySource({ + fetchImpl: fetch.fetchImpl, + halfDeadlineMs: 20, + }); + const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + assert.deepEqual( + new Set(response.presentBoxes.map(bbox)), + new Set([bbox(EAST_HALF), bbox(WEST_HALF)]), + ); +}); + +test('frozen responses retain availability', async () => { + const fetch = timedFetch({ + east: (s) => answer({ present: true })(s).then(Object.freeze), + west: answer({ present: false }), + }); + const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); + const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + assert.deepEqual(response.presentBoxes, [EAST_HALF]); + assert.ok((await response.blob()).size); +}); + +test('removes previous drape when evidence changes from unknown to empty', () => { + const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); + const globe = fakeCollection(); + renderer.rebind({ collection: globe, kind: 'globe' }); + renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX); + assert.equal(globe.layers.length, 2); + assert.equal( + renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { availableBoxes: [] }), + false, + ); + assert.equal(globe.layers.length, 0); + renderer.destroy(); +}); diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.js index 5ab8e05ccb..50d7a442c4 100644 --- a/src/layers/recentImagery/index.js +++ b/src/layers/recentImagery/index.js @@ -549,6 +549,10 @@ export function createRecentImageryLayer({ : (slotId === 'a') !== _swapped ? 'left' : 'right', + // Which halves of a dateline box the probe proved present; the + // renderer drapes only those, so a confirmed-empty half never + // lands on the map as black "no data" tiles. + availableBoxes: thumbnails.get(candidate.key)?.availableBoxes ?? null, }); } else { renderer.hideSlot(slotId); diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index 9f151d571b..86a67b84cd 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -29,6 +29,15 @@ function clampAlpha(value) { const boxKey = (box) => [box.west, box.south, box.east, box.north].map(Number).join(','); +/** Comparable per-half availability signature; '' with no evidence. */ +const boxesKey = (list) => + Array.isArray(list) + ? list + .map((box) => boxKey(box)) + .sort() + .join(';') + : 'unknown'; + /** * Gate a provider's `requestImage` through the semaphore. Returning * `undefined` tells Cesium to retry on a later frame, but under @@ -147,13 +156,23 @@ export function createRecentImageryRenderer({ } } - function mount(slotId, { candidate, box, alpha, split }) { + function mount(slotId, { candidate, box, alpha, split, availableBoxes }) { // [] means "not a box": add no layer rather than drape the raw box. const parts = nonCrossingBoxes(box); if (!parts.length) return false; + // A dateline day drapes only the halves its probe proved present (VIIRS + // is a JPEG product; a draped confirmed-empty half is a black rectangle). + // No evidence drapes the whole box, as before. Proven halves that do not + // match this box (a stale entry) leave the slot empty, never draped. + const allowed = Array.isArray(availableBoxes) + ? parts.filter((part) => + availableBoxes.some((half) => half && boxKey(half) === boxKey(part)), + ) + : parts; + if (!allowed.length) return false; // Build every provider before adding any layer, so a throw on the second // half of a dateline box cannot leave the first layer untracked. - const providers = parts.map((part) => createProvider(candidate, part)); + const providers = allowed.map((part) => createProvider(candidate, part)); const layers = []; try { for (const provider of providers) @@ -175,6 +194,7 @@ export function createRecentImageryRenderer({ box, alpha, split, + availableBoxes, }; applyLook(owned[slotId]); return true; @@ -194,7 +214,7 @@ export function createRecentImageryRenderer({ slotId, candidate, box, - { alpha = 1, splitDirection = 'none' } = {}, + { alpha = 1, splitDirection = 'none', availableBoxes = null } = {}, ) { if (destroyed || !candidate?.key || !box) return false; if (!host.collection) { @@ -207,7 +227,8 @@ export function createRecentImageryRenderer({ current && current.collection === host.collection && current.candidate.key === candidate.key && - boxKey(current.box) === boxKey(box) + boxKey(current.box) === boxKey(box) && + boxesKey(current.availableBoxes) === boxesKey(availableBoxes) ) { if (current.alpha !== look.alpha || current.split !== look.split) { Object.assign(current, look); @@ -217,7 +238,8 @@ export function createRecentImageryRenderer({ return true; } removeOwned(slotId); - if (!mount(slotId, { candidate, box, ...look })) return false; + if (!mount(slotId, { candidate, box, ...look, availableBoxes })) + return false; requestRender('recent-imagery-show'); return true; }, diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index d82e4dbda0..45022d8ce7 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -1,6 +1,14 @@ import { searchHls } from './catalog.js'; import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js'; +/** + * A half's answer is only worth so much waiting: past this deadline the half + * is cancelled with its own `TimeoutError` so a day whose wider side answered + * at once is never stranded at "checking" behind a narrow side that never + * sends headers. + */ +const DEFAULT_HALF_DEADLINE_MS = 15_000; + /** * Worldview Snapshots rejects a BBOX with west > east, so a dateline box is * probed as its two non-crossing halves, wider first. Granules do not cross @@ -21,10 +29,11 @@ const dataPresent = (response) => : ''; /** - * One answer for a crossing box: the first half that has data (the wider side - * wins a tie, so the thumbnail shows it); both confirmed empty is empty; any - * other mix (a failed or unreadable half) is returned as that half's response - * so the day is never called empty on partial evidence. + * One answer for a crossing box across only the halves that actually + * answered: the first half that has data (the wider side wins a tie, so the + * thumbnail shows it); both confirmed empty is empty; any other mix (a + * failed or unreadable half) is returned as that half's response so the day + * is never called empty on partial evidence. */ function combineHalves(responses) { const present = responses.find(isPresent); @@ -33,6 +42,106 @@ function combineHalves(responses) { return unproven ?? responses[0]; } +/** + * One half's snapshot fetch, raced against its own deadline so a half that + * never answers — including a transport that ignores its AbortSignal — is + * bounded and the day settles instead of hanging. The controller is private: + * only a half that has not settled is ever aborted, so a settled response's + * body stays readable afterwards, while the caller's signal still stops + * every pending half at once. No half is settled early on the other's + * answer: both headers are heard, so two present halves both survive. + */ +function probeHalf( + url, + { fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl }, +) { + const controller = new AbortController(); + let settle = null; + let timer = null; + let transportSettled = false; + const finishTimeout = () => { + if (timer !== null) { + clearTimeoutImpl(timer); + timer = null; + } + }; + const stop = (why) => { + const reason = + why ?? + signal?.reason ?? + new DOMException('Thumbnail half stopped', 'AbortError'); + controller.abort(reason); + finishTimeout(); + // The transport's own rejection is the answer when it honours abort; + // for one that does not, the race itself carries the stop to the probe. + if (!transportSettled) settle?.reject(reason); + }; + if (signal?.aborted) stop(); + else + signal?.addEventListener('abort', () => stop(signal.reason), { + once: true, + }); + let promise; + try { + promise = fetchImpl(url, { signal: controller.signal }); + } catch (error) { + finishTimeout(); + throw error; + } + const response = new Promise((resolve, reject) => { + settle = { resolve, reject }; + if (deadlineMs > 0) + timer = setTimeoutImpl( + () => + stop(new DOMException('Thumbnail half timed out', 'TimeoutError')), + deadlineMs, + ); + promise.then( + (value) => { + transportSettled = true; + finishTimeout(); + resolve(value); + }, + (error) => { + transportSettled = true; + finishTimeout(); + reject(error); + }, + ); + }); + // The deadline dies with the fetch's own settle; the caller-abort wiring + // deliberately outlives it, so a stop that arrives while the response body + // is still being read still cancels the half, right up until the caller's + // signal (and this listener with it) is collected. + return { stop, response }; +} + +/** + * The answer to one request: the response, enriched (non-enumerably, so the + * transport's own shape is untouched) with the non-crossing halves the probe + * proved present. An empty evidence list is a confirmed-empty day; no field + * means the caller did not probe per half. + */ +function withPresentBoxes(response, presentBoxes) { + if (!response) return response; + try { + Object.defineProperty(response, 'presentBoxes', { + value: presentBoxes, + enumerable: false, + configurable: true, + }); + return response; + } catch { + // Preserve the loader's response contract even for a frozen Response. + return { + ok: response.ok, + headers: response.headers, + blob: () => response.blob(), + presentBoxes, + }; + } +} + /** * NASA-compatible imagery acquisition; transport and URL builders are replaceable. * Thumbnail responses must expose Data-Present: true for image admission, or @@ -44,35 +153,68 @@ export function createRecentImagerySource({ thumbnailUrl = wvsSnapshotUrl, tileTemplate = gibsTemplate, credit = 'NASA GIBS', + halfDeadlineMs = DEFAULT_HALF_DEADLINE_MS, + setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms), + clearTimeoutImpl = (id) => globalThis.clearTimeout(id), } = {}) { return { credit, searchHls: (query) => search({ ...query, fetchImpl }), async getThumbnail(candidate, box, { size = 256, signal } = {}) { signal?.throwIfAborted(); - const settled = await Promise.allSettled( - requestBoxes(box).map((half) => - fetchImpl( - thumbnailUrl({ - product: candidate.product, - day: candidate.day, - box: half, - width: size, - height: size, - }), - { signal }, - ), + const halves = requestBoxes(box); + const probes = halves.map((half) => ({ + half, + ...probeHalf( + thumbnailUrl({ + product: candidate.product, + day: candidate.day, + box: half, + width: size, + height: size, + }), + { + fetchImpl, + signal, + deadlineMs: halves.length > 1 ? halfDeadlineMs : 0, + setTimeoutImpl, + clearTimeoutImpl, + }, ), + })); + // Bounded header race: every half is raced against its own deadline, + // so a half that never answers — even a transport that ignores its + // AbortSignal — is bounded. Both headers are heard; no half is settled + // early on the other's answer, so two present halves both survive. + const results = await Promise.allSettled( + probes.map((probe) => probe.response), ); signal?.throwIfAborted(); - const responses = settled - .filter((result) => result.status === 'fulfilled') - .map((result) => result.value); - // A half that data proves present settles the day; otherwise a - // rejected half is an error, never an empty day. - if (responses.length < settled.length && !responses.some(isPresent)) - throw settled.find((result) => result.status === 'rejected').reason; - return responses.length > 1 ? combineHalves(responses) : responses[0]; + const fulfilled = []; + results.forEach((result, i) => { + if (result.status === 'fulfilled') + fulfilled.push({ value: result.value, half: probes[i].half }); + }); + const responses = fulfilled.map((entry) => entry.value); + // Retain every half except one that answered confirmed empty. A failed + // probe is not evidence of absence, even when its sibling proves a day. + const proven = fulfilled.filter((entry) => isPresent(entry.value)); + if (proven.length) + return withPresentBoxes( + combineHalves(responses), + probes + .filter( + (probe, i) => + results[i].status === 'rejected' || + dataPresent(results[i].value) !== 'false', + ) + .map((entry) => nonCrossingBoxes(entry.half)[0]), + ); + // A rejected half is an error, never an empty day, unless another half + // proved data on its own. + if (results.length > responses.length) + throw results.find((result) => result.status === 'rejected').reason; + return withPresentBoxes(combineHalves(responses), []); }, getTileTemplate: (product, day) => tileTemplate(product, day), }; diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index 415fb5ea33..570c5e0040 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -4,10 +4,16 @@ import { createRecentImagerySource } from './source.js'; test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => { const controller = new AbortController(); - const query = { box: { west: 0, east: 1, south: 0, north: 1 }, signal: controller.signal }; + const query = { + box: { west: 0, east: 1, south: 0, north: 1 }, + signal: controller.signal, + }; const candidate = { product: 'S30', day: '2026-10-01' }; const calls = []; - const fetchImpl = async (...args) => { calls.push(args); return new Response('image'); }; + const fetchImpl = async (...args) => { + calls.push(args); + return new Response('image'); + }; const source = createRecentImagerySource({ fetchImpl, search: async (request) => { @@ -16,16 +22,34 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt assert.equal(request.box, query.box); return [candidate]; }, - thumbnailUrl: ({ product, day, width }) => `https://imagery.example/${product}/${day}/${width}`, - tileTemplate: (product, day) => `https://tiles.example/${product}/${day}/{z}/{x}/{y}`, + thumbnailUrl: ({ product, day, width }) => + `https://imagery.example/${product}/${day}/${width}`, + tileTemplate: (product, day) => + `https://tiles.example/${product}/${day}/{z}/{x}/{y}`, credit: 'Example imagery', }); assert.deepEqual(await source.searchHls(query), [candidate]); - assert.equal(await (await source.getThumbnail(candidate, query.box, { signal: controller.signal })).text(), 'image'); + assert.equal( + await ( + await source.getThumbnail(candidate, query.box, { + signal: controller.signal, + }) + ).text(), + 'image', + ); assert.equal(calls.length, 1); assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256'); - assert.equal(calls[0][1].signal, controller.signal); - assert.equal(source.getTileTemplate(candidate.product, candidate.day), 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}'); + // Each half is bounded by a controller of its own (a deadline can cancel + // one half without the other), but it is chained to the caller's signal. + const halfSignal = calls[0][1].signal; + assert.notEqual(halfSignal, controller.signal); + assert.equal(halfSignal.aborted, false); + controller.abort(); + assert.equal(halfSignal.aborted, true); + assert.equal( + source.getTileTemplate(candidate.product, candidate.day), + 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}', + ); assert.equal(source.credit, 'Example imagery'); }); @@ -34,10 +58,20 @@ test('cancelled thumbnail acquisition does not return stale responses or retry', let calls = 0; const source = createRecentImagerySource({ thumbnailUrl: () => 'https://imagery.example/thumbnail', - fetchImpl: async () => { calls++; controller.abort(); return new Response('image'); }, + fetchImpl: async () => { + calls++; + controller.abort(); + return new Response('image'); + }, }); - await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' }); - await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' }); + await assert.rejects( + source.getThumbnail({}, {}, { signal: controller.signal }), + { name: 'AbortError' }, + ); + await assert.rejects( + source.getThumbnail({}, {}, { signal: controller.signal }), + { name: 'AbortError' }, + ); assert.equal(calls, 1); }); @@ -79,7 +113,8 @@ const dated = (present, body = 'image') => function halvesSource(answers) { const requested = []; const source = createRecentImagerySource({ - thumbnailUrl: ({ box }) => `https://imagery.example/${box.west}/${box.east}`, + thumbnailUrl: ({ box }) => + `https://imagery.example/${box.west}/${box.east}`, fetchImpl: async (url) => { requested.push(url); const answer = answers[url.split('imagery.example/')[1]]; @@ -129,13 +164,14 @@ test('a crossing box is not called empty when the other half failed', async () = assert.equal(response.ok, false); }); -test('a crossing box with both halves present shows the wider half', async () => { +test('a crossing box with both halves present shows the wider half and keeps both presentBoxes', async () => { const { source } = halvesSource({ '-180/-179': dated('true', 'wide'), '179.9/180': dated('true', 'narrow'), }); const response = await source.getThumbnail(candidate, NARROW_WEST); assert.equal(await response.text(), 'wide'); + assert.equal(response.presentBoxes.length, 2, 'every present half survives'); }); test('a rejected half does not hide data on the other half, and never reads as empty', async () => { diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index 4aaec294bf..0b583ba936 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -15,6 +15,7 @@ const EMPTY = Object.freeze({ status: 'unknown', objectUrl: null, acquisitionTime: null, + availableBoxes: null, loading: false, }); @@ -90,6 +91,9 @@ export function createThumbnailLoader({ let status = 'error'; let objectUrl = null; let acquisitionTime = null; + // Which half of a dateline box the probe proved present; null when the + // request was not probed per half. + let availableBoxes = null; let cancelled = false; try { const response = await requestThumbnail(entry.candidate, entry.box, { @@ -102,6 +106,7 @@ export function createThumbnailLoader({ const present = String( response.headers?.get?.('Data-Present') ?? '', ).toLowerCase(); + availableBoxes = response.presentBoxes ?? null; acquisitionTime = response.headers?.get?.('Acquisition-Time') || null; if (present === 'false') { status = 'empty'; @@ -133,6 +138,7 @@ export function createThumbnailLoader({ if (status !== 'error' || entry.status !== 'present') { entry.status = status; entry.acquisitionTime = acquisitionTime; + entry.availableBoxes = availableBoxes; } entry.objectUrl = objectUrl; touch(entry); @@ -237,7 +243,7 @@ export function createThumbnailLoader({ /** * Read a day's state. A read is not a use: it never changes residency. * @param {string} key Candidate key. - * @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }} + * @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array | null, loading: boolean }} */ get(key) { const entry = entries.get(key); @@ -246,6 +252,7 @@ export function createThumbnailLoader({ status: entry.status, objectUrl: entry.objectUrl, acquisitionTime: entry.acquisitionTime, + availableBoxes: entry.availableBoxes ?? null, loading: entry.loading, }; }, diff --git a/src/layers/recentImagery/thumbnails.test.mjs b/src/layers/recentImagery/thumbnails.test.mjs index ada857f9ae..6d521c27e7 100644 --- a/src/layers/recentImagery/thumbnails.test.mjs +++ b/src/layers/recentImagery/thumbnails.test.mjs @@ -68,6 +68,7 @@ test('Data-Present decides the day: present with an object URL and sensing time, status: 'present', objectUrl: 'blob:1', acquisitionTime: '2026-09-18T17:12:00Z', + availableBoxes: [BOX], loading: false, }); assert.equal(loader.get('L30:2026-09-16').status, 'empty'); From eeda6d51d166e6284af9b4410ecaafd05d2705df Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Tue, 10 Nov 2026 12:36:19 -0600 Subject: [PATCH 05/18] fix(recent-imagery): refresh when availability removes drape --- changelog.d/1540-recent-imagery-dateline.md | 2 +- src/layers/recentImagery/index.js | 4 +--- src/layers/recentImagery/rendering.js | 15 ++++++++------- src/layers/recentImagery/source.js | 4 ++-- src/layers/recentImagery/thumbnails.js | 3 +-- 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md index 11f35f95bc..f896c11ace 100644 --- a/changelog.d/1540-recent-imagery-dateline.md +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -2,7 +2,7 @@ into a box about 360° wide and refused as too large; it is now the short box across ±180°, which lists the days for that box and drapes a pinned day on both sides. Availability probes both sides of ±180° (a day counts as present when either - side has data, and only the sides the probe proved present are draped — a + side has data, and sides confirmed empty are not draped — a side confirmed empty never lands on the map), each side is bounded by its own deadline and both sides' answers are heard — sides proven present all drape, a side that stalls only bounds the day for its deadline instead of diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.js index 50d7a442c4..6520d81f85 100644 --- a/src/layers/recentImagery/index.js +++ b/src/layers/recentImagery/index.js @@ -549,9 +549,7 @@ export function createRecentImageryLayer({ : (slotId === 'a') !== _swapped ? 'left' : 'right', - // Which halves of a dateline box the probe proved present; the - // renderer drapes only those, so a confirmed-empty half never - // lands on the map as black "no data" tiles. + // Keep every half except those confirmed empty by the probe. availableBoxes: thumbnails.get(candidate.key)?.availableBoxes ?? null, }); } else { diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index 86a67b84cd..b6c23a0663 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -29,7 +29,7 @@ function clampAlpha(value) { const boxKey = (box) => [box.west, box.south, box.east, box.north].map(Number).join(','); -/** Comparable per-half availability signature; '' with no evidence. */ +/** Comparable per-half availability signature; unknown differs from empty. */ const boxesKey = (list) => Array.isArray(list) ? list @@ -160,10 +160,9 @@ export function createRecentImageryRenderer({ // [] means "not a box": add no layer rather than drape the raw box. const parts = nonCrossingBoxes(box); if (!parts.length) return false; - // A dateline day drapes only the halves its probe proved present (VIIRS - // is a JPEG product; a draped confirmed-empty half is a black rectangle). - // No evidence drapes the whole box, as before. Proven halves that do not - // match this box (a stale entry) leave the slot empty, never draped. + // Skip confirmed-empty halves; a failed probe is not proof of emptiness. + // No evidence drapes the whole box, as before. Evidence for a different + // box leaves the slot empty rather than applying stale availability. const allowed = Array.isArray(availableBoxes) ? parts.filter((part) => availableBoxes.some((half) => half && boxKey(half) === boxKey(part)), @@ -237,9 +236,11 @@ export function createRecentImageryRenderer({ } return true; } - removeOwned(slotId); - if (!mount(slotId, { candidate, box, ...look, availableBoxes })) + const removed = removeOwned(slotId); + if (!mount(slotId, { candidate, box, ...look, availableBoxes })) { + if (removed) requestRender('recent-imagery-hide'); return false; + } requestRender('recent-imagery-show'); return true; }, diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 45022d8ce7..02f4ff2366 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -119,8 +119,8 @@ function probeHalf( /** * The answer to one request: the response, enriched (non-enumerably, so the * transport's own shape is untouched) with the non-crossing halves the probe - * proved present. An empty evidence list is a confirmed-empty day; no field - * means the caller did not probe per half. + * did not confirm empty. An empty evidence list is a confirmed-empty day; + * no field means the caller did not probe per half. */ function withPresentBoxes(response, presentBoxes) { if (!response) return response; diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index 0b583ba936..c727dcf40c 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -91,8 +91,7 @@ export function createThumbnailLoader({ let status = 'error'; let objectUrl = null; let acquisitionTime = null; - // Which half of a dateline box the probe proved present; null when the - // request was not probed per half. + // Halves not confirmed empty; null when no per-half probe is available. let availableBoxes = null; let cancelled = false; try { From 7b76525528c906843b20f397a3cb2739957bdf38 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Tue, 10 Nov 2026 12:48:25 -0600 Subject: [PATCH 06/18] fix(recent-imagery): settle synchronous cancellation --- .../recentImagery/dateline-halves.test.mjs | 22 +++++++++++++++++++ src/layers/recentImagery/source.js | 19 ++++++++++------ 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/src/layers/recentImagery/dateline-halves.test.mjs b/src/layers/recentImagery/dateline-halves.test.mjs index 5d987f82a3..13a1ba8244 100644 --- a/src/layers/recentImagery/dateline-halves.test.mjs +++ b/src/layers/recentImagery/dateline-halves.test.mjs @@ -23,6 +23,28 @@ async function until(condition, tries = 200, gapMs = 5) { * alpha, so a draped confirmed-empty half is a black rectangle on the map. */ +test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => { + const controller = new AbortController(); + const source = createRecentImagerySource({ + thumbnailUrl: () => 'https://example.invalid/', + halfDeadlineMs: 10000, + fetchImpl: () => { + controller.abort(); + return new Promise(() => {}); + }, + }); + const outcome = await Promise.race([ + source + .getThumbnail(FIJI_CANDIDATE, FIJI_BOX, { signal: controller.signal }) + .then( + () => 'resolved', + (error) => error.name, + ), + new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)), + ]); + assert.equal(outcome, 'AbortError'); +}); + // Fiji across the antimeridian: east side (-180 … -177) is the wider half. const FIJI_BOX = { west: 179, south: -18, east: -177, north: -17 }; const FIJI_DAY = '2026-11-04'; diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 02f4ff2366..20ac79a15f 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -81,21 +81,26 @@ function probeHalf( signal?.addEventListener('abort', () => stop(signal.reason), { once: true, }); - let promise; - try { - promise = fetchImpl(url, { signal: controller.signal }); - } catch (error) { - finishTimeout(); - throw error; - } const response = new Promise((resolve, reject) => { settle = { resolve, reject }; + if (controller.signal.aborted) { + reject(controller.signal.reason); + return; + } if (deadlineMs > 0) timer = setTimeoutImpl( () => stop(new DOMException('Thumbnail half timed out', 'TimeoutError')), deadlineMs, ); + let promise; + try { + promise = Promise.resolve(fetchImpl(url, { signal: controller.signal })); + } catch (error) { + finishTimeout(); + reject(error); + return; + } promise.then( (value) => { transportSettled = true; From b2a6aa4d9fdb404c0aec031c66d9ed2cfe8e5814 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Tue, 10 Nov 2026 12:50:18 -0600 Subject: [PATCH 07/18] test(recent-imagery): strengthen half coverage --- changelog.d/1540-recent-imagery-dateline.md | 10 ++++------ src/layers/recentImagery/dateline-halves.test.mjs | 6 +++--- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md index f896c11ace..a81494959c 100644 --- a/changelog.d/1540-recent-imagery-dateline.md +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -2,11 +2,9 @@ into a box about 360° wide and refused as too large; it is now the short box across ±180°, which lists the days for that box and drapes a pinned day on both sides. Availability probes both sides of ±180° (a day counts as present when either - side has data, and sides confirmed empty are not draped — a - side confirmed empty never lands on the map), each side is bounded by its - own deadline and both sides' answers are heard — sides proven present all - drape, a side that stalls only bounds the day for its deadline instead of - being cancelled, and a side whose transport ignores abort is timed out at - the deadline itself, voice accepts named areas across the dateline, and EXPORT is + side has data, and sides confirmed empty are not draped). Each side has a + deadline so a stalled probe cannot indefinitely block the day; unknown or + failed sides are not treated as empty. Voice accepts named areas across the + dateline, and EXPORT is disabled up front with the reason, since Worldview Snapshots cannot draw a box that crosses ±180° (Byrd-IT, #1540). diff --git a/src/layers/recentImagery/dateline-halves.test.mjs b/src/layers/recentImagery/dateline-halves.test.mjs index 13a1ba8244..ce26ab2a02 100644 --- a/src/layers/recentImagery/dateline-halves.test.mjs +++ b/src/layers/recentImagery/dateline-halves.test.mjs @@ -230,9 +230,9 @@ test('both present halves are preserved: presentBoxes carries every data half an [EAST_HALF, WEST_HALF].find((h) => sameBox(h, half)), ); assert.deepEqual( - drapes.length, - 2, - 'each present half maps to one probe half', + new Set(drapes), + new Set([EAST_HALF, WEST_HALF]), + 'each present half maps to a distinct probe half', ); assert.ok(response.blob, 'the answer stays a readable response'); const blob = await response.blob(); From 6b216b3534eb6b07b99d6f117b6b009d3bc89555 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Tue, 10 Nov 2026 12:52:05 -0600 Subject: [PATCH 08/18] fix(recent-imagery): preserve frozen response accessors --- .../recentImagery/dateline-halves.test.mjs | 17 +++++++++++++++++ src/layers/recentImagery/source.js | 15 ++++++++------- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/layers/recentImagery/dateline-halves.test.mjs b/src/layers/recentImagery/dateline-halves.test.mjs index ce26ab2a02..e15e505d80 100644 --- a/src/layers/recentImagery/dateline-halves.test.mjs +++ b/src/layers/recentImagery/dateline-halves.test.mjs @@ -683,6 +683,23 @@ test('frozen responses retain availability', async () => { assert.ok((await response.blob()).size); }); +test('frozen native Response retains status and text methods', async () => { + const source = createRecentImagerySource({ + thumbnailUrl: () => 'https://example.invalid/', + fetchImpl: async () => + Object.freeze( + new Response('image', { + status: 200, + headers: { 'Data-Present': 'true' }, + }), + ), + }); + const response = await source.getThumbnail(FIJI_CANDIDATE, EAST_HALF); + assert.equal(response.status, 200); + assert.equal(await response.text(), 'image'); + assert.deepEqual(response.presentBoxes, [EAST_HALF]); +}); + test('removes previous drape when evidence changes from unknown to empty', () => { const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); const globe = fakeCollection(); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 20ac79a15f..4b8fddb6cb 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -137,13 +137,14 @@ function withPresentBoxes(response, presentBoxes) { }); return response; } catch { - // Preserve the loader's response contract even for a frozen Response. - return { - ok: response.ok, - headers: response.headers, - blob: () => response.blob(), - presentBoxes, - }; + // Preserve native Response getters and methods on non-extensible objects. + return new Proxy(Object.create(Object.getPrototypeOf(response)), { + get(_target, property) { + if (property === 'presentBoxes') return presentBoxes; + const value = Reflect.get(response, property, response); + return typeof value === 'function' ? value.bind(response) : value; + }, + }); } } From 5f1c230b5214928956b7381c737adfe5588160f6 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Tue, 10 Nov 2026 12:58:39 -0600 Subject: [PATCH 09/18] fix(recent-imagery): avoid exposing transport errors --- .../recentImagery/dateline-halves.test.mjs | 25 ++++++++++++++++++- src/layers/recentImagery/source.js | 8 ++++-- src/layers/recentImagery/source.test.mjs | 2 +- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/layers/recentImagery/dateline-halves.test.mjs b/src/layers/recentImagery/dateline-halves.test.mjs index e15e505d80..37a6191d39 100644 --- a/src/layers/recentImagery/dateline-halves.test.mjs +++ b/src/layers/recentImagery/dateline-halves.test.mjs @@ -351,7 +351,7 @@ test('a half that fails or stalls after the other half proved data does not unse const strict = createRecentImagerySource({ fetchImpl: failing.fetchImpl }); await assert.rejects( strict.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), - /snapshot failed/, + /Thumbnail request failed/, 'a failed half is an error, never an empty day', ); }); @@ -683,6 +683,29 @@ test('frozen responses retain availability', async () => { assert.ok((await response.blob()).size); }); +test('transport rejection does not expose untrusted error details', async () => { + const marker = 'synthetic-secret-do-not-expose-ABC123'; + const source = createRecentImagerySource({ + thumbnailUrl: () => 'https://example.invalid/', + fetchImpl: () => { + throw new Error(marker); + }, + }); + await assert.rejects( + source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), + (error) => { + assert.equal(error.message, 'Thumbnail request failed'); + assert.equal( + `${error.stack} ${JSON.stringify(error)} ${error.cause}`.includes( + marker, + ), + false, + ); + return true; + }, + ); +}); + test('frozen native Response retains status and text methods', async () => { const source = createRecentImagerySource({ thumbnailUrl: () => 'https://example.invalid/', diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 4b8fddb6cb..f9f304ef45 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -218,8 +218,12 @@ export function createRecentImagerySource({ ); // A rejected half is an error, never an empty day, unless another half // proved data on its own. - if (results.length > responses.length) - throw results.find((result) => result.status === 'rejected').reason; + if (results.length > responses.length) { + const failure = results.find((result) => result.status === 'rejected'); + if (failure.reason?.name === 'TimeoutError') + throw new DOMException('Thumbnail request timed out', 'TimeoutError'); + throw new Error('Thumbnail request failed'); + } return withPresentBoxes(combineHalves(responses), []); }, getTileTemplate: (product, day) => tileTemplate(product, day), diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index 570c5e0040..1318286a61 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -187,6 +187,6 @@ test('a rejected half does not hide data on the other half, and never reads as e }); await assert.rejects( failing.source.getThumbnail(candidate, NARROW_WEST), - /network/, + /Thumbnail request failed/, ); }); From 797bd2584119b0bda33b8ebf5d3b2f9ba1e918ab Mon Sep 17 00:00:00 2001 From: Byrd-IT <189950726+Byrd-IT@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:52:14 -0600 Subject: [PATCH 10/18] docs: CURRENT-STATE and changelog fragment describe the per-side dateline probe (#1540) --- changelog.d/1540-recent-imagery-dateline.md | 13 ++++++------- docs/CURRENT-STATE.md | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md index a81494959c..4786ba34e7 100644 --- a/changelog.d/1540-recent-imagery-dateline.md +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -1,10 +1,9 @@ - Recent Imagery takes a box dragged across the dateline. The drag was turned into a box about 360° wide and refused as too large; it is now the short box across ±180°, which lists the days for that box and drapes a pinned day on - both sides. Availability probes both sides of ±180° (a day counts as present when either - side has data, and sides confirmed empty are not draped). Each side has a - deadline so a stalled probe cannot indefinitely block the day; unknown or - failed sides are not treated as empty. Voice accepts named areas across the - dateline, and EXPORT is - disabled up front with the reason, since Worldview Snapshots cannot draw a - box that crosses ±180° (Byrd-IT, #1540). + both sides. Availability probes both sides of ±180° (a day counts as present + when either side has data, and sides confirmed empty are not draped). Each + side has a deadline so a stalled probe cannot indefinitely block the day; + unknown or failed sides are not treated as empty. Voice accepts named areas + across the dateline, and EXPORT is disabled up front with the reason, since + Worldview Snapshots cannot draw a box that crosses ±180° (Byrd-IT, #1540). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index cf1141a940..f5d0954e00 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7277,7 +7277,7 @@ pins and share links already supply complete boxes. - The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, a box across the dateline sent as one bounding box with west > east, which CMR reads as the short box, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. -- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT and `get_recent_imagery` refuse a dateline box (`Select one side of the dateline`) without requesting one, and its thumbnails and Data-Present probes use the box's wider side. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT and `get_recent_imagery` refuse a dateline box (`Select one side of the dateline`) without requesting one, and its thumbnails and Data-Present probes ask Worldview about each side of ±180° separately (wider side first, 15 s deadline per side, the caller's cancellation kept): the day is present when either side has data and empty only when both sides are confirmed empty, a side that failed or timed out is never read as empty, and a side confirmed empty is not draped. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. - **Rendering.** `rendering.js` owns at most two slots (a dateline box drapes two GIBS layers in its slot, one each side of ±180) on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. From fb3f921ac7a41f333d493c78a72da2730df9c171 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Wed, 11 Nov 2026 11:54:45 -0600 Subject: [PATCH 11/18] docs: CURRENT-STATE names both dateline refusal messages (#1540) --- docs/CURRENT-STATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f5d0954e00..5da48f0298 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7277,7 +7277,7 @@ pins and share links already supply complete boxes. - The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, a box across the dateline sent as one bounding box with west > east, which CMR reads as the short box, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. -- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT and `get_recent_imagery` refuse a dateline box (`Select one side of the dateline`) without requesting one, and its thumbnails and Data-Present probes ask Worldview about each side of ±180° separately (wider side first, 15 s deadline per side, the caller's cancellation kept): the day is present when either side has data and empty only when both sides are confirmed empty, a side that failed or timed out is never read as empty, and a side confirmed empty is not draped. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`A snapshot cannot cross the dateline`) refuse a dateline box without requesting one, and its thumbnails and Data-Present probes ask Worldview about each side of ±180° separately (wider side first, 15 s deadline per side, the caller's cancellation kept): the day is present when either side has data and empty only when both sides are confirmed empty, a side that failed or timed out is never read as empty, and a side confirmed empty is not draped. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. - **Rendering.** `rendering.js` owns at most two slots (a dateline box drapes two GIBS layers in its slot, one each side of ±180) on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. From 154d3388e526f19d6f4ad22015b9129d51237df0 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Fri, 13 Nov 2026 09:35:51 -0600 Subject: [PATCH 12/18] fix: refresh imagery halves after thumbnail probes --- changelog.d/1540-recent-imagery-dateline.md | 11 ++- docs/CURRENT-STATE.md | 2 +- .../recentImagery/dateline-halves.test.mjs | 12 ++- src/layers/recentImagery/index.js | 4 +- src/layers/recentImagery/index.test.mjs | 17 ++++ src/layers/recentImagery/source.js | 28 ++++-- src/layers/recentImagery/source.test.mjs | 85 +++++++++++++++++++ 7 files changed, 146 insertions(+), 13 deletions(-) diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md index 4786ba34e7..6b5dfa6419 100644 --- a/changelog.d/1540-recent-imagery-dateline.md +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -4,6 +4,11 @@ both sides. Availability probes both sides of ±180° (a day counts as present when either side has data, and sides confirmed empty are not draped). Each side has a deadline so a stalled probe cannot indefinitely block the day; - unknown or failed sides are not treated as empty. Voice accepts named areas - across the dateline, and EXPORT is disabled up front with the reason, since - Worldview Snapshots cannot draw a box that crosses ±180° (Byrd-IT, #1540). + unknown or failed sides are not treated as empty. A side that is not + confirmed present is draped only where the product has alpha: VIIRS is a + JPEG, so an unproven side would land on the map as a black rectangle, and + only a side Worldview confirmed present is draped for it; a PNG (HLS) + keeps the unproven side because alpha hides it. The day itself stays + present. Voice accepts named areas across the dateline, and EXPORT is + disabled up front with the reason, since Worldview Snapshots cannot draw a + box that crosses ±180° (Byrd-IT, #1540). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 5da48f0298..43beee2ae9 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7277,7 +7277,7 @@ pins and share links already supply complete boxes. - The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, a box across the dateline sent as one bounding box with west > east, which CMR reads as the short box, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. -- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`A snapshot cannot cross the dateline`) refuse a dateline box without requesting one, and its thumbnails and Data-Present probes ask Worldview about each side of ±180° separately (wider side first, 15 s deadline per side, the caller's cancellation kept): the day is present when either side has data and empty only when both sides are confirmed empty, a side that failed or timed out is never read as empty, and a side confirmed empty is not draped. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`A snapshot cannot cross the dateline`) refuse a dateline box without requesting one, and its thumbnails and Data-Present probes ask Worldview about each side of ±180° separately (wider side first, 15 s deadline per side, the caller's cancellation kept): the day is present when either side has data and empty only when both sides are confirmed empty, a side that failed or timed out is never read as empty, and a side confirmed empty is not draped. A side that is not confirmed present is draped only for a product with alpha: VIIRS is a JPEG, so an unproven side would land on the map as a black rectangle and only a side Worldview confirmed present is draped for it, while a PNG (HLS) keeps the unproven side because alpha hides it. The day itself stays present. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. - **Rendering.** `rendering.js` owns at most two slots (a dateline box drapes two GIBS layers in its slot, one each side of ±180) on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. diff --git a/src/layers/recentImagery/dateline-halves.test.mjs b/src/layers/recentImagery/dateline-halves.test.mjs index 37a6191d39..a430eda348 100644 --- a/src/layers/recentImagery/dateline-halves.test.mjs +++ b/src/layers/recentImagery/dateline-halves.test.mjs @@ -340,8 +340,8 @@ test('a half that fails or stalls after the other half proved data does not unse assert.equal(response.headers.get('Data-Present'), 'true'); assert.deepEqual( response.presentBoxes, - [EAST_HALF, WEST_HALF], - 'the unproven half is not called empty', + [WEST_HALF], + 'the stalled half is not draped: VIIRS is a JPEG without alpha', ); const failing = timedFetch({ @@ -666,9 +666,15 @@ test('a failed half is not mistaken for confirmed empty when the other is presen halfDeadlineMs: 20, }); const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); + assert.equal( + response.headers.get('Data-Present'), + 'true', + 'the day itself stays present', + ); assert.deepEqual( new Set(response.presentBoxes.map(bbox)), - new Set([bbox(EAST_HALF), bbox(WEST_HALF)]), + new Set([bbox(EAST_HALF)]), + 'the failed half is not draped: VIIRS is a JPEG without alpha', ); }); diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.js index 6520d81f85..ba29b3e95f 100644 --- a/src/layers/recentImagery/index.js +++ b/src/layers/recentImagery/index.js @@ -832,7 +832,9 @@ export function createRecentImageryLayer({ const drapesChanged = SLOT_IDS.some( (slotId) => (owned[slotId]?.key || null) !== shown[slotId], ); - if (drapesChanged && !pruned && !followed) syncRender(); + // The key can stay the same while a new probe changes its boxes. + // showSlot itself avoids rebuilding an unchanged drape. + if (!pruned && !followed) syncRender(); notify('thumbnail'); if (pruned || followed || drapesChanged) notify(); }); diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 913d5a1a6a..0268e8e093 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -1410,3 +1410,20 @@ test('a box dragged across the dateline is searched, listed and draped as one bo assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped'); assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°'); }); + + +test('thumbnail availability changes refresh an already shown day', async () => { + const f = fixture(); + const priorGet = f.thumbnails.get; + let boxes = [BOX]; + f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes }); + await f.ready(); + f.thumbnails.probeRequested(); + const slot = Object.keys(f.owned()).find((id) => f.owned()[id]); + assert.ok(slot, 'a day is already on the map'); + const key = f.owned()[slot].key; + boxes = [{ ...BOX, east: BOX.west + 1 }]; + f.thumbnails.probe(key, 'present'); + assert.deepEqual(f.owned()[slot].availableBoxes, boxes); + f.layer.destroy(); +}); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index f9f304ef45..18f2cf3753 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -1,5 +1,10 @@ import { searchHls } from './catalog.js'; -import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js'; +import { + PRODUCTS, + gibsTemplate, + nonCrossingBoxes, + wvsSnapshotUrl, +} from './model.js'; /** * A half's answer is only worth so much waiting: past this deadline the half @@ -23,6 +28,15 @@ function requestBoxes(box) { const isPresent = (response) => dataPresent(response) === 'true'; +/** + * A product without alpha (the VIIRS JPEG) cannot hide an empty half: it + * would drape as a black rectangle. Only a half Worldview confirmed present + * may be draped for it; a PNG (HLS) has alpha, so an unknown half is safe + * to keep and drape. + */ +const drapesOnlyProven = (candidate) => + PRODUCTS[candidate?.product]?.format === 'jpg'; + const dataPresent = (response) => response?.ok ? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase() @@ -209,10 +223,14 @@ export function createRecentImagerySource({ return withPresentBoxes( combineHalves(responses), probes - .filter( - (probe, i) => - results[i].status === 'rejected' || - dataPresent(results[i].value) !== 'false', + .filter((probe, i) => + // A product without alpha may drape only a half Worldview + // confirmed present: an empty or unproven half would land on + // the map as a black rectangle. A PNG keeps an unproven half. + drapesOnlyProven(candidate) + ? isPresent(results[i].value) + : results[i].status === 'rejected' || + dataPresent(results[i].value) !== 'false', ) .map((entry) => nonCrossingBoxes(entry.half)[0]), ); diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index 1318286a61..0d488a1da6 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -190,3 +190,88 @@ test('a rejected half does not hide data on the other half, and never reads as e /Thumbnail request failed/, ); }); + +// PR #1540 review (P2): a half whose probe failed or hung must not be +// draped for a product without alpha. VIIRS is a JPEG, so an empty or +// unknown half would land on the map as a black rectangle. Only a half +// Worldview confirmed present (`Data-Present: true`) may be draped for it. +// PNG products (HLS) keep an unknown half: alpha hides it. +const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' }; +const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 }; +const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 }; + +test('a JPEG product drapes only the half Worldview confirmed present: a rejected half is not draped', async () => { + const { source } = halvesSource({ + '-180/-179': new Error('network'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); + assert.equal( + response.headers.get('Data-Present'), + 'true', + 'the day itself stays present', + ); + assert.deepEqual( + response.presentBoxes, + [NARROW_BOX], + 'the failed half is not draped', + ); +}); + +test('a JPEG product does not drape a half whose probe hung', async () => { + const requested = []; + const source = createRecentImagerySource({ + thumbnailUrl: ({ box }) => { + requested.push(box); + return `https://imagery.example/${box.west}/${box.east}`; + }, + halfDeadlineMs: 20, + fetchImpl: async (url) => { + const answer = { + '-180/-179': () => new Promise(() => {}), + '179.9/180': () => dated('true', 'narrow'), + }[url.split('imagery.example/')[1]]; + return answer(); + }, + }); + const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); + assert.equal(requested.length, 2, 'both halves were requested'); + assert.equal( + response.headers.get('Data-Present'), + 'true', + 'the day itself stays present', + ); + assert.deepEqual( + response.presentBoxes, + [NARROW_BOX], + 'the hung half is not draped', + ); +}); + +test('a JPEG product does not drape a half that answered with an unknown presence', async () => { + const { source } = halvesSource({ + '-180/-179': dated('unknown', 'maybe'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); + assert.equal(response.headers.get('Data-Present'), 'true'); + assert.deepEqual( + response.presentBoxes, + [NARROW_BOX], + 'an unproven half is not draped', + ); +}); + +test('a PNG product keeps an unknown or failed half: alpha hides it', async () => { + const { source } = halvesSource({ + '-180/-179': new Error('network'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(await response.text(), 'narrow'); + assert.deepEqual( + response.presentBoxes, + [WIDE_BOX, NARROW_BOX], + 'a PNG keeps the unproven half', + ); +}); From ccffaeca4d0447389affa81d97c3826f7564fcb3 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Fri, 13 Nov 2026 09:36:17 -0600 Subject: [PATCH 13/18] style: format imagery regression test --- src/layers/recentImagery/index.test.mjs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 0268e8e093..bc3c1903d4 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -1411,7 +1411,6 @@ test('a box dragged across the dateline is searched, listed and draped as one bo assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°'); }); - test('thumbnail availability changes refresh an already shown day', async () => { const f = fixture(); const priorGet = f.thumbnails.get; From fc137bef85a96af8042abc161d5e39a6c1f40a49 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 18:50:06 +0400 Subject: [PATCH 14/18] fix(recent-imagery): keep drapes and proven halves steady across re-probes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The renderer compares the rectangles it actually drapes, so a probe that confirms the same halves no longer rebuilds a shown layer. - A re-probe of a present day keeps a side it proved earlier through a transient failure and drops it only on fresh empty evidence. - DETAILS shows partial coverage when a side is confirmed empty; the presentBoxes contract of the source is documented. - probeHalf, the presentBoxes filter, requestBoxes and mount are simplified; the frozen-response Proxy is gone. - Duplicate source tests move into their own suites and share the existing fixtures; tests pin the exact ±180 seam and the dateline refusals. - Comments, CURRENT-STATE and the changelog fragment are shortened and match the JPEG / PNG drape rules. --- changelog.d/1540-recent-imagery-dateline.md | 20 +- docs/CURRENT-STATE.md | 4 +- .../recentImagery/dateline-halves.test.mjs | 744 ------------------ src/layers/recentImagery/index.js | 10 +- src/layers/recentImagery/index.test.mjs | 224 +++++- src/layers/recentImagery/model.js | 40 +- src/layers/recentImagery/model.test.mjs | 4 +- src/layers/recentImagery/rendering.js | 79 +- src/layers/recentImagery/rendering.test.mjs | 127 ++- src/layers/recentImagery/source.js | 216 ++--- src/layers/recentImagery/source.test.mjs | 113 ++- src/layers/recentImagery/testDoubles.mjs | 49 ++ src/layers/recentImagery/thumbnails.js | 24 +- src/layers/recentImagery/thumbnails.test.mjs | 79 +- src/tools/queries/imagery.js | 2 +- src/tools/queries/imagery.test.mjs | 3 +- src/ui/imageryBoxTool.js | 2 - src/ui/recentImagery.js | 18 +- src/ui/recentImagery.test.mjs | 16 + src/ui/recentImageryNotice.test.mjs | 20 +- src/voice/imageryActions.js | 14 +- 21 files changed, 715 insertions(+), 1093 deletions(-) delete mode 100644 src/layers/recentImagery/dateline-halves.test.mjs diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md index 6b5dfa6419..227db9ca93 100644 --- a/changelog.d/1540-recent-imagery-dateline.md +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -1,14 +1,6 @@ -- Recent Imagery takes a box dragged across the dateline. The drag was turned - into a box about 360° wide and refused as too large; it is now the short box - across ±180°, which lists the days for that box and drapes a pinned day on - both sides. Availability probes both sides of ±180° (a day counts as present - when either side has data, and sides confirmed empty are not draped). Each - side has a deadline so a stalled probe cannot indefinitely block the day; - unknown or failed sides are not treated as empty. A side that is not - confirmed present is draped only where the product has alpha: VIIRS is a - JPEG, so an unproven side would land on the map as a black rectangle, and - only a side Worldview confirmed present is draped for it; a PNG (HLS) - keeps the unproven side because alpha hides it. The day itself stays - present. Voice accepts named areas across the dateline, and EXPORT is - disabled up front with the reason, since Worldview Snapshots cannot draw a - box that crosses ±180° (Byrd-IT, #1540). +- Recent Imagery takes a box dragged across the dateline as the short box across + ±180° instead of refusing it as about 360° wide. A day counts when either side + has imagery. A side confirmed empty is not draped, and the VIIRS overview + drapes only a side confirmed to have data. Voice accepts named areas across + the dateline. EXPORT and `get_recent_imagery` refuse such a box, since + Worldview Snapshots cannot draw one (Byrd-IT, #1540). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 43beee2ae9..c8d0f61717 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7277,9 +7277,9 @@ pins and share links already supply complete boxes. - The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, a box across the dateline sent as one bounding box with west > east, which CMR reads as the short box, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. -- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`A snapshot cannot cross the dateline`) refuse a dateline box without requesting one, and its thumbnails and Data-Present probes ask Worldview about each side of ±180° separately (wider side first, 15 s deadline per side, the caller's cancellation kept): the day is present when either side has data and empty only when both sides are confirmed empty, a side that failed or timed out is never read as empty, and a side confirmed empty is not draped. A side that is not confirmed present is draped only for a product with alpha: VIIRS is a JPEG, so an unproven side would land on the map as a black rectangle and only a side Worldview confirmed present is draped for it, while a PNG (HLS) keeps the unproven side because alpha hides it. The day itself stays present. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the dateline: Worldview snapshots cannot`) refuse a dateline box without requesting one. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. -- **Rendering.** `rendering.js` owns at most two slots (a dateline box drapes two GIBS layers in its slot, one each side of ±180) on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Rendering.** `rendering.js` owns at most two slots (a dateline box drapes up to two GIBS layers in its slot, one each side of ±180) on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when fewer sides drape than the box contains. Thumbnails: three days probed at once (two fetches each for a dateline box), sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. - **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once. - **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). diff --git a/src/layers/recentImagery/dateline-halves.test.mjs b/src/layers/recentImagery/dateline-halves.test.mjs deleted file mode 100644 index a430eda348..0000000000 --- a/src/layers/recentImagery/dateline-halves.test.mjs +++ /dev/null @@ -1,744 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { createRecentImagerySource } from './source.js'; -import { createThumbnailLoader } from './thumbnails.js'; -import { createRecentImageryRenderer } from './rendering.js'; -import { createRecentImageryLayer } from './index.js'; -import { nonCrossingBoxes } from './model.js'; - -/** Wait, briefly, for an async chain (search → probe → drape) to land. */ -async function until(condition, tries = 200, gapMs = 5) { - for (let i = 0; i < tries; i += 1) { - if (condition()) return true; - await new Promise((resolve) => setTimeout(resolve, gapMs)); - } - return false; -} -/** - * PR #1540 review, P1 + P2: a dateline box is probed as its two halves, and - * per-half availability must survive the whole walk to the map — - * `getThumbnail` (early settle on the first present half, per-half deadline, - * caller cancellation) → the loader's day state → `showSlot`, which drapes - * only the halves the probe proved present. VIIRS is a JPEG product with no - * alpha, so a draped confirmed-empty half is a black rectangle on the map. - */ - -test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => { - const controller = new AbortController(); - const source = createRecentImagerySource({ - thumbnailUrl: () => 'https://example.invalid/', - halfDeadlineMs: 10000, - fetchImpl: () => { - controller.abort(); - return new Promise(() => {}); - }, - }); - const outcome = await Promise.race([ - source - .getThumbnail(FIJI_CANDIDATE, FIJI_BOX, { signal: controller.signal }) - .then( - () => 'resolved', - (error) => error.name, - ), - new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)), - ]); - assert.equal(outcome, 'AbortError'); -}); - -// Fiji across the antimeridian: east side (-180 … -177) is the wider half. -const FIJI_BOX = { west: 179, south: -18, east: -177, north: -17 }; -const FIJI_DAY = '2026-11-04'; -const FIJI_CANDIDATE = { - key: `VIIRS:${FIJI_DAY}`, - product: 'VIIRS', - day: FIJI_DAY, - granules: [], - cloud: null, - timeRange: null, - availability: 'unknown', - coverage: 'full', -}; -const HALVES = nonCrossingBoxes(FIJI_BOX); // [west(179…180), east(-180…-177)] -const WEST_HALF = HALVES[0]; // narrow, empty -const EAST_HALF = HALVES[1]; // wider, has data -const bbox = (box) => [box.south, box.west, box.north, box.east].join(','); -const halfOf = (url) => - nonCrossingBoxes({ - west: Number(new URL(url).searchParams.get('BBOX').split(',')[1]), - south: Number(new URL(url).searchParams.get('BBOX').split(',')[0]), - east: Number(new URL(url).searchParams.get('BBOX').split(',')[3]), - north: Number(new URL(url).searchParams.get('BBOX').split(',')[2]), - })[0]; -const sameBox = (a, b) => - a.west === b.west && - a.south === b.south && - a.east === b.east && - a.north === b.north; - -function snapshot({ - present, - acquisitionTime = null, - delay = 0, - hangsForever = false, - reject = null, -} = {}) { - /** A Worldview snapshot shaped like fetch's: it honours the caller's signal. */ - return (signal) => - new Promise((resolve, rejectPromise) => { - const stop = (why) => - rejectPromise( - why ?? signal?.reason ?? new DOMException('Aborted', 'AbortError'), - ); - if (reject !== null) { - const timer = setTimeout(() => rejectPromise(reject), delay); - signal?.addEventListener( - 'abort', - () => { - clearTimeout(timer); - stop(signal.reason); - }, - { once: true }, - ); - return; - } - if (signal?.aborted) { - stop(); - return; - } - if (signal) - signal.addEventListener('abort', () => stop(signal.reason), { - once: true, - }); - if (hangsForever) return; // never settles unless aborted - const timer = setTimeout(() => { - resolve({ - ok: true, - headers: { - get: (name) => - name === 'Data-Present' - ? String(present) - : name === 'Acquisition-Time' - ? acquisitionTime - : null, - }, - blob: async () => new Blob([present ? 'viirs' : 'empty']), - }); - }, delay); - if (signal) - signal.addEventListener( - 'abort', - () => { - clearTimeout(timer); - stop(signal.reason); - }, - { once: true }, - ); - }); -} - -function timedFetch(answers) { - const calls = []; - const stopped = new Set(); - const fetchImpl = (url, { signal } = {}) => { - calls.push(String(url)); - const half = halfOf(url); - const side = sameBox(half, EAST_HALF) ? 'east' : 'west'; - signal?.addEventListener('abort', () => stopped.add(side), { once: true }); - return answers[side](signal); - }; - return { calls, fetchImpl, stopped }; -} - -const answer = (options) => snapshot(options); - -const neverSettles = () => new Promise(() => {}); // ignores abort entirely - -// ---- source level ------------------------------------------------------ - -test('a dateline day with a stalled half settles bounded: the present half survives, the stall is bounded by the deadline', async () => { - const fetch = timedFetch({ - east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), - west: answer({ hangsForever: true }), - }); - const source = createRecentImagerySource({ - fetchImpl: fetch.fetchImpl, - halfDeadlineMs: 30, - }); - const started = Date.now(); - const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - const elapsed = Date.now() - started; - - assert.ok( - elapsed >= 25, - `the stalled half was bounded, not dropped (${elapsed} ms)`, - ); - assert.ok(elapsed < 2000, `bounded by the deadline (${elapsed} ms)`); - assert.equal(response.headers.get('Data-Present'), 'true'); - assert.equal( - response.headers.get('Acquisition-Time'), - `${FIJI_DAY}T22:10:00Z`, - ); - assert.equal([...fetch.calls].length, 2, 'both halves were requested'); -}); - -test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => { - const calls = []; - const source = createRecentImagerySource({ - thumbnailUrl: ({ box }) => { - calls.push(box); - return 'https://imagery.example/thumbnail'; - }, - fetchImpl: neverSettles, - halfDeadlineMs: 10, - }); - const started = Date.now(); - await assert.rejects( - source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), - (error) => error?.name === 'TimeoutError', - ); - assert.ok(Date.now() - started < 1000, 'the deadline fired without abort'); - assert.equal(calls.length, 2, 'both halves were requested'); -}); - -test("the caller's cancellation rejects even when a transport ignores AbortSignal", async () => { - const source = createRecentImagerySource({ - fetchImpl: neverSettles, - halfDeadlineMs: 60_000, - }); - const controller = new AbortController(); - const settled = source - .getThumbnail(FIJI_CANDIDATE, FIJI_BOX, { signal: controller.signal }) - .then( - () => 'resolved', - (error) => error, - ); - controller.abort(new DOMException('stopped', 'AbortError')); - const outcome = await settled; - assert.equal(outcome?.name, 'AbortError', 'the day rejected with the stop'); -}); - -test('both present halves are preserved: presentBoxes carries every data half and the blob stays readable', async () => { - const fetch = timedFetch({ - east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T21:00:00Z` }), - west: answer({ present: true, acquisitionTime: `${FIJI_DAY}T20:00:00Z` }), - }); - const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); - const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - - assert.equal(response.presentBoxes.length, 2, 'every present half survives'); - const drapes = response.presentBoxes.map((half) => - [EAST_HALF, WEST_HALF].find((h) => sameBox(h, half)), - ); - assert.deepEqual( - new Set(drapes), - new Set([EAST_HALF, WEST_HALF]), - 'each present half maps to a distinct probe half', - ); - assert.ok(response.blob, 'the answer stays a readable response'); - const blob = await response.blob(); - assert.ok(blob.size > 0, 'the blob reads after presentBoxes is attached'); -}); - -test('a successful probe leaves no deadline timer behind', async () => { - const timers = new Set(); - let cleared = []; - const fetch = timedFetch({ - east: answer({ present: true }), - west: answer({ present: false }), - }); - const source = createRecentImagerySource({ - fetchImpl: fetch.fetchImpl, - setTimeoutImpl: (fn, ms) => { - const id = timers.size + 1; - timers.add(id); - return id; - }, - clearTimeoutImpl: (id) => { - cleared.push(id); - timers.delete(id); - }, - }); - await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - assert.notEqual(fetch, undefined); - assert.equal(timers.size, 0, 'every live deadline timer was cleared'); - assert.ok(cleared.length > 0, 'clearTimeout ran at least once'); -}); - -test('a hung half is bounded by the per-half deadline: the day errors instead of holding a loader slot forever', async () => { - const fetch = timedFetch({ - east: answer({ hangsForever: true }), - west: answer({ hangsForever: true }), - }); - const source = createRecentImagerySource({ - fetchImpl: fetch.fetchImpl, - halfDeadlineMs: 20, - }); - const started = Date.now(); - await assert.rejects( - source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), - (error) => error?.name === 'TimeoutError', - ); - assert.ok(Date.now() - started < 500, 'the deadline fired promptly'); -}); - -test('per-half availability is carried on the response: one present half, one confirmed empty', async () => { - const fetch = timedFetch({ - east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), - west: answer({ present: false }), - }); - const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); - const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - // P1: which half has data survives past combineHalves. - assert.deepEqual(response.presentBoxes, [EAST_HALF]); - assert.notEqual(response.blob, undefined); -}); - -test('both halves confirmed empty keep the day empty; a single non-crossing half reports its own box', async () => { - const fetch = timedFetch({ - east: answer({ present: false }), - west: answer({ present: false }), - }); - const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); - const empty = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - assert.equal(empty.headers.get('Data-Present'), 'false', 'the day is empty'); - assert.deepEqual(empty.presentBoxes, []); - - const plainBox = nonCrossingBoxes({ - west: -97.8, - south: 30.2, - east: -97.7, - north: 30.3, - })[0]; - const plainSource = createRecentImagerySource({ - fetchImpl: (url, { signal } = {}) => - answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` })( - signal, - ), - }); - const plainResponse = await plainSource.getThumbnail( - FIJI_CANDIDATE, - plainBox, - ); - assert.equal( - plainResponse.presentBoxes.length, - 1, - 'the plain box proves itself', - ); - assert.ok(sameBox(plainResponse.presentBoxes[0], plainBox)); -}); - -test('a half that fails or stalls after the other half proved data does not unseat the day; a failed half never reads as empty', async () => { - const fetch = timedFetch({ - east: answer({ hangsForever: true }), - west: answer({ present: true, acquisitionTime: `${FIJI_DAY}T20:00:00Z` }), - }); - const source = createRecentImagerySource({ - fetchImpl: fetch.fetchImpl, - halfDeadlineMs: 30, - }); - const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - assert.equal(response.headers.get('Data-Present'), 'true'); - assert.deepEqual( - response.presentBoxes, - [WEST_HALF], - 'the stalled half is not draped: VIIRS is a JPEG without alpha', - ); - - const failing = timedFetch({ - east: answer({ present: false }), - west: answer({ reject: new Error('snapshot failed'), delay: 5 }), - }); - const strict = createRecentImagerySource({ fetchImpl: failing.fetchImpl }); - await assert.rejects( - strict.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), - /Thumbnail request failed/, - 'a failed half is an error, never an empty day', - ); -}); - -test("the caller's cancellation rejects promptly and touches every half", async () => { - const fetch = timedFetch({ - east: answer({ hangsForever: true }), - west: answer({ hangsForever: true }), - }); - const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); - const controller = new AbortController(); - const settled = source - .getThumbnail(FIJI_CANDIDATE, FIJI_BOX, { signal: controller.signal }) - .then( - () => 'resolved', - (error) => error, - ); - controller.abort(new DOMException('stopped', 'AbortError')); - const outcome = await settled; - assert.equal(outcome?.name, 'AbortError', 'the day rejected with the stop'); - assert.ok( - fetch.stopped.has('east') && fetch.stopped.has('west'), - 'each half was cancelled', - ); -}); - -// ---- loader level (real loader over the real source) ------------------- - -test('the loader proves a dateline day present from one half and hands the present half onward', async () => { - const fetch = timedFetch({ - east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), - west: answer({ present: false }), - }); - const loader = createThumbnailLoader({ - fetchImpl: fetch.fetchImpl, - size: 256, - }); - const notified = new Promise((resolve) => { - const off = loader.subscribe((key) => { - if (key === FIJI_CANDIDATE.key) { - off(); - resolve(); - } - }); - }); - loader.request(FIJI_CANDIDATE, FIJI_BOX); - await notified; - const day = loader.get(FIJI_CANDIDATE.key); - assert.equal(day.status, 'present', 'one half with data proves the day'); - assert.equal( - day.acquisitionTime, - `${FIJI_DAY}T22:10:00Z`, - 'the present half’s sensing time', - ); - assert.ok(day.objectUrl); - assert.deepEqual( - day.availableBoxes, - [EAST_HALF], - 'per-half availability rides along', - ); - loader.destroy(); -}); - -test('a hung half does not strand the loader day at "checking" when the deadline bounds it', async () => { - const fetch = timedFetch({ - east: answer({ hangsForever: true }), - west: answer({ hangsForever: true }), - }); - const loader = createThumbnailLoader({ fetchImpl: fetch.fetchImpl }); - const source = createRecentImagerySource({ - fetchImpl: fetch.fetchImpl, - halfDeadlineMs: 20, - }); - const hungLoader = createThumbnailLoader({ - requestThumbnail: source.getThumbnail, - }); - const notified = new Promise((resolve) => - hungLoader.subscribe(() => resolve()), - ); - hungLoader.request(FIJI_CANDIDATE, FIJI_BOX); - await notified; - assert.equal( - hungLoader.get(FIJI_CANDIDATE.key).status, - 'error', - 'a deadline is an error, not "checking" forever', - ); - hungLoader.destroy(); - loader.destroy(); -}); - -// ---- renderer level ---------------------------------------------------- - -function fakeCesium() { - class Provider { - constructor(options) { - this.options = options; - } - requestImage() { - return new Promise(() => {}); - } - } - return { - UrlTemplateImageryProvider: Provider, - WebMercatorTilingScheme: class {}, - Rectangle: { - fromDegrees: (west, south, east, north) => ({ west, south, east, north }), - }, - SplitDirection: { LEFT: -1, NONE: 0, RIGHT: 1 }, - }; -} - -function fakeCollection() { - const layers = []; - return { - layers, - addImageryProvider(provider) { - const layer = { provider, alpha: 1, splitDirection: 0 }; - layers.push(layer); - return layer; - }, - remove(layer, destroy) { - layers.splice(layers.indexOf(layer), 1); - layer.destroyed = destroy; - }, - }; -} - -const rectangles = (collection) => - collection.layers.map((layer) => layer.provider.options.rectangle); - -test('the renderer drapes only the halves the probe proved present, and rebind keeps that choice', () => { - const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); - const globe = fakeCollection(); - renderer.rebind({ collection: globe, kind: 'globe' }); - - assert.equal( - renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { - availableBoxes: [EAST_HALF], - }), - true, - ); - const draped = rectangles(globe); - assert.equal(draped.length, 1, 'only the data-present half is draped'); - assert.ok(sameBox(draped[0], EAST_HALF)); - for (const rect of draped) - assert.ok(rect.west <= rect.east, 'every draped rectangle is plain'); - - // A dateline day that both halves proved present drapes both halves. - renderer.showSlot('b', FIJI_CANDIDATE, FIJI_BOX, { - availableBoxes: [EAST_HALF, WEST_HALF], - }); - assert.equal( - globe.layers.length, - 3, - 'a day proven on both halves drapes both halves (plus slot a)', - ); - - // A host switch rebuilds on the same evidence. - const globe2 = fakeCollection(); - renderer.rebind({ collection: globe2, kind: 'globe' }); - assert.ok( - sameBox(rectangles(globe2)[0], EAST_HALF), - 'rebind re-mounts the present half', - ); - - // Without availability the whole box is still draped (any proven day, HLS). - renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX); - assert.equal( - globe2.layers.length, - 4, - 'unlimited by evidence, both halves drape (slot b keeps its both-half evidence)', - ); - renderer.destroy(); - assert.equal(globe2.layers.length, 0, 'destroy tears the layers down'); -}); - -test('an empty day with no proven half drapes nothing; a stale half never drapes either', () => { - const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); - const globe = fakeCollection(); - renderer.rebind({ collection: globe, kind: 'globe' }); - assert.equal( - renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { availableBoxes: [] }), - false, - 'no proven half, no drape', - ); - assert.equal(globe.layers.length, 0); - const elsewhere = nonCrossingBoxes({ - west: -97.8, - south: 30.2, - east: -97.7, - north: 30.3, - })[0]; - assert.equal( - renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { - availableBoxes: [elsewhere], - }), - false, - 'proven halves of another box do not drape this one', - ); - assert.equal(globe.layers.length, 0); -}); - -// ---- the whole layer (real source → loader → renderer) ------------------ - -test('a VIIRS dateline day with data on one half drapes only that half through the real layer', async () => { - const fetch = timedFetch({ - east: answer({ present: true, acquisitionTime: `${FIJI_DAY}T22:10:00Z` }), - west: answer({ present: false }), - }); - const loader = createThumbnailLoader({ fetchImpl: fetch.fetchImpl }); - const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); - const globe = fakeCollection(); - const catalog = { - searchHls: async () => ({ - candidates: [FIJI_CANDIDATE], - truncated: false, - errors: [], - }), - }; - const layer = createRecentImageryLayer({ - catalog, - renderer, - thumbnails: loader, - host: () => ({ collection: globe, kind: 'globe' }), - now: () => new Date(`${FIJI_DAY}T15:00:00Z`), - }); - layer.init({ camera: {} }); - layer.setSources({ viirs: true }); - layer.enable(); - assert.equal(layer.setBox(FIJI_BOX), true, 'the dateline box validates'); - - // The probe fetched both halves, wider first, and the layer draped the - // winner on its own notify. - await until(() => rectangles(globe).length > 0); - const snapshot = layer.getSnapshot(); - const draped = rectangles(globe); - assert.equal(fetch.calls.length, 2, 'one probe per half'); - const probed = fetch.calls.map((url) => halfOf(url)); - assert.ok(sameBox(probed[0], EAST_HALF), 'the wider half is probed first'); - assert.ok(sameBox(probed[1], WEST_HALF)); - - assert.equal(draped.length, 1, 'only the data-present half hit the map'); - assert.ok(sameBox(draped[0], EAST_HALF)); - - // The day stays present and listed after draping. - assert.equal(loader.get(FIJI_CANDIDATE.key).status, 'present'); - assert.equal(snapshot.candidates[0].thumbnail.status, 'present'); - assert.equal(snapshot.candidates[0].drapable, true); - assert.equal( - snapshot.auto?.key, - FIJI_CANDIDATE.key, - 'START HERE keeps the day', - ); - - layer.destroy(); - loader.destroy(); - assert.equal( - globe.layers.length, - 0, - 'tearing the layer down takes the imagery with it', - ); -}); - -test('a dateline day both halves confirm empty never drapes and leaves the strip when hidden', async () => { - const fetch = timedFetch({ - east: answer({ present: false }), - west: answer({ present: false }), - }); - const loader = createThumbnailLoader({ fetchImpl: fetch.fetchImpl }); - const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); - const globe = fakeCollection(); - const catalog = { - searchHls: async () => ({ - candidates: [FIJI_CANDIDATE], - truncated: false, - errors: [], - }), - }; - const layer = createRecentImageryLayer({ - catalog, - renderer, - thumbnails: loader, - host: () => ({ collection: globe, kind: 'globe' }), - now: () => new Date(`${FIJI_DAY}T15:00:00Z`), - }); - layer.init({ camera: {} }); - layer.setSources({ viirs: true }); - layer.enable(); - layer.setBox(FIJI_BOX); - await new Promise((resolve) => { - const off = loader.subscribe(() => { - off(); - resolve(); - }); - layer.subscribe(() => { - /* the layer is the one that reacts */ - }); - }); - await until(() => loader.get(FIJI_CANDIDATE.key).status === 'empty'); - assert.equal(globe.layers.length, 0, 'a confirmed-empty day never drapes'); - layer.destroy(); - loader.destroy(); -}); - -test('a failed half is not mistaken for confirmed empty when the other is present', async () => { - const fetch = timedFetch({ - east: answer({ present: true }), - west: answer({ reject: new Error('offline') }), - }); - const source = createRecentImagerySource({ - fetchImpl: fetch.fetchImpl, - halfDeadlineMs: 20, - }); - const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - assert.equal( - response.headers.get('Data-Present'), - 'true', - 'the day itself stays present', - ); - assert.deepEqual( - new Set(response.presentBoxes.map(bbox)), - new Set([bbox(EAST_HALF)]), - 'the failed half is not draped: VIIRS is a JPEG without alpha', - ); -}); - -test('frozen responses retain availability', async () => { - const fetch = timedFetch({ - east: (s) => answer({ present: true })(s).then(Object.freeze), - west: answer({ present: false }), - }); - const source = createRecentImagerySource({ fetchImpl: fetch.fetchImpl }); - const response = await source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX); - assert.deepEqual(response.presentBoxes, [EAST_HALF]); - assert.ok((await response.blob()).size); -}); - -test('transport rejection does not expose untrusted error details', async () => { - const marker = 'synthetic-secret-do-not-expose-ABC123'; - const source = createRecentImagerySource({ - thumbnailUrl: () => 'https://example.invalid/', - fetchImpl: () => { - throw new Error(marker); - }, - }); - await assert.rejects( - source.getThumbnail(FIJI_CANDIDATE, FIJI_BOX), - (error) => { - assert.equal(error.message, 'Thumbnail request failed'); - assert.equal( - `${error.stack} ${JSON.stringify(error)} ${error.cause}`.includes( - marker, - ), - false, - ); - return true; - }, - ); -}); - -test('frozen native Response retains status and text methods', async () => { - const source = createRecentImagerySource({ - thumbnailUrl: () => 'https://example.invalid/', - fetchImpl: async () => - Object.freeze( - new Response('image', { - status: 200, - headers: { 'Data-Present': 'true' }, - }), - ), - }); - const response = await source.getThumbnail(FIJI_CANDIDATE, EAST_HALF); - assert.equal(response.status, 200); - assert.equal(await response.text(), 'image'); - assert.deepEqual(response.presentBoxes, [EAST_HALF]); -}); - -test('removes previous drape when evidence changes from unknown to empty', () => { - const renderer = createRecentImageryRenderer({ cesium: fakeCesium() }); - const globe = fakeCollection(); - renderer.rebind({ collection: globe, kind: 'globe' }); - renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX); - assert.equal(globe.layers.length, 2); - assert.equal( - renderer.showSlot('a', FIJI_CANDIDATE, FIJI_BOX, { availableBoxes: [] }), - false, - ); - assert.equal(globe.layers.length, 0); - renderer.destroy(); -}); diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.js index ba29b3e95f..d10c4946c7 100644 --- a/src/layers/recentImagery/index.js +++ b/src/layers/recentImagery/index.js @@ -549,8 +549,8 @@ export function createRecentImageryLayer({ : (slotId === 'a') !== _swapped ? 'left' : 'right', - // Keep every half except those confirmed empty by the probe. - availableBoxes: thumbnails.get(candidate.key)?.availableBoxes ?? null, + // The halves the probe lets this product drape, unknown before it answers. + availableBoxes: thumbnails.get(candidate.key)?.availableBoxes, }); } else { renderer.hideSlot(slotId); @@ -820,7 +820,6 @@ export function createRecentImageryLayer({ // preview; both change more than the cards, so a full notification // follows the thumbnail one. const pruned = pruneEmpty(); - if (pruned) syncRender(); const followed = Boolean(_followKey) && _followKey === _focusKey && @@ -832,9 +831,8 @@ export function createRecentImageryLayer({ const drapesChanged = SLOT_IDS.some( (slotId) => (owned[slotId]?.key || null) !== shown[slotId], ); - // The key can stay the same while a new probe changes its boxes. - // showSlot itself avoids rebuilding an unchanged drape. - if (!pruned && !followed) syncRender(); + // One render per probe: the key can stay the same while its halves change. + if (!followed) syncRender(); notify('thumbnail'); if (pruned || followed || drapesChanged) notify(); }); diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index bc3c1903d4..b5f08eb8e4 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -1,5 +1,10 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { until } from '../../testSupport/kartaViewFakes.mjs'; +import { createRecentImagerySource } from './source.js'; +import { createThumbnailLoader } from './thumbnails.js'; +import { createRecentImageryRenderer } from './rendering.js'; +import { nonCrossingBoxes } from './model.js'; import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js'; import { acquireImageryComparison } from '../../maps/imageryComparison.js'; import { MapSourceController } from '../../maps/controller.js'; @@ -15,9 +20,12 @@ import { import { BOX, CANDIDATES, + FIJI_BOX, boxToolFakes, candidate, fakeCatalog, + fakeCesium, + fakeCollection, fakeController, fakeRenderer, fakeThumbnails, @@ -1411,18 +1419,226 @@ test('a box dragged across the dateline is searched, listed and draped as one bo assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°'); }); -test('thumbnail availability changes refresh an already shown day', async () => { +test('a new probe of a shown dateline day hands the renderer the halves it now allows', async () => { const f = fixture(); const priorGet = f.thumbnails.get; - let boxes = [BOX]; + const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 }; + const [west, east] = nonCrossingBoxes(box); + let boxes = [west]; f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes }); - await f.ready(); + f.layer.enable(); + f.layer.setBox(box); + f.catalog.resolveLast(); + await settle(); f.thumbnails.probeRequested(); const slot = Object.keys(f.owned()).find((id) => f.owned()[id]); assert.ok(slot, 'a day is already on the map'); const key = f.owned()[slot].key; - boxes = [{ ...BOX, east: BOX.west + 1 }]; + assert.deepEqual(f.owned()[slot].availableBoxes, [west]); + boxes = [west, east]; f.thumbnails.probe(key, 'present'); assert.deepEqual(f.owned()[slot].availableBoxes, boxes); f.layer.destroy(); }); + +const sideOf = (url) => + Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0 + ? 'west' + : 'east'; +const snapshotAnswer = (present) => + new Response('img', { headers: { 'Data-Present': String(present) } }); + +function realLayer({ + fetchImpl, + candidates, + maxDecoded = 16, + halfDeadlineMs = 50, +}) { + const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs }); + let nextUrl = 0; + const loader = createThumbnailLoader({ + requestThumbnail: source.getThumbnail, + createObjectUrl: () => `blob:${++nextUrl}`, + revokeObjectUrl: () => {}, + maxDecoded, + }); + const globe = fakeCollection(); + const layer = createRecentImageryLayer({ + catalog: { + searchHls: async () => ({ candidates, truncated: false, errors: [] }), + }, + renderer: createRecentImageryRenderer({ cesium: fakeCesium() }), + thumbnails: loader, + host: () => ({ collection: globe, kind: 'globe' }), + now: () => new Date('2026-11-13T15:00:00Z'), + }); + layer.init({ camera: {} }); + return { layer, loader, globe }; +} + +test('a VIIRS dateline day with data on one side drapes only that side through the real layer', async () => { + const day = candidate('VIIRS', '2026-11-10'); + const sides = []; + const { layer, loader, globe } = realLayer({ + candidates: [day], + fetchImpl: async (url) => { + const side = sideOf(url); + sides.push(side); + return snapshotAnswer(side === 'east'); + }, + }); + layer.setSources({ viirs: true }); + layer.enable(); + assert.equal(layer.setBox(FIJI_BOX), true); + // The probe asks about both halves, wider first. The layer drapes the one with data. + assert.equal( + await until(() => globe.layers.length > 0, { ticks: 2000 }), + true, + ); + assert.deepEqual(sides, ['east', 'west']); + assert.deepEqual( + globe.layers.map((layer) => layer.provider.options.rectangle), + [nonCrossingBoxes(FIJI_BOX)[1]], + ); + assert.equal(loader.get(day.key).status, 'present'); + const snapshot = layer.getSnapshot(); + assert.equal(snapshot.candidates[0].thumbnail.status, 'present'); + assert.equal(snapshot.candidates[0].drapable, true); + assert.equal(snapshot.auto?.key, day.key); + layer.destroy(); + assert.equal(globe.layers.length, 0); +}); + +test('a dateline day both halves confirm empty never drapes and leaves the strip', async () => { + const day = candidate('VIIRS', '2026-11-10'); + const { layer, loader, globe } = realLayer({ + candidates: [day], + fetchImpl: async () => snapshotAnswer(false), + }); + layer.setSources({ viirs: true }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day.key).status === 'empty', { ticks: 2000 }), + true, + ); + assert.equal(globe.layers.length, 0); + assert.equal( + layer.getSnapshot().candidates.some((c) => c.key === day.key), + false, + 'an empty day leaves the strip', + ); + layer.destroy(); +}); + +function counting(collection) { + const counts = { add: 0, remove: 0 }; + const add = collection.addImageryProvider.bind(collection); + const remove = collection.remove.bind(collection); + collection.addImageryProvider = (provider) => { + counts.add += 1; + return add(provider); + }; + collection.remove = (layer, destroy) => { + counts.remove += 1; + return remove(layer, destroy); + }; + return counts; +} + +for (const [label, box] of [ + ['a plain box', { west: -98, south: 30, east: -97, north: 31 }], + ['a dateline box', FIJI_BOX], +]) { + test(`an HLS day draped before its probe keeps its layers when the probe confirms ${label}`, async () => { + const day = candidate('S30', '2026-11-10'); + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + const { layer, loader, globe } = realLayer({ + candidates: [day], + halfDeadlineMs: 5000, + fetchImpl: async () => { + await gate; + return snapshotAnswer(true); + }, + }); + const counts = counting(globe); + layer.enable(); + layer.setBox(box); + assert.equal( + await until(() => globe.layers.length === nonCrossingBoxes(box).length, { + ticks: 2000, + }), + true, + ); + const before = { ...counts, layers: [...globe.layers] }; + release(); + assert.equal( + await until(() => loader.get(day.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(counts.add, before.add); + assert.equal(counts.remove, before.remove); + assert.ok(globe.layers.every((layer) => before.layers.includes(layer))); + layer.destroy(); + }); +} + +test('a re-probe of a present VIIRS dateline day keeps a half that failed this time', async () => { + const day1 = candidate('VIIRS', '2026-11-10'); + const day2 = candidate('VIIRS', '2026-11-11'); + let eastCalls = 0; + let releaseDay2; + const gate = new Promise((resolve) => { + releaseDay2 = resolve; + }); + const { layer, loader, globe } = realLayer({ + candidates: [day2, day1], + maxDecoded: 1, + halfDeadlineMs: 5000, + fetchImpl: async (url) => { + if (new URL(url).searchParams.get('TIME') === day2.day) await gate; + else if (sideOf(url) === 'east' && ++eastCalls === 2) + throw new TypeError('Failed to fetch'); + return snapshotAnswer(true); + }, + }); + layer.setSources({ hls: false, viirs: true }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day1.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).availableBoxes.length, 2); + releaseDay2(); + assert.equal( + await until(() => loader.get(day2.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).objectUrl, null); + layer.setAssignment('a', day1.key); + assert.equal( + await until(() => eastCalls === 2 && !loader.get(day1.key).loading, { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).status, 'present'); + assert.equal(loader.get(day1.key).availableBoxes.length, 2); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual( + globe.layers.map((layer) => layer.provider.options.rectangle), + [west, east], + 'a half that failed on the re-probe stays draped', + ); + layer.destroy(); +}); diff --git a/src/layers/recentImagery/model.js b/src/layers/recentImagery/model.js index 2f1add85b2..a2e3d74d7b 100644 --- a/src/layers/recentImagery/model.js +++ b/src/layers/recentImagery/model.js @@ -72,13 +72,11 @@ export const PRODUCTS = Object.freeze({ const finite = (value) => typeof value === 'number' && Number.isFinite(value); const toRadians = (degrees) => (degrees * Math.PI) / 180; +/** A longitude brought back into ±180 after one step past it. */ +const wrapLon = (value) => + value > 180 ? value - 360 : value < -180 ? value + 360 : value; const pad2 = (value) => String(value).padStart(2, '0'); -/** - * Coerce a box to `{ west, south, east, north }` with south ≤ north. West and - * east are not swapped: west > east is the short arc across the dateline. - * Null when any edge is nonfinite. - */ /** A box edge as a number, or null when it is missing, blank or not numeric. */ function edgeNumber(value) { if (typeof value === 'number') return Number.isFinite(value) ? value : null; @@ -87,6 +85,11 @@ function edgeNumber(value) { return Number.isFinite(number) ? number : null; } +/** + * Coerce a box to `{ west, south, east, north }` with south ≤ north. West and + * east are not swapped: west > east is the short arc across the dateline. + * Null when any edge is nonfinite. + */ function normalizeBox(box) { if (!box || typeof box !== 'object') return null; const [west, south, east, north] = [ @@ -105,9 +108,10 @@ function normalizeBox(box) { } /** - * Degrees of longitude from `west` to `east`. A west > east box is the short - * arc across the antimeridian. A west <= east box is unchanged, even when - * that span is the long way round. + * Degrees of longitude going east from `west` to `east`. A west > east pair + * wraps across the antimeridian (`lonSpanDeg(170, -170)` is 20 and + * `lonSpanDeg(10, -10)` is 340). A west <= east pair is `east - west`, + * even the long way round. * @param {number} west Degrees. * @param {number} east Degrees. * @returns {number} @@ -119,7 +123,7 @@ export function lonSpanDeg(west, east) { /** * One or two boxes with west <= east that cover the same area. A dateline * box is split at ±180 so each side is a plain rectangle for a draped layer - * or a Worldview request. An invalid box is []. + * or a Worldview request. A box with a missing or nonfinite edge is []. * @param {object} box Degrees box. * @returns {Array} */ @@ -223,10 +227,10 @@ export function fitViewHeightM({ width, height, fovy } = {}) { export function boxCentre(box) { const normalized = normalizeBox(box); if (!normalized) return null; - let lon = normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2; - if (lon > 180) lon -= 360; return { - lon, + lon: wrapLon( + normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2, + ), lat: (normalized.south + normalized.north) / 2, }; } @@ -251,8 +255,6 @@ export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) { const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat); // A half-width of 90° or more is not a short arc; refuse rather than wrap. if (halfLon >= 90) return null; - const wrapLon = (value) => - value > 180 ? value - 360 : value < -180 ? value + 360 : value; const clampLat = (value) => Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value)); const result = validateBox({ @@ -492,12 +494,10 @@ export function coverageFor(candidate, box) { // outside the west corner stays put: shifting every value below west would // send that corner the long way round and miss a footprint that covers it. const crossing = west > east; - const project = (lon) => { - if (!crossing) return lon; - if (lon >= west) return lon; - if (lon <= east) return lon + 360; - return west - lon <= lon - east ? lon : lon + 360; - }; + const project = (lon) => + crossing && lon < west && (lon <= east || lon - east < west - lon) + ? lon + 360 + : lon; const samples = [ [project(west), south], [project(east), south], diff --git a/src/layers/recentImagery/model.test.mjs b/src/layers/recentImagery/model.test.mjs index 42c1efdc0c..8933032e1b 100644 --- a/src/layers/recentImagery/model.test.mjs +++ b/src/layers/recentImagery/model.test.mjs @@ -338,9 +338,9 @@ test('coverage of a dateline box uses the short arc, not the long way', () => { 'one footprint that crosses ±180', ); assert.equal( - coverageFor(withRings(ring(178.9, 180.1), ring(-180.1, -178.9)), box), + coverageFor(withRings(ring(178.9, 180), ring(-180, -178.9)), box), 'full', - 'a pair split at ±180', + 'a pair split exactly at ±180', ); assert.equal( coverageFor(withRings(ring(179, 180)), box), diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index b6c23a0663..e004b00c69 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -1,13 +1,12 @@ /** * Draped-imagery renderer for the Recent Imagery layer: at most two slots * (slot `a`, left of a swipe; slot `b`, right) on whichever host the map - * stack offers. A box that crosses the dateline drapes two imagery layers - * in that slot, one on each side of ±180, each a plain west <= east - * rectangle (see `nonCrossingBoxes`). Against the - * basemap slot `a` splits left and slot `b` stays empty. Every layer is - * removed from the collection that owns it, so a host switch or a replaced - * image never strands one. Tile requests pass a small semaphore of our own; - * Cesium's global request limits stay untouched. + * stack offers. A dateline box drapes up to two layers in its slot, one each + * side of ±180 (see `nonCrossingBoxes`). Against the basemap slot `a` splits + * left and slot `b` stays empty. Every layer is removed from the collection + * that owns it, so a host switch or a replaced image never strands one. + * Tile requests pass a small semaphore of our own. Cesium's global request + * limits stay untouched. */ import * as Cesium from 'cesium'; import { PRODUCTS, gibsTemplate, nonCrossingBoxes } from './model.js'; @@ -29,14 +28,20 @@ function clampAlpha(value) { const boxKey = (box) => [box.west, box.south, box.east, box.north].map(Number).join(','); -/** Comparable per-half availability signature; unknown differs from empty. */ -const boxesKey = (list) => - Array.isArray(list) - ? list - .map((box) => boxKey(box)) - .sort() - .join(';') - : 'unknown'; +/** One comparable key for a slot's draped parts. */ +const partsKey = (parts) => parts.map(boxKey).sort().join(';'); + +/** + * Without per-half evidence every part drapes. With evidence, only the parts + * it lists drape (the source's drapesOnlyProven decides which those are). + * Evidence for another box lists none of them. + */ +function drapedParts(box, availableBoxes) { + const parts = nonCrossingBoxes(box); + if (!Array.isArray(availableBoxes)) return parts; + const listed = new Set(availableBoxes.filter(Boolean).map(boxKey)); + return parts.filter((part) => listed.has(boxKey(part))); +} /** * Gate a provider's `requestImage` through the semaphore. Returning @@ -92,7 +97,7 @@ export function createRecentImageryRenderer({ let host = NO_HOST; let destroyed = false; const admission = { limit: maxTileRequests, inFlight: 0 }; - /** @type {Record<'a'|'b', null | { layers: Array, collection: object, candidate: object, box: object, alpha: number, split: string }>} */ + /** @type {Record<'a'|'b', null | { layers: Array, collection: object, candidate: object, box: object, parts: Array, alpha: number, split: string }>} */ const owned = { a: null, b: null }; // One timer for both slots: any number of upstream deferrals while it is @@ -156,36 +161,11 @@ export function createRecentImageryRenderer({ } } - function mount(slotId, { candidate, box, alpha, split, availableBoxes }) { - // [] means "not a box": add no layer rather than drape the raw box. - const parts = nonCrossingBoxes(box); + function mount(slotId, { candidate, box, alpha, split, parts }) { if (!parts.length) return false; - // Skip confirmed-empty halves; a failed probe is not proof of emptiness. - // No evidence drapes the whole box, as before. Evidence for a different - // box leaves the slot empty rather than applying stale availability. - const allowed = Array.isArray(availableBoxes) - ? parts.filter((part) => - availableBoxes.some((half) => half && boxKey(half) === boxKey(part)), - ) - : parts; - if (!allowed.length) return false; - // Build every provider before adding any layer, so a throw on the second - // half of a dateline box cannot leave the first layer untracked. - const providers = allowed.map((part) => createProvider(candidate, part)); - const layers = []; - try { - for (const provider of providers) - layers.push(host.collection.addImageryProvider(provider)); - } catch (error) { - for (const layer of layers) { - try { - host.collection.remove(layer, true); - } catch { - /* the collection is already gone */ - } - } - throw error; - } + const layers = parts.map((part) => + host.collection.addImageryProvider(createProvider(candidate, part)), + ); owned[slotId] = { layers, collection: host.collection, @@ -193,7 +173,7 @@ export function createRecentImageryRenderer({ box, alpha, split, - availableBoxes, + parts, }; applyLook(owned[slotId]); return true; @@ -222,12 +202,13 @@ export function createRecentImageryRenderer({ } const current = owned[slotId]; const look = { alpha: clampAlpha(alpha), split: splitDirection }; + const parts = drapedParts(box, availableBoxes); if ( current && current.collection === host.collection && current.candidate.key === candidate.key && boxKey(current.box) === boxKey(box) && - boxesKey(current.availableBoxes) === boxesKey(availableBoxes) + partsKey(current.parts) === partsKey(parts) ) { if (current.alpha !== look.alpha || current.split !== look.split) { Object.assign(current, look); @@ -237,7 +218,7 @@ export function createRecentImageryRenderer({ return true; } const removed = removeOwned(slotId); - if (!mount(slotId, { candidate, box, ...look, availableBoxes })) { + if (!mount(slotId, { candidate, box, ...look, parts })) { if (removed) requestRender('recent-imagery-hide'); return false; } @@ -298,7 +279,7 @@ export function createRecentImageryRenderer({ return out; }, - /** Number of slots this renderer owns (never above two). A dateline box uses two imagery layers in its slot. */ + /** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */ ownedCount() { return SLOT_IDS.filter((slotId) => owned[slotId]).length; }, diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index 74890c4222..c2b3210a6d 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -5,49 +5,14 @@ import { TILE_RETRY_DELAY_MS, createRecentImageryRenderer, } from './rendering.js'; -import { BOX, manualTimers } from './testDoubles.mjs'; - -/** A provider whose tile requests stay pending until the test settles them. */ -class UrlTemplateImageryProvider { - constructor(options) { - this.options = options; - this.calls = []; - this.pending = []; - } - requestImage(x, y, level) { - this.calls.push([x, y, level]); - return new Promise((resolve) => this.pending.push(resolve)); - } -} - -function fakeCesium(requestImage) { - class Provider extends UrlTemplateImageryProvider {} - if (requestImage) Provider.prototype.requestImage = requestImage; - return { - UrlTemplateImageryProvider: Provider, - WebMercatorTilingScheme: class {}, - Rectangle: { - fromDegrees: (west, south, east, north) => ({ west, south, east, north }), - }, - SplitDirection: { LEFT: -1, NONE: 0, RIGHT: 1 }, - }; -} - -function fakeCollection() { - const layers = []; - return { - layers, - addImageryProvider(provider) { - const layer = { provider, alpha: 1, splitDirection: 0 }; - layers.push(layer); - return layer; - }, - remove(layer, destroy) { - layers.splice(layers.indexOf(layer), 1); - layer.destroyed = destroy; - }, - }; -} +import { nonCrossingBoxes } from './model.js'; +import { + BOX, + FIJI_BOX, + fakeCesium, + fakeCollection, + manualTimers, +} from './testDoubles.mjs'; const S30 = { key: 'S30:2026-09-18', product: 'S30', day: '2026-09-18' }; const L30 = { key: 'L30:2026-09-16', product: 'L30', day: '2026-09-16' }; @@ -257,43 +222,51 @@ test('a dateline box drapes one layer on each side of ±180 and removes both', ( assert.equal(globe.layers.length, 0); }); -test('a dateline provider that fails on the second half adds no layer', () => { - let built = 0; - const base = fakeCesium(); - const Provider = base.UrlTemplateImageryProvider; - base.UrlTemplateImageryProvider = class extends Provider { - constructor(options) { - built += 1; - if (built === 2) throw new Error('provider failed'); - super(options); - } - }; - const renderer = createRecentImageryRenderer({ - cesium: base, - requestRender: () => {}, - }); - const globe = fakeCollection(); - renderer.rebind({ collection: globe, kind: 'globe' }); - assert.throws( - () => - renderer.showSlot('a', S30, { - west: 179, - south: 0, - east: -179, - north: 1, - }), - /provider failed/, +test('the renderer drapes only the halves the probe allows, and rebind keeps them', () => { + const { renderer, globe } = fixture(); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + assert.equal( + renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [east] }), + true, ); - assert.equal(globe.layers.length, 0); - assert.equal(renderer.ownedCount(), 0); + assert.deepEqual( + globe.layers.map((layer) => layer.provider.options.rectangle), + [east], + ); + renderer.showSlot('b', VIIRS, FIJI_BOX, { availableBoxes: [east, west] }); + assert.equal(globe.layers.length, 3); + + const next = fakeCollection(); + renderer.rebind({ collection: next, kind: 'globe' }); + assert.deepEqual( + next.layers.map((layer) => layer.provider.options.rectangle), + [east, west, east], + ); + renderer.showSlot('a', VIIRS, FIJI_BOX); + assert.equal(next.layers.length, 4); + renderer.destroy(); + assert.equal(next.layers.length, 0); }); -test('a box that is not a box adds no layer and drapes nothing', () => { - const { renderer, globe, renders } = fixture(); - for (const bad of [{ west: NaN, south: 0, east: 1, north: 1 }, { west: 0 }]) { - assert.equal(renderer.showSlot('a', S30, bad), false); +test('no allowed half, or halves of another box, drapes nothing', () => { + const { renderer, globe } = fixture(); + for (const availableBoxes of [[], [BOX]]) { + assert.equal( + renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes }), + false, + ); + assert.equal(globe.layers.length, 0); } +}); + +test('evidence going from none to empty removes the drape', () => { + const { renderer, globe } = fixture(); + renderer.showSlot('a', VIIRS, FIJI_BOX); + assert.equal(globe.layers.length, 2); + assert.equal( + renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [] }), + false, + ); assert.equal(globe.layers.length, 0); - assert.equal(renderer.ownedCount(), 0); - assert.deepEqual(renders, []); + renderer.destroy(); }); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 18f2cf3753..85d0f2d2eb 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -7,32 +7,29 @@ import { } from './model.js'; /** - * A half's answer is only worth so much waiting: past this deadline the half - * is cancelled with its own `TimeoutError` so a day whose wider side answered - * at once is never stranded at "checking" behind a narrow side that never - * sends headers. + * Deadline for one half's response headers, so a day whose other half + * answered is not held at "checking". */ const DEFAULT_HALF_DEADLINE_MS = 15_000; /** * Worldview Snapshots rejects a BBOX with west > east, so a dateline box is - * probed as its two non-crossing halves, wider first. Granules do not cross - * +/-180, so a day has data when either half does. + * probed as its two non-crossing halves, wider first. A plain box is its + * one normalized half. Granules do not cross ±180, so a day has data when + * either half does. */ function requestBoxes(box) { - if (!(box?.west > box?.east)) return [box]; const halves = nonCrossingBoxes(box); if (!halves.length) return [box]; - return [...halves].sort((a, b) => b.east - b.west - (a.east - a.west)); + return halves.sort((a, b) => b.east - b.west - (a.east - a.west)); } const isPresent = (response) => dataPresent(response) === 'true'; /** - * A product without alpha (the VIIRS JPEG) cannot hide an empty half: it - * would drape as a black rectangle. Only a half Worldview confirmed present - * may be draped for it; a PNG (HLS) has alpha, so an unknown half is safe - * to keep and drape. + * Which halves a product may drape. The VIIRS JPEG has no alpha and would + * drape an empty side as a black rectangle, so it drapes only a half + * Worldview confirmed present. An HLS PNG drapes every half not confirmed empty. */ const drapesOnlyProven = (candidate) => PRODUCTS[candidate?.product]?.format === 'jpg'; @@ -43,11 +40,9 @@ const dataPresent = (response) => : ''; /** - * One answer for a crossing box across only the halves that actually - * answered: the first half that has data (the wider side wins a tie, so the - * thumbnail shows it); both confirmed empty is empty; any other mix (a - * failed or unreadable half) is returned as that half's response so the day - * is never called empty on partial evidence. + * Of the halves that answered, prefer the first with data (wider wins a + * tie), then the first not confirmed empty so an unreadable answer is + * never called empty, then the first response. */ function combineHalves(responses) { const present = responses.find(isPresent); @@ -58,49 +53,34 @@ function combineHalves(responses) { /** * One half's snapshot fetch, raced against its own deadline so a half that - * never answers — including a transport that ignores its AbortSignal — is - * bounded and the day settles instead of hanging. The controller is private: - * only a half that has not settled is ever aborted, so a settled response's - * body stays readable afterwards, while the caller's signal still stops - * every pending half at once. No half is settled early on the other's - * answer: both headers are heard, so two present halves both survive. + * never answers, even over a transport that ignores AbortSignal, still + * settles. Its deadline cancels only this half. The caller can cancel it + * at any time, including while its body is being read. */ function probeHalf( url, { fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl }, ) { const controller = new AbortController(); - let settle = null; - let timer = null; - let transportSettled = false; - const finishTimeout = () => { - if (timer !== null) { - clearTimeoutImpl(timer); + return new Promise((resolve, reject) => { + let timer = null; + const finishTimeout = () => { + if (timer !== null) clearTimeoutImpl(timer); timer = null; + }; + const stop = (reason) => { + controller.abort(reason); + finishTimeout(); + // Settle even if the transport ignores abort. + reject(reason); + }; + if (signal?.aborted) { + stop(signal.reason); + return; } - }; - const stop = (why) => { - const reason = - why ?? - signal?.reason ?? - new DOMException('Thumbnail half stopped', 'AbortError'); - controller.abort(reason); - finishTimeout(); - // The transport's own rejection is the answer when it honours abort; - // for one that does not, the race itself carries the stop to the probe. - if (!transportSettled) settle?.reject(reason); - }; - if (signal?.aborted) stop(); - else signal?.addEventListener('abort', () => stop(signal.reason), { once: true, }); - const response = new Promise((resolve, reject) => { - settle = { resolve, reject }; - if (controller.signal.aborted) { - reject(controller.signal.reason); - return; - } if (deadlineMs > 0) timer = setTimeoutImpl( () => @@ -117,55 +97,38 @@ function probeHalf( } promise.then( (value) => { - transportSettled = true; finishTimeout(); resolve(value); }, (error) => { - transportSettled = true; finishTimeout(); reject(error); }, ); }); - // The deadline dies with the fetch's own settle; the caller-abort wiring - // deliberately outlives it, so a stop that arrives while the response body - // is still being read still cancels the half, right up until the caller's - // signal (and this listener with it) is collected. - return { stop, response }; } /** - * The answer to one request: the response, enriched (non-enumerably, so the - * transport's own shape is untouched) with the non-crossing halves the probe - * did not confirm empty. An empty evidence list is a confirmed-empty day; - * no field means the caller did not probe per half. + * Non-enumerable evidence for the box's non-crossing halves. presentBoxes + * lists the halves this product may drape (see drapesOnlyProven). + * emptyBoxes lists the halves Worldview confirmed empty. */ -function withPresentBoxes(response, presentBoxes) { +function withHalves(response, { presentBoxes, emptyBoxes }) { if (!response) return response; - try { - Object.defineProperty(response, 'presentBoxes', { - value: presentBoxes, - enumerable: false, - configurable: true, - }); - return response; - } catch { - // Preserve native Response getters and methods on non-extensible objects. - return new Proxy(Object.create(Object.getPrototypeOf(response)), { - get(_target, property) { - if (property === 'presentBoxes') return presentBoxes; - const value = Reflect.get(response, property, response); - return typeof value === 'function' ? value.bind(response) : value; - }, - }); - } + Object.defineProperties(response, { + presentBoxes: { value: presentBoxes, configurable: true }, + emptyBoxes: { value: emptyBoxes, configurable: true }, + }); + return response; } /** * NASA-compatible imagery acquisition; transport and URL builders are replaceable. * Thumbnail responses must expose Data-Present: true for image admission, or * false for confirmed empty coverage, including injected getThumbnail sources. + * getThumbnail also sets presentBoxes and emptyBoxes (see withHalves). + * Without per-half evidence the renderer drapes every side of a dateline + * box, so an empty side of a VIIRS JPEG then draws black. */ export function createRecentImagerySource({ fetchImpl = (...args) => globalThis.fetch(...args), @@ -183,66 +146,57 @@ export function createRecentImagerySource({ async getThumbnail(candidate, box, { size = 256, signal } = {}) { signal?.throwIfAborted(); const halves = requestBoxes(box); - const probes = halves.map((half) => ({ - half, - ...probeHalf( - thumbnailUrl({ - product: candidate.product, - day: candidate.day, - box: half, - width: size, - height: size, - }), - { - fetchImpl, - signal, - deadlineMs: halves.length > 1 ? halfDeadlineMs : 0, - setTimeoutImpl, - clearTimeoutImpl, - }, - ), - })); - // Bounded header race: every half is raced against its own deadline, - // so a half that never answers — even a transport that ignores its - // AbortSignal — is bounded. Both headers are heard; no half is settled - // early on the other's answer, so two present halves both survive. + const deadlineMs = halves.length > 1 ? halfDeadlineMs : 0; const results = await Promise.allSettled( - probes.map((probe) => probe.response), + halves.map((half) => + probeHalf( + thumbnailUrl({ + product: candidate.product, + day: candidate.day, + box: half, + width: size, + height: size, + }), + { + fetchImpl, + signal, + deadlineMs, + setTimeoutImpl, + clearTimeoutImpl, + }, + ), + ), ); signal?.throwIfAborted(); - const fulfilled = []; - results.forEach((result, i) => { - if (result.status === 'fulfilled') - fulfilled.push({ value: result.value, half: probes[i].half }); - }); - const responses = fulfilled.map((entry) => entry.value); - // Retain every half except one that answered confirmed empty. A failed - // probe is not evidence of absence, even when its sibling proves a day. - const proven = fulfilled.filter((entry) => isPresent(entry.value)); - if (proven.length) - return withPresentBoxes( - combineHalves(responses), - probes - .filter((probe, i) => - // A product without alpha may drape only a half Worldview - // confirmed present: an empty or unproven half would land on - // the map as a black rectangle. A PNG keeps an unproven half. - drapesOnlyProven(candidate) - ? isPresent(results[i].value) - : results[i].status === 'rejected' || - dataPresent(results[i].value) !== 'false', - ) - .map((entry) => nonCrossingBoxes(entry.half)[0]), - ); - // A rejected half is an error, never an empty day, unless another half - // proved data on its own. - if (results.length > responses.length) { - const failure = results.find((result) => result.status === 'rejected'); + // Per half, its Data-Present answer or null when it did not answer. + const answers = results.map((result) => + result.status === 'fulfilled' ? dataPresent(result.value) : null, + ); + const responses = results + .filter((result) => result.status === 'fulfilled') + .map((result) => result.value); + const halvesWhere = (keep) => halves.filter((_, i) => keep(answers[i])); + const emptyBoxes = halvesWhere((answer) => answer === 'false'); + if (answers.includes('true')) + return withHalves(combineHalves(responses), { + presentBoxes: halvesWhere( + drapesOnlyProven(candidate) + ? (answer) => answer === 'true' + : (answer) => answer !== 'false', + ), + emptyBoxes, + }); + // A missing answer is an error unless another half proved data. + const failure = results.find((result) => result.status === 'rejected'); + if (failure) { if (failure.reason?.name === 'TimeoutError') throw new DOMException('Thumbnail request timed out', 'TimeoutError'); throw new Error('Thumbnail request failed'); } - return withPresentBoxes(combineHalves(responses), []); + return withHalves(combineHalves(responses), { + presentBoxes: [], + emptyBoxes, + }); }, getTileTemplate: (product, day) => tileTemplate(product, day), }; diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index 0d488a1da6..59d6ecb455 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -1,5 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { manualTimers } from './testDoubles.mjs'; import { createRecentImagerySource } from './source.js'; test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => { @@ -39,8 +40,7 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt ); assert.equal(calls.length, 1); assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256'); - // Each half is bounded by a controller of its own (a deadline can cancel - // one half without the other), but it is chained to the caller's signal. + // The fetch gets a private signal chained to the caller's. const halfSignal = calls[0][1].signal; assert.notEqual(halfSignal, controller.signal); assert.equal(halfSignal.aborted, false); @@ -108,11 +108,17 @@ test('a dateline thumbnail is requested as two non-crossing halves, never as a c }); const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 }; +// VIIRS is a JPEG without alpha. S30 (candidate) is a PNG. +const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' }; +const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 }; +const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 }; + const dated = (present, body = 'image') => new Response(body, { headers: { 'Data-Present': present } }); -function halvesSource(answers) { +function halvesSource(answers, options = {}) { const requested = []; const source = createRecentImagerySource({ + ...options, thumbnailUrl: ({ box }) => `https://imagery.example/${box.west}/${box.east}`, fetchImpl: async (url) => { @@ -135,6 +141,8 @@ test('a crossing box probes both halves and is present when only the narrow half assert.equal(requested.length, 2); assert.equal(response.headers.get('Data-Present'), 'true'); assert.equal(await response.text(), 'narrow'); + assert.deepEqual(response.presentBoxes, [NARROW_BOX]); + assert.deepEqual(response.emptyBoxes, [WIDE_BOX]); }); test('a crossing box with data only on the wider half is present and shows the wider side', async () => { @@ -153,6 +161,8 @@ test('a crossing box is empty only when both halves are confirmed empty', async }); const response = await source.getThumbnail(candidate, NARROW_WEST); assert.equal(response.headers.get('Data-Present'), 'false'); + assert.deepEqual(response.presentBoxes, []); + assert.deepEqual(response.emptyBoxes, [WIDE_BOX, NARROW_BOX]); }); test('a crossing box is not called empty when the other half failed', async () => { @@ -171,7 +181,7 @@ test('a crossing box with both halves present shows the wider half and keeps bot }); const response = await source.getThumbnail(candidate, NARROW_WEST); assert.equal(await response.text(), 'wide'); - assert.equal(response.presentBoxes.length, 2, 'every present half survives'); + assert.deepEqual(response.presentBoxes, [WIDE_BOX, NARROW_BOX]); }); test('a rejected half does not hide data on the other half, and never reads as empty', async () => { @@ -191,15 +201,6 @@ test('a rejected half does not hide data on the other half, and never reads as e ); }); -// PR #1540 review (P2): a half whose probe failed or hung must not be -// draped for a product without alpha. VIIRS is a JPEG, so an empty or -// unknown half would land on the map as a black rectangle. Only a half -// Worldview confirmed present (`Data-Present: true`) may be draped for it. -// PNG products (HLS) keep an unknown half: alpha hides it. -const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' }; -const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 }; -const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 }; - test('a JPEG product drapes only the half Worldview confirmed present: a rejected half is not draped', async () => { const { source } = halvesSource({ '-180/-179': new Error('network'), @@ -275,3 +276,89 @@ test('a PNG product keeps an unknown or failed half: alpha hides it', async () = 'a PNG keeps the unproven half', ); }); + +test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => { + const controller = new AbortController(); + const source = createRecentImagerySource({ + thumbnailUrl: () => 'https://example.invalid/', + halfDeadlineMs: 10000, + fetchImpl: () => { + controller.abort(); + return new Promise(() => {}); + }, + }); + const outcome = await Promise.race([ + source + .getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { signal: controller.signal }) + .then( + () => 'resolved', + (error) => error.name, + ), + new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)), + ]); + assert.equal(outcome, 'AbortError'); +}); + +test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => { + const hang = () => new Promise(() => {}); + const { source, requested } = halvesSource( + { '-180/-179': hang, '179.9/180': hang }, + { halfDeadlineMs: 10 }, + ); + await assert.rejects(source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), { + name: 'TimeoutError', + }); + assert.equal(requested.length, 2); +}); + +test("the caller's cancellation rejects at once and stops every half", async () => { + const aborted = []; + const source = createRecentImagerySource({ + thumbnailUrl: ({ box }) => String(box.west), + fetchImpl: (url, { signal }) => { + signal.addEventListener('abort', () => aborted.push(url), { once: true }); + return new Promise(() => {}); + }, + }); + const controller = new AbortController(); + const result = source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { + signal: controller.signal, + }); + controller.abort(); + await assert.rejects(result, { name: 'AbortError' }); + assert.deepEqual(aborted, ['-180', '179.9']); +}); + +test('a successful probe leaves no deadline timer behind', async () => { + const timers = manualTimers(); + const { source } = halvesSource( + { '-180/-179': dated('true'), '179.9/180': dated('false') }, + timers, + ); + await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); + assert.equal(timers.armed(), 0); + assert.equal(timers.cleared.length, 2); +}); + +test('transport rejection does not expose untrusted error details', async () => { + const marker = 'synthetic-secret-do-not-expose-ABC123'; + const source = createRecentImagerySource({ + thumbnailUrl: () => 'https://example.invalid/', + fetchImpl: () => { + throw new Error(marker); + }, + }); + await assert.rejects( + source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), + (error) => { + assert.equal(error.message, 'Thumbnail request failed'); + assert.equal( + `${error.stack} ${JSON.stringify(error)} ${error.cause}`.includes( + marker, + ), + false, + ); + return true; + }, + ); +}); diff --git a/src/layers/recentImagery/testDoubles.mjs b/src/layers/recentImagery/testDoubles.mjs index 2b00e5b019..cb71106f1d 100644 --- a/src/layers/recentImagery/testDoubles.mjs +++ b/src/layers/recentImagery/testDoubles.mjs @@ -11,6 +11,55 @@ export const BOX = Object.freeze({ north: 30.3, }); +export const FIJI_BOX = Object.freeze({ + west: 179, + south: -18, + east: -177, + north: -17, +}); + +/** A provider whose tile requests stay pending until the test settles them. */ +class UrlTemplateImageryProvider { + constructor(options) { + this.options = options; + this.calls = []; + this.pending = []; + } + requestImage(x, y, level) { + this.calls.push([x, y, level]); + return new Promise((resolve) => this.pending.push(resolve)); + } +} + +export function fakeCesium(requestImage) { + class Provider extends UrlTemplateImageryProvider {} + if (requestImage) Provider.prototype.requestImage = requestImage; + return { + UrlTemplateImageryProvider: Provider, + WebMercatorTilingScheme: class {}, + Rectangle: { + fromDegrees: (west, south, east, north) => ({ west, south, east, north }), + }, + SplitDirection: { LEFT: -1, NONE: 0, RIGHT: 1 }, + }; +} + +export function fakeCollection() { + const layers = []; + return { + layers, + addImageryProvider(provider) { + const layer = { provider, alpha: 1, splitDirection: 0 }; + layers.push(layer); + return layer; + }, + remove(layer, destroy) { + layers.splice(layers.indexOf(layer), 1); + layer.destroyed = destroy; + }, + }; +} + export const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); /** Timers that fire only when the test says so. */ diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index c727dcf40c..80c3a7b9ee 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -19,6 +19,16 @@ const EMPTY = Object.freeze({ loading: false, }); +const halfKey = (box) => [box.west, box.south, box.east, box.north].join(','); + +/** Keep earlier proof on a re-probe unless the new answer confirms that half empty. */ +function keepProvenHalves(previous, next, empty) { + if (!Array.isArray(previous) || !Array.isArray(next) || !Array.isArray(empty)) + return next; + const drop = new Set([...next, ...empty].map(halfKey)); + return [...next, ...previous.filter((half) => !drop.has(halfKey(half)))]; +} + /** * @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options] */ @@ -91,8 +101,9 @@ export function createThumbnailLoader({ let status = 'error'; let objectUrl = null; let acquisitionTime = null; - // Halves not confirmed empty; null when no per-half probe is available. + // The halves the probe lets this product drape, or null without a per-half probe. let availableBoxes = null; + let emptyBoxes = null; let cancelled = false; try { const response = await requestThumbnail(entry.candidate, entry.box, { @@ -106,6 +117,7 @@ export function createThumbnailLoader({ response.headers?.get?.('Data-Present') ?? '', ).toLowerCase(); availableBoxes = response.presentBoxes ?? null; + emptyBoxes = response.emptyBoxes ?? null; acquisitionTime = response.headers?.get?.('Acquisition-Time') || null; if (present === 'false') { status = 'empty'; @@ -134,7 +146,14 @@ export function createThumbnailLoader({ return; } // A failed re-fetch of an evicted image keeps what the day proved. + // A re-probe drops a half only on a fresh "empty". if (status !== 'error' || entry.status !== 'present') { + if (status === 'present' && entry.status === 'present') + availableBoxes = keepProvenHalves( + entry.availableBoxes, + availableBoxes, + emptyBoxes, + ); entry.status = status; entry.acquisitionTime = acquisitionTime; entry.availableBoxes = availableBoxes; @@ -188,6 +207,7 @@ export function createThumbnailLoader({ status: 'unknown', objectUrl: null, acquisitionTime: null, + availableBoxes: null, loading: false, controller: null, touched: 0, @@ -251,7 +271,7 @@ export function createThumbnailLoader({ status: entry.status, objectUrl: entry.objectUrl, acquisitionTime: entry.acquisitionTime, - availableBoxes: entry.availableBoxes ?? null, + availableBoxes: entry.availableBoxes, loading: entry.loading, }; }, diff --git a/src/layers/recentImagery/thumbnails.test.mjs b/src/layers/recentImagery/thumbnails.test.mjs index 6d521c27e7..3c9913ba95 100644 --- a/src/layers/recentImagery/thumbnails.test.mjs +++ b/src/layers/recentImagery/thumbnails.test.mjs @@ -1,13 +1,9 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { createThumbnailLoader } from './thumbnails.js'; -import { BOX, response, settle } from './testDoubles.mjs'; - -const candidate = (product, day) => ({ - key: `${product}:${day}`, - product, - day, -}); +import { createRecentImagerySource } from './source.js'; +import { nonCrossingBoxes } from './model.js'; +import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs'; /** A fetch whose responses the test releases, in any order. */ function fakeFetch() { @@ -337,3 +333,72 @@ test('injected thumbnail acquisition owns requests while the loader releases obj loader.destroy(); assert.deepEqual(revoked, ['blob:1']); }); + +test('the loader proves a dateline day present from one half and hands that half on', async () => { + const day = candidate('VIIRS', '2026-11-04'); + const time = day.day + 'T22:10:00Z'; + const { loader } = fixture({ + fetchImpl: async (url) => { + const east = + new URL(url).searchParams.get('BBOX').split(',')[1] === '-180'; + return response({ + headers: east + ? { 'Data-Present': 'true', 'Acquisition-Time': time } + : { 'Data-Present': 'false' }, + }); + }, + }); + loader.request(day, FIJI_BOX); + await settle(); + const entry = loader.get(day.key); + assert.equal(entry.status, 'present'); + assert.equal(entry.acquisitionTime, time); + assert.ok(entry.objectUrl); + assert.deepEqual(entry.availableBoxes, [nonCrossingBoxes(FIJI_BOX)[1]]); + loader.destroy(); +}); + +test('a dateline day whose halves both hang is an error, not "checking" forever', async () => { + const source = createRecentImagerySource({ + fetchImpl: () => new Promise(() => {}), + halfDeadlineMs: 20, + }); + const loader = createThumbnailLoader({ + requestThumbnail: source.getThumbnail, + }); + const day = candidate('VIIRS', '2026-11-04'); + const settled = new Promise((resolve) => loader.subscribe(resolve)); + loader.request(day, FIJI_BOX); + await settled; + assert.equal(loader.get(day.key).status, 'error'); + loader.destroy(); +}); + +test('a re-probe of a present day drops a half only when it is confirmed empty', async () => { + const box = { west: 179, south: 0, east: -179, north: 1 }; + const [west, east] = nonCrossingBoxes(box); + const answers = [ + { presentBoxes: [west, east], emptyBoxes: [] }, + { presentBoxes: [west, east], emptyBoxes: [] }, + { presentBoxes: [west], emptyBoxes: [east] }, + ]; + const { loader } = fixture({ + maxDecoded: 1, + requestThumbnail: async () => + Object.assign( + response({ headers: { 'Data-Present': 'true' } }), + answers.shift(), + ), + }); + const day1 = candidate('VIIRS', '2026-11-04'); + const day2 = candidate('VIIRS', '2026-11-05'); + loader.request(day1, box); + await settle(); + loader.request(day2, box); + await settle(); + assert.equal(loader.get(day1.key).objectUrl, null); + loader.request(day1, box); + await settle(); + assert.deepEqual(loader.get(day1.key).availableBoxes, [west]); + loader.destroy(); +}); diff --git a/src/tools/queries/imagery.js b/src/tools/queries/imagery.js index dbb3743473..da3483a13a 100644 --- a/src/tools/queries/imagery.js +++ b/src/tools/queries/imagery.js @@ -55,7 +55,7 @@ export const getRecentImagery = defineTool({ if (box.west > box.east) throw new ToolError( 'invalid_arguments', - 'A snapshot cannot cross the dateline', + 'The area must not cross the dateline: Worldview snapshots cannot', ); let latest; try { diff --git a/src/tools/queries/imagery.test.mjs b/src/tools/queries/imagery.test.mjs index 77574b7eb1..605a7be48a 100644 --- a/src/tools/queries/imagery.test.mjs +++ b/src/tools/queries/imagery.test.mjs @@ -102,9 +102,10 @@ test('overview fallback, empty results and invalid areas are reported', async () wrapped.call('get_recent_imagery', { area: { bbox: [179, 0, -179, 1] }, }), - /snapshot cannot cross the dateline/, + /must not cross the dateline/, ); assert.equal(crossing.snapshots.length, 0); + assert.equal(crossing.boxes.length, 0); await assert.rejects( none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }), /±85° latitude/, diff --git a/src/ui/imageryBoxTool.js b/src/ui/imageryBoxTool.js index e510776de3..9e4d52692c 100644 --- a/src/ui/imageryBoxTool.js +++ b/src/ui/imageryBoxTool.js @@ -23,8 +23,6 @@ export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box'; * @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps * `onEscape` runs before the tool cancels on Escape; returning `true` claims * the key (it is still consumed) and leaves the tool armed. - * A drag whose corners are more than 180 degrees of longitude apart is the - * short box across the dateline, returned with west > east. * @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise } | null} */ export function initImageryBoxTool({ diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.js index 66c2172bfb..2ea48b1011 100644 --- a/src/ui/recentImagery.js +++ b/src/ui/recentImagery.js @@ -22,7 +22,7 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue'; import { PRODUCTS, hhmm, - lonSpanDeg, + nonCrossingBoxes, wvsSnapshotUrl, } from '../layers/recentImagery/model.js'; import { displayDay, displayMetres } from '../layers/recentImagery/display.js'; @@ -142,6 +142,16 @@ function coverageText(coverage) { return t('unknown'); } +/** A present day covers the box only in part when its probe omits a side. */ +function shownCoverage(candidate, box) { + const drapes = candidate.thumbnail?.availableBoxes; + return candidate.thumbnail?.status === 'present' && + Array.isArray(drapes) && + drapes.length < nonCrossingBoxes(box).length + ? 'partial' + : candidate.coverage; +} + function cloudText(candidate) { if (candidate.thumbnail?.status === 'empty') return t('no imagery'); if (!candidate.cloud) return t('cloud unknown'); @@ -579,7 +589,9 @@ export function createRecentImageryPanel({ }), ); times.push( - t('Coverage {coverage}', { coverage: coverageText(focus.coverage) }), + t('Coverage {coverage}', { + coverage: coverageText(shownCoverage(focus, snapshot.box)), + }), ); lines.push({ id: 'acquired', text: times.join(' · ') }); (focus.granules || []).forEach((granule, index) => { @@ -785,7 +797,7 @@ export function createRecentImageryPanel({ // The snapshot is plate carrée: keep the box's degree aspect, with the // longer side at the size limit. const size = longerSideKm(snapshot.boxSizeKm) > 25 ? 2048 : 1024; - const spanLon = lonSpanDeg(snapshot.box.west, snapshot.box.east) || 1; + const spanLon = Math.abs(snapshot.box.east - snapshot.box.west) || 1; const spanLat = Math.abs(snapshot.box.north - snapshot.box.south) || 1; const width = Math.max( 1, diff --git a/src/ui/recentImagery.test.mjs b/src/ui/recentImagery.test.mjs index f4a59208b9..2a6560905c 100644 --- a/src/ui/recentImagery.test.mjs +++ b/src/ui/recentImagery.test.mjs @@ -4,9 +4,11 @@ import assert from 'node:assert/strict'; import { assertSameNode } from '../testSupport/domAssert.mjs'; import { readFileSync } from 'node:fs'; import { createRecentImageryPanel } from './recentImagery.js'; +import { nonCrossingBoxes } from '../layers/recentImagery/model.js'; import { createRecentImageryLayer } from '../layers/recentImagery/index.js'; import { BOX, + FIJI_BOX, fakeCatalog, fakeController, fakeRenderer, @@ -1055,6 +1057,20 @@ test('DETAILS is a collapsed rail card holding every note, and the empty-days to assert.equal(article.dataset.open, 'false'); }); +test('DETAILS shows partial coverage when a present dateline day drapes one half', async () => { + const f = fixture(); + f.layer.enable(); + f.layer.setBox(FIJI_BOX); + f.catalog.resolveLast(); + await settle(); + assert.match(f.byId('ri-details').textContent, /Coverage full/); + const get = f.thumbnails.get; + const [west] = nonCrossingBoxes(FIJI_BOX); + f.thumbnails.get = (key) => ({ ...get(key), availableBoxes: [west] }); + f.thumbnails.probe(f.snap().focus.key, 'present'); + assert.match(f.byId('ri-details').textContent, /Coverage partial/); +}); + test('the body scroll position survives renders even when DOM mutations reset it', async () => { const f = fixture(); await f.ready(); diff --git a/src/ui/recentImageryNotice.test.mjs b/src/ui/recentImageryNotice.test.mjs index 67bcea040e..3dca902aea 100644 --- a/src/ui/recentImageryNotice.test.mjs +++ b/src/ui/recentImageryNotice.test.mjs @@ -14,14 +14,15 @@ const REFUSALS = [ 'Point the camera at the ground to use the view', // layers/recentImagery/index.js 'That point cannot anchor a box', // layers/recentImagery/index.js ...[ - { west: 170, south: 10, east: -170, north: 20 }, // too large (dateline arc) - { west: 10, south: 80, east: 20, north: 89 }, // polar - { west: 10, south: 10, east: 10, north: 20 }, // degenerate - { west: 10, south: 10, east: 200, north: 20 }, // longitude range - { west: Number.NaN, south: 10, east: 20, north: 20 }, // not finite - ].map((box) => { + [{ west: 170, south: 10, east: -170, north: 20 }, 'too-large'], + [{ west: 10, south: 80, east: 20, north: 89 }, 'polar'], + [{ west: 10, south: 10, east: 10, north: 20 }, 'degenerate'], + [{ west: 10, south: 10, east: 200, north: 20 }, 'invalid'], + [{ west: Number.NaN, south: 10, east: 20, north: 20 }, 'invalid'], + ].map(([box, reason]) => { const result = validateBox(box); assert.equal(result.ok, false); + assert.equal(result.reason, reason); return result.message; }), ]; @@ -35,6 +36,13 @@ const SHOWN_EN = new Map([ ], ]); +test('a dateline box is measured on its short arc', () => { + assert.equal( + validateBox({ west: 179, south: 0, east: -179, north: 1 }).ok, + true, + ); +}); + test('en: refusals stay English', () => { setLocale('en'); for (const text of REFUSALS) { diff --git a/src/voice/imageryActions.js b/src/voice/imageryActions.js index 6c0aa3ff85..1d857cdec4 100644 --- a/src/voice/imageryActions.js +++ b/src/voice/imageryActions.js @@ -20,7 +20,7 @@ import { PRODUCTS, boxCentre, - lonSpanDeg, + boxSideKm, rankLatest, } from '../layers/recentImagery/model.js'; import { @@ -210,14 +210,10 @@ export async function findImagery( const [west, south, east, north] = record.bbox; // 30 m pixels over a landmark-sized area show a handful of blobs: a small // area gets the layer's own 10 km box around its centre instead. - // west > east is the short arc across the date line: measure and centre - // it with the layer's own helpers, never (west + east) / 2. - const small = - (north - south) * 111 < 5 && - lonSpanDeg(west, east) * - 111 * - Math.cos((((north + south) / 2) * Math.PI) / 180) < - 5; + // west > east is the short arc across the date line. The layer's helpers + // measure and centre it. + const { width, height } = boxSideKm({ west, south, east, north }); + const small = width < 5 && height < 5; box = small ? { pin: boxCentre({ west, south, east, north }) } : { west, south, east, north }; From e71ed722729fabddbddc8b364208ad37f2356fab Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 11:31:14 +0400 Subject: [PATCH 15/18] fix(recent-imagery): keep a slot's halves in place when its probe changes them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A probe that narrows or widens a dateline slot keeps the layer of the half that stays; a new half is inserted right above it, so in A/B without a split one day stays on top on both sides of ±180. - A VIIRS dateline box drapes nothing without per-half evidence, so a replacement source without presentBoxes cannot drape an empty black side. - The loader keeps the halves confirmed empty; DETAILS says partial for a confirmed-empty side and unknown for a side that did not answer. - mount adds parts without a rollback; unused Cesium test fakes are gone. --- src/layers/recentImagery/rendering.js | 63 +++++++++++++------ src/layers/recentImagery/rendering.test.mjs | 55 +++++++++++++++- .../slot-order-widening.test.mjs | 37 +++++++++++ src/layers/recentImagery/source.js | 4 +- src/layers/recentImagery/testDoubles.mjs | 42 ------------- src/layers/recentImagery/thumbnails.js | 6 +- src/layers/recentImagery/thumbnails.test.mjs | 1 + src/ui/recentImagery.js | 16 ++--- src/ui/recentImagery.test.mjs | 17 ++++- 9 files changed, 164 insertions(+), 77 deletions(-) create mode 100644 src/layers/recentImagery/slot-order-widening.test.mjs diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index 62cc1b34dc..f7635f95fd 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -41,13 +41,16 @@ const boxKey = (box) => const partsKey = (parts) => parts.map(boxKey).sort().join(';'); /** - * Without per-half evidence every part drapes. With evidence, only the parts - * it lists drape (the source's drapesOnlyProven decides which those are). - * Evidence for another box lists none of them. + * Without per-half evidence a dateline JPEG waits for the probe because + * an empty side would draw black. Other boxes drape all their parts. + * With evidence, only the listed parts of this box drape. */ -function drapedParts(box, availableBoxes) { +function drapedParts(candidate, box, availableBoxes) { const parts = nonCrossingBoxes(box); - if (!Array.isArray(availableBoxes)) return parts; + if (!Array.isArray(availableBoxes)) + return parts.length > 1 && PRODUCTS[candidate.product]?.format === 'jpg' + ? [] + : parts; const listed = new Set(availableBoxes.filter(Boolean).map(boxKey)); return parts.filter((part) => listed.has(boxKey(part))); } @@ -138,16 +141,10 @@ export function createRecentImageryRenderer({ function mount(slotId, { candidate, parts, alpha, split }) { if (!parts.length) return false; - const layers = []; - try { - for (const part of parts) - layers.push(host.globe.imagery.add(specFor(candidate, part))); - } catch (error) { - for (const layer of layers) layer.remove(); - throw error; - } owned[slotId] = { - layers, + layers: parts.map((part) => + host.globe.imagery.add(specFor(candidate, part)), + ), globe: host.globe, candidate, parts, @@ -160,8 +157,9 @@ export function createRecentImageryRenderer({ return { /** - * Drape the available parts of a candidate into a slot. The same parts of - * the same day on the same port only need their look updated. + * Drape the available parts of a candidate into a slot. On the same day + * and port, keep each surviving layer, add a new part right above it and + * remove dropped parts. * @param {'a'|'b'} slotId * @param {object} candidate * @param {object} box Degrees box. @@ -181,14 +179,41 @@ export function createRecentImageryRenderer({ } const current = owned[slotId]; const look = { alpha: clampAlpha(alpha), split: splitDirection }; - const parts = drapedParts(box, availableBoxes); + const parts = drapedParts(candidate, box, availableBoxes); if ( current && current.globe === host.globe && current.candidate.key === candidate.key && - partsKey(current.parts) === partsKey(parts) + parts.length ) { - if (current.alpha !== look.alpha || current.split !== look.split) { + if (partsKey(current.parts) !== partsKey(parts)) { + const previous = new Map( + current.parts.map((part, i) => [boxKey(part), current.layers[i]]), + ); + // A new half goes right above the slot's surviving half, so both + // halves keep the same place against the other slot. + const survivor = parts + .map((part) => previous.get(boxKey(part))) + .find(Boolean); + const at = survivor + ? host.globe.imagery.list().indexOf(survivor) + 1 + : undefined; + const layers = parts.map((part) => { + const key = boxKey(part); + const layer = previous.get(key); + previous.delete(key); + return ( + layer ?? host.globe.imagery.add(specFor(candidate, part), at) + ); + }); + for (const layer of previous.values()) layer.remove(); + Object.assign(current, { layers, parts, ...look }); + applyLook(current); + requestRender('recent-imagery-show'); + } else if ( + current.alpha !== look.alpha || + current.split !== look.split + ) { Object.assign(current, look); applyLook(current); requestRender('recent-imagery-look'); diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index 4a0de2b8ed..7289b746b5 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -330,7 +330,7 @@ test('the renderer drapes only the halves the probe allows, and rebind keeps the next.layers.map((layer) => layer.spec.rectangle), [east, west, east], ); - renderer.showSlot('a', VIIRS, FIJI_BOX); + renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [west, east] }); assert.equal(next.layers.length, 4); renderer.destroy(); assert.equal(next.layers.length, 0); @@ -347,18 +347,67 @@ test('no allowed half, or halves of another box, drapes nothing', () => { } }); +test('without per-half evidence a VIIRS dateline box drapes nothing, a plain VIIRS box and an HLS dateline box still drape', () => { + const { renderer, globe } = fixture(); + assert.equal(renderer.showSlot('a', VIIRS, FIJI_BOX), false); + assert.equal(globe.layers.length, 0); + assert.equal(renderer.showSlot('a', VIIRS, BOX), true); + assert.equal(globe.layers.length, 1); + assert.equal(renderer.showSlot('b', S30, FIJI_BOX), true); + assert.equal(globe.layers.length, 3); + renderer.destroy(); +}); + test('evidence going from none to empty removes the drape', () => { const { renderer, globe } = fixture(); - renderer.showSlot('a', VIIRS, FIJI_BOX); + renderer.showSlot('a', S30, FIJI_BOX); assert.equal(globe.layers.length, 2); assert.equal( - renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [] }), + renderer.showSlot('a', S30, FIJI_BOX, { availableBoxes: [] }), false, ); assert.equal(globe.layers.length, 0); renderer.destroy(); }); +test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => { + const renderer = createRecentImageryRenderer(); + const globe = fakeGlobePort(); + renderer.rebind({ collection: {}, kind: 'globe', globe }); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + const keyOf = (box) => [box.west, box.south, box.east, box.north].join(','); + const layerFor = (box) => + globe.layers.find((layer) => keyOf(layer.spec.rectangle) === keyOf(box)); + + // An HLS day drapes both halves before its probe answers. + renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' }); + const kept = layerFor(west); + assert.ok(kept); + const added = globe.added.length; + + // The probe confirms the east half empty: only the east layer goes. + renderer.showSlot('a', S30, FIJI_BOX, { + alpha: 0.4, + splitDirection: 'left', + availableBoxes: [west], + }); + assert.equal(kept.removed, false, 'the west layer survives the narrowing'); + assert.equal(globe.added.length, added, 'narrowing adds no layer'); + assert.equal(layerFor(east), undefined); + + // A later probe admits east again: only the east layer is added. + renderer.showSlot('a', S30, FIJI_BOX, { + alpha: 0.4, + splitDirection: 'left', + availableBoxes: [west, east], + }); + assert.equal(kept.removed, false, 'the west layer survives the widening'); + assert.equal(globe.added.length, added + 1); + assert.equal(kept.alpha, 0.4); + assert.equal(kept.split, 'left'); + renderer.destroy(); +}); + test('the drag preview draws a wrapped fill and outline across the dateline', async () => { const draw = fakeDrawPort(); let box = { west: 179, south: 0, east: 179, north: 0 }; diff --git a/src/layers/recentImagery/slot-order-widening.test.mjs b/src/layers/recentImagery/slot-order-widening.test.mjs new file mode 100644 index 0000000000..3a46c289ba --- /dev/null +++ b/src/layers/recentImagery/slot-order-widening.test.mjs @@ -0,0 +1,37 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createRecentImageryRenderer } from './rendering.js'; +import { nonCrossingBoxes } from './model.js'; +import { FIJI_BOX } from './testDoubles.mjs'; +import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; + +const A = { key: 'S30:2026-09-18', product: 'S30', day: '2026-09-18' }; +const B = { key: 'L30:2026-09-16', product: 'L30', day: '2026-09-16' }; + +test('slot order survives widening', () => { + const renderer = createRecentImageryRenderer(); + const globe = fakeGlobePort(); + renderer.rebind({ collection: {}, kind: 'globe', globe }); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + const k = (b) => [b.west, b.south, b.east, b.north].join(','); + const look = { alpha: 1, splitDirection: 'none' }; + renderer.showSlot('a', A, FIJI_BOX, { ...look, availableBoxes: [west] }); + renderer.showSlot('b', B, FIJI_BOX, { + ...look, + availableBoxes: [west, east], + }); + renderer.showSlot('a', A, FIJI_BOX, { + ...look, + availableBoxes: [west, east], + }); + const topOn = (box) => { + const on = globe.layers.filter((l) => k(l.spec.rectangle) === k(box)); + return on.at(-1).spec.url.includes('S30') ? 'A' : 'B'; + }; + assert.equal( + topOn(west), + topOn(east), + `west top ${topOn(west)}, east top ${topOn(east)}`, + ); + renderer.destroy(); +}); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 85d0f2d2eb..f1c89c0a71 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -127,8 +127,8 @@ function withHalves(response, { presentBoxes, emptyBoxes }) { * Thumbnail responses must expose Data-Present: true for image admission, or * false for confirmed empty coverage, including injected getThumbnail sources. * getThumbnail also sets presentBoxes and emptyBoxes (see withHalves). - * Without per-half evidence the renderer drapes every side of a dateline - * box, so an empty side of a VIIRS JPEG then draws black. + * Without per-half evidence the renderer drapes every side of an HLS + * dateline box and no side of a VIIRS one. */ export function createRecentImagerySource({ fetchImpl = (...args) => globalThis.fetch(...args), diff --git a/src/layers/recentImagery/testDoubles.mjs b/src/layers/recentImagery/testDoubles.mjs index 5dabc53bcb..d38d207034 100644 --- a/src/layers/recentImagery/testDoubles.mjs +++ b/src/layers/recentImagery/testDoubles.mjs @@ -23,48 +23,6 @@ export const FIJI_BOX = Object.freeze({ north: -17, }); -/** A provider whose tile requests stay pending until the test settles them. */ -class UrlTemplateImageryProvider { - constructor(options) { - this.options = options; - this.calls = []; - this.pending = []; - } - requestImage(x, y, level) { - this.calls.push([x, y, level]); - return new Promise((resolve) => this.pending.push(resolve)); - } -} - -export function fakeCesium(requestImage) { - class Provider extends UrlTemplateImageryProvider {} - if (requestImage) Provider.prototype.requestImage = requestImage; - return { - UrlTemplateImageryProvider: Provider, - WebMercatorTilingScheme: class {}, - Rectangle: { - fromDegrees: (west, south, east, north) => ({ west, south, east, north }), - }, - SplitDirection: { LEFT: -1, NONE: 0, RIGHT: 1 }, - }; -} - -export function fakeCollection() { - const layers = []; - return { - layers, - addImageryProvider(provider) { - const layer = { provider, alpha: 1, splitDirection: 0 }; - layers.push(layer); - return layer; - }, - remove(layer, destroy) { - layers.splice(layers.indexOf(layer), 1); - layer.destroyed = destroy; - }, - }; -} - export const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); /** Timers that fire only when the test says so. */ diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index ec1ff26862..be02b7a58b 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -16,6 +16,7 @@ const EMPTY = Object.freeze({ objectUrl: null, acquisitionTime: null, availableBoxes: null, + emptyBoxes: null, loading: false, }); @@ -157,6 +158,7 @@ export function createThumbnailLoader({ entry.status = status; entry.acquisitionTime = acquisitionTime; entry.availableBoxes = availableBoxes; + entry.emptyBoxes = emptyBoxes; } entry.objectUrl = objectUrl; touch(entry); @@ -221,6 +223,7 @@ export function createThumbnailLoader({ objectUrl: null, acquisitionTime: null, availableBoxes: null, + emptyBoxes: null, loading: false, controller: null, touched: 0, @@ -297,7 +300,7 @@ export function createThumbnailLoader({ /** * Read a day's state. A read is not a use: it never changes residency. * @param {string} key Candidate key. - * @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array | null, loading: boolean }} + * @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array | null, emptyBoxes: Array | null, loading: boolean }} */ get(key) { const entry = entries.get(key); @@ -307,6 +310,7 @@ export function createThumbnailLoader({ objectUrl: entry.objectUrl, acquisitionTime: entry.acquisitionTime, availableBoxes: entry.availableBoxes, + emptyBoxes: entry.emptyBoxes, loading: entry.loading, }; }, diff --git a/src/layers/recentImagery/thumbnails.test.mjs b/src/layers/recentImagery/thumbnails.test.mjs index d98ed59ea3..e5843dea6e 100644 --- a/src/layers/recentImagery/thumbnails.test.mjs +++ b/src/layers/recentImagery/thumbnails.test.mjs @@ -65,6 +65,7 @@ test('Data-Present decides the day: present with an object URL and sensing time, objectUrl: 'blob:1', acquisitionTime: '2026-09-18T17:12:00Z', availableBoxes: [BOX], + emptyBoxes: [], loading: false, }); assert.equal(loader.get('L30:2026-09-16').status, 'empty'); diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.js index 78e9a9320f..da2ecc1206 100644 --- a/src/ui/recentImagery.js +++ b/src/ui/recentImagery.js @@ -136,14 +136,16 @@ function coverageText(coverage) { return t('unknown'); } -/** A present day covers the box only in part when its probe omits a side. */ +/** A confirmed-empty side means partial coverage. An unanswered side leaves coverage unknown. */ function shownCoverage(candidate, box) { - const drapes = candidate.thumbnail?.availableBoxes; - return candidate.thumbnail?.status === 'present' && - Array.isArray(drapes) && - drapes.length < nonCrossingBoxes(box).length - ? 'partial' - : candidate.coverage; + const { status, availableBoxes, emptyBoxes } = candidate.thumbnail ?? {}; + if ( + status !== 'present' || + !Array.isArray(availableBoxes) || + availableBoxes.length >= nonCrossingBoxes(box).length + ) + return candidate.coverage; + return emptyBoxes?.length ? 'partial' : 'unknown'; } function cloudText(candidate) { diff --git a/src/ui/recentImagery.test.mjs b/src/ui/recentImagery.test.mjs index fce1e3590c..7a114ea6c0 100644 --- a/src/ui/recentImagery.test.mjs +++ b/src/ui/recentImagery.test.mjs @@ -1066,7 +1066,7 @@ test('DETAILS is a collapsed rail card holding every note, and the empty-days to assert.equal(article.dataset.open, 'false'); }); -test('DETAILS shows partial coverage when a present dateline day drapes one half', async () => { +test('DETAILS shows partial coverage for a dateline day with one side empty, unknown when a side did not answer', async () => { const f = fixture(); f.layer.enable(); f.layer.setBox(FIJI_BOX); @@ -1074,10 +1074,21 @@ test('DETAILS shows partial coverage when a present dateline day drapes one half await settle(); assert.match(f.byId('ri-details').textContent, /Coverage full/); const get = f.thumbnails.get; - const [west] = nonCrossingBoxes(FIJI_BOX); - f.thumbnails.get = (key) => ({ ...get(key), availableBoxes: [west] }); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + f.thumbnails.get = (key) => ({ + ...get(key), + availableBoxes: [west], + emptyBoxes: [east], + }); f.thumbnails.probe(f.snap().focus.key, 'present'); assert.match(f.byId('ri-details').textContent, /Coverage partial/); + f.thumbnails.get = (key) => ({ + ...get(key), + availableBoxes: [west], + emptyBoxes: [], + }); + f.thumbnails.probe(f.snap().focus.key, 'present'); + assert.match(f.byId('ri-details').textContent, /Coverage unknown/); }); test('the body scroll position survives renders even when DOM mutations reset it', async () => { From 1f64a9ce44807bad704f9bedf307cf3702fc931b Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 19:20:49 +0400 Subject: [PATCH 16/18] fix(recent-imagery): keep HLS drapes and empty halves steady when a probe gives no answer - A Worldview 200 without Data-Present no longer takes an HLS day already on the map off it: the source reports only the halves that answered, and the renderer drapes a PNG on every part not confirmed empty. - A re-probe keeps the last explicit answer for each half, so a side confirmed empty stays undraped when it does not answer again. - A host change noticed while rendering after a probe sends a full notification, so the panel updates the divider. - Tests: the short-arc refusal asserts the measured box, the widening test expects slot B on top on both sides, and the drape-policy cases are one table; the widening test moves into rendering.test.mjs. - Shared box key and Data-Present parsing; transport errors pass through unchanged; unreachable guards and repeated comments removed; docs describe partial vs. unknown coverage. --- docs/CURRENT-STATE.md | 6 +- .../recentImagery/hlsMissingHeader.test.mjs | 71 ++++++++++ .../recentImagery/hlsRemembersEmpty.test.mjs | 104 +++++++++++++++ src/layers/recentImagery/index.js | 11 +- src/layers/recentImagery/model.js | 5 + src/layers/recentImagery/model.test.mjs | 6 +- src/layers/recentImagery/rendering.js | 44 ++++--- src/layers/recentImagery/rendering.test.mjs | 46 ++++++- .../slot-order-widening.test.mjs | 37 ------ src/layers/recentImagery/source.js | 82 ++++-------- src/layers/recentImagery/source.test.mjs | 123 ++++-------------- src/layers/recentImagery/thumbnails.js | 36 ++--- src/tools/queries/imagery.js | 2 +- src/tools/queries/imagery.test.mjs | 2 +- src/ui/imageryBoxTool.js | 2 +- src/ui/imageryBoxTool.test.mjs | 13 +- src/ui/recentImagery.js | 7 - src/ui/recentImagery.test.mjs | 3 +- src/ui/recentImageryNotice.test.mjs | 20 +-- 19 files changed, 348 insertions(+), 272 deletions(-) create mode 100644 src/layers/recentImagery/hlsMissingHeader.test.mjs create mode 100644 src/layers/recentImagery/hlsRemembersEmpty.test.mjs delete mode 100644 src/layers/recentImagery/slot-order-widening.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8fc47c95ea..02f2a7eec2 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -8864,10 +8864,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool, pins and share links already supply complete boxes. - The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. -- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, a box across the dateline sent as one bounding box with west > east, which CMR reads as the short box, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. -- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the dateline: Worldview snapshots cannot`) refuse a dateline box without requesting one. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. CMR gets a box across the dateline as one bounding box with west > east and reads it as the short box. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the antimeridian`) refuse a dateline box without requesting one. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. When that day probes empty the next ranked day takes over, and focus still on the empty day moves with it, so the successor drapes once its probe says present; a day the user picked meanwhile, still being probed or debounced, keeps the slot instead (and the Esri lease while it waits), and if that pick probes empty, fails, loses its source or gives way to an empty card the hand-over goes ahead. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. -- **Rendering.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when fewer sides drape than the box contains. Thumbnails: three days probed at once (two fetches each for a dateline box), sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe. +- **Rendering.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof, present or empty, for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when a side is confirmed empty and `unknown` when a side is only unproven. Thumbnails: three days probed at once (two fetches each for a dateline box), sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. - **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once. - **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). diff --git a/src/layers/recentImagery/hlsMissingHeader.test.mjs b/src/layers/recentImagery/hlsMissingHeader.test.mjs new file mode 100644 index 0000000000..17c84ec69c --- /dev/null +++ b/src/layers/recentImagery/hlsMissingHeader.test.mjs @@ -0,0 +1,71 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { until } from '../../testSupport/kartaViewFakes.mjs'; +import { createRecentImagerySource } from './source.js'; +import { createThumbnailLoader } from './thumbnails.js'; +import { createRecentImageryLayer } from './index.js'; +import { createRecentImageryRenderer } from './rendering.js'; +import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; +import { candidate } from './testDoubles.mjs'; + +const PLAIN = { west: -98, south: 30, east: -97, north: 31 }; +const answer = (present) => + new Response('img', { + headers: present === null ? {} : { 'Data-Present': String(present) }, + }); + +function realLayer({ fetchImpl, candidates, maxDecoded = 16 }) { + const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs: 5000 }); + let nextUrl = 0; + const loader = createThumbnailLoader({ + requestThumbnail: source.getThumbnail, + createObjectUrl: () => `blob:${++nextUrl}`, + revokeObjectUrl: () => {}, + maxDecoded, + }); + const globe = fakeGlobePort(); + const layer = createRecentImageryLayer({ + catalog: { + searchHls: async () => ({ candidates, truncated: false, errors: [] }), + }, + renderer: createRecentImageryRenderer(), + thumbnails: loader, + host: () => ({ collection: globe.imagery, kind: 'globe' }), + globeOf: () => globe, + now: () => new Date('2026-11-13T15:00:00Z'), + }); + layer.init({ camera: {} }); + return { layer, loader, globe }; +} + +test('hls-missing-header: a shown HLS day on a plain box stays on the map after a 200 without Data-Present', async () => { + const day = candidate('S30', '2026-11-10'); + let release; + const gate = new Promise((r) => (release = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day], + fetchImpl: async () => { + await gate; + return answer(null); + }, + }); + layer.enable(); + layer.setBox(PLAIN); + assert.equal( + await until(() => globe.layers.length === 1, { ticks: 2000 }), + true, + ); + release(); + assert.equal( + await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }), + true, + ); + await until(() => false, { ticks: 50 }); + const shownA = layer.getSnapshot().shown.a; + assert.equal( + globe.layers.length, + 1, + `layers=${globe.layers.length} shown.a=${shownA} availableBoxes=${JSON.stringify(loader.get(day.key).availableBoxes)}`, + ); + layer.destroy(); +}); diff --git a/src/layers/recentImagery/hlsRemembersEmpty.test.mjs b/src/layers/recentImagery/hlsRemembersEmpty.test.mjs new file mode 100644 index 0000000000..8973ca3ef8 --- /dev/null +++ b/src/layers/recentImagery/hlsRemembersEmpty.test.mjs @@ -0,0 +1,104 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { until } from '../../testSupport/kartaViewFakes.mjs'; +import { createRecentImagerySource } from './source.js'; +import { createThumbnailLoader } from './thumbnails.js'; +import { nonCrossingBoxes } from './model.js'; +import { createRecentImageryLayer } from './index.js'; +import { createRecentImageryRenderer } from './rendering.js'; +import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; +import { FIJI_BOX, candidate } from './testDoubles.mjs'; + +const sideOf = (url) => + Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0 + ? 'west' + : 'east'; +const answer = (present) => + new Response('img', { + headers: present === null ? {} : { 'Data-Present': String(present) }, + }); + +function realLayer({ fetchImpl, candidates, maxDecoded = 16 }) { + const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs: 5000 }); + let nextUrl = 0; + const loader = createThumbnailLoader({ + requestThumbnail: source.getThumbnail, + createObjectUrl: () => `blob:${++nextUrl}`, + revokeObjectUrl: () => {}, + maxDecoded, + }); + const globe = fakeGlobePort(); + const layer = createRecentImageryLayer({ + catalog: { + searchHls: async () => ({ candidates, truncated: false, errors: [] }), + }, + renderer: createRecentImageryRenderer(), + thumbnails: loader, + host: () => ({ collection: globe.imagery, kind: 'globe' }), + globeOf: () => globe, + now: () => new Date('2026-11-13T15:00:00Z'), + }); + layer.init({ camera: {} }); + return { layer, loader, globe }; +} + +test('hls-remembers-empty: a re-probe with one failed half keeps that half confirmed empty', async () => { + const day1 = candidate('S30', '2026-11-10'); + const day2 = candidate('S30', '2026-11-11'); + let eastCalls = 0; + let releaseDay2; + const gate = new Promise((r) => (releaseDay2 = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day2, day1], + maxDecoded: 1, + fetchImpl: async (url) => { + if (new URL(url).searchParams.get('TIME') === day2.day) { + await gate; + return answer(true); + } + if (sideOf(url) === 'east') { + eastCalls += 1; + if (eastCalls === 1) return answer(false); + throw new TypeError('Failed to fetch'); + } + return answer(true); + }, + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day1.key).status === 'present', { + ticks: 2000, + }), + true, + ); + const [west] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual(loader.get(day1.key).availableBoxes, [west]); + assert.equal(loader.get(day1.key).emptyBoxes.length, 1); + releaseDay2(); + assert.equal( + await until(() => loader.get(day2.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).objectUrl, null); + layer.setAssignment('a', day1.key); + assert.equal( + await until(() => eastCalls === 2 && !loader.get(day1.key).loading, { + ticks: 2000, + }), + true, + ); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day1.key); + assert.deepEqual( + { + available: entry.availableBoxes.length, + empty: entry.emptyBoxes.length, + layers: globe.layers.length, + }, + { available: 1, empty: 1, layers: 1 }, + ); + layer.destroy(); +}); diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.js index 3ec1476564..ace8d8d7cb 100644 --- a/src/layers/recentImagery/index.js +++ b/src/layers/recentImagery/index.js @@ -581,6 +581,8 @@ export function createRecentImageryLayer({ for (const slotId of SLOT_IDS) { const candidate = candidateFor(shown[slotId]); if (candidate && _hostInfo.collection) { + const { availableBoxes, emptyBoxes } = + thumbnails.get(candidate.key) ?? {}; renderer.showSlot(slotId, candidate, _box, { alpha: _alpha, splitDirection: !live @@ -588,8 +590,8 @@ export function createRecentImageryLayer({ : (slotId === 'a') !== _swapped ? 'left' : 'right', - // The halves the probe lets this product drape, unknown before it answers. - availableBoxes: thumbnails.get(candidate.key)?.availableBoxes, + availableBoxes, + emptyBoxes, }); } else { renderer.hideSlot(slotId); @@ -904,16 +906,17 @@ export function createRecentImageryLayer({ _followKey === _focusKey && drapable(candidateFor(_followKey)) && applyPreview(_followKey); - // A pinned or previewed day that was still being probed drapes now. const shown = plan(); const owned = renderer.getOwned?.() || {}; const drapesChanged = SLOT_IDS.some( (slotId) => (owned[slotId]?.key || null) !== shown[slotId], ); // One render per probe: the key can stay the same while its halves change. + // A host found moved changes the divider, so the panel renders in full. + const moved = !followed && syncHost(); if (!followed) syncRender(); notify('thumbnail'); - if (pruned || followed || drapesChanged) notify(); + if (pruned || followed || drapesChanged || moved) notify(); }); syncHost(); if (_box && !_candidates.length) void runSearch(); diff --git a/src/layers/recentImagery/model.js b/src/layers/recentImagery/model.js index 87c2331019..2ef7255b32 100644 --- a/src/layers/recentImagery/model.js +++ b/src/layers/recentImagery/model.js @@ -120,10 +120,15 @@ export function lonSpanDeg(west, east) { return east >= west ? east - west : east + 360 - west; } +/** A comparable key for a degrees box. */ +export const boxKey = (box) => + [box.west, box.south, box.east, box.north].map(Number).join(','); + /** * One or two boxes with west <= east that cover the same area. A dateline * box is split at ±180 so each side is a plain rectangle for a draped layer * or a Worldview request. A box with a missing or nonfinite edge is []. + * So is a dateline box of zero width (west 180, east -180). * @param {object} box Degrees box. * @returns {Array} */ diff --git a/src/layers/recentImagery/model.test.mjs b/src/layers/recentImagery/model.test.mjs index 8933032e1b..f99a20ef54 100644 --- a/src/layers/recentImagery/model.test.mjs +++ b/src/layers/recentImagery/model.test.mjs @@ -528,7 +528,11 @@ test('boxFromPin returns the short-arc box for a pin near the dateline', () => { (lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half, ), ); - assert.equal(nonCrossingBoxes(box).length, 2, 'splits for tiling and CMR'); + assert.equal( + nonCrossingBoxes(box).length, + 2, + 'splits for tiling and Worldview', + ); assert.ok( Math.abs( Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon), diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index f7635f95fd..ca18900688 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -17,6 +17,7 @@ import { markBaseTileset } from '../../render/baseTilesets.js'; import { drawOf } from '../../render/rendererOf.js'; import { PRODUCTS, + boxKey, gibsTemplate, lonSpanDeg, nonCrossingBoxes, @@ -34,25 +35,26 @@ function clampAlpha(value) { return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1; } -const boxKey = (box) => - [box.west, box.south, box.east, box.north].map(Number).join(','); - /** One comparable key for a slot's draped parts. */ const partsKey = (parts) => parts.map(boxKey).sort().join(';'); /** - * Without per-half evidence a dateline JPEG waits for the probe because - * an empty side would draw black. Other boxes drape all their parts. - * With evidence, only the listed parts of this box drape. + * The parts of a box a slot drapes. The VIIRS JPEG has no alpha and would + * draw an empty side black, so it drapes only parts Worldview confirmed + * present, and no part of a dateline box before the probe answers. A PNG + * drapes every part not confirmed empty. */ -function drapedParts(candidate, box, availableBoxes) { +function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) { const parts = nonCrossingBoxes(box); - if (!Array.isArray(availableBoxes)) - return parts.length > 1 && PRODUCTS[candidate.product]?.format === 'jpg' - ? [] - : parts; - const listed = new Set(availableBoxes.filter(Boolean).map(boxKey)); - return parts.filter((part) => listed.has(boxKey(part))); + const keys = (list) => new Set(list.map(boxKey)); + if (PRODUCTS[candidate.product]?.format !== 'jpg') { + if (!Array.isArray(emptyBoxes)) return parts; + const empty = keys(emptyBoxes); + return parts.filter((part) => !empty.has(boxKey(part))); + } + if (!Array.isArray(availableBoxes)) return parts.length > 1 ? [] : parts; + const proven = keys(availableBoxes); + return parts.filter((part) => proven.has(boxKey(part))); } /** @@ -157,20 +159,24 @@ export function createRecentImageryRenderer({ return { /** - * Drape the available parts of a candidate into a slot. On the same day - * and port, keep each surviving layer, add a new part right above it and - * remove dropped parts. + * Drape the parts of a candidate's box that the evidence allows (see drapedParts). + * The same candidate on the same port keeps the layer of each unchanged part. * @param {'a'|'b'} slotId * @param {object} candidate * @param {object} box Degrees box. - * @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null }} [look] + * @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look] * @returns {boolean} Whether a layer is now draped for the slot. */ showSlot( slotId, candidate, box, - { alpha = 1, splitDirection = 'none', availableBoxes = null } = {}, + { + alpha = 1, + splitDirection = 'none', + availableBoxes = null, + emptyBoxes = null, + } = {}, ) { if (destroyed || !candidate?.key || !box) return false; if (!host.globe) { @@ -179,7 +185,7 @@ export function createRecentImageryRenderer({ } const current = owned[slotId]; const look = { alpha: clampAlpha(alpha), split: splitDirection }; - const parts = drapedParts(candidate, box, availableBoxes); + const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes }); if ( current && current.globe === host.globe && diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index 7289b746b5..8abafc5f6e 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -6,7 +6,7 @@ import { createRecentImageryRenderer, } from './rendering.js'; import { fromDegrees } from '../../geo/ellipsoid.js'; -import { nonCrossingBoxes } from './model.js'; +import { boxKey, nonCrossingBoxes } from './model.js'; import { BOX, FIJI_BOX } from './testDoubles.mjs'; import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; @@ -363,13 +363,35 @@ test('evidence going from none to empty removes the drape', () => { renderer.showSlot('a', S30, FIJI_BOX); assert.equal(globe.layers.length, 2); assert.equal( - renderer.showSlot('a', S30, FIJI_BOX, { availableBoxes: [] }), + renderer.showSlot('a', S30, FIJI_BOX, { + availableBoxes: [], + emptyBoxes: nonCrossingBoxes(FIJI_BOX), + }), false, ); assert.equal(globe.layers.length, 0); renderer.destroy(); }); +test('an HLS dateline day drapes every half not confirmed empty, a VIIRS one only the confirmed halves', () => { + const [west, east] = nonCrossingBoxes(FIJI_BOX); + for (const [product, expected] of [ + [S30, [west, east]], + [VIIRS, [east]], + ]) { + const { renderer, globe } = fixture(); + renderer.showSlot('a', product, FIJI_BOX, { + availableBoxes: [east], + emptyBoxes: [], + }); + assert.deepEqual( + globe.layers.map((layer) => layer.spec.rectangle), + expected, + ); + renderer.destroy(); + } +}); + test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => { const renderer = createRecentImageryRenderer(); const globe = fakeGlobePort(); @@ -390,6 +412,7 @@ test('a probe that narrows or widens a dateline drape keeps the layer of the unc alpha: 0.4, splitDirection: 'left', availableBoxes: [west], + emptyBoxes: [east], }); assert.equal(kept.removed, false, 'the west layer survives the narrowing'); assert.equal(globe.added.length, added, 'narrowing adds no layer'); @@ -400,6 +423,7 @@ test('a probe that narrows or widens a dateline drape keeps the layer of the unc alpha: 0.4, splitDirection: 'left', availableBoxes: [west, east], + emptyBoxes: [], }); assert.equal(kept.removed, false, 'the west layer survives the widening'); assert.equal(globe.added.length, added + 1); @@ -408,6 +432,24 @@ test('a probe that narrows or widens a dateline drape keeps the layer of the unc renderer.destroy(); }); +test('widening slot a over the dateline keeps it below slot b on both sides', () => { + const { renderer, globe } = fixture(); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + const topOn = (box) => + globe.layers + .filter((layer) => boxKey(layer.spec.rectangle) === boxKey(box)) + .at(-1) + .spec.url.includes('S30') + ? 'A' + : 'B'; + renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [east] }); + renderer.showSlot('b', L30, FIJI_BOX, { emptyBoxes: [] }); + assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']); + renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [] }); + assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']); + renderer.destroy(); +}); + test('the drag preview draws a wrapped fill and outline across the dateline', async () => { const draw = fakeDrawPort(); let box = { west: 179, south: 0, east: 179, north: 0 }; diff --git a/src/layers/recentImagery/slot-order-widening.test.mjs b/src/layers/recentImagery/slot-order-widening.test.mjs deleted file mode 100644 index 3a46c289ba..0000000000 --- a/src/layers/recentImagery/slot-order-widening.test.mjs +++ /dev/null @@ -1,37 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { createRecentImageryRenderer } from './rendering.js'; -import { nonCrossingBoxes } from './model.js'; -import { FIJI_BOX } from './testDoubles.mjs'; -import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; - -const A = { key: 'S30:2026-09-18', product: 'S30', day: '2026-09-18' }; -const B = { key: 'L30:2026-09-16', product: 'L30', day: '2026-09-16' }; - -test('slot order survives widening', () => { - const renderer = createRecentImageryRenderer(); - const globe = fakeGlobePort(); - renderer.rebind({ collection: {}, kind: 'globe', globe }); - const [west, east] = nonCrossingBoxes(FIJI_BOX); - const k = (b) => [b.west, b.south, b.east, b.north].join(','); - const look = { alpha: 1, splitDirection: 'none' }; - renderer.showSlot('a', A, FIJI_BOX, { ...look, availableBoxes: [west] }); - renderer.showSlot('b', B, FIJI_BOX, { - ...look, - availableBoxes: [west, east], - }); - renderer.showSlot('a', A, FIJI_BOX, { - ...look, - availableBoxes: [west, east], - }); - const topOn = (box) => { - const on = globe.layers.filter((l) => k(l.spec.rectangle) === k(box)); - return on.at(-1).spec.url.includes('S30') ? 'A' : 'B'; - }; - assert.equal( - topOn(west), - topOn(east), - `west top ${topOn(west)}, east top ${topOn(east)}`, - ); - renderer.destroy(); -}); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index f1c89c0a71..5c61edf468 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -1,10 +1,5 @@ import { searchHls } from './catalog.js'; -import { - PRODUCTS, - gibsTemplate, - nonCrossingBoxes, - wvsSnapshotUrl, -} from './model.js'; +import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js'; /** * Deadline for one half's response headers, so a day whose other half @@ -15,42 +10,20 @@ const DEFAULT_HALF_DEADLINE_MS = 15_000; /** * Worldview Snapshots rejects a BBOX with west > east, so a dateline box is * probed as its two non-crossing halves, wider first. A plain box is its - * one normalized half. Granules do not cross ±180, so a day has data when - * either half does. + * one normalized half. A day has data when either half does. */ function requestBoxes(box) { - const halves = nonCrossingBoxes(box); - if (!halves.length) return [box]; - return halves.sort((a, b) => b.east - b.west - (a.east - a.west)); + return nonCrossingBoxes(box).sort( + (a, b) => b.east - b.west - (a.east - a.west), + ); } -const isPresent = (response) => dataPresent(response) === 'true'; - -/** - * Which halves a product may drape. The VIIRS JPEG has no alpha and would - * drape an empty side as a black rectangle, so it drapes only a half - * Worldview confirmed present. An HLS PNG drapes every half not confirmed empty. - */ -const drapesOnlyProven = (candidate) => - PRODUCTS[candidate?.product]?.format === 'jpg'; - -const dataPresent = (response) => +/** A response's Data-Present answer in lower case, or '' when it failed or has none. */ +export const dataPresent = (response) => response?.ok ? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase() : ''; -/** - * Of the halves that answered, prefer the first with data (wider wins a - * tie), then the first not confirmed empty so an unreadable answer is - * never called empty, then the first response. - */ -function combineHalves(responses) { - const present = responses.find(isPresent); - if (present) return present; - const unproven = responses.find((r) => dataPresent(r) !== 'false'); - return unproven ?? responses[0]; -} - /** * One half's snapshot fetch, raced against its own deadline so a half that * never answers, even over a transport that ignores AbortSignal, still @@ -109,12 +82,11 @@ function probeHalf( } /** - * Non-enumerable evidence for the box's non-crossing halves. presentBoxes - * lists the halves this product may drape (see drapesOnlyProven). - * emptyBoxes lists the halves Worldview confirmed empty. + * Non-enumerable per-half evidence for the box's non-crossing halves: + * presentBoxes lists the halves Worldview confirmed present, emptyBoxes + * the halves it confirmed empty. What drapes is decided by drapedParts in rendering.js. */ function withHalves(response, { presentBoxes, emptyBoxes }) { - if (!response) return response; Object.defineProperties(response, { presentBoxes: { value: presentBoxes, configurable: true }, emptyBoxes: { value: emptyBoxes, configurable: true }, @@ -172,30 +144,20 @@ export function createRecentImagerySource({ const answers = results.map((result) => result.status === 'fulfilled' ? dataPresent(result.value) : null, ); - const responses = results - .filter((result) => result.status === 'fulfilled') - .map((result) => result.value); - const halvesWhere = (keep) => halves.filter((_, i) => keep(answers[i])); - const emptyBoxes = halvesWhere((answer) => answer === 'false'); - if (answers.includes('true')) - return withHalves(combineHalves(responses), { - presentBoxes: halvesWhere( - drapesOnlyProven(candidate) - ? (answer) => answer === 'true' - : (answer) => answer !== 'false', - ), - emptyBoxes, - }); // A missing answer is an error unless another half proved data. const failure = results.find((result) => result.status === 'rejected'); - if (failure) { - if (failure.reason?.name === 'TimeoutError') - throw new DOMException('Thumbnail request timed out', 'TimeoutError'); - throw new Error('Thumbnail request failed'); - } - return withHalves(combineHalves(responses), { - presentBoxes: [], - emptyBoxes, + if (failure && !answers.includes('true')) throw failure.reason; + // Show the first half with data (the wider wins a tie), else the first + // not confirmed empty, so an unreadable answer is never called empty. + // Every half answered here unless one proved data. + let shown = answers.indexOf('true'); + if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false'); + if (shown < 0) shown = 0; + const halvesWhere = (value) => + halves.filter((_, i) => answers[i] === value); + return withHalves(results[shown].value, { + presentBoxes: halvesWhere('true'), + emptyBoxes: halvesWhere('false'), }); }, getTileTemplate: (product, day) => tileTemplate(product, day), diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index 59d6ecb455..f573c1f711 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -55,6 +55,7 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt test('cancelled thumbnail acquisition does not return stale responses or retry', async () => { const controller = new AbortController(); + const box = { west: 0, south: 0, east: 1, north: 1 }; let calls = 0; const source = createRecentImagerySource({ thumbnailUrl: () => 'https://imagery.example/thumbnail', @@ -65,11 +66,11 @@ test('cancelled thumbnail acquisition does not return stale responses or retry', }, }); await assert.rejects( - source.getThumbnail({}, {}, { signal: controller.signal }), + source.getThumbnail({}, box, { signal: controller.signal }), { name: 'AbortError' }, ); await assert.rejects( - source.getThumbnail({}, {}, { signal: controller.signal }), + source.getThumbnail({}, box, { signal: controller.signal }), { name: 'AbortError' }, ); assert.equal(calls, 1); @@ -197,85 +198,28 @@ test('a rejected half does not hide data on the other half, and never reads as e }); await assert.rejects( failing.source.getThumbnail(candidate, NARROW_WEST), - /Thumbnail request failed/, + /network/, ); }); -test('a JPEG product drapes only the half Worldview confirmed present: a rejected half is not draped', async () => { - const { source } = halvesSource({ - '-180/-179': new Error('network'), - '179.9/180': dated('true', 'narrow'), - }); - const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); - assert.equal( - response.headers.get('Data-Present'), - 'true', - 'the day itself stays present', - ); - assert.deepEqual( - response.presentBoxes, - [NARROW_BOX], - 'the failed half is not draped', - ); -}); - -test('a JPEG product does not drape a half whose probe hung', async () => { - const requested = []; - const source = createRecentImagerySource({ - thumbnailUrl: ({ box }) => { - requested.push(box); - return `https://imagery.example/${box.west}/${box.east}`; - }, - halfDeadlineMs: 20, - fetchImpl: async (url) => { - const answer = { - '-180/-179': () => new Promise(() => {}), - '179.9/180': () => dated('true', 'narrow'), - }[url.split('imagery.example/')[1]]; - return answer(); - }, - }); - const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); - assert.equal(requested.length, 2, 'both halves were requested'); - assert.equal( - response.headers.get('Data-Present'), - 'true', - 'the day itself stays present', - ); - assert.deepEqual( - response.presentBoxes, - [NARROW_BOX], - 'the hung half is not draped', - ); -}); - -test('a JPEG product does not drape a half that answered with an unknown presence', async () => { - const { source } = halvesSource({ - '-180/-179': dated('unknown', 'maybe'), - '179.9/180': dated('true', 'narrow'), - }); - const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); - assert.equal(response.headers.get('Data-Present'), 'true'); - assert.deepEqual( - response.presentBoxes, - [NARROW_BOX], - 'an unproven half is not draped', - ); -}); - -test('a PNG product keeps an unknown or failed half: alpha hides it', async () => { - const { source } = halvesSource({ - '-180/-179': new Error('network'), - '179.9/180': dated('true', 'narrow'), - }); - const response = await source.getThumbnail(candidate, NARROW_WEST); - assert.equal(await response.text(), 'narrow'); - assert.deepEqual( - response.presentBoxes, - [WIDE_BOX, NARROW_BOX], - 'a PNG keeps the unproven half', - ); -}); +for (const [label, answer] of [ + ['rejected', new Error('network')], + ['hung', () => new Promise(() => {})], + ['answered without a presence', () => dated('unknown', 'maybe')], +]) { + for (const product of [JPEG_CANDIDATE, candidate]) { + test(`a ${product.product} half that ${label} is neither present nor empty`, async () => { + const { source } = halvesSource( + { '-180/-179': answer, '179.9/180': () => dated('true', 'narrow') }, + { halfDeadlineMs: 20 }, + ); + const response = await source.getThumbnail(product, NARROW_WEST); + assert.equal(response.headers.get('Data-Present'), 'true'); + assert.deepEqual(response.presentBoxes, [NARROW_BOX]); + assert.deepEqual(response.emptyBoxes, []); + }); + } +} test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => { const controller = new AbortController(); @@ -339,26 +283,3 @@ test('a successful probe leaves no deadline timer behind', async () => { assert.equal(timers.armed(), 0); assert.equal(timers.cleared.length, 2); }); - -test('transport rejection does not expose untrusted error details', async () => { - const marker = 'synthetic-secret-do-not-expose-ABC123'; - const source = createRecentImagerySource({ - thumbnailUrl: () => 'https://example.invalid/', - fetchImpl: () => { - throw new Error(marker); - }, - }); - await assert.rejects( - source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), - (error) => { - assert.equal(error.message, 'Thumbnail request failed'); - assert.equal( - `${error.stack} ${JSON.stringify(error)} ${error.cause}`.includes( - marker, - ), - false, - ); - return true; - }, - ); -}); diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index be02b7a58b..41ec83cd35 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -1,6 +1,6 @@ /** * Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per - * candidate day. The response's `Data-Present` header is the only proof that + * candidate day (one per side of a dateline box). The response's `Data-Present` header is the only proof that * a day has pixels in the box (GIBS answers an empty tile with HTTP 200), and * `Acquisition-Time` carries the sensing time. Fetches are bounded, and so * are decoded images: residency is least-recently-USED, where a request or a @@ -8,8 +8,8 @@ * card on every render, so a read that counted would evict the visible cards * first). Eviction revokes the image only; what the probe proved is kept. */ -import { thumbnailOrder } from './model.js'; -import { createRecentImagerySource } from './source.js'; +import { boxKey, thumbnailOrder } from './model.js'; +import { createRecentImagerySource, dataPresent } from './source.js'; const EMPTY = Object.freeze({ status: 'unknown', @@ -20,14 +20,16 @@ const EMPTY = Object.freeze({ loading: false, }); -const halfKey = (box) => [box.west, box.south, box.east, box.north].join(','); - -/** Keep earlier proof on a re-probe unless the new answer confirms that half empty. */ -function keepProvenHalves(previous, next, empty) { - if (!Array.isArray(previous) || !Array.isArray(next) || !Array.isArray(empty)) +/** On a re-probe, keep earlier halves of one answer (present or empty) unless the new probe answered them the other way. */ +function keepProvenHalves(previous, next, opposite) { + if ( + !Array.isArray(previous) || + !Array.isArray(next) || + !Array.isArray(opposite) + ) return next; - const drop = new Set([...next, ...empty].map(halfKey)); - return [...next, ...previous.filter((half) => !drop.has(halfKey(half)))]; + const drop = new Set([...next, ...opposite].map(boxKey)); + return [...next, ...previous.filter((half) => !drop.has(boxKey(half)))]; } /** @@ -102,7 +104,7 @@ export function createThumbnailLoader({ let status = 'error'; let objectUrl = null; let acquisitionTime = null; - // The halves the probe lets this product drape, or null without a per-half probe. + // Per-half evidence (see withHalves in source.js), or null without it. let availableBoxes = null; let emptyBoxes = null; let cancelled = false; @@ -114,9 +116,7 @@ export function createThumbnailLoader({ if (controller.signal.aborted) { cancelled = true; } else if (response?.ok) { - const present = String( - response.headers?.get?.('Data-Present') ?? '', - ).toLowerCase(); + const present = dataPresent(response); availableBoxes = response.presentBoxes ?? null; emptyBoxes = response.emptyBoxes ?? null; acquisitionTime = response.headers?.get?.('Acquisition-Time') || null; @@ -147,14 +147,16 @@ export function createThumbnailLoader({ return; } // A failed re-fetch of an evicted image keeps what the day proved. - // A re-probe drops a half only on a fresh "empty". if (status !== 'error' || entry.status !== 'present') { - if (status === 'present' && entry.status === 'present') + if (status === 'present' && entry.status === 'present') { + const fresh = availableBoxes; availableBoxes = keepProvenHalves( entry.availableBoxes, - availableBoxes, + fresh, emptyBoxes, ); + emptyBoxes = keepProvenHalves(entry.emptyBoxes, emptyBoxes, fresh); + } entry.status = status; entry.acquisitionTime = acquisitionTime; entry.availableBoxes = availableBoxes; diff --git a/src/tools/queries/imagery.js b/src/tools/queries/imagery.js index da3483a13a..2615d1a212 100644 --- a/src/tools/queries/imagery.js +++ b/src/tools/queries/imagery.js @@ -55,7 +55,7 @@ export const getRecentImagery = defineTool({ if (box.west > box.east) throw new ToolError( 'invalid_arguments', - 'The area must not cross the dateline: Worldview snapshots cannot', + 'The area must not cross the antimeridian', ); let latest; try { diff --git a/src/tools/queries/imagery.test.mjs b/src/tools/queries/imagery.test.mjs index 605a7be48a..e450d57929 100644 --- a/src/tools/queries/imagery.test.mjs +++ b/src/tools/queries/imagery.test.mjs @@ -102,7 +102,7 @@ test('overview fallback, empty results and invalid areas are reported', async () wrapped.call('get_recent_imagery', { area: { bbox: [179, 0, -179, 1] }, }), - /must not cross the dateline/, + /must not cross the antimeridian/, ); assert.equal(crossing.snapshots.length, 0); assert.equal(crossing.boxes.length, 0); diff --git a/src/ui/imageryBoxTool.js b/src/ui/imageryBoxTool.js index d6b829c0ba..df2c5e08ed 100644 --- a/src/ui/imageryBoxTool.js +++ b/src/ui/imageryBoxTool.js @@ -53,7 +53,7 @@ export function initImageryBoxTool({ const lo = Math.min(anchor.lon, corner.lon); const hi = Math.max(anchor.lon, corner.lon); // Corners more than half the globe apart are the short way round, over - // the dateline: west is the eastern corner and east the western one. + // the dateline: west gets the larger longitude, east the smaller. const crosses = hi - lo > 180; return { west: crosses ? hi : lo, diff --git a/src/ui/imageryBoxTool.test.mjs b/src/ui/imageryBoxTool.test.mjs index 19e6a7b869..ffefdc5dad 100644 --- a/src/ui/imageryBoxTool.test.mjs +++ b/src/ui/imageryBoxTool.test.mjs @@ -10,6 +10,7 @@ import { IMAGERY_BOX_POINTER_OWNER, initImageryBoxTool, } from './imageryBoxTool.js'; +import { lonSpanDeg, validateBox } from '../layers/recentImagery/model.js'; import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs'; import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js'; import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; @@ -230,11 +231,19 @@ test('a drag whose short arc is still over the size limit is refused as too larg lon: nx < 0.5 ? 100 : -100, lat: ny, }); - const f = fixture({ pickWorld }); + const refused = []; + const f = fixture({ + pickWorld, + onCancel: (reason, message, box) => refused.push({ reason, message, box }), + }); f.tool.start(); f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } }); f.fire('LEFT_UP', { position: { x: 800, y: 250 } }); assert.equal(f.boxes.length, 0); - assert.equal(f.cancels.at(-1)[0], 'too-large'); + const { reason, message, box } = refused.at(-1); + assert.equal(reason, 'too-large'); + assert.deepEqual([box.west, box.east], [100, -100], 'the short arc'); + assert.equal(lonSpanDeg(box.west, box.east), 160); + assert.equal(message, validateBox(box).message); await f.tool.destroy(); }); diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.js index da2ecc1206..9e58ca3590 100644 --- a/src/ui/recentImagery.js +++ b/src/ui/recentImagery.js @@ -529,7 +529,6 @@ export function createRecentImageryPanel({ function exportsView() { const ab = snapshot.mode === 'ab'; - // Worldview Snapshots rejects a crossing BBOX: say so up front. const crossing = Boolean( snapshot.box && snapshot.box.west > snapshot.box.east, ); @@ -781,12 +780,6 @@ export function createRecentImageryPanel({ const candidate = exportTarget(slotId); if (destroyed || !candidate || !snapshot.box || exporting.has(slotId)) return false; - // Worldview Snapshots rejects a west > east BBOX: say so, request nothing. - if (snapshot.box.west > snapshot.box.east) { - exportError = t('Select one side of the dateline'); - preserveScroll(paint); - return false; - } exporting.add(slotId); exportError = null; preserveScroll(paint); diff --git a/src/ui/recentImagery.test.mjs b/src/ui/recentImagery.test.mjs index 7a114ea6c0..06f6eabe20 100644 --- a/src/ui/recentImagery.test.mjs +++ b/src/ui/recentImagery.test.mjs @@ -992,11 +992,10 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX const crossingExport = f.byAction('export-a'); assert.equal(crossingExport.disabled, true, 'EXPORT is off up front'); assert.equal(crossingExport.title, 'Select one side of the dateline'); - // The exportImage guard stays as a backstop. assert.equal(await f.readout.exportImage('a'), false); assert.equal( f.byId('ri-notice-text').textContent, - 'Select one side of the dateline', + 'Export failed · A snapshot cannot cross the dateline', ); assert.equal( f.fetches.length, diff --git a/src/ui/recentImageryNotice.test.mjs b/src/ui/recentImageryNotice.test.mjs index 64304d5aac..a7dffa7176 100644 --- a/src/ui/recentImageryNotice.test.mjs +++ b/src/ui/recentImageryNotice.test.mjs @@ -13,26 +13,18 @@ const REFUSALS = [ 'Point the camera at the ground to use the view', // layers/recentImagery/index.js 'That point cannot anchor a box', // layers/recentImagery/index.js ...[ - [{ west: 170, south: 10, east: -170, north: 20 }, 'too-large'], - [{ west: 10, south: 80, east: 20, north: 89 }, 'polar'], - [{ west: 10, south: 10, east: 10, north: 20 }, 'degenerate'], - [{ west: 10, south: 10, east: 200, north: 20 }, 'invalid'], - [{ west: Number.NaN, south: 10, east: 20, north: 20 }, 'invalid'], - ].map(([box, reason]) => { + { west: 170, south: 10, east: -170, north: 20 }, // dateline, over the size cap + { west: 10, south: 80, east: 20, north: 89 }, + { west: 10, south: 10, east: 10, north: 20 }, + { west: 10, south: 10, east: 200, north: 20 }, + { west: Number.NaN, south: 10, east: 20, north: 20 }, + ].map((box) => { const result = validateBox(box); assert.equal(result.ok, false); - assert.equal(result.reason, reason); return result.message; }), ]; -test('a dateline box is measured on its short arc', () => { - assert.equal( - validateBox({ west: 179, south: 0, east: -179, north: 1 }).ok, - true, - ); -}); - test('en: refusals stay English', () => { setLocale('en'); for (const text of REFUSALS) { From 8604968746e15b5bdf461e068ee19649ca1f8ddb Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 20:39:51 +0400 Subject: [PATCH 17/18] fix(recent-imagery): keep a half's explicit answer when the other half's probe fails - The loader reads each half's Data-Present answer whatever the response status, and merges it before the thumbnail status rule, so a side Worldview confirmed empty stays undraped when the other side answers 503 or without the header, on a first probe and on a re-probe. - DETAILS shows partial coverage for a day with a confirmed-empty side even when its probe failed. - The dateline layer tests live in index.test.mjs on its shared fixture; the rendering test uses the model's boxKey. --- .../recentImagery/hlsMissingHeader.test.mjs | 71 ------- .../recentImagery/hlsRemembersEmpty.test.mjs | 104 ---------- src/layers/recentImagery/index.test.mjs | 190 +++++++++++++++++- src/layers/recentImagery/rendering.test.mjs | 3 +- src/layers/recentImagery/thumbnails.js | 41 ++-- src/ui/recentImagery.js | 6 +- 6 files changed, 212 insertions(+), 203 deletions(-) delete mode 100644 src/layers/recentImagery/hlsMissingHeader.test.mjs delete mode 100644 src/layers/recentImagery/hlsRemembersEmpty.test.mjs diff --git a/src/layers/recentImagery/hlsMissingHeader.test.mjs b/src/layers/recentImagery/hlsMissingHeader.test.mjs deleted file mode 100644 index 17c84ec69c..0000000000 --- a/src/layers/recentImagery/hlsMissingHeader.test.mjs +++ /dev/null @@ -1,71 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { until } from '../../testSupport/kartaViewFakes.mjs'; -import { createRecentImagerySource } from './source.js'; -import { createThumbnailLoader } from './thumbnails.js'; -import { createRecentImageryLayer } from './index.js'; -import { createRecentImageryRenderer } from './rendering.js'; -import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; -import { candidate } from './testDoubles.mjs'; - -const PLAIN = { west: -98, south: 30, east: -97, north: 31 }; -const answer = (present) => - new Response('img', { - headers: present === null ? {} : { 'Data-Present': String(present) }, - }); - -function realLayer({ fetchImpl, candidates, maxDecoded = 16 }) { - const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs: 5000 }); - let nextUrl = 0; - const loader = createThumbnailLoader({ - requestThumbnail: source.getThumbnail, - createObjectUrl: () => `blob:${++nextUrl}`, - revokeObjectUrl: () => {}, - maxDecoded, - }); - const globe = fakeGlobePort(); - const layer = createRecentImageryLayer({ - catalog: { - searchHls: async () => ({ candidates, truncated: false, errors: [] }), - }, - renderer: createRecentImageryRenderer(), - thumbnails: loader, - host: () => ({ collection: globe.imagery, kind: 'globe' }), - globeOf: () => globe, - now: () => new Date('2026-11-13T15:00:00Z'), - }); - layer.init({ camera: {} }); - return { layer, loader, globe }; -} - -test('hls-missing-header: a shown HLS day on a plain box stays on the map after a 200 without Data-Present', async () => { - const day = candidate('S30', '2026-11-10'); - let release; - const gate = new Promise((r) => (release = r)); - const { layer, loader, globe } = realLayer({ - candidates: [day], - fetchImpl: async () => { - await gate; - return answer(null); - }, - }); - layer.enable(); - layer.setBox(PLAIN); - assert.equal( - await until(() => globe.layers.length === 1, { ticks: 2000 }), - true, - ); - release(); - assert.equal( - await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }), - true, - ); - await until(() => false, { ticks: 50 }); - const shownA = layer.getSnapshot().shown.a; - assert.equal( - globe.layers.length, - 1, - `layers=${globe.layers.length} shown.a=${shownA} availableBoxes=${JSON.stringify(loader.get(day.key).availableBoxes)}`, - ); - layer.destroy(); -}); diff --git a/src/layers/recentImagery/hlsRemembersEmpty.test.mjs b/src/layers/recentImagery/hlsRemembersEmpty.test.mjs deleted file mode 100644 index 8973ca3ef8..0000000000 --- a/src/layers/recentImagery/hlsRemembersEmpty.test.mjs +++ /dev/null @@ -1,104 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { until } from '../../testSupport/kartaViewFakes.mjs'; -import { createRecentImagerySource } from './source.js'; -import { createThumbnailLoader } from './thumbnails.js'; -import { nonCrossingBoxes } from './model.js'; -import { createRecentImageryLayer } from './index.js'; -import { createRecentImageryRenderer } from './rendering.js'; -import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; -import { FIJI_BOX, candidate } from './testDoubles.mjs'; - -const sideOf = (url) => - Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0 - ? 'west' - : 'east'; -const answer = (present) => - new Response('img', { - headers: present === null ? {} : { 'Data-Present': String(present) }, - }); - -function realLayer({ fetchImpl, candidates, maxDecoded = 16 }) { - const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs: 5000 }); - let nextUrl = 0; - const loader = createThumbnailLoader({ - requestThumbnail: source.getThumbnail, - createObjectUrl: () => `blob:${++nextUrl}`, - revokeObjectUrl: () => {}, - maxDecoded, - }); - const globe = fakeGlobePort(); - const layer = createRecentImageryLayer({ - catalog: { - searchHls: async () => ({ candidates, truncated: false, errors: [] }), - }, - renderer: createRecentImageryRenderer(), - thumbnails: loader, - host: () => ({ collection: globe.imagery, kind: 'globe' }), - globeOf: () => globe, - now: () => new Date('2026-11-13T15:00:00Z'), - }); - layer.init({ camera: {} }); - return { layer, loader, globe }; -} - -test('hls-remembers-empty: a re-probe with one failed half keeps that half confirmed empty', async () => { - const day1 = candidate('S30', '2026-11-10'); - const day2 = candidate('S30', '2026-11-11'); - let eastCalls = 0; - let releaseDay2; - const gate = new Promise((r) => (releaseDay2 = r)); - const { layer, loader, globe } = realLayer({ - candidates: [day2, day1], - maxDecoded: 1, - fetchImpl: async (url) => { - if (new URL(url).searchParams.get('TIME') === day2.day) { - await gate; - return answer(true); - } - if (sideOf(url) === 'east') { - eastCalls += 1; - if (eastCalls === 1) return answer(false); - throw new TypeError('Failed to fetch'); - } - return answer(true); - }, - }); - layer.enable(); - layer.setBox(FIJI_BOX); - assert.equal( - await until(() => loader.get(day1.key).status === 'present', { - ticks: 2000, - }), - true, - ); - const [west] = nonCrossingBoxes(FIJI_BOX); - assert.deepEqual(loader.get(day1.key).availableBoxes, [west]); - assert.equal(loader.get(day1.key).emptyBoxes.length, 1); - releaseDay2(); - assert.equal( - await until(() => loader.get(day2.key).status === 'present', { - ticks: 2000, - }), - true, - ); - assert.equal(loader.get(day1.key).objectUrl, null); - layer.setAssignment('a', day1.key); - assert.equal( - await until(() => eastCalls === 2 && !loader.get(day1.key).loading, { - ticks: 2000, - }), - true, - ); - await until(() => false, { ticks: 50 }); - const entry = loader.get(day1.key); - assert.deepEqual( - { - available: entry.availableBoxes.length, - empty: entry.emptyBoxes.length, - layers: globe.layers.length, - }, - { available: 1, empty: 1, layers: 1 }, - ); - layer.destroy(); -}); diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 2006718c5f..d7d43c41ab 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -4,7 +4,7 @@ import assert from 'node:assert/strict'; import { until } from '../../testSupport/kartaViewFakes.mjs'; import { createRecentImagerySource } from './source.js'; import { createThumbnailLoader } from './thumbnails.js'; -import { nonCrossingBoxes } from './model.js'; +import { boxKey, nonCrossingBoxes } from './model.js'; import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js'; import { acquireImageryComparison } from '../../maps/imageryComparison.js'; import { MapSourceController } from '../../maps/controller.js'; @@ -1614,8 +1614,12 @@ const sideOf = (url) => Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0 ? 'west' : 'east'; -const snapshotAnswer = (present) => - new Response('img', { headers: { 'Data-Present': String(present) } }); +/** A snapshot response; `present: null` sends no Data-Present header. */ +const snapshotAnswer = (present, status = 200) => + new Response('img', { + status, + headers: present === null ? {} : { 'Data-Present': String(present) }, + }); function realLayer({ fetchImpl, @@ -1797,6 +1801,186 @@ test('a re-probe of a present VIIRS dateline day keeps a half that failed this t layer.destroy(); }); +test('a re-probe of a present HLS dateline day keeps a half confirmed empty when that half fails this time', async () => { + const day1 = candidate('S30', '2026-11-10'); + const day2 = candidate('S30', '2026-11-11'); + let eastCalls = 0; + let releaseDay2; + const gate = new Promise((r) => (releaseDay2 = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day2, day1], + maxDecoded: 1, + halfDeadlineMs: 5000, + fetchImpl: async (url) => { + if (new URL(url).searchParams.get('TIME') === day2.day) { + await gate; + return snapshotAnswer(true); + } + if (sideOf(url) === 'east') { + eastCalls += 1; + if (eastCalls === 1) return snapshotAnswer(false); + throw new TypeError('Failed to fetch'); + } + return snapshotAnswer(true); + }, + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day1.key).status === 'present', { + ticks: 2000, + }), + true, + ); + const [west] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual(loader.get(day1.key).availableBoxes, [west]); + assert.equal(loader.get(day1.key).emptyBoxes.length, 1); + releaseDay2(); + assert.equal( + await until(() => loader.get(day2.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).objectUrl, null); + layer.setAssignment('a', day1.key); + assert.equal( + await until(() => eastCalls === 2 && !loader.get(day1.key).loading, { + ticks: 2000, + }), + true, + ); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day1.key); + assert.deepEqual( + { + available: entry.availableBoxes.length, + empty: entry.emptyBoxes.length, + layers: globe.layers.length, + }, + { available: 1, empty: 1, layers: 1 }, + ); + layer.destroy(); +}); + +test('a shown HLS day on a plain box stays draped after a probe without Data-Present', async () => { + const day = candidate('S30', '2026-11-10'); + let release; + const gate = new Promise((r) => (release = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day], + halfDeadlineMs: 5000, + fetchImpl: async () => { + await gate; + return snapshotAnswer(null); + }, + }); + layer.enable(); + layer.setBox({ west: -98, south: 30, east: -97, north: 31 }); + assert.equal( + await until(() => globe.layers.length === 1, { ticks: 2000 }), + true, + ); + release(); + assert.equal( + await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }), + true, + ); + await until(() => false, { ticks: 50 }); + assert.equal(globe.layers.length, 1); + layer.destroy(); +}); + +test('an HLS dateline day leaves out a half confirmed empty when the other half fails', async () => { + const day = candidate('S30', '2026-11-10'); + const { layer, loader, globe } = realLayer({ + candidates: [day], + halfDeadlineMs: 5000, + fetchImpl: async (url) => + sideOf(url) === 'west' + ? snapshotAnswer(false) + : snapshotAnswer(null, 503), + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day.key)?.status === 'error', { ticks: 2000 }), + true, + ); + layer.setAssignment('a', day.key); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day.key); + const [west] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual( + { + empty: (entry.emptyBoxes ?? []).map(boxKey), + layers: globe.layers.length, + }, + { empty: [boxKey(west)], layers: 1 }, + ); + layer.destroy(); +}); + +test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => { + const day1 = candidate('S30', '2026-11-10'); + const day2 = candidate('S30', '2026-11-11'); + let round = 0; + let releaseDay2; + const gate = new Promise((r) => (releaseDay2 = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day2, day1], + maxDecoded: 1, + halfDeadlineMs: 5000, + fetchImpl: async (url) => { + if (new URL(url).searchParams.get('TIME') === day2.day) { + await gate; + return snapshotAnswer(true); + } + if (round === 0) + return sideOf(url) === 'west' + ? snapshotAnswer(true) + : snapshotAnswer(null); + return sideOf(url) === 'west' + ? snapshotAnswer(null) + : snapshotAnswer(false); + }, + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day1.key)?.status === 'present', { + ticks: 2000, + }), + true, + ); + round = 1; + releaseDay2(); + assert.equal( + await until( + () => + loader.get(day2.key)?.status === 'present' && + loader.get(day1.key).objectUrl === null, + { ticks: 2000 }, + ), + true, + ); + layer.setAssignment('a', day1.key); + await until(() => false, { ticks: 50 }); + await until(() => !loader.get(day1.key).loading, { ticks: 2000 }); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day1.key); + const [, east] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual( + { + status: entry.status, + empty: (entry.emptyBoxes ?? []).map(boxKey), + layers: globe.layers.length, + }, + { status: 'present', empty: [boxKey(east)], layers: 1 }, + ); + layer.destroy(); +}); + test('a pick that probes empty after the automatic day lets the next ranked day drape', async () => { for (const order of [ [S18, V15], diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index 8abafc5f6e..804c73a88f 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -397,9 +397,8 @@ test('a probe that narrows or widens a dateline drape keeps the layer of the unc const globe = fakeGlobePort(); renderer.rebind({ collection: {}, kind: 'globe', globe }); const [west, east] = nonCrossingBoxes(FIJI_BOX); - const keyOf = (box) => [box.west, box.south, box.east, box.north].join(','); const layerFor = (box) => - globe.layers.find((layer) => keyOf(layer.spec.rectangle) === keyOf(box)); + globe.layers.find((layer) => boxKey(layer.spec.rectangle) === boxKey(box)); // An HLS day drapes both halves before its probe answers. renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' }); diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index 41ec83cd35..5dac769ce8 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -20,16 +20,14 @@ const EMPTY = Object.freeze({ loading: false, }); -/** On a re-probe, keep earlier halves of one answer (present or empty) unless the new probe answered them the other way. */ +/** Keep earlier halves of one answer (present or empty) unless the new probe answered them. */ function keepProvenHalves(previous, next, opposite) { - if ( - !Array.isArray(previous) || - !Array.isArray(next) || - !Array.isArray(opposite) - ) - return next; + if (!Array.isArray(next) || !Array.isArray(opposite)) return previous; const drop = new Set([...next, ...opposite].map(boxKey)); - return [...next, ...previous.filter((half) => !drop.has(boxKey(half)))]; + return [ + ...next, + ...(previous ?? []).filter((half) => !drop.has(boxKey(half))), + ]; } /** @@ -113,12 +111,13 @@ export function createThumbnailLoader({ size, signal: controller.signal, }); + // Each half's explicit answer counts even when the shown response fails. + availableBoxes = response?.presentBoxes ?? null; + emptyBoxes = response?.emptyBoxes ?? null; if (controller.signal.aborted) { cancelled = true; } else if (response?.ok) { const present = dataPresent(response); - availableBoxes = response.presentBoxes ?? null; - emptyBoxes = response.emptyBoxes ?? null; acquisitionTime = response.headers?.get?.('Acquisition-Time') || null; if (present === 'false') { status = 'empty'; @@ -146,21 +145,21 @@ export function createThumbnailLoader({ pump(); return; } + // Each half keeps its latest explicit answer. + entry.availableBoxes = keepProvenHalves( + entry.availableBoxes, + availableBoxes, + emptyBoxes, + ); + entry.emptyBoxes = keepProvenHalves( + entry.emptyBoxes, + emptyBoxes, + availableBoxes, + ); // A failed re-fetch of an evicted image keeps what the day proved. if (status !== 'error' || entry.status !== 'present') { - if (status === 'present' && entry.status === 'present') { - const fresh = availableBoxes; - availableBoxes = keepProvenHalves( - entry.availableBoxes, - fresh, - emptyBoxes, - ); - emptyBoxes = keepProvenHalves(entry.emptyBoxes, emptyBoxes, fresh); - } entry.status = status; entry.acquisitionTime = acquisitionTime; - entry.availableBoxes = availableBoxes; - entry.emptyBoxes = emptyBoxes; } entry.objectUrl = objectUrl; touch(entry); diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.js index 9e58ca3590..4d1bf989e5 100644 --- a/src/ui/recentImagery.js +++ b/src/ui/recentImagery.js @@ -139,13 +139,15 @@ function coverageText(coverage) { /** A confirmed-empty side means partial coverage. An unanswered side leaves coverage unknown. */ function shownCoverage(candidate, box) { const { status, availableBoxes, emptyBoxes } = candidate.thumbnail ?? {}; + const halves = nonCrossingBoxes(box).length; + if (emptyBoxes?.length && emptyBoxes.length < halves) return 'partial'; if ( status !== 'present' || !Array.isArray(availableBoxes) || - availableBoxes.length >= nonCrossingBoxes(box).length + availableBoxes.length >= halves ) return candidate.coverage; - return emptyBoxes?.length ? 'partial' : 'unknown'; + return 'unknown'; } function cloudText(candidate) { From 3973772b83791f10ab9a7bfea2c01f8fe0dab6af Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 23:36:39 +0400 Subject: [PATCH 18/18] fix(recent-imagery): keep a half confirmed empty when the other half's request fails When one half of a dateline box rejects or hits its deadline and the other half answered Data-Present: false, the thrown error now carries the per-half answers, and the loader merges them as it does for a 503 or a missing header. The empty side stays undraped and DETAILS shows partial coverage. --- src/layers/recentImagery/index.test.mjs | 66 ++++++++++++++----------- src/layers/recentImagery/source.js | 22 +++++++-- src/layers/recentImagery/thumbnails.js | 6 ++- 3 files changed, 60 insertions(+), 34 deletions(-) diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index d7d43c41ab..b226bb3d73 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -1891,35 +1891,45 @@ test('a shown HLS day on a plain box stays draped after a probe without Data-Pre layer.destroy(); }); -test('an HLS dateline day leaves out a half confirmed empty when the other half fails', async () => { - const day = candidate('S30', '2026-11-10'); - const { layer, loader, globe } = realLayer({ - candidates: [day], - halfDeadlineMs: 5000, - fetchImpl: async (url) => - sideOf(url) === 'west' - ? snapshotAnswer(false) - : snapshotAnswer(null, 503), - }); - layer.enable(); - layer.setBox(FIJI_BOX); - assert.equal( - await until(() => loader.get(day.key)?.status === 'error', { ticks: 2000 }), - true, - ); - layer.setAssignment('a', day.key); - await until(() => false, { ticks: 50 }); - const entry = loader.get(day.key); - const [west] = nonCrossingBoxes(FIJI_BOX); - assert.deepEqual( - { - empty: (entry.emptyBoxes ?? []).map(boxKey), - layers: globe.layers.length, +for (const [label, failEast] of [ + ['answers 503', async () => snapshotAnswer(null, 503)], + [ + 'rejects', + async () => { + throw new TypeError('Failed to fetch'); }, - { empty: [boxKey(west)], layers: 1 }, - ); - layer.destroy(); -}); + ], + ['never answers', () => new Promise(() => {})], +]) { + test(`an HLS dateline day leaves out a half confirmed empty when the other half ${label}`, async () => { + const day = candidate('S30', '2026-11-10'); + const { layer, loader, globe } = realLayer({ + candidates: [day], + fetchImpl: async (url) => + sideOf(url) === 'west' ? snapshotAnswer(false) : failEast(), + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day.key)?.status === 'error', { + ticks: 2000, + }), + true, + ); + layer.setAssignment('a', day.key); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day.key); + const [west] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual( + { + empty: (entry.emptyBoxes ?? []).map(boxKey), + layers: globe.layers.length, + }, + { empty: [boxKey(west)], layers: 1 }, + ); + layer.destroy(); + }); +} test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => { const day1 = candidate('S30', '2026-11-10'); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 5c61edf468..1e2afa1159 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -98,7 +98,8 @@ function withHalves(response, { presentBoxes, emptyBoxes }) { * NASA-compatible imagery acquisition; transport and URL builders are replaceable. * Thumbnail responses must expose Data-Present: true for image admission, or * false for confirmed empty coverage, including injected getThumbnail sources. - * getThumbnail also sets presentBoxes and emptyBoxes (see withHalves). + * getThumbnail also sets presentBoxes and emptyBoxes (see withHalves), + * also on the error it throws when another half was confirmed empty. * Without per-half evidence the renderer drapes every side of an HLS * dateline box and no side of a VIIRS one. */ @@ -144,17 +145,28 @@ export function createRecentImagerySource({ const answers = results.map((result) => result.status === 'fulfilled' ? dataPresent(result.value) : null, ); - // A missing answer is an error unless another half proved data. + const halvesWhere = (value) => + halves.filter((_, i) => answers[i] === value); + // A missing answer is an error unless another half proved data. The + // error keeps a half confirmed empty (see withHalves). const failure = results.find((result) => result.status === 'rejected'); - if (failure && !answers.includes('true')) throw failure.reason; + if (failure && !answers.includes('true')) { + const emptyBoxes = halvesWhere('false'); + if (Object.isExtensible(failure.reason)) + withHalves( + failure.reason, + emptyBoxes.length + ? { presentBoxes: [], emptyBoxes } + : { presentBoxes: null, emptyBoxes: null }, + ); + throw failure.reason; + } // Show the first half with data (the wider wins a tie), else the first // not confirmed empty, so an unreadable answer is never called empty. // Every half answered here unless one proved data. let shown = answers.indexOf('true'); if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false'); if (shown < 0) shown = 0; - const halvesWhere = (value) => - halves.filter((_, i) => answers[i] === value); return withHalves(results[shown].value, { presentBoxes: halvesWhere('true'), emptyBoxes: halvesWhere('false'), diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index 5dac769ce8..70e00526d3 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -133,7 +133,11 @@ export function createThumbnailLoader({ } catch (error) { if (controller.signal.aborted || error?.name === 'AbortError') cancelled = true; - else status = 'error'; + else { + status = 'error'; + availableBoxes = error?.presentBoxes ?? availableBoxes; + emptyBoxes = error?.emptyBoxes ?? emptyBoxes; + } } finally { inFlight -= 1; entry.loading = false;