From a0b4e6cf5f13d2d2f592fc10c13848496c5865f4 Mon Sep 17 00:00:00 2001 From: Trix <75177432+trixmoe@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:22:42 +0100 Subject: [PATCH 01/30] fix(nodes): light-mode map follows tile picks, key and theme changes (#1470/#1420) (#2386) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix(nodes): light-mode map follows tile picks, key and theme changes (#1470/#1420) ## Problem The node-detail maps (`#/nodes/` full page + side pane — and their reusers `node-reach-map.js`, `rx-coverage.js`) pick a different basemap in **light mode** than the rest of the app: - hardcode Carto Positron: the user's *Light Mode Provider* customizer pick and the operator's `map.tiles.lightDefault` are ignored - render Carto's `API KEY REQUIRED` watermark when `/api/config/client` lands after the map is created — the tile requests stay keyless until a remount (they come back HTTP 200, so nothing surfaces as an error) - never react to a theme flip or provider change while the page is open Dark mode is unaffected, which is why it only shows up in light mode. Reproduce on `master`: open `#/nodes/` in light mode with `mc-light-tile-provider = carto-voyager` — the inset requests `light_all` while the main map requests `rastertiles/voyager`. ## Root cause `_applyTilesToNodeMap` (`public/nodes.js`) asked `window.getTileUrl()` for a single URL string, and roles.js's light branch returned the frozen `TILE_LIGHT` scalar — the dark branch was the only one that consulted the runtime registry (`public/map-tile-providers.js`), which is what owns localStorage picks, server defaults, the Carto key, and per-provider attribution/maxZoom/refUrl/invertFilter. map.js and live.js keep the only other registry-aware resolvers of the same logic. ## What this PR does - adds one resolver, `MC_resolveTile(isDark)`, in map-tile-providers.js, returning the full descriptor `{ type, id, url, attribution, maxZoom, refUrl, invertFilter }`: - `url` is always a resolved string — function-typed providers are invoked at call time (contract of #1614) - one precedence rule everywhere: explicit operator overrides (`cfg.tiles.dark|light`, `map.tiles.darkUrl|lightUrl`, tracked via `MC_LEGACY_TILE_OVERRIDE`) > user/server registry pick > `TILE_DARK`/`TILE_LIGHT` constants — **this is a deliberate behavior change on map.js/live.js, see below** - fully lazy: registry rebuilds / pick changes are picked up by the next resolve, so config landing after page load fixes itself - roles.js `getTileUrl()` becomes a thin wrapper over it; the public API and the #1614 sandbox contract are unchanged; `getActiveTileProvider()` keeps its documented null-in-light contract - `nodes.js _applyTilesToNodeMap` resolves through the descriptor and stays reactive: one shared `mc-tile-provider-changed` listener + one `data-theme` MutationObserver re-sync every registered map in place — old layers removed before the new ones are added, never stacked; maps whose container left the DOM are pruned at sync time, so SPA navigation cannot leak listeners - map.js `_resolveTileUrl` / live.js `_liveResolveTile` delegate to the shared resolver (their legacy bodies remain only as sandbox fallbacks) - provider `maxZoom` replaces the hardcoded 18/19 caps (OpenTopoMap 17 and USGS 16 used to 404 above their max zoom) - analytics.js subpath minimap gets provider `maxZoom` as well ## Behavior change (deliberate): operator URL overrides now win on every surface On `master`, the two tile-selection mechanisms conflicted and each surface resolved the conflict differently: - `map.js` / `live.js`: user/server **registry pick won** — an operator's `tiles.dark|light` / `map.tiles.darkUrl|lightUrl` was effectively dead config on those pages - the legacy roles.js path (nodes page, reach map, rx-coverage, analytics minimap): **operator override won** This PR unifies on **operator-override-wins**, because that is the only reading that gives live operator config a consistent meaning: - these keys are still applied today. The deprecation warning says they would "be ignored in v3.5.0", and v3.5.0 shipped 2026-04-08 — the instance line is now at v3.16.0 and the keys still take effect, so they are live configuration, not dead letters. An explicit operator pin should not be silently defeated by a per-user pick on some pages and honored on others; whichever way the mechanism eventually goes, it must behave identically everywhere until it is actually removed. - user choice is not reduced in the general case: picks remain authoritative for every provider the registry offers, and overrides only exist where an operator explicitly wrote a literal URL. If maintainers would rather have pick-wins (operator URL acts only as a fallback default), flipping the precedence in `MC_resolveTile` is a small, well-tested change — say so in review and it will be reworked. Related cleanup, out of scope here: the stale "ignored in v3.5.0" deprecation warning in `cmd/server/config.go` should either be honored or reworded now that the project is past v3.16.0. ## No change without operator overrides or picks ## Verification Unit (all deterministic, `vm`-sandbox based): - new `tests/unit/test-tile-resolver.js` — 22 cases: light/dark pick honored, operator `lightDefault`, disabled-provider fallback, override precedence, lazy function-URLs, key-after-async-config, in-place swap without stacking, detached-map prune, multi-map single-listener sync, provider maxZoom; listed in `test-all.sh` - existing suites green: `test-issue-1420-tile-providers` (47), `test-issue-1470-node-tile-helper` (6), `test-issue-1614-tile-url-function` (3), `test-frontend-helpers` (79), `test-settings-sync`, `test-packet-filter` (105), `test-aging` - every one of the 227 suites listed in `test-all.sh`, run individually: all green except `test-manage-workflow` (2 failures that are local-env only — CRLF bootstrap artifact — and pass in CI; `sh test-all.sh` aborts there locally under `set -e`, which is why the suites were run one by one this time; the scripted pipeline runs fully in CI) - `eslint` on all six touched files: 0 errors Browser (headless Chromium against this branch, `/api/config/client` delayed ~800 ms to force the config race): - light + `/#/nodes/`: 12 keyless tile requests before config, 12 keyed re-requests after — no reload, no stacked layer - light pick `carto-voyager`: inset requests `rastertiles/voyager` from the start (parity with the main map) - theme flip on an open node page: `dark_all` swaps in in place - dark defaults unchanged (`dark_all`, keyed after config) The Playwright E2E suite was not run locally — no Go toolchain on the workstation to serve the backend — CI will cover it. ## Scope / follow-ups (intentionally not here) - `home.js` mini-map (OSM only) and the geo-filter mini-maps in the customizers are untouched on purpose: they are outside this bug's path, and migrating them to `MC_resolveTile` later is mechanical ## Performance Not a hot path: one registry lookup + string build per map creation and per provider/theme-change event (each is rare); no per-packet or per-render work; the listener footprint is O(1) app-wide (single shared listener pair + a pruned registry), so there is no growth across SPA navigations. Co-authored-by: OpenCode Co-authored-by: OpenCode:GLM-5.3-Flash Assisted-by: OpenCode:GLM-5.3-Flash eslint --------- Co-authored-by: OpenCode --- public/analytics.js | 7 +- public/live.js | 36 +- public/map-tile-providers.js | 112 ++++ public/map.js | 35 +- public/node-reach-map.js | 5 +- public/nodes.js | 167 +++++- public/roles.js | 80 ++- public/rx-coverage.js | 8 +- test-all.sh | 1 + .../unit/test-issue-1862-map-region-filter.js | 12 + tests/unit/test-tile-resolver.js | 508 ++++++++++++++++++ 11 files changed, 870 insertions(+), 101 deletions(-) create mode 100644 tests/unit/test-tile-resolver.js diff --git a/public/analytics.js b/public/analytics.js index b40060804..d62343158 100644 --- a/public/analytics.js +++ b/public/analytics.js @@ -2466,7 +2466,12 @@ // Render minimap if (hasMap && typeof L !== 'undefined') { const map = L.map('subpathMap', { zoomControl: false, attributionControl: false }); - L.tileLayer(getTileUrl(), { maxZoom: 18 }).addTo(map); + // Shared resolver for attribution/maxZoom parity with the other maps + // (OpenTopoMap caps at 17, USGS at 16 — a hardcoded 18 404s above those). + const _tileR = (typeof window.MC_resolveTile === 'function') + ? window.MC_resolveTile(typeof window.MC_isDarkTheme === 'function' ? window.MC_isDarkTheme() : false) + : null; + L.tileLayer((_tileR && _tileR.url) || getTileUrl(), { maxZoom: (_tileR && _tileR.maxZoom) || 18 }).addTo(map); const latlngs = []; nodesWithLoc.forEach((n, i) => { diff --git a/public/live.js b/public/live.js index 14a4948db..b4f86aa21 100644 --- a/public/live.js +++ b/public/live.js @@ -1549,27 +1549,14 @@ } _rebindDPRListener(); - const isDark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); - // #1420 — multi-provider dark-tile picker. Light mode unchanged. + const isDark = window.MC_isDarkTheme(); + // #1420 — multi-provider dark-tile picker. Light mode unchanged (live page). let _liveDarkRefLayer = null; + // Single shared registry resolver (map-tile-providers.js loads before this + // file; there is deliberately no second fallback body here — AGENTS.md DRY). function _liveResolveTile(dark) { - const reg = window.MC_TILE_PROVIDERS || {}; - if (!dark) { - const lightId = (typeof window.MC_getLightTileProvider === 'function') ? window.MC_getLightTileProvider() : null; - const lp = lightId ? (reg[lightId] || null) : null; - if (lp && lp.url) { - return { url: (typeof lp.url === 'function' ? lp.url() : lp.url), attribution: lp.attribution || '© OpenStreetMap © CartoDB', refUrl: null }; - } - return { url: TILE_LIGHT, attribution: '© OpenStreetMap © CartoDB', refUrl: null }; - } - const id = (typeof window.MC_getDarkTileProvider === 'function') ? window.MC_getDarkTileProvider() : 'carto-dark'; - const p = reg[id] || reg['carto-dark'] || {}; - return { - url: (typeof p.url === 'function' ? p.url() : p.url) || (typeof p.baseUrl === 'function' ? p.baseUrl() : p.baseUrl) || TILE_DARK, - attribution: p.attribution || '© OpenStreetMap © CartoDB', - refUrl: p.refUrl || null - }; + const r = window.MC_resolveTile(!!dark); + return { url: r.url, attribution: r.attribution, refUrl: r.refUrl, maxZoom: r.maxZoom }; } const liveAutoLayerGroup = L.layerGroup().addTo(map); @@ -1596,9 +1583,9 @@ } } const _liveInitTile = _liveResolveTile(isDark); - let tileLayer = L.tileLayer(_liveInitTile.url, { maxZoom: 19, attribution: _liveInitTile.attribution }).addTo(liveAutoLayerGroup); + let tileLayer = L.tileLayer(_liveInitTile.url, { maxZoom: _liveInitTile.maxZoom || 19, attribution: _liveInitTile.attribution }).addTo(liveAutoLayerGroup); if (isDark && _liveInitTile.refUrl) { - _liveDarkRefLayer = L.tileLayer(_liveInitTile.refUrl, { maxZoom: 19, attribution: _liveInitTile.attribution }).addTo(liveAutoLayerGroup); + _liveDarkRefLayer = L.tileLayer(_liveInitTile.refUrl, { maxZoom: _liveInitTile.maxZoom || 19, attribution: _liveInitTile.attribution }).addTo(liveAutoLayerGroup); } if (typeof window.MC_applyTileFilter === 'function') window.MC_applyTileFilter(); @@ -1654,15 +1641,12 @@ // Swap tiles when theme changes const _themeObs = new MutationObserver(function () { - const dark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); - _liveSyncDarkTiles(dark); + _liveSyncDarkTiles(window.MC_isDarkTheme()); }); _themeObs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); // #1420 — re-render on customizer change. window.addEventListener('mc-tile-provider-changed', function (e) { - const dark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); + const dark = window.MC_isDarkTheme(); if (e && e.detail && e.detail.type && e.detail.type !== (dark ? 'dark' : 'light')) return; _liveSyncDarkTiles(dark); }); diff --git a/public/map-tile-providers.js b/public/map-tile-providers.js index 74fe94e17..f7f06dcda 100644 --- a/public/map-tile-providers.js +++ b/public/map-tile-providers.js @@ -198,6 +198,10 @@ window.MC_setServerDefaultTileProvider = setServerDefault; window.MC_setServerDefaultLightTileProvider = setServerDefaultLight; window.MC_applyTileFilter = applyTileFilter; + // Theme truth used by every map surface (data-theme attr, else OS preference). + // roles.js helpers consult this at call time instead of re-deriving it, so a + // theme flip and a pixel-perfect tile pick can't disagree about "dark". + window.MC_isDarkTheme = _isDark; /** * Resolve a registry id to a concrete tile-URL string, invoking function-typed @@ -212,6 +216,114 @@ return (typeof u === 'function') ? u() : u; }; + // ── Shared tile resolution (single source of truth) ────────────────────── + // + // Before this block every surface resolved its own basemap: map.js/_resolveTileUrl + // and live.js/_liveResolveTile honoured the light provider pick, while roles.js' + // getTileUrl() light branch returned the bare TILE_LIGHT constant and every other + // consumer (node detail inset, node reach, rx-coverage, analytics minimap) went + // through that asymmetric path — wrong basemap in light mode, keyless Carto tiles + // when config raced page load, and provider extras (attribution, maxZoom, + // refUrl, invertFilter) dropped on the floor. All of them now come here. + + // Bare-constant fallbacks for the sandboxed/no-registry case (roles.js is the + // normal home of TILE_DARK/TILE_LIGHT and loads before this file; keep the + // literals in sync with roles.js if either ever changes). + var _FALLBACK_TILE_DARK = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'; + var _FALLBACK_TILE_LIGHT = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'; + var _ATTR_CARTO = '© OpenStreetMap © CartoDB'; + var _ATTR_OSM = '© OpenStreetMap contributors'; + var _DEFAULT_MAX_ZOOM = 19; + + function _constantTileUrl(dark) { + // Prefer the roles.js-scalar when present (it carries explicit legacy + // overrides and keyed defaults after MeshConfigReady resolves). + try { + if (dark && typeof TILE_DARK === 'string' && TILE_DARK) return TILE_DARK; + if (!dark && typeof TILE_LIGHT === 'string' && TILE_LIGHT) return TILE_LIGHT; + } catch (_e) { /* not loaded — use the literals */ } + return dark ? _FALLBACK_TILE_DARK : _FALLBACK_TILE_LIGHT; + } + + /** + * Resolve the effective tile provider for a theme into a plain descriptor: + * { type, id, url, attribution, maxZoom, refUrl, invertFilter } + * `url` is always a resolved string — provider `url`/`baseUrl` builders are + * invoked here so callers never hand L.tileLayer a function (#1614). + * Resolution happens at call time (never cached): MC_initTileRegistry(true) + * reassigns the registry when async config arrives, and localStorage picks + * can change at any moment. + * + * Precedence: + * 1. Explicit operator override (cfg.tiles.dark|light or + * map.tiles.darkUrl|lightUrl — tracked by roles.js in + * window.MC_LEGACY_TILE_OVERRIDE; beats everything). + * 2. User/operator registry pick for the theme (MC_getDarkTileProvider / + * MC_getLightTileProvider — localStorage, then server default, then the + * shipped carto defaults). + * 3. The TILE_DARK/TILE_LIGHT constants (pre-config load or a registry + * the config has emptied out). + */ + window.MC_resolveTile = function (isDark) { + isDark = !!isDark; + var desc = { + type: isDark ? 'dark' : 'light', + id: null, + url: null, + attribution: _ATTR_CARTO, + maxZoom: _DEFAULT_MAX_ZOOM, + refUrl: null, + invertFilter: null, + override: false + }; + // 1. Explicit operator override beats user picks + try { + var ov = window.MC_LEGACY_TILE_OVERRIDE; + if (ov && ov[desc.type]) { + desc.url = _constantTileUrl(isDark); + desc.attribution = _ATTR_OSM; + desc.override = true; + return desc; + } + } catch (_e) { /* fall through to the registry */ } + // 2. Registry pick for this theme (honours localStorage + server defaults). + // Reads the PUBLIC getters/registry ref, not the private internals: they're + // the stable contract (window.MC_TILE_PROVIDERS is kept in sync by + // MC_initTileRegistry after every rebuild) and they let test sandboxes + // inject mocks the same way the #1614 harness does. + var id = null; + try { + if (isDark && typeof window.MC_getDarkTileProvider === 'function') id = window.MC_getDarkTileProvider(); + else if (!isDark && typeof window.MC_getLightTileProvider === 'function') id = window.MC_getLightTileProvider(); + } catch (_e) { id = null; } + var reg = null; + try { reg = window.MC_TILE_PROVIDERS || null; } catch (_e) { reg = null; } + if (!reg) reg = REGISTRY; + var _pick = function (pid) { + return (pid && Object.prototype.hasOwnProperty.call(reg, pid)) ? reg[pid] : null; + }; + var p = _pick(id); + var pickedId = p ? id : null; + // The stored/default id may reference a provider the running config has + // disabled; keep the old map.js/live.js behaviour of falling back to the + // shipped default entry before giving up on the registry. + var defId = isDark ? DEFAULT_ID : DEFAULT_ID_LIGHT; + if (!p) { p = _pick(defId); pickedId = p ? defId : null; } + if (p && p.type && p.type !== desc.type) { p = null; pickedId = null; } // registry is authoritative on types + if (!p) { // 3. Bare constants (roles.js scalars or shipped literals) + desc.url = _constantTileUrl(isDark); + return desc; + } + var u = p.url || p.baseUrl; + desc.id = pickedId; // the entry the URL actually came from + desc.url = (typeof u === 'function') ? u() : u; + desc.attribution = p.attribution || _ATTR_CARTO; + desc.maxZoom = p.maxZoom || _DEFAULT_MAX_ZOOM; + desc.refUrl = p.refUrl || null; + desc.invertFilter = p.invertFilter || null; + return desc; + }; + /** * Build and attach a Leaflet layer control listing "Auto (follows theme)" diff --git a/public/map.js b/public/map.js index 39b5d48de..a6a054c37 100644 --- a/public/map.js +++ b/public/map.js @@ -666,27 +666,14 @@ // If navigated with ?node=PUBKEY, highlight that node after markers load targetNodeKey = urlParams.get('node') || null; - const isDark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); - // #1420 — multi-provider dark-tile picker. Light mode unchanged. + const isDark = window.MC_isDarkTheme(); + // #1420 — multi-provider dark-tile picker. Light mode unchanged (map page). let _darkRefLayer = null; // Esri-only: labels overlay + // Single shared registry resolver (map-tile-providers.js loads before this + // file; there is deliberately no second fallback body here — AGENTS.md DRY). function _resolveTileUrl(dark) { - const reg = window.MC_TILE_PROVIDERS || {}; - if (!dark) { - const lightId = (typeof window.MC_getLightTileProvider === 'function') ? window.MC_getLightTileProvider() : null; - const lp = lightId ? (reg[lightId] || null) : null; - if (lp && lp.url) { - return { url: (typeof lp.url === 'function' ? lp.url() : lp.url), attribution: lp.attribution || '© OpenStreetMap © CartoDB', refUrl: null }; - } - return { url: TILE_LIGHT, attribution: '© OpenStreetMap © CartoDB', refUrl: null }; - } - const id = (typeof window.MC_getDarkTileProvider === 'function') ? window.MC_getDarkTileProvider() : 'carto-dark'; - const p = reg[id] || reg['carto-dark'] || {}; - return { - url: (typeof p.url === 'function' ? p.url() : p.url) || (typeof p.baseUrl === 'function' ? p.baseUrl() : p.baseUrl) || TILE_DARK, - attribution: p.attribution || '© OpenStreetMap © CartoDB', - refUrl: p.refUrl || null - }; + const r = window.MC_resolveTile(!!dark); + return { url: r.url, attribution: r.attribution, refUrl: r.refUrl, maxZoom: r.maxZoom }; } const autoLayerGroup = L.layerGroup().addTo(map); @@ -715,10 +702,10 @@ const _initTile = _resolveTileUrl(isDark); const tileLayer = L.tileLayer(_initTile.url, { attribution: _initTile.attribution, - maxZoom: 19, + maxZoom: _initTile.maxZoom || 19, }).addTo(autoLayerGroup); if (isDark && _initTile.refUrl) { - _darkRefLayer = L.tileLayer(_initTile.refUrl, { maxZoom: 19, attribution: _initTile.attribution }).addTo(autoLayerGroup); + _darkRefLayer = L.tileLayer(_initTile.refUrl, { maxZoom: _initTile.maxZoom || 19, attribution: _initTile.attribution }).addTo(autoLayerGroup); } if (typeof window.MC_applyTileFilter === 'function') window.MC_applyTileFilter(); @@ -728,15 +715,13 @@ } const _mapThemeObs = new MutationObserver(function () { - const dark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); + const dark = window.MC_isDarkTheme(); _syncDarkTiles(dark); }); _mapThemeObs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); // #1420 — re-render when the user picks a different dark provider in the customizer. window.addEventListener('mc-tile-provider-changed', function (e) { - const dark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); + const dark = window.MC_isDarkTheme(); if (e && e.detail && e.detail.type && e.detail.type !== (dark ? 'dark' : 'light')) return; _syncDarkTiles(dark); }); diff --git a/public/node-reach-map.js b/public/node-reach-map.js index 139b1816d..84549e4e8 100644 --- a/public/node-reach-map.js +++ b/public/node-reach-map.js @@ -86,7 +86,10 @@ map: map, setLinks: setLinks, get bounds() { return bounds; }, - destroy: function () { try { map.remove(); } catch (e) {} } + destroy: function () { + try { if (window.__mcNodeTileSyncUnregister) window.__mcNodeTileSyncUnregister(map); } catch (e) {} + try { map.remove(); } catch (e) {} + } }; } diff --git a/public/nodes.js b/public/nodes.js index 72a547732..95dd7bb66 100644 --- a/public/nodes.js +++ b/public/nodes.js @@ -100,7 +100,13 @@ if (owner && detailMap && !owner.contains(detailMap.getContainer())) return; clearTimeout(detailMapResizeTimer); detailMapResizeTimer = null; - if (detailMap) { detailMap.remove(); detailMap = null; } + if (detailMap) { + // Drop the tile-sync record before Leaflet tears the map down (#review: + // the shared onChange prune cannot see an attached container). + try { if (window.__mcNodeTileSyncUnregister) window.__mcNodeTileSyncUnregister(detailMap); } catch (_e) {} + detailMap.remove(); + detailMap = null; + } } function resizeDetailMapAfterLayout() { @@ -111,26 +117,149 @@ }, 100); } - // #1461 followup: node-detail inset map tile layer that honors the - // customizer dark-tile-provider pick (#1420/#1430). Falls back to - // window.getTileUrl() output if the registry isn't loaded. Also applies - // the provider's invert CSS filter to the tile pane when needed. + // #1470 followup, node-map light-tiles refactor: the node detail inset map + // (and every page reusing this helper via window._applyTilesToNodeMap — + // node-reach-map.js, rx-coverage.js) resolves tiles through the shared + // MC_resolveTile() registry resolver, so light mode honours the same + // provider pick / operator lightDefault as the main map, carries the Carto + // key even when /api/config/client lands after the map is created, and + // passes the provider's attribution/maxZoom/refUrl/invertFilter through. + // + // Reactivity: maps register in one shared window slot (__mcNodeTileSync); + // a single mc-tile-provider-changed listener + a single data-theme + // MutationObserver re-sync every live map in place — old layers are removed + // before the new ones are added, never stacked. Maps whose container has + // left the DOM are pruned at sync time, so SPA navigation (removeDetailMap, + // reach-map destroy) cannot leak listeners or touch removed maps. + // Deliberately self-contained (no other nodes.js helpers): the #1470 unit + // test extracts just this function and runs it in a sandbox. function _applyTilesToNodeMap(map) { - if (!map) return; - var tileUrl = (window.getTileUrl && window.getTileUrl()) || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; - var provider = window.getActiveTileProvider && window.getActiveTileProvider(); - var attribution = (provider && provider.attribution) || '© OpenStreetMap contributors'; - var layer = L.tileLayer(tileUrl, { maxZoom: 18, attribution: attribution }).addTo(map); - // Esri 2-layer provider: add the labels reference overlay too - if (provider && provider.refUrl) { - try { L.tileLayer(provider.refUrl, { maxZoom: 18 }).addTo(map); } catch (_e) {} + if (!map) return null; + var st = (window.__mcNodeTileSync = window.__mcNodeTileSync || { maps: [], wired: false, onChange: null }); + + function themeIsDark() { + if (typeof window.MC_isDarkTheme === 'function') return !!window.MC_isDarkTheme(); + try { // canonical check mirrors map-tile-providers.js _isDark() + var attr = document.documentElement.getAttribute('data-theme'); + if (attr === 'dark') return true; + if (attr === 'light') return false; + return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); + } catch (_e) { return false; } } - // Apply invert CSS filter to the tile pane if the provider needs it - try { - var pane = map.getPane && map.getPane('tilePane'); - if (pane) pane.style.filter = (provider && provider.invertFilter) ? provider.invertFilter : ''; - } catch (_e) {} - return layer; + + function resolve() { + if (window.MC_resolveTile) { + try { return window.MC_resolveTile(themeIsDark()); } catch (_e) {} + } + // Registry module absent: fall back to what getTileUrl() knows. + var url = (window.getTileUrl && window.getTileUrl()) || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; + var provider = window.getActiveTileProvider && window.getActiveTileProvider(); + return { + url: url, + attribution: (provider && provider.attribution) || '© OpenStreetMap contributors', + maxZoom: 18, + refUrl: (provider && provider.refUrl) || null, + invertFilter: (provider && provider.invertFilter) || null + }; + } + + // Build the (reusable) layer for one map record: resolve → remove old + // layers → add new ones → apply pane filter. Registered records carry + // this closure as apply(), so the single shared listener can re-sync + // every live map. + function makeApply(rec) { + return function () { + var r = resolve(); + if (rec.layer) { try { map.removeLayer(rec.layer); } catch (_e) {} rec.layer = null; } + if (rec.refLayer) { try { map.removeLayer(rec.refLayer); } catch (_e) {} rec.refLayer = null; } + try { + rec.layer = L.tileLayer(r.url, { maxZoom: r.maxZoom || 18, attribution: r.attribution || '© OpenStreetMap contributors' }).addTo(map); + // Esri 2-layer provider: labels come as a separate reference tileset + // stacked on the base layer. + if (r.refUrl) { + rec.refLayer = L.tileLayer(r.refUrl, { maxZoom: r.maxZoom || 18, attribution: r.attribution || '© OpenStreetMap contributors' }).addTo(map); + } + } catch (_e) { return rec.layer; } + // Apply the invert CSS filter to the tile pane when the provider needs + // it (dark-inverted light styles like positron-dark / carto-voyager-dark). + try { + var pane = map.getPane && map.getPane('tilePane'); + if (pane) pane.style.filter = r.invertFilter || ''; + } catch (_e) {} + return rec.layer; + }; + } + + // Bounded registry (AGENTS.md rule 0): records are dropped (a) when a new + // map registers and theirs is disconnected, and (b) explicitly via + // window.__mcNodeTileSyncUnregister(map) from the destroy paths of every + // consumer — removeDetailMap (nodes.js), node-reach-map.js, rx-coverage.js. + // Explicit unregister covers maps whose container stays attached after + // map.remove(), which the isConnected check cannot see. + function pruneStaleRecords() { + var kept = []; + for (var k = 0; k < st.maps.length; k++) { + var container = st.maps[k].map && st.maps[k].map.getContainer && st.maps[k].map.getContainer(); + if (container && container.isConnected === false) continue; + kept.push(st.maps[k]); + } + st.maps = kept; + } + + var rec = { map: map, layer: null, refLayer: null, apply: null }; + rec.apply = makeApply(rec); + pruneStaleRecords(); + // Re-registering the same map (rx-coverage re-init) replaces its record + // instead of stacking a second sync for it. Its old layers must go too — + // otherwise a leaflet rewire leaves two base layers stacked on the map. + (function replacePrevRec() { + for (var i = 0; i < st.maps.length; i++) { + if (st.maps[i].map === map) { + var prev = st.maps.splice(i, 1)[0]; + if (prev.layer) { try { map.removeLayer(prev.layer); } catch (_e) {} } + if (prev.refLayer) { try { map.removeLayer(prev.refLayer); } catch (_e) {} } + break; + } + } + })(); + st.maps.push(rec); + + function onChange(e) { + // Ignore a pick for the other theme: it doesn't change these tiles. + var type = (e && e.detail && e.detail.type) || null; + if (type && type !== (themeIsDark() ? 'dark' : 'light')) return; + pruneStaleRecords(); + for (var i = 0; i < st.maps.length; i++) { + try { st.maps[i].apply(); } catch (_err) {} + } + } + + // Explicit unregister for destroy paths (see pruneStaleRecords note). + // Wire-once: every consumer guard-checks typeof before calling. + window.__mcNodeTileSyncUnregister = function (m) { + if (!m || !st) return; + for (var i = 0; i < st.maps.length; i++) { + if (st.maps[i].map === m) { + var gone = st.maps.splice(i, 1)[0]; + if (gone.layer) { try { m.removeLayer(gone.layer); } catch (_e) {} } + if (gone.refLayer) { try { m.removeLayer(gone.refLayer); } catch (_e) {} } + break; + } + } + }; + + if (!st.wired) { + st.onChange = onChange; // exposed for tests/sandboxes without MutationObserver + try { window.addEventListener('mc-tile-provider-changed', onChange); } catch (_e) {} + if (typeof MutationObserver === 'function') { + try { + new MutationObserver(function () { onChange(null); }) + .observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); + } catch (_e) {} + } + st.wired = true; + } + return rec.apply(); } // Exposed so the node-reach link-map (node-reach-map.js) reuses the user's // configured tile provider instead of hardcoding OSM. diff --git a/public/roles.js b/public/roles.js index 639b91b19..5b40e57fc 100644 --- a/public/roles.js +++ b/public/roles.js @@ -523,22 +523,53 @@ window.TILE_DARK = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'; window.TILE_LIGHT = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'; + /* Helper: get the full provider object (for callers that also need the + * invertFilter or refUrl/attribution). Returns null when no customizer + * provider applies (light mode, or registry not loaded). */ + window.getActiveTileProvider = function () { + var isDark = (typeof window.MC_isDarkTheme === 'function') ? !!window.MC_isDarkTheme() : _tileThemeIsDark(); + if (!isDark) return null; + try { + if (window.MC_getDarkTileProvider && window.MC_TILE_PROVIDERS) { + var id = window.MC_getDarkTileProvider(); + return window.MC_TILE_PROVIDERS[id] || null; + } + } catch (_e) {} + return null; + }; + + // Theme check for the legacy (registry-not-loaded) path below; kept in sync + // with map-tile-providers.js' _isDark(), which is the canonical version. + function _tileThemeIsDark() { + try { + var attr = document.documentElement.getAttribute('data-theme'); + if (attr === 'dark') return true; + if (attr === 'light') return false; + return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); + } catch (_e) { return false; } + } + + /* getTileUrl(): thin wrapper over MC_resolveTile(). Before the node-map + * light-tiles refactor this function resolved dark providers from the + * registry but returned the bare TILE_LIGHT scalar in light mode — ignoring + * the user's Light Mode Provider pick, the operator's lightDefault, and the + * Carto key when /api/config/client hadn't landed yet. Callers that only + * need the URL can keep calling this; callers that also want attribution / + * maxZoom / refUrl / invertFilter should call window.MC_resolveTile() + * directly and read the whole descriptor. */ window.getTileUrl = function () { - var isDark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && - window.matchMedia('(prefers-color-scheme: dark)').matches); + var isDark = (typeof window.MC_isDarkTheme === 'function') ? !!window.MC_isDarkTheme() : _tileThemeIsDark(); + if (window.MC_resolveTile) { + try { return window.MC_resolveTile(isDark).url; } catch (_e) {} + } + // Legacy fallback for sandboxes that mock the registry without loading + // map-tile-providers.js (mirrors #1614's function-URL contract). if (!isDark) return TILE_LIGHT; - // #1461 followup: honor customizer's dark-tile-provider pick (#1420 / #1430) - // when the registry is loaded. Falls back to TILE_DARK if absent. try { if (window.MC_getDarkTileProvider && window.MC_TILE_PROVIDERS) { var id = window.MC_getDarkTileProvider(); var p = window.MC_TILE_PROVIDERS[id]; if (p && (p.url || p.baseUrl)) { - // #1614: providers added in #1533 (carto/osm/stamen) declare - // `url` as a function for lazy config resolution. Invoke it so - // we always return a string URL template; L.tileLayer otherwise - // stringifies the function source and every tile request 404s. var u = p.url || p.baseUrl; return (typeof u === 'function') ? u() : u; } @@ -546,22 +577,7 @@ } catch (_e) {} return TILE_DARK; }; - /* Helper: get the full provider object (for callers that also need the - * invertFilter or refUrl/attribution). Returns null when no customizer - * provider applies (light mode, or registry not loaded). */ - window.getActiveTileProvider = function () { - var isDark = document.documentElement.getAttribute('data-theme') === 'dark' || - (document.documentElement.getAttribute('data-theme') !== 'light' && - window.matchMedia('(prefers-color-scheme: dark)').matches); - if (!isDark) return null; - try { - if (window.MC_getDarkTileProvider && window.MC_TILE_PROVIDERS) { - var id = window.MC_getDarkTileProvider(); - return window.MC_TILE_PROVIDERS[id] || null; - } - } catch (_e) {} - return null; - }; + // ─── SNR thresholds ─── window.SNR_THRESHOLDS = { excellent: 6, good: 0 }; @@ -657,11 +673,19 @@ } if (typeof window.MC_initTileRegistry === 'function') window.MC_initTileRegistry(true); // CARTO raster needs an API key now, so the bare TILE_DARK/TILE_LIGHT - // fallbacks have to pick it up as well — getTileUrl() returns TILE_LIGHT - // directly in light mode and never consults the registry. Explicit - // darkUrl/lightUrl overrides above still win. + // fallbacks pick it up here — code that still reads the constants directly + // (screens without the registry) gets keyed URLs. Registry-driven surfaces + // fetch their URLs lazily through MC_resolveTile() instead. if (typeof window.MC_tileUrlById === 'function') { var _tOv = (cfg.tiles || (cfg.map && cfg.map.tiles) || {}); + // Tell MC_resolveTile that explicit operator overrides are in play so + // they beat the user's provider pick on every consumer (only the legacy + // roles.js path saw them before). Resolved lazily at call time via the + // TILE_DARK/TILE_LIGHT scalars, which carry the override URLs above. + window.MC_LEGACY_TILE_OVERRIDE = { + dark: !!(_tOv.dark || _tOv.darkUrl), + light: !!(_tOv.light || _tOv.lightUrl) + }; if (!_tOv.dark && !_tOv.darkUrl) window.TILE_DARK = window.MC_tileUrlById('carto-dark', window.TILE_DARK); if (!_tOv.light && !_tOv.lightUrl) window.TILE_LIGHT = window.MC_tileUrlById('carto-light', window.TILE_LIGHT); } diff --git a/public/rx-coverage.js b/public/rx-coverage.js index bdfd7bf84..79fdd32e5 100644 --- a/public/rx-coverage.js +++ b/public/rx-coverage.js @@ -654,7 +654,13 @@ function destroy() { destroyed = true; generation++; - if (map) { try { map.remove(); } catch (e) {} map = null; } + if (map) { + // Bounded tile-sync registry: drop the record before Leaflet removal + // (the container can stay attached, so isConnected pruning can't see it). + try { if (window.__mcNodeTileSyncUnregister) window.__mcNodeTileSyncUnregister(map); } catch (e) {} + try { map.remove(); } catch (e) {} + map = null; + } covLayer = null; gapRenderer = null; } diff --git a/test-all.sh b/test-all.sh index 356d61ca8..641fca736 100755 --- a/test-all.sh +++ b/test-all.sh @@ -99,6 +99,7 @@ node tests/unit/test-issue-1456-score-labels.js node tests/unit/test-issue-1461-mobile-page-actions.js node tests/unit/test-issue-1470-card-bg-contrast.js node tests/unit/test-issue-1470-node-tile-helper.js +node tests/unit/test-tile-resolver.js node tests/unit/test-issue-1473-prefix-generator.js node tests/unit/test-issue-1473-reserved-prefixes.js node tests/unit/test-issue-1485-live-anim-z.js diff --git a/tests/unit/test-issue-1862-map-region-filter.js b/tests/unit/test-issue-1862-map-region-filter.js index 58f2e5c25..bcc1d4f24 100644 --- a/tests/unit/test-issue-1862-map-region-filter.js +++ b/tests/unit/test-issue-1862-map-region-filter.js @@ -52,6 +52,13 @@ function makeSandbox(stored) { vm.createContext(ctx); vm.runInContext(fs.readFileSync('public/roles.js', 'utf8'), ctx); for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k]; + // map.js's render path (index.html order) uses the tile-provider module's + // hooks. Stub the two the sandbox needs — loading the full module would + // drag the Leaflet layer control into a mock that doesn't support it. + // (PR #2386 CI catch: map.js calls MC_isDarkTheme() during page render.) + ctx.window.MC_isDarkTheme = () => false; + ctx.window.MC_resolveTile = () => ({ type: 'light', id: null, url: 'https://tiles.example/{z}/{x}/{y}.png', attribution: 'test', maxZoom: 19, refUrl: null, invertFilter: null }); + for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k]; vm.runInContext(fs.readFileSync('public/map.js', 'utf8'), ctx); for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k]; return ctx; @@ -355,6 +362,11 @@ async function makePage(opts) { vm.createContext(ctx); vm.runInContext(fs.readFileSync('public/roles.js', 'utf8'), ctx); for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k]; + // Same tile-provider stubs as the first harness above — map.js page render + // depends on them (index.html load order). + ctx.window.MC_isDarkTheme = () => false; + ctx.window.MC_resolveTile = () => ({ type: 'light', id: null, url: 'https://tiles.example/{z}/{x}/{y}.png', attribution: 'test', maxZoom: 19, refUrl: null, invertFilter: null }); + for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k]; vm.runInContext(fs.readFileSync('public/map.js', 'utf8'), ctx); for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k]; diff --git a/tests/unit/test-tile-resolver.js b/tests/unit/test-tile-resolver.js new file mode 100644 index 000000000..38d0f949b --- /dev/null +++ b/tests/unit/test-tile-resolver.js @@ -0,0 +1,508 @@ +/* test-tile-resolver.js — shared tile resolution contract (#1420/#1470 followup, + * node-map light-tiles refactor). + * + * Bug being pinned: roles.js getTileUrl() resolved light mode from the frozen + * TILE_LIGHT scalar — every consumer that is not map.js/live.js (node detail + * inset map and its reusers, analytics minimap) shipped the wrong basemap in + * light mode: the user's Light Mode Provider pick and the operator's + * map.tiles.lightDefault were ignored, and a map created before + * /api/config/client resolved kept a keyless Carto URL (watermark) forever, + * because only map.js and live.js listen for mc-tile-provider-changed. + * + * Contract under test (public/map-tile-providers.js): + * window.MC_resolveTile(isDark) → { type, id, url, attribution, maxZoom, + * refUrl, invertFilter, override } + * - url is ALWAYS a string (function-typed providers are invoked, #1614) + * - light + dark pick the registry entry for the theme + * (localStorage pick > server lightDefault/darkDefault > shipped default) + * - explicit operator overrides (MC_LEGACY_TILE_OVERRIDE + TILE_* scalar) + * beat the user's provider pick + * - provider attribution/maxZoom/refUrl/invertFilter are carried through + * - resolution is lazy: re-running MC_initTileRegistry after async config + * changes the next resolve's output (Carto key picked up without reload) + * window.MC_isDarkTheme() → data-theme attr, else prefers-color-scheme + * nodes.js _applyTilesToNodeMap: light pick honoured; re-sync on + * mc-tile-provider-changed swaps layers in place (never stacks); maps gone + * from the DOM are pruned; late config is picked up. + * + * Pure vm sandbox, no browser or dependencies — mirrors the harness used by + * test-issue-1420-tile-providers.js / test-issue-1470-node-tile-helper.js. + * Runs via: node tests/unit/test-tile-resolver.js + */ +'use strict'; +const REPO_ROOT = require('path').resolve(__dirname, '..', '..'); +const vm = require('vm'); +const fs = require('fs'); +const path = require('path'); +const assert = require('assert'); + +let passed = 0, failed = 0; +function test(name, fn) { + try { fn(); passed++; console.log(' ✅ ' + name); } + catch (e) { failed++; console.log(' ❌ ' + name + ': ' + e.message); } +} + +function makeStorage() { + const store = {}; + return { + getItem(k) { return Object.prototype.hasOwnProperty.call(store, k) ? store[k] : null; }, + setItem(k, v) { store[k] = String(v); }, + removeItem(k) { delete store[k]; }, + clear() { for (const k of Object.keys(store)) delete store[k]; }, + }; +} + +/** Sandbox where documentElement's data-theme is MUTABLE (theme flips). */ +function makeSandbox(opts) { + opts = opts || {}; + let theme = opts.theme || 'dark'; + const listeners = {}; + const events = []; + const ctx = { + console, + setTimeout, clearTimeout, + JSON, Date, Math, Object, Array, String, Number, Boolean, Set, Map, + fetch: () => Promise.resolve({ ok: false, json: () => Promise.resolve({}) }), + localStorage: makeStorage(), + document: { + documentElement: { + getAttribute: (k) => k === 'data-theme' ? theme : null, + setAttribute: (k, v) => { if (k === 'data-theme') theme = v; }, + style: { getPropertyValue: () => '' }, + }, + querySelector: () => null, + querySelectorAll: () => [], + getElementById: () => null, + createElement: () => ({ style: {}, appendChild: () => {}, setAttribute: () => {}, addEventListener: () => {} }), + addEventListener: () => {}, + body: { appendChild: () => {}, style: {} }, + head: { appendChild: () => {} }, + readyState: 'complete', + }, + window: { + addEventListener: (type, fn) => { (listeners[type] = listeners[type] || []).push(fn); }, + removeEventListener: (type, fn) => { + const l = listeners[type] || []; + const i = l.indexOf(fn); + if (i >= 0) l.splice(i, 1); + }, + dispatchEvent: (ev) => { events.push(ev); return true; }, + matchMedia: () => ({ matches: opts.prefersDark === true, addEventListener: () => {} }), + }, + CustomEvent: function (type, init) { this.type = type; this.detail = (init && init.detail) || null; }, + }; + ctx.window.localStorage = ctx.localStorage; + ctx.window.document = ctx.document; + ctx.globalThis = ctx; + vm.createContext(ctx); + ctx.setTheme = (t) => { theme = t; }; + ctx.listeners = listeners; + ctx.fire = (type, ev) => { (listeners[type] || []).forEach(fn => fn(ev)); }; + return ctx; +} + +function loadInto(ctx, relPath) { + const src = fs.readFileSync(path.join(REPO_ROOT, relPath), 'utf8'); + vm.runInContext(src, ctx, { filename: relPath }); + for (const k of Object.keys(ctx.window)) { + if (!(k in ctx)) ctx[k] = ctx.window[k]; + } +} + +/** Leaflet mock recording tileLayer/addTo/removeLayer with setUrl support. */ +function makeL() { + const layers = []; + let layerId = 0; + const L = { + tileLayer(url, opts) { + const layer = { id: ++layerId, url, opts, _removed: false, + addTo(map) { map._layers.push(this); layers.push({ layer: this, map }); return this; } }; + return layer; + }, + map() { return { _layers: [], getPane: () => null }; }, + }; + return { + L, layers, + newMap() { + const map = { _layers: [] }; + map.getPane = (n) => n === 'tilePane' ? (map._pane = map._pane || { style: { filter: '' } }) : null; + map.getContainer = () => ({ isConnected: map._connected === false ? false : true }); + map.removeLayer = (layer) => { + layer._removed = true; + const i = map._layers.indexOf(layer); + if (i >= 0) map._layers.splice(i, 1); + }; + return map; + }, + }; +} + +function extractApplyTilesHelper() { + const nodesSrc = fs.readFileSync(path.join(REPO_ROOT, 'public', 'nodes.js'), 'utf8'); + const startMatch = nodesSrc.match(/function\s+_applyTilesToNodeMap\s*\(map\)\s*\{/); + if (!startMatch) throw new Error('_applyTilesToNodeMap definition not found in public/nodes.js'); + const start = startMatch.index; + let depth = 0, i = start; + for (; i < nodesSrc.length; i++) { + const ch = nodesSrc[i]; + if (ch === '{') depth++; + else if (ch === '}') { depth--; if (depth === 0) { i++; break; } } + } + return nodesSrc.slice(start, i); +} + +console.log('── MC_resolveTile / MC_isDarkTheme / node-map tile sync ──'); + +function loadResolver(ctx) { + loadInto(ctx, 'public/map-tile-providers.js'); + loadInto(ctx, 'public/roles.js'); +} + +// ── Resolver basics ───────────────────────────────────────────────────────── + +test('resolve(light, no pick) → Carto light_all, no key when none configured', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const r = ctx.window.MC_resolveTile(false); + assert.strictEqual(r.type, 'light'); + assert.strictEqual(r.id, 'carto-light'); + assert.ok(/light_all/.test(r.url), 'light_all URL — got ' + r.url); + assert.ok(!/\?key=/.test(r.url), 'no key when unconfigured — got ' + r.url); + assert.strictEqual(r.maxZoom, 19); + assert.strictEqual(r.invertFilter, null); + assert.strictEqual(r.refUrl, null); + assert.ok(r.attribution && /Carto/.test(r.attribution), 'Carto attribution — got ' + r.attribution); +}); + +test('resolve(light) carries the configured Carto key WITHOUT config-patching (lazy #1614)', () => { + const ctx = makeSandbox({ theme: 'light' }); + ctx.window.MC_MAP_CFG = { tiles: { providers: { carto: { enabled: true, key: 'SECRET-KEY' } } } }; + loadResolver(ctx); + const r = ctx.window.MC_resolveTile(false); + assert.ok(/\?key=SECRET-KEY/.test(r.url), 'keyed URL — got ' + r.url); +}); + +test('resolve(light, pick=carto-voyager) → voyager tiles (the node-map light bug)', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + ctx.window.MC_setLightTileProvider('carto-voyager'); + const r = ctx.window.MC_resolveTile(false); + assert.strictEqual(r.id, 'carto-voyager'); + assert.ok(/voyager/.test(r.url), 'voyager URL — got ' + r.url); +}); + +test('resolve(light, stored pick disabled by config) → falls back cleanly', () => { + const ctx = makeSandbox({ theme: 'light' }); + ctx.window.MC_MAP_CFG = { tiles: { providers: { carto: { enabled: false } } } }; + loadResolver(ctx); + ctx.window.localStorage.setItem('mc-light-tile-provider', 'carto-voyager'); // no longer in registry + const r = ctx.window.MC_resolveTile(false); + assert.ok(r.url, 'still resolves a URL — got ' + r.url); + assert.ok(!/voyager/.test(r.url), 'disabled pick not used — got ' + r.url); + assert.strictEqual(r.override, false); + // Review followup: the id must name the entry the URL actually came from. + // Here even the shipped default is gone from the registry (carto disabled + // entirely), so the constant fallback applies and no id exists. + assert.strictEqual(r.id, null, 'no id for the constant fallback — got ' + r.id); +}); + +test('resolve(desc.id) reports the server default entry when the stored pick is disabled', () => { + const ctx = makeSandbox({ theme: 'dark' }); + ctx.window.MC_MAP_CFG = { tiles: { darkDefault: 'carto-dark', providers: { carto: { enabled: true } } } }; + loadResolver(ctx); + ctx.window.localStorage.setItem('mc-dark-tile-provider', 'nonexistent'); // invalid id → default + const r = ctx.window.MC_resolveTile(true); + assert.strictEqual(r.id, 'carto-dark', 'id = default entry — got ' + r.id); + assert.ok(/dark_all/.test(r.url)); +}); + +test('resolve(light, server lightDefault=carto-voyager, no user pick) → voyager', () => { + const ctx = makeSandbox({ theme: 'light' }); + ctx.window.MC_MAP_CFG = { tiles: { providers: { carto: { enabled: true } }, lightDefault: 'carto-voyager' } }; + loadResolver(ctx); + const r = ctx.window.MC_resolveTile(false); + assert.ok(/voyager/.test(r.url), 'operator lightDefault honoured — got ' + r.url); +}); + +test('resolve(dark, pick=carto-voyager-dark) → invertFilter + attrs carried', () => { + const ctx = makeSandbox({ theme: 'dark' }); + loadResolver(ctx); + ctx.window.MC_setDarkTileProvider('carto-voyager-dark'); + const r = ctx.window.MC_resolveTile(true); + assert.strictEqual(r.id, 'carto-voyager-dark'); + assert.ok(/voyager/.test(r.url), 'voyager URL — got ' + r.url); + assert.ok(/invert\(/.test(r.invertFilter), 'invertFilter — got ' + JSON.stringify(r.invertFilter)); + assert.strictEqual(r.maxZoom, 19); +}); + +test('resolve(maxZoom passthrough): usgs-topo pick → maxZoom 16', () => { + const ctx = makeSandbox({ theme: 'light' }); + ctx.window.MC_MAP_CFG = { tiles: { providers: { usgs: { enabled: true } } } }; + loadResolver(ctx); + ctx.window.MC_setLightTileProvider('usgs-topo'); + const r = ctx.window.MC_resolveTile(false); + assert.ok(/USGSTopo|basemap\.nationalmap/.test(r.url), 'usgs URL — got ' + r.url); + assert.strictEqual(r.maxZoom, 16, 'operator maxZoom carried — got ' + r.maxZoom); +}); + +test('explicit operator override (MC_LEGACY_TILE_OVERRIDE) beats the user pick', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + // TILE_LIGHT is read as a bare global by the resolver (in the browser it IS + // window.TILE_LIGHT); mirror the window-stub write onto the vm global. + ctx.window.TILE_LIGHT = 'https://tiles.operator.example/light/{z}/{x}/{y}.png'; + ctx.TILE_LIGHT = ctx.window.TILE_LIGHT; + ctx.window.MC_LEGACY_TILE_OVERRIDE = { dark: false, light: true }; + ctx.window.MC_setLightTileProvider('carto-voyager'); // user pick loses to the override + const r = ctx.window.MC_resolveTile(false); + assert.strictEqual(r.url, 'https://tiles.operator.example/light/{z}/{x}/{y}.png', 'override URL wins'); + assert.strictEqual(r.override, true); +}); + +test('resolver invokes function-typed urls and never returns a function (#1614)', () => { + const ctx = makeSandbox({ theme: 'dark' }); + loadResolver(ctx); + ctx.window.MC_TILE_PROVIDERS = { + 'fn-provider': { provider: 'carto', label: 'Fn', + url: () => 'https://{s}.tiles.example.com/dark/{z}/{x}/{y}.png', + attribution: 'x', type: 'dark' }, + }; + ctx.window.MC_getDarkTileProvider = () => 'fn-provider'; + const r = ctx.window.MC_resolveTile(true); + assert.strictEqual(typeof r.url, 'string'); + assert.ok(/\{z\}/.test(r.url) && /\{x\}/.test(r.url) && /\{y\}/.test(r.url)); +}); + +test('lazy: url built at call time picks up a Carto key arriving after load (config race)', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const before = ctx.window.MC_resolveTile(false).url; + assert.ok(!/\?key=/.test(before), 'pre-config: no key — got ' + before); + // Async config arrives: registry re-init (exactly what roles.js does on + // MeshConfigReady) → next resolve carries the key without any reload. + ctx.window.MC_MAP_CFG = { tiles: { providers: { carto: { enabled: true, key: 'KEY-LATER' } } } }; + ctx.window.MC_initTileRegistry(true); + const after = ctx.window.MC_resolveTile(false).url; + assert.ok(/\?key=KEY-LATER/.test(after), 'post-config: keyed — got ' + after); +}); + +// ── MC_isDarkTheme + getTileUrl wrapper ───────────────────────────────────── + +test('MC_isDarkTheme follows data-theme attr; falls back to OS when unset', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + assert.strictEqual(ctx.window.MC_isDarkTheme(), false); + ctx.setTheme('dark'); + assert.strictEqual(ctx.window.MC_isDarkTheme(), true); + // attr absent + ctx.document.documentElement.getAttribute = (k) => k === 'data-theme' ? null : null; + // prefer-color-scheme dark + ctx.window.matchMedia = (q) => ({ matches: /dark/.test(q), addEventListener: () => {} }); + assert.strictEqual(ctx.window.MC_isDarkTheme(), true, 'OS preference used when no attr'); + ctx.window.matchMedia = () => ({ matches: false, addEventListener: () => {} }); + assert.strictEqual(ctx.window.MC_isDarkTheme(), false); +}); + +test('getTileUrl() light returns the stored light pick (wrapper integration)', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + ctx.window.MC_setLightTileProvider('carto-voyager'); + const url = ctx.window.getTileUrl(); + assert.ok(/voyager/.test(url), 'getTileUrl honours light pick — got ' + url); +}); + +test('getTileUrl() dark still returns a string with mocked registry (1614 harness shape)', () => { + const ctx = makeSandbox({ theme: 'dark' }); + loadResolver(ctx); + ctx.window.MC_TILE_PROVIDERS = { + 'str-provider': { provider: 'carto', label: 'Str', + url: 'https://tiles.example.com/dark/{z}/{x}/{y}.png', attribution: 'x', type: 'dark' }, + }; + ctx.window.MC_getDarkTileProvider = () => 'str-provider'; + assert.strictEqual(ctx.window.getTileUrl(), 'https://tiles.example.com/dark/{z}/{x}/{y}.png'); +}); + +// ── nodes.js _applyTilesToNodeMap ─────────────────────────────────────────── + +function loadNodeHelper(ctx, makeMap, L) { + ctx.L = L; + const map = makeMap(); + ctx._map = map; + vm.runInContext(extractApplyTilesHelper(), ctx, { filename: 'nodes.js#_applyTilesToNodeMap' }); + vm.runInContext('window.__lastNodeTileLayer = _applyTilesToNodeMap(_map);', ctx); + return map; +} + +test('node helper: light + light pick=carto-voyager → voyager base layer (acceptance #1)', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + ctx.window.MC_setLightTileProvider('carto-voyager'); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + const base = map._layers.filter(l => /voyager|light_all/.test(l.url)); + assert.ok(base.length === 1 && /voyager/.test(base[0].url), + 'exactly one base layer, voyager — got ' + JSON.stringify(map._layers.map(l => l.url))); +}); + +test('node helper: maxZoom from the provider, not hardcoded (usgs-topo → 16)', () => { + const ctx = makeSandbox({ theme: 'light' }); + ctx.window.MC_MAP_CFG = { tiles: { providers: { usgs: { enabled: true } } } }; + loadResolver(ctx); + ctx.window.MC_setLightTileProvider('usgs-topo'); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + assert.ok(map._layers.length >= 1, 'layer added'); + assert.strictEqual(map._layers[0].opts.maxZoom, 16, 'provider maxZoom — got ' + map._layers[0].opts.maxZoom); +}); + +test('node helper: re-sync on mc-tile-provider-changed swaps layers, never stacks', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + assert.strictEqual(map._layers.length, 1); + ctx.window.MC_setLightTileProvider('carto-voyager'); // dispatches the change event + ctx.fire('mc-tile-provider-changed', { type: 'mc-tile-provider-changed', detail: { id: 'carto-voyager', type: 'light' } }); + const bases = map._layers; // removeLayer splices, so this IS the live set + assert.strictEqual(bases.length, 1, 'exactly one live base layer after re-sync — got ' + bases.length); + assert.ok(/voyager/.test(bases[0].url), 'swapped to the new provider — got ' + bases[0].url); + // Removed layers are gone from the map but still visible in the creation log. + const removedOld = mock.layers.filter(e => e.map === map && e.layer._removed && /light_all/.test(e.layer.url)); + assert.strictEqual(removedOld.length, 1, 'old positron layer was removed, not stacked'); +}); + +test('node helper: late Carto key (fromConfig re-init) is picked up in place', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + assert.ok(!/\?key=/.test(map._layers[0].url), 'pre-config: keyless — got ' + map._layers[0].url); + ctx.window.MC_MAP_CFG = { tiles: { providers: { carto: { enabled: true, key: 'KEY-LATER' } } } }; + ctx.window.MC_initTileRegistry(true); // fires fromConfig → maps re-sync + ctx.fire('mc-tile-provider-changed', { type: 'mc-tile-provider-changed', detail: { fromConfig: true } }); + assert.ok(/\?key=KEY-LATER/.test(map._layers.filter(l => !l._removed)[0].url), + 'post-config: keyed — got ' + map._layers.filter(l => !l._removed)[0].url); +}); + +test('node helper: pick for the OTHER theme does not re-sync', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + const before = map._layers[0].url; + ctx.window.MC_setDarkTileProvider('carto-voyager-dark'); // dispatches with detail.type='dark' + ctx.fire('mc-tile-provider-changed', { type: 'mc-tile-provider-changed', detail: { id: 'carto-voyager-dark', type: 'dark' } }); + assert.strictEqual(map._layers.filter(l => !l._removed)[0].url, before, + 'light tile layer untouched by a dark pick'); +}); + +test('node helper: theme flip re-syncs via the data-theme observer path (onChange(null))', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + ctx.setTheme('dark'); + // Trigger the prune/sync entry point the MutationObserver calls. + const st = ctx.window.__mcNodeTileSync; + st.onChange(null); + const live = map._layers.filter(l => !l._removed); + assert.strictEqual(live.length, 1, 'one live base layer after theme flip'); + assert.ok(/dark_all|voyager/.test(live[0].url), 'now a dark provider — got ' + live[0].url); +}); + +test('node helper: map whose container left the DOM is pruned (no leak, no crash)', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + assert.ok(Object.prototype.hasOwnProperty.call(map, 'getContainer'), 'prune test needs a getContainer-aware map'); + const st = ctx.window.__mcNodeTileSync; + assert.strictEqual(st.maps.length, 1); + map.getContainer = () => ({ isConnected: false }); // SPA navigated away + ctx.fire('mc-tile-provider-changed', { type: 'mc-tile-provider-changed', detail: { fromConfig: true } }); + assert.strictEqual(st.maps.length, 0, 'disconnected map dropped from the sync registry'); +}); + +test('node helper: two maps on one page both re-sync with one shared listener', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const mapA = loadNodeHelper(ctx, mock.newMap, mock.L); + ctx._map = null; + const mapB = (() => { const m = mock.newMap(); ctx._map = m; return m; })(); + vm.runInContext('_applyTilesToNodeMap(_map);', ctx); + ctx.window.MC_setLightTileProvider('carto-voyager'); + ctx.fire('mc-tile-provider-changed', { type: 'mc-tile-provider-changed', detail: { id: 'carto-voyager', type: 'light' } }); + for (const m of [mapA, mapB]) { + const live = m._layers.filter(l => !l._removed); + assert.strictEqual(live.length, 1, 'one live base layer per map'); + assert.ok(/voyager/.test(live[0].url), 'both maps swapped'); + } +}); + +// Reapplying the same helper on one map instance must not stack a second sync. +test('node helper: re-apply on the SAME map replaces the record, one base layer', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + vm.runInContext('_applyTilesToNodeMap(_map);', ctx); // rx-coverage-style re-init + assert.strictEqual(Object.keys(map._layers).length, map._layers.length, 'sanity'); + const live = map._layers.filter(l => !l._removed); + assert.strictEqual(live.length, 1, 'no stacking on same-map re-init — got ' + live.length + + (live.length ? ' url=' + live[0].url : '')); + assert.strictEqual(ctx.window.__mcNodeTileSync.maps.length, 1, 'no duplicate sync records'); +}); + +// ── Review followup: bounded tile-sync registry (AGENTS.md rule 0) ────────── + +test('node helper: registration prunes records of maps gone from the DOM (bounded)', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + ctx.L = mock.L; + vm.runInContext(extractApplyTilesHelper(), ctx, { filename: 'nodes.js#_applyTilesToNodeMap' }); + // Walk through 50 node pages WITHOUT any theme/provider change (so the + // shared onChange prune never runs) — the registry must still stay bounded. + for (let i = 0; i < 50; i++) { + const map = mock.newMap(); + ctx._map = map; + vm.runInContext('window.__lastNodeTileLayer = _applyTilesToNodeMap(_map);', ctx); + map._connected = false; // SPA navigated away (no explicit unregister call) + } + assert.strictEqual(ctx.window.__mcNodeTileSync.maps.length, 1, + 'one live record after 50 navigations — got ' + ctx.window.__mcNodeTileSync.maps.length); +}); + +test('node helper: explicit unregister drops the record + its layers', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + assert.ok(typeof ctx.window.__mcNodeTileSyncUnregister === 'function', + 'unregister hook exists after the first map registers'); + assert.strictEqual(ctx.window.__mcNodeTileSync.maps.length, 1); + ctx.window.__mcNodeTileSyncUnregister(map); + assert.strictEqual(ctx.window.__mcNodeTileSync.maps.length, 0, 'record dropped'); + // The layers were also detached from the map (removeDetailMap removes the + // map right after, but the hook must not leak a layer for safety). + assert.strictEqual(map._layers.filter(l => !l._removed).length, 0, 'layers detached'); + // Firing the shared listener afterwards must not resurrect anything. + ctx.fire('mc-tile-provider-changed', { type: 'mc-tile-provider-changed', detail: { fromConfig: true } }); + assert.strictEqual(ctx.window.__mcNodeTileSync.maps.length, 0, 'stays empty'); +}); + +test('node helper: unregister is idempotent and tolerates unknown maps', () => { + const ctx = makeSandbox({ theme: 'light' }); + loadResolver(ctx); + const mock = makeL(); + const map = loadNodeHelper(ctx, mock.newMap, mock.L); + ctx.window.__mcNodeTileSyncUnregister(map); + ctx.window.__mcNodeTileSyncUnregister(map); // second call: no throw + ctx.window.__mcNodeTileSyncUnregister(null); // null: no throw + ctx.window.__mcNodeTileSyncUnregister({}); // unknown map: no throw + assert.strictEqual(ctx.window.__mcNodeTileSync.maps.length, 0); +}); + +console.log(`\ntile resolver: ${passed} passed, ${failed} failed`); +process.exit(failed === 0 ? 0 : 1); From c2e770ef65537ecea65582d2a7c51f61c553bc37 Mon Sep 17 00:00:00 2001 From: n30nex Date: Sun, 15 Nov 2026 06:23:50 -0500 Subject: [PATCH 02/30] docs: archive superseded repeater liveness plans (#2392) Partial fix for #1385 (PR-E). Move the two April repeater-liveness documents from `docs/superpowers/` into existing `docs/archive/` with `git mv`. Preserve their dated filenames, content and headings; add historical notices clarifying that the proposed `relaying` status/signature is outdated and linking current guidance. Validation: exact commit blobs preserve 41,483 original bytes and 24 headings after removing only notices; four local links resolve; no tracked old-path references; whitespace and PII checks pass. TDD exemption: pure documentation, no behavior change. No runtime, configuration, customizer, test, hierarchy or ignore-rule changes. Application suites were not rerun. Both published Markdown pages and their guidance links render correctly. [Docs-only CI](https://github.com/Kpa-clawbot/CoreScope/actions/runs/43199869942) and three independent reviews pass. The umbrella issue stays open pending maintainer reconciliation. Co-authored-by: n30nex <6686206+n30nex@users.noreply.github.com> --- .../2026-04-15-repeater-liveness-design.md | 6 ++++++ .../plans => archive}/2026-04-15-repeater-liveness.md | 6 ++++++ 2 files changed, 12 insertions(+) rename docs/{superpowers/specs => archive}/2026-04-15-repeater-liveness-design.md (94%) rename docs/{superpowers/plans => archive}/2026-04-15-repeater-liveness.md (99%) diff --git a/docs/superpowers/specs/2026-04-15-repeater-liveness-design.md b/docs/archive/2026-04-15-repeater-liveness-design.md similarity index 94% rename from docs/superpowers/specs/2026-04-15-repeater-liveness-design.md rename to docs/archive/2026-04-15-repeater-liveness-design.md index d9cde1d22..420502cd7 100644 --- a/docs/superpowers/specs/2026-04-15-repeater-liveness-design.md +++ b/docs/archive/2026-04-15-repeater-liveness-design.md @@ -1,5 +1,11 @@ # Repeater Liveness — Design Spec +> **Archived plan.** Historical planning material; proposals, status claims, and +> instructions below may be outdated or unimplemented. The proposed `relaying` +> status and helper signature are not current. For current liveness guidance, +> see [AGENTS.md](../../AGENTS.md#last_heard-vs-last_seen) and the +> [status helpers](../../public/roles.js). + **Issue:** Kpa-clawbot/CoreScope#662 **Date:** 2026-04-15 **Status:** Approved diff --git a/docs/superpowers/plans/2026-04-15-repeater-liveness.md b/docs/archive/2026-04-15-repeater-liveness.md similarity index 99% rename from docs/superpowers/plans/2026-04-15-repeater-liveness.md rename to docs/archive/2026-04-15-repeater-liveness.md index 53badc61e..5b761a4d2 100644 --- a/docs/superpowers/plans/2026-04-15-repeater-liveness.md +++ b/docs/archive/2026-04-15-repeater-liveness.md @@ -1,5 +1,11 @@ # Repeater Liveness Implementation Plan +> **Archived plan.** Historical planning material; proposals, status claims, and +> instructions below may be outdated or unimplemented. The proposed `relaying` +> status and helper signature are not current. For current liveness guidance, +> see [AGENTS.md](../../AGENTS.md#last_heard-vs-last_seen) and the +> [status helpers](../../public/roles.js). + > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Distinguish repeaters that are actively relaying traffic from those that are alive but idle, using a precomputed O(log n) sorted-timestamp index. From ea8778425751afcc823704b2fa9274ad3080747c Mon Sep 17 00:00:00 2001 From: n30nex Date: Sun, 15 Nov 2026 06:24:20 -0500 Subject: [PATCH 03/30] refactor(live): reuse shared timestamp renderer (#2395) Live timestamps duplicated the shared timestamp markup in `app.js`. Keep `formatLiveTimestampHtml` as the input adapter and delegate its final markup to `renderTimestampHtml`, retaining the existing missing-helper fallback and Date/number/string normalization. Partial follow-up to #1154 U10 and the [maintainer note on #2283](https://github.com/Kpa-clawbot/CoreScope/pull/2283#pullrequestreview-5850899652). This addresses only the Live wrapper; the umbrella remains open. Validation: - All 229 existing standalone frontend suites pass. Two shell-dependent suites passed after selecting the installed shell/interpreter for the local test process. - 5,040 exact-base/candidate comparisons match byte-for-byte across timestamp inputs, preferences, escaping, future warnings, and missing-helper fallbacks. - Actual Go fixture and Chromium: node-panel and replay-feed timestamps checked on desktop and phone, with no page exceptions. The existing phone portrait layout hides the feed; its replay DOM remains populated. - ESLint: zero errors. No new settings, requests, dependencies, or caches; constant work per timestamp, with no speedup claimed. Pure-refactor TDD exemption: **tests/ files diff: no changes**. No test files added or modified; existing assertions remain green. [Final CI](https://github.com/Kpa-clawbot/CoreScope/actions/runs/43202375909) and three independent reviews pass. Parent independently repeated the Live unit, parity and post-push browser checks. Co-authored-by: n30nex <6686206+n30nex@users.noreply.github.com> --- public/live.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/public/live.js b/public/live.js index b4f86aa21..8099ee85c 100644 --- a/public/live.js +++ b/public/live.js @@ -306,11 +306,7 @@ } const d = isoLike ? new Date(isoLike) : null; const iso = d && isFinite(d.getTime()) ? d.toISOString() : null; - const f = formatTimestampWithTooltip(iso, getTimestampMode()); - const warn = f.isFuture - ? ' ' - : ''; - return `${escapeHtml(f.text)}${warn}`; + return renderTimestampHtml(iso); } function initResizeHandler() { From 0e23c248478d61262ae06d9753cb6ed10b02c3bf Mon Sep 17 00:00:00 2001 From: SaarMesh-Bot Date: Sun, 15 Nov 2026 12:24:27 +0100 Subject: [PATCH 04/30] fix(scope-stats): report total and split unscoped by route (#2364) (#2368) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #2364. ## Problem Since #1838, `GetScopeStats` folds every non-transport transmission (FLOOD 1, DIRECT 2) into `summary.unscoped`, while `transportTotal` and `scoped` still cover transport routes (0, 3) only. The documented `transportTotal = scoped + unscoped` no longer holds, and a client computing an unscoped share against `transportTotal` gets >100% (the reporter shows `transportTotal 7620`, `unscoped 14320`). ## Fix — additive, no existing field changes value `summary` gains: | field | meaning | |---|---| | `total` | all observed transmissions, routes 0–3 (= `scoped + unscoped`) | | `unscopedTransport` | route 0/3 with Code1 = 0000 | | `unscopedFlood` | route 1 — unscoped by protocol | | `unscopedDirect` | route 2 — unscoped by protocol | Invariants (now asserted in `TestGetScopeStats`): ``` transportTotal = scoped + unscopedTransport unscoped = unscopedTransport + unscopedFlood + unscopedDirect total = scoped + unscoped ``` The non-transport count query keeps its single scan; it just splits route 1 vs 2 with `CASE`. On the design question in the issue: rather than changing what `unscoped` means (the Scopes tab and #1842 rely on it), the split lets a rollout view use `unscopedFlood` directly: repeaters apply region rejection to flood routes only (`isRouteFlood()` in `examples/simple_repeater/MyMesh.cpp`), so DIRECT traffic is not subject to flood-region filtering. `docs/api-spec.md` now says so, spells out the route mapping, and notes that `timeSeries` is transport-only (its `unscoped` matches `unscopedTransport`). ## Frontend Scopes tab uses `summary.total` when present and shows `N transport, N flood, N direct` on the Unscoped card; falls back unchanged for older servers. The cards are built by `scopeSummaryCardsHtml(summary)` (exposed as `window._analyticsScopeSummaryCardsHtml`). ## Tested - `go vet ./...` (cmd/server) clean, `gofmt -l` clean - `go test -run ScopeStats ./...` — pass (incl. extended `TestGetScopeStats` and `/api/scope-stats` route test) - `node --check public/analytics.js`; `tests/unit/test-issue-1375-scope-stats-fetch.js`, `test-issue-1979-scope-adverts-by-role.js` pass - new `tests/unit/test-issue-2364-scope-summary-cards.js` (vm sandbox, 11 assertions: shares of `total`, route split, fallback for servers without `total`/split, partial split, empty window); full `test-all.sh` green Co-Authored-By: Claude --------- Co-authored-by: SaarMesh-Bot <300107934+SaarMesh-Bot@users.noreply.github.com> Co-authored-by: Claude --- cmd/server/db.go | 15 ++- cmd/server/db_test.go | 18 +++ cmd/server/routes_test.go | 8 ++ cmd/server/types.go | 22 ++- docs/api-spec.md | 23 +++- public/analytics.js | 50 ++++--- test-all.sh | 1 + .../test-issue-2364-scope-summary-cards.js | 126 ++++++++++++++++++ 8 files changed, 231 insertions(+), 32 deletions(-) create mode 100644 tests/unit/test-issue-2364-scope-summary-cards.js diff --git a/cmd/server/db.go b/cmd/server/db.go index ea74bcfd0..a3c628d13 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -3333,7 +3333,7 @@ func (db *DB) GetScopeStats(window string) (*ScopeStatsResponse, error) { if err := row.Scan( &resp.Summary.TransportTotal, &resp.Summary.Scoped, - &resp.Summary.Unscoped, + &resp.Summary.UnscopedTransport, &resp.Summary.UnknownScope, ); err != nil { return nil, fmt.Errorf("scope summary query: %w", err) @@ -3343,14 +3343,19 @@ func (db *DB) GetScopeStats(window string) (*ScopeStatsResponse, error) { // transport_code_1 per MeshCore protocol, so they are inherently unscoped. // Fold their count into Summary.Unscoped so the analytics denominator // reflects total-observed-transmissions rather than only transport-eligible. - var nonTransportUnscoped int + // #2364: keep the per-route split and report Total so the summary adds up. + // Same single scan as before; the CASE split costs nothing extra. if err := db.conn.QueryRow(` - SELECT COUNT(*) FROM transmissions + SELECT + COALESCE(SUM(CASE WHEN route_type = 1 THEN 1 ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN route_type = 2 THEN 1 ELSE 0 END), 0) + FROM transmissions WHERE `+routeTypeNonTransportSQL+` AND first_seen >= ? - `, since).Scan(&nonTransportUnscoped); err != nil { + `, since).Scan(&resp.Summary.UnscopedFlood, &resp.Summary.UnscopedDirect); err != nil { return nil, fmt.Errorf("scope non-transport count query: %w", err) } - resp.Summary.Unscoped += nonTransportUnscoped + resp.Summary.Unscoped = resp.Summary.UnscopedTransport + resp.Summary.UnscopedFlood + resp.Summary.UnscopedDirect + resp.Summary.Total = resp.Summary.Scoped + resp.Summary.Unscoped // Per-region counts (named regions only) rows, err := db.conn.Query(scopeStatsByRegionQuery, since) diff --git a/cmd/server/db_test.go b/cmd/server/db_test.go index 65fe6a822..0a3f68d62 100644 --- a/cmd/server/db_test.go +++ b/cmd/server/db_test.go @@ -2310,6 +2310,24 @@ func TestGetScopeStats(t *testing.T) { if stats.Summary.UnknownScope != 1 { t.Errorf("UnknownScope = %d, want 1", stats.Summary.UnknownScope) } + // #2364: per-route split of Unscoped, and a Total the summary adds up to. + s := stats.Summary + if s.UnscopedTransport != 1 || s.UnscopedFlood != 1 || s.UnscopedDirect != 1 { + t.Errorf("unscoped split = transport %d / flood %d / direct %d, want 1/1/1", + s.UnscopedTransport, s.UnscopedFlood, s.UnscopedDirect) + } + if s.Total != 5 { + t.Errorf("Total = %d, want 5 (all routes)", s.Total) + } + if s.TransportTotal != s.Scoped+s.UnscopedTransport { + t.Errorf("transportTotal %d != scoped %d + unscopedTransport %d", s.TransportTotal, s.Scoped, s.UnscopedTransport) + } + if s.Unscoped != s.UnscopedTransport+s.UnscopedFlood+s.UnscopedDirect { + t.Errorf("unscoped %d != sum of its route split", s.Unscoped) + } + if s.Total != s.Scoped+s.Unscoped { + t.Errorf("total %d != scoped %d + unscoped %d", s.Total, s.Scoped, s.Unscoped) + } if len(stats.ByRegion) != 1 || stats.ByRegion[0].Name != "#belgium" || stats.ByRegion[0].Count != 1 { t.Errorf("ByRegion = %+v, want [{#belgium 1}]", stats.ByRegion) } diff --git a/cmd/server/routes_test.go b/cmd/server/routes_test.go index b33b92224..970041050 100644 --- a/cmd/server/routes_test.go +++ b/cmd/server/routes_test.go @@ -4358,6 +4358,14 @@ func TestHandleScopeStats(t *testing.T) { if resp.Summary.UnknownScope != 1 { t.Errorf("unknownScope = %d, want 1", resp.Summary.UnknownScope) } + // #2364: the summary adds up again. + if resp.Summary.Total != 6 { + t.Errorf("total = %d, want 6", resp.Summary.Total) + } + if resp.Summary.UnscopedTransport != 1 || resp.Summary.UnscopedFlood != 1 || resp.Summary.UnscopedDirect != 1 { + t.Errorf("unscoped split = %d/%d/%d, want 1/1/1", + resp.Summary.UnscopedTransport, resp.Summary.UnscopedFlood, resp.Summary.UnscopedDirect) + } if len(resp.ByRegion) != 1 || resp.ByRegion[0].Name != "#belgium" || resp.ByRegion[0].Count != 2 { t.Errorf("byRegion = %v, want [{#belgium 2}]", resp.ByRegion) } diff --git a/cmd/server/types.go b/cmd/server/types.go index 7ea74919d..d824d5580 100644 --- a/cmd/server/types.go +++ b/cmd/server/types.go @@ -98,11 +98,25 @@ type StatsResponse struct { // ─── Scope Stats ─────────────────────────────────────────────────────────────── +// ScopeStatsSummary invariants (#2364): +// +// transportTotal = scoped + unscopedTransport (routes 0, 3) +// unscoped = unscopedTransport + unscopedFlood + unscopedDirect +// total = scoped + unscoped (routes 0-3) +// +// Unscoped has folded in the non-transport routes since #1838, so it is +// compared against Total, not TransportTotal. The three Unscoped* fields +// split it by route so a client can, for example, look at unscoped floods +// only (DIRECT traffic is not subject to flood-region filtering). type ScopeStatsSummary struct { - TransportTotal int `json:"transportTotal"` - Scoped int `json:"scoped"` - Unscoped int `json:"unscoped"` - UnknownScope int `json:"unknownScope"` + Total int `json:"total"` + TransportTotal int `json:"transportTotal"` + Scoped int `json:"scoped"` + Unscoped int `json:"unscoped"` + UnscopedTransport int `json:"unscopedTransport"` + UnscopedFlood int `json:"unscopedFlood"` + UnscopedDirect int `json:"unscopedDirect"` + UnknownScope int `json:"unknownScope"` } type ScopeRegionCount struct { diff --git a/docs/api-spec.md b/docs/api-spec.md index 3d09e13c6..c57900220 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -2144,10 +2144,14 @@ Scope-based packet statistics over a time window. Requires ingestor `scope_name_ { "window": string, // echoed window ("1h", "24h", or "7d") "summary": { - "transportTotal": number, // scoped + unscoped transport-route packets - "scoped": number, // Code1 ≠ 0000 (named + unknown regions) - "unscoped": number, // transport-route with Code1 = 0000 - "unknownScope": number // scoped but no configured region matched (subset of scoped) + "total": number, // all observed transmissions, routes 0-3 (= scoped + unscoped) + "transportTotal": number, // transport routes 0 and 3 (= scoped + unscopedTransport) + "scoped": number, // Code1 ≠ 0000 (named + unknown regions) + "unscoped": number, // all unscoped traffic (= unscopedTransport + unscopedFlood + unscopedDirect) + "unscopedTransport": number, // transport route (0, 3) with Code1 = 0000 + "unscopedFlood": number, // FLOOD (route 1): no transport code, unscoped by protocol + "unscopedDirect": number, // DIRECT (route 2): no transport code, never floods + "unknownScope": number // scoped but no configured region matched (subset of scoped) }, "byRegion": [ { "name": string, "count": number } // region name and packet count @@ -2167,9 +2171,16 @@ Scope-based packet statistics over a time window. Requires ingestor `scope_name_ ``` **Notes:** -- `transportTotal` = `scoped` + `unscoped` (only route_type 0 or 3 packets) +- Route types per MeshCore `docs/packet_format.md`: 0 = TRANSPORT_FLOOD, 1 = FLOOD, 2 = DIRECT, + 3 = TRANSPORT_DIRECT. Only routes 0 and 3 carry a transport code (Code1). +- `total` = `scoped` + `unscoped` (all route types) +- `transportTotal` = `scoped` + `unscopedTransport` (only route_type 0 or 3 packets) - `scoped` = packets with Code1 ≠ 0000 -- `unscoped` = transport-route packets with Code1 = 0000 +- `unscoped` = `unscopedTransport` + `unscopedFlood` + `unscopedDirect`. Since #1838 it includes the + non-transport routes 1 and 2, so it can exceed `transportTotal`; compute shares against `total` (#2364). +- `unscopedFlood` is the figure to watch for region rollout: DIRECT traffic (`unscopedDirect`) is not + subject to flood-region filtering, which repeaters apply to flood routes only. +- `timeSeries` counts transport routes (0, 3) only; its `unscoped` corresponds to `unscopedTransport`. - `unknownScope` = scoped packets that did not match any configured region name - Time-series bucket size depends on window: - `1h` window → 5-minute buckets diff --git a/public/analytics.js b/public/analytics.js index d62343158..60c43bc83 100644 --- a/public/analytics.js +++ b/public/analytics.js @@ -3237,6 +3237,7 @@ function destroy() { _stopRolesRefresh(); _stopScopesRefresh(); _stopDistanceRet window._analyticsRetransmissionBucketFor = retransmissionBucketFor; window._analyticsRenderRetransmissionChart = renderRetransmissionChart; window._analyticsScopeAdvertsByRoleHtml = scopeAdvertsByRoleHtml; + window._analyticsScopeSummaryCardsHtml = scopeSummaryCardsHtml; window._analyticsPacketsPerHourCard = packetsPerHourCard; } @@ -5034,6 +5035,35 @@ function destroy() { _stopRolesRefresh(); _stopScopesRefresh(); _stopDistanceRet ''; } + // #2364: summary cards for /api/scope-stats. Shares are of `total` + // (scoped + unscoped, all routes); servers older than #2364 send no + // `total`, so it falls back to scoped + unscoped. The route split of + // unscoped is only shown when the server reports it. + function scopeSummaryCardsHtml(s) { + function pct(n, total) { + if (!total) return '—'; + return (n / total * 100).toFixed(1) + '%'; + } + var transportTotal = s.transportTotal || 0; + var overall = s.total != null ? s.total : (s.scoped || 0) + (s.unscoped || 0); + var unscopedNote = pct(s.unscoped, overall) + ' of all traffic'; + if (s.unscopedFlood != null && s.unscopedDirect != null) { + unscopedNote += ' · ' + (s.unscopedTransport || 0).toLocaleString() + ' transport, ' + + s.unscopedFlood.toLocaleString() + ' flood, ' + s.unscopedDirect.toLocaleString() + ' direct'; + } + return [ + { label: 'Transport Total', value: transportTotal.toLocaleString(), note: 'routes 0,3 (carry scope)' }, + { label: 'Scoped', value: s.scoped.toLocaleString(), note: pct(s.scoped, overall) + ' of all traffic' }, + { label: 'Unscoped', value: s.unscoped.toLocaleString(), note: unscopedNote }, + { label: 'Unknown Scope', value: s.unknownScope.toLocaleString(), note: pct(s.unknownScope, s.scoped) + ' of scoped' }, + ].map(function(c) { + return '
' + c.value + '
' + + '
' + c.label + '
' + + (c.note ? '
' + c.note + '
' : '') + + '
'; + }).join(''); + } + async function renderScopesTab(el) { var winKey = 'scopes_window'; var selectedWindow = (typeof sessionStorage !== 'undefined' && sessionStorage.getItem(winKey)) || '24h'; @@ -5100,24 +5130,10 @@ function destroy() { _stopRolesRefresh(); _stopScopesRefresh(); _stopDistanceRet // #1838: denominator = transport-carrying transmissions (route_type 0,3). // Unscoped now includes non-transport routes (1,2) which are inherently // unscoped by MeshCore protocol, so unscoped can exceed transportTotal. - var total = s.transportTotal || 0; - var overall = (s.scoped || 0) + (s.unscoped || 0); - - // Summary cards + // #2364: the server reports `total` (= scoped + unscoped) and splits + // unscoped by route; fall back for older servers. var cardsEl = document.getElementById('scopes-cards'); - if (cardsEl) { - cardsEl.innerHTML = [ - { label: 'Transport Total', value: total.toLocaleString(), note: 'routes 0,3 (carry scope)' }, - { label: 'Scoped', value: s.scoped.toLocaleString(), note: pct(s.scoped, overall) + ' of all traffic' }, - { label: 'Unscoped', value: s.unscoped.toLocaleString(), note: pct(s.unscoped, overall) + ' of all traffic' }, - { label: 'Unknown Scope', value: s.unknownScope.toLocaleString(), note: pct(s.unknownScope, s.scoped) + ' of scoped' }, - ].map(function(c) { - return '
' + c.value + '
' + - '
' + c.label + '
' + - (c.note ? '
' + c.note + '
' : '') + - '
'; - }).join(''); - } + if (cardsEl) cardsEl.innerHTML = scopeSummaryCardsHtml(s); // Per-region table var tbodyEl = document.getElementById('scopes-tbody'); diff --git a/test-all.sh b/test-all.sh index 641fca736..f00510265 100755 --- a/test-all.sh +++ b/test-all.sh @@ -156,6 +156,7 @@ node tests/unit/test-packet-detail-hash-size.js node tests/unit/test-issue-1890-og-url.js node tests/unit/test-issue-1956-release-routing.js node tests/unit/test-issue-1979-scope-adverts-by-role.js +node tests/unit/test-issue-2364-scope-summary-cards.js node tests/unit/test-issue-1997-distance-building.js node tests/unit/test-issue-2042-recent-adverts-label.js node tests/unit/test-issue-2001-map-scope-state.js diff --git a/tests/unit/test-issue-2364-scope-summary-cards.js b/tests/unit/test-issue-2364-scope-summary-cards.js new file mode 100644 index 000000000..1a3cde482 --- /dev/null +++ b/tests/unit/test-issue-2364-scope-summary-cards.js @@ -0,0 +1,126 @@ +/* Unit tests for the Scopes tab summary cards (#2364). + * + * /api/scope-stats reports `total` (= scoped + unscoped, all routes) and + * splits unscoped into transport, flood and direct. The Scoped and Unscoped + * cards show their share of `total`, and the Unscoped card lists the route + * split. Servers older than #2364 send neither, so the cards fall back to + * scoped + unscoped as the denominator and leave the split out. + * + * Loads the real public/analytics.js in a vm sandbox and exercises the helper + * it exposes, the same way test-issue-1979-scope-adverts-by-role.js does. + */ +'use strict'; +const vm = require('vm'); +const fs = require('fs'); +const assert = require('assert'); + +let passed = 0, failed = 0; +function test(name, fn) { + try { fn(); passed++; console.log(` ✅ ${name}`); } + catch (e) { failed++; console.log(` ❌ ${name}: ${e.message}`); } +} + +function makeSandbox() { + const ctx = { + window: {}, + document: { + documentElement: {}, addEventListener() {}, removeEventListener() {}, + getElementById() { return null; }, querySelector() { return null; }, querySelectorAll() { return []; }, + createElement() { return { style: {}, addEventListener() {} }; }, + }, + console, Date, Math, Array, Object, String, Number, JSON, RegExp, Error, + parseInt, parseFloat, isFinite, isNaN, Map, Set, Promise, + setTimeout: () => {}, clearTimeout: () => {}, setInterval: () => {}, clearInterval: () => {}, + localStorage: { getItem: () => null, setItem() {}, removeItem() {} }, + getComputedStyle: () => ({ getPropertyValue: () => '' }), + registerPage: () => {}, api: async () => ({}), fetch: async () => ({ json: async () => ({}) }), + addEventListener() {}, removeEventListener() {}, + }; + ctx.window = ctx; + vm.createContext(ctx); + vm.runInContext(fs.readFileSync('public/analytics.js', 'utf8'), ctx); + return ctx; +} + +// The note under the card with the given label. +function note(html, label) { + const re = new RegExp('
' + label + '
]*>([^<]*)
'); + const m = html.match(re); + return m ? m[1] : null; +} + +console.log('\n=== analytics.js: scope summary cards (#2364) ==='); +{ + const ctx = makeSandbox(); + const render = ctx.window._analyticsScopeSummaryCardsHtml; + + test('helper is exposed for testing', () => { + assert.strictEqual(typeof render, 'function', '_analyticsScopeSummaryCardsHtml must be exposed'); + }); + if (typeof render !== 'function') { + console.log(`\n${passed} passed, ${failed} failed`); + process.exit(1); + } + + // unscoped (150) exceeds transportTotal (100): the case #2364 is about. + const current = { + total: 200, transportTotal: 100, scoped: 50, unscoped: 150, + unscopedTransport: 50, unscopedFlood: 70, unscopedDirect: 30, unknownScope: 10, + }; + const html = render(current); + + test('renders the four cards', () => { + const labels = (html.match(/
[^<]*<\/div>/g) || []).map((s) => s.replace(/<[^>]+>/g, '')); + assert.deepStrictEqual(labels, ['Transport Total', 'Scoped', 'Unscoped', 'Unknown Scope']); + }); + + test('shares use total, not transportTotal', () => { + assert.strictEqual(note(html, 'Scoped'), '25.0% of all traffic'); + assert.ok(note(html, 'Unscoped').startsWith('75.0% of all traffic'), note(html, 'Unscoped')); + }); + + test('unscoped note lists the route split', () => { + assert.strictEqual(note(html, 'Unscoped'), '75.0% of all traffic · 50 transport, 70 flood, 30 direct'); + }); + + test('unknown scope is a share of scoped', () => { + assert.strictEqual(note(html, 'Unknown Scope'), '20.0% of scoped'); + }); + + test('transport total card shows transportTotal', () => { + assert.ok(/
100<\/div>
Transport Total<\/div>/.test(html)); + }); + + // A server from before #2364: no total, no route split. + const old = { transportTotal: 100, scoped: 50, unscoped: 150, unknownScope: 10 }; + const oldHtml = render(old); + + test('older server: falls back to scoped + unscoped', () => { + assert.strictEqual(note(oldHtml, 'Scoped'), '25.0% of all traffic'); + }); + + test('older server: no route split', () => { + assert.strictEqual(note(oldHtml, 'Unscoped'), '75.0% of all traffic'); + }); + + test('partial split (no unscopedDirect) is left out', () => { + const partial = Object.assign({}, old, { unscopedFlood: 70 }); + assert.strictEqual(note(render(partial), 'Unscoped'), '75.0% of all traffic'); + }); + + test('empty window shows a dash instead of NaN', () => { + const empty = render({ total: 0, transportTotal: 0, scoped: 0, unscoped: 0, unknownScope: 0 }); + assert.strictEqual(note(empty, 'Scoped'), '— of all traffic'); + assert.strictEqual(note(empty, 'Unknown Scope'), '— of scoped'); + assert.ok(!/NaN/.test(empty)); + }); + + test('total of 0 is honoured, not replaced by the fallback', () => { + // total present but 0 must not fall back to scoped + unscoped. + const z = render({ total: 0, transportTotal: 0, scoped: 5, unscoped: 5, unknownScope: 0 }); + assert.strictEqual(note(z, 'Scoped'), '— of all traffic'); + }); +} + +console.log(`\n${passed} passed, ${failed} failed`); +if (failed) process.exit(1); From d80ce90976d5ca7e31c270badda58187100a8af8 Mon Sep 17 00:00:00 2001 From: n30nex Date: Sun, 15 Nov 2026 06:24:43 -0500 Subject: [PATCH 05/30] fix(store): release evicted packet references from secondary indexes (#2327) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses #2324 for upstream SQLite; PostgreSQL qualification remains separate. Eviction releases actual node memberships, pointer tails and cache roots without SQL reconstruction. Borrowed distance snapshots and bounded hash-migration ownership remain protected. Review correction `0b1049b5` skips each distance-array copy when no record is evicted from that array. When affected, it clones once and filters the suffix beginning at the first match, preserving borrowed snapshots and the surviving prefix. Work remains O(distance records); no new locks, reader bookkeeping, settings or general speedup claim. Tests-only `16509577` reaches [three real assertion failures in CI](https://github.com/Kpa-clawbot/CoreScope/actions/runs/43200112374/job/131121073845). GREEN leaves those tests unchanged. Cases cover neither/hops-only/paths-only impact, repeated removals, live prefixes, tail removal and snapshot contents. Parent independently reproduced RED and reran GREEN. Full native server/ingestor suites pass. Targeted checks: 167 passed; race: 165 passed, with two existing timing skips that pass in the ordinary run. Current master `a0b4e6cf` is normally merged; original RED/GREEN history is preserved. Historical November 10 measurements: synthetic retained heap 98.00→27.14 MiB with equal live data; path-update cost at 30k hops/10k paths 0.591→3.675ms and 2,824→5,368,584 B/op. The older ~30ms extra eviction lock time at 240k transmissions is unremeasured. Large-window qualification/optimization: #2393. Invalidated migration progress: #2394; no SQL migration redesign here. Browser verified: populated matching revision (500 transmissions/502 observations), 3/3 interactions. [Final CI](https://github.com/Kpa-clawbot/CoreScope/actions/runs/43202356164) and three independent reviews pass. No settings changes. --------- Co-authored-by: n30nex <6686206+n30nex@users.noreply.github.com> --- cmd/server/distance_ownership_bench_test.go | 54 +++ cmd/server/eviction_churn_bench_test.go | 154 ++++++++ cmd/server/eviction_ownership_test.go | 374 +++++++++++++++++++ cmd/server/eviction_resolved_pubkeys_test.go | 54 --- cmd/server/hash_migrate.go | 103 +++-- cmd/server/hash_migrate_eviction_test.go | 210 +++++++++++ cmd/server/resolved_index.go | 69 ---- cmd/server/resolved_pubkeys_bench_test.go | 10 - cmd/server/store.go | 266 ++++--------- 9 files changed, 939 insertions(+), 355 deletions(-) create mode 100644 cmd/server/distance_ownership_bench_test.go create mode 100644 cmd/server/eviction_churn_bench_test.go create mode 100644 cmd/server/eviction_ownership_test.go delete mode 100644 cmd/server/eviction_resolved_pubkeys_test.go create mode 100644 cmd/server/hash_migrate_eviction_test.go diff --git a/cmd/server/distance_ownership_bench_test.go b/cmd/server/distance_ownership_bench_test.go new file mode 100644 index 000000000..bd309f72c --- /dev/null +++ b/cmd/server/distance_ownership_bench_test.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "testing" + "time" +) + +// Exercise the real reader and batch path-update entry points with 10,000 +// transmissions, 30,000 hop records and 10,000 path records. Setup is excluded. +func BenchmarkDistanceOwnership(b *testing.B) { + for _, operation := range []string{"analytics-read", "path-update"} { + b.Run(operation, func(b *testing.B) { + s := NewPacketStore(nil, nil) + nodes := []nodeInfo{ + {PublicKey: "aa", Name: "A", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1}, + {PublicKey: "bb", Name: "B", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1.01}, + {PublicKey: "cc", Name: "C", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1.02}, + {PublicKey: "dd", Name: "D", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1.03}, + } + s.nodeCache, s.nodePM, s.nodeCacheTime = nodes, buildPrefixMap(nodes), time.Now() + const count = 10000 + s.distHops = make([]distHopRecord, 0, count*3) + s.distPaths = make([]distPathRecord, 0, count) + stamp := time.Now().UTC().Format(time.RFC3339) + for i := 0; i < count; i++ { + tx := &StoreTx{ID: i + 1, Hash: fmt.Sprintf("synthetic-%d", i), FirstSeen: stamp, + PathJSON: `["aa","bb","cc","dd"]`, parsedPath: []string{"aa", "bb", "cc", "dd"}, pathParsed: true} + s.packets = append(s.packets, tx) + details := make([]distHopDetail, 3) + for j := range details { + a, z := nodes[j], nodes[j+1] + s.distHops = append(s.distHops, distHopRecord{FromName: a.Name, FromPk: a.PublicKey, + ToName: z.Name, ToPk: z.PublicKey, Dist: 1, Type: "R↔R", Hash: tx.Hash, Timestamp: stamp, tx: tx}) + details[j] = distHopDetail{FromName: a.Name, FromPk: a.PublicKey, ToName: z.Name, ToPk: z.PublicKey, Dist: 1} + } + s.distPaths = append(s.distPaths, distPathRecord{Hash: tx.Hash, TotalDist: 3, HopCount: 3, + Timestamp: stamp, Hops: details, tx: tx}) + } + changed := s.packets[:1] + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if operation == "analytics-read" { + s.computeAnalyticsDistance("", "") + } else { + s.mu.Lock() + s.updateDistanceIndexForTxs(changed) + s.mu.Unlock() + } + } + }) + } +} diff --git a/cmd/server/eviction_churn_bench_test.go b/cmd/server/eviction_churn_bench_test.go new file mode 100644 index 000000000..f1514fba2 --- /dev/null +++ b/cmd/server/eviction_churn_bench_test.go @@ -0,0 +1,154 @@ +package main + +import ( + "fmt" + "runtime" + "strings" + "testing" + "time" +) + +// Synthetic live-ingest bookkeeping uses the real membership, observation and byte +// accounting helpers. No fixture keeps packet pointers outside the store. +func appendEvictionChurnBatch(s *PacketStore, firstID, count, fanout int, now time.Time) { + const hops = 8 + relays := make([]string, 512) + for i := range relays { + relays[i] = fmt.Sprintf("%02x%062x", i%256, i) + } + origin := strings.Repeat("f", 64) // distinct from every resolved relay + stamp := now.UTC().Format(time.RFC3339) + hopsSeen := make(map[string]bool) + for id := firstID; id < firstID+count; id++ { + pt := 5 + tx := &StoreTx{ + ID: id, Hash: fmt.Sprintf("%064x", id), RawHex: strings.Repeat("ab", 64), + FirstSeen: stamp, LatestSeen: stamp, PayloadType: &pt, + DecodedJSON: fmt.Sprintf(`{"pubKey":%q,"text":"synthetic churn packet %d"}`, origin, id), + } + s.packets = append(s.packets, tx) + s.byHash[tx.Hash], s.byTxID[id] = tx, tx + s.byPayloadType[pt] = append(s.byPayloadType[pt], tx) + s.indexByNode(tx) + for j := 0; j < fanout; j++ { + pks, rawHops := make([]string, hops), make([]string, hops) + for k := range pks { + pks[k] = relays[(id*17+j*19+k*13)%len(relays)] + rawHops[k] = fmt.Sprintf("%q", pks[k][:2]) + } + path := "[" + strings.Join(rawHops, ",") + "]" + observer := fmt.Sprintf("observer-%03d", (id+j)%225) + snr := float64(j%12) - 4 + obs := &StoreObs{ID: id*fanout + j, TransmissionID: id, + ObserverID: observer, ObserverName: "Synthetic " + observer, + PathJSON: path, Timestamp: stamp, Direction: "rx", SNR: &snr} + tx.addObservation(obs) + s.byObsID[obs.ID] = obs + s.byObserver[observer] = append(s.byObserver[observer], obs) + s.totalObs++ + s.trackedBytes += estimateStoreObsBytes(obs) + s.indexResolvedPathHops(tx, pks, hopsSeen, nil, obs) + } + pickBestObservation(tx) + s.trackedBytes += rechargeTx(tx) + addTxToPathHopIndex(s.byPathHop, tx) + } +} + +func newEvictionChurnStore(now time.Time) *PacketStore { + s := makeTestStore(0, now, 0) + s.retentionHours = 1 + s.byPathHop = make(map[string][]*StoreTx) + s.useResolvedPathIndex = true + s.initResolvedPathIndex() + return s +} + +func evictedNodePacketCount(s *PacketStore) int { + seen := make(map[int]bool) + for _, list := range s.byNode { + for _, tx := range list { + if s.byTxID[tx.ID] != tx { + seen[tx.ID] = true + } + } + } + return len(seen) +} + +func TestEvictionChurnOwnsOnlyLivePackets(t *testing.T) { + now := time.Now().UTC() + s := newEvictionChurnStore(now) + const batch = 8 + for cycle := 0; cycle < 5; cycle++ { + for _, tx := range s.packets { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + appendEvictionChurnBatch(s, cycle*batch+1, batch, 4, now) + s.RunEviction() + if len(s.packets) != batch || s.totalObs != batch*4 { + t.Fatalf("cycle %d retained %d packets/%d observations", cycle, len(s.packets), s.totalObs) + } + if got := evictedNodePacketCount(s); got != 0 { + t.Fatalf("cycle %d retains %d evicted packets through the node index", cycle, got) + } + var charged int64 + for _, tx := range s.packets { + charged += tx.accountedBytes + for _, obs := range tx.Observations { + charged += estimateStoreObsBytes(obs) + } + } + if s.trackedBytes != charged { + t.Fatalf("cycle %d charged %d bytes, want live-packet sum %d", cycle, s.trackedBytes, charged) + } + } +} + +// One operation is eight complete 1,000-transmission generations, each with +// sixteen observations and distinct resolved eight-hop paths. It leaves the +// final generation live. GC samples run outside the timer, and only the store +// retains packet pointers. This measures in-memory churn, not SQL or HTTP. +func BenchmarkEvictionOwnershipChurn(b *testing.B) { + const batch, fanout, cycles = 1000, 16, 8 + b.ReportAllocs() + var retained, tracked, orphans, livePackets, liveObservations float64 + for i := 0; i < b.N; i++ { + b.StopTimer() + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + now := time.Now().UTC() + s := newEvictionChurnStore(now) + b.StartTimer() + for cycle := 0; cycle < cycles; cycle++ { + for _, tx := range s.packets { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + appendEvictionChurnBatch(s, cycle*batch+1, batch, fanout, now) + s.RunEviction() + } + b.StopTimer() + runtime.GC() + runtime.ReadMemStats(&after) + packetCount, observationCount := len(s.packets), 0 + for _, tx := range s.packets { + observationCount += len(tx.Observations) + } + if packetCount != batch || observationCount != batch*fanout { + b.Fatalf("retained %d packets/%d observations, want %d/%d", packetCount, observationCount, batch, batch*fanout) + } + retained += float64(int64(after.HeapAlloc) - int64(before.HeapAlloc)) + tracked += float64(s.trackedBytes) + orphans += float64(evictedNodePacketCount(s)) + livePackets += float64(packetCount) + liveObservations += float64(observationCount) + runtime.KeepAlive(s) + b.StartTimer() + } + b.ReportMetric(retained/float64(b.N), "retained-B/op") + b.ReportMetric(tracked/float64(b.N), "tracked-B/op") + b.ReportMetric(orphans/float64(b.N), "orphan-tx/op") + b.ReportMetric(livePackets/float64(b.N), "live-tx/op") + b.ReportMetric(liveObservations/float64(b.N), "live-obs/op") +} diff --git a/cmd/server/eviction_ownership_test.go b/cmd/server/eviction_ownership_test.go new file mode 100644 index 000000000..8b508e42e --- /dev/null +++ b/cmd/server/eviction_ownership_test.go @@ -0,0 +1,374 @@ +package main + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "slices" + "strings" + "sync/atomic" + "testing" + "time" +) + +func assertEvictedNodeMemberships(t *testing.T, s *PacketStore, removed map[int]bool) { + t.Helper() + for key, list := range s.byNode { + for _, tx := range list[:cap(list)] { + if tx != nil && removed[tx.ID] { + t.Errorf("node index %q retains evicted transmission %d", key, tx.ID) + } + } + for id := range s.nodeHashes[key] { + if s.byTxID[id] == nil { + t.Errorf("node hash index %q retains evicted transmission %d", key, id) + } + } + } + for key, hashes := range s.nodeHashes { + if len(hashes) == 0 || len(s.byNode[key]) == 0 { + t.Errorf("node hash index %q has no live memberships", key) + } + } +} + +func TestEvictionOwnsResolvedNodeMemberships(t *testing.T) { + for _, mode := range []string{"missing", "different", "expanded", "matching", "index-disabled"} { + t.Run(mode, func(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.useResolvedPathIndex = mode != "index-disabled" + s.initResolvedPathIndex() + s.byPathHop = make(map[string][]*StoreTx) + relay, other := strings.Repeat("a", 64), strings.Repeat("b", 64) + for _, tx := range s.packets { + s.indexResolvedPathHops(tx, []string{relay}, make(map[string]bool), nil, nil) + } + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + batch := map[int][]string{} + switch mode { + case "different": + batch[1] = []string{other} + case "expanded", "matching": + batch[1] = []string{relay} + } + removed := map[int]bool{1: true} + if mode == "expanded" { + // The SQL batch was selected while only ID 1 was eligible. + // Expiration can advance before the actual eviction lock is acquired. + s.packets[1].FirstSeen = now.Add(-90 * time.Minute).Format(time.RFC3339) + removed[2] = true + } + // Even a duplicate index entry must not keep an evicted packet alive. + s.byNode[relay] = append(s.byNode[relay], s.packets[0]) + s.mu.Lock() + got := s.EvictStaleWithRP(batch) + s.mu.Unlock() + if got != len(removed) { + t.Fatalf("evicted %d packets, want %d", got, len(removed)) + } + assertEvictedNodeMemberships(t, s, removed) + if len(s.byNode[relay]) != 4-len(removed) { + t.Errorf("resolved relay has %d memberships, want %d live packets", len(s.byNode[relay]), 4-len(removed)) + } + for _, tx := range s.packets { + if !s.nodeHasTx(relay, tx) { + t.Errorf("lost surviving hash %q", tx.Hash) + } + s.addToByNode(tx, relay) + } + if len(s.byNode[relay]) != 4-len(removed) { + t.Error("surviving memberships lost their deduplication markers") + } + }) + } +} + +func TestEvictionAfterLocalPathResolution(t *testing.T) { + for _, producer := range []string{"cold-missing", "ingest-different", "late-missing"} { + t.Run(producer, func(t *testing.T) { + relay := strings.Repeat("a", 64) + other := strings.Repeat("b", 64) + dsn := createTestDBWithResolvedPath(t, 2, nil) + w, err := sql.Open("sqlite3", dsn+"?_journal_mode=WAL") + if err != nil { + t.Fatal(err) + } + defer w.Close() + if _, err = w.Exec("INSERT INTO nodes(public_key,name,role) VALUES(?,'Synthetic relay','repeater')", relay); err != nil { + t.Fatal(err) + } + var persisted any + if producer == "ingest-different" { + persisted = fmt.Sprintf(`[%q]`, other) + } + path := `["aa"]` + if producer == "late-missing" { + path = `[]` + } + if _, err = w.Exec("UPDATE observations SET path_json=?, resolved_path=?", path, persisted); err != nil { + t.Fatal(err) + } + db, err := OpenDB(dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + s := NewPacketStore(db, &PacketStoreConfig{RetentionHours: 24}) + now := time.Now().UTC() + if producer == "cold-missing" { + if err := s.loadChunk(now.Add(-72*time.Hour), now); err != nil { + t.Fatal(err) + } + } else { + s.IngestNewFromDB(0, 10) + if producer == "late-missing" { + for id := 1; id <= 2; id++ { + if _, err = w.Exec(`INSERT INTO observations(id,transmission_id,observer_id,path_json,timestamp) + VALUES(?,?,'late-observer','["aa"]',?)`, id+2, id, now.Add(-48*time.Hour).Format(time.RFC3339)); err != nil { + t.Fatal(err) + } + } + s.IngestNewObservations(2, 10) + } + } + if len(s.byNode[relay]) != 2 { + t.Fatalf("producer did not locally resolve both packets: %d memberships", len(s.byNode[relay])) + } + if got := s.RunEviction(); got != 2 { + t.Fatalf("evicted %d packets, want 2", got) + } + assertEvictedNodeMemberships(t, s, map[int]bool{1: true, 2: true}) + var count int + if err := w.QueryRow("SELECT COUNT(*) FROM transmissions").Scan(&count); err != nil || count != 2 { + t.Fatalf("cache eviction changed SQL history: count=%d, err=%v", count, err) + } + }) + } +} + +func TestEvictionDoesNotWaitForSQL(t *testing.T) { + db := setupTestDB(t) + defer db.Close() + db.conn.SetMaxOpenConns(1) + conn, err := db.conn.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + s := makeTestStore(2, time.Now().Add(-2*time.Hour), 0) + s.retentionHours, s.db = 1, db + done := make(chan int, 1) + go func() { done <- s.RunEviction() }() + select { + case got := <-done: + if got != 2 { + t.Fatalf("evicted %d packets, want 2", got) + } + case <-time.After(time.Second): + // Release the only SQL connection and drain eviction before failing. + conn.Close() + <-done + t.Fatal("cache eviction waited for a SQL connection") + } +} + +func TestEvictionReleasesPrivateSliceTails(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + for _, tx := range s.packets[:2] { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + // Cold load can append newest-first buckets. Removing their oldest tail + // must clear it, not just shorten the visible slice. + slices.Reverse(s.byPayloadType[4]) + for _, list := range s.byObserver { + slices.Reverse(list) + } + if got := s.RunEviction(); got != 2 { + t.Fatalf("evicted %d packets, want 2", got) + } + check := func(owner string, list []*StoreTx) { + t.Helper() + for _, tx := range list[:cap(list)] { + if tx != nil && tx.ID <= 2 { + t.Errorf("%s backing array retains evicted transmission %d", owner, tx.ID) + } + } + } + check("payload", s.byPayloadType[4]) + for key, list := range s.byObserver { + for _, obs := range list[:cap(list)] { + if obs != nil && obs.TransmissionID <= 2 { + t.Errorf("observer %q backing array retains evicted observation %d", key, obs.ID) + } + } + } + // An empty primary slice must not keep its former contents alive. + for _, tx := range s.packets { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + if got := s.RunEviction(); got != 2 { + t.Fatalf("final eviction removed %d packets, want 2", got) + } + for _, tx := range s.packets[:cap(s.packets)] { + if tx != nil { + t.Error("empty packet store retains a transmission in its backing array") + break + } + } +} + +func TestPathHopRemovalReleasesTail(t *testing.T) { + old, live := &StoreTx{ID: 1}, &StoreTx{ID: 2} + idx := map[string][]*StoreTx{"aa": {live, old}} + removeTxFromSlice(idx, "aa", old) + if !reflect.DeepEqual(idx["aa"], []*StoreTx{live}) { + t.Fatal("path-hop removal lost its survivor") + } + for _, tx := range idx["aa"][:cap(idx["aa"])] { + if tx == old { + t.Fatal("removed path-hop transmission remains in the backing array") + } + } +} + +func TestEvictionCopiesOnlyAffectedDistanceArrays(t *testing.T) { + for _, tc := range []struct { + name string + hopsAffected bool + pathsAffected bool + }{ + {name: "neither"}, + {name: "hops-only", hopsAffected: true}, + {name: "paths-only", pathsAffected: true}, + } { + t.Run(tc.name, func(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + wantHops := slices.Clone(s.distHops[1:]) + wantPaths := slices.Clone(s.distPaths[1:]) + if tc.hopsAffected { + // Removals may follow a live prefix and occur more than once. + s.distHops = []distHopRecord{s.distHops[1], s.distHops[0], s.distHops[2], s.distHops[0], s.distHops[3]} + } else { + s.distHops = slices.Clone(wantHops) + } + if tc.pathsAffected { + s.distPaths = []distPathRecord{s.distPaths[1], s.distPaths[2], s.distPaths[3], s.distPaths[0]} + } else { + s.distPaths = slices.Clone(wantPaths) + } + + s.mu.RLock() + hops, paths := s.snapshotDistanceIndexLocked() + s.mu.RUnlock() + beforeHops, beforePaths := slices.Clone(hops), slices.Clone(paths) + if got := s.RunEviction(); got != 1 { + t.Fatalf("evicted %d packets, want 1", got) + } + if !reflect.DeepEqual(s.distHops, wantHops) || !reflect.DeepEqual(s.distPaths, wantPaths) { + t.Fatal("eviction did not preserve the surviving distance records") + } + if !reflect.DeepEqual(hops, beforeHops) || !reflect.DeepEqual(paths, beforePaths) { + t.Error("eviction modified a distance snapshot borrowed by an unlocked reader") + } + // Equal contents alone would miss an unnecessary full-array allocation. + if !tc.hopsAffected && &s.distHops[0] != &hops[0] { + t.Error("eviction copied the unaffected distance hop array") + } + if !tc.pathsAffected && &s.distPaths[0] != &paths[0] { + t.Error("eviction copied the unaffected distance path array") + } + }) + } +} + +func TestEvictionPreservesDistanceSnapshots(t *testing.T) { + for _, operation := range []string{"eviction", "path-update"} { + t.Run(operation, func(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + // Use the same snapshot boundary as computeAnalyticsDistance. The + // arrays it owns must survive later eviction and live path updates. + s.mu.RLock() + hops, paths := s.snapshotDistanceIndexLocked() + s.mu.RUnlock() + wantHops, wantPaths := slices.Clone(hops), slices.Clone(paths) + if operation == "eviction" { + s.RunEviction() + } else { + s.nodeCacheTime = now + s.nodePM = &prefixMap{m: map[string][]nodeInfo{}} + s.mu.Lock() + s.updateDistanceIndexForTxs(s.packets[:1]) + s.mu.Unlock() + } + if !reflect.DeepEqual(hops, wantHops) || !reflect.DeepEqual(paths, wantPaths) { + t.Error("writer modified a distance snapshot borrowed by an unlocked reader") + } + for _, hop := range s.distHops[:cap(s.distHops)] { + if hop.tx != nil && hop.tx.ID == 1 { + t.Error("distance hop backing array retains a removed record") + } + } + for _, path := range s.distPaths[:cap(s.distPaths)] { + if path.tx != nil && path.tx.ID == 1 { + t.Error("distance path backing array retains a removed record") + } + } + }) + } +} + +func TestEvictionReleasesGroupedCache(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + if got := s.QueryGroupedPackets(PacketQuery{}).Total; got != 4 { + t.Fatalf("warm grouped total=%d, want 4", got) + } + // A returned snapshot is allowed to finish after eviction. Invalidating the + // cache must release its root without clearing an active reader's array. + reader := s.groupedCacheTxs + s.groupedCacheExp = now.Add(-time.Second) + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + s.RunEviction() + if s.groupedCacheTxs != nil { + t.Error("eviction retained the expired grouped packet cache") + } + if len(reader) != 4 || reader[0].tx == nil { + t.Error("cache invalidation corrupted a borrowed grouped snapshot") + } + if got := s.QueryGroupedPackets(PacketQuery{}).Total; got != 3 { + t.Errorf("grouped total after eviction=%d, want 3", got) + } +} + +func TestGroupedCacheRejectsPreEvictionSnapshot(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.QueryGroupedPackets(PacketQuery{}) + oldSnapshot := s.groupedCacheTxs + oldGeneration := atomic.LoadInt64(&s.evicted) + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + s.RunEviction() + // A query that captured its pointers before eviction can finish sorting + // afterwards. Exercise its real publication step in that exact order. + s.cacheGroupedPackets(oldSnapshot, "retired", oldGeneration) + if s.groupedCacheTxs != nil { + t.Fatal("late grouped-cache publication retained a pre-eviction snapshot") + } + s.cacheGroupedPackets([]groupedEntry{{tx: s.packets[0]}, {tx: s.packets[1]}, {tx: s.packets[2]}}, "live", atomic.LoadInt64(&s.evicted)) + if len(s.groupedCacheTxs) != 3 || s.groupedCacheKey != "live" { + t.Fatal("current grouped snapshot was not published") + } +} diff --git a/cmd/server/eviction_resolved_pubkeys_test.go b/cmd/server/eviction_resolved_pubkeys_test.go deleted file mode 100644 index 078ca351f..000000000 --- a/cmd/server/eviction_resolved_pubkeys_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "fmt" - "runtime" - "testing" -) - -func evictionResolvedStore(t testing.TB, n int) (*PacketStore, []int) { - t.Helper() - db := setupTestDB(t) - t.Cleanup(func() { db.Close() }) - pk := func(i int) string { return fmt.Sprintf("%064x", i) } - ids := make([]int, 0, n) - for i := 1; i <= n; i++ { - if _, err := db.conn.Exec(`INSERT INTO transmissions (id, raw_hex, hash, first_seen) VALUES (?, '00', ?, '2026-01-01T00:00:00Z')`, i, fmt.Sprintf("h%015d", i)); err != nil { - t.Fatal(err) - } - for o := 0; o < 3; o++ { - rp := `["` + pk(i%9) + `",null,"` + pk(o+20) + `","` + pk(i%9) + `"]` - if _, err := db.conn.Exec(`INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp, resolved_path) VALUES (?, 1, '["aa","bb","cc","dd"]', 0, ?)`, i, rp); err != nil { - t.Fatal(err) - } - } - ids = append(ids, i) - } - return &PacketStore{db: db}, ids -} - -// Eviction looks up the resolved pubkeys of every packet it drops, once a -// minute in steady state. It decoded each resolved_path into a pointer per -// hop and built a de-dup map per packet: about 130MB of allocations per -// five minutes on a busy week. -func TestResolvedPubkeysForEvictionBatch(t *testing.T) { - s, ids := evictionResolvedStore(t, 300) - got := s.resolvedPubkeysForEvictionBatch(ids) - want := []string{fmt.Sprintf("%064x", 1), fmt.Sprintf("%064x", 20), fmt.Sprintf("%064x", 21), fmt.Sprintf("%064x", 22)} - if fmt.Sprint(got[1]) != fmt.Sprint(want) { - t.Fatalf("tx 1: %v, want %v (first-seen order, de-duplicated)", got[1], want) - } - if len(got) != 300 { - t.Fatalf("%d packets resolved, want 300", len(got)) - } - var a, b runtime.MemStats - runtime.GC() - runtime.ReadMemStats(&a) - _ = s.resolvedPubkeysForEvictionBatch(ids) - runtime.ReadMemStats(&b) - per := float64(b.Mallocs-a.Mallocs) / float64(len(ids)) - t.Logf("%.1f allocations per evicted packet (3 observations, 4 hops each)", per) - if per > 20 { - t.Fatalf("%.1f allocations per evicted packet, limit 20", per) - } -} diff --git a/cmd/server/hash_migrate.go b/cmd/server/hash_migrate.go index a85d58bc1..cb4cd4a32 100644 --- a/cmd/server/hash_migrate.go +++ b/cmd/server/hash_migrate.go @@ -2,6 +2,7 @@ package main import ( "log" + "sync/atomic" "time" ) @@ -10,6 +11,24 @@ import ( // both the DB and the in-memory byHash index. The migration is idempotent: // once all hashes match the current formula it completes instantly. func migrateContentHashesAsync(store *PacketStore, batchSize int, yieldDuration time.Duration) { + // Eviction compacts the slice, and background loads may prepend packets. + // Keep one boundary pointer, not a snapshot that pins all data. + store.mu.RLock() + total := len(store.packets) + evicted := atomic.LoadInt64(&store.evicted) + var last *StoreTx + if total > 0 { + last = store.packets[total-1] + } + store.mu.RUnlock() + // Caller holds store.mu. Appends leave the original range intact; merges + // before its end move the boundary and invalidate offset-based traversal. + sameRange := func() bool { + return len(store.packets) >= total && atomic.LoadInt64(&store.evicted) == evicted && + (total == 0 || store.packets[total-1] == last) + } + inputChanged := false + // #1856: every DB failure below continues to the next batch, so the loop // always reaches the deferred completion. Setting the flag unconditionally // therefore reported success after migrating nothing, which is exactly what @@ -28,21 +47,17 @@ func migrateContentHashesAsync(store *PacketStore, batchSize int, yieldDuration "and the migration belongs in the ingestor (#1856).", failedBatches) return } + store.mu.RLock() + defer store.mu.RUnlock() + if inputChanged || !sameRange() { + log.Printf("[hash-migrate] INCOMPLETE: packet set changed during migration") + return + } store.hashMigrationComplete.Store(true) }() - // Snapshot the packet slice length under lock (packets only grow). - store.mu.RLock() - total := len(store.packets) - store.mu.RUnlock() - migrated := 0 for offset := 0; offset < total; offset += batchSize { - end := offset + batchSize - if end > total { - end = total - } - // Collect stale hashes in this batch under RLock. type hashUpdate struct { tx *StoreTx @@ -51,17 +66,27 @@ func migrateContentHashesAsync(store *PacketStore, batchSize int, yieldDuration } var updates []hashUpdate - store.mu.RLock() - for _, tx := range store.packets[offset:end] { - if tx.RawHex == "" { - continue + func() { + store.mu.RLock() + defer store.mu.RUnlock() + if !sameRange() { + inputChanged = true + return } - newHash := ComputeContentHash(tx.RawHex) - if newHash != tx.Hash { - updates = append(updates, hashUpdate{tx: tx, oldHash: tx.Hash, newHash: newHash}) + end := min(offset+batchSize, min(total, len(store.packets))) + for _, tx := range store.packets[offset:end] { + if tx.RawHex == "" { + continue + } + newHash := ComputeContentHash(tx.RawHex) + if newHash != tx.Hash { + updates = append(updates, hashUpdate{tx: tx, oldHash: tx.Hash, newHash: newHash}) + } } + }() + if inputChanged { + return } - store.mu.RUnlock() if len(updates) == 0 { continue @@ -104,27 +129,33 @@ func migrateContentHashesAsync(store *PacketStore, batchSize int, yieldDuration } // Update in-memory index under write lock. - store.mu.Lock() - for _, u := range updates { - delete(store.byHash, u.oldHash) - if u.newHash == "" { - // Merged duplicate — remove from packets slice and indexes. - delete(store.byTxID, u.tx.ID) - // Move observations to survivor if present. - if surv := store.byHash[ComputeContentHash(u.tx.RawHex)]; surv != nil { - for _, obs := range u.tx.Observations { - surv.Observations = append(surv.Observations, obs) - surv.ObservationCount++ + func() { + store.mu.Lock() + defer store.mu.Unlock() + for _, u := range updates { + // SQL can wait while eviction removes or replaces this object. + if store.byTxID[u.tx.ID] != u.tx { + inputChanged = true + continue + } + delete(store.byHash, u.oldHash) + if u.newHash == "" { + // Merged duplicate — remove from packets slice and indexes. + delete(store.byTxID, u.tx.ID) + // Move observations to survivor if present. + if surv := store.byHash[ComputeContentHash(u.tx.RawHex)]; surv != nil { + for _, obs := range u.tx.Observations { + surv.Observations = append(surv.Observations, obs) + surv.ObservationCount++ + } } + } else { + u.tx.Hash = u.newHash + store.byHash[u.newHash] = u.tx } - } else { - u.tx.Hash = u.newHash - store.byHash[u.newHash] = u.tx + migrated++ } - } - store.mu.Unlock() - - migrated += len(updates) + }() // Yield to let HTTP handlers run. time.Sleep(yieldDuration) diff --git a/cmd/server/hash_migrate_eviction_test.go b/cmd/server/hash_migrate_eviction_test.go new file mode 100644 index 000000000..293d9918e --- /dev/null +++ b/cmd/server/hash_migrate_eviction_test.go @@ -0,0 +1,210 @@ +package main + +import ( + "context" + "database/sql" + "runtime" + "testing" + "time" +) + +func TestMigrateContentHashesAsyncSurvivesEviction(t *testing.T) { + for _, tc := range []struct { + name string + batchSize int + replace bool + }{ + {name: "later_batch", batchSize: 1}, + {name: "pending_batch", batchSize: 4}, + {name: "replacement_with_same_ID", batchSize: 4, replace: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dbPath := createTestDBWithResolvedPath(t, 4, nil) + // Reuse the valid raw packet from the existing migration regression. + // The fixture's legacy hashes intentionally need migration. + writer, err := sql.Open("sqlite3", dbPath) + if err != nil { + t.Fatal(err) + } + _, err = writer.Exec("UPDATE transmissions SET raw_hex = ?", "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976") + writer.Close() + if err != nil { + t.Fatal(err) + } + db, err := OpenDB(dbPath) + if err != nil { + t.Fatal(err) + } + defer db.Close() + store := NewPacketStore(db, &PacketStoreConfig{RetentionHours: 24}) + now := time.Now().UTC() + if err := store.loadChunk(now.Add(-72*time.Hour), now); err != nil { + t.Fatal(err) + } + if len(store.packets) != 4 { + t.Fatalf("fixture loaded %d packets, want 4", len(store.packets)) + } + original := append([]*StoreTx(nil), store.packets...) + + finish := pauseHashMigrationAtSQL(t, store, tc.batchSize) + defer finish() + if got := store.RunEviction(); got != 4 { + t.Fatalf("evicted %d packets, want 4", got) + } + + var replacements []*StoreTx + if tc.replace { + // A reloaded transmission has the same ID but a new pointer. + // Refill to the original length so a length-only check is insufficient. + store.mu.Lock() + for _, tx := range original { + replacement := &StoreTx{ID: tx.ID, Hash: tx.Hash, RawHex: tx.RawHex, FirstSeen: now.Format(time.RFC3339)} + replacements = append(replacements, replacement) + store.packets = append(store.packets, replacement) + store.byTxID[replacement.ID] = replacement + store.byHash[replacement.Hash] = replacement + } + store.mu.Unlock() + } + finish() + + if !store.mu.TryLock() { + // The migration has returned and no other readers exist. Release + // its leaked RLock so the assertion failure does not strand the test. + store.mu.RUnlock() + t.Error("migration returned while retaining the store read lock") + } else { + store.mu.Unlock() + } + if !store.mu.TryRLock() { + t.Fatal("store read lock is unusable after migration") + } + defer store.mu.RUnlock() + if got := len(store.packets); got != len(replacements) { + t.Errorf("primary packet count = %d, want %d", got, len(replacements)) + } + if got := len(store.byTxID); got != len(replacements) { + t.Errorf("byTxID count = %d, want %d", got, len(replacements)) + } + if got := len(store.byHash); got != len(replacements) { + t.Errorf("byHash count = %d, want %d; pending migration republished evicted packets", got, len(replacements)) + } + for _, tx := range original { + for hash, cached := range store.byHash { + if cached == tx { + t.Errorf("byHash[%q] retained evicted transmission %d", hash, tx.ID) + } + } + } + for _, tx := range replacements { + if store.byTxID[tx.ID] != tx || store.byHash[tx.Hash] != tx { + t.Errorf("migration changed ownership of replacement transmission %d", tx.ID) + } + } + if store.hashMigrationComplete.Load() { + t.Error("migration must not claim completion after its input changed") + } + var unchanged int + if err := db.conn.QueryRow("SELECT COUNT(*) FROM transmissions WHERE hash LIKE 'hash1558_%'").Scan(&unchanged); err != nil { + t.Fatal(err) + } + if unchanged != 4 { + t.Errorf("read-only fixture retained %d original hashes, want 4", unchanged) + } + }) + } +} + +func TestMigrateContentHashesAsyncKeepsInitialRange(t *testing.T) { + for _, prepend := range []bool{false, true} { + name := "append" + if prepend { + name = "prepend" + } + t.Run(name, func(t *testing.T) { + db := setupTestDBv2(t) + defer db.Close() + store := NewPacketStore(db, nil) + rawHex := "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976" + for _, suffix := range []string{"76", "77", "78"} { + raw := rawHex[:len(rawHex)-2] + suffix + if _, err := db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type) + VALUES (?, ?, datetime('now'), 0, 2)`, raw, "old-"+raw); err != nil { + t.Fatal(err) + } + } + if err := store.Load(); err != nil { + t.Fatal(err) + } + if len(store.packets) != 3 { + t.Fatalf("fixture loaded %d packets, want 3", len(store.packets)) + } + original := append([]*StoreTx(nil), store.packets...) + finish := pauseHashMigrationAtSQL(t, store, 2) + defer finish() + + added := &StoreTx{ID: 4, RawHex: rawHex, Hash: "added-hash"} + store.mu.Lock() + if prepend { + store.packets = mergeChunkIntoPackets([]*StoreTx{added}, store.packets) + } else { + store.packets = append(store.packets, added) + } + store.byTxID[added.ID] = added + store.byHash[added.Hash] = added + store.mu.Unlock() + finish() + + for i, tx := range original { + wantHash := ComputeContentHash(tx.RawHex) + if prepend && i >= 2 { + wantHash = "old-" + tx.RawHex + } + if store.byHash[wantHash] != tx || tx.Hash != wantHash { + t.Errorf("original transmission %d hash = %q, want %q and retained ownership", tx.ID, tx.Hash, wantHash) + } + } + if added.Hash != "added-hash" || store.byHash["added-hash"] != added { + t.Error("bounded migration changed a transmission outside its initial range") + } + if got := store.hashMigrationComplete.Load(); got != !prepend { + t.Errorf("hashMigrationComplete = %v, want %v", got, !prepend) + } + }) + } +} + +// Occupy the SQL pool until the real migration captures its first batch and +// releases the store's read lock. The caller must release and drain it. +func pauseHashMigrationAtSQL(t *testing.T, store *PacketStore, batchSize int) func() { + t.Helper() + store.db.conn.SetMaxOpenConns(1) + conn, err := store.db.conn.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + before := store.db.conn.Stats().WaitCount + done := make(chan struct{}) + go func() { + defer close(done) + migrateContentHashesAsync(store, batchSize, 0) + }() + finish := func() { + t.Helper() + conn.Close() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("migration did not return after releasing the SQL connection") + } + } + deadline := time.Now().Add(5 * time.Second) + for store.db.conn.Stats().WaitCount == before && time.Now().Before(deadline) { + runtime.Gosched() + } + if store.db.conn.Stats().WaitCount == before { + finish() + t.Fatal("migration did not reach its first SQL batch") + } + return finish +} diff --git a/cmd/server/resolved_index.go b/cmd/server/resolved_index.go index 11ab7498a..f1bd2159a 100644 --- a/cmd/server/resolved_index.go +++ b/cmd/server/resolved_index.go @@ -536,75 +536,6 @@ func (s *PacketStore) lruDelete(obsID int) { // Don't scan lruOrder — eviction handles stale entries naturally. } -// resolvedPubkeysForEvictionBatch fetches resolved pubkeys for multiple txIDs -// from SQL in a single batched query. Returns a map from txID to unique pubkeys. -// MUST be called WITHOUT holding s.mu — this is the whole point of the batch approach. -// Chunks queries to stay under SQLite's 500-parameter limit. -func (s *PacketStore) resolvedPubkeysForEvictionBatch(txIDs []int) map[int][]string { - result := make(map[int][]string, len(txIDs)) - if len(txIDs) == 0 || s.db == nil || s.db.conn == nil { - return result - } - - const chunkSize = 499 // SQLite SQLITE_MAX_VARIABLE_NUMBER default is 999; stay well under - for start := 0; start < len(txIDs); start += chunkSize { - end := start + chunkSize - if end > len(txIDs) { - end = len(txIDs) - } - chunk := txIDs[start:end] - - // Build query with placeholders - placeholders := make([]byte, 0, len(chunk)*2) - args := make([]interface{}, len(chunk)) - for i, id := range chunk { - if i > 0 { - placeholders = append(placeholders, ',') - } - placeholders = append(placeholders, '?') - args[i] = id - } - - query := "SELECT transmission_id, resolved_path FROM observations WHERE transmission_id IN (" + - string(placeholders) + ") AND resolved_path IS NOT NULL" - - rows, err := s.db.conn.Query(query, args...) - if err != nil { - continue - } - - var txID int - var rpJSON sql.NullString - for rows.Next() { - if err := rows.Scan(&txID, &rpJSON); err != nil { - continue - } - if !rpJSON.Valid || rpJSON.String == "" { - continue - } - // De-duplicate as we go: a packet has a handful of keys, so a - // scan of its list is cheaper than a map per packet. - pks := result[txID] - for _, pk := range resolvedPubkeysFromJSON(rpJSON.String) { - dup := false - for _, have := range pks { - if have == pk { - dup = true - break - } - } - if !dup { - pks = append(pks, pk) - } - } - result[txID] = pks - } - rows.Close() - } - - return result -} - // initResolvedPathIndex initializes the resolved path index data structures. func (s *PacketStore) initResolvedPathIndex() { s.resolvedPubkeyIndex = make(map[uint64][]int, 4096) diff --git a/cmd/server/resolved_pubkeys_bench_test.go b/cmd/server/resolved_pubkeys_bench_test.go index 70adcb8bd..ad55f73db 100644 --- a/cmd/server/resolved_pubkeys_bench_test.go +++ b/cmd/server/resolved_pubkeys_bench_test.go @@ -25,13 +25,3 @@ func BenchmarkResolvedPubkeysFromJSON(b *testing.B) { _ = resolvedPubkeysFromJSON(paths[i%len(paths)]) } } - -// An eviction batch of 1,000 packets with 3 observations each. -func BenchmarkResolvedPubkeysForEvictionBatch(b *testing.B) { - s, ids := evictionResolvedStore(b, 1000) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = s.resolvedPubkeysForEvictionBatch(ids) - } -} diff --git a/cmd/server/store.go b/cmd/server/store.go index 12942f9d8..94f01a0b0 100644 --- a/cmd/server/store.go +++ b/cmd/server/store.go @@ -2236,6 +2236,7 @@ func (s *PacketStore) QueryGroupedPackets(q PacketQuery) *PacketResult { for i, tx := range results { txs[i] = groupedEntry{tx: tx, latest: tx.LatestSeen} } + evictionGeneration := atomic.LoadInt64(&s.evicted) s.mu.RUnlock() total := len(txs) @@ -2246,16 +2247,24 @@ func (s *PacketStore) QueryGroupedPackets(q PacketQuery) *PacketResult { }) // Cache the sorted entries (not maps) — lightweight and reusable for any page. - s.groupedCacheMu.Lock() - s.groupedCacheTxs = txs - s.groupedCacheTotal = total - s.groupedCacheKey = cacheKey - s.groupedCacheExp = time.Now().Add(3 * time.Second) - s.groupedCacheMu.Unlock() + s.cacheGroupedPackets(txs, cacheKey, evictionGeneration) return s.groupedPage(txs, total, q.Offset, q.Limit) } +func (s *PacketStore) cacheGroupedPackets(txs []groupedEntry, cacheKey string, evictionGeneration int64) { + s.groupedCacheMu.Lock() + defer s.groupedCacheMu.Unlock() + // Eviction may have invalidated the cache while this snapshot was sorted. + // Do not publish its retired packet pointers after that invalidation. + if evictionGeneration == atomic.LoadInt64(&s.evicted) { + s.groupedCacheTxs = txs + s.groupedCacheTotal = len(txs) + s.groupedCacheKey = cacheKey + s.groupedCacheExp = time.Now().Add(3 * time.Second) + } +} + // pagePacketResult returns a window of a PacketResult without re-allocating the slice. func pagePacketResult(r *PacketResult, offset, limit int) *PacketResult { total := r.Total @@ -2655,6 +2664,10 @@ func (s *PacketStore) invalidateCachesFor(inv cacheInvalidation) { s.channelsCacheMu.Lock() s.channelsCacheRes = nil s.channelsCacheMu.Unlock() + s.groupedCacheMu.Lock() + s.groupedCacheTxs = nil + s.groupedCacheTotal = 0 + s.groupedCacheMu.Unlock() s.lastInvalidated = time.Now() s.pendingInv = nil return @@ -4891,7 +4904,7 @@ func removeTxFromSlice(idx map[string][]*StoreTx, key string, tx *StoreTx) { list := idx[key] for i, t := range list { if t.ID == tx.ID { - idx[key] = append(list[:i], list[i+1:]...) + idx[key] = slices.Delete(list, i, i+1) break } } @@ -4910,22 +4923,10 @@ func (s *PacketStore) updateDistanceIndexForTxs(txs []*StoreTx) { for _, tx := range txs { removeSet[tx] = true } - n := 0 - for _, r := range s.distHops { - if !removeSet[r.tx] { - s.distHops[n] = r - n++ - } - } - s.distHops = s.distHops[:n] - n = 0 - for _, r := range s.distPaths { - if !removeSet[r.tx] { - s.distPaths[n] = r - n++ - } - } - s.distPaths = s.distPaths[:n] + // Distance readers borrow these arrays after releasing s.mu. Copy here, + // once per changed-path batch, so their O(1) snapshots remain immutable. + s.distHops = slices.DeleteFunc(slices.Clone(s.distHops), func(r distHopRecord) bool { return removeSet[r.tx] }) + s.distPaths = slices.DeleteFunc(slices.Clone(s.distPaths), func(r distPathRecord) bool { return removeSet[r.tx] }) // Build lookup maps once. allNodes, pm := s.getCachedNodesAndPM() @@ -5188,70 +5189,17 @@ func (s *PacketStore) trackedMemoryMB() float64 { return float64(s.trackedBytes) / 1048576.0 } -// EvictStale removes packets older than the retention window and/or exceeding -// the memory cap. Must be called with s.mu held (Lock). Returns the number of -// packets evicted. -// evictionCandidateTxIDs determines which tx IDs would be evicted and returns them. -// Must be called under s.mu.Lock (or RLock). Does NOT modify any state. -func (s *PacketStore) evictionCandidateTxIDs() []int { - if s.retentionHours <= 0 && s.maxMemoryMB <= 0 { - return nil - } - cutoffIdx := 0 - if s.retentionHours > 0 { - cutoff := time.Now().UTC().Add(-time.Duration(s.retentionHours * float64(time.Hour))).Format(time.RFC3339) - for cutoffIdx < len(s.packets) && s.packets[cutoffIdx].FirstSeen < cutoff { - cutoffIdx++ - } - } - if s.maxMemoryMB > 0 { - highWatermark := int64(s.maxMemoryMB) * 1048576 - lowWatermark := int64(float64(highWatermark) * 0.85) - if s.trackedBytes > highWatermark && len(s.packets) > 0 { - var bytesToEvict int64 - memCutoff := cutoffIdx - for memCutoff < len(s.packets) && (s.trackedBytes-bytesToEvict) > lowWatermark { - tx := s.packets[memCutoff] - bytesToEvict += tx.accountedBytes - for _, obs := range tx.Observations { - bytesToEvict += estimateStoreObsBytes(obs) - } - memCutoff++ - } - maxEvict := len(s.packets) / 4 - if maxEvict < 1 { - maxEvict = 1 - } - if memCutoff > maxEvict { - memCutoff = maxEvict - } - if memCutoff > cutoffIdx { - cutoffIdx = memCutoff - } - } - } - if cutoffIdx == 0 || cutoffIdx > len(s.packets) { - return nil - } - ids := make([]int, cutoffIdx) - for i := 0; i < cutoffIdx; i++ { - ids[i] = s.packets[i].ID - } - return ids -} - -// EvictStaleWithRP runs eviction using pre-fetched resolved pubkeys. -// rpBatch may be nil (in which case resolved pubkey cleanup for byNode/nodeHashes is skipped). +// EvictStaleWithRP retains the old entry point for callers with a prefetched +// batch. Cleanup uses actual in-memory membership; SQL paths may differ from it. // Must be called under s.mu.Lock. -func (s *PacketStore) EvictStaleWithRP(rpBatch map[int][]string) int { - return s.evictStaleInternal(rpBatch) +func (s *PacketStore) EvictStaleWithRP(_ map[int][]string) int { + return s.evictStaleInternal() } -// EvictStale runs eviction, fetching resolved pubkeys inline (SQL under lock). -// Prefer RunEviction() which batches the SQL outside the lock. +// EvictStale removes expired packets and their in-memory memberships without SQL. // Must be called under s.mu.Lock. func (s *PacketStore) EvictStale() int { - return s.evictStaleInternal(nil) + return s.evictStaleInternal() } // mergeChunkIntoPackets merges a background chunk into the packet slice while @@ -5295,7 +5243,7 @@ func mergeChunkIntoPackets(chunk, existing []*StoreTx) []*StoreTx { return out } -func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { +func (s *PacketStore) evictStaleInternal() int { if s.retentionHours <= 0 && s.maxMemoryMB <= 0 { return 0 } @@ -5359,7 +5307,6 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { // Track which observer IDs and payload types need filtering affectedObservers := make(map[string]struct{}) affectedPayloadTypes := make(map[int]struct{}) - affectedNodes := make(map[string]struct{}) // First pass: remove from primary indexes (byHash, byTxID, byObsID), // collect IDs for batch secondary index cleanup, and handle non-index work @@ -5390,45 +5337,6 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { affectedPayloadTypes[*tx.PayloadType] = struct{}{} } - // Remove from nodeHashes and collect affected node keys. - // Must mirror indexByNode: process decoded JSON fields AND resolved_path pubkeys. - evictedFromNode := make(map[string]bool) - if tx.DecodedJSON != "" { - if decoded := tx.ParsedDecoded(); decoded != nil { - for _, field := range []string{"pubKey", "destPubKey", "srcPubKey"} { - if v, ok := decoded[field].(string); ok && v != "" { - if hashes, ok := s.nodeHashes[v]; ok { - delete(hashes, tx.ID) - if len(hashes) == 0 { - delete(s.nodeHashes, v) - } - } - affectedNodes[v] = struct{}{} - evictedFromNode[v] = true - } - } - } - } - // Clean up resolved_path pubkeys from byNode/nodeHashes. - // Uses pre-fetched batch data when available (no SQL under lock). - var rpPubkeys []string - if rpBatch != nil { - rpPubkeys = rpBatch[tx.ID] - } - for _, pk := range rpPubkeys { - if pk == "" || evictedFromNode[pk] { - continue - } - if hashes, ok := s.nodeHashes[pk]; ok { - delete(hashes, tx.ID) - if len(hashes) == 0 { - delete(s.nodeHashes, pk) - } - } - affectedNodes[pk] = struct{}{} - evictedFromNode[pk] = true - } - // Remove from resolved pubkey index s.removeFromResolvedPubkeyIndex(tx.ID) } @@ -5454,12 +5362,10 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { // Batch-remove from byObserver: single pass per affected observer slice for obsID := range affectedObservers { obsList := s.byObserver[obsID] - filtered := obsList[:0] - for _, o := range obsList { - if _, evicted := evictedObsIDs[o.ID]; !evicted { - filtered = append(filtered, o) - } - } + filtered := slices.DeleteFunc(obsList, func(o *StoreObs) bool { + _, evicted := evictedObsIDs[o.ID] + return evicted + }) if len(filtered) == 0 { delete(s.byObserver, obsID) } else { @@ -5470,12 +5376,10 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { // Batch-remove from byPayloadType: single pass per affected type slice for pt := range affectedPayloadTypes { ptList := s.byPayloadType[pt] - filtered := ptList[:0] - for _, t := range ptList { - if _, evicted := evictedTxIDs[t.ID]; !evicted { - filtered = append(filtered, t) - } - } + filtered := slices.DeleteFunc(ptList, func(t *StoreTx) bool { + _, evicted := evictedTxIDs[t.ID] + return evicted + }) if len(filtered) == 0 { delete(s.byPayloadType, pt) } else { @@ -5483,17 +5387,21 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { } } - // Batch-remove from byNode: single pass per affected node slice - for nodeKey := range affectedNodes { - nodeList := s.byNode[nodeKey] - filtered := nodeList[:0] - for _, t := range nodeList { - if _, evicted := evictedTxIDs[t.ID]; !evicted { - filtered = append(filtered, t) + // Sweep actual memberships once per batch, as for byPathHop. Server-side + // resolution can differ from persisted paths or have no persisted path at + // all. Reconstructing keys from SQL leaves uncharged packet graphs alive. + // Readers either hold s.mu or copy these buckets before releasing it. + for nodeKey, nodeList := range s.byNode { + filtered := slices.DeleteFunc(nodeList, func(t *StoreTx) bool { + _, evicted := evictedTxIDs[t.ID] + if evicted { + delete(s.nodeHashes[nodeKey], t.ID) } - } + return evicted + }) if len(filtered) == 0 { delete(s.byNode, nodeKey) + delete(s.nodeHashes, nodeKey) delete(s.certainHeard, nodeKey) delete(s.certainRelayed, nodeKey) } else { @@ -5506,24 +5414,24 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { for _, tx := range evicting { evictedTxSet[tx] = true } - newDistHops := s.distHops[:0] - for i := range s.distHops { - if !evictedTxSet[s.distHops[i].tx] { - newDistHops = append(newDistHops, s.distHops[i]) - } + // Only copy arrays with evicted records. Preserve arrays borrowed by + // unlocked readers; deleting from the copied suffix clears retired pointers. + isEvictedHop := func(r distHopRecord) bool { return evictedTxSet[r.tx] } + if first := slices.IndexFunc(s.distHops, isEvictedHop); first >= 0 { + hops := slices.Clone(s.distHops) + filtered := slices.DeleteFunc(hops[first:], isEvictedHop) + s.distHops = hops[:first+len(filtered)] } - s.distHops = newDistHops - - newDistPaths := s.distPaths[:0] - for i := range s.distPaths { - if !evictedTxSet[s.distPaths[i].tx] { - newDistPaths = append(newDistPaths, s.distPaths[i]) - } + isEvictedPath := func(r distPathRecord) bool { return evictedTxSet[r.tx] } + if first := slices.IndexFunc(s.distPaths, isEvictedPath); first >= 0 { + paths := slices.Clone(s.distPaths) + filtered := slices.DeleteFunc(paths[first:], isEvictedPath) + s.distPaths = paths[:first+len(filtered)] } - s.distPaths = newDistPaths // Trim packets slice n := copy(s.packets, s.packets[cutoffIdx:]) + clear(s.packets[n:]) s.packets = s.packets[:n] s.totalObs -= evictedObs @@ -5553,25 +5461,10 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { // RunEviction acquires the write lock and runs eviction. Safe to call from // a goroutine. Returns evicted count. -// Uses a two-phase approach: determines eviction candidates under lock, -// releases lock for batch SQL fetch of resolved pubkeys, then re-acquires -// lock for the actual eviction pass. func (s *PacketStore) RunEviction() int { - // Phase 1: determine candidates under lock - s.mu.Lock() - txIDs := s.evictionCandidateTxIDs() - s.mu.Unlock() - - // Phase 2: batch-fetch resolved pubkeys from SQL (no lock held) - var rpBatch map[int][]string - if len(txIDs) > 0 { - rpBatch = s.resolvedPubkeysForEvictionBatch(txIDs) - } - - // Phase 3: actual eviction under write lock, using pre-fetched data s.mu.Lock() defer s.mu.Unlock() - return s.EvictStaleWithRP(rpBatch) + return s.EvictStale() } // StartEvictionTicker starts a background goroutine that runs eviction every @@ -8411,6 +8304,13 @@ func (s *PacketStore) GetAnalyticsDistance(region, area string) map[string]inter return result } +// snapshotDistanceIndexLocked borrows immutable record arrays for an unlocked +// reader. Path updates and eviction filter copies; appends stay beyond the +// captured length. Hop-detail slices are immutable too. Caller holds s.mu. +func (s *PacketStore) snapshotDistanceIndexLocked() ([]distHopRecord, []distPathRecord) { + return s.distHops, s.distPaths +} + func (s *PacketStore) computeAnalyticsDistance(region, area string) map[string]interface{} { // #1239: hold s.mu.RLock() only long enough to (a) snapshot the // distHops/distPaths slice headers and (b) build the region match @@ -8419,14 +8319,9 @@ func (s *PacketStore) computeAnalyticsDistance(region, area string) map[string]i // and category stats run on locally-captured slices OUTSIDE the // lock so concurrent ingest writers are not blocked by readers. // - // Safety: snapshot slice headers are O(1). distHops/distPaths are - // append-only via re-slice in buildDistanceIndex / updateDistanceIndexForTxs - // under s.mu.Lock; if the backing array is reallocated after we - // release the RLock, our snapshot still points at the prior backing - // array (kept alive by GC) and observes the consistent length we - // captured. The distHopRecord / distPathRecord values themselves - // are value types (not pointers to live records) so we cannot read - // torn writes from them post-release. + // Safety: snapshot slice headers are O(1). Ingest appends beyond the + // captured length; path updates and eviction filter copies, never mutate + // these borrowed backing arrays. Hop-detail slices are immutable too. var regionObs map[string]bool if region != "" { // resolveRegionObservers uses its own mutex (regionObsMu) @@ -8439,8 +8334,7 @@ func (s *PacketStore) computeAnalyticsDistance(region, area string) map[string]i } s.mu.RLock() - hopsSnap := s.distHops - pathsSnap := s.distPaths + hopsSnap, pathsSnap := s.snapshotDistanceIndexLocked() // Build region match set INSIDE the lock — touches tx.Observations // (slice header mutated by ingest). For non-region calls (the common @@ -8497,8 +8391,8 @@ func (s *PacketStore) computeAnalyticsDistance(region, area string) map[string]i } else if areaNodes != nil { // No region filter but area filter: build matchSet from area nodes matchSet = make(map[*StoreTx]bool) - for i := range s.distHops { - tx := s.distHops[i].tx + for i := range hopsSnap { + tx := hopsSnap[i].tx if matchSet[tx] { continue } @@ -8511,8 +8405,8 @@ func (s *PacketStore) computeAnalyticsDistance(region, area string) map[string]i matchSet[tx] = true } } - for i := range s.distPaths { - tx := s.distPaths[i].tx + for i := range pathsSnap { + tx := pathsSnap[i].tx if matchSet[tx] { continue } From e7fd48a0543ea4427a53b3f613ba32ce2a871b4e Mon Sep 17 00:00:00 2001 From: Paul Picazo Date: Mon, 16 Nov 2026 05:56:09 -0800 Subject: [PATCH 06/30] feat(frontend): serve the UI from a web container or a static host, three deployment modes (#2383) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this does The frontend half of serving the UI apart from the server. The server half was #2362. It gives CoreScope three deployment modes. The server container is the same image in all three, and it still serves everything, the classic UI included. | Mode | The UI is served by | API | Server CORS setting | Logins | |---|---|---|---|---| | All-in-one container (today) | the server container | same origin | none | yes | | Split containers (new) | a web container that forwards the API | same origin | none | yes | | Static host or CDN (new) | Cloudflare Pages, a CDN or any web server | another origin | `CORS_ALLOWED_ORIGINS` | no, links to the classic UI | ### Commit 1: the UI as static files, for any host - **One place for API URLs:** `public/deployment.js` says where the API is, and `public/api-base.js` (`CSApi`) builds every API and WebSocket URL. A lint rule keeps raw `/api` fetches out of the other files. The embedded UI keeps `apiBase: ''`, so it behaves as before, except that its WebSocket now uses `/ws` instead of `/`. - **Build:** `make web` (`scripts/static/build.sh`) writes `dist/web`, which is `public/` byte for byte except for the cache buster in `index.html` and `deployment.js`. - It is `dist/web` rather than `dist/` because the Go binaries are built into `dist/` and `make clean` removes that folder. - `API_BASE=same-origin` is for a host that forwards `/api` and `/ws` itself, as the web container does. - **Anonymous build (`AUTH=false`):** for another origin. It has no account features: login, account, admin and other writes link to the same page on the classic UI. It sends no cookies, and its three JSON POSTs go as `text/plain`, so there is no preflight. - **Error notices:** a blocked API answer or an HTML answer each show a notice. - **Channel badge:** `beta`, `next` and `dev` builds show a badge that opens a pre-filled issue, plus an "Open in classic" link. - **Runbook:** `deploy/static/README.md` covers Cloudflare Pages, previews, server CORS and rollback. ### Commit 2: the web container and the three modes - **`Dockerfile.web`:** Caddy on `alpine:3.24`, like the main image. It packages the UI with `build.sh` when the image is built, serves it, and forwards `/api/*` and `/ws` to `BACKEND` (default `corescope:3000`). `SITE_ADDRESS` set to a domain name turns on automatic HTTPS. - **Cache rules:** `docker/web/Caddyfile` sends the same no-cache rules as `deploy/static/_headers`, and compresses responses with zstd or gzip. - **`docker-compose.split.yml`:** the stock server image (its own Caddy off) plus the web container: `CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge docker compose -f docker-compose.split.yml up -d --build`. - `CORESCOPE_IMAGE` is required and must match the checkout's version, so a release server is never paired with a newer UI by default. - The server's built-in broker, which accepts anonymous clients, is published on `127.0.0.1` unless `MQTT_BIND` says otherwise. - **Docs:** `docs/deployment.md` has a new "Deployment modes" section, and `DEPLOY.md` points to it. ### Keeping new code on `CSApi` - **Lint rule:** `.eslintrc.json` now rejects every direct network call in `public/*.js`. That covers `fetch`, `XMLHttpRequest`, `EventSource`, `sendBeacon` and `WebSocket` without `CSApi.wsUrl`, plus `/api` paths in `href`, `src` and `action` (assigned, set with `setAttribute` or written into markup), `window.open`, `location.assign`, `location.replace` and `location =`. `api-base.js` is the one file exempt. - **HTML pages:** `eslint public/*.js` never sees the inline scripts and markup of `public/*.html`, so `test-lint-network-calls.js` applies the same rule to them, at their page lines. `area-map.html`'s two fetches carry an `eslint-disable` with the reason: its Server field can name another server. - **Why it changed:** the earlier rule only caught a literal `/api…` passed straight to `fetch`. - **Check:** CI already fails on lint errors, and `tests/e2e/test-lint-network-calls.js` pins exactly what the rule reports: 25 bad statements reported, 15 good ones not, `api-base.js` exempt. - **AGENTS.md:** a new "API calls" section covers: - which helper to use for each need; - the lint rule; - how anonymous builds gate login-only features; - loading `api-base.js` in vm and jsdom tests (the region quick-picks suite missed that, and failed shard 1 on the first CI run). ### Review follow-ups - **Account tokens:** the channel badge's pre-filled issue drops the query on `#/account/…` routes, so mail-link tokens never reach a GitHub URL. "Open in classic" keeps the full route, since the classic UI needs the token. - **HTML answers:** on a packaged UI (static host, web container), `api()` rejects an HTML answer before status and retry handling. An HTML 404 or 503 (a wrong `API_BASE`, a proxy error page) shows "Server returned an unexpected response" after one request. It used to give a generic error, or six "warming up" retries for a 503. JSON errors and the server's JSON 503 warm-up behave as before. The embedded UI keeps its old handling (`CSApi.embedded`). - **Logins:** `docs/deployment.md`, `Dockerfile.web` and `docker-compose.split.yml` say `userManagement.publicBaseUrl` must be the web container's public origin. ### Audit fixes - **No broken logins build:** `build.sh` refuses `AUTH=true` with a cross-origin `API_BASE`. The server allows no credentialed CORS, so every API request of such a build was blocked; in Chromium all 12 were, and the pages stayed empty. - **No accidental deletes:** `build.sh` refuses an `OUT` that is neither empty nor a previous build. It used to wipe whatever folder or file `OUT` named. - **Lint:** the rule now also reports `/api/` paths in `href`, `src` and `action` attributes in single-quoted strings and template literals. `tests/e2e/test-lint-network-calls.js` pins exactly what it reports. - **Compose:** `CORESCOPE_IMAGE` has no default, and MQTT is published on localhost only. - **Runbook:** the deploy and rollback examples use `vX.Y.Z`, since v3.16.0 and v3.15.0 predate the static build. It also names the server version the static build needs: before #2362 the warm-up headers stay hidden and wildcard previews are refused. ### Audit notes, fixed - **Cache busting on every page:** the tool pages (`area-map.html`, `geofilter-builder.html`) load their scripts with `?v=__BUST__`. The server and `build.sh` replace it in every top-level page, and `_headers` and the Caddyfile make every page revalidate. Behind Caddy, a returning visitor could otherwise get a new tool page with an old `api-base.js`. - **HTTP/3:** the split compose publishes 443 over UDP too, for the HTTP/3 Caddy advertises once `SITE_ADDRESS` is a domain. Checked with Chromium forced onto QUIC: the page and `/api/healthz` loaded over `h3`. - **WebSocket on `/`:** a Go test pins that an upgrade on `/` still works, for UIs cached from before `/ws`. ### Second review - **Trusted proxies:** the docs said to trust the compose subnet, and also to publish port 3000 if wanted. Together they let a client spoof its address: the subnet holds the gateway, where a client reaching a published 3000 through Docker's proxy arrives from. The compose file now fixes the subnet (`SPLIT_NET`, default `172.30.83.0/24`) and the web container's address (`172.30.83.200`), and the docs say to trust that address alone. - **Classic UI unchanged:** the HTML-answer notice above applies to packaged UIs only. On the embedded UI a proxy's HTML 503 is retried as before, and an unknown `/api` path fails to parse as before, with no notice. - **Lint coverage:** the HTML pages and the extra sinks above. AGENTS.md says what the rule cannot see: a URL assembled elsewhere and passed in a variable. - **AGENTS.md:** `build.sh` is described as packaging (a copy, `deployment.js` and `__BUST__`, never a code transform), and rule 3 says `__BUST__` is filled in every top-level page. - **CI builds the web image:** the image-check job (no publish) builds `Dockerfile.web`, runs it, and checks the busted, no-cache `index.html`, the same-origin `deployment.js` and that `/api` reaches `BACKEND`. It also validates the split compose file. - **Cross-origin logins:** a hand-edited `deployment.js` with `auth: true` and another origin now logs a warning naming the setting, instead of failing with CORS errors alone. ## Upgrade notes - **WebSocket path:** the UI's live feed connects to `/ws` instead of `/`. The server has answered `/ws` since #1793 and still upgrades `/`, so browsers holding the previous UI keep working. - A reverse proxy that forwards WebSocket upgrades only for an exact `/` must forward `/ws` too. - The nginx example in `docs/deployment.md` (`location /`) already covers it. - **Static UI from another origin:** - The server needs `CORS_ALLOWED_ORIGINS`, and a version with #2362 for the warm-up banner and wildcard preview origins. - `build.sh` refuses `AUTH=true` there, since the server allows no credentialed CORS. - **Split containers:** - `CORESCOPE_IMAGE` is required. - With user accounts on, `userManagement.publicBaseUrl` must be the web container's public origin. - The built-in MQTT broker is published on `127.0.0.1` unless `MQTT_BIND` says otherwise. - The compose network is `172.30.83.0/24`, with the web container at `.200`. If Docker reports that the pool overlaps another network, set `SPLIT_NET`. ## Testing - `go test ./...`, `go vet` and `gofmt` are clean in `cmd/server`, with new tests for busting every page and the WebSocket upgrade on `/`. - `sh test-all.sh` passes. New unit suites: - `test-static-build.js`: the build and its input checks, `same-origin` included, cross-origin logins refused, and an unrelated `OUT` left intact. - `test-web-container.js`: the Dockerfile, Caddyfile and compose file agree on packaging, forwarded paths, cache rules and the server port; the server image has no default and MQTT stays on localhost. - The `api-base`, anonymous mode, badge and `dev-static` suites. - `eslint public/*.js` has 0 errors. `test-lint-network-calls.js` passes 47/47, the four pages included; it needs eslint, so CI runs it on E2E shard 1. - **Static host or CDN mode:** `test-split-anonymous-e2e.js` passes 11/11. That is the static build on one origin against an API-only server on another, which CI runs on E2E shard 1. - **Split containers mode:** - The image builds, and `caddy validate` passes (Caddy 2.11.4). The new CI step passes locally, and fails when the Caddyfile stops forwarding `/api`. - Trusted proxies, with the stack up: the web container gets `172.30.83.200`. With only that address trusted, a spoofed `X-Forwarded-For` sent straight to a published 3000 is ignored, and one sent through Caddy is replaced with the client's address. With the subnet trusted, as the docs used to say, the spoofed address was believed: a deny entry for it rejected the upgrade. - With `docker-compose.split.yml` on the E2E fixture, seeded the way CI seeds it, `test-e2e-playwright.js` passes 149 of 152 (3 skipped) both through the web container and against the server directly. - Headers, checked with curl: - `no-cache` on `/`, `/index.html` and `/deployment.js`; - zstd on static assets; - `/api/*` proxied (`Via: 1.1 Caddy`); - a `101` WebSocket upgrade on `/ws`. - In Chromium: - every API request and the WebSocket stay on the web container's origin; - there are no page errors and no horizontal overflow at 390 px; - no badge shows on the `static` channel. - Logins through the web container: with user management on and `userManagement.publicBaseUrl` set to the web container's origin, a Chromium run passed every step, all on the web container's origin with no page errors: - registration, and activation from the mail link (which uses `publicBaseUrl`); - the session surviving a reload; - a CSRF-protected `PATCH /api/account`; - logout, then login with the form. - The same login with the backend's origin as `Origin` is refused with 403. The server checks `Origin` against `publicBaseUrl`, not `Host`, which is why the docs ask for it. ## Performance There are no hot-path changes. API calls go through `CSApi.url()`, a string concatenation. In the web container, Caddy serves files from disk and compresses them; API responses pass through with one proxy hop, the same as the all-in-one image's built-in Caddy. ## Notes - **Per-IP limits:** behind the web container, as behind the all-in-one image's Caddy, requests reach the server from the proxy's address. The per-IP limits stay off until `trustedProxies` lists it: `172.30.83.200`, the web container's fixed address. The docs say so. - **`depends_on`:** the web container starts with the server, not after its healthcheck, like the all-in-one image's Caddy. Gating on health would make every `up` wait for the first check (30 s) and fail outright when a large database loads for longer than the healthcheck allows; until the server listens, Caddy answers `/api` with 502. - **Not in this PR:** - publishing a `corescope-web` image (CI builds and smokes it, without publishing); - Cross-origin login—including a static frontend and API on sibling custom domains—is outside this PR. In the deployments supported by this PR, account support requires the frontend and API to share one browser origin, either served together or through a reverse proxy. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .eslintrc.json | 59 ++- .github/workflows/deploy.yml | 51 +++ AGENTS.md | 34 +- DEPLOY.md | 7 + Dockerfile.web | 38 ++ Makefile | 35 +- cmd/server/helpers_test.go | 32 ++ cmd/server/main.go | 64 +++- cmd/server/websocket_test.go | 28 ++ deploy/static/README.md | 174 +++++++++ deploy/static/_headers | 19 + docker-compose.split.yml | 99 +++++ docker/web/Caddyfile | 23 ++ docs/deployment.md | 80 ++++ public/account.js | 3 +- public/admin.js | 1 + public/analytics.js | 6 +- public/api-base.js | 85 +++++ public/app.js | 59 ++- public/area-filter.js | 2 +- public/area-map.html | 6 +- public/auth.js | 25 +- public/beta-ui.js | 93 +++++ public/channels.js | 2 +- public/customize-v2.js | 13 +- public/deployment.js | 10 + public/geofilter-builder.html | 8 +- public/index.html | 3 + public/live.js | 18 +- public/map.js | 23 +- public/mqtt-status-panel.js | 2 +- public/nav-drawer.js | 2 +- public/node-reach-coverage.js | 2 +- public/nodes.js | 4 +- public/packets.js | 13 +- public/path-inspector.js | 6 +- public/perf.js | 17 +- public/region-filter.js | 4 +- public/reported-nodes.js | 2 +- public/roles.js | 9 +- public/route-view.js | 6 +- public/rx-coverage.js | 8 +- public/style.css | 13 + public/warmup-banner.js | 2 +- scripts/dev-static.mjs | 96 +++++ scripts/non-unit-tests.json | 4 +- scripts/static/build.sh | 126 +++++++ test-all.sh | 6 + tests/e2e/test-lint-network-calls.js | 132 +++++++ tests/e2e/test-region-quick-picks.js | 4 + tests/e2e/test-split-anonymous-e2e.js | 191 ++++++++++ tests/unit/api-base-sandbox.js | 30 ++ tests/unit/test-1659-analytics-warmup.js | 2 + tests/unit/test-admin-dashboard-ui.js | 3 + tests/unit/test-aging.js | 2 + tests/unit/test-anonymous-mode.js | 163 +++++++++ tests/unit/test-api-base.js | 342 ++++++++++++++++++ tests/unit/test-area-filter.js | 2 + tests/unit/test-beta-ui.js | 156 ++++++++ tests/unit/test-dev-static.js | 89 +++++ tests/unit/test-fetch-all-nodes-pagination.js | 2 + tests/unit/test-frontend-helpers.js | 8 + tests/unit/test-hb-column-header-route.js | 2 + tests/unit/test-health-status.js | 2 + tests/unit/test-hop-path-detail.js | 2 + .../unit/test-issue-1136-observer-iata-map.js | 2 + .../unit/test-issue-1166-first-seen-column.js | 2 + tests/unit/test-issue-1356-map-a11y.js | 2 + .../test-issue-1407-cb-preset-propagation.js | 2 + .../test-issue-1412-customizer-no-override.js | 4 + tests/unit/test-issue-1418-cb-preset-ramp.js | 2 + .../unit/test-issue-1438-customizer-mcrole.js | 3 + .../unit/test-issue-1446-cb-preset-cascade.js | 8 + .../unit/test-issue-1470-node-tile-helper.js | 2 + .../unit/test-issue-1562-observers-summary.js | 2 + .../test-issue-1563-aggregate-and-inflight.js | 2 + .../unit/test-issue-1614-tile-url-function.js | 2 + tests/unit/test-issue-1849-trace-hashbytes.js | 2 + .../test-issue-1851-channel-message-scope.js | 3 + .../unit/test-issue-1862-map-region-filter.js | 3 + tests/unit/test-issue-1868-control-decode.js | 2 + .../unit/test-issue-1997-distance-building.js | 3 + tests/unit/test-issue-2001-map-scope-state.js | 2 + tests/unit/test-issue-2098-last-hop-region.js | 4 + ...-issue-2218-node-analytics-stale-render.js | 3 + .../test-issue-2230-account-stale-render.js | 2 + tests/unit/test-live-region-filter.js | 2 + tests/unit/test-live.js | 2 + tests/unit/test-map-clustering.js | 2 + tests/unit/test-my-repeaters-dashboard.js | 2 + tests/unit/test-nav-drawer-version-footer.js | 2 + .../unit/test-node-reach-coverage-debounce.js | 2 + .../unit/test-packet-detail-channel-escape.js | 2 + tests/unit/test-packet-detail-hash-size.js | 2 + tests/unit/test-packets.js | 2 + tests/unit/test-perf-disk-io-1120.js | 4 +- tests/unit/test-perf-render-1258.js | 4 +- tests/unit/test-pull-to-reconnect-1091.js | 2 + tests/unit/test-pull-to-reconnect.js | 2 + tests/unit/test-region-filter-url-param.js | 2 + tests/unit/test-reported-nodes.js | 2 + tests/unit/test-rx-coverage-viewport.js | 4 +- tests/unit/test-static-build.js | 198 ++++++++++ tests/unit/test-user-management-ui.js | 7 + tests/unit/test-warmup-banner.js | 4 + tests/unit/test-web-container.js | 117 ++++++ tests/unit/test-ws-stale-watchdog-1074.js | 2 + 107 files changed, 2861 insertions(+), 116 deletions(-) create mode 100644 Dockerfile.web create mode 100644 deploy/static/README.md create mode 100644 deploy/static/_headers create mode 100644 docker-compose.split.yml create mode 100644 docker/web/Caddyfile create mode 100644 public/api-base.js create mode 100644 public/beta-ui.js create mode 100644 public/deployment.js create mode 100644 scripts/dev-static.mjs create mode 100755 scripts/static/build.sh create mode 100644 tests/e2e/test-lint-network-calls.js create mode 100644 tests/e2e/test-split-anonymous-e2e.js create mode 100644 tests/unit/api-base-sandbox.js create mode 100644 tests/unit/test-anonymous-mode.js create mode 100644 tests/unit/test-api-base.js create mode 100644 tests/unit/test-beta-ui.js create mode 100644 tests/unit/test-dev-static.js create mode 100644 tests/unit/test-static-build.js create mode 100644 tests/unit/test-web-container.js diff --git a/.eslintrc.json b/.eslintrc.json index f6e644a5a..7207011a8 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -12,12 +12,14 @@ "CACHE_INVALIDATE_MS": "readonly", "CLIENT_CONFIG": "readonly", "CLIENT_TTL": "readonly", + "CSApi": "readonly", "CSAuth": "readonly", "ChannelColorPicker": "readonly", "ChannelColors": "readonly", "ChannelDecrypt": "readonly", "ChannelQR": "readonly", "Chart": "readonly", + "CSBeta": "readonly", "DIST_THRESHOLDS": "readonly", "DragManager": "readonly", "EXTERNAL_URLS": "readonly", @@ -298,6 +300,59 @@ "argsIgnorePattern": "^_", "varsIgnorePattern": "^_" } + ], + "no-restricted-syntax": [ + "error", + { + "selector": "CallExpression[callee.name='fetch']", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression[callee.property.name='fetch'][callee.object.name=/^(window|self|globalThis)$/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "NewExpression[callee.name=/^(XMLHttpRequest|EventSource)$/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression[callee.property.name='sendBeacon']", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "NewExpression[callee.name='WebSocket']:not([arguments.0.callee.property.name='wsUrl'])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "Literal[value=/(href|src|action)=[\"']\\/api(\\/|$)/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "TemplateElement[value.raw=/(href|src|action)=[\"']\\/api(\\/|$)/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "AssignmentExpression:matches([left.property.name=/^(href|src|action|location)$/], [left.name='location']):matches([right.value=/^\\/api(\\/|$)/], [right.left.value=/^\\/api(\\/|$)/], [right.left.left.value=/^\\/api(\\/|$)/], [right.quasis.0.value.raw=/^\\/api(\\/|$)/])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression:matches([callee.name='open'], [callee.property.name='open'], [callee.object.name='location'][callee.property.name=/^(assign|replace)$/], [callee.object.property.name='location'][callee.property.name=/^(assign|replace)$/]):matches([arguments.0.value=/^\\/api(\\/|$)/], [arguments.0.left.value=/^\\/api(\\/|$)/], [arguments.0.left.left.value=/^\\/api(\\/|$)/], [arguments.0.quasis.0.value.raw=/^\\/api(\\/|$)/])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression[callee.property.name='setAttribute'][arguments.0.value=/^(href|src|action|formaction)$/]:matches([arguments.1.value=/^\\/api(\\/|$)/], [arguments.1.left.value=/^\\/api(\\/|$)/], [arguments.1.left.left.value=/^\\/api(\\/|$)/], [arguments.1.quasis.0.value.raw=/^\\/api(\\/|$)/])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + } ] - } -} \ No newline at end of file + }, + "overrides": [ + { + "files": [ + "public/api-base.js" + ], + "rules": { + "no-restricted-syntax": "off" + } + } + ] +} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 350c28648..a22c3425c 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -553,6 +553,25 @@ jobs: sleep 1 done + - name: Start split frontend (static build + API-only server) + # The anonymous static build on :8788 against a stock server on :13591 + # that lists that origin in CORS_ALLOWED_ORIGINS, the way a static + # frontend (Cloudflare Pages) calls the containers. -public on a missing + # directory is API-only mode, so nothing is served same-origin. + if: matrix.shard == 1 + run: | + CHANNEL=dev COMMIT=e2e API_BASE=http://localhost:13591 AUTH=false CLASSIC_URL=http://localhost:13591 bash scripts/static/build.sh + fuser -k 13591/tcp 8788/tcp 2>/dev/null || true + CORS_ALLOWED_ORIGINS=http://localhost:8788 ./corescope-server -port 13591 -db test-fixtures/e2e-fixture.db -public /nonexistent & + echo $! > .server-split.pid + node scripts/dev-static.mjs --root dist/web --port 8788 & + echo $! > .static-split.pid + for i in $(seq 1 30); do + if curl -sf http://localhost:13591/api/healthz > /dev/null 2>&1 && curl -sf -o /dev/null http://localhost:8788/; then echo "split frontend ready after ${i}s"; break; fi + if [ "$i" -eq 30 ]; then echo "split frontend failed to start within 30s"; exit 1; fi + sleep 1 + done + - name: Run Playwright E2E tests (fail-fast) env: # On master pushes every suite records the frontend coverage of the @@ -587,6 +606,8 @@ jobs: # Allowlist: tests/a11y-allowlist.yaml (0 entries — hard pass policy). # Per-viewport summary printed at the end; any net>0 fails the build. suite 1 test-a11y-axe-1668.js BASE_URL=$B AXE_SCREENSHOT_DIR=/tmp/axe-1668 + # The static build on another origin than the API (scripts/static/build.sh). + suite 1 test-split-anonymous-e2e.js SPLIT_URL=http://localhost:8788 API_URL=http://localhost:13591 suite 2 test-filter-ux-e2e.js BASE_URL=$B suite 2 test-radio-setting-1869-e2e.js BASE_URL=$B suite 2 test-observer-neighbors-2270-e2e.js BASE_URL=$B @@ -719,6 +740,8 @@ jobs: suite 3 test-path-inspector-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-pr-1490-live-map-gpu-animations-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 1 test-region-quick-picks.js + # The lint rule that keeps network calls on CSApi (needs eslint). + suite 1 test-lint-network-calls.js suite 3 test-table-sort.js suite 1 test-touch-targets.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-live-dedup.js BASE_URL=$B @@ -784,6 +807,9 @@ jobs: kill $(cat .server-um.pid) 2>/dev/null || true rm -f .server-um.pid fi + for f in .server-split.pid .static-split.pid; do + if [ -f "$f" ]; then kill $(cat "$f") 2>/dev/null || true; rm -f "$f"; fi + done - name: Upload shard results if: success() @@ -944,9 +970,34 @@ jobs: - name: Validate staging compose file run: docker compose -f "$STAGING_COMPOSE_FILE" -p corescope-staging config --quiet + # Split containers: operators build the web image from their checkout and + # nothing publishes it, so without this a broken base image, package or + # Caddyfile would reach an operator first. + - name: Validate split compose file + run: CORESCOPE_IMAGE=corescope:check docker compose -f docker-compose.split.yml config --quiet + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 + - name: Build and smoke the web image (Dockerfile.web) + env: + GIT_COMMIT: ${{ steps.meta.outputs.git_commit }} + run: | + set -euo pipefail + docker buildx build . -f Dockerfile.web --load -t corescope-web:check --build-arg GIT_COMMIT="$GIT_COMMIT" + # BACKEND is a closed port: /api must reach it (502), not the file server (404). + docker run -d --name web-check -p 8080:80 -e BACKEND=127.0.0.1:9 corescope-web:check + trap 'docker logs web-check 2>&1 | tail -20; docker rm -f web-check >/dev/null' EXIT + for i in $(seq 1 30); do curl -fs -o /dev/null http://localhost:8080/ && break; sleep 1; done + page=$(curl -fsS -D headers.txt http://localhost:8080/) + echo "$page" | grep -q "app.js?v=$GIT_COMMIT" || { echo "::error::index.html is not busted with the commit"; exit 1; } + if echo "$page" | grep -q __BUST__; then echo "::error::index.html still has __BUST__"; exit 1; fi + grep -qi '^cache-control: no-cache' headers.txt || { echo "::error::index.html may be cached"; exit 1; } + curl -fsS http://localhost:8080/deployment.js | grep -q "apiBase: ''" || { echo "::error::deployment.js is not same-origin"; exit 1; } + code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/api/healthz) + [ "$code" = 502 ] || { echo "::error::/api/healthz answered $code, not 502 from the closed BACKEND"; exit 1; } + echo "web image serves the packaged UI and forwards /api ✅" + - name: Set up QEMU (arm64 runtime stage + arm64 smoke) uses: docker/setup-qemu-action@v3 diff --git a/AGENTS.md b/AGENTS.md index fd35106a0..0e3f1726f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,8 @@ Guide for AI agents working on this codebase. Read this before writing any code. ## Architecture -Go backend + static frontend. No build step. No framework. No bundler. +Go backend + static frontend. No build step: `public/` is what the browser runs. No framework. No bundler. +`scripts/static/build.sh` is packaging, not a build: it copies `public/` for a static host or the web container, writes `deployment.js` and fills in `__BUST__`, and never transforms code. **⚠️ The Node.js server (server.js) is DEPRECATED and has been removed. All backend code is in Go.** **⚠️ DO NOT create or modify any Node.js server files. All backend changes go in `cmd/server/` or `cmd/ingestor/`.** @@ -18,7 +19,9 @@ cmd/server/ — Go API server (REST + WebSocket broadcast + static file s decoder.go — MeshCore packet decoder cmd/ingestor/ — Go MQTT ingestor (separate binary, writes to shared SQLite DB) public/ — Frontend (vanilla JS, one file per page) — ACTIVE, NOT DEPRECATED - app.js — SPA router, shared globals, theme loading + app.js — SPA router, shared globals, theme loading, api() (cached GETs) + deployment.js — where the API is (rewritten by scripts/static/build.sh for a static host) + api-base.js — CSApi: the ONLY code that builds API URLs or opens connections (see "API calls") roles.js — ROLE_COLORS, TYPE_COLORS, health thresholds, shared helpers nodes.js — Nodes list + side pane + full detail page map.js — Leaflet map with markers, legend, filters @@ -33,9 +36,10 @@ public/ — Frontend (vanilla JS, one file per page) — ACTIVE, NOT style.css — Main styles, CSS variables for theming live.css — Live page styles home.css — Home page styles - index.html — SPA shell, script/style tags with __BUST__ placeholder (auto-replaced at server startup) + index.html — SPA shell, script/style tags with __BUST__ placeholder (filled in automatically; see rule 3) test-fixtures/ — Real data SQLite fixture from staging (used for E2E tests) -scripts/ — Tooling (coverage collector, fixture capture, frontend instrumentation) +scripts/ — Tooling (coverage collector, fixture capture, frontend instrumentation; + static/build.sh packages the UI for a static host or the web container) ``` ### Data Flow @@ -105,7 +109,7 @@ Every change must consider performance impact BEFORE implementation. This codeba No proof = no merge. ### 1. No commit without tests -Every change that touches logic MUST have tests. For Go backend: `cd cmd/server && go test ./...` and `cd cmd/ingestor && go test ./...`, or `make test` for all 14 modules. For frontend: `node tests/unit/test-packet-filter.js && node tests/unit/test-aging.js && node tests/unit/test-frontend-helpers.js`. If you add new logic, add tests. No exceptions. +Every change that touches logic MUST have tests. For Go backend: `cd cmd/server && go test ./...` and `cd cmd/ingestor && go test ./...`, or `make test` for all 14 modules. For frontend: `node tests/unit/test-packet-filter.js && node tests/unit/test-aging.js && node tests/unit/test-frontend-helpers.js`, and `npx eslint public/*.js` (CI fails on any error). If you add new logic, add tests. No exceptions. The SQLite driver (`github.com/mattn/go-sqlite3`) is cgo. **`CGO_ENABLED=0` still *builds*** — that is the trap. It links a stub, and the binary dies on the first query with `go-sqlite3 requires cgo to work. This is a stub`, so a green build proves nothing. A plain `GOOS=linux go build` likewise cannot cross-compile it. Use `make build` / `make crossbuild` — the latter needs [`zig`](https://ziglang.org/download/) as the cross C compiler and produces static musl binaries. Never re-add `CGO_ENABLED=0`. @@ -113,7 +117,7 @@ The SQLite driver (`github.com/mattn/go-sqlite3`) is cgo. **`CGO_ENABLED=0` stil After pushing, verify the change works in an actual browser. Use `browser profile=openclaw` against the running instance. Take a screenshot if the change is visual. If you can't validate it, say so — don't claim it works. ### 3. Cache busters are automatic — do NOT manually edit them -Cache busters are injected automatically by the Go server at startup. The `__BUST__` placeholder in `index.html` is replaced with a Unix timestamp when the server reads the file. No manual bumping needed — every server restart picks up new asset versions. Do NOT replace `__BUST__` with hardcoded timestamps. +Cache busters are injected automatically. The Go server replaces the `__BUST__` placeholder in every top-level page (`index.html`, `area-map.html`, `geofilter-*.html`) with a Unix timestamp at startup, so every server restart picks up new asset versions. `scripts/static/build.sh` replaces it with the commit when it packages the UI. No manual bumping needed. Do NOT replace `__BUST__` with hardcoded timestamps, and give every local script or stylesheet a new page loads `?v=__BUST__`. ### 4. Verify API response shape before building UI Before writing client code that consumes an API endpoint, check what the endpoint ACTUALLY returns. Use `curl` or check the server code. Don't assume fields exist — grouped packets (`groupByHash=true`) have different fields than raw packets. This has caused multiple breakages. @@ -196,6 +200,22 @@ If you need to know how something works — a flag, a field, a timing, a behavio ## Frontend Conventions +### API calls (api-base.js) +The UI runs embedded in the server, in the web container, and from a static host or CDN on another origin (see "Deployment modes" in `docs/deployment.md`). `public/deployment.js` says where the API is, and `public/api-base.js` (`window.CSApi`) is the only code that turns a path into a URL or opens a connection. Everything else goes through it: + +| Need | Use | +|------|-----| +| GET JSON, cached | `api('/nodes?…')` (app.js) | +| Any other request | `CSApi.fetch('/api/…', opts)` | +| JSON POST | `CSApi.postJSON('/api/…', body)`: sends `text/plain`, so a cross-origin POST has no preflight (the server decodes JSON whatever the Content-Type; `cmd/server/simple_post_test.go`) | +| Logged-in request | `CSAuth.request(method, '/api/…', body)` | +| Link, download, `src` | `CSApi.url('/api/…')` | +| WebSocket | `new WebSocket(CSApi.wsUrl('/ws'))` | + +- **Never** call `fetch`, `XMLHttpRequest`, `EventSource`, `navigator.sendBeacon` or `new WebSocket(url)` directly, or put a bare `/api/…` path in an `href`, `src` or `action` (assigned, set with `setAttribute` or written into markup) or in `window.open`, `location.assign`, `location.replace` or `location =`. It works embedded and breaks on a static host. The `no-restricted-syntax` rule in `.eslintrc.json` rejects all of these in `public/*.js` (only `api-base.js` is exempt) and CI fails on it: run `npx eslint public/*.js` before pushing. That command never sees the inline scripts and markup of `public/*.html`; `tests/e2e/test-lint-network-calls.js` applies the same rule to them, and pins what the rule reports: extend it when you extend the rule. The rule sees a path at the start of a string, a concatenation or a template; a URL assembled elsewhere and passed in a variable gets past it, so it does not replace review. Do not silence it with `eslint-disable`. The one exception is `area-map.html`, whose Server field can name another server. +- **Logins and writes:** the anonymous static build (`CSApi.anonymous`) sends no cookies. A feature that needs a login or a write shows `CSBeta.classicOnlyHtml('…')` (or links with `CSApi.classicHref(hash)`) instead, as `account.js`, `admin.js` and `perf.js` do. +- **Tests:** a test that runs a frontend file outside the browser must load `deployment.js` and `api-base.js` first, or `CSApi` is undefined and its fetches fail silently inside their `try` blocks. vm sandboxes: `tests/unit/api-base-sandbox.js`. jsdom: `w.eval` both files before the file under test (`tests/e2e/test-region-quick-picks.js`). + ### Theming All colors MUST use CSS variables. Never hardcode `#hex` values outside of `:root` definitions. The customizer controls colors via `THEME_CSS_MAP` in customize.js. If you add a new color, add it as a CSS variable and map it in the customizer. @@ -378,6 +398,7 @@ One logical change per commit. Each commit is deployable. Each commit has its te | Gave up testing locally | 2 | Basic tests work on ARM — only heavy coverage scripts crash | | Copy-pasted functions for "coverage" | 1 | Test the real code, not copies in a helper file | | Subagent timed out mid-work | 4 | Give clear scope, don't try to run slow pipelines locally | +| Frontend file tested without api-base.js | 1 | Load `deployment.js` + `api-base.js` first (see "API calls") | ## File Naming - Tests: `test-{feature}.js` in `tests/unit/` (standalone, listed in `test-all.sh`) or `tests/e2e/` (browser, listed in `scripts/non-unit-tests.json`) — never in repo root @@ -397,5 +418,6 @@ Existing patterns: `#/nodes/{pubkey}?section=node-neighbors`, `#/analytics?tab=c - Don't add framework abstractions (React, Vue, etc.) - Don't hardcode colors — use CSS variables - Don't make per-packet server API calls from the frontend +- Don't call `fetch` / `WebSocket` / XHR directly from the frontend — go through `CSApi` (see "API calls") - Don't push without running tests - Don't start implementing without plan approval diff --git a/DEPLOY.md b/DEPLOY.md index 040cd0981..444ed5656 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -24,6 +24,13 @@ curl -sL https://raw.githubusercontent.com/Kpa-clawbot/CoreScope/master/docker-c docker compose up -d ``` +### Other deployment modes + +The UI can also run in a container of its own (`docker-compose.split.yml`, with +`CORESCOPE_IMAGE` set to the server image of your checkout's version) or from a +static host or CDN such as Cloudflare Pages. See +[Deployment modes](docs/deployment.md#deployment-modes). + ## Image Tags | Tag | Description | diff --git a/Dockerfile.web b/Dockerfile.web new file mode 100644 index 000000000..e22799c95 --- /dev/null +++ b/Dockerfile.web @@ -0,0 +1,38 @@ +# CoreScope web container: the static UI on its own, served by Caddy, which +# forwards /api and /ws to a CoreScope server container. The UI and the API +# then share one origin, so the server needs no CORS settings. Logins work as +# on the classic UI once the server's userManagement.publicBaseUrl is this +# container's public origin. docker-compose.split.yml runs the two together; +# see "Deployment modes" in docs/deployment.md. +# +# Runtime environment: +# BACKEND host:port of the CoreScope server. Default corescope:3000. +# SITE_ADDRESS :80 (default) for plain HTTP, or a domain name for Caddy's +# automatic HTTPS (publish 80 and 443, and keep /data). + +FROM alpine:3.24 AS build +RUN apk add --no-cache bash +WORKDIR /src +COPY public/ public/ +COPY scripts/static/ scripts/static/ +COPY deploy/static/ deploy/static/ +# GIT_COMMIT is the cache buster on every asset (?v=); without one, the build +# time, as the server does at start. CHANNEL beta, next or dev shows a badge. +ARG GIT_COMMIT= +ARG CHANNEL=static +RUN COMMIT="$(printf '%.12s' "${GIT_COMMIT:-$(date +%s)}")" \ + API_BASE=same-origin AUTH=true CHANNEL="$CHANNEL" OUT=/srv \ + bash scripts/static/build.sh && \ + rm /srv/_headers + +FROM alpine:3.24 +RUN apk add --no-cache caddy +COPY --from=build /srv /srv +COPY docker/web/Caddyfile /etc/caddy/Caddyfile +ENV BACKEND=corescope:3000 \ + SITE_ADDRESS=:80 \ + XDG_DATA_HOME=/data \ + XDG_CONFIG_HOME=/config +EXPOSE 80 443 +VOLUME ["/data"] +CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"] diff --git a/Makefile b/Makefile index 345d628f0..cc633614a 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,8 @@ # make crossbuild # linux/amd64 + linux/arm64, static, into dist/ # make test / vet / fmt-check # across all modules # make docker-build # multi-arch image via buildx +# make web API_BASE=… AUTH=… # the UI alone, for a static host, into dist/web +# make dev-split # UI on :8788 calling the API on :3000 cross-origin GO ?= $(shell command -v go) GIT_VERSION ?= $(shell git describe --tags --match "v*" 2>/dev/null || echo unknown) @@ -59,12 +61,12 @@ DOCKER_IMAGE ?= ghcr.io/kpa-clawbot/corescope DOCKER_TAG ?= $(GIT_VERSION) DOCKER_PLATFORMS ?= linux/amd64,linux/arm64 -.PHONY: all build crossbuild test vet fmt-check tidy clean docker-build docker-push help +.PHONY: all build crossbuild test vet fmt-check tidy clean web dev-split docker-build docker-push help all: build help: - @echo "targets: build crossbuild test vet fmt-check tidy clean docker-build docker-push" + @echo "targets: build crossbuild test vet fmt-check tidy clean web dev-split docker-build docker-push" @echo " build-{$(shell echo $(CMDS) | tr ' ' ',')}" # -- host builds --------------------------------------------------------------- @@ -119,6 +121,35 @@ tidy: clean: rm -rf $(DIST) +# -- static frontend ------------------------------------------------------------ +# +# web packages public/ into dist/web for a static host or a CDN. It reads +# API_BASE, AUTH, CHANNEL, CLASSIC_URL and COMMIT; see scripts/static/build.sh. +# The Go binaries share dist/, which is why the UI gets a folder of its own. +web: + bash scripts/static/build.sh + +# dev-split runs the UI the way a static host serves it: the anonymous +# build on :8788 calling an API-only server on :3000 cross-origin, with no +# proxy. The server change is the one env var, exactly as in production. +# DEV_SPLIT_DB=path/to.db picks the data (default: the E2E fixture); it runs on a +# migrated copy in dist/, so the original is never touched. +DEV_SPLIT_DB ?= test-fixtures/e2e-fixture.db +DEV_SPLIT_API_PORT ?= 3000 +DEV_SPLIT_STATIC_PORT ?= 8788 + +dev-split: build-server build-migrate + cp $(DEV_SPLIT_DB) $(DIST)/dev-split.db + $(DIST)/corescope-migrate -db $(DIST)/dev-split.db + CHANNEL=dev COMMIT=dev AUTH=false \ + API_BASE=http://localhost:$(DEV_SPLIT_API_PORT) CLASSIC_URL=http://localhost:$(DEV_SPLIT_API_PORT) \ + bash scripts/static/build.sh + @echo "UI: http://localhost:$(DEV_SPLIT_STATIC_PORT) API: http://localhost:$(DEV_SPLIT_API_PORT) (Ctrl-C stops both)" + @trap 'kill 0' INT TERM EXIT; \ + CORS_ALLOWED_ORIGINS=http://localhost:$(DEV_SPLIT_STATIC_PORT) \ + $(DIST)/corescope-server -port $(DEV_SPLIT_API_PORT) -db $(DIST)/dev-split.db -public /nonexistent & \ + node scripts/dev-static.mjs --root $(DIST)/web --port $(DEV_SPLIT_STATIC_PORT) + # -- docker -------------------------------------------------------------------- docker-build: diff --git a/cmd/server/helpers_test.go b/cmd/server/helpers_test.go index b2bff47a6..f146ffc53 100644 --- a/cmd/server/helpers_test.go +++ b/cmd/server/helpers_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "regexp" "strings" "testing" ) @@ -447,6 +448,37 @@ func TestSpaHandlerCacheBust(t *testing.T) { }) } +// Every top-level page gets the same cache buster as index.html, so a tool +// page (area-map.html, geofilter-builder.html) served fresh never runs a +// script cached from before the server started. +func TestSpaHandlerBustsEveryTopLevelPage(t *testing.T) { + dir := t.TempDir() + os.WriteFile(filepath.Join(dir, "index.html"), []byte(``), 0644) + os.WriteFile(filepath.Join(dir, "tool.html"), []byte(``), 0644) + handler := spaHandler(dir, http.FileServer(http.Dir(dir))) + + get := func(p string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("GET", p, nil)) + return w + } + bust := regexp.MustCompile(`v=(\d+)`) + index, tool := get("/"), get("/tool.html") + if strings.Contains(tool.Body.String(), "__BUST__") { + t.Fatalf("tool.html kept its placeholder: %s", tool.Body.String()) + } + im, tm := bust.FindStringSubmatch(index.Body.String()), bust.FindStringSubmatch(tool.Body.String()) + if im == nil || tm == nil || im[1] != tm[1] { + t.Errorf("tool.html buster %v, index.html buster %v: want the same timestamp", tm, im) + } + if got := tool.Header().Get("Cache-Control"); got != "no-cache, no-store, must-revalidate" { + t.Errorf("tool.html Cache-Control = %q", got) + } + if got := tool.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/html") { + t.Errorf("tool.html Content-Type = %q", got) + } +} + func TestWriteJSON(t *testing.T) { w := httptest.NewRecorder() writeJSON(w, map[string]interface{}{"key": "value"}) diff --git a/cmd/server/main.go b/cmd/server/main.go index ac880ada6..4958be1da 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -606,16 +606,22 @@ func main() { // It reads index.html once at creation time and replaces the __BUST__ placeholder // with a Unix timestamp so browsers fetch fresh JS/CSS after each server restart. func spaHandler(root string, fs http.Handler) http.Handler { - // Pre-process index.html: replace __BUST__ with a cache-bust timestamp - indexPath := filepath.Join(root, "index.html") - rawHTML, err := os.ReadFile(indexPath) - if err != nil { - log.Printf("[static] warning: could not read index.html for cache-bust: %v", err) - rawHTML = []byte("

CoreScope

index.html not found

") - } + // Pre-process every top-level page, index.html and the tool pages + // (area-map.html, geofilter-builder.html): replace __BUST__ with a + // cache-bust timestamp, so each loads the scripts of this start. bustValue := fmt.Sprintf("%d", time.Now().Unix()) - indexHTML := []byte(strings.ReplaceAll(string(rawHTML), "__BUST__", bustValue)) - log.Printf("[static] cache-bust value: %s", bustValue) + pages := bustPages(root, bustValue) + indexHTML, ok := pages["/index.html"] + if !ok { + log.Printf("[static] warning: could not read index.html for cache-bust") + indexHTML = []byte("

CoreScope

index.html not found

") + } + log.Printf("[static] cache-bust value: %s (%d pages)", bustValue, len(pages)) + servePage := func(w http.ResponseWriter, body []byte) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + w.Write(body) + } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Defense-in-depth: explicitly reject path-traversal attempts before @@ -628,20 +634,21 @@ func spaHandler(root string, fs http.Handler) http.Handler { http.Error(w, "bad request", http.StatusBadRequest) return } - // Serve pre-processed index.html for root and /index.html - if r.URL.Path == "/" || r.URL.Path == "/index.html" { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - w.Write(indexHTML) + // Serve the pre-processed index.html for the root, and each + // pre-processed page (/index.html included) at its own path + if r.URL.Path == "/" { + servePage(w, indexHTML) + return + } + if page, ok := pages[r.URL.Path]; ok { + servePage(w, page) return } path := filepath.Join(root, r.URL.Path) if _, err := os.Stat(path); os.IsNotExist(err) { // SPA fallback — serve pre-processed index.html - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - w.Write(indexHTML) + servePage(w, indexHTML) return } // Disable caching for JS/CSS/HTML @@ -652,6 +659,29 @@ func spaHandler(root string, fs http.Handler) http.Handler { }) } +// bustPages reads each .html file at the top of root, keyed by its URL path +// ("/index.html"), with every __BUST__ replaced by bust. +func bustPages(root, bust string) map[string][]byte { + pages := map[string][]byte{} + entries, err := os.ReadDir(root) + if err != nil { + log.Printf("[static] warning: could not list %s for cache-bust: %v", root, err) + return pages + } + for _, e := range entries { + if e.IsDir() || !strings.EqualFold(filepath.Ext(e.Name()), ".html") { + continue + } + raw, err := os.ReadFile(filepath.Join(root, e.Name())) + if err != nil { + log.Printf("[static] warning: could not read %s for cache-bust: %v", e.Name(), err) + continue + } + pages["/"+e.Name()] = []byte(strings.ReplaceAll(string(raw), "__BUST__", bust)) + } + return pages +} + // isSafeStaticPath rejects request paths that contain traversal sequences // or backslashes — defense-in-depth for the SPA static handler so a future // router with SkipClean(true) cannot expose the filesystem. Empty input is diff --git a/cmd/server/websocket_test.go b/cmd/server/websocket_test.go index fbdd62106..17bf337d6 100644 --- a/cmd/server/websocket_test.go +++ b/cmd/server/websocket_test.go @@ -454,3 +454,31 @@ func TestHubDefaultPingInterval(t *testing.T) { t.Fatalf("pingInterval = %v, want 30s (public/app.js WS_STALE_MS depends on it)", got) } } + +// UIs cached from before the UI moved its WebSocket to /ws still connect on +// "/": wsOrStatic upgrades any path the static handler serves. Keep that +// until those clients are gone; this pins it. +func TestWebSocketUpgradeOnRootStillWorks(t *testing.T) { + hub := NewHub() + static := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("static")) + }) + srv := httptest.NewServer(wsOrStatic(hub, static)) + defer srv.Close() + + conn, resp, err := websocket.DefaultDialer.Dial("ws"+srv.URL[4:]+"/", nil) + if err != nil { + t.Fatalf("dial /: %v", err) + } + defer conn.Close() + if resp.StatusCode != http.StatusSwitchingProtocols { + t.Fatalf("dial /: status %d, want 101", resp.StatusCode) + } + deadline := time.Now().Add(2 * time.Second) + for hub.ClientCount() != 1 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if hub.ClientCount() != 1 { + t.Errorf("expected the root connection to register with the hub, got %d clients", hub.ClientCount()) + } +} diff --git a/deploy/static/README.md b/deploy/static/README.md new file mode 100644 index 000000000..a7d53f002 --- /dev/null +++ b/deploy/static/README.md @@ -0,0 +1,174 @@ +# Frontend on a static host or CDN + +The CoreScope UI is static files. This directory and `scripts/static/build.sh` +let it be served from Cloudflare Pages or any other static host, while the +existing container keeps serving the API and the classic, embedded UI. This is +the third of the deployment modes in +[docs/deployment.md](../../docs/deployment.md#deployment-modes); the other two +run the UI in a container. + +This is the **anonymous** build (`AUTH=false`): it reads everything a logged-out +visitor can read, live updates included, and links to the classic site for +logging in and admin work. On the server it needs one setting, +`CORS_ALLOWED_ORIGINS` (see [Server](#server)), on a version that includes #2362: +`edge` now, and releases cut from `master` after it. Older servers accept the +origin too, but they hide the `Retry-After` and `X-CoreScope-Load-Status` +headers from it, so the warm-up banner never shows, and they refuse wildcard +preview origins. + +## How it works + +- `public/deployment.js` says where the API is. The embedded UI ships it with + `apiBase: ''` (same origin, as today). `build.sh` rewrites it for the + static build. +- `public/api-base.js` (`window.CSApi`) is the only place that builds API and + WebSocket URLs. A lint rule keeps raw `fetch('/api…')` out of every other file. +- The anonymous build sends no cookies, sends its three JSON `POST`s as + `text/plain` (so the browser sends no preflight), and hides login, account and + admin controls in favour of an "available on classic" link. + +## Building + +```bash +make web API_BASE=https://analyzer.example.org AUTH=false +``` + +writes `dist/web`: `public/` byte for byte, except that every top-level page +(`index.html` and the tool pages) gets the cache buster and `deployment.js` says +where the API is. Serve that folder at the root of a hostname; the UI uses +absolute paths such as `/icons/…`. `_headers` holds the cache rules: the pages +and `deployment.js` always revalidate, while everything they load carries +`?v=`. Cloudflare Pages and Netlify read it; other hosts need the same +rules in their own config. The variables are in step 6 below and at the top of +`scripts/static/build.sh`. + +## Deploying from a fork + +This repository is the software, not any one CoreScope instance: it has no +Pages project and deploys nothing. Each instance (a region, the flagship) +deploys from its own fork. Pages needs that anyway: its GitHub App is installed +on a repository you administer. + +The fork carries **no code changes**. Every setting lives in the Pages project +variables, and deploying means moving a branch to a commit that already exists +upstream. + +### One-time setup + +1. Fork this repository into an account or org your maintainers administer. +2. In the fork, turn GitHub Actions off (Settings → Actions). Otherwise syncing + `master` runs this repository's CI and deploy workflows there, which fail + without its secrets. Pages builds do not use Actions. +3. Create the deploy branches `stage` and `prod`, and protect `prod` so only + maintainers can move it. +4. Install the Cloudflare Pages GitHub App on the fork only. +5. Create one Pages project per deploy branch, on the Free plan: + + | Project | Production branch | Serves | API | + |---|---|---|---| + | e.g. `corescope-web-stage` | `stage` | your staging frontend | your staging server | + | e.g. `corescope-web-prod` | `prod` | your production frontend | your production server | + + For both: + - build command: `bash scripts/static/build.sh`; + - build output directory: `dist/web`; root directory: blank (the + repository root holds files over Pages' 25 MiB limit); + - preview branches: None, or All to get a preview of every other branch + pushed to the fork (see Previews below). + + One project on `prod` is enough if you have no staging server. +6. Environment variables (Production environment, and Preview too if previews + are on) for each project: + + | Name | Example | Notes | + |---|---|---| + | `API_BASE` | `https://analyzer.example.org` | The CoreScope server. https, lowercase, no path | + | `AUTH` | `false` | Required, no default. Must be `false`: the server allows no credentialed CORS, so `build.sh` refuses `true` with a cross-origin `API_BASE` | + | `CHANNEL` | `beta` | `beta`, `next` or `dev` show a badge; `static` shows none | + | `CLASSIC_URL` | `https://analyzer.example.org` | Optional. Target of the "Open in classic" links | + | `SKIP_DEPENDENCY_INSTALL` | `1` | `build.sh` needs no npm packages | + + `COMMIT` defaults to the first 7 characters of `CF_PAGES_COMMIT_SHA`. +7. Add a custom domain to each project (for example `beta.example.org`). The + UI uses absolute paths such as `/icons/…`, so it must be served at the root + of a hostname. + +### Deploying + +Keep each frontend on the version its server runs: `prod` on the release tag +your production containers run, `stage` on upstream `master` if staging runs +the master image. Upgrade the server first, then move the branch. Move branches +by fast-forward, so they stay identical to upstream commits (`upstream` is this +repository, `region` is your fork, and `vX.Y.Z` is the release your production +server runs): + +```bash +git fetch upstream --tags +git push region vX.Y.Z:refs/heads/prod +git push region upstream/master:refs/heads/stage +``` + +Releases up to v3.16.0 predate `scripts/static/build.sh` and have nothing to +build, so `prod` can only follow releases cut after it. + +Only move `stage` to a `master` commit whose CI passed. A pull request into +`prod` also works if you want a review step, but its merge commits make the +branch drift from upstream. Each project builds only when its branch moves. + +### Previews + +With preview branches on, every other branch pushed to the fork, and every pull +request between branches of the fork, gets its own deployment at +`..pages.dev` plus a branch alias such as +`my-branch..pages.dev`. Set `CHANNEL=dev` in the Preview environment +so previews show the Dev badge. Pull requests to this repository come from +forks and get no preview. + +A preview is code from a branch, so keep previews anonymous (`AUTH=false`), +pointed at a staging server if you have one. + +## Server + +Append the static origin to the embed CORS list and restart: + +```bash +# Keep every origin already listed; add the static one exactly. Never "*". +CORS_ALLOWED_ORIGINS=https://existing-embed.example.org,https://beta.example.org +``` + +- The env var replaces `corsAllowedOrigins` from `config.json`, so it must list + every origin, old and new. +- An entry is an exact origin: lowercase, scheme included, no trailing slash. +- For previews, also list `https://.pages.dev` and + `https://*..pages.dev` (wildcard labels need a server with #2362; see + `config.example.json`). The wildcard matches one label only, and the server + refuses `https://*.pages.dev`. +- The same list admits the origin to `/ws`. A `*` entry does not work for `/ws`. + +Check it: + +```bash +curl -sI -H "Origin: https://beta.example.org" https://analyzer.example.org/api/stats | grep -i access-control-allow-origin +``` + +It must print the origin, and no `Access-Control-Allow-Credentials` line. + +## Local and CI + +```bash +make dev-split +``` + +The UI on `http://localhost:8788` calls an API-only server on +`http://localhost:3000` cross-origin, with no proxy. CI runs +`tests/e2e/test-split-anonymous-e2e.js` the same way on E2E shard 1. Pull requests +to this repository get no preview deployment; this is how to try one. + +## Roll back + +- **The UI:** in the Pages dashboard, roll back to the previous deployment, or + move the deploy branch back to the previous release tag + (`git push --force-with-lease region vX.Y.Z:refs/heads/prod`). +- **Access from the static origin:** remove it from `CORS_ALLOWED_ORIGINS` and + restart. The static UI then shows "Can't reach the CoreScope API"; the classic + UI and embeds are unaffected. diff --git a/deploy/static/_headers b/deploy/static/_headers new file mode 100644 index 000000000..56aa174bd --- /dev/null +++ b/deploy/static/_headers @@ -0,0 +1,19 @@ +# Copied into the static build by scripts/static/build.sh. Cloudflare Pages +# and Netlify read it; other hosts ignore it and need the same rules in their +# own config (the web container's are in docker/web/Caddyfile). The pages and +# deployment.js change on every deploy without a ?v= buster, so a browser must +# always revalidate them. Every local script and stylesheet a page loads +# carries ?v= (vendor/ files carry their version in the path), so +# those may use the host's default caching. +/ + Cache-Control: no-cache, no-store, must-revalidate +/index.html + Cache-Control: no-cache, no-store, must-revalidate +/area-map.html + Cache-Control: no-cache, no-store, must-revalidate +/geofilter-builder.html + Cache-Control: no-cache, no-store, must-revalidate +/geofilter-docs.html + Cache-Control: no-cache, no-store, must-revalidate +/deployment.js + Cache-Control: no-cache, no-store, must-revalidate diff --git a/docker-compose.split.yml b/docker-compose.split.yml new file mode 100644 index 000000000..bdf90546d --- /dev/null +++ b/docker-compose.split.yml @@ -0,0 +1,99 @@ +# CoreScope — split containers: the UI in its own web container and the +# server in the usual image. +# +# The web container (Dockerfile.web, Caddy) serves the static UI and forwards +# /api and /ws to the server, so both share one origin: no CORS settings. With +# user management on, set the server's userManagement.publicBaseUrl to the web +# container's public origin (scheme and port included): logins and other +# writes are checked against it. The server container is unchanged and still +# serves everything, the classic UI included, on port 3000 inside the compose +# network; publish it too if you want to reach that directly. For per-IP +# limits, the server trusts the web container's fixed address: see networks. +# +# Usage: CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge \ +# docker compose -f docker-compose.split.yml up -d --build +# Docs: docs/deployment.md, "Deployment modes" +# +# Variables (shell or .env): +# CORESCOPE_IMAGE required: the server image of the same version as this +# checkout, which the web image is built from. :edge on +# master, :vX.Y.Z on a release tag. There is no default, so +# a release server is never paired with a newer UI unasked. +# DATA_DIR the server's data directory. Default ./data +# HTTP_PORT default 80; HTTPS_PORT default 443 (TCP and UDP) +# SITE_ADDRESS :80 (default), or a domain name for automatic HTTPS, which +# needs the default ports: certificate issuance and the +# HTTP/3 advertisement both assume 80 and 443 +# GIT_COMMIT the UI's cache buster; default the build time +# CHANNEL static (default), or beta, next, dev for a badge +# MQTT_BIND where the server's built-in broker is published. Default +# 127.0.0.1: it accepts anonymous clients, so set 0.0.0.0 +# only to let gateways on a network you trust publish to it. +# MQTT_PORT default 1883 +# SPLIT_NET the compose network's /24, as its first three octets. +# Default 172.30.83, which puts the web container at +# 172.30.83.200. Change it only if Docker reports that the +# pool overlaps another network, and update the server's +# trustedProxies to match. + +services: + corescope: + image: ${CORESCOPE_IMAGE:?set CORESCOPE_IMAGE to the server image of this checkout's version, e.g. ghcr.io/kpa-clawbot/corescope:edge on master or :vX.Y.Z on a release tag} + ports: + - "${MQTT_BIND:-127.0.0.1}:${MQTT_PORT:-1883}:1883" + volumes: + - ${DATA_DIR:-./data}:/app/data + environment: + - DISABLE_CADDY=true + - DISABLE_MOSQUITTO=${DISABLE_MOSQUITTO:-false} + restart: unless-stopped + healthcheck: + test: ["CMD", "wget", "-qO-", "http://localhost:3000/api/healthz"] + interval: 30s + timeout: 5s + retries: 3 + + web: + build: + context: . + dockerfile: Dockerfile.web + args: + GIT_COMMIT: ${GIT_COMMIT:-} + CHANNEL: ${CHANNEL:-static} + image: corescope-web:latest + ports: + - "${HTTP_PORT:-80}:80" + - "${HTTPS_PORT:-443}:443" + # HTTP/3: Caddy advertises it on 443 when SITE_ADDRESS is a domain. + - "${HTTPS_PORT:-443}:443/udp" + volumes: + - web-caddy-data:/data + environment: + - BACKEND=corescope:3000 + - SITE_ADDRESS=${SITE_ADDRESS:-:80} + networks: + default: + # The one address the server's trustedProxies lists; see networks. + ipv4_address: "${SPLIT_NET:-172.30.83}.200" + depends_on: + - corescope + restart: unless-stopped + +networks: + # A fixed subnet gives the web container a fixed address, so the server's + # webSocket.trustedProxies and userManagement.trustedProxies can list it + # alone (172.30.83.200 by default) and still match after a recreate. Never + # list the whole subnet: it holds the gateway address too, and a client + # that reaches a published port 3000 through Docker's proxy arrives from + # there, so its own X-Forwarded-For would be believed. + default: + ipam: + config: + - subnet: "${SPLIT_NET:-172.30.83}.0/24" + # Automatic addresses come from the lower half, so no container + # can take the web container's. + ip_range: "${SPLIT_NET:-172.30.83}.0/25" + +volumes: + # Caddy's TLS certificates when SITE_ADDRESS is a domain name. + web-caddy-data: diff --git a/docker/web/Caddyfile b/docker/web/Caddyfile new file mode 100644 index 000000000..7e259cc8f --- /dev/null +++ b/docker/web/Caddyfile @@ -0,0 +1,23 @@ +# The web container (Dockerfile.web): the static UI from /srv, with the API +# and the WebSocket forwarded to the CoreScope server, so both share this +# origin. BACKEND is the server's host:port; SITE_ADDRESS is ":80" for plain +# HTTP, or a domain name for automatic HTTPS. +# +# Caddy adds X-Forwarded-For. To keep the server's per-IP limits behind this +# proxy, list its address in webSocket.trustedProxies (and +# userManagement.trustedProxies) in the server's config.json. + +{$SITE_ADDRESS::80} { + encode zstd gzip + + @backend path /api/* /ws + reverse_proxy @backend {$BACKEND} + + # The same rules as deploy/static/_headers: these change on every deploy + # without a ?v= buster, so a browser must always revalidate them. + @nocache path / /index.html /area-map.html /geofilter-builder.html /geofilter-docs.html /deployment.js + header @nocache Cache-Control "no-cache, no-store, must-revalidate" + + root * /srv + file_server +} diff --git a/docs/deployment.md b/docs/deployment.md index 4c4d5c6e9..78309d63b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -5,6 +5,7 @@ Comprehensive guide to deploying and operating CoreScope. For a quick start, see ## Table of Contents - [System Requirements](#system-requirements) +- [Deployment modes](#deployment-modes) - [Docker Deployment](#docker-deployment) - [Configuration Reference](#configuration-reference) - [MQTT Setup](#mqtt-setup) @@ -33,6 +34,85 @@ CoreScope runs well on Raspberry Pi 4/5 (ARM64). The Go server uses ~300 MB RAM --- +## Deployment modes + +The UI is static files (`public/`) that call the server's API. The three modes +differ only in what serves those files. The server container is the same image +in all three, and it still serves the classic UI itself. + +| Mode | The UI is served by | API | Server CORS setting | Logins | +|---|---|---|---|---| +| [All-in-one container](#all-in-one-container) | the server container | same origin | none | yes | +| [Split containers](#split-containers) | a web container (`Dockerfile.web`) that forwards the API | same origin | none | yes | +| [Static host or CDN](#static-host-or-cdn) | Cloudflare Pages, a CDN or any web server | another origin | `CORS_ALLOWED_ORIGINS` | no, links to the classic UI | + +### All-in-one container + +The default, and what the rest of this guide describes: one image runs the +server, the ingestor and, optionally, Mosquitto and Caddy. The server serves the +UI from `/app/public` and the API on one origin. See +[Docker Deployment](#docker-deployment). + +### Split containers + +`docker-compose.split.yml` runs the server image unchanged next to a web +container built from `Dockerfile.web`. The web container is Caddy: it serves the +UI, packaged by `scripts/static/build.sh` when the image is built, and forwards +`/api/*` and `/ws` to the server. The browser sees one origin, so the server +needs no CORS setting. Logins work as on the classic UI when account +configuration uses the public web origin, as described below. + +```bash +CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge \ + docker compose -f docker-compose.split.yml up -d --build +``` + +| Variable | Default | | +|---|---|---| +| `HTTP_PORT`, `HTTPS_PORT` | `80`, `443` | Published by the web container; 443 over TCP and UDP (HTTP/3) | +| `SITE_ADDRESS` | `:80` | A domain name turns on Caddy's automatic HTTPS and HTTP/3. Keep the default ports then: certificate issuance and the HTTP/3 advertisement both assume 80 and 443 | +| `CORESCOPE_IMAGE` | none, required | The server image of the same version as the checkout the web image is built from: `:edge` on `master`, `:vX.Y.Z` on a release tag | +| `DATA_DIR` | `./data` | The server's data directory | +| `GIT_COMMIT` | the build time | The UI's cache buster | +| `CHANNEL` | `static` | `beta`, `next` or `dev` shows a badge | +| `MQTT_BIND`, `MQTT_PORT` | `127.0.0.1`, `1883` | Where the server's built-in broker is published. It accepts anonymous clients, so set `MQTT_BIND=0.0.0.0` only to let gateways on a network you trust publish to it | +| `SPLIT_NET` | `172.30.83` | The compose network's /24, as its first three octets; the web container is `.200` in it. Change it only if Docker reports that the pool overlaps another network, and update `trustedProxies` to match | + +- When `userManagement.enabled` is true, set `userManagement.publicBaseUrl` in + the server's config to the public web origin, including its scheme and port + (for example, `http://localhost:8080` for a web container published on port + 8080). Login and other state-changing requests compare the browser's `Origin` + or `Referer` with this configured origin; forwarding the public `Host` header + alone is not enough. This value also determines mail links. See + [account configuration](user-guide/accounts.md#2-configure). +- The web container finds the server through `BACKEND` (`corescope:3000` in the + compose file). Port 3000 stays inside the compose network, and the server + still serves everything there, the classic UI included; publish it if you want + to reach that directly. +- The web image is built from your checkout, so keep the checkout and + `CORESCOPE_IMAGE` on the same version: a newer UI may call endpoints an older + server lacks. To update only the UI, rebuild the web container: + `docker compose -f docker-compose.split.yml up -d --build web`. +- Behind the web container, as behind the all-in-one image's Caddy, every + request reaches the server from the proxy's address, so per-IP limits are off + until `webSocket.trustedProxies` and `userManagement.trustedProxies` list it. + The compose file fixes that address at `172.30.83.200`: list it alone. Never + list the compose subnet. It also holds the gateway address, and a client that + reaches a published port 3000 through Docker's proxy (from the host itself or + over IPv6, for example) arrives from there, so its own `X-Forwarded-For` + would be believed. + +### Static host or CDN + +`make web` (or `scripts/static/build.sh`) writes the anonymous build to +`dist/web` for Cloudflare Pages or any static host. It calls the server +cross-origin, so the server lists the UI's origin in `CORS_ALLOWED_ORIGINS`. +It sends no cookies; logins and admin pages link to the classic UI on the +server. Setup, previews, server settings and rollback: +[deploy/static/README.md](../deploy/static/README.md). + +--- + ## Docker Deployment ### Quick Start (one command) diff --git a/public/account.js b/public/account.js index 9345dbf3c..e8ed60634 100644 --- a/public/account.js +++ b/public/account.js @@ -119,7 +119,7 @@ (window.CSSettingsSync ? '

Settings sync

' : '') + '

My data

' + '' + - '' + + '' + '

Delete account