# OpenSkiTime Live API Source: https://openskiti.me/live-api/ Read published races in real time: start lists, starts, intermediate times, finishes, DNS, DNF and DSQ. No key or registration. ## Overview When an organizer publishes a race with OpenSkiTime, anyone can read it: in the browser, or with this API. The hosted service is `https://live.openskiti.me`. The local live timing of a race computer offers the same API, by default at `http://localhost:5078` and only on that computer. Anyone can also run a server of their own. There are two ways to read a race: - **HTTP** lists the published races and returns the complete state of one race. - **SignalR** sends every change as it happens, over one WebSocket connection. The API is read-only. It tells what the organizer publishes now; it is not a results archive. **All results are unofficial.** Machine-readable descriptions: [OpenAPI 3.1 of the HTTP part](https://openskiti.me/live-api/openapi.json) and [JSON Schema of every message](https://openskiti.me/live-api/live-api.schema.json). For AI coding tools, [one text file](https://openskiti.me/live-api/live-api.txt) has this page, the schema and the example readers. ## Quick start List the races published now: ``` curl https://live.openskiti.me/api/sessions ``` Follow one race with the [JavaScript reader](https://github.com/tnakeli/OpenSkiTime/blob/master/website/live-api/live-reader.mjs), using a `sessionId` from the list: ``` npm install @microsoft/signalr@10 node live-reader.mjs https://live.openskiti.me SESSION_ID ``` It prints what happens in the race: ``` Race | Synthetic slalom | 40 competitors Run 1 | 1 TEST Anna | OnCourse Run 1 | 1 TEST Anna | Intermediate 1 25.01 Run 1 | 1 TEST Anna | Finished 50.12, rank 1 Run 1 | 3 EXAMPLE Maria | DNS ``` The same reader is available for [.NET and Java](https://openskiti.me/live-api/#examples). All examples on this page are synthetic. ## HTTP requests | Request | Answer | | --- | --- | | `GET /api/sessions` | The races published now, newest race date first. An empty list when there are none. | | `GET /api/sessions/{sessionId}/state` | The complete [state](https://openskiti.me/live-api/#data) of one race. 404 when the server has no state for the ID. | One race in the list: ``` { "sessionId": "3f2b8c1e-5d47-4a90-9b1c-7e6f0a2d4c58", "name": "Synthetic slalom", "place": "Testville", "discipline": "SL", "date": "2026-11-24", "gender": "L", "category": "Club", "isFis": false, "codex": "", "updatedAt": "2026-11-24T10:04:12+02:00", "paused": false } ``` Recognize a race by its `codex`, or by date, name and discipline: a race that is published again can get a new `sessionId`. The hosted service sleeps when nobody uses it, and the first request can take a couple of minutes. Use a timeout of two minutes for the first request. Do not send the `X-OpenSkiTime-Live-Protocol` header; it belongs to publishers. ## Race data The state of a race: | Property | Meaning | | --- | --- | | `competition` | Name, place, discipline, date, codex, gender, category, `intermediateCount` and `runCount`. | | `competitors` | `bib`, `lastName`, `firstName`, `nation`, `club`, `fisCode` and, in a race with classes, `category`. | | `currentRun` | Number of the run being timed. | | `runs` | Each run has a `number`, the `startOrder` (bibs), the `results` and possibly `forerunners`. | | `updatedAt` | Time of the latest update from the publisher. | | `paused` | The organizer has stopped publishing for now. | A result row: ``` { "bib": 1, "status": "Finished", "hundredths": 5012, "rank": 1, "difference": 0, "at": "2026-11-24T10:04:12+02:00", "startedAt": "2026-11-24T10:03:22+02:00", "startSourceTicks": "639000000000000000", "finishSourceTicks": "639000000501200000", "intermediates": [ { "number": 1, "hundredths": 2501, "at": "2026-11-24T10:03:47+02:00", "sourceTicks": "639000000250100000" } ], "totalHundredths": null, "totalRank": null, "totalDifference": null } ``` - **Times are integers in hundredths of a second:** 5012 is 50.12. Do not convert them to floating point for calculations, and do not calculate times from the source ticks, which are diagnostic. - **Ranks, differences and totals are ready-made.** Equal times share a rank. In a race with classes they are those within the class. - **Totals** (`totalHundredths`, `totalRank`, `totalDifference`) are given from Run 2 on, for a competitor with a finished time in every run so far. - **The order of the rows is not the ranking.** Use `rank`, and `startOrder` for the start list. - `intermediates` can be null. Rows also contain `splits`, an older copy of it; do not use it. | Status | Meaning | | --- | --- | | `Ready` | Has not started. | | `OnCourse` | Started, not yet at the finish. | | `Finished` | Has a valid time in `hundredths`. | | `DNS` | Did not start. | | `DNF` | Did not finish. | | `DSQ` | Disqualified. | | `NPS` | Not permitted to start. | | `Review` | The timing crew is checking the times. Not a result yet. | Forerunners have a letter, a name and a status, never a time. ## 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. ## Synchronization rules The server sends the messages of a race in order. A reader keeps the state with its `generation` and `revision`, and follows these rules: - **Sync** is always the newest. `Live`: replace the state, generation and revision, whatever they were. `Awaiting`: forget the generation and revision but keep the state, as the publisher normally restores it. `Deleted`: drop the state and disconnect. - **Delta** applies only when its `generation` is yours and its `baseRevision` equals your `revision`. Ignore a delta of your generation whose `revision` is not newer than yours. Anything else is a gap. - **Applying a delta:** in each listed run, every row in `results` replaces the row with the same bib, or is added at the end. If `order` is given, put all rows in that order; it must list every row once. If `forerunners` is given, it replaces the list. Then take `version`, `updatedAt`, `paused` and `revision` from the delta. If a run is unknown or the order does not fit, change nothing and treat it as a gap. - **Beacon** should agree with what you have. If the status, generation or revision differs, treat it as a gap. - **After a gap** wait a random 0.5–5 seconds and send `Resync()`, at least 3 seconds after the previous one. Ignore deltas until the `Sync` arrives. If it has not arrived in 30 seconds, ask again at the next beacon. - **After a lost connection** connect again and invoke `WatchSync`, waiting 1 second at first and doubling the wait up to 15 seconds, with a random part. Keep showing the previous state until the new `Sync`, and ignore deltas and beacons before it. Generations have no order; compare them only for equality. Do not use `version` for synchronization. ## From changes to events The API sends results, not events. Compare the rows before and after each `Delta` **and each `Sync`**; a row or run you did not have counts as `Ready`: | Change of a row | Event | | --- | --- | | `status` becomes `OnCourse` | Started | | New number in `intermediates` | Intermediate time | | `status` becomes `Finished` | Arrived at the finish; time and rank are in the same row | | `status` becomes `DNS`, `DNF`, `DSQ` or `NPS` | Classified | | `hundredths` of a finished row, or an intermediate time, changes or disappears | Corrected | | Only `rank`, `difference` or totals change | Someone else’s result moved this row | - The first `Sync` is the starting point, not a set of events. - **A result can change afterwards,** in any direction: a finisher can be disqualified, a DSQ can be cancelled, a time can be corrected, and a competitor with a re-run goes back to `OnCourse`. - **The latest state is reliable, every step on the way is not.** After a break in a connection, several changes can arrive as one: a competitor can go straight from `Ready` to `Finished`. ## Polling Without a SignalR client, for example in PHP, read `GET /api/sessions/{sessionId}/state` every 10 seconds while the race is on, never more often than every 5 seconds, and compare the rows as above. One background job should poll for all your users. The answer is always the complete state, some tens of kilobytes for a hundred competitors; there are no conditional requests. - **404:** the race is not available now. Keep the last results and try again less often, for example every 30 seconds; give up after a while. - **429 or a network error:** wait longer before the next request, up to a minute. ## 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](https://github.com/tnakeli/OpenSkiTime/tree/master/website/live-api), 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](https://www.npmjs.com/package/@microsoft/signalr). ``` npm install @microsoft/signalr@10 node live-reader.mjs https://live.openskiti.me SESSION_ID ``` ### .NET .NET 10 or later, package [Microsoft.AspNetCore.SignalR.Client](https://www.nuget.org/packages/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 ``` ### Java Java 17 or later, dependency [com.microsoft.signalr:signalr](https://central.sonatype.com/artifact/com.microsoft.signalr/signalr) 10.0.15. With [JBang](https://www.jbang.dev) the file runs as it is: ``` jbang LiveReader.java https://live.openskiti.me SESSION_ID ``` ## Limits and fair use - **Connect from a server or an application, once per race,** and pass the results on to your own users yourself. The connections of the hosted service are shared with the spectators of every race. - **Connect for the race, not around the clock.** A connection or a poll keeps the service awake. Disconnect when the race is over or deleted, and if it stays `Awaiting` or `paused` for long. To find a race, read the list every few minutes around its start time. - **Web pages of other sites cannot call the API directly.** The server sends no CORS headers. - **Limits of the hosted service now:** 1000 simultaneous connections in all, 200 from one address, and 3000 requests per minute from one address. They can change. A request over a limit is refused with 429. - The state is in the memory of the server only. It disappears when the organizer deletes the race, when the publisher does not restore it after a restart, and in any case within 14 days of publishing. Store what you need. - The service is free and comes without an availability guarantee. ## Versions and stability This is version 1 of the Live API: the two HTTP requests, `WatchSync` with version 1, `Resync`, and the messages `Sync`, `Delta` and `Beacon`. It works with live timing server 0.10.0 and later, and with the local live timing of OpenSkiTime 0.3.0 and later. - **Compatible additions can come at any time:** new properties, new status values and new messages. Ignore what you do not know, and show an unknown status as no result. - **An incompatible change gets a new version.** It is announced in the [changelog of the live timing server](https://github.com/tnakeli/OpenSkiTime/blob/master/CHANGELOG-LIVE.md) beforehand, and the previous version keeps working for a transition period. - Publishing, race radio, server statistics and everything else not described here can change without notice. Questions and ideas: [GitHub issues](https://github.com/tnakeli/OpenSkiTime/issues). ## Personal data Races contain names, clubs, nations and results of competitors, who are often children. The organizer decides what is published here and for how long. You are responsible for what your service does with the data: agree on it with the organizer, show the results as unofficial, and follow corrections and deletions. ## File: live-api.schema.json ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://openskiti.me/live-api/live-api.schema.json", "title": "OpenSkiTime Live API", "description": "Messages of the OpenSkiTime Live API, version 1. New properties, new status values and new messages can be added at any time: readers ignore what they do not know. A property is listed as required when the server always sends it.", "$defs": { "Race": { "title": "Race", "description": "One published race in the list of races.", "type": "object", "required": ["sessionId", "name", "place", "discipline", "date", "gender", "category", "isFis", "codex", "updatedAt", "paused"], "properties": { "sessionId": { "type": "string", "format": "uuid", "description": "The race on this server. A race published again can get a new ID." }, "name": { "type": "string" }, "place": { "type": "string" }, "discipline": { "type": "string", "description": "Discipline code as the organizer entered it, for example SL or GS." }, "date": { "type": "string", "format": "date" }, "gender": { "type": "string" }, "category": { "type": "string" }, "isFis": { "type": "boolean" }, "codex": { "type": "string", "description": "Race codex; empty when the race has none." }, "updatedAt": { "type": "string", "format": "date-time" }, "paused": { "type": "boolean", "description": "The organizer has stopped publishing for now." } } }, "State": { "title": "State", "description": "The complete published state of one race.", "type": "object", "required": ["version", "competition", "competitors", "currentRun", "runs", "updatedAt", "paused"], "properties": { "version": { "type": "integer", "description": "The publisher's own counter. Do not use it to detect or order changes: pausing does not increment it." }, "competition": { "$ref": "#/$defs/Competition" }, "competitors": { "type": "array", "items": { "$ref": "#/$defs/Competitor" } }, "currentRun": { "type": "integer", "description": "Number of the run being timed." }, "runs": { "type": "array", "items": { "$ref": "#/$defs/Run" } }, "updatedAt": { "type": "string", "format": "date-time" }, "paused": { "type": "boolean", "description": "The organizer has stopped publishing for now." } } }, "Competition": { "title": "Competition", "type": "object", "required": ["name", "place", "discipline", "date", "isFis", "codex", "gender", "category", "intermediateCount", "slope", "runCount"], "properties": { "name": { "type": "string" }, "place": { "type": "string" }, "discipline": { "type": "string", "description": "Discipline code as the organizer entered it, for example SL or GS." }, "date": { "type": "string", "format": "date" }, "isFis": { "type": "boolean" }, "codex": { "type": "string", "description": "Race codex; empty when the race has none." }, "gender": { "type": "string" }, "category": { "type": "string" }, "intermediateCount": { "type": "integer", "minimum": 0, "description": "Number of intermediate timing points on the course." }, "slope": { "type": "string" }, "runCount": { "type": "integer", "minimum": 0, "description": "Number of runs in the race, or 0 when the publisher does not tell." } } }, "Competitor": { "title": "Competitor", "type": "object", "required": ["bib", "lastName", "firstName", "nation", "club", "fisCode", "category"], "properties": { "bib": { "type": "integer", "minimum": 1, "description": "Unique in the race. Result rows and start orders refer to it." }, "lastName": { "type": "string" }, "firstName": { "type": "string" }, "nation": { "type": "string", "description": "Nation code; can be empty." }, "club": { "type": "string", "description": "Can be empty." }, "fisCode": { "type": "string", "description": "FIS or national federation code of the competitor; can be empty." }, "category": { "type": "string", "description": "Class of the competitor, for example N10. Empty in a race without classes." } } }, "Run": { "title": "Run", "type": "object", "required": ["number", "listCreatedAt", "startOrder", "results", "forerunners"], "properties": { "number": { "type": "integer", "minimum": 1 }, "listCreatedAt": { "type": "string", "format": "date-time", "description": "When the start list of the run was created." }, "startOrder": { "type": "array", "items": { "type": "integer" }, "description": "Bibs in start order." }, "results": { "type": "array", "items": { "$ref": "#/$defs/Result" }, "description": "One row per bib. The order of the rows is not the ranking; use rank." }, "forerunners": { "type": ["array", "null"], "items": { "$ref": "#/$defs/Forerunner" }, "description": "Null when the run has no forerunners." } } }, "Result": { "title": "Result", "description": "The result row of one competitor in one run. Times are integers in hundredths of a second: 5012 is 50.12 seconds. In a race with classes, rank and difference (and their totals) are those within the class.", "type": "object", "required": ["bib", "status", "hundredths", "rank", "difference", "at", "startedAt", "startSourceTicks", "finishSourceTicks", "intermediates", "totalHundredths", "totalRank", "totalDifference"], "properties": { "bib": { "type": "integer", "minimum": 1 }, "status": { "$ref": "#/$defs/Status" }, "hundredths": { "type": ["integer", "null"], "minimum": 0, "description": "Run time. Use it only when the status is Finished." }, "rank": { "type": ["integer", "null"], "minimum": 1, "description": "Rank in the run. Equal times share a rank." }, "difference": { "type": ["integer", "null"], "minimum": 0, "description": "Gap to the best time of the run." }, "at": { "type": "string", "format": "date-time", "description": "Time of the latest impulse or correction of the row." }, "startedAt": { "type": ["string", "null"], "format": "date-time", "description": "Start time, for a running clock." }, "startSourceTicks": { "type": ["string", "null"], "pattern": "^[0-9]+$", "description": "Diagnostic source timestamp of the timing device in 100 ns units, as a decimal string. Do not calculate results from it." }, "finishSourceTicks": { "type": ["string", "null"], "pattern": "^[0-9]+$", "description": "Like startSourceTicks, for the finish." }, "intermediates": { "type": ["array", "null"], "items": { "$ref": "#/$defs/Intermediate" }, "description": "Intermediate times so far; null or empty when there are none." }, "splits": { "type": "array", "items": { "$ref": "#/$defs/Intermediate" }, "deprecated": true, "description": "Copy of intermediates; use intermediates." }, "totalHundredths": { "type": ["integer", "null"], "minimum": 0, "description": "Combined time of all runs so far, from Run 2 on. Null without a finished time in every run so far." }, "totalRank": { "type": ["integer", "null"], "minimum": 1 }, "totalDifference": { "type": ["integer", "null"], "minimum": 0 } } }, "Intermediate": { "title": "Intermediate", "type": "object", "required": ["number", "hundredths", "at", "sourceTicks"], "properties": { "number": { "type": "integer", "minimum": 1, "description": "Timing point, 1 is the first one after the start." }, "hundredths": { "type": "integer", "minimum": 0, "description": "Time from the start in hundredths of a second." }, "at": { "type": "string", "format": "date-time" }, "sourceTicks": { "type": ["string", "null"], "pattern": "^[0-9]+$", "description": "Diagnostic source timestamp, as in Result." } } }, "Forerunner": { "title": "Forerunner", "description": "Progress of a forerunner. A forerunner never has a time.", "type": "object", "required": ["letter", "lastName", "firstName", "nation", "status"], "properties": { "letter": { "type": "string" }, "lastName": { "type": "string" }, "firstName": { "type": "string" }, "nation": { "type": "string" }, "status": { "$ref": "#/$defs/Status" } } }, "Status": { "title": "Status", "type": "string", "enum": ["Ready", "OnCourse", "Finished", "DNS", "DNF", "DSQ", "NPS", "Review"], "description": "Ready: has not started. OnCourse: started. Finished: has a valid time. DNS: did not start. DNF: did not finish. DSQ: disqualified. NPS: not permitted to start. Review: the timing crew is checking the times; not a result yet." }, "SyncMessage": { "title": "Sync", "description": "SignalR message Sync: the complete state of the race, or why there is none.", "type": "object", "required": ["status", "generation", "revision", "state"], "properties": { "status": { "$ref": "#/$defs/SessionStatus" }, "generation": { "type": ["string", "null"], "description": "Identifier of this history of the race on the server; null unless Live. Compare only for equality." }, "revision": { "type": "integer", "description": "Increases by one with every change of the same generation; 0 unless Live." }, "state": { "oneOf": [{ "$ref": "#/$defs/State" }, { "type": "null" }] } } }, "DeltaMessage": { "title": "Delta", "description": "SignalR message Delta: one change. It applies only to revision baseRevision of the same generation, and only as a whole.", "type": "object", "required": ["generation", "baseRevision", "revision", "version", "updatedAt", "paused", "runs"], "properties": { "generation": { "type": "string" }, "baseRevision": { "type": "integer" }, "revision": { "type": "integer" }, "version": { "type": "integer", "description": "Replaces version of the state." }, "updatedAt": { "type": "string", "format": "date-time", "description": "Replaces updatedAt of the state." }, "paused": { "type": "boolean", "description": "Replaces paused of the state." }, "runs": { "type": "array", "items": { "$ref": "#/$defs/RunDelta" }, "description": "The runs that changed." } } }, "RunDelta": { "title": "RunDelta", "type": "object", "required": ["number", "results"], "properties": { "number": { "type": "integer" }, "results": { "type": "array", "items": { "$ref": "#/$defs/Result" }, "description": "Complete rows. Each one replaces the row with the same bib, or is new." }, "order": { "type": "array", "items": { "type": "integer" }, "description": "Bibs of all rows in their new order. When absent, rows keep their places and new rows follow in the order of results." }, "forerunners": { "type": "array", "items": { "$ref": "#/$defs/Forerunner" }, "description": "The complete new list. When absent, the forerunners did not change." } } }, "BeaconMessage": { "title": "Beacon", "description": "SignalR message Beacon, about every 30 seconds: what a reader that missed nothing has now.", "type": "object", "required": ["status", "generation", "revision"], "properties": { "status": { "$ref": "#/$defs/SessionStatus" }, "generation": { "type": ["string", "null"] }, "revision": { "type": "integer" } } }, "SessionStatus": { "title": "SessionStatus", "type": "string", "enum": ["Live", "Deleted", "Awaiting"], "description": "Live: the server has the state. Deleted: the organizer deleted the race. Awaiting: the server has no state now (not published yet, not restored after a server restart, or an unknown ID)." } } } ``` ## File: live-reader.mjs ```js // 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 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')); } } ``` ## File: live-reader.cs ```csharp #: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 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($"{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); /// The state of one race, kept up to date from the messages of the server. 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; /// A new connection: the previous state stays until the subscription is answered. public void Connected() { Phase = Phase.Subscribing; _generation = null; _revision = 0; _resyncSince = null; } /// The complete state, or the reason why there is none. Always the newest on this connection. 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; } /// One change. It applies only to the revision it names. 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; } /// What the server has now: confirms the state, or shows that a message was missed. 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(); 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 { /// What happened between two states: status changes, intermediate times and corrected run times. public static List Changes(State before, State after) { var result = new List(); 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(); 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; } /// Follows one race until it is deleted. The callbacks run one at a time. public static async Task FollowAsync(string server, string sessionId, Action> onState, Action 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 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("Sync", message => Handle(() => race.Sync(message))); hub.On("Delta", message => Handle(() => race.Delta(message))); hub.On("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))); } } } ``` ## File: LiveReader.java ```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 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 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 changed = new LinkedHashMap<>(); for (RunDelta run : delta.runs) { changed.put(run.number, run); } List runs = new ArrayList<>(); for (Run run : state.runs) { RunDelta change = changed.remove(run.number); if (change == null) { runs.add(run); continue; } Map 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 rows(Run run) { Map rows = new LinkedHashMap<>(); if (run != null) { for (Row row : run.results) { rows.put(row.bib, row); } } return rows; } private static Map times(Row row) { Map 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 changes(State before, State after) { List result = new ArrayList<>(); for (Run run : after.runs) { Map 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 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 times = times(row), oldTimes = times(old); TreeSet 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 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 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 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 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. } } ```