Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83ad66fd9a | ||
|
|
de8dc0f15c |
@@ -1,197 +0,0 @@
|
||||
name: CI
|
||||
|
||||
# Signage builds, tests, and runs only inside an Ekklesia workspace, so every job first assembles it
|
||||
# into the platform commit pinned in ci/platform.env (ci/assemble.sh) and installs that workspace
|
||||
# with --frozen-lockfile from ci/pnpm-lock.yaml.
|
||||
#
|
||||
# The same trust rules as the platform's own CI (docs/development/security.md there):
|
||||
# * every action is pinned by a full commit SHA;
|
||||
# * every checkout sets `persist-credentials: false`, and nothing in this workflow pushes;
|
||||
# * no repository, organization, or instance secret is referenced;
|
||||
# * there is no `pull_request_target`;
|
||||
# * the self-hosted runner executes trusted, reviewed code only.
|
||||
#
|
||||
# The server is Gitea 1.24, which ignores `permissions`, `concurrency`, and `timeout-minutes`
|
||||
# (https://docs.gitea.com/1.24/usage/actions/comparison). They are declared so the workflow is already
|
||||
# correct on a release that honours them; on 1.24 they bound nothing, and `permissions` does not
|
||||
# restrict the job token.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
working-directory: build/workspace
|
||||
run: pnpm --filter @ekklesia/signage lint
|
||||
|
||||
typecheck:
|
||||
name: typecheck
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build the platform packages Signage depends on
|
||||
working-directory: build/workspace
|
||||
run: pnpm exec turbo run build --filter='@ekklesia/signage^...'
|
||||
|
||||
- name: Typecheck the server, browser, and browser-test projects
|
||||
working-directory: build/workspace
|
||||
run: pnpm --filter @ekklesia/signage typecheck
|
||||
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build the platform packages Signage depends on
|
||||
working-directory: build/workspace
|
||||
run: pnpm exec turbo run build --filter='@ekklesia/signage^...'
|
||||
|
||||
- name: Unit, browser, and display contract tests
|
||||
working-directory: build/workspace
|
||||
run: pnpm --filter @ekklesia/signage test
|
||||
|
||||
build:
|
||||
name: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
# The same gates the platform's image build runs against exactly this module set: its boundary
|
||||
# rules (which apply to modules), the manifest, and the migrations.
|
||||
- name: Platform gates (boundaries, module manifest, migrations)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
pnpm boundaries
|
||||
pnpm modules:validate
|
||||
pnpm migrations:validate
|
||||
|
||||
- name: Build Signage and the platform it depends on
|
||||
working-directory: build/workspace
|
||||
run: pnpm exec turbo run build --filter='@ekklesia/signage...'
|
||||
|
||||
# Signage inside Ekklesia, end to end, in a real browser: the platform's own Dockerfile builds the
|
||||
# deployment image with Signage in it, and the platform's split-topology deployment smoke runs
|
||||
# against it, pairing a kiosk display and running the scenarios in ci/display-scenarios. A
|
||||
# disposable database and object store with generated secrets; nothing is pushed or logged in to.
|
||||
integration:
|
||||
name: integration
|
||||
needs:
|
||||
- test
|
||||
- build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
DOCKER_BUILDKIT: "1"
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Build the image and run the display scenarios
|
||||
run: bash ci/integration.sh
|
||||
@@ -4,4 +4,3 @@ dist/
|
||||
coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
build/
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Assembles Signage into the Ekklesia platform it is tested against: the platform at the commit pinned
|
||||
# in ci/platform.env, this checkout at modules/signage, and ci/pnpm-lock.yaml as the workspace
|
||||
# lockfile. Signage cannot build or run outside an Ekklesia workspace, so every CI job starts here.
|
||||
#
|
||||
# bash ci/assemble.sh [--allow-missing-lock] [output directory]
|
||||
#
|
||||
# The output directory (default build/workspace) is deleted and recreated. The platform is fetched
|
||||
# by its `main` branch and the pinned commit must be on it, so CI only ever runs reviewed platform
|
||||
# code; the checkout is then by commit, so nothing after it depends on a ref the network can move.
|
||||
# Every .git directory is removed afterwards.
|
||||
#
|
||||
# --allow-missing-lock keeps the platform's own lockfile. Only ci/update-lock.sh uses it.
|
||||
set -Eeuo pipefail
|
||||
|
||||
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
allow_missing_lock=0
|
||||
if [[ "${1:-}" == "--allow-missing-lock" ]]; then
|
||||
allow_missing_lock=1
|
||||
shift
|
||||
fi
|
||||
out="${1:-$root/build/workspace}"
|
||||
|
||||
fail() {
|
||||
echo "assemble: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
for command in git tar; do
|
||||
command -v "$command" >/dev/null || fail "$command is required."
|
||||
done
|
||||
|
||||
# Read the two pins without sourcing the file: it is data, not a script.
|
||||
pin() {
|
||||
local value
|
||||
value="$(sed -n "s/^$1=//p" "$root/ci/platform.env")"
|
||||
[[ -n "$value" ]] || fail "ci/platform.env has no $1."
|
||||
printf '%s' "$value"
|
||||
}
|
||||
repository="$(pin EKKLESIA_PLATFORM_REPOSITORY)"
|
||||
commit="$(pin EKKLESIA_PLATFORM_COMMIT)"
|
||||
[[ "$commit" =~ ^[0-9a-f]{40}$ ]] || fail "EKKLESIA_PLATFORM_COMMIT must be a full commit SHA."
|
||||
|
||||
rm -rf "$out"
|
||||
mkdir -p "$(dirname -- "$out")"
|
||||
git init --quiet "$out"
|
||||
git -C "$out" remote add origin "$repository"
|
||||
git -C "$out" fetch --quiet --no-tags origin "+refs/heads/main:refs/remotes/origin/main" ||
|
||||
fail "cannot fetch the platform's main from ${repository}."
|
||||
git -C "$out" cat-file -e "${commit}^{commit}" 2>/dev/null ||
|
||||
fail "the pinned platform commit ${commit} is not on the platform's main."
|
||||
git -C "$out" merge-base --is-ancestor "$commit" refs/remotes/origin/main ||
|
||||
fail "the pinned platform commit ${commit} is not on the platform's main."
|
||||
git -C "$out" -c advice.detachedHead=false checkout --quiet --detach "$commit"
|
||||
[[ "$(git -C "$out" rev-parse HEAD)" == "$commit" ]] || fail "the platform did not check out at ${commit}."
|
||||
rm -rf "$out/.git"
|
||||
echo "assemble: platform ${commit}"
|
||||
|
||||
[[ ! -e "$out/modules/signage" ]] || fail "the platform checkout already has modules/signage."
|
||||
mkdir -p "$out/modules/signage"
|
||||
# Exactly the files this checkout tracks, as committed or as changed in the working tree. Nothing
|
||||
# installed, built, or ignored, and not the CI scaffolding, which is not part of the module.
|
||||
git -C "$root" ls-files -z --cached --others --exclude-standard -- . ':!ci' ':!.gitea' |
|
||||
tar -C "$root" --null --files-from=- --create --file=- |
|
||||
tar -C "$out/modules/signage" --extract --file=-
|
||||
echo "assemble: signage $(git -C "$root" rev-parse HEAD 2>/dev/null || echo "(working tree)")"
|
||||
|
||||
if [[ -f "$root/ci/pnpm-lock.yaml" ]]; then
|
||||
cp "$root/ci/pnpm-lock.yaml" "$out/pnpm-lock.yaml"
|
||||
elif ((allow_missing_lock == 0)); then
|
||||
fail "ci/pnpm-lock.yaml is missing; run bash ci/update-lock.sh."
|
||||
fi
|
||||
@@ -1,7 +0,0 @@
|
||||
# The platform's display-device scenarios this repository's CI runs against Signage, one per line
|
||||
# (scripts/lib/deploy-smoke-display.mjs in the pinned platform). Pairing a kiosk and restarting it on
|
||||
# the same profile always run first. A change that makes another scenario pass adds it here.
|
||||
two-pages
|
||||
session-blip
|
||||
stream-failure
|
||||
stream-recycle
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Signage inside Ekklesia, end to end: builds the deployment image from the assembled workspace with
|
||||
# the platform's own Dockerfile, then runs the platform's split-topology deployment smoke against it
|
||||
# with the display-device scenarios listed in ci/display-scenarios. A disposable PostgreSQL and object
|
||||
# store, generated secrets, and an explicit migration apply against that fresh database only; nothing
|
||||
# is pushed, published, or logged in to. The image is removed afterwards.
|
||||
#
|
||||
# bash ci/integration.sh (after bash ci/assemble.sh)
|
||||
set -Eeuo pipefail
|
||||
|
||||
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
workspace="$root/build/workspace"
|
||||
[[ -f "$workspace/deploy/Dockerfile" ]] || {
|
||||
echo "integration: run bash ci/assemble.sh first." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
image="signage-ci:${GITHUB_SHA:-local}-${GITHUB_RUN_ID:-0}-${GITHUB_RUN_ATTEMPT:-1}"
|
||||
trap 'docker image rm --force "$image" >/dev/null 2>&1 || true' EXIT
|
||||
|
||||
scenarios="$(sed -e 's/#.*//' -e '/^[[:space:]]*$/d' "$root/ci/display-scenarios" | tr '\n' ' ')"
|
||||
[[ -n "${scenarios// /}" ]] || {
|
||||
echo "integration: ci/display-scenarios lists no scenario." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
DOCKER_BUILDKIT=1 docker build --quiet --file "$workspace/deploy/Dockerfile" --tag "$image" \
|
||||
"$workspace" >/dev/null
|
||||
echo "integration: built the deployment image with Signage; scenarios: ${scenarios}"
|
||||
|
||||
cd "$workspace"
|
||||
EKKLESIA_SMOKE_TOPOLOGY=split \
|
||||
EKKLESIA_SMOKE_IMAGE="$image" \
|
||||
EKKLESIA_SMOKE_DISPLAY_DEVICE=1 \
|
||||
EKKLESIA_SMOKE_DISPLAY_SCENARIOS="$scenarios" \
|
||||
EKKLESIA_SMOKE_WATCH_MS=120000 \
|
||||
EKKLESIA_SMOKE_RECYCLE_WATCH_MS=120000 \
|
||||
bash scripts/smoke-deploy.sh
|
||||
@@ -1,6 +0,0 @@
|
||||
# The Ekklesia platform Signage's CI builds and tests against: one reviewed commit on the platform's
|
||||
# `main`, never a moving ref. ci/assemble.sh refuses a commit that is not on `main`.
|
||||
#
|
||||
# Move it deliberately: change the commit, run `bash ci/update-lock.sh`, and commit both.
|
||||
EKKLESIA_PLATFORM_REPOSITORY=https://git.riverofglorymn.org/River_of_Glory_Church/Ekklesia.git
|
||||
EKKLESIA_PLATFORM_COMMIT=f50e8f42018c15698709739e2ba54771e97df08a
|
||||
Generated
-4403
File diff suppressed because it is too large
Load Diff
@@ -1,21 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates ci/pnpm-lock.yaml: the lockfile of Signage assembled into the pinned platform. Run it
|
||||
# after changing Signage's dependencies or ci/platform.env, and commit the result. CI installs with
|
||||
# --frozen-lockfile, so a stale lockfile fails there rather than resolving anything new.
|
||||
#
|
||||
# bash ci/update-lock.sh
|
||||
#
|
||||
# Uses the platform's own pinned pnpm (its packageManager field) through Corepack.
|
||||
set -Eeuo pipefail
|
||||
|
||||
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
bash "$root/ci/assemble.sh" --allow-missing-lock "$work/workspace"
|
||||
cd "$work/workspace"
|
||||
corepack enable >/dev/null 2>&1 || true
|
||||
corepack install >/dev/null
|
||||
pnpm install --lockfile-only
|
||||
cp pnpm-lock.yaml "$root/ci/pnpm-lock.yaml"
|
||||
echo "update-lock: wrote ci/pnpm-lock.yaml"
|
||||
@@ -1,21 +0,0 @@
|
||||
/**
|
||||
* How long a display waits before trying a failed request again.
|
||||
*
|
||||
* Exponential from one second to a one-minute ceiling, so a screen whose server is restarting is
|
||||
* back within seconds, and one whose server is down for an evening asks once a minute rather than
|
||||
* hammering it. The wait is jittered between half and all of that step, so a building's worth of
|
||||
* screens that lost the server at the same moment do not all come back at the same moment.
|
||||
*
|
||||
* There is no attempt limit. A television on a wall has nobody to press Retry, so giving up is the
|
||||
* one thing it must never do.
|
||||
*/
|
||||
export const DISPLAY_RETRY_BASE_MS = 1_000;
|
||||
export const DISPLAY_RETRY_MAX_MS = 60_000;
|
||||
|
||||
export function displayRetryDelayMs(attempt: number, random: () => number = Math.random): number {
|
||||
const step = Math.min(
|
||||
DISPLAY_RETRY_MAX_MS,
|
||||
DISPLAY_RETRY_BASE_MS * 2 ** Math.min(Math.max(0, attempt), 16),
|
||||
);
|
||||
return Math.round(step / 2 + (step / 2) * Math.min(1, Math.max(0, random())));
|
||||
}
|
||||
+69
-143
@@ -1,5 +1,4 @@
|
||||
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
|
||||
import { displayRetryDelayMs } from "../browser/backoff.js";
|
||||
import {
|
||||
type OfflineSnapshot,
|
||||
resolveOffline,
|
||||
@@ -19,13 +18,6 @@ import {
|
||||
type SignageMediaCache,
|
||||
signageMediaKey,
|
||||
} from "../browser/storage.js";
|
||||
import {
|
||||
type DisplayChannelState,
|
||||
type DisplayHeartbeat,
|
||||
type DisplayRealtimeGroup,
|
||||
parseViewerSessionResponse,
|
||||
type ViewerSessionResponse,
|
||||
} from "../shared/display-protocol.js";
|
||||
|
||||
/**
|
||||
* The display: what it fetches, what it shows, and what it reports.
|
||||
@@ -46,11 +38,36 @@ const SNAPSHOT_STORAGE = "last-known-good";
|
||||
* must not sit on a stale frame until the next; and a delivery URL has a finite life. */
|
||||
const REFRESH_INTERVAL_MS = 4 * 60 * 1000;
|
||||
|
||||
/** The channel state a display renders, exactly as the server sends it (`src/shared`). */
|
||||
export type DisplayChannelStateView = DisplayChannelState;
|
||||
export interface DisplayChannelStateView {
|
||||
readonly serverNowMs: number;
|
||||
readonly channel: { readonly id: string; readonly key: string; readonly groupId: string };
|
||||
readonly crossfadeMs: number;
|
||||
readonly playback: {
|
||||
readonly revision: number;
|
||||
readonly transport: string;
|
||||
readonly blackout: boolean;
|
||||
readonly remainingMs: number | null;
|
||||
readonly selectionRevision: number | null;
|
||||
readonly currentSelectionId: string | null;
|
||||
readonly currentSlotId: string | null;
|
||||
readonly activeTimelineId: string | null;
|
||||
readonly pendingTimelineId: string | null;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
};
|
||||
readonly timeline: OfflineSnapshot["timeline"];
|
||||
readonly current: SceneSelection | null;
|
||||
readonly staticHold: SceneSelection | null;
|
||||
readonly selections: readonly SceneSelection[];
|
||||
}
|
||||
|
||||
/** The display's registration, exactly as the server answers it (`src/shared`). */
|
||||
export type DisplaySessionView = ViewerSessionResponse;
|
||||
export interface DisplaySessionView {
|
||||
readonly viewerId: string;
|
||||
readonly channelId: string;
|
||||
readonly channelKey: string;
|
||||
readonly groupId: string;
|
||||
readonly heartbeatIntervalMs: number;
|
||||
}
|
||||
|
||||
/** What an operator can see about this screen, and what a test asserts on. Sanitized by
|
||||
* construction: identity, counts, and a code. */
|
||||
@@ -123,13 +140,6 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
let snapshot: OfflineSnapshot | undefined;
|
||||
let offlineActive = false;
|
||||
let offlineHandle: unknown;
|
||||
/** Retries, each on its own backoff. A display has nobody to press Retry, so none of them give up;
|
||||
* each resets once its request works again. */
|
||||
let sessionHandle: unknown;
|
||||
let sessionAttempt = 0;
|
||||
let refreshAttempt = 0;
|
||||
let realtimeHandle: unknown;
|
||||
let realtimeAttempt = 0;
|
||||
/** Selections this display has tried and failed to render. A broken item is skipped rather than
|
||||
* retried in a tight loop, which is what keeps one bad slide from becoming a flicker. */
|
||||
const unusable = new Set<string>();
|
||||
@@ -505,119 +515,17 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
`channels/${session.channelId}/display-state`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
await refreshFailed();
|
||||
return;
|
||||
}
|
||||
const state = (await response.json()) as DisplayChannelStateView;
|
||||
refreshAttempt = 0;
|
||||
await apply(state);
|
||||
} catch {
|
||||
await refreshFailed();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The server is unreachable, or answered with an error. The frame stays and local continuation
|
||||
* takes over — nothing about a network failure belongs on a lobby wall — and the refresh is tried
|
||||
* again on its own, because a realtime message that would otherwise prompt it may never come.
|
||||
*/
|
||||
async function refreshFailed(): Promise<void> {
|
||||
online = false;
|
||||
await runOffline();
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
if (refreshHandle !== undefined) {
|
||||
clearTimer(refreshHandle);
|
||||
}
|
||||
refreshHandle = setTimer(() => {
|
||||
refreshHandle = undefined;
|
||||
void refresh();
|
||||
}, displayRetryDelayMs(refreshAttempt));
|
||||
refreshAttempt += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers this display, and keeps trying until it can.
|
||||
*
|
||||
* Until it has registered, a display continues from its own persisted state, honestly marked as
|
||||
* offline. The first registration that works brings it live — realtime, heartbeats, and fresh
|
||||
* state — exactly as if it had worked the first time.
|
||||
*/
|
||||
async function register(): Promise<void> {
|
||||
if (stopped || session) {
|
||||
return;
|
||||
}
|
||||
let registered: DisplaySessionView | undefined;
|
||||
try {
|
||||
const response = await options.context.api.request("viewers/session", {
|
||||
body: JSON.stringify({ viewerKey: await viewerKey() }),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST",
|
||||
});
|
||||
if (response.ok) {
|
||||
// Read, not cast: a registration the display cannot understand is no registration, and is
|
||||
// tried again like any other failure.
|
||||
const parsed = parseViewerSessionResponse(await response.json());
|
||||
registered = parsed.ok ? parsed.value : undefined;
|
||||
}
|
||||
await apply((await response.json()) as DisplayChannelStateView);
|
||||
} catch {
|
||||
registered = undefined;
|
||||
}
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
if (!registered) {
|
||||
// The server is unreachable. The frame stays and local continuation takes over; nothing about
|
||||
// a network failure belongs on a lobby wall.
|
||||
online = false;
|
||||
report();
|
||||
sessionHandle = setTimer(() => {
|
||||
sessionHandle = undefined;
|
||||
void register();
|
||||
}, displayRetryDelayMs(sessionAttempt));
|
||||
sessionAttempt += 1;
|
||||
return;
|
||||
await runOffline();
|
||||
}
|
||||
sessionAttempt = 0;
|
||||
session = registered;
|
||||
online = true;
|
||||
subscribe();
|
||||
heartbeatHandle = setInterval(
|
||||
() => void heartbeat(),
|
||||
registered.heartbeatIntervalMs,
|
||||
) as unknown;
|
||||
await refresh();
|
||||
void heartbeat();
|
||||
report();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to the display's realtime channel, and again whenever the host reports that a
|
||||
* subscription has ended for good. The host retries ordinary disconnects itself; a stream that
|
||||
* is refused outright ends, and until this resubscribes the display would only learn of changes
|
||||
* at its next slot deadline.
|
||||
*/
|
||||
function subscribe(): void {
|
||||
if (stopped || !session) {
|
||||
return;
|
||||
}
|
||||
subscription?.close();
|
||||
subscription = options.context.realtime.subscribe("display-state", {
|
||||
onSnapshot: (state) => onRealtime(state),
|
||||
onStatus: (status) => {
|
||||
online = status === "connected";
|
||||
if (status === "connected") {
|
||||
realtimeAttempt = 0;
|
||||
} else if (status === "closed" && !stopped && realtimeHandle === undefined) {
|
||||
realtimeHandle = setTimer(() => {
|
||||
realtimeHandle = undefined;
|
||||
subscribe();
|
||||
}, displayRetryDelayMs(realtimeAttempt));
|
||||
realtimeAttempt += 1;
|
||||
}
|
||||
report();
|
||||
},
|
||||
onUpdate: (state) => onRealtime(state),
|
||||
});
|
||||
}
|
||||
|
||||
async function heartbeat(): Promise<void> {
|
||||
@@ -625,10 +533,11 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Built as the shared message type, which is the same type the route parses with.
|
||||
const report: DisplayHeartbeat = {
|
||||
await options.context.api.request(`viewers/${session.viewerId}/heartbeat`, {
|
||||
body: JSON.stringify({
|
||||
cachedAssetCount,
|
||||
error: lastError === undefined ? null : { code: lastError.code, detail: lastError.detail },
|
||||
error:
|
||||
lastError === undefined ? null : { code: lastError.code, detail: lastError.detail },
|
||||
offlineReady: snapshot !== undefined && snapshot.selections.length > 0,
|
||||
reportedContributionId:
|
||||
lastState?.current?.renderer.kind === "contribution"
|
||||
@@ -638,9 +547,7 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
reportedProviderId: lastState?.current?.providerId ?? null,
|
||||
reportedSelectionId: renderedSelectionId ?? null,
|
||||
reportedTimelineId: lastState?.playback.activeTimelineId ?? null,
|
||||
};
|
||||
await options.context.api.request(`viewers/${session.viewerId}/heartbeat`, {
|
||||
body: JSON.stringify(report),
|
||||
}),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST",
|
||||
});
|
||||
@@ -688,7 +595,36 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
}
|
||||
|
||||
if (telemetry) {
|
||||
await register();
|
||||
try {
|
||||
const response = await options.context.api.request("viewers/session", {
|
||||
body: JSON.stringify({ viewerKey: await viewerKey() }),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST",
|
||||
});
|
||||
if (response.ok) {
|
||||
session = (await response.json()) as DisplaySessionView;
|
||||
online = true;
|
||||
}
|
||||
} catch {
|
||||
online = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (session) {
|
||||
subscription = options.context.realtime.subscribe("display-state", {
|
||||
onSnapshot: (state) => onRealtime(state),
|
||||
onStatus: (status) => {
|
||||
online = status === "connected";
|
||||
report();
|
||||
},
|
||||
onUpdate: (state) => onRealtime(state),
|
||||
});
|
||||
heartbeatHandle = setInterval(
|
||||
() => void heartbeat(),
|
||||
session.heartbeatIntervalMs,
|
||||
) as unknown;
|
||||
await refresh();
|
||||
void heartbeat();
|
||||
}
|
||||
report();
|
||||
},
|
||||
@@ -705,13 +641,6 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
clearTimer(refreshHandle);
|
||||
refreshHandle = undefined;
|
||||
}
|
||||
for (const handle of [sessionHandle, realtimeHandle]) {
|
||||
if (handle !== undefined) {
|
||||
clearTimer(handle);
|
||||
}
|
||||
}
|
||||
sessionHandle = undefined;
|
||||
realtimeHandle = undefined;
|
||||
exitOffline();
|
||||
await stage?.destroy();
|
||||
stage = undefined;
|
||||
@@ -729,10 +658,7 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
if (stopped || !session) {
|
||||
return;
|
||||
}
|
||||
// Checked at run time as well as typed: realtime state is the platform's transport, and a frame
|
||||
// this display cannot read is simply not one it acts on.
|
||||
const groups = (payload as { groups?: readonly Partial<DisplayRealtimeGroup>[] } | null)
|
||||
?.groups;
|
||||
const groups = (payload as { groups?: readonly Record<string, unknown>[] } | null)?.groups;
|
||||
if (!Array.isArray(groups)) {
|
||||
return;
|
||||
}
|
||||
|
||||
+70
-18
@@ -1,9 +1,4 @@
|
||||
import type { ModuleStorage } from "@ekklesia/module-sdk";
|
||||
import type {
|
||||
DisplayChannelState as DisplayChannelStateWire,
|
||||
DisplaySelection,
|
||||
DisplayTimeline,
|
||||
} from "../../shared/display-protocol.js";
|
||||
import {
|
||||
resolveNativeScene,
|
||||
SIGNAGE_NATIVE_PROVIDER_ID,
|
||||
@@ -40,21 +35,78 @@ import type {
|
||||
* and a display refreshes state long before one lapses.
|
||||
*/
|
||||
|
||||
export type {
|
||||
DisplayMedia,
|
||||
DisplaySelection,
|
||||
DisplayTimeline,
|
||||
DisplayTimelineSlot,
|
||||
} from "../../shared/display-protocol.js";
|
||||
export interface DisplayMedia {
|
||||
readonly url: string;
|
||||
readonly expiresAtMs: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel state the server builds: the wire shape a display reads (`src/shared`), plus the
|
||||
* channel's name and the group's whole playback snapshot. Declared as an extension so that a field
|
||||
* the display relies on cannot be renamed or retyped here without failing to compile.
|
||||
*/
|
||||
export interface DisplayChannelState extends DisplayChannelStateWire {
|
||||
readonly channel: DisplayChannelStateWire["channel"] & { readonly name: string };
|
||||
export interface DisplaySelection {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly slotId: string | null;
|
||||
readonly providerId: string;
|
||||
readonly itemId: string;
|
||||
readonly itemRevision: string;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
readonly durationMs: number;
|
||||
readonly availableUntilMs: number | null;
|
||||
readonly withdrawn: boolean;
|
||||
readonly stale: boolean;
|
||||
/** `native-image` is drawn by Signage's own display code; `contribution` is mounted through the
|
||||
* platform's contribution ABI by id. A display never receives a URL for either. */
|
||||
readonly renderer:
|
||||
| { readonly kind: "native-image" }
|
||||
| {
|
||||
readonly kind: "contribution";
|
||||
readonly contributionId: string;
|
||||
readonly contributionVersion: string;
|
||||
}
|
||||
| { readonly kind: "unavailable" };
|
||||
/** The provider's own payload for this channel's audience, or its default. */
|
||||
readonly payload: unknown;
|
||||
readonly presentation: unknown;
|
||||
/** Native images only: fresh delivery URLs, and the already-resolved scene. */
|
||||
readonly media?: { readonly display: DisplayMedia; readonly thumbnail: DisplayMedia };
|
||||
readonly scene?: ReturnType<typeof resolveNativeScene>;
|
||||
}
|
||||
|
||||
export interface DisplayTimelineSlot {
|
||||
readonly id: string;
|
||||
readonly position: number;
|
||||
readonly enabled: boolean;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly estimatedDurationMs: number;
|
||||
}
|
||||
|
||||
export interface DisplayTimeline {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly slots: readonly DisplayTimelineSlot[];
|
||||
}
|
||||
|
||||
export interface DisplayChannelState {
|
||||
readonly serverNowMs: number;
|
||||
readonly channel: {
|
||||
readonly id: string;
|
||||
readonly key: string;
|
||||
readonly name: string;
|
||||
readonly groupId: string;
|
||||
};
|
||||
readonly crossfadeMs: number;
|
||||
readonly playback: PlaybackSnapshot;
|
||||
readonly timeline: DisplayTimeline | null;
|
||||
readonly current: DisplaySelection | null;
|
||||
/** The held image, already resolved as a scene. Separate from `current` because a static hold sits
|
||||
* *over* a preserved cursor rather than replacing it. */
|
||||
readonly staticHold: DisplaySelection | null;
|
||||
/** Bounded, newest first. Material for offline continuation, never a substitute for authority. */
|
||||
readonly selections: readonly DisplaySelection[];
|
||||
}
|
||||
|
||||
/** How many resolved selections travel to a display. Enough to cover a pattern and then some, small
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import type { ModuleHttpRouteRegistrar, ModuleRouteHandlerContext } from "@ekklesia/module-sdk";
|
||||
import {
|
||||
type DisplayHeartbeatResponse,
|
||||
type ProtocolResult,
|
||||
parseDisplayHeartbeat,
|
||||
parseViewerSessionRequest,
|
||||
type ViewerSessionResponse,
|
||||
} from "../../shared/display-protocol.js";
|
||||
import { buildDisplayChannelState } from "../display/state.js";
|
||||
import { SignageError, signageBoundary } from "../errors.js";
|
||||
import { optionalString, readJsonObject, requireUuidParam } from "../http.js";
|
||||
import {
|
||||
optionalBoolean,
|
||||
optionalInteger,
|
||||
optionalString,
|
||||
readJsonObject,
|
||||
requireUuidParam,
|
||||
} from "../http.js";
|
||||
import type { SignagePlaybackService } from "../playback/service.js";
|
||||
import type { SignageProviderRegistry } from "../providers/registry.js";
|
||||
import { readSignageSettings } from "../settings.js";
|
||||
@@ -22,23 +21,11 @@ import {
|
||||
updateViewerAssignment,
|
||||
} from "../viewers/service.js";
|
||||
|
||||
/** How a route reaches Signage's tables. Production uses the module database; the display contract
|
||||
* test supplies the in-memory store so the real handlers can answer the real display controller. */
|
||||
/** How often a display checks in. Sent to the display rather than built into it, so the server can
|
||||
* change its own expectations without a display deployment. */
|
||||
export const SIGNAGE_HEARTBEAT_INTERVAL_MS = 12_000;
|
||||
const OPAQUE_ID = /^[\w][\w.:-]{0,199}$/u;
|
||||
|
||||
/** A display message the shared protocol refused, as Signage's own sanitized code naming the field. */
|
||||
function accepted<Value>(result: ProtocolResult<Value>): Value {
|
||||
if (!result.ok) {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: result.field });
|
||||
function store(context: ModuleRouteHandlerContext): SignageStore {
|
||||
return createSignageStore(context.services.database);
|
||||
}
|
||||
return result.value;
|
||||
}
|
||||
|
||||
export type ViewerRouteStore = (context: ModuleRouteHandlerContext) => SignageStore;
|
||||
|
||||
const databaseStore: ViewerRouteStore = (context) => createSignageStore(context.services.database);
|
||||
|
||||
/**
|
||||
* The safe Core device identifier, when the caller is a paired display.
|
||||
@@ -70,7 +57,6 @@ export function registerViewerRoutes(
|
||||
http: ModuleHttpRouteRegistrar,
|
||||
playback: () => SignagePlaybackService,
|
||||
registry: () => SignageProviderRegistry,
|
||||
store: ViewerRouteStore = databaseStore,
|
||||
): void {
|
||||
http.route({
|
||||
method: "POST",
|
||||
@@ -79,7 +65,11 @@ export function registerViewerRoutes(
|
||||
maxBodyBytes: 2048,
|
||||
handler(request, context) {
|
||||
return signageBoundary(async () => {
|
||||
const { viewerKey } = accepted(parseViewerSessionRequest(await readJsonObject(request)));
|
||||
const body = await readJsonObject(request);
|
||||
const viewerKey = body.viewerKey;
|
||||
if (typeof viewerKey !== "string") {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "viewerKey" });
|
||||
}
|
||||
// A display registers with the identity it keeps in its own IndexedDB and lands on the
|
||||
// default channel. It never chooses one: a public screen that could would let anyone who
|
||||
// reaches the page decide what a wall shows (ADR 0004).
|
||||
@@ -89,15 +79,14 @@ export function registerViewerRoutes(
|
||||
store: store(context),
|
||||
viewerKey,
|
||||
});
|
||||
const response: ViewerSessionResponse = {
|
||||
return Response.json({
|
||||
channelId: session.channel.id,
|
||||
channelKey: session.channel.key,
|
||||
groupId: session.groupId,
|
||||
heartbeatIntervalMs: SIGNAGE_HEARTBEAT_INTERVAL_MS,
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: session.viewer.id,
|
||||
viewerName: session.viewer.name,
|
||||
};
|
||||
return Response.json(response);
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -110,21 +99,52 @@ export function registerViewerRoutes(
|
||||
handler(request, context) {
|
||||
return signageBoundary(async () => {
|
||||
const viewerId = requireUuidParam(context, "viewerId");
|
||||
const heartbeat = accepted(parseDisplayHeartbeat(await readJsonObject(request)));
|
||||
const body = await readJsonObject(request);
|
||||
const settings = readSignageSettings(context.config);
|
||||
const rawError = body.error;
|
||||
// Telemetry only. Nothing a display reports here changes authoritative playback, and a
|
||||
// local cursor is never accepted as truth.
|
||||
const result = await recordViewerHeartbeat({
|
||||
at: new Date(),
|
||||
heartbeat,
|
||||
heartbeat: {
|
||||
cachedAssetCount:
|
||||
optionalInteger(body, "cachedAssetCount", {
|
||||
maximum: 100_000,
|
||||
minimum: 0,
|
||||
}) ?? undefined,
|
||||
offlineReady: optionalBoolean(body, "offlineReady") ?? undefined,
|
||||
reportedContributionId:
|
||||
optionalString(body, "reportedContributionId", { maxLength: 200 }) ?? null,
|
||||
reportedPlaybackRevision:
|
||||
optionalInteger(body, "reportedPlaybackRevision", {
|
||||
maximum: Number.MAX_SAFE_INTEGER,
|
||||
minimum: 0,
|
||||
}) ?? null,
|
||||
reportedProviderId:
|
||||
optionalString(body, "reportedProviderId", { maxLength: 200 }) ?? null,
|
||||
reportedSelectionId:
|
||||
optionalString(body, "reportedSelectionId", { maxLength: 64 }) ?? null,
|
||||
reportedTimelineId:
|
||||
optionalString(body, "reportedTimelineId", { maxLength: 64 }) ?? null,
|
||||
...(rawError === undefined
|
||||
? {}
|
||||
: {
|
||||
error:
|
||||
rawError === null
|
||||
? null
|
||||
: {
|
||||
code: readErrorCode(rawError),
|
||||
detail: readErrorDetail(rawError),
|
||||
},
|
||||
}),
|
||||
},
|
||||
minimumWriteIntervalMs: settings.viewerHeartbeatWriteMs,
|
||||
store: store(context),
|
||||
viewerId,
|
||||
});
|
||||
// The response says what a display needs to keep itself honest, and nothing about other
|
||||
// displays or the installation.
|
||||
const response: DisplayHeartbeatResponse = { acknowledged: true, recorded: result.written };
|
||||
return Response.json(response);
|
||||
return Response.json({ acknowledged: true, recorded: result.written });
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -215,3 +235,25 @@ export function registerViewerRoutes(
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function readErrorCode(value: unknown): string {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "error" });
|
||||
}
|
||||
const code = (value as { code?: unknown }).code;
|
||||
if (typeof code !== "string" || !OPAQUE_ID.test(code)) {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "error.code" });
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
function readErrorDetail(value: unknown): string | null {
|
||||
const detail = (value as { detail?: unknown }).detail;
|
||||
if (detail === undefined || detail === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof detail !== "string") {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "error.detail" });
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
type ModuleRuntimeContext,
|
||||
type ModuleRuntimeDefinition,
|
||||
} from "@ekklesia/module-sdk";
|
||||
import type { DisplayRealtimePayload } from "../shared/display-protocol.js";
|
||||
import { SIGNAGE_SLIDE_RENDERER_INPUT_VERSION } from "../shared/renderer-input.js";
|
||||
import {
|
||||
SIGNAGE_IMAGE_MAX_BYTES,
|
||||
@@ -99,10 +98,10 @@ export function createSignageModuleRuntime(
|
||||
left.groupId.localeCompare(right.groupId),
|
||||
);
|
||||
try {
|
||||
// The shape the display reads (`src/shared/display-protocol.ts`): each group's whole snapshot
|
||||
// carries the revisions it compares.
|
||||
const display: DisplayRealtimePayload = { groups, serverNowMs: now().getTime() };
|
||||
context.realtime.publish(SIGNAGE_DISPLAY_CHANNEL, display);
|
||||
context.realtime.publish(SIGNAGE_DISPLAY_CHANNEL, {
|
||||
groups,
|
||||
serverNowMs: now().getTime(),
|
||||
});
|
||||
context.realtime.publish(SIGNAGE_MANAGEMENT_CHANNEL, {
|
||||
// Revisions only. The dashboard refetches what changed over authorized HTTP.
|
||||
groups: groups.map((snapshot) => ({
|
||||
|
||||
@@ -1,318 +0,0 @@
|
||||
/**
|
||||
* What a display and Signage's server say to each other, defined once.
|
||||
*
|
||||
* The display controller builds these messages and the viewer routes read them, from this one file.
|
||||
* They used to be described twice — once in the controller's own interfaces and once in each
|
||||
* route's field-by-field parsing — and the two descriptions disagreed about one thing: the display
|
||||
* sent `null` for "nothing to report" and the heartbeat route accepted only a *missing* field. Every
|
||||
* heartbeat from a screen showing a native image was refused with a 400, silently, for as long as it
|
||||
* ran. Nothing here can drift that way again, because there is nothing to drift between.
|
||||
*
|
||||
* Three rules hold for every message:
|
||||
*
|
||||
* - **A nullable field accepts `null` explicitly.** `null` means "I have nothing", and is a value.
|
||||
* - **An absent field means "not reported".** A receiver keeps whatever it already had.
|
||||
* - **An unknown field is ignored, never refused.** A newer display reporting something an older
|
||||
* server does not know yet must still be heard; refusing it would be this same bug in reverse.
|
||||
*
|
||||
* Like the rest of `src/shared`, it imports nothing from outside `src/shared`: it is compiled into the browser
|
||||
* artifact as well as the server, and must pull neither the module SDK nor Node into a display.
|
||||
*/
|
||||
|
||||
import type { SignageNativeScene } from "./native-images.js";
|
||||
|
||||
// --- Parsing ---------------------------------------------------------------------------------------
|
||||
|
||||
/** The outcome of reading one message: the value, or the one field that was wrong. Never a parser's
|
||||
* own message, which is not something a client or an operator should see. */
|
||||
export type ProtocolResult<Value> =
|
||||
| { readonly ok: true; readonly value: Value }
|
||||
| { readonly ok: false; readonly field: string };
|
||||
|
||||
type Reader<Value> = (raw: unknown) => { readonly ok: true; readonly value: Value } | undefined;
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function text(options: { readonly maxLength: number; readonly pattern?: RegExp }): Reader<string> {
|
||||
return (raw) => {
|
||||
if (typeof raw !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const value = raw.trim();
|
||||
if (value.length === 0 || value.length > options.maxLength) {
|
||||
return undefined;
|
||||
}
|
||||
if (options.pattern && !options.pattern.test(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return { ok: true, value };
|
||||
};
|
||||
}
|
||||
|
||||
function integer(options: { readonly minimum: number; readonly maximum: number }): Reader<number> {
|
||||
return (raw) =>
|
||||
typeof raw === "number" &&
|
||||
Number.isSafeInteger(raw) &&
|
||||
raw >= options.minimum &&
|
||||
raw <= options.maximum
|
||||
? { ok: true, value: raw }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
const flag: Reader<boolean> = (raw) =>
|
||||
typeof raw === "boolean" ? { ok: true, value: raw } : undefined;
|
||||
|
||||
function nullable<Value>(read: Reader<Value>): Reader<Value | null> {
|
||||
return (raw) => (raw === null ? { ok: true, value: null } : read(raw));
|
||||
}
|
||||
|
||||
/** Reads the named fields of a message. Absent fields are left out of the result; any other field
|
||||
* of the object is ignored. */
|
||||
function readFields<Shape extends object>(
|
||||
raw: unknown,
|
||||
readers: { readonly [Key in keyof Shape]-?: Reader<Exclude<Shape[Key], undefined>> },
|
||||
): ProtocolResult<Shape> {
|
||||
if (!isRecord(raw)) {
|
||||
return { field: "body", ok: false };
|
||||
}
|
||||
const value: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(readers) as (keyof Shape & string)[]) {
|
||||
if (raw[key] === undefined) {
|
||||
continue;
|
||||
}
|
||||
const read = readers[key](raw[key]);
|
||||
if (!read) {
|
||||
return { field: key, ok: false };
|
||||
}
|
||||
value[key] = read.value;
|
||||
}
|
||||
return { ok: true, value: value as Shape };
|
||||
}
|
||||
|
||||
function requireFields<Shape>(
|
||||
result: ProtocolResult<Partial<Shape>>,
|
||||
required: readonly (keyof Shape & string)[],
|
||||
): ProtocolResult<Shape> {
|
||||
if (!result.ok) {
|
||||
return result;
|
||||
}
|
||||
for (const key of required) {
|
||||
if (result.value[key] === undefined) {
|
||||
return { field: key, ok: false };
|
||||
}
|
||||
}
|
||||
return result as ProtocolResult<Shape>;
|
||||
}
|
||||
|
||||
// --- Limits ----------------------------------------------------------------------------------------
|
||||
|
||||
/** A display's own identity, kept in its IndexedDB. */
|
||||
export const DISPLAY_VIEWER_KEY = /^[\w-]{8,128}$/u;
|
||||
/** The longest error detail a display may report. Operator-facing text a browser supplied, so it is
|
||||
* bounded, and because an unbounded one is a way to fill a table. */
|
||||
export const DISPLAY_ERROR_DETAIL_MAX = 200;
|
||||
export const DISPLAY_ERROR_CODE = /^[\w][\w.:-]{0,63}$/u;
|
||||
export const DISPLAY_CACHED_ASSET_MAX = 100_000;
|
||||
|
||||
// --- Viewer session: POST viewers/session ----------------------------------------------------------
|
||||
|
||||
export interface ViewerSessionRequest {
|
||||
readonly viewerKey: string;
|
||||
}
|
||||
|
||||
export interface ViewerSessionResponse {
|
||||
readonly viewerId: string;
|
||||
readonly viewerName: string;
|
||||
readonly channelId: string;
|
||||
readonly channelKey: string;
|
||||
readonly groupId: string;
|
||||
readonly heartbeatIntervalMs: number;
|
||||
}
|
||||
|
||||
const identifier = text({ maxLength: 200 });
|
||||
|
||||
export function parseViewerSessionRequest(raw: unknown): ProtocolResult<ViewerSessionRequest> {
|
||||
return requireFields<ViewerSessionRequest>(
|
||||
readFields<Partial<ViewerSessionRequest>>(raw, {
|
||||
viewerKey: text({ maxLength: 128, pattern: DISPLAY_VIEWER_KEY }),
|
||||
}),
|
||||
["viewerKey"],
|
||||
);
|
||||
}
|
||||
|
||||
export function parseViewerSessionResponse(raw: unknown): ProtocolResult<ViewerSessionResponse> {
|
||||
return requireFields<ViewerSessionResponse>(
|
||||
readFields<Partial<ViewerSessionResponse>>(raw, {
|
||||
channelId: identifier,
|
||||
channelKey: identifier,
|
||||
groupId: identifier,
|
||||
heartbeatIntervalMs: integer({ maximum: 600_000, minimum: 1_000 }),
|
||||
viewerId: identifier,
|
||||
viewerName: text({ maxLength: 200 }),
|
||||
}),
|
||||
["viewerId", "viewerName", "channelId", "channelKey", "groupId", "heartbeatIntervalMs"],
|
||||
);
|
||||
}
|
||||
|
||||
// --- Heartbeat: POST viewers/:viewerId/heartbeat ---------------------------------------------------
|
||||
|
||||
export interface DisplayReportedError {
|
||||
readonly code: string;
|
||||
readonly detail: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a display reports about itself. Telemetry, never authority: nothing here changes playback.
|
||||
*
|
||||
* Every field is optional on the wire (absent = not reported). The display sends all of them.
|
||||
*/
|
||||
export interface DisplayHeartbeat {
|
||||
readonly cachedAssetCount?: number;
|
||||
readonly offlineReady?: boolean;
|
||||
readonly reportedTimelineId?: string | null;
|
||||
readonly reportedSelectionId?: string | null;
|
||||
readonly reportedProviderId?: string | null;
|
||||
readonly reportedContributionId?: string | null;
|
||||
readonly reportedPlaybackRevision?: number | null;
|
||||
readonly error?: DisplayReportedError | null;
|
||||
}
|
||||
|
||||
const reportedError: Reader<DisplayReportedError> = (raw) => {
|
||||
const read = readFields<{ code?: string; detail?: string | null }>(raw, {
|
||||
code: text({ maxLength: 64, pattern: DISPLAY_ERROR_CODE }),
|
||||
detail: nullable(text({ maxLength: DISPLAY_ERROR_DETAIL_MAX })),
|
||||
});
|
||||
if (!read.ok || read.value.code === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return { ok: true, value: { code: read.value.code, detail: read.value.detail ?? null } };
|
||||
};
|
||||
|
||||
export function parseDisplayHeartbeat(raw: unknown): ProtocolResult<DisplayHeartbeat> {
|
||||
return readFields<DisplayHeartbeat>(raw, {
|
||||
cachedAssetCount: integer({ maximum: DISPLAY_CACHED_ASSET_MAX, minimum: 0 }),
|
||||
error: nullable(reportedError),
|
||||
offlineReady: flag,
|
||||
reportedContributionId: nullable(text({ maxLength: 200 })),
|
||||
reportedPlaybackRevision: nullable(integer({ maximum: Number.MAX_SAFE_INTEGER, minimum: 0 })),
|
||||
reportedProviderId: nullable(text({ maxLength: 200 })),
|
||||
reportedSelectionId: nullable(text({ maxLength: 64 })),
|
||||
reportedTimelineId: nullable(text({ maxLength: 64 })),
|
||||
});
|
||||
}
|
||||
|
||||
export interface DisplayHeartbeatResponse {
|
||||
readonly acknowledged: true;
|
||||
readonly recorded: boolean;
|
||||
}
|
||||
|
||||
// --- Channel state: GET channels/:channelId/display-state -----------------------------------------
|
||||
|
||||
/** A fresh, signed delivery URL. A bearer capability with an expiry: never persisted by a display. */
|
||||
export interface DisplayMedia {
|
||||
readonly url: string;
|
||||
readonly expiresAtMs: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
export type DisplayRenderer =
|
||||
| { readonly kind: "native-image" }
|
||||
| {
|
||||
readonly kind: "contribution";
|
||||
readonly contributionId: string;
|
||||
readonly contributionVersion: string;
|
||||
}
|
||||
| { readonly kind: "unavailable" };
|
||||
|
||||
export interface DisplaySelection {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly slotId: string | null;
|
||||
readonly providerId: string;
|
||||
readonly itemId: string;
|
||||
readonly itemRevision: string;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
readonly durationMs: number;
|
||||
readonly availableUntilMs: number | null;
|
||||
readonly withdrawn: boolean;
|
||||
readonly stale: boolean;
|
||||
/** `native-image` is drawn by Signage's own display code; `contribution` is mounted through the
|
||||
* platform's contribution ABI by id. A display never receives a URL for either. */
|
||||
readonly renderer: DisplayRenderer;
|
||||
/** The provider's own payload for this channel's audience, or its default. */
|
||||
readonly payload: unknown;
|
||||
readonly presentation: unknown;
|
||||
/** Native images only: fresh delivery URLs, and the already-resolved scene. */
|
||||
readonly media?: { readonly display: DisplayMedia; readonly thumbnail: DisplayMedia };
|
||||
readonly scene?: SignageNativeScene;
|
||||
}
|
||||
|
||||
export interface DisplayTimelineSlot {
|
||||
readonly id: string;
|
||||
readonly position: number;
|
||||
readonly enabled: boolean;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly estimatedDurationMs: number;
|
||||
}
|
||||
|
||||
export interface DisplayTimeline {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly slots: readonly DisplayTimelineSlot[];
|
||||
}
|
||||
|
||||
/** The part of the group's playback a display acts on. The server sends its whole snapshot; this is
|
||||
* what a display may rely on being there. */
|
||||
export interface DisplayPlayback {
|
||||
readonly revision: number;
|
||||
readonly transport: string;
|
||||
readonly blackout: boolean;
|
||||
readonly remainingMs: number | null;
|
||||
readonly selectionRevision: number | null;
|
||||
readonly currentSelectionId: string | null;
|
||||
readonly currentSlotId: string | null;
|
||||
readonly activeTimelineId: string | null;
|
||||
readonly pendingTimelineId: string | null;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
}
|
||||
|
||||
export interface DisplayChannelState {
|
||||
readonly serverNowMs: number;
|
||||
readonly channel: {
|
||||
readonly id: string;
|
||||
readonly key: string;
|
||||
readonly groupId: string;
|
||||
};
|
||||
readonly crossfadeMs: number;
|
||||
readonly playback: DisplayPlayback;
|
||||
readonly timeline: DisplayTimeline | null;
|
||||
readonly current: DisplaySelection | null;
|
||||
/** The held image, already resolved as a scene. Separate from `current` because a static hold sits
|
||||
* *over* a preserved cursor rather than replacing it. */
|
||||
readonly staticHold: DisplaySelection | null;
|
||||
/** Bounded, newest first. Material for offline continuation, never a substitute for authority. */
|
||||
readonly selections: readonly DisplaySelection[];
|
||||
}
|
||||
|
||||
// --- Realtime: the display-state channel ----------------------------------------------------------
|
||||
|
||||
/** One group's revisions on the realtime channel. Compact on purpose: a revision this display has
|
||||
* not applied means "fetch the state you are authorized for", never content. */
|
||||
export interface DisplayRealtimeGroup {
|
||||
readonly groupId: string;
|
||||
readonly revision: number;
|
||||
readonly selectionRevision: number | null;
|
||||
}
|
||||
|
||||
export interface DisplayRealtimePayload {
|
||||
readonly groups: readonly DisplayRealtimeGroup[];
|
||||
readonly serverNowMs: number;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DISPLAY_RETRY_BASE_MS,
|
||||
DISPLAY_RETRY_MAX_MS,
|
||||
displayRetryDelayMs,
|
||||
} from "../../src/browser/backoff.js";
|
||||
|
||||
describe("display retry backoff", () => {
|
||||
it("doubles from one second and stops at one minute", () => {
|
||||
const longest = (attempt: number) => displayRetryDelayMs(attempt, () => 1);
|
||||
expect([0, 1, 2, 3, 4, 5, 6, 7, 50].map(longest)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 32_000, 60_000, 60_000, 60_000,
|
||||
]);
|
||||
});
|
||||
|
||||
it("jitters between half and all of each step, and never waits zero", () => {
|
||||
for (const attempt of [0, 3, 6, 40]) {
|
||||
const step = Math.min(DISPLAY_RETRY_MAX_MS, DISPLAY_RETRY_BASE_MS * 2 ** attempt);
|
||||
expect(displayRetryDelayMs(attempt, () => 0)).toBe(step / 2);
|
||||
expect(displayRetryDelayMs(attempt, () => 1)).toBe(step);
|
||||
for (let index = 0; index < 50; index += 1) {
|
||||
const delay = displayRetryDelayMs(attempt);
|
||||
expect(delay).toBeGreaterThanOrEqual(step / 2);
|
||||
expect(delay).toBeLessThanOrEqual(step);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("treats a nonsensical attempt or random value as the nearest sensible one", () => {
|
||||
expect(displayRetryDelayMs(-3, () => 1)).toBe(1_000);
|
||||
expect(displayRetryDelayMs(2, () => 7)).toBe(4_000);
|
||||
expect(displayRetryDelayMs(2, () => -1)).toBe(2_000);
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,6 @@ const SELECTION = {
|
||||
},
|
||||
revision: 1,
|
||||
slotId: "slot-trivia",
|
||||
stale: false,
|
||||
startedAtMs: 0,
|
||||
withdrawn: false,
|
||||
};
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type { ModuleRouteDefinitionInput, ModuleRouteHandlerContext } from "@ekklesia/module-sdk";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { createMemoryMediaCache, createMemoryStore } from "../../src/browser/storage.js";
|
||||
import { createDisplayController } from "../../src/display/controller.js";
|
||||
import { ingestNativeImage } from "../../src/server/images/service.js";
|
||||
import {
|
||||
createPlaybackService,
|
||||
type SignagePlaybackService,
|
||||
} from "../../src/server/playback/service.js";
|
||||
import { createNativeImageProvider } from "../../src/server/providers/native-provider.js";
|
||||
import {
|
||||
createProviderRegistry,
|
||||
type SignageProviderRegistry,
|
||||
} from "../../src/server/providers/registry.js";
|
||||
import { registerViewerRoutes } from "../../src/server/routes/viewers.js";
|
||||
import { addSlot, createTimeline } from "../../src/server/timelines/service.js";
|
||||
import { SIGNAGE_NATIVE_PROVIDER_ID } from "../../src/shared/native-images.js";
|
||||
import { SIGNAGE_DEFAULT_SETTINGS } from "../../src/shared/settings.js";
|
||||
import { createFakeStorage, type FakeStorage } from "../support/fake-storage.js";
|
||||
import { makeImage } from "../support/images.js";
|
||||
import { createMemorySignageStore, type MemorySignageStore } from "../support/memory-store.js";
|
||||
import { fakeConfiguration, fakeHandlerContext } from "../support/module-harness.js";
|
||||
import { createFakeHost, type FakeHost } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
* The display and the server, speaking to each other for real.
|
||||
*
|
||||
* Every other display test answers the controller with a hand-written stub, and every server test
|
||||
* calls the service with a hand-written object. Each side was therefore only ever tested against its
|
||||
* own idea of the other, and in production every heartbeat a display sent was refused with a 400:
|
||||
* the display sent `null` for an absent value and the route accepted only a missing field.
|
||||
*
|
||||
* Here the **real** display controller's requests are answered by the **real** viewer routes, over
|
||||
* Signage's in-memory store. A request one side builds and the other refuses fails this suite.
|
||||
*/
|
||||
|
||||
const START = Date.parse("2026-10-05T15:00:00.000Z");
|
||||
const DEVICE_ID = "6f1c2d3e-4b5a-4c6d-8e7f-901a2b3c4d5e";
|
||||
|
||||
interface RouteCall {
|
||||
readonly method: string;
|
||||
readonly path: string;
|
||||
readonly status: number;
|
||||
readonly code: string | undefined;
|
||||
}
|
||||
|
||||
/** Matches a relative module path against the routes the module registered, and runs the handler
|
||||
* exactly as the platform would: one Request, one handler context. */
|
||||
function routeTable(routes: readonly ModuleRouteDefinitionInput[]) {
|
||||
return routes.map((route) => {
|
||||
const names: string[] = [];
|
||||
const pattern = new RegExp(
|
||||
`^${route.path.replace(/:(\w+)/gu, (_match, name: string) => {
|
||||
names.push(name);
|
||||
return "([^/]+)";
|
||||
})}$`,
|
||||
"u",
|
||||
);
|
||||
return { names, pattern, route };
|
||||
});
|
||||
}
|
||||
|
||||
describe("display ↔ server contract", () => {
|
||||
let clock: number;
|
||||
let counter: number;
|
||||
let store: MemorySignageStore;
|
||||
let storage: FakeStorage;
|
||||
let registry: SignageProviderRegistry;
|
||||
let playback: SignagePlaybackService;
|
||||
let calls: RouteCall[];
|
||||
let host: FakeHost;
|
||||
let root: HTMLElement;
|
||||
|
||||
const newId = () => {
|
||||
counter += 1;
|
||||
return `00000000-0000-4000-8000-${String(counter).padStart(12, "0")}`;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
clock = START;
|
||||
counter = 0;
|
||||
calls = [];
|
||||
store = createMemorySignageStore({ now: () => new Date(clock) });
|
||||
storage = createFakeStorage({ now: () => new Date(clock) });
|
||||
registry = createProviderRegistry({ now: () => new Date(clock), timeoutMs: 1000 });
|
||||
registry.capability.register(
|
||||
createNativeImageProvider({ defaultDurationMs: 7000, now: () => new Date(clock), store })
|
||||
.registration,
|
||||
);
|
||||
playback = createPlaybackService({
|
||||
newId,
|
||||
now: () => clock,
|
||||
registry,
|
||||
setTimer: () => undefined,
|
||||
settings: SIGNAGE_DEFAULT_SETTINGS,
|
||||
store,
|
||||
});
|
||||
await playback.ensureDefaultGroup();
|
||||
|
||||
// One native image on a pinned slot: the most ordinary thing a wall shows, and exactly the case
|
||||
// whose heartbeat carries no contribution id.
|
||||
const image = await ingestNativeImage({
|
||||
bytes: await makeImage({ format: "png", height: 1080, width: 1920 }),
|
||||
displayName: "Welcome",
|
||||
expiresAt: null,
|
||||
filename: "welcome.png",
|
||||
storage,
|
||||
store,
|
||||
});
|
||||
const timeline = await createTimeline({ name: "Lobby", newId, store });
|
||||
await addSlot({
|
||||
newId,
|
||||
pinned: { itemId: image.image.id, providerId: SIGNAGE_NATIVE_PROVIDER_ID },
|
||||
store,
|
||||
timelineId: timeline.timeline.id,
|
||||
});
|
||||
const groups = await store.listChannelGroups();
|
||||
await playback.activate(groups[0]?.group.id as string, timeline.timeline.id, "now");
|
||||
|
||||
const registered: ModuleRouteDefinitionInput[] = [];
|
||||
registerViewerRoutes(
|
||||
{ route: (definition) => registered.push(definition) },
|
||||
() => playback,
|
||||
() => registry,
|
||||
() => store,
|
||||
);
|
||||
const table = routeTable(registered);
|
||||
|
||||
host = createFakeHost({
|
||||
permissions: ["signage.display.view"],
|
||||
principal: { deviceId: DEVICE_ID, kind: "device" } as never,
|
||||
routes: [],
|
||||
});
|
||||
Object.assign(host.context.api, {
|
||||
async request(path: string, init?: RequestInit): Promise<Response> {
|
||||
const method = (init?.method ?? "GET").toUpperCase();
|
||||
const relative = `/${path.replace(/^\//u, "").split("?")[0]}`;
|
||||
for (const { names, pattern, route } of table) {
|
||||
const match = pattern.exec(relative);
|
||||
if (route.method !== method || !match) {
|
||||
continue;
|
||||
}
|
||||
const params = Object.fromEntries(names.map((name, index) => [name, match[index + 1]]));
|
||||
const context: ModuleRouteHandlerContext = fakeHandlerContext({
|
||||
config: fakeConfiguration({}),
|
||||
params: Object.freeze(params) as never,
|
||||
principal: { deviceId: DEVICE_ID, kind: "device" } as never,
|
||||
storage,
|
||||
});
|
||||
const request = new Request(
|
||||
`https://api.example.test/api/v1/modules/signage${relative}`,
|
||||
{
|
||||
...(init?.body === undefined ? {} : { body: init.body }),
|
||||
headers: init?.headers ?? {},
|
||||
method,
|
||||
},
|
||||
);
|
||||
const response = await route.handler(request, context);
|
||||
const body = (await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null)) as { code?: string } | null;
|
||||
calls.push({ code: body?.code, method, path: route.path, status: response.status });
|
||||
return response;
|
||||
}
|
||||
throw new Error(
|
||||
`The display asked for ${method} ${relative}, which Signage does not serve.`,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
});
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
function controller() {
|
||||
return createDisplayController({
|
||||
context: host.context,
|
||||
decodeImage: () => Promise.resolve(),
|
||||
media: createMemoryMediaCache(),
|
||||
newViewerKey: () => "kiosk-contract-0001",
|
||||
now: () => clock,
|
||||
root,
|
||||
store: createMemoryStore(),
|
||||
});
|
||||
}
|
||||
|
||||
it("the server accepts every request the display sends", async () => {
|
||||
const display = controller();
|
||||
await display.start();
|
||||
await settle();
|
||||
await display.stop();
|
||||
|
||||
const sent = calls.map((call) => `${call.method} ${call.path}`);
|
||||
expect(sent).toContain("POST /viewers/session");
|
||||
expect(sent).toContain("GET /channels/:channelId/display-state");
|
||||
expect(sent).toContain("POST /viewers/:viewerId/heartbeat");
|
||||
// Not one refusal, of any kind, for anything the display built itself.
|
||||
expect(calls.filter((call) => call.status >= 400)).toEqual([]);
|
||||
});
|
||||
|
||||
it("a heartbeat from a screen showing a native image is recorded", async () => {
|
||||
const display = controller();
|
||||
await display.start();
|
||||
await settle();
|
||||
await display.stop();
|
||||
|
||||
const [viewer] = await store.listViewers();
|
||||
expect(viewer).toBeDefined();
|
||||
// What the display reported is what the roster now holds — which is only true if the server
|
||||
// took the heartbeat, rather than refusing it and leaving the session's values in place.
|
||||
expect(viewer?.reportedSelectionId).not.toBeNull();
|
||||
expect(viewer?.reportedProviderId).toBe(SIGNAGE_NATIVE_PROVIDER_ID);
|
||||
expect(viewer?.reportedContributionId).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,307 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
createMemoryMediaCache,
|
||||
createMemoryStore,
|
||||
type SignageLocalStore,
|
||||
} from "../../src/browser/storage.js";
|
||||
import {
|
||||
createDisplayController,
|
||||
type DisplayChannelStateView,
|
||||
} from "../../src/display/controller.js";
|
||||
import { createFakeHost, type FakeHost, jsonResponse } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
* A display never reaches a dead end.
|
||||
*
|
||||
* Every network path a display depends on — registering, fetching state, realtime — can fail once,
|
||||
* as a kiosk that boots before its network settles or an API that restarts will make it. Each must
|
||||
* be tried again, with backoff, until it works, and the display must then be exactly as live as if
|
||||
* nothing had happened. None of it may need a person to reload a television.
|
||||
*
|
||||
* Time is virtual: every timer the controller schedules goes through the queue below.
|
||||
*/
|
||||
|
||||
const SESSION = {
|
||||
channelId: "chan-1",
|
||||
channelKey: "default",
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
viewerName: "Foyer",
|
||||
};
|
||||
|
||||
function selection(id: string) {
|
||||
return {
|
||||
availableUntilMs: null,
|
||||
deadlineAtMs: 5000,
|
||||
durationMs: 5000,
|
||||
id,
|
||||
itemId: `image-${id}`,
|
||||
itemRevision: "rev-1",
|
||||
media: {
|
||||
display: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 1080,
|
||||
url: `https://cdn.invalid/${id}`,
|
||||
width: 1920,
|
||||
},
|
||||
thumbnail: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 270,
|
||||
url: `https://cdn.invalid/${id}-t`,
|
||||
width: 480,
|
||||
},
|
||||
},
|
||||
payload: { kind: "native-image" },
|
||||
presentation: null,
|
||||
providerId: "signage.native-images",
|
||||
renderer: { kind: "native-image" as const },
|
||||
revision: 1,
|
||||
scene: {
|
||||
backgroundColor: "#000000",
|
||||
backgroundImage: false,
|
||||
backgroundMode: "none" as const,
|
||||
blurPixels: 0,
|
||||
darkenOpacity: 0,
|
||||
fit: "fill" as const,
|
||||
shadow: false,
|
||||
},
|
||||
slotId: "slot-1",
|
||||
stale: false,
|
||||
startedAtMs: 0,
|
||||
withdrawn: false,
|
||||
};
|
||||
}
|
||||
|
||||
function channelState(revision = 3): DisplayChannelStateView {
|
||||
const current = selection("sel-1");
|
||||
return {
|
||||
channel: { groupId: "group-1", id: "chan-1", key: "default" },
|
||||
crossfadeMs: 0,
|
||||
current,
|
||||
playback: {
|
||||
activeTimelineId: "timeline-1",
|
||||
blackout: false,
|
||||
currentSelectionId: current.id,
|
||||
currentSlotId: current.slotId,
|
||||
deadlineAtMs: 5000,
|
||||
pendingTimelineId: null,
|
||||
remainingMs: 5000,
|
||||
revision,
|
||||
selectionRevision: 1,
|
||||
startedAtMs: 0,
|
||||
transport: "playing",
|
||||
},
|
||||
selections: [current],
|
||||
serverNowMs: 0,
|
||||
staticHold: null,
|
||||
timeline: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Server behaviour that a test can change mid-run. */
|
||||
interface Server {
|
||||
sessionFailures: number;
|
||||
stateFailing: boolean;
|
||||
sessionRequests: number;
|
||||
stateRequests: number;
|
||||
}
|
||||
|
||||
describe("a display recovers from every failed request without a reload", () => {
|
||||
let clock: number;
|
||||
let timers: Map<number, { at: number; run: () => void }>;
|
||||
let nextTimer: number;
|
||||
let root: HTMLElement;
|
||||
let local: SignageLocalStore;
|
||||
let server: Server;
|
||||
let host: FakeHost;
|
||||
let subscriptions: { onStatus?: (status: string) => void }[];
|
||||
|
||||
beforeEach(() => {
|
||||
clock = 0;
|
||||
timers = new Map();
|
||||
nextTimer = 1;
|
||||
root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
local = createMemoryStore();
|
||||
server = { sessionFailures: 0, sessionRequests: 0, stateFailing: false, stateRequests: 0 };
|
||||
subscriptions = [];
|
||||
host = createFakeHost({
|
||||
permissions: ["signage.display.view"],
|
||||
routes: [
|
||||
{
|
||||
method: "POST",
|
||||
path: "viewers/session",
|
||||
respond: () => {
|
||||
server.sessionRequests += 1;
|
||||
if (server.sessionFailures > 0) {
|
||||
server.sessionFailures -= 1;
|
||||
throw new TypeError("Failed to fetch");
|
||||
}
|
||||
return jsonResponse(SESSION);
|
||||
},
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channels/chan-1/display-state",
|
||||
respond: () => {
|
||||
server.stateRequests += 1;
|
||||
if (server.stateFailing) {
|
||||
throw new TypeError("Failed to fetch");
|
||||
}
|
||||
return jsonResponse(channelState());
|
||||
},
|
||||
},
|
||||
{ method: "POST", path: /^viewers\/.*\/heartbeat$/u, respond: () => jsonResponse({}) },
|
||||
],
|
||||
});
|
||||
Object.assign(host.context, {
|
||||
realtime: {
|
||||
subscribe: (_channel: string, handlers: { onStatus?: (status: string) => void }) => {
|
||||
subscriptions.push(handlers);
|
||||
return { close: () => undefined };
|
||||
},
|
||||
} satisfies Pick<ModuleUiHostContext["realtime"], "subscribe"> as never,
|
||||
});
|
||||
});
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves virtual time forward, firing every timer that falls due, in order. */
|
||||
async function advance(ms: number): Promise<void> {
|
||||
const end = clock + ms;
|
||||
for (;;) {
|
||||
const due = [...timers]
|
||||
.filter(([, timer]) => timer.at <= end)
|
||||
.sort((left, right) => left[1].at - right[1].at)[0];
|
||||
if (!due) {
|
||||
break;
|
||||
}
|
||||
timers.delete(due[0]);
|
||||
clock = due[1].at;
|
||||
due[1].run();
|
||||
await settle();
|
||||
}
|
||||
clock = end;
|
||||
}
|
||||
|
||||
function build() {
|
||||
return createDisplayController({
|
||||
clearTimer: (handle) => timers.delete(handle as number),
|
||||
context: host.context,
|
||||
decodeImage: () => Promise.resolve(),
|
||||
media: createMemoryMediaCache(),
|
||||
newViewerKey: () => "viewer-fixed-key-0001",
|
||||
now: () => clock,
|
||||
root,
|
||||
setTimer: (run, delayMs) => {
|
||||
const id = nextTimer;
|
||||
nextTimer += 1;
|
||||
timers.set(id, { at: clock + delayMs, run });
|
||||
return id;
|
||||
},
|
||||
store: local,
|
||||
});
|
||||
}
|
||||
|
||||
/** One ordinary live run, so the display has a persisted snapshot to continue from, exactly as a
|
||||
* screen that has been on the wall for a while does. */
|
||||
async function runOnceLive(): Promise<void> {
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
await display.stop();
|
||||
timers.clear();
|
||||
}
|
||||
|
||||
it("registers once the server answers, after its first registration failed", async () => {
|
||||
await runOnceLive();
|
||||
server.sessionFailures = 1;
|
||||
const sessionsBefore = server.sessionRequests;
|
||||
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
// Continuing from its own state while it cannot register: the honest banner.
|
||||
expect(root.dataset.offline).toBe("true");
|
||||
|
||||
await advance(60_000);
|
||||
|
||||
expect(server.sessionRequests - sessionsBefore).toBeGreaterThanOrEqual(2);
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
expect(subscriptions.length).toBeGreaterThanOrEqual(2);
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("keeps retrying registration with backoff, and never gives up", async () => {
|
||||
await runOnceLive();
|
||||
server.sessionFailures = 8;
|
||||
const sessionsBefore = server.sessionRequests;
|
||||
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
// Eight failures back off for at most 1 + 2 + 4 + 8 + 16 + 32 + 60 + 60 seconds, the last two at
|
||||
// the one-minute ceiling. Five virtual minutes is enough for all of them and the success after.
|
||||
await advance(5 * 60_000);
|
||||
|
||||
expect(server.sessionRequests - sessionsBefore).toBe(9);
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("retries a failed state refresh until the server answers, with no realtime nudge", async () => {
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
|
||||
// The slot's deadline refresh fails, as it would mid-restart. Realtime says nothing.
|
||||
server.stateFailing = true;
|
||||
await advance(6_000);
|
||||
expect(root.dataset.offline).toBe("true");
|
||||
const failedRequests = server.stateRequests;
|
||||
|
||||
server.stateFailing = false;
|
||||
await advance(120_000);
|
||||
|
||||
expect(server.stateRequests).toBeGreaterThan(failedRequests);
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("subscribes again when the host reports its realtime stream closed for good", async () => {
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
expect(subscriptions).toHaveLength(1);
|
||||
|
||||
subscriptions[0]?.onStatus?.("closed");
|
||||
await settle();
|
||||
await advance(60_000);
|
||||
|
||||
expect(subscriptions.length).toBeGreaterThanOrEqual(2);
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("schedules nothing after it is stopped", async () => {
|
||||
await runOnceLive();
|
||||
server.sessionFailures = 3;
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
await display.stop();
|
||||
const sessionsAtStop = server.sessionRequests;
|
||||
|
||||
await advance(5 * 60_000);
|
||||
|
||||
expect(server.sessionRequests).toBe(sessionsAtStop);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type DisplayChannelStateView,
|
||||
type DisplayController,
|
||||
} from "../../src/display/controller.js";
|
||||
import type { ViewerSessionResponse } from "../../src/shared/display-protocol.js";
|
||||
import { createFakeHost, jsonResponse } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
@@ -115,14 +114,12 @@ function state(overrides: Partial<DisplayChannelStateView> = {}): DisplayChannel
|
||||
};
|
||||
}
|
||||
|
||||
/** Typed as the shared protocol message, so a stub cannot drift from what the server sends. */
|
||||
const SESSION: ViewerSessionResponse = {
|
||||
const SESSION = {
|
||||
channelId: "chan-1",
|
||||
channelKey: "default",
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
viewerName: "Foyer",
|
||||
};
|
||||
|
||||
describe("display controller", () => {
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
createDisplayController,
|
||||
type DisplayChannelStateView,
|
||||
} from "../../src/display/controller.js";
|
||||
import type { DisplaySelection, ViewerSessionResponse } from "../../src/shared/display-protocol.js";
|
||||
import { createFakeHost, jsonResponse } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
@@ -310,26 +309,14 @@ describe("a display that loses its network", () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** A native selection exactly as the server sends one in channel state. */
|
||||
function nativeSelection(id: string, slotId: string): DisplaySelection {
|
||||
function nativeSelection(id: string, slotId: string): SceneSelection {
|
||||
return {
|
||||
...selection({ id, slotId }),
|
||||
media: {
|
||||
display: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 1080,
|
||||
url: `https://cdn.invalid/${id}?sig=a`,
|
||||
width: 1920,
|
||||
display: { url: `https://cdn.invalid/${id}?sig=a` },
|
||||
thumbnail: { url: `https://cdn.invalid/${id}-t?sig=a` },
|
||||
},
|
||||
thumbnail: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 270,
|
||||
url: `https://cdn.invalid/${id}-t?sig=a`,
|
||||
width: 480,
|
||||
},
|
||||
},
|
||||
stale: false,
|
||||
};
|
||||
} as SceneSelection;
|
||||
}
|
||||
|
||||
function state(currentId: string): DisplayChannelStateView {
|
||||
@@ -386,8 +373,7 @@ describe("a display that loses its network", () => {
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
viewerName: "Foyer",
|
||||
} satisfies ViewerSessionResponse),
|
||||
}),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DISPLAY_ERROR_DETAIL_MAX,
|
||||
parseDisplayHeartbeat,
|
||||
parseViewerSessionRequest,
|
||||
parseViewerSessionResponse,
|
||||
} from "../src/shared/display-protocol.js";
|
||||
|
||||
/**
|
||||
* The rules every display message follows, pinned one by one, because the production failure was
|
||||
* exactly a disagreement about one of them.
|
||||
*/
|
||||
|
||||
const FULL_HEARTBEAT = {
|
||||
cachedAssetCount: 3,
|
||||
error: null,
|
||||
offlineReady: true,
|
||||
reportedContributionId: null,
|
||||
reportedPlaybackRevision: 4,
|
||||
reportedProviderId: "signage.native-images",
|
||||
reportedSelectionId: "sel-1",
|
||||
reportedTimelineId: "timeline-1",
|
||||
};
|
||||
|
||||
describe("display heartbeat", () => {
|
||||
it("accepts null for every nullable field: null is a value, not an omission", () => {
|
||||
const result = parseDisplayHeartbeat({
|
||||
...FULL_HEARTBEAT,
|
||||
reportedContributionId: null,
|
||||
reportedPlaybackRevision: null,
|
||||
reportedProviderId: null,
|
||||
reportedSelectionId: null,
|
||||
reportedTimelineId: null,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
...FULL_HEARTBEAT,
|
||||
reportedContributionId: null,
|
||||
reportedPlaybackRevision: null,
|
||||
reportedProviderId: null,
|
||||
reportedSelectionId: null,
|
||||
reportedTimelineId: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("treats an absent field as not reported, so the receiver keeps what it had", () => {
|
||||
const result = parseDisplayHeartbeat({ offlineReady: false });
|
||||
expect(result).toEqual({ ok: true, value: { offlineReady: false } });
|
||||
});
|
||||
|
||||
it("ignores a field it does not know, so a newer display is never refused by an older server", () => {
|
||||
const result = parseDisplayHeartbeat({ ...FULL_HEARTBEAT, reportedSomethingNew: { a: 1 } });
|
||||
expect(result).toEqual({ ok: true, value: FULL_HEARTBEAT });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["cachedAssetCount", null],
|
||||
["cachedAssetCount", -1],
|
||||
["cachedAssetCount", 1.5],
|
||||
["offlineReady", null],
|
||||
["offlineReady", "yes"],
|
||||
["reportedSelectionId", ""],
|
||||
["reportedSelectionId", "x".repeat(65)],
|
||||
["reportedProviderId", 7],
|
||||
["reportedPlaybackRevision", -1],
|
||||
["error", { code: "" }],
|
||||
["error", { code: "BAD CODE" }],
|
||||
["error", { code: "OK", detail: "y".repeat(DISPLAY_ERROR_DETAIL_MAX + 1) }],
|
||||
["error", "SLIDE_UNRENDERABLE"],
|
||||
])("refuses %s = %j, naming that field and nothing else", (field, value) => {
|
||||
expect(parseDisplayHeartbeat({ ...FULL_HEARTBEAT, [field]: value })).toEqual({
|
||||
field,
|
||||
ok: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a reported error with or without detail", () => {
|
||||
expect(parseDisplayHeartbeat({ error: { code: "SLIDE_UNRENDERABLE", detail: null } })).toEqual({
|
||||
ok: true,
|
||||
value: { error: { code: "SLIDE_UNRENDERABLE", detail: null } },
|
||||
});
|
||||
expect(parseDisplayHeartbeat({ error: { code: "SLIDE_UNRENDERABLE" } })).toEqual({
|
||||
ok: true,
|
||||
value: { error: { code: "SLIDE_UNRENDERABLE", detail: null } },
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses something that is not an object at all", () => {
|
||||
for (const body of [null, [], "heartbeat", 3]) {
|
||||
expect(parseDisplayHeartbeat(body)).toEqual({ field: "body", ok: false });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("viewer session", () => {
|
||||
it("requires a well-formed viewer key", () => {
|
||||
expect(parseViewerSessionRequest({ viewerKey: "kiosk-lobby-0001" })).toEqual({
|
||||
ok: true,
|
||||
value: { viewerKey: "kiosk-lobby-0001" },
|
||||
});
|
||||
for (const viewerKey of [undefined, null, "short", "has spaces in it", "x".repeat(129)]) {
|
||||
expect(parseViewerSessionRequest({ viewerKey })).toEqual({ field: "viewerKey", ok: false });
|
||||
}
|
||||
});
|
||||
|
||||
it("a display accepts only a complete registration", () => {
|
||||
const complete = {
|
||||
channelId: "chan-1",
|
||||
channelKey: "default",
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
viewerName: "New display",
|
||||
};
|
||||
expect(parseViewerSessionResponse(complete)).toEqual({ ok: true, value: complete });
|
||||
const { viewerId: _omitted, ...missing } = complete;
|
||||
expect(parseViewerSessionResponse(missing)).toEqual({ field: "viewerId", ok: false });
|
||||
expect(parseViewerSessionResponse({ ...complete, heartbeatIntervalMs: 0 })).toEqual({
|
||||
field: "heartbeatIntervalMs",
|
||||
ok: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user