Changes in real time
Connect a SignalR client with the JSON protocol to /live and invoke WatchSync(sessionId, 1). The number is the version of this protocol. One connection follows one race. The server then sends three messages:
| Message | When and what |
Sync | The answer to WatchSync and Resync, and whenever a change does not fit in a delta. The complete state when status is Live. |
Delta | One change: the complete new result rows of the competitors it concerns. |
Beacon | About every 30 seconds: what a reader that missed nothing has now. |
The status of a Sync or Beacon is Live, Deleted (the organizer deleted the race) or Awaiting (the server has no state: the race is not published yet, the server has restarted and waits for the publisher, or the ID is unknown).
A delta: bib 1 started in Run 1.
{
"generation": "d1e8773d12ba6801",
"baseRevision": 1,
"revision": 2,
"version": 2,
"updatedAt": "2026-11-24T10:03:22+02:00",
"paused": false,
"runs": [
{
"number": 1,
"results": [
{
"bib": 1,
"status": "OnCourse",
"hundredths": null,
"rank": null,
"difference": null,
"at": "2026-11-24T10:03:22+02:00",
"startedAt": "2026-11-24T10:03:22+02:00",
"startSourceTicks": "639000000000000000",
"finishSourceTicks": null,
"intermediates": null,
"totalHundredths": null,
"totalRank": null,
"totalDifference": null
}
]
}
]
}
A beacon:
{
"status": "Live",
"generation": "d1e8773d12ba6801",
"revision": 2
}
The server also sends Radio and Viewers to its own race page. They are not part of this API; ignore them and any other message you do not know.
JavaScript, .NET, Java
The three readers do the same: without a session they list the races, with one they follow it until it is deleted. They recover from lost messages, broken connections and server restarts, and the project tests the JavaScript and .NET readers against the real server. They are on GitHub, free to use under the MIT license.
SignalR clients for other languages work too, if they support the JSON protocol.
JavaScript
Node.js 22 or later, package @microsoft/signalr.
npm install @microsoft/signalr@10
node live-reader.mjs https://live.openskiti.me SESSION_ID
Show live-reader.mjs
// OpenSkiTime Live API reader for Node.js 22 or later. MIT license. https://openskiti.me/live-api/
//
// npm install @microsoft/signalr@10
// node live-reader.mjs lists the races published now
// node live-reader.mjs https://live.openskiti.me <sessionId> follows one race
import { pathToFileURL } from 'node:url';
/** The state of one race, kept up to date from the messages of the server. */
export class RaceState {
phase = 'subscribing'; // subscribing, live, awaiting or deleted
generation = null;
revision = 0;
state = null;
resyncSince = null; // When the complete state was asked for, or null.
/** A new connection: the previous state stays until the subscription is answered. */
connected() { Object.assign(this, { phase: 'subscribing', generation: null, revision: 0, resyncSince: null }); }
/** The complete state, or the reason why there is none. Always the newest on this connection. */
sync(message) {
const live = message.status === 'Live';
this.resyncSince = null;
this.phase = live ? 'live' : message.status === 'Deleted' ? 'deleted' : 'awaiting';
this.generation = live ? message.generation : null;
this.revision = live ? message.revision : 0;
if (live) this.state = message.state;
else if (this.phase === 'deleted') this.state = null;
return 'changed';
}
/** One change. It applies only to the revision it names. */
delta(message, now = Date.now()) {
if (this.phase === 'subscribing' || this.resyncSince !== null) return 'none';
if (this.phase !== 'live' || message.generation !== this.generation) return this.#resync(now);
if (message.revision <= this.revision) return 'none';
if (message.baseRevision !== this.revision) return this.#resync(now);
const next = merge(this.state, message);
if (!next) return this.#resync(now);
this.revision = message.revision;
this.state = next;
return 'changed';
}
/** What the server has now: confirms the state, or shows that a message was missed. */
beacon(message, now = Date.now()) {
if (this.phase === 'subscribing') return 'none';
if (this.resyncSince !== null) return now - this.resyncSince >= 30000 ? this.#resync(now) : 'none';
const agrees = message.status === 'Live'
? this.phase === 'live' && message.generation === this.generation && message.revision === this.revision
: this.phase === (message.status === 'Deleted' ? 'deleted' : 'awaiting');
return agrees ? 'none' : this.#resync(now);
}
#resync(now) { this.resyncSince = now; return 'resync'; }
}
/** The state after a delta, or null when the delta does not fit it. */
export function merge(state, delta) {
if (delta.runs.some(change => !state.runs.some(run => run.number === change.number))) return null;
const runs = [];
for (const run of state.runs) {
const change = delta.runs.find(x => x.number === run.number);
if (!change) { runs.push(run); continue; }
const rows = new Map(run.results.map(row => [row.bib, row]));
for (const row of change.results) rows.set(row.bib, row); // A Map keeps known rows in place and appends new ones.
const order = change.order ?? [...rows.keys()];
if (order.length !== rows.size || new Set(order).size !== order.length || order.some(bib => !rows.has(bib))) return null;
runs.push({ ...run, results: order.map(bib => rows.get(bib)), forerunners: change.forerunners ?? run.forerunners });
}
return { ...state, version: delta.version, updatedAt: delta.updatedAt, paused: delta.paused, runs };
}
/** What happened between two states: status changes, intermediate times and corrected run times. */
export function changes(before, after) {
const result = [];
for (const run of after.runs) {
const rows = new Map((before.runs.find(x => x.number === run.number)?.results ?? []).map(row => [row.bib, row]));
for (const row of run.results) {
const old = rows.get(row.bib) ?? { status: 'Ready', hundredths: null, intermediates: null };
const at = { run: run.number, row };
const status = row.status !== old.status ? [{ ...at, kind: 'status', from: old.status }]
: row.status === 'Finished' && row.hundredths !== old.hundredths ? [{ ...at, kind: 'time' }] : [];
const times = new Map((row.intermediates ?? []).map(x => [x.number, x.hundredths]));
const oldTimes = new Map((old.intermediates ?? []).map(x => [x.number, x.hundredths]));
const intermediates = [...new Set([...oldTimes.keys(), ...times.keys()])].sort((a, b) => a - b)
.filter(number => times.get(number) !== oldTimes.get(number))
.map(number => ({ ...at, kind: 'intermediate', number, hundredths: times.get(number) ?? null }));
// When a break in the connection joined several changes, a start comes before and a finish after the intermediates.
result.push(...(row.status === 'OnCourse' ? [...status, ...intermediates] : [...intermediates, ...status]));
}
}
return result;
}
/** Follows one race until it is deleted. Calls onState(state, changes) after every change and onStatus(phase) without state. */
export async function follow(server, sessionId, onState, onStatus) {
const { HubConnectionBuilder, LogLevel } = await import('@microsoft/signalr');
const race = new RaceState();
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
for (let attempt = 0; ;) {
const hub = new HubConnectionBuilder().withUrl(`${server}/live`).configureLogging(LogLevel.None).build();
const closed = new Promise(resolve => hub.onclose(resolve));
let lastResync = 0;
const handle = step => message => {
const before = race.state, outcome = step(message);
if (outcome === 'changed') {
if (race.phase === 'live') onState(race.state, before ? changes(before, race.state) : []);
else onStatus(race.phase);
if (race.phase === 'deleted') hub.stop();
} else if (outcome === 'resync') {
const delay = Math.max(500 + Math.random() * 4500, lastResync + 3000 - Date.now());
setTimeout(() => {
if (race.resyncSince === null || hub.state !== 'Connected') return;
lastResync = Date.now();
hub.send('Resync').catch(() => { /* The connection broke; the loop connects again. */ });
}, delay);
}
};
hub.on('Sync', handle(message => race.sync(message)));
hub.on('Delta', handle(message => race.delta(message)));
hub.on('Beacon', handle(message => race.beacon(message)));
race.connected();
let connected = false;
try {
await hub.start();
connected = true;
await hub.invoke('WatchSync', sessionId, 1);
attempt = 0;
await closed;
} catch (error) {
if (connected && hub.state === 'Connected') throw error; // The server refused the subscription.
}
if (race.phase === 'deleted') return;
await wait(Math.min(15000, 1000 * 2 ** attempt++) * (0.5 + Math.random() / 2));
}
}
/** Hundredths as 50.12 or 1:02.03, with integer arithmetic. */
export function time(hundredths) {
const minutes = Math.floor(hundredths / 6000), seconds = Math.floor(hundredths / 100) % 60;
const rest = String(hundredths % 100).padStart(2, '0');
return minutes > 0 ? `${minutes}:${String(seconds).padStart(2, '0')}.${rest}` : `${seconds}.${rest}`;
}
function describe(change) {
const { row } = change;
if (change.kind === 'intermediate')
return `Intermediate ${change.number} ${change.hundredths === null ? 'removed' : time(change.hundredths)}`;
if (row.status === 'Finished') return `${change.kind === 'time' ? 'Time changed' : 'Finished'} ${time(row.hundredths)}, rank ${row.rank}`;
return row.status;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const [server = 'https://live.openskiti.me', sessionId] = process.argv.slice(2);
if (!sessionId) {
// The hosted service sleeps between races: the first answer can take a couple of minutes.
const response = await fetch(`${server}/api/sessions`, { signal: AbortSignal.timeout(120000) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const races = await response.json();
if (races.length === 0) console.log('No race is published now.');
for (const race of races) console.log(`${race.sessionId} | ${race.date} | ${race.discipline} | ${race.name}`);
} else {
let named = false;
await follow(server, sessionId, (state, list) => {
if (!named) console.log(`Race | ${state.competition.name} | ${state.competitors.length} competitors`);
named = true;
for (const change of list) {
const who = state.competitors.find(x => x.bib === change.row.bib);
console.log(`Run ${change.run} | ${change.row.bib} ${who?.lastName ?? ''} ${who?.firstName ?? ''} | ${describe(change)}`);
}
}, phase => console.log(phase === 'deleted' ? 'Deleted' : 'Waiting for the publisher'));
}
}
live-reader.mjs on GitHub ↗
.NET
.NET 10 or later, package Microsoft.AspNetCore.SignalR.Client. The file runs as it is, in a folder of its own:
dotnet run live-reader.cs -- https://live.openskiti.me SESSION_ID
Show live-reader.cs
#:package Microsoft.AspNetCore.SignalR.Client@10.0.15
#:property PublishAot=false
// OpenSkiTime Live API reader for .NET 10 or later. MIT license. https://openskiti.me/live-api/
// Save this file in a folder of its own.
//
// dotnet run live-reader.cs lists the races published now
// dotnet run live-reader.cs -- https://live.openskiti.me <sessionId> follows one race
using System.Net.Http.Json;
using System.Text;
using Microsoft.AspNetCore.SignalR.Client;
Console.OutputEncoding = new UTF8Encoding(false);
var server = args.Length > 0 ? args[0] : "https://live.openskiti.me";
if (args.Length < 2)
{
// The hosted service sleeps between races: the first answer can take a couple of minutes.
using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
var races = await http.GetFromJsonAsync<Race[]>($"{server}/api/sessions") ?? [];
if (races.Length == 0) { Console.WriteLine("No race is published now."); }
foreach (var race in races) { Console.WriteLine($"{race.SessionId} | {race.Date} | {race.Discipline} | {race.Name}"); }
return;
}
var named = false;
await LiveReader.FollowAsync(server, args[1], (state, changes) =>
{
if (!named) { Console.WriteLine($"Race | {state.Competition.Name} | {state.Competitors.Length} competitors"); }
named = true;
foreach (var change in changes)
{
var who = state.Competitors.FirstOrDefault(x => x.Bib == change.Row.Bib);
Console.WriteLine($"Run {change.Run} | {change.Row.Bib} {who?.LastName} {who?.FirstName} | {Describe(change)}");
}
}, phase => Console.WriteLine(phase == Phase.Deleted ? "Deleted" : "Waiting for the publisher"));
static string Describe(Change change) => change.Kind switch
{
ChangeKind.Intermediate => $"Intermediate {change.Number} {(change.Hundredths is { } x ? Time(x) : "removed")}",
_ when change.Row.Status != "Finished" => change.Row.Status,
_ => $"{(change.Kind == ChangeKind.Time ? "Time changed" : "Finished")} {Time(change.Row.Hundredths ?? 0)}, rank {change.Row.Rank}"
};
// Hundredths as 50.12 or 1:02.03, with integer arithmetic.
static string Time(long x) => x >= 6000 ? $"{x / 6000}:{x / 100 % 60:00}.{x % 100:00}" : $"{x / 100}.{x % 100:00}";
// The messages. Properties not listed here are ignored; add the ones you need.
record Race(Guid SessionId, string Name, string Discipline, string Date);
record Competition(string Name, string Discipline, string Date, string Codex);
record Competitor(int Bib, string LastName, string FirstName, string Nation, string Club, string FisCode, string Category);
record Intermediate(int Number, long Hundredths);
record Forerunner(string Letter, string LastName, string FirstName, string Nation, string Status);
record Row(int Bib, string Status, long? Hundredths, int? Rank, long? Difference, DateTimeOffset At, DateTimeOffset? StartedAt,
Intermediate[]? Intermediates, long? TotalHundredths, int? TotalRank, long? TotalDifference);
record Run(int Number, int[] StartOrder, Row[] Results, Forerunner[]? Forerunners);
record State(long Version, Competition Competition, Competitor[] Competitors, int CurrentRun, Run[] Runs, DateTimeOffset UpdatedAt, bool Paused);
record SyncMessage(string Status, string? Generation, long Revision, State? State);
record RunDelta(int Number, Row[] Results, int[]? Order, Forerunner[]? Forerunners);
record DeltaMessage(string Generation, long BaseRevision, long Revision, long Version, DateTimeOffset UpdatedAt, bool Paused, RunDelta[] Runs);
record BeaconMessage(string Status, string? Generation, long Revision);
enum Phase { Subscribing, Live, Awaiting, Deleted }
enum Outcome { None, Changed, Resync }
enum ChangeKind { Status, Time, Intermediate }
record Change(int Run, Row Row, ChangeKind Kind, int Number = 0, long? Hundredths = null);
/// <summary>The state of one race, kept up to date from the messages of the server.</summary>
sealed class RaceState
{
private string? _generation;
private long _revision;
private DateTimeOffset? _resyncSince; // When the complete state was asked for.
public Phase Phase { get; private set; } = Phase.Subscribing;
public State? State { get; private set; }
public bool NeedsResync => _resyncSince is not null;
/// <summary>A new connection: the previous state stays until the subscription is answered.</summary>
public void Connected() { Phase = Phase.Subscribing; _generation = null; _revision = 0; _resyncSince = null; }
/// <summary>The complete state, or the reason why there is none. Always the newest on this connection.</summary>
public Outcome Sync(SyncMessage message)
{
var live = message.Status == "Live";
_resyncSince = null;
Phase = live ? Phase.Live : message.Status == "Deleted" ? Phase.Deleted : Phase.Awaiting;
_generation = live ? message.Generation : null;
_revision = live ? message.Revision : 0;
if (live) { State = message.State; }
else if (Phase == Phase.Deleted) { State = null; }
return Outcome.Changed;
}
/// <summary>One change. It applies only to the revision it names.</summary>
public Outcome Delta(DeltaMessage message)
{
if (Phase == Phase.Subscribing || NeedsResync) { return Outcome.None; }
if (Phase != Phase.Live || message.Generation != _generation) { return Resync(); }
if (message.Revision <= _revision) { return Outcome.None; }
if (message.BaseRevision != _revision || Merge(State!, message) is not { } next) { return Resync(); }
_revision = message.Revision;
State = next;
return Outcome.Changed;
}
/// <summary>What the server has now: confirms the state, or shows that a message was missed.</summary>
public Outcome Beacon(BeaconMessage message)
{
if (Phase == Phase.Subscribing) { return Outcome.None; }
if (_resyncSince is { } since) { return DateTimeOffset.UtcNow - since >= TimeSpan.FromSeconds(30) ? Resync() : Outcome.None; }
var agrees = message.Status == "Live"
? Phase == Phase.Live && message.Generation == _generation && message.Revision == _revision
: Phase == (message.Status == "Deleted" ? Phase.Deleted : Phase.Awaiting);
return agrees ? Outcome.None : Resync();
}
private Outcome Resync() { _resyncSince = DateTimeOffset.UtcNow; return Outcome.Resync; }
// The state after a delta, or null when the delta does not fit it.
private static State? Merge(State state, DeltaMessage delta)
{
if (delta.Runs.Any(x => state.Runs.All(run => run.Number != x.Number))) { return null; }
var runs = new List<Run>();
foreach (var run in state.Runs)
{
if (delta.Runs.FirstOrDefault(x => x.Number == run.Number) is not { } change) { runs.Add(run); continue; }
var rows = run.Results.ToDictionary(x => x.Bib);
var bibs = run.Results.Select(x => x.Bib).ToList();
foreach (var row in change.Results)
{
if (!rows.ContainsKey(row.Bib)) { bibs.Add(row.Bib); }
rows[row.Bib] = row;
}
var order = change.Order ?? [.. bibs];
if (order.Length != rows.Count || order.Distinct().Count() != order.Length || order.Any(x => !rows.ContainsKey(x))) { return null; }
runs.Add(run with { Results = [.. order.Select(x => rows[x])], Forerunners = change.Forerunners ?? run.Forerunners });
}
return state with { Version = delta.Version, UpdatedAt = delta.UpdatedAt, Paused = delta.Paused, Runs = [.. runs] };
}
}
static class LiveReader
{
/// <summary>What happened between two states: status changes, intermediate times and corrected run times.</summary>
public static List<Change> Changes(State before, State after)
{
var result = new List<Change>();
foreach (var run in after.Runs)
{
var rows = before.Runs.FirstOrDefault(x => x.Number == run.Number)?.Results.ToDictionary(x => x.Bib) ?? [];
foreach (var row in run.Results)
{
var old = rows.GetValueOrDefault(row.Bib);
var status = new List<Change>();
if (row.Status != (old?.Status ?? "Ready")) { status.Add(new(run.Number, row, ChangeKind.Status)); }
else if (row.Status == "Finished" && row.Hundredths != old?.Hundredths) { status.Add(new(run.Number, row, ChangeKind.Time)); }
var times = (row.Intermediates ?? []).ToDictionary(x => x.Number, x => (long?)x.Hundredths);
var oldTimes = (old?.Intermediates ?? []).ToDictionary(x => x.Number, x => (long?)x.Hundredths);
var intermediates = oldTimes.Keys.Union(times.Keys).Order()
.Where(x => times.GetValueOrDefault(x) != oldTimes.GetValueOrDefault(x))
.Select(x => new Change(run.Number, row, ChangeKind.Intermediate, x, times.GetValueOrDefault(x)));
// When a break in the connection joined several changes, a start comes before and a finish after the intermediates.
result.AddRange(row.Status == "OnCourse" ? status.Concat(intermediates) : intermediates.Concat(status));
}
}
return result;
}
/// <summary>Follows one race until it is deleted. The callbacks run one at a time.</summary>
public static async Task FollowAsync(string server, string sessionId, Action<State, List<Change>> onState, Action<Phase> onStatus)
{
var race = new RaceState();
var gate = new Lock();
for (var attempt = 0; ;)
{
await using var hub = new HubConnectionBuilder().WithUrl($"{server}/live").Build();
var closed = new TaskCompletionSource();
hub.Closed += _ => { closed.TrySetResult(); return Task.CompletedTask; };
var lastResync = DateTimeOffset.MinValue;
void Handle(Func<Outcome> step)
{
lock (gate)
{
var before = race.State;
var outcome = step();
if (outcome == Outcome.Resync)
{
var earliest = lastResync == DateTimeOffset.MinValue ? TimeSpan.Zero : lastResync.AddSeconds(3) - DateTimeOffset.UtcNow;
var delay = TimeSpan.FromMilliseconds(Random.Shared.Next(500, 5000));
_ = ResyncAsync(delay > earliest ? delay : earliest);
}
if (outcome != Outcome.Changed) { return; }
if (race.Phase == Phase.Live) { onState(race.State!, before is null ? [] : Changes(before, race.State!)); }
else { onStatus(race.Phase); }
if (race.Phase == Phase.Deleted) { closed.TrySetResult(); }
}
}
async Task ResyncAsync(TimeSpan delay)
{
await Task.Delay(delay);
lock (gate)
{
if (!race.NeedsResync || hub.State != HubConnectionState.Connected) { return; }
lastResync = DateTimeOffset.UtcNow;
}
try { await hub.SendAsync("Resync"); }
catch (Exception) { /* The connection broke; the loop connects again. */ }
}
hub.On<SyncMessage>("Sync", message => Handle(() => race.Sync(message)));
hub.On<DeltaMessage>("Delta", message => Handle(() => race.Delta(message)));
hub.On<BeaconMessage>("Beacon", message => Handle(() => race.Beacon(message)));
lock (gate) { race.Connected(); }
try
{
await hub.StartAsync();
await hub.InvokeAsync("WatchSync", sessionId, 1);
attempt = 0;
await closed.Task;
}
catch (Exception) when (hub.State != HubConnectionState.Connected) { /* No connection; try again below. */ }
if (race.Phase == Phase.Deleted) { return; }
await Task.Delay(TimeSpan.FromMilliseconds(Math.Min(15000, 1000 * Math.Pow(2, attempt++)) * (0.5 + Random.Shared.NextDouble() / 2)));
}
}
}
live-reader.cs on GitHub ↗
Java
Java 17 or later, dependency com.microsoft.signalr:signalr 10.0.15. With JBang the file runs as it is:
jbang LiveReader.java https://live.openskiti.me SESSION_ID
Show LiveReader.java
// OpenSkiTime Live API reader for Java 17 or later. MIT license. https://openskiti.me/live-api/
//
// Needs com.microsoft.signalr:signalr:10.0.15 and its dependencies on the class path, for example with JBang:
// jbang LiveReader.java lists the races published now
// jbang LiveReader.java https://live.openskiti.me <sessionId> follows one race
//JAVA 17+
//DEPS com.microsoft.signalr:signalr:10.0.15
import com.google.gson.Gson;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.HubConnectionState;
import java.io.PrintStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public final class LiveReader {
// The messages. Properties not listed here are ignored; add the ones you need.
static final class Race { String sessionId, name, discipline, date; }
static final class Competition { String name, discipline, date, codex; }
static final class Competitor { int bib; String lastName, firstName, nation, club, fisCode, category; }
static final class Intermediate { int number; long hundredths; }
static final class Forerunner { String letter, lastName, firstName, nation, status; }
static final class Row {
int bib; String status, at, startedAt;
Long hundredths, difference, totalHundredths, totalDifference; Integer rank, totalRank;
Intermediate[] intermediates;
}
static final class Run { int number; int[] startOrder; Row[] results; Forerunner[] forerunners; }
static final class State {
long version; Competition competition; Competitor[] competitors; int currentRun; Run[] runs; String updatedAt; boolean paused;
}
static final class SyncMessage { String status, generation; long revision; State state; }
static final class RunDelta { int number; Row[] results; int[] order; Forerunner[] forerunners; }
static final class DeltaMessage {
String generation, updatedAt; long baseRevision, revision, version; boolean paused; RunDelta[] runs;
}
static final class BeaconMessage { String status, generation; long revision; }
enum Phase { SUBSCRIBING, LIVE, AWAITING, DELETED }
enum Outcome { NONE, CHANGED, RESYNC }
enum Kind { STATUS, TIME, INTERMEDIATE }
record Change(int run, Row row, Kind kind, int number, Long hundredths) { }
interface Listener {
void state(State state, List<Change> changes);
void status(Phase phase);
}
/** The state of one race, kept up to date from the messages of the server. */
static final class RaceState {
Phase phase = Phase.SUBSCRIBING;
String generation;
long revision;
State state;
long resyncSince; // When the complete state was asked for (System.nanoTime), or 0.
/** A new connection: the previous state stays until the subscription is answered. */
void connected() { phase = Phase.SUBSCRIBING; generation = null; revision = 0; resyncSince = 0; }
/** The complete state, or the reason why there is none. Always the newest on this connection. */
Outcome sync(SyncMessage message) {
boolean live = "Live".equals(message.status);
resyncSince = 0;
phase = live ? Phase.LIVE : "Deleted".equals(message.status) ? Phase.DELETED : Phase.AWAITING;
generation = live ? message.generation : null;
revision = live ? message.revision : 0;
if (live) { state = message.state; } else if (phase == Phase.DELETED) { state = null; }
return Outcome.CHANGED;
}
/** One change. It applies only to the revision it names. */
Outcome delta(DeltaMessage message) {
if (phase == Phase.SUBSCRIBING || resyncSince != 0) { return Outcome.NONE; }
if (phase != Phase.LIVE || !message.generation.equals(generation)) { return resync(); }
if (message.revision <= revision) { return Outcome.NONE; }
if (message.baseRevision != revision) { return resync(); }
State next = merge(state, message);
if (next == null) { return resync(); }
revision = message.revision;
state = next;
return Outcome.CHANGED;
}
/** What the server has now: confirms the state, or shows that a message was missed. */
Outcome beacon(BeaconMessage message) {
if (phase == Phase.SUBSCRIBING) { return Outcome.NONE; }
if (resyncSince != 0) { return System.nanoTime() - resyncSince >= TimeUnit.SECONDS.toNanos(30) ? resync() : Outcome.NONE; }
boolean agrees = "Live".equals(message.status)
? phase == Phase.LIVE && Objects.equals(message.generation, generation) && message.revision == revision
: phase == ("Deleted".equals(message.status) ? Phase.DELETED : Phase.AWAITING);
return agrees ? Outcome.NONE : resync();
}
private Outcome resync() { resyncSince = System.nanoTime(); return Outcome.RESYNC; }
// The state after a delta, or null when the delta does not fit it.
private static State merge(State state, DeltaMessage delta) {
Map<Integer, RunDelta> changed = new LinkedHashMap<>();
for (RunDelta run : delta.runs) { changed.put(run.number, run); }
List<Run> runs = new ArrayList<>();
for (Run run : state.runs) {
RunDelta change = changed.remove(run.number);
if (change == null) { runs.add(run); continue; }
Map<Integer, Row> rows = rows(run); // Keeps known rows in place and appends new ones.
for (Row row : change.results) { rows.put(row.bib, row); }
int[] order = change.order != null ? change.order : rows.keySet().stream().mapToInt(x -> x).toArray();
if (order.length != rows.size() || !new HashSet<>(Arrays.stream(order).boxed().toList()).equals(rows.keySet())) { return null; }
Run next = new Run();
next.number = run.number;
next.startOrder = run.startOrder;
next.results = Arrays.stream(order).mapToObj(rows::get).toArray(Row[]::new);
next.forerunners = change.forerunners != null ? change.forerunners : run.forerunners;
runs.add(next);
}
if (!changed.isEmpty()) { return null; }
State next = new State();
next.competition = state.competition;
next.competitors = state.competitors;
next.currentRun = state.currentRun;
next.version = delta.version;
next.updatedAt = delta.updatedAt;
next.paused = delta.paused;
next.runs = runs.toArray(Run[]::new);
return next;
}
}
private static Map<Integer, Row> rows(Run run) {
Map<Integer, Row> rows = new LinkedHashMap<>();
if (run != null) { for (Row row : run.results) { rows.put(row.bib, row); } }
return rows;
}
private static Map<Integer, Long> times(Row row) {
Map<Integer, Long> times = new TreeMap<>();
if (row != null && row.intermediates != null) { for (Intermediate x : row.intermediates) { times.put(x.number, x.hundredths); } }
return times;
}
/** What happened between two states: status changes, intermediate times and corrected run times. */
static List<Change> changes(State before, State after) {
List<Change> result = new ArrayList<>();
for (Run run : after.runs) {
Map<Integer, Row> rows = rows(Arrays.stream(before.runs).filter(x -> x.number == run.number).findFirst().orElse(null));
for (Row row : run.results) {
Row old = rows.get(row.bib);
List<Change> status = new ArrayList<>(), intermediates = new ArrayList<>();
if (!row.status.equals(old == null ? "Ready" : old.status)) { status.add(new Change(run.number, row, Kind.STATUS, 0, null)); }
else if ("Finished".equals(row.status) && !Objects.equals(row.hundredths, old == null ? null : old.hundredths)) {
status.add(new Change(run.number, row, Kind.TIME, 0, null));
}
Map<Integer, Long> times = times(row), oldTimes = times(old);
TreeSet<Integer> numbers = new TreeSet<>(times.keySet());
numbers.addAll(oldTimes.keySet());
for (int number : numbers) {
if (!Objects.equals(times.get(number), oldTimes.get(number))) {
intermediates.add(new Change(run.number, row, Kind.INTERMEDIATE, number, times.get(number)));
}
}
// When a break in the connection joined several changes, a start comes before and a finish after the intermediates.
boolean started = "OnCourse".equals(row.status);
result.addAll(started ? status : intermediates);
result.addAll(started ? intermediates : status);
}
}
return result;
}
/** Follows one race until it is deleted. The callbacks run one at a time. */
static void follow(String server, String sessionId, Listener listener) throws InterruptedException {
RaceState race = new RaceState();
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
try {
for (int attempt = 0; ;) {
Connection connection = new Connection(server, race, timer, listener);
try {
connection.run(sessionId);
attempt = 0;
} catch (RuntimeException error) {
if (connection.hub.getConnectionState() == HubConnectionState.CONNECTED) { throw error; } // The server refused the subscription.
} finally {
connection.stop();
}
synchronized (race) { if (race.phase == Phase.DELETED) { return; } }
long delay = Math.min(15000, 1000L << Math.min(attempt++, 4));
Thread.sleep((long) (delay * (0.5 + ThreadLocalRandom.current().nextDouble() / 2)));
}
} finally {
timer.shutdownNow();
}
}
private static final class Connection {
final HubConnection hub;
private final RaceState race;
private final ScheduledExecutorService timer;
private final Listener listener;
private final CompletableFuture<Void> closed = new CompletableFuture<>();
private long lastResync;
Connection(String server, RaceState race, ScheduledExecutorService timer, Listener listener) {
this.race = race;
this.timer = timer;
this.listener = listener;
hub = HubConnectionBuilder.create(server + "/live").build();
hub.onClosed(error -> closed.complete(null));
hub.on("Sync", message -> handle(() -> race.sync(message)), SyncMessage.class);
hub.on("Delta", message -> handle(() -> race.delta(message)), DeltaMessage.class);
hub.on("Beacon", message -> handle(() -> race.beacon(message)), BeaconMessage.class);
synchronized (race) { race.connected(); }
}
void run(String sessionId) {
hub.start().blockingAwait();
hub.invoke("WatchSync", sessionId, 1).blockingAwait();
closed.join();
}
void stop() {
try { hub.stop().blockingAwait(5, TimeUnit.SECONDS); } catch (RuntimeException error) { /* Already closed. */ }
}
private void handle(Supplier<Outcome> step) {
synchronized (race) {
State before = race.state;
Outcome outcome = step.get();
if (outcome == Outcome.RESYNC) {
long earliest = lastResync == 0 ? 0 : lastResync + 3000 - System.currentTimeMillis();
timer.schedule(this::resync, Math.max(ThreadLocalRandom.current().nextLong(500, 5000), earliest), TimeUnit.MILLISECONDS);
}
if (outcome != Outcome.CHANGED) { return; }
if (race.phase == Phase.LIVE) { listener.state(race.state, before == null ? List.of() : changes(before, race.state)); }
else { listener.status(race.phase); }
if (race.phase == Phase.DELETED) { closed.complete(null); }
}
}
private void resync() {
synchronized (race) {
if (race.resyncSince == 0 || hub.getConnectionState() != HubConnectionState.CONNECTED) { return; }
lastResync = System.currentTimeMillis();
}
try { hub.send("Resync"); } catch (RuntimeException error) { /* The connection broke; the loop connects again. */ }
}
}
/** Hundredths as 50.12 or 1:02.03, with integer arithmetic. */
static String time(long x) {
return x >= 6000 ? String.format(Locale.ROOT, "%d:%02d.%02d", x / 6000, x / 100 % 60, x % 100) : String.format(Locale.ROOT, "%d.%02d", x / 100, x % 100);
}
private static String describe(Change change) {
Row row = change.row();
if (change.kind() == Kind.INTERMEDIATE) {
return "Intermediate " + change.number() + " " + (change.hundredths() == null ? "removed" : time(change.hundredths()));
}
if (!"Finished".equals(row.status)) { return row.status; }
return (change.kind() == Kind.TIME ? "Time changed " : "Finished ") + time(row.hundredths) + ", rank " + row.rank;
}
public static void main(String[] args) throws Exception {
PrintStream out = new PrintStream(System.out, true, StandardCharsets.UTF_8);
String server = args.length > 0 ? args[0] : "https://live.openskiti.me";
if (args.length < 2) {
// The hosted service sleeps between races: the first answer can take a couple of minutes.
HttpRequest request = HttpRequest.newBuilder(URI.create(server + "/api/sessions")).timeout(Duration.ofMinutes(2)).build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) { throw new IllegalStateException("HTTP " + response.statusCode()); }
Race[] races = new Gson().fromJson(response.body(), Race[].class);
if (races.length == 0) { out.println("No race is published now."); }
for (Race race : races) { out.println(race.sessionId + " | " + race.date + " | " + race.discipline + " | " + race.name); }
return;
}
follow(server, args[1], new Listener() {
private boolean named;
@Override public void state(State state, List<Change> changes) {
if (!named) { out.println("Race | " + state.competition.name + " | " + state.competitors.length + " competitors"); }
named = true;
for (Change change : changes) {
Competitor who = Arrays.stream(state.competitors).filter(x -> x.bib == change.row().bib).findFirst().orElse(null);
String name = who == null ? " " : who.lastName + " " + who.firstName;
out.println("Run " + change.run() + " | " + change.row().bib + " " + name + " | " + describe(change));
}
}
@Override public void status(Phase phase) { out.println(phase == Phase.DELETED ? "Deleted" : "Waiting for the publisher"); }
});
System.exit(0); // The HTTP client of the SignalR library keeps threads alive for a while.
}
}
LiveReader.java on GitHub ↗