feat(webapp): the device-routing rules as pure functions, tested through Node
One block of sfm_webapp.html (/* <device-routing> */) holds every rule that decides where a /device/ request goes or whether a series-specific control is live: seriesFromSerial, unitQuery, deviceUrl, confirmedSeries, controlsFor, changeSummary, downloadSummary. No DOM, no fetch, so the tests run it in Node. The safety rules it pins: a control follows the unit's own /device/info answer, never a typed serial alone, and stops counting when the serial is edited; Diagnostics only for a confirmed Series 3, Hang up only for Series 4; config and call-home writes off for both series until phases 4-5. Also a test that the page's inline scripts parse together (shared global scope). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
1cb11abcef
commit
e3717706f8
2 files changed
+273
No files matched your search
@@ -1438,6 +1438,108 @@
|
||||
|
||||
<!-- ── Script ─────────────────────────────────────────────────────── -->
|
||||
<script>
|
||||
/* <device-routing> */
|
||||
// Every rule that decides where a /device/ request goes, or whether a
|
||||
// series-specific control is live. Pure functions -- no DOM, no fetch -- so
|
||||
// tests/test_webapp_device_routing.py runs them in Node (phase 1c, 2026-10-29).
|
||||
// A control follows the unit's own /device/info answer, never a typed serial
|
||||
// alone: 0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate.
|
||||
|
||||
const SERIES_BY_PREFIX = [['UM', 4], ['BE', 3], ['BA', 3]]; // sfm/device_access/series.py
|
||||
|
||||
function normSerial(serial) { return String(serial || '').trim().toUpperCase(); }
|
||||
|
||||
function seriesFromSerial(serial) {
|
||||
const s = normSerial(serial);
|
||||
for (const [prefix, series] of SERIES_BY_PREFIX) {
|
||||
if (s.startsWith(prefix) && s.length > prefix.length) return series;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function unitQuery(unit) {
|
||||
const parts = [];
|
||||
const s = normSerial(unit.serial);
|
||||
if (s) parts.push(`serial=${encodeURIComponent(s)}`);
|
||||
parts.push(`host=${encodeURIComponent(unit.host || '')}`);
|
||||
parts.push(`tcp_port=${encodeURIComponent(unit.tcpPort)}`);
|
||||
return parts.join('&');
|
||||
}
|
||||
|
||||
// action -> [method, path, needs a serial (no legacy equivalent)]
|
||||
const DEVICE_ROUTES = {
|
||||
info: ['GET', '/device/info', false],
|
||||
status: ['GET', '/device/monitor/status', false],
|
||||
settings: ['GET', '/device/settings', true],
|
||||
events: ['GET', '/device/events', false],
|
||||
download: ['POST', '/device/events/download', true],
|
||||
start: ['POST', '/device/monitor/start', false],
|
||||
stop: ['POST', '/device/monitor/stop', false],
|
||||
hangup: ['POST', '/device/hangup', true],
|
||||
storage_range: ['GET', '/device/events/storage_range', false],
|
||||
index: ['GET', '/device/events/index', false],
|
||||
erase: ['POST', '/device/events/erase', false],
|
||||
rescue: ['POST', '/device/rescue', false],
|
||||
blind_stop: ['POST', '/device/stop_monitoring_blind', false],
|
||||
slow_drip: ['POST', '/device/stop_monitoring_slow_drip', false],
|
||||
call_home_read: ['GET', '/device/call_home', false],
|
||||
call_home_write: ['POST', '/device/call_home', false],
|
||||
config_write: ['POST', '/device/config', false],
|
||||
};
|
||||
|
||||
function deviceUrl(action, unit, params = {}) {
|
||||
const route = DEVICE_ROUTES[action];
|
||||
if (!route) throw new Error(`unknown device action: ${action}`);
|
||||
const [method, path, needsSerial] = route;
|
||||
if (needsSerial && !normSerial(unit.serial)) return null;
|
||||
// Hang-up releases whatever line is held at the address: no serial.
|
||||
let query = action === 'hangup' ? unitQuery({ ...unit, serial: '' }) : unitQuery(unit);
|
||||
for (const [k, v] of Object.entries(params)) query += `&${k}=${encodeURIComponent(v)}`;
|
||||
return { method, path: `${path}?${query}` };
|
||||
}
|
||||
|
||||
function confirmedSeries(unit) {
|
||||
const c = unit.confirmed;
|
||||
if (!c) return null;
|
||||
const typed = normSerial(unit.serial);
|
||||
if (!typed) return c.series; // a legacy identify, no serial typed
|
||||
return typed === normSerial(c.serial) ? c.series : null;
|
||||
}
|
||||
|
||||
function controlsFor(unit) {
|
||||
const series = confirmedSeries(unit);
|
||||
const serialMode = Boolean(normSerial(unit.serial));
|
||||
return {
|
||||
startStop: serialMode && (series === 3 || series === 4),
|
||||
hangup: series === 4,
|
||||
diagnostics: series === 3,
|
||||
callHomeRead: series === 3,
|
||||
configWrite: false,
|
||||
callHomeWrite: false,
|
||||
reasons: { configWrite: 'Coming in phase 5 (#46)', callHomeWrite: 'Coming in phase 4' },
|
||||
};
|
||||
}
|
||||
|
||||
function changeSummary(body) {
|
||||
const id8 = String(body.audit_id || '').slice(0, 8);
|
||||
if (body.outcome === 'dry_run') {
|
||||
const subs = ((body.plan || {}).steps || []).map(s => s.sub).join(', ');
|
||||
return `${body.action}: dry run — would send ${subs}`;
|
||||
}
|
||||
if (body.outcome === 'skipped') return `${body.action}: already ${body.state_before} — nothing sent`;
|
||||
if (body.outcome === 'sent' && body.verified === 'ok') {
|
||||
return `${body.action}: confirmed — ${body.state_before} → ${body.state_after} (audit ${id8})`;
|
||||
}
|
||||
return `${body.action}: ${body.outcome}, ${body.verified} (audit ${id8})`;
|
||||
}
|
||||
|
||||
function downloadSummary(body) {
|
||||
if (body.inserted === false) return `already stored — ${body.stored_filename}`;
|
||||
return `stored ${body.stored_filename}, ${body.filesize} bytes, check: ${(body.detail || {}).check}`;
|
||||
}
|
||||
/* </device-routing> */
|
||||
</script>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""The SFM page's device-routing rules, run through Node (phase 1c).
|
||||
|
||||
sfm/sfm_webapp.html keeps every rule that decides where a request goes, or
|
||||
whether a series-specific control is live, in one block of pure functions
|
||||
between `/* <device-routing> */` and `/* </device-routing> */`. This file
|
||||
extracts that block and runs it in Node -- no browser, no DOM.
|
||||
|
||||
The safety rules it pins (agreed with Brian, 2026-10-28):
|
||||
* a series-specific control follows the unit's own /device/info answer, never
|
||||
a typed serial alone, and stops counting the moment the serial is edited;
|
||||
* config and call-home writes stay off for both series until phases 4-5.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PAGE = Path(__file__).resolve().parent.parent / "sfm" / "sfm_webapp.html"
|
||||
NODE = shutil.which("node")
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="node is not installed; the page-logic tests need it")
|
||||
|
||||
EXPORTS = ["seriesFromSerial", "unitQuery", "deviceUrl", "confirmedSeries", "controlsFor",
|
||||
"changeSummary", "downloadSummary"]
|
||||
|
||||
|
||||
def _block() -> str:
|
||||
m = re.search(r"/\* <device-routing> \*/(.*?)/\* </device-routing> \*/", PAGE.read_text(), re.S)
|
||||
assert m, "no device-routing block in sfm_webapp.html"
|
||||
return m.group(1)
|
||||
|
||||
|
||||
def run(*cases):
|
||||
"""Each case is (function name, [args]); returns each result, or {'throws': msg}."""
|
||||
driver = _block() + """
|
||||
const __fns = {%s};
|
||||
const __cases = JSON.parse(require('fs').readFileSync(0, 'utf8'));
|
||||
process.stdout.write(JSON.stringify(__cases.map(([fn, args]) => {
|
||||
try { const r = __fns[fn](...args); return r === undefined ? null : r; }
|
||||
catch (e) { return {throws: String(e.message || e)}; }
|
||||
})));
|
||||
""" % ", ".join(EXPORTS)
|
||||
out = subprocess.run([NODE, "-e", driver], input=json.dumps(cases), capture_output=True,
|
||||
text=True, timeout=30)
|
||||
assert out.returncode == 0, out.stderr
|
||||
return json.loads(out.stdout)
|
||||
|
||||
|
||||
S3 = {"serial": "BE9441", "host": "h", "tcpPort": 9034}
|
||||
S4 = {"serial": "UM20147", "host": "h", "tcpPort": 9034}
|
||||
BLANK = {"serial": "", "host": "h", "tcpPort": 9034}
|
||||
|
||||
|
||||
def test_series_from_serial():
|
||||
assert run(["seriesFromSerial", ["UM20147"]], ["seriesFromSerial", [" be9441 "]],
|
||||
["seriesFromSerial", ["BA123"]], ["seriesFromSerial", ["BE"]],
|
||||
["seriesFromSerial", ["XX1"]], ["seriesFromSerial", [""]]) == [4, 3, 3, None, None, None]
|
||||
|
||||
|
||||
def test_unit_query():
|
||||
assert run(["unitQuery", [{"serial": " be9441 ", "host": "h", "tcpPort": 9034}]],
|
||||
["unitQuery", [BLANK]],
|
||||
["unitQuery", [{"serial": "", "host": "a&b", "tcpPort": 1}]]) == [
|
||||
"serial=BE9441&host=h&tcp_port=9034", "host=h&tcp_port=9034", "host=a%26b&tcp_port=1"]
|
||||
|
||||
|
||||
def test_device_url():
|
||||
r = run(["deviceUrl", ["info", S3]], ["deviceUrl", ["status", S4]],
|
||||
["deviceUrl", ["hangup", S4]], ["deviceUrl", ["settings", BLANK]],
|
||||
["deviceUrl", ["download", S3, {"event_id": "BE9441:01110000:20261026"}]],
|
||||
["deviceUrl", ["start", S4]], ["deviceUrl", ["stop", S3]],
|
||||
["deviceUrl", ["erase", S3]], ["deviceUrl", ["call_home_read", BLANK]],
|
||||
["deviceUrl", ["config_write", S3]], ["deviceUrl", ["nonsense", S3]],
|
||||
["deviceUrl", ["download", BLANK, {"event_id": "x"}]], ["deviceUrl", ["hangup", BLANK]])
|
||||
assert r[0] == {"method": "GET", "path": "/device/info?serial=BE9441&host=h&tcp_port=9034"}
|
||||
assert r[1] == {"method": "GET", "path": "/device/monitor/status?serial=UM20147&host=h&tcp_port=9034"}
|
||||
assert r[2] == {"method": "POST", "path": "/device/hangup?host=h&tcp_port=9034"}
|
||||
assert r[3] is None
|
||||
assert r[4] == {"method": "POST", "path": "/device/events/download?serial=BE9441&host=h&tcp_port=9034"
|
||||
"&event_id=BE9441%3A01110000%3A20261026"}
|
||||
assert r[5] == {"method": "POST", "path": "/device/monitor/start?serial=UM20147&host=h&tcp_port=9034"}
|
||||
assert r[6] == {"method": "POST", "path": "/device/monitor/stop?serial=BE9441&host=h&tcp_port=9034"}
|
||||
assert r[7] == {"method": "POST", "path": "/device/events/erase?serial=BE9441&host=h&tcp_port=9034"}
|
||||
assert r[8] == {"method": "GET", "path": "/device/call_home?host=h&tcp_port=9034"}
|
||||
assert r[9] == {"method": "POST", "path": "/device/config?serial=BE9441&host=h&tcp_port=9034"}
|
||||
assert "throws" in r[10]
|
||||
assert r[11] is None and r[12] is None
|
||||
|
||||
|
||||
def _with(unit, confirmed):
|
||||
return {**unit, "confirmed": confirmed}
|
||||
|
||||
|
||||
def test_controls_typed_serial_is_not_confirmation():
|
||||
c = run(["controlsFor", [_with(S3, None)]])[0]
|
||||
assert c["diagnostics"] is False and c["startStop"] is False and c["hangup"] is False
|
||||
|
||||
|
||||
def test_controls_confirmed_series3():
|
||||
c = run(["controlsFor", [_with(S3, {"serial": "BE9441", "series": 3})]])[0]
|
||||
assert (c["diagnostics"], c["callHomeRead"], c["startStop"], c["hangup"]) == (True, True, True, False)
|
||||
|
||||
|
||||
def test_controls_confirmed_series4():
|
||||
c = run(["controlsFor", [_with(S4, {"serial": "UM20147", "series": 4})]])[0]
|
||||
assert (c["hangup"], c["startStop"], c["diagnostics"], c["callHomeRead"]) == (True, True, False, False)
|
||||
|
||||
|
||||
def test_controls_confirmation_drops_when_the_serial_changes():
|
||||
unit = {**S3, "serial": "BE9442", "confirmed": {"serial": "BE9441", "series": 3}}
|
||||
c = run(["controlsFor", [unit]], ["confirmedSeries", [unit]])
|
||||
assert c[1] is None
|
||||
assert not any(c[0][k] for k in ("startStop", "hangup", "diagnostics", "callHomeRead"))
|
||||
|
||||
|
||||
def test_controls_a_legacy_identify_confirms_without_a_typed_serial():
|
||||
unit = _with(BLANK, {"serial": "BE9441", "series": 3})
|
||||
c, s = run(["controlsFor", [unit]], ["confirmedSeries", [unit]])
|
||||
assert s == 3 and c["diagnostics"] is True and c["startStop"] is False # start/stop needs a serial
|
||||
|
||||
|
||||
def test_controls_writes_wait_for_phases_4_and_5():
|
||||
for unit in (_with(S3, {"serial": "BE9441", "series": 3}), _with(S4, {"serial": "UM20147", "series": 4})):
|
||||
c = run(["controlsFor", [unit]])[0]
|
||||
assert c["configWrite"] is False and c["callHomeWrite"] is False
|
||||
assert c["reasons"] == {"configWrite": "Coming in phase 5 (#46)", "callHomeWrite": "Coming in phase 4"}
|
||||
|
||||
|
||||
def test_change_summary():
|
||||
base = {"action": "start monitoring", "state_before": "idle", "state_after": "monitoring",
|
||||
"audit_id": "cb540970-5e17-415d-b902-4b8343186494",
|
||||
"plan": {"steps": [{"sub": "0x96"}]}}
|
||||
r = run(["changeSummary", [{**base, "outcome": "dry_run", "verified": "not_checked"}]],
|
||||
["changeSummary", [{**base, "outcome": "skipped", "verified": "not_checked",
|
||||
"state_before": "monitoring"}]],
|
||||
["changeSummary", [{**base, "outcome": "sent", "verified": "ok"}]],
|
||||
["changeSummary", [{**base, "outcome": "sent", "verified": "mismatch", "state_after": "idle"}]],
|
||||
["changeSummary", [{**base, "outcome": "failed", "verified": "not_checked"}]])
|
||||
assert r == ["start monitoring: dry run — would send 0x96",
|
||||
"start monitoring: already monitoring — nothing sent",
|
||||
"start monitoring: confirmed — idle → monitoring (audit cb540970)",
|
||||
"start monitoring: sent, mismatch (audit cb540970)",
|
||||
"start monitoring: failed, not_checked (audit cb540970)"]
|
||||
|
||||
|
||||
def test_download_summary():
|
||||
r = run(["downloadSummary", [{"inserted": True, "stored_filename": "K441LTON.900", "filesize": 71106,
|
||||
"detail": {"check": "a histogram: stored unverified"}}]],
|
||||
["downloadSummary", [{"inserted": False, "stored_filename": "K441LTOK.R10", "filesize": 60290,
|
||||
"detail": {"already_stored": True}}]])
|
||||
assert r == ["stored K441LTON.900, 71106 bytes, check: a histogram: stored unverified",
|
||||
"already stored — K441LTOK.R10"]
|
||||
|
||||
|
||||
def test_the_block_touches_no_dom():
|
||||
b = _block()
|
||||
assert "document" not in b and "fetch(" not in b and "window" not in b
|
||||
|
||||
|
||||
def test_the_page_scripts_parse_together(tmp_path):
|
||||
"""The page's inline scripts share one global scope: a syntax slip, or a name
|
||||
declared in both, breaks the whole page. Joined, they must pass node --check."""
|
||||
scripts = re.findall(r"<script>(.*?)</script>", PAGE.read_text(), re.S)
|
||||
js = tmp_path / "page.js"
|
||||
js.write_text("\n;\n".join(scripts))
|
||||
r = subprocess.run([NODE, "--check", str(js)], capture_output=True, text=True, timeout=30)
|
||||
assert r.returncode == 0, r.stderr
|
||||
Reference in new issue
Block a user