fix(sync): a browser that is not the race master can't change heats, laps or the active heat (1.89.38)

This commit is contained in:
larssand committed 2026-11-15 16:55:58 +01:00
1 parent cea278518e
commit 5928ce847b
8 files changed
+76 -10

No files matched your search

+6
View File
@@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet.
## 1.89.38
### Fixed
- A second computer that only shows the race (not the Race Controller Master) can no longer change the race control. Picking a heat to look at, or any other save from it, sent its whole copy to the server - and moved the active heat for everyone, or with an older copy put heats back. Saves now carry the browser's controller id, and while a master is live the server keeps the master's race control from any other browser's save: the active heat, each heat's status and clock, the laps, and heats that have run (also when they are missing from the copy). Edits to drivers, classes, heat grids and the like from that computer still save; judging corrections already go their own way.
## 1.89.37
### Fixed
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.89.37",
"version": "1.89.38",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.89.37",
"version": "1.89.38",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.89.37",
"version": "1.89.38",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+6 -2
View File
@@ -6,7 +6,7 @@ const { spawn, execFile } = require("child_process");
const express = require("express");
const QRCode = require("qrcode");
const Database = require("better-sqlite3");
const { keepStartedSessions } = require("./server/session_guard.js");
const { keepStartedSessions, keepRaceControl } = require("./server/session_guard.js");
const publicTrainingProfile = require("./server/public_training_profile");
const { createBackupService } = require("./server/backup_service");
const { createAuth, COOKIE_NAME: AUTH_COOKIE_NAME, TOKEN_MAX_AGE_MS } = require("./server/auth");
@@ -508,7 +508,11 @@ app.post("/api/state", (req, res) => {
}
const stored = readStoredAppState();
const { state: guarded, kept } = keepStartedSessions(req.body, stored?.state);
// Not the master (a second computer showing the race): the race control stays the master's.
const master = liveController();
const clientId = String(req.query?.client || "");
const fromFollower = Boolean(master && clientId && clientId !== master.clientId);
const { state: guarded, kept } = keepStartedSessions(fromFollower ? keepRaceControl(req.body, stored?.state) : req.body, stored?.state);
if (kept.length) console.log(`[state] Kept ${kept.length} run heat(s) a save from an older copy tried to put back to ready: ${kept.join(", ")}`);
const stateJson = JSON.stringify(protectRecentSessionResults(guarded, stored));
const nowIso = new Date().toISOString();
+30 -1
View File
@@ -32,4 +32,33 @@ function keepStartedSessions(incoming, stored) {
return { state: incoming, kept };
}
module.exports = { keepStartedSessions };
// A save from a browser that is not the Race Controller Master (a second computer that only
// shows the race): it may change drivers, classes, heat grids and so on, but the race control
// stays the master's - which heat is active, each heat's status and clock, and the laps. Judging
// corrections from that browser go through /api/session-results, not through this save.
const RACE_CONTROL_FIELDS = ["status", "startedAt", "endedAt", "finishedByTimer", "pausedAt", "totalPausedMs", "followUpStartedAt", "followUpPausedMs", "finishWaitUntil", "resultsResetAt", "audioAnnouncements", "trackLayoutId", "calledAt"];
function keepRaceControl(incoming, stored) {
if (!incoming || typeof incoming !== "object" || !stored || typeof stored !== "object") return incoming;
incoming.activeSessionId = stored.activeSessionId ?? null;
if (stored.resultsBySession && typeof stored.resultsBySession === "object") incoming.resultsBySession = stored.resultsBySession;
const storedById = new Map((Array.isArray(stored.sessions) ? stored.sessions : []).filter((session) => session?.id).map((session) => [session.id, session]));
if (Array.isArray(incoming.sessions)) {
incoming.sessions = incoming.sessions.map((session) => {
const before = storedById.get(session?.id);
if (!before) return session;
const merged = { ...session };
RACE_CONTROL_FIELDS.forEach((field) => { if (field in before) merged[field] = before[field]; else delete merged[field]; });
return merged;
});
// A heat that has run and is missing from the copy: the copy is older (or a heat with laps
// was deleted from the wrong computer) - it stays.
const present = new Set(incoming.sessions.map((session) => session?.id));
storedById.forEach((session, id) => {
if (!present.has(id) && (session.startedAt || Object.keys(stored.resultsBySession?.[id]?.competitors || {}).length)) incoming.sessions.push(session);
});
}
return incoming;
}
module.exports = { keepStartedSessions, keepRaceControl };
+1 -1
View File
@@ -281,7 +281,7 @@ const hydrateFromBackend = ({ initial = false } = {}) => hydrateFromBackendHelpe
const isRunningRaceHere = () => !overlayMode && Boolean(getPrologueSession() || pendingStartSessionId || startsInProgress > 0
|| (state.decoder?.connected && state.sessions.some((session) => ["running", "paused"].includes(session.status))));
const scheduleBackendSync = createBackendSyncScheduler({ sync: () => syncStateToBackend(), isHidden: () => document.hidden });
const syncStateToBackendOnce = () => syncStateToBackendHelper({ backend, t, getBackendUrl, buildPersistableState, getLocalStateVersion: () => localStateVersion, getSyncedStateVersion: () => syncedStateVersion, setSyncedStateVersion: (value) => { syncedStateVersion = value; }, getLocalStateDirty: () => localStateDirty, setLocalStateDirty: (value) => { localStateDirty = value; } });
const syncStateToBackendOnce = () => syncStateToBackendHelper({ backend, t, getBackendUrl, buildPersistableState, getClientId: () => raceController?.clientId || "", getLocalStateVersion: () => localStateVersion, getSyncedStateVersion: () => syncedStateVersion, setSyncedStateVersion: (value) => { syncedStateVersion = value; }, getLocalStateDirty: () => localStateDirty, setLocalStateDirty: (value) => { localStateDirty = value; } });
// A save that fails (server restarting, network gone) is tried again every 5 s until it gets
// through, so "Changes waiting to save" never hangs when nothing else changes.
let syncRetryTimer = null;
+5 -2
View File
@@ -227,11 +227,14 @@ export function createBackendSyncScheduler({ sync, isHidden = () => false, delay
};
}
export async function syncStateToBackendHelper({ backend, t, getBackendUrl, buildPersistableState, getLocalStateVersion, getSyncedStateVersion, setSyncedStateVersion, setLocalStateDirty }) {
// getClientId: this tab's Race Controller id - the server keeps the race control (heat status,
// laps, the active heat) out of saves from a browser that is not the master.
export async function syncStateToBackendHelper({ backend, t, getBackendUrl, buildPersistableState, getLocalStateVersion, getSyncedStateVersion, setSyncedStateVersion, setLocalStateDirty, getClientId = () => "" }) {
backend.pendingWrites = (backend.pendingWrites || 0) + 1;
const syncVersion = getLocalStateVersion();
try {
const res = await fetch(`${getBackendUrl()}/api/state`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(buildPersistableState()) });
const clientId = getClientId();
const res = await fetch(`${getBackendUrl()}/api/state${clientId ? `?client=${encodeURIComponent(clientId)}` : ""}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(buildPersistableState()) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
backend.available = true;
backend.lastError = "";
+25 -1
View File
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const { keepStartedSessions } = require("../server/session_guard.js");
const { keepStartedSessions, keepRaceControl } = require("../server/session_guard.js");
const stored = () => ({
sessions: [
@@ -51,3 +51,27 @@ test("normal progress, new and deleted heats pass through untouched", () => {
assert.deepEqual(state.sessions.map((session) => session.id), ["a2", "a3", "new"], "a1 deleted on purpose stays deleted");
assert.equal(keepStartedSessions(null, stored()).state, null);
});
test("a save from the computer that is not master keeps the master's race control but its other edits", () => {
const master = { ...stored(), activeSessionId: "a2", sessions: [...stored().sessions, { id: "q1", status: "finished", startedAt: 50, endedAt: 90 }] };
master.resultsBySession.q1 = { competitors: { k: { laps: 9 } } };
const slaveCopy = {
activeSessionId: "a3",
drivers: [{ id: "d1", name: "Renamed on the slave" }],
// older copy: a2 not started yet, a3 picked to look at, q1 missing, a new heat added
sessions: [{ id: "a1", status: "finished", startedAt: 100, endedAt: 400, name: "A final 1" }, { id: "a2", status: "ready", startedAt: null, driverIds: ["d1", "d2"] }, { id: "a3", status: "ready", calledAt: 5 }, { id: "b1", status: "ready" }],
resultsBySession: {},
};
const state = keepRaceControl(slaveCopy, master);
assert.equal(state.activeSessionId, "a2", "looking at a heat on the slave doesn't move the master's focus");
assert.equal(state.drivers[0].name, "Renamed on the slave");
const a2 = state.sessions.find((session) => session.id === "a2");
assert.equal(a2.status, "running");
assert.equal(a2.startedAt, 500);
assert.deepEqual(a2.driverIds, ["d1", "d2"], "the grid edit from the slave is kept");
assert.equal("calledAt" in state.sessions.find((session) => session.id === "a3"), false);
assert.ok(state.sessions.some((session) => session.id === "b1"), "a heat added on the slave is kept");
assert.ok(state.sessions.some((session) => session.id === "q1"), "a run heat missing from the old copy is not deleted");
assert.equal(state.resultsBySession.q1.competitors.k.laps, 9);
assert.equal(state.resultsBySession.a1.competitors.k.laps, 14);
});