screentinker/brightsign/server/node-server.html
screentinker 9a1a82a100
Run the ScreenTinker server on the player it serves (#288)
* Make a BrightSign say what it is running, and what it is plugged into

A panel on a wall could not answer three questions an operator asks first:
which version am I, which page am I running, and which screen is that. All
three had answers already travelling over the socket; nothing was reading them.

VERSION. device_info.app_version was the literal '1.1.0-web' for every web
player, BrightSign included — the same string as PLAYER_VERSION, which already
travels separately as client_version. So the column carried no information at
all: a panel provisioned this morning and one running a year-old host reported
identically. app_version is now the ON-DEVICE host package, the artifact OTA
replaces and the only one here that can be stale, and PLAYER_VERSION is stamped
at serve time from VERSION rather than being a constant nobody bumped for the
whole 1.x line. No '-web' suffix: client_version is only compared for equality
today, but X.Y.Z-web is a semver PRERELEASE that sorts BELOW X.Y.Z, and this
project has been bitten by exactly that before.

The host version arrives asynchronously and can land after the page registers,
so register sends what it has and the heartbeat corrects the record — which also
catches the version changing under a live page, which is what a self-update is.

THE CARD SHOWED FOR NOBODY. The Info tab's version card sat inside the block
gated on android_version && !startsWith('Web/'). A BrightSign registers as
"Web/<ua>", so the panel that most needed a version never displayed one.

THE PAD THAT COULD NOT BE CLICKED. System View was gated on tier === 2. tier is
an Android device-owner concept, NOT NULL DEFAULT 0, written only by the APK —
so a BrightSign or Tizen panel sat at 0 forever and rendered HOME, BACK, POWER,
the D-pad and OK permanently pointer-events:none, for keys those players
genuinely handle. Greying an Android gate over a working control is the "button
that cannot work" the capability system exists to prevent, inverted. Only
Recents (KEYCODE_APP_SWITCH) and Settings are truly Android-only; those are now
the only things hidden.

THE PACKAGE POINTED AT THE WRONG SERVER. autorun.zip carried the committed
default, so a player self-updating from alpha or a self-hosted box was handed a
config pointing at screentinker.com — which surfaces as a pairing bug, miles
from the packaging code that caused it. It is now stamped with the URL it was
fetched from. The bytes therefore vary per origin, so the cache is keyed by
origin and BOTH routes derive it identically: the manifest checksum and the
served bytes must come from one buffer or every player downloads, fails
verification and retries forever.

EDID. getEdidIdentity() answers seven questions and cannot answer any others —
manufacturer, EDID version, physical size, gamma and the mode lists exist only
in the raw block, which getEdid() returns as 2048 bytes. The player ships those
on the register (identity, not a reading: it changes when someone swaps the
screen) and the SERVER parses them. That split is the point: a new field becomes
a server deploy instead of a bridge update behind a 4h CDN plus an OTA for the
host. Verified against real hardware — an XT245 with a CX101 decodes to RTK /
0x1010 / serial 1 / 2020w26 / 22x13cm, preferred 1920x1200@62, matching the
player's own DWS field for field. The odd-looking 62 is right: 168.5MHz over
2200 x 1245 is 61.5Hz, and rounding it to a nicer 60 would contradict the panel.

Also corrects two comments that had outgrown their reasoning: the BrightSign
capability baseline still explained its exclusions with "a canvas cannot read
the video plane", which native capture made obsolete, and player-parity.md
claimed the bridge is "always current" when a zone-wide Cloudflare Browser Cache
TTL had been rewriting its no-cache to max-age=14400 for months.

Every new guard is mutation-tested — the fix was reverted in the source and each
test confirmed to fail. 1676 -> 1714 tests, all green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014kfhrUPit5MCqxeTQyqr56

* Run the ScreenTinker server on the player it serves

A BrightSign XT245 now downloads, installs and runs the server itself, with
the display showing what it is doing until it is up.

WHY IT NEEDED A NEW SHAPE

BrightSignOS cannot open a large autorun.zip. The 73MB build failed at boot
with "ZipArchive error at line 91", and the OS renamed it autorun.zip_invalid
- which is how a device that had already unpacked once came back up with no
autorun at all. The identical package cut to 32KB and five files boots fine;
paths (182 chars) and depth (8) are unremarkable, so the limit is in the
boot-time reader, not the archive. BrightSign's own notes acknowledge package
size as a problem and point at webpack; that route needs the dynamic requires
in scripts/ removed first, so instead autorun.zip carries only what starts the
process and the payload arrives over HTTP into a Node that has no such limit.
The payload can also be updated without re-provisioning the device.

WHY roNodeJs AND NOT THE WIDGET

The first version ran the server inside an roHtmlWidget with nodejs_enabled.
That is a Node context inside an Electron renderer, and it is not Node. Four
separate boot failures came out of it, each invisible to a local test because
a local test runs on real Node:

  - shebangs are not stripped, so any `#!/usr/bin/env node` file dies with
    "Failed to construct 'ContextifyScript': Invalid or unexpected token".
    Note it names no token - "#" is not one. An ESM file compiled as CJS says
    "Unexpected token 'export'" instead, which is how the two are told apart.
  - require() of an ESM-only package is unsupported, which plain Node 24
    handles. uuid 14 is ESM-only and 21 files import it.
  - setInterval is the DOM's and returns a NUMBER, so setInterval(...).unref()
    throws. Two call sites were unguarded; sixteen more were written
    defensively and had been silently not unreffing.
  - worker_threads cannot create a thread at all.

BrightSign's dev-cookbook is explicit: roNodeJs "for long running processes
like ... running a web server", roHtmlWidget "for browser-based apps". Their
cra-template examples do exactly this - server in roNodeJs, widget pointed at
localhost. It also fixes the lifecycle problem that was the original argument
against a server on this hardware: in a widget the server dies with the page,
taking an open SQLite WAL with it.

The shims for the first three are kept in the packager for now rather than
removed in the same change that moves the container, so that if something
breaks it is the move and not four simultaneous removals.

CHANGES THAT ARE NOT BRIGHTSIGN-SPECIFIC

  db/database.js, routes/status.js  fs.copyFileSync does not merely copy
    bytes: it fchmods the destination to match the source. exFAT has no
    permission bits, so the pre-migration snapshot failed with EPERM and the
    failure path called process.exit(1) - which inside a widget also killed
    the page, leaving a black screen and no diagnostic. The guard was right;
    the copy was wrong. lib/fsutil.js copies without touching mode.

  db/wal-checkpointer.js  the module already degraded correctly when its
    worker died or could not be respawned, but the FIRST spawn was not
    wrapped, so a host that cannot make threads lost the whole server rather
    than falling back to inline autocheckpoint.

  db/sqlite-compat.js  a better-sqlite3 facade over node:sqlite. With it the
    bundle contains no native code at all, which is what lets an x86_64
    laptop build a package for an aarch64 player. 1719/1719 tests pass on
    Node 24 through this shim.

The packager refuses to build if a source file is untracked (git ls-files
decides what ships, and lib/fsutil.js reached a player without shipping
alongside the code that required it), if any .node binary is present, if a
shebang survives, or if a database, upload, cert or .env is staged - the first
build of this package swept up a real 33MB database and 105MB of uploads.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014kfhrUPit5MCqxeTQyqr56

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Dan Walters <dan.walters@bytetinker.net>
2026-08-18 15:16:09 -05:00

144 lines
6.7 KiB
HTML

<!doctype html>
<!--
ScreenTinker server diagnostics, displayed on the player.
THE SERVER IS NOT IN THIS PAGE. It runs as a separate roNodeJs process; this is only the screen.
It used to host the server, and that was a mistake worth recording. A Node context inside an
Electron renderer is not Node: shebangs are not stripped, require(ESM) is unsupported,
setInterval is the DOM's and returns a number rather than a Timeout, and worker_threads cannot
create a thread at all. Four separate boot failures, each invisible to a local test because a
local test runs on real Node. BrightSign's own guidance is explicit - roNodeJs for "a long
running process like ... running a web server", roHtmlWidget for "browser-based apps".
The other half of that mistake was lifecycle: a server inside the page dies with the page, and
takes an open SQLite WAL with it. roNodeJs runs in the background uninterrupted.
So this page does one job - show what the server process reports, including while it is still
downloading itself - and it does that over HTTP because the two are no longer in one process.
-->
<meta charset="utf-8">
<title>ScreenTinker server</title>
<style>
html, body { margin: 0; height: 100%; background: #0b0f1a; color: #e6edf7;
font: 22px/1.5 ui-monospace, "DejaVu Sans Mono", monospace; }
.wrap { padding: 40px 56px; }
h1 { font-size: 34px; margin: 0 0 4px; letter-spacing: .5px; }
.sub { color: #7d8da5; margin-bottom: 28px; }
.url { font-size: 44px; color: #4ade80; margin: 18px 0 26px; word-break: break-all; }
table { border-collapse: collapse; margin-bottom: 26px; }
td { padding: 3px 26px 3px 0; }
td.k { color: #7d8da5; }
.bad { color: #f87171; }
/* Not green: green reads as "ready", and it is not ready. */
.url.pending { color: #7d8da5; }
#log { background: #060911; border: 1px solid #1e2a3d; border-radius: 6px; padding: 14px 18px;
font-size: 17px; line-height: 1.45; height: 34vh; overflow: hidden; color: #9fb3cd;
white-space: pre-wrap; }
</style>
<div class="wrap">
<h1>ScreenTinker server</h1>
<div class="sub" id="sub">starting&hellip;</div>
<div class="url" id="url">&mdash;</div>
<table>
<tr><td class="k">uptime</td><td id="uptime">&mdash;</td>
<td class="k">memory</td><td id="mem">&mdash;</td></tr>
<tr><td class="k">disk</td><td id="disk">&mdash;</td>
<td class="k">database</td><td id="db">&mdash;</td></tr>
<tr><td class="k">node</td><td id="node">&mdash;</td>
<td class="k">load</td><td id="load">&mdash;</td></tr>
</table>
<div id="log">waiting for the server&hellip;</div>
</div>
<script>
// Plain browser JavaScript. This page no longer needs nodejs_enabled: it does not require()
// anything, it just polls the server process. One less hybrid context to reason about.
(function () {
var el = function (id) { return document.getElementById(id); };
function fail(what, e) {
el('sub').innerHTML = '<span class="bad">' + what + '</span>';
el('log').textContent = String(e && e.stack ? e.stack : e);
}
/*
* The server runs in a DIFFERENT PROCESS now (roNodeJs), so this page cannot require() it.
*
* It used to: both halves lived inside one roHtmlWidget, and the page pulled status straight out
* of the module. Moving the server to roNodeJs is what makes it survive this page reloading, and
* gives it a real Node runtime instead of a renderer - at the cost that the two now have to talk.
* They talk over HTTP on a small port that the wrapper binds immediately, before the payload is
* even downloaded, because "downloading" and "failed to start" are exactly the states this screen
* exists to show.
*/
var STATUS_URL = 'http://127.0.0.1:8182/';
var last = null;
var lastError = null;
function poll() {
// XHR rather than fetch: this page is loaded from file://, and XHR's failure modes here are
// easier to report than a rejected promise with an opaque TypeError.
var xhr = new XMLHttpRequest();
xhr.open('GET', STATUS_URL + '?t=' + Date.now(), true);
xhr.timeout = 4000;
xhr.onload = function () {
try { last = JSON.parse(xhr.responseText); lastError = null; }
catch (e) { lastError = 'bad status payload'; }
paint();
};
xhr.onerror = function () { lastError = 'no answer from the server process'; paint(); };
xhr.ontimeout = function () { lastError = 'status request timed out'; paint(); };
try { xhr.send(); } catch (e) { lastError = String(e && e.message ? e.message : e); paint(); }
}
function paint() {
var s = last;
if (!s) {
// Before the first successful poll there is genuinely nothing to report. Say that, rather
// than paint zeros that look like a running server with no traffic.
el('sub').textContent = lastError ? ('waiting for the server process \u2014 ' + lastError)
: 'starting\u2026';
el('sub').className = 'sub';
el('url').textContent = 'starting\u2026';
el('url').className = 'url pending';
return;
}
// While the payload is coming down there is no server yet and nothing to be alarmed about, so
// say what is happening rather than showing a bare 'starting...' for the length of a 71MB fetch.
var inst = s.install || {};
var busy = inst.phase && inst.phase !== 'installed' && inst.phase !== 'idle' && inst.phase !== 'failed';
el('sub').className = 'sub' + (s.fatal ? ' bad' : '');
el('sub').textContent = s.fatal ? 'FAILED'
: busy ? (inst.phase + (inst.pct !== null && inst.pct !== undefined ? ' ' + inst.pct + '%' : '')
+ (inst.detail ? ' \u2014 ' + inst.detail : ''))
: 'running';
// Only show the address once something answers on it - see `serving` in bs-server-boot.js.
// Until then say what is actually happening, so nobody types in a URL that cannot work.
if (s.serving && s.ip) {
el('url').textContent = 'http://' + s.ip + ':' + s.port;
el('url').className = 'url';
} else {
el('url').textContent = !s.ip ? 'no network'
: busy ? 'installing\u2026'
: s.fatal ? 'not running' : 'starting\u2026';
el('url').className = 'url pending';
}
el('uptime').textContent = s.uptimeSec + 's';
el('mem').textContent = 'rss ' + s.rssMb + 'MB / free ' + s.freeMemMb + 'MB';
el('disk').textContent = s.disk
? (s.disk.freeMb + 'MB free of ' + s.disk.totalMb + 'MB (' + s.disk.usedPct + '% used)')
: 'n/a';
el('db').textContent = (s.dbMb === null || s.dbMb === undefined) ? 'n/a' : (s.dbMb + 'MB');
el('node').textContent = s.node;
el('load').textContent = s.loadAvg && s.loadAvg.length ? s.loadAvg[0] : 'n/a';
el('log').textContent = (s.log || []).map(function (l) { return l.m; }).join('\n');
}
paint();
poll();
setInterval(poll, 2000);
})();
</script>