feat(control): Race Controller Master, one browser runs the race and others follow or take over (1.77.0)
This commit is contained in:
1 parent
54989d8597
commit
cf3a4c5fdb
16 files changed
+316
-9
No files matched your search
+84
-5
@@ -30,6 +30,7 @@ import { renderDashboardView, renderClassesView, renderDriversView, renderCarsVi
|
||||
|
||||
import { renderGuideView, renderOverlayPageView } from "./misc_views.js";
|
||||
import { installAuthFetchGuard, showPinDialog, mountAuthSettings } from "./auth_view.js";
|
||||
import { createRaceController } from "./race_controller.js";
|
||||
import { getSessionsForEventHelper, getModeLabelHelper, normalizeStartModeHelper, getStartModeLabelHelper, getClassNameHelper, getEventNameHelper, renderAssignmentListView, renderSessionsTableView } from "./event_common.js";
|
||||
import { renderEventWorkspaceView } from "./event_workspace_controller.js";
|
||||
import { renderEventManagerMarkup } from "./event_manager_view.js";
|
||||
@@ -282,7 +283,7 @@ const tickClock = () => {
|
||||
if (overlayMode && overlayViewMode === "schedule") renderView();
|
||||
};
|
||||
const buildTeamRaceResultsHtml = (event) => buildTeamRaceResultsHtmlHelper(event, { t, escapeHtml, resolveEventBranding, getClassName, buildPrintBrandBlock, buildTeamRaceStandings, renderTable, formatLap, renderTeamStintLog, renderSessionChannelAnalysis });
|
||||
const connectDecoder = () => connectDecoderHelper({
|
||||
const connectDecoder = () => (!isRaceMaster() ? notifyNotMaster() : connectDecoderHelper({
|
||||
state,
|
||||
t,
|
||||
saveState,
|
||||
@@ -296,7 +297,7 @@ const connectDecoder = () => connectDecoderHelper({
|
||||
getActiveSession,
|
||||
processDecoderMessage,
|
||||
disconnectDecoder,
|
||||
});
|
||||
}));
|
||||
const disconnectDecoder = (options = {}) => disconnectDecoderHelper(options, {
|
||||
state,
|
||||
saveState,
|
||||
@@ -456,7 +457,7 @@ function describeAutopilot(action) {
|
||||
return t(`day.auto_${action.reason}`, { name });
|
||||
}
|
||||
function tickAutopilot() {
|
||||
if (!autopilotDate || overlayMode) return;
|
||||
if (!autopilotDate || overlayMode || !isRaceMaster()) return;
|
||||
const day = getDayPlan(autopilotDate);
|
||||
const rows = buildDayRows(autopilotDate);
|
||||
const busy = Boolean(getPrologueSession() || pendingStartSessionId || startsInProgress > 0 || autopilotLaunchingId
|
||||
@@ -517,7 +518,7 @@ function getDueCallFor(date) {
|
||||
return getDueCall(buildDayRows(date), { day: getDayPlan(date), snoozedUntil: (id) => callSnoozes.get(id) || 0 });
|
||||
}
|
||||
function tickDayCalls() {
|
||||
if (overlayMode) return;
|
||||
if (overlayMode || !isRaceMaster()) return;
|
||||
if (autopilotDate) {
|
||||
const due = getDueCallFor(autopilotDate);
|
||||
if (due) callHeat(due.session.id);
|
||||
@@ -1300,6 +1301,17 @@ const TRANSLATIONS = {
|
||||
"timing.show_live": "Visa den",
|
||||
"overlay.obs_show_position_change": "Placering sedan start (▲/▼) i race",
|
||||
"overlay.obs_show_start": "Startplats bredvid placeringen (TV-grafik)",
|
||||
"controller.you_are_master": "Race Controller Master",
|
||||
"controller.viewer": "Du följer racet. Race Controller Master är {name} (sedan {since}).",
|
||||
"controller.none": "Ingen Race Controller Master just nu.",
|
||||
"controller.take_over": "Ta över som master",
|
||||
"controller.become": "Bli Race Controller Master",
|
||||
"controller.confirm_take_over": "Ta över som Race Controller Master? {name} tappar decodern och kan inte längre starta, pausa eller stoppa heat.",
|
||||
"controller.not_master": "Bara Race Controller Master kan köra racet och decodern. Ta över i rutan högst upp.",
|
||||
"controller.title": "Race Controller Master",
|
||||
"controller.hint": "Bara en dator åt gången kör racet: decodern, start, paus, stopp och autopiloten. De andra följer och kan förbereda förare och race. Den som jobbar som race controller tar över med en knapp, och med admin-PIN krävs inloggning.",
|
||||
"controller.name": "Den här datorns namn",
|
||||
"controller.name_hint": "Visas för de andra, t.ex. Speakerbåset. Tomt = IP-adressen. Sparas bara i den här webbläsaren.",
|
||||
"overlay.col_start": "Start",
|
||||
"overlay.position_change_title": "Placeringar vunna (▲) eller förlorade (▼) sedan starten",
|
||||
"settings.public_address_title": "Publik adress (domän / DynDNS)",
|
||||
@@ -3438,6 +3450,17 @@ const TRANSLATIONS = {
|
||||
"timing.show_live": "Show it",
|
||||
"overlay.obs_show_position_change": "Places since the start (▲/▼) in races",
|
||||
"overlay.obs_show_start": "Start position next to the place (TV graphics)",
|
||||
"controller.you_are_master": "Race Controller Master",
|
||||
"controller.viewer": "You are following the race. Race Controller Master is {name} (since {since}).",
|
||||
"controller.none": "No Race Controller Master right now.",
|
||||
"controller.take_over": "Take over as master",
|
||||
"controller.become": "Become Race Controller Master",
|
||||
"controller.confirm_take_over": "Take over as Race Controller Master? {name} loses the decoder and can no longer start, pause or stop heats.",
|
||||
"controller.not_master": "Only the Race Controller Master can run the race and the decoder. Take over in the box at the top.",
|
||||
"controller.title": "Race Controller Master",
|
||||
"controller.hint": "One computer at a time runs the race: the decoder, start, pause, stop and the autopilot. The others follow and can prepare drivers and races. Whoever works as race controller takes over with one button; with the admin PIN on, a login is needed.",
|
||||
"controller.name": "This computer's name",
|
||||
"controller.name_hint": "Shown to the others, e.g. Speaker booth. Empty = the IP address. Saved in this browser only.",
|
||||
"overlay.col_start": "Start",
|
||||
"overlay.position_change_title": "Places gained (▲) or lost (▼) since the start",
|
||||
"settings.public_address_title": "Public address (domain / DynDNS)",
|
||||
@@ -5456,6 +5479,15 @@ const overlayViewMode = allowedOverlayModes.includes(routeOverlayMode)
|
||||
? queryOverlayMode
|
||||
: "leaderboard";
|
||||
const publicOverlayMode = Boolean(publicOverlayMatch);
|
||||
// Race Controller Master (see race_controller.js). Overlay windows never run the race.
|
||||
const CONTROLLER_NAME_KEY = "rc_controller_name";
|
||||
const readControllerName = () => { try { return localStorage.getItem(CONTROLLER_NAME_KEY) || ""; } catch { return ""; } };
|
||||
const raceController = overlayMode ? null : createRaceController({
|
||||
getName: readControllerName,
|
||||
onChange: () => renderControllerBanner(),
|
||||
onLost: () => { disconnectDecoder({ silent: true }); renderView(); },
|
||||
});
|
||||
const isRaceMaster = () => Boolean(raceController?.isMaster());
|
||||
const state = loadState();
|
||||
const sessionReplay = createSessionReplayRuntime();
|
||||
const requestedView = String(urlParams.get("view") || "").toLowerCase();
|
||||
@@ -5788,7 +5820,7 @@ async function init() {
|
||||
document.getElementById("appUpdateAvailable")?.addEventListener("click", navigateToSettings);
|
||||
setInterval(() => refreshUpdateStatus({ render: currentView === "settings" }), 20 * 60 * 1000);
|
||||
|
||||
Promise.allSettled([hydrateFromBackend({ initial: true }), loadAmmcConfigFromBackend(), refreshServerBackups({ render: false }), refreshUpdateStatus({ render: false })]).finally(() => {
|
||||
Promise.allSettled([hydrateFromBackend({ initial: true }), loadAmmcConfigFromBackend(), refreshServerBackups({ render: false }), refreshUpdateStatus({ render: false }), raceController?.start()]).finally(() => {
|
||||
initialLoadDone = true;
|
||||
applyTheme();
|
||||
renderNav();
|
||||
@@ -5815,6 +5847,49 @@ async function init() {
|
||||
|
||||
}
|
||||
|
||||
// Banner for a browser that is not the Race Controller Master (and a sidebar badge for the
|
||||
// one that is). The take-over asks first and needs the admin PIN when one is set.
|
||||
function renderControllerBanner() {
|
||||
const banner = document.getElementById("controllerBanner");
|
||||
const badge = document.getElementById("controllerBadge");
|
||||
if (!banner || !raceController) return;
|
||||
const status = raceController.getStatus();
|
||||
const master = raceController.isMaster();
|
||||
if (badge) {
|
||||
badge.hidden = !master || status.unreachable;
|
||||
badge.textContent = `🎙 ${t("controller.you_are_master")}`;
|
||||
}
|
||||
banner.hidden = master;
|
||||
if (master) return;
|
||||
const since = status.master ? new Date(status.master.since).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "";
|
||||
const text = status.master ? t("controller.viewer", { name: status.master.name || "?", since }) : t("controller.none");
|
||||
const button = t(status.master ? "controller.take_over" : "controller.become");
|
||||
if (banner.dataset.text === text + button) return;
|
||||
banner.dataset.text = text + button;
|
||||
banner.innerHTML = `<span>👁 ${escapeHtml(text)}</span> <button class="btn btn-mini btn-primary" type="button" id="controllerTakeOver">${escapeHtml(button)}</button>`;
|
||||
banner.querySelector("#controllerTakeOver").addEventListener("click", takeOverRaceControl);
|
||||
}
|
||||
|
||||
async function takeOverRaceControl() {
|
||||
const status = raceController?.getStatus();
|
||||
if (!raceController || (status?.master && !window.confirm(t("controller.confirm_take_over", { name: status.master.name || "?" })))) return;
|
||||
const result = await raceController.claim(Boolean(status?.master));
|
||||
if (!result.ok) return;
|
||||
if (state.settings.wsUrl && state.settings.autoReconnect && !state.decoder.connected) connectDecoder();
|
||||
renderView();
|
||||
}
|
||||
|
||||
// Returns the message, for callers that show it themselves (Race Day's start).
|
||||
function notifyNotMaster() {
|
||||
const banner = document.getElementById("controllerBanner");
|
||||
if (banner) {
|
||||
banner.classList.remove("is-flash");
|
||||
void banner.offsetWidth;
|
||||
banner.classList.add("is-flash");
|
||||
}
|
||||
return t("controller.not_master");
|
||||
}
|
||||
|
||||
function updateSyncStatus() {
|
||||
const container = document.getElementById("syncStatus");
|
||||
if (!container) return;
|
||||
@@ -6129,6 +6204,7 @@ function saveState(options = {}) {
|
||||
async function startOperationalSession(session, callbacks = {}) {
|
||||
session = currentSession(session);
|
||||
if (!session) return { ok: false, message: t("race_day.start_failed") };
|
||||
if (!isRaceMaster()) return { ok: false, message: notifyNotMaster() };
|
||||
const { requirePreflight = false, onTone, ...sequenceCallbacks } = callbacks;
|
||||
if (session.mode === "track") {
|
||||
const validation = validateTrackSessionForStart(session);
|
||||
@@ -6213,6 +6289,7 @@ function saveOperationalLapWindow(session, minLapSec, maxLapSec) {
|
||||
function finishOperationalSession(session) {
|
||||
session = currentSession(session);
|
||||
if (!session) return false;
|
||||
if (!isRaceMaster()) { notifyNotMaster(); return false; }
|
||||
cancelRaceStart();
|
||||
state.activeSessionId = session.id;
|
||||
finishSessionControl(session);
|
||||
@@ -6226,6 +6303,7 @@ function finishOperationalSession(session) {
|
||||
|
||||
function pauseOperationalSession(session) {
|
||||
session = currentSession(session);
|
||||
if (!isRaceMaster()) { notifyNotMaster(); return false; }
|
||||
if (!pauseSessionControl(session)) return false;
|
||||
triggerRaceAudio("race_paused", { interrupt: true, force: true, logData: { raceId: session.eventId, sessionId: session.id } });
|
||||
saveState();
|
||||
@@ -6235,6 +6313,7 @@ function pauseOperationalSession(session) {
|
||||
|
||||
function resumeOperationalSession(session) {
|
||||
session = currentSession(session);
|
||||
if (!isRaceMaster()) { notifyNotMaster(); return false; }
|
||||
if (!resumeSessionControl(session)) return false;
|
||||
triggerRaceAudio("race_resumed", { interrupt: true, force: true, logData: { raceId: session.eventId, sessionId: session.id } });
|
||||
saveState();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Race Controller Master: only one browser tab at a time runs the race - the decoder
|
||||
// connection, start, pause, finish and the autopilot. Other admin browsers follow and can
|
||||
// prepare (drivers, races) and take over with one click. The lock lives on the server
|
||||
// (/api/controller); the master renews it every 5 s.
|
||||
const HEARTBEAT_MS = 5000;
|
||||
const CLIENT_KEY = "rc_controller_client_id";
|
||||
|
||||
function readClientId() {
|
||||
const fresh = `tab_${Math.random().toString(36).slice(2, 12)}`;
|
||||
try {
|
||||
// sessionStorage: a reload keeps the tab's id (and so its master role), a new tab gets its own.
|
||||
const stored = sessionStorage.getItem(CLIENT_KEY);
|
||||
if (stored) return stored;
|
||||
sessionStorage.setItem(CLIENT_KEY, fresh);
|
||||
} catch { /* private mode: one id for this page load */ }
|
||||
return fresh;
|
||||
}
|
||||
|
||||
export function createRaceController({ getName = () => "", onChange = () => {}, onLost = () => {}, intervalMs = HEARTBEAT_MS } = {}) {
|
||||
const clientId = readClientId();
|
||||
// unreachable: without the server's answer the tab keeps working as before (one laptop, no lock).
|
||||
let status = { master: null, unreachable: true };
|
||||
let timer = null;
|
||||
|
||||
const isMaster = () => status.unreachable || status.master?.clientId === clientId;
|
||||
const apply = (next) => {
|
||||
const wasMaster = isMaster();
|
||||
status = next;
|
||||
if (wasMaster && !isMaster()) onLost(status.master);
|
||||
onChange(status);
|
||||
};
|
||||
const request = async (path, body) => {
|
||||
try {
|
||||
const response = await fetch(path, body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {});
|
||||
if (response.status === 401 || response.status === 403) return { denied: true };
|
||||
const data = await response.json();
|
||||
return response.ok || response.status === 409 ? { data } : { failed: true };
|
||||
} catch {
|
||||
return { failed: true };
|
||||
}
|
||||
};
|
||||
const refresh = async () => {
|
||||
const result = await request("/api/controller");
|
||||
if (result.data) apply({ master: result.data.master, unreachable: false });
|
||||
};
|
||||
const claim = async (force = false) => {
|
||||
const result = await request("/api/controller/claim", { clientId, name: getName(), force });
|
||||
if (result.data) apply({ master: result.data.master, unreachable: false });
|
||||
return { ok: isMaster(), denied: Boolean(result.denied) };
|
||||
};
|
||||
const tick = async () => {
|
||||
// The master renews; a viewer only follows (it never grabs a lapsed lock on its own).
|
||||
if (!status.unreachable && status.master?.clientId === clientId) await claim();
|
||||
else await refresh();
|
||||
};
|
||||
|
||||
return {
|
||||
clientId,
|
||||
isMaster,
|
||||
getStatus: () => status,
|
||||
claim,
|
||||
// On load: become master when nobody is, or when this tab already was (a reload).
|
||||
async start({ autoClaim = true } = {}) {
|
||||
await refresh();
|
||||
if (autoClaim && !status.unreachable && (!status.master || status.master.clientId === clientId)) await claim();
|
||||
clearInterval(timer);
|
||||
timer = setInterval(tick, intervalMs);
|
||||
},
|
||||
stop() { clearInterval(timer); },
|
||||
};
|
||||
}
|
||||
@@ -464,6 +464,17 @@ export function renderSettings(deps) {
|
||||
<div class="panel-body" id="authSettings"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel mt-16" id="settingsController">
|
||||
<div class="panel-header"><h3>🎙 ${t("controller.title")}</h3></div>
|
||||
<div class="panel-body">
|
||||
<p class="hint">${t("controller.hint")}</p>
|
||||
<label>${t("controller.name")}
|
||||
<input id="controllerName" maxlength="60" value="${escapeHtml((() => { try { return localStorage.getItem("rc_controller_name") || ""; } catch { return ""; } })())}" />
|
||||
<small>${t("controller.name_hint")}</small>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel mt-16" id="settingsPublicAddress">
|
||||
<div class="panel-header"><div><h3>${t("settings.public_address_title")}</h3><p class="hint">${t("settings.public_address_hint")}</p></div></div>
|
||||
<div class="panel-body">
|
||||
@@ -621,6 +632,10 @@ Erik Eriksson;654321;4WD;Associated;;</code></pre>
|
||||
pendingSettingsFocusId = "";
|
||||
}
|
||||
mountAuthSettings(document.getElementById("authSettings"), { t, escapeHtml });
|
||||
// Per computer, not in the shared settings: sent with the next heartbeat of the master lock.
|
||||
document.getElementById("controllerName")?.addEventListener("change", (event) => {
|
||||
try { localStorage.setItem("rc_controller_name", event.target.value.trim()); } catch { /* storage blocked */ }
|
||||
});
|
||||
mountTtsSettings(document.getElementById("ttsSettings"), { state, t, escapeHtml, saveState, speakText });
|
||||
mountDecoderSimSettings(document.getElementById("decoderSimSettings"), { state, t, escapeHtml, getBackendUrl, saveState, connectDecoder, renderView });
|
||||
|
||||
|
||||
@@ -4932,3 +4932,11 @@ tr:has(> td > .medal-3) { background: linear-gradient(90deg, rgba(205, 127, 60,
|
||||
.obs-tv-foot { padding: 0.15em 0.5em; background: rgb(10 12 18 / 92%); font-size: 0.7em; font-weight: 600; letter-spacing: 0.04em; }
|
||||
.obs-tv-foot strong { color: #d39bff; }
|
||||
.obs-tv-empty { margin: 0; padding: 0.4em 0.6em; background: rgb(17 21 30 / 88%); }
|
||||
|
||||
/* Race Controller Master: banner for the browsers that follow, badge for the master. */
|
||||
.controller-banner { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0 0 10px; padding: 8px 12px; border: 1px solid var(--accent); border-radius: 8px; background: color-mix(in srgb, var(--accent) 12%, var(--panel)); color: var(--text); font-size: 0.85rem; }
|
||||
.controller-banner[hidden] { display: none; }
|
||||
.controller-banner.is-flash { animation: controller-flash 0.9s ease 2; }
|
||||
@keyframes controller-flash { 50% { background: color-mix(in srgb, var(--accent) 45%, var(--panel)); } }
|
||||
.controller-badge { background: color-mix(in srgb, var(--accent) 22%, var(--panel)); color: var(--text); }
|
||||
.controller-badge[hidden] { display: none; }
|
||||
Reference in new issue
Block a user