Files
Signage/src/shared/display-protocol.ts
T
ekklesiaandClaude Opus 5.5 67d89f1020 fix(display): keep blackout across reloads and follow the display's current assignment
A kiosk that reloaded during a blackout restored its last frame from local
state without the blackout, so the hidden slide flashed on the wall until the
server answered.

A display resolved its channel once, at registration. Moving it to another
group or audience, or deleting the channel it was on, never reached a running
screen: it kept showing the old channel, or fell into offline continuation
against a 404 forever. The display now fetches its state by viewer, so the
server resolves the current assignment on every fetch, and the heartbeat reply
names the assigned channel so a reassignment lands within one heartbeat. A
display removed from the roster registers again once, on backoff; only
Signage's own not-found means removal, so a foreign 404 can never cause a
registration loop. The channel route stays for the preview and for display
code a kiosk cached earlier. A replaced realtime subscription can no longer
schedule a stray resubscription when it reports closing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 21:32:04 -05:00

338 lines
13 KiB
TypeScript

/**
* 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;
/** The channel an administrator has this viewer assigned to now. A display whose own idea of its
* channel differs refetches its state, so a reassignment reaches a running screen within one
* heartbeat. Optional: a display ignores a response without it. */
readonly channelId?: string;
}
/** The assigned channel from a heartbeat response, if it carried a usable one. */
export function assignedChannelOf(raw: unknown): string | undefined {
if (typeof raw !== "object" || raw === null) {
return undefined;
}
const channelId = (raw as { readonly channelId?: unknown }).channelId;
return typeof channelId === "string" && channelId.length > 0 && channelId.length <= 64
? channelId
: undefined;
}
// --- Channel state: GET viewers/:viewerId/display-state (and channels/:channelId/display-state) -----
//
// A registered display asks by its own viewer id, so the server resolves which channel it is assigned
// to at that moment. The channel route remains for the management preview and for display code a
// kiosk cached before the viewer route existed.
/** 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;
}