fix(recent-imagery): keep drapes and proven halves steady across re-probes

- 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.
This commit is contained in:
German Khokhlov committed 2026-11-19 18:50:06 +04:00
1 parent ccffaeca4d
commit fc137bef85
21 files changed
+715 -1093

No files matched your search

+6 -14
View File
@@ -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).
+2 -2
View File
@@ -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).
@@ -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();
});
+4 -6
View File
@@ -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();
});
+220 -4
View File
@@ -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();
});
+20 -20
View File
@@ -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<object>}
*/
@@ -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],
+2 -2
View File
@@ -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),
+30 -49
View File
@@ -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<object>, collection: object, candidate: object, box: object, alpha: number, split: string }>} */
/** @type {Record<'a'|'b', null | { layers: Array<object>, collection: object, candidate: object, box: object, parts: Array<object>, 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;
},
+50 -77
View File
@@ -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();
});
+85 -131
View File
@@ -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),
};
+100 -13
View File
@@ -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;
},
);
});
+49
View File
@@ -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. */
+22 -2
View File
@@ -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,
};
},
+72 -7
View File
@@ -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();
});
+1 -1
View File
@@ -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 {
+2 -1
View File
@@ -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/,
-2
View File
@@ -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<void> } | null}
*/
export function initImageryBoxTool({
+15 -3
View File
@@ -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,
+16
View File
@@ -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();
+14 -6
View File
@@ -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) {
+5 -9
View File
@@ -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 };