fix(recent-imagery): preserve dateline half availability

This commit is contained in:
brandonabyrd authored and Byrd-IT committed 2026-11-13 17:12:47 -06:00
1 parent d60f2420f4
commit 9924cb15eb
8 files changed
+936 -43

No files matched your search

+6 -1
View File
@@ -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).
@@ -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();
});
+4
View File
@@ -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);
+27 -5
View File
@@ -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;
},
+166 -24
View File
@@ -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),
};
+48 -12
View File
@@ -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 () => {
+8 -1
View File
@@ -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<object> | 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,
};
},
@@ -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');