From 3b9f94d6e1eadd2d7b4993b6ab2f7c245be4c2d4 Mon Sep 17 00:00:00 2001 From: Lethonium Dev Server <38733902+RalfLeonFasler@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:32:11 +0000 Subject: [PATCH 1/4] Add draft v0 spec: shared presence over WebSocket Defines the connection, the 1D route format with velodrome-250 as the first route, join/update/leave messages, self-declared app IDs and public usage statistics. Co-Authored-By: Claude Opus 5.5 --- spec/v0.md | 374 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 374 insertions(+) create mode 100644 spec/v0.md diff --git a/spec/v0.md b/spec/v0.md new file mode 100644 index 0000000..3460c3f --- /dev/null +++ b/spec/v0.md @@ -0,0 +1,374 @@ +# OpenBikeNet Protocol v0: Shared Presence + +**Status: draft.** v0 may still change in breaking ways until it is marked stable. Feedback is +welcome in [Discussions](../../../discussions). + +The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as described in +[RFC 2119](https://www.rfc-editor.org/rfc/rfc2119). + +## 1. Scope + +v0 lets indoor cycling apps show each other's riders on shared routes. Each app keeps its own +physics and reports where its riders are. The server keeps the current state and passes it on. + +v0 covers: + +- a WebSocket connection between an app and a server, +- shared routes defined as a 1D elevation profile, +- joining, updating and leaving riders on a route, +- self-declared app identification and public usage statistics. + +Not in v0: server-side physics, accounts, private rooms with access control, races and events, +proof of app ownership, other transports such as MQTT. The message format does not depend on +WebSocket, so other transports can be added later. + +## 2. Terms + +- **App:** an indoor cycling application that implements this protocol. +- **Connection:** one WebSocket connection from an app instance to a server. It MAY carry many + riders. Apps with a backend SHOULD connect from the backend and carry all their riders over one + connection. Apps without a backend connect from the client, usually with one rider. +- **Rider:** one person riding. A rider is on at most one route at a time. +- **Route:** a shared route as defined in section 4. +- **Room:** a group of riders on the same route who see each other. The default room is `public`. + +## 3. Connection + +### 3.1 Endpoint + +Servers accept WebSocket connections at the path `/v0`, for example +`wss:///v0`. Public servers MUST use `wss`. A later incompatible version gets a new path +(`/v1`), and a server MAY serve both. + +### 3.2 Frames + +Every message is one WebSocket text frame holding one JSON object with a string field `type`. +Binary frames are not used, and a server MUST close the connection if it receives one. + +Receivers MUST ignore unknown fields. A server MUST answer an unknown `type` with an +`error` (`unknown_type`). This lets new optional fields be added without a new version. + +Any message from an app MAY carry a string field `ref` (at most 64 characters). If the server +answers that message with an `error`, the error carries the same `ref`. + +### 3.3 Units + +| Quantity | Unit | JSON type | +|---|---|---| +| distance, length, elevation | metres | number | +| speed | metres per second | number | +| power | watts | integer | +| cadence | revolutions per minute | integer | +| heart rate | beats per minute | integer | + +### 3.4 Lifecycle + +1. The app opens the connection and MUST send `hello` as its first message, within 10 seconds. +2. The server answers with `welcome`. +3. The app sends `subscribe` for each route and room whose riders it wants to see, and receives a + `snapshot` for each. +4. The app sends `join` for each of its riders, then `update` messages while they ride, and + `leave` when they stop. +5. The server sends `joined`, `updated` and `left` for riders of other connections in the routes + and rooms the app has subscribed to. + +Subscribing and joining are independent. An app can watch a route without riders on it, and it +can put riders on a route without watching it. + +### 3.5 Keepalive and disconnect + +The server sends a WebSocket ping at least every 15 seconds. If no pong arrives within 30 +seconds, the server closes the connection. + +When a connection closes, all of its riders leave with reason `disconnect`. An app that +reconnects MUST send `hello`, `subscribe` and `join` again. Its riders get new server IDs. + +Apps SHOULD reconnect with exponential backoff (for example 1 s, 2 s, 4 s, up to 60 s). + +## 4. Routes + +### 4.1 Route files + +Shared routes are published in this repository as `routes/.json` and validated by +[`schemas/route.schema.json`](../schemas/route.schema.json). + +```json +{ + "id": "velodrome-250", + "name": "Velodrome 250 m", + "length": 250, + "loop": true, + "profile": [[0, 0], [250, 0]] +} +``` + +| Field | Meaning | +|---|---| +| `id` | stable route ID, `^[a-z0-9][a-z0-9-]{1,63}$` | +| `name` | display name | +| `length` | route length in metres, greater than 0 | +| `loop` | `true` if the end of the route joins its start | +| `profile` | list of `[distance, elevation]` points in metres | + +Rules for `profile`: + +- The first point has distance 0 and the last point has distance `length`. +- Distances strictly increase. +- Elevation between two points is linear interpolation. The gradient between two points is the + elevation difference divided by the distance difference. +- On a loop, the first and last elevation MUST be equal. + +A route describes only distance and elevation. Geometry, curves, banking, width and scenery are +up to each app. A rider at the same distance is at the same spot on the route in every app. + +### 4.2 Route identity + +A published route file MUST NOT change. A changed route is published under a new ID, for example +`velodrome-250-v2`. + +### 4.3 Position + +A rider's position is given by two fields: + +- `distance`: metres from the start of the route, `0 ≤ distance < length`. On a loop, the + distance goes back to 0 when the rider crosses the start line. +- `lap`: number of laps the rider has finished since joining, an integer ≥ 0. On a route that is + not a loop, `lap` is always 0. + +Apps place riders by `distance`. `lap` is extra information, for example for a leaderboard. + +On a route that is not a loop, a rider who reaches the end SHOULD leave. + +### 4.4 The first route + +`velodrome-250` is a flat 250 m loop. It is the first shared route because every app can build +it the same way. + +## 5. App identification + +An app identifies itself in `hello` with an app ID, for example `openradlr`. The ID: + +- matches `^[a-z0-9][a-z0-9-]{1,31}$`, +- is chosen by the app's developers and SHOULD be the app's name, +- needs no registration, approval or secret. + +The ID is a claim, not proof. Servers use it for statistics and show it with each rider, so +users can see which app a rider uses. Servers MUST NOT use it to grant access. + +To avoid two apps choosing the same ID, developers SHOULD add their app to +[`apps.md`](../apps.md) with a pull request. The list is for discovery only, and servers do not +check it. + +## 6. Messages from the app + +### 6.1 `hello` + +```json +{"type": "hello", "app": {"id": "openradlr", "version": "0.3.1", "name": "OpenRadlr", "url": "https://openradlr.com"}} +``` + +| Field | Required | Meaning | +|---|---|---| +| `app.id` | yes | app ID (section 5) | +| `app.version` | yes | app version, free text, at most 32 characters | +| `app.name` | no | display name of the app, at most 32 characters | +| `app.url` | no | website of the app, at most 200 characters | + +`hello` MUST be sent exactly once. A second `hello` gets the error `hello_repeated`. + +### 6.2 `subscribe` and `unsubscribe` + +```json +{"type": "subscribe", "route": "velodrome-250", "room": "public"} +{"type": "unsubscribe", "route": "velodrome-250", "room": "public"} +``` + +`room` is optional and defaults to `public`. It matches `^[a-z0-9][a-z0-9-]{0,31}$`. + +After `subscribe` the server sends a `snapshot` of the room, then `joined`, `updated` and `left` +for that room until `unsubscribe` or disconnect. Subscribing twice to the same route and room has +no effect beyond a new `snapshot`. + +Apps SHOULD use the room `public`. In v0 any valid room name works the same way. Room names are +not secret and give no privacy. + +### 6.3 `join` + +```json +{"type": "join", "rider": "u-1842", "route": "velodrome-250", "room": "public", "name": "Anna", + "lap": 0, "distance": 0, "speed": 0} +``` + +| Field | Required | Meaning | +|---|---|---| +| `rider` | yes | the app's own ID for this rider, 1 to 64 characters, unique within the connection | +| `route` | yes | route ID | +| `room` | no | room, default `public` | +| `name` | yes | display name, 1 to 32 characters, no control characters | +| `lap`, `distance`, `speed`, `power`, `cadence`, `heart_rate` | as in `update` | the starting state | + +The server never shows the app's `rider` value to other apps. Apps SHOULD NOT use personal data, +such as an e-mail address, as the rider value. + +A rider that has already joined MUST leave before it joins again, on the same or another route. + +### 6.4 `update` + +```json +{"type": "update", "riders": [ + {"rider": "u-1842", "lap": 3, "distance": 112.4, "speed": 11.8, "power": 245, "cadence": 92, "heart_rate": 151}, + {"rider": "u-2077", "lap": 1, "distance": 20.0, "speed": 9.6} +]} +``` + +| Field | Required | Range | +|---|---|---| +| `rider` | yes | a joined rider of this connection | +| `lap` | yes | integer, ≥ 0 | +| `distance` | yes | `0 ≤ distance < length` of the route | +| `speed` | yes | 0 to 30 | +| `power` | no | integer, 0 to 3000 | +| `cadence` | no | integer, 0 to 250 | +| `heart_rate` | no | integer, 20 to 250 | + +One `update` carries any number of riders of the connection, on any routes. Apps SHOULD send +each rider about once per second and MUST NOT send a rider more often than `max_update_hz` +(section 9). + +The server checks each rider entry on its own. An invalid entry is dropped and answered with an +`error`. The other entries of the message still apply. + +If the server receives no update for a rider for `rider_timeout_s` seconds (section 9), the +rider leaves with reason `timeout`. + +### 6.5 `leave` + +```json +{"type": "leave", "rider": "u-1842"} +``` + +The rider leaves its route with reason `leave`. + +## 7. Messages from the server + +Remote riders are identified by an `id` the server assigns. It is at most 16 characters, unique +on the server, and not reused while the server runs. A server does not send an app its own +riders. + +### 7.1 `welcome` + +```json +{"type": "welcome", "protocol": "0.1", "connection": "c9Qe4", + "limits": {"max_update_hz": 4, "rider_timeout_s": 10, "max_riders": 200, "max_subscriptions": 16, "max_message_bytes": 65536}} +``` + +`protocol` is the minor version of v0 the server implements. `connection` is the server's ID for +the connection, useful when reporting problems. + +### 7.2 `snapshot` + +```json +{"type": "snapshot", "route": "velodrome-250", "room": "public", "riders": [ + {"id": "r7Kx2", "app": "incyclist", "name": "Ben", "lap": 5, "distance": 201.3, "speed": 12.1, "power": 260} +]} +``` + +All riders in the room from other connections, with their latest state. + +### 7.3 `joined` + +```json +{"type": "joined", "route": "velodrome-250", "room": "public", + "rider": {"id": "r7Kx2", "app": "incyclist", "name": "Ben", "lap": 0, "distance": 0, "speed": 0}} +``` + +### 7.4 `updated` + +```json +{"type": "updated", "route": "velodrome-250", "room": "public", "riders": [ + {"id": "r7Kx2", "lap": 5, "distance": 213.4, "speed": 12.1, "power": 262} +]} +``` + +The server passes each `update` on without delay. A server MAY combine updates of several +riders into one `updated` message. Optional fields appear only if the app sent them. + +Apps SHOULD interpolate remote riders between updates so they move smoothly. + +### 7.5 `left` + +```json +{"type": "left", "route": "velodrome-250", "room": "public", "id": "r7Kx2", "reason": "timeout"} +``` + +`reason` is `leave`, `timeout` or `disconnect`. + +### 7.6 `error` + +```json +{"type": "error", "code": "invalid_value", "message": "distance must be below 250", "ref": "42", "rider": "u-1842", "fatal": false} +``` + +| Field | Meaning | +|---|---| +| `code` | one of the codes below | +| `message` | text for developers, not meant for users | +| `ref` | the `ref` of the message that caused the error, if it had one | +| `rider` | the app's rider value, if the error is about one rider | +| `fatal` | `true` if the server closes the connection right after this message | + +| Code | Fatal | When | +|---|---|---| +| `hello_required` | yes | the first message was not `hello`, or no `hello` arrived in 10 seconds | +| `hello_repeated` | no | a second `hello` | +| `invalid_message` | no | not valid JSON, missing or wrong field | +| `unknown_type` | no | unknown `type` | +| `invalid_app_id` | yes | `app.id` does not match the format | +| `unknown_route` | no | the route does not exist on this server | +| `invalid_room` | no | the room does not match the format | +| `rider_exists` | no | `join` for a rider that has already joined | +| `unknown_rider` | no | `update` or `leave` for a rider that has not joined | +| `invalid_value` | no | a value is out of range | +| `rate_limited` | no | a rider was sent more often than `max_update_hz`; the entry is dropped | +| `limit_exceeded` | no | `max_riders` or `max_subscriptions` reached | +| `message_too_large` | yes | a message is larger than `max_message_bytes` | +| `too_many_errors` | yes | the connection keeps causing errors | + +## 8. Usage statistics + +Servers SHOULD publish usage per app ID as JSON at `GET /v0/stats` (plain HTTPS, same host): + +```json +{"apps": [ + {"id": "openradlr", "versions": ["0.3.1"], "connections": 1, "riders": 4, + "first_seen": "2026-11-20", "last_seen": "2026-11-21", "rider_minutes_30d": 812} +]} +``` + +| Field | Meaning | +|---|---| +| `versions` | app versions seen in the last 30 days | +| `connections`, `riders` | open connections and riders right now | +| `first_seen`, `last_seen` | UTC dates of the first and the most recent connection | +| `rider_minutes_30d` | minutes ridden by riders of the app in the last 30 days | + +## 9. Limits + +Servers announce their limits in `welcome`. Recommended values: + +| Limit | Value | +|---|---| +| `max_update_hz` per rider | 4 | +| `rider_timeout_s` | 10 | +| `max_riders` per connection | 200 | +| `max_subscriptions` per connection | 16 | +| `max_message_bytes` | 65536 | +| open connections per IP address | 10 | + +## 10. Privacy + +- Riders are shown to others by display name only. Apps SHOULD let riders choose this name and + SHOULD NOT send full real names without the rider's consent. +- Servers MUST NOT store display names, rider values, positions or IP addresses beyond what the + running connections need. Only the per-app statistics of section 8 are stored. +- Power, cadence and heart rate are optional. Apps SHOULD let riders turn off sharing them. From 1454515fa71a015222efb3c43613d7fea34b3f4f Mon Sep 17 00:00:00 2001 From: Lethonium Dev Server <38733902+RalfLeonFasler@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:44:54 +0000 Subject: [PATCH 2/4] Add implementation plan for v0 schemas, route and examples Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-11-06-protocol-v0-artifacts.md | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-06-protocol-v0-artifacts.md diff --git a/docs/superpowers/plans/2026-11-06-protocol-v0-artifacts.md b/docs/superpowers/plans/2026-11-06-protocol-v0-artifacts.md new file mode 100644 index 0000000..36d123c --- /dev/null +++ b/docs/superpowers/plans/2026-11-06-protocol-v0-artifacts.md @@ -0,0 +1,161 @@ +# Protocol v0 Artifacts Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add the machine-readable parts of the v0 spec to the protocol repo: JSON Schemas, the `velodrome-250` route, example messages, `apps.md`, and CI that checks them. + +**Architecture:** Schemas in `schemas/`, the route in `routes/`, examples in `examples/`. One Python script `tools/validate.py` checks everything and is the single CI step. The examples are the shared test data: the reference server's tests read them through a git submodule. + +**Tech Stack:** JSON Schema draft 2020-12, Python 3 with `jsonschema` (pinned in `tools/requirements.txt`), GitHub Actions. + +**Spec:** `spec/v0.md` (branch `spec-v0-draft`). Server design: `server/docs/design.md`. + +## Global Constraints + +- Work on the branch `spec-v0-draft`. Commits end with `Co-Authored-By: Claude Opus 5.5 `. Do not push. +- Schemas use `"$schema": "https://json-schema.org/draft/2020-12/schema"`, with `"$id"` set to `https://github.com/OpenBikeNet/protocol/schemas/`. +- **Unknown fields are allowed everywhere** (spec 3.2): never set `additionalProperties: false`. +- Formats, copied from the spec: app ID `^[a-z0-9][a-z0-9-]{1,31}$`, route ID `^[a-z0-9][a-z0-9-]{1,63}$`, room `^[a-z0-9][a-z0-9-]{0,31}$`, `ref` at most 64 characters, `rider` 1 to 64 characters, `name` 1 to 32 characters with no control characters (in the schema file: `"pattern": "^[^\\u0000-\\u001f\\u007f]+$"`), `app.version` 1 to 32 characters, `app.name` up to 32, `app.url` up to 200, server rider ID and connection ID up to 16 characters. +- Value ranges (spec 6.4): `lap` integer ≥ 0, `distance` number ≥ 0 (the upper bound depends on the route, so the schema can't check it), `speed` 0 to 30, `power` integer 0 to 3000, `cadence` integer 0 to 250, `heart_rate` integer 20 to 250. +- Every example JSON in the spec MUST exist as a file in `examples/` with the same content, so spec and examples can't drift. +- Licenses: the schemas, examples and tools are MIT (`LICENSE-CODE`); spec text and `apps.md` are CC BY 4.0. No license headers in files. +- Pinned CI action SHAs (same as OpenRadlr): `actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1`. + +## Review Focus + +1. **An app adds a field we don't know yet**, e.g. `hello` with `"platform": "web"`. It must still validate. Pinned by `examples/app/hello-extra-field.json` (Task 2). +2. **A loop route whose start and end elevation differ** would give a step at the start line. It must be rejected. Pinned by `tools/fixtures/invalid-routes/loop-elevation-mismatch.json` (Task 1). +3. **Route file name and `id` differ** (`routes/velodrome.json` with `id: velodrome-250`). Servers load by file, apps refer by ID. It must be rejected. Pinned by a check in `validate.py` plus the fixture `tools/fixtures/misnamed-route/velodrome.json` (Task 1). +4. **A JSON example in the spec doesn't match the file in `examples/`.** `validate.py` extracts every ```` ```json ```` block of `spec/v0.md` and checks that each object appears in `examples/` (Task 2). +5. **An `update` with a non-integer `lap` (1.5) or `power` (245.5)** must fail, not be rounded. Pinned by `examples/invalid/app/invalid_value--fractional-lap.json` (Task 2). + +--- + +### Task 1: Route schema, velodrome route, validator and CI + +**Files:** +- Create: `schemas/route.schema.json` +- Create: `routes/velodrome-250.json` +- Create: `tools/validate.py`, `tools/requirements.txt` (`jsonschema==4.23.0`) +- Create: `tools/fixtures/invalid-routes/{last-point-not-length,distances-not-increasing,first-point-not-zero,loop-elevation-mismatch,bad-id}.json` +- Create: `tools/fixtures/misnamed-route/velodrome.json` +- Create: `apps.md` +- Create: `.github/workflows/validate.yml` +- Modify: `README.md` ("What will live here" becomes a "Contents" list with links) + +**Interfaces:** +- Produces: `routes/.json` files (read by the server's `routes` module), and `python3 tools/validate.py`, which exits 0 when everything is valid and otherwise prints one line per problem (`: `) and exits 1. Task 2 adds checks to it. + +- [ ] **Step 1: Write the invalid route fixtures** + +Each fixture is a velodrome-like route with exactly one defect: +- `last-point-not-length.json`: `length` 250, profile `[[0,0],[200,0]]` +- `distances-not-increasing.json`: profile `[[0,0],[100,0],[100,1],[250,0]]` +- `first-point-not-zero.json`: profile `[[10,0],[250,0]]` +- `loop-elevation-mismatch.json`: `loop` true, profile `[[0,0],[250,5]]` +- `bad-id.json`: `id` `"Velodrome_250"` + +Plus `tools/fixtures/misnamed-route/velodrome.json`: a valid route with `id` `velodrome-250`. + +- [ ] **Step 2: Write `tools/validate.py` with the route checks** + +`check_route(path: Path, route: dict) -> list[str]` returns the problems: +- schema errors from `route.schema.json`, +- first distance ≠ 0, last distance ≠ `length`, distances not strictly increasing, and on a loop, first elevation ≠ last elevation, +- the file name stem ≠ `id`. + +`main()` runs `check_route` on every file in `routes/`, plus a duplicate-ID check. It then asserts that every file in `tools/fixtures/invalid-routes/` and `tools/fixtures/misnamed-route/` gives **at least one** problem, and reports `": expected invalid, but passed"` if one doesn't. Use `jsonschema.Draft202012Validator`. Paths are relative to the repo root, found via `Path(__file__).resolve().parent.parent`. + +- [ ] **Step 3: Run the validator before the schema and route exist** + +Run: `python3 tools/validate.py` +Expected: exit 1, and it says the route schema is missing. It does not crash with a traceback. + +- [ ] **Step 4: Write `schemas/route.schema.json` and `routes/velodrome-250.json`** + +Schema: required `id` (pattern), `name` (string, 1 to 64 characters), `length` (number, `exclusiveMinimum: 0`), `loop` (boolean), `profile` (array, `minItems` 2, items are arrays of exactly 2 numbers). The route file is the one in spec 4.1, verbatim. + +- [ ] **Step 5: Run the validator** + +Run: `python3 tools/validate.py` +Expected: exit 0, no output. Then temporarily set `"loop": false` in `tools/fixtures/invalid-routes/loop-elevation-mismatch.json`, and expect exit 1 with `expected invalid, but passed`. Restore the file. + +- [ ] **Step 6: Write `apps.md`, `README.md` and the CI workflow** + +`apps.md`: one paragraph saying the list is optional and only for discovery, that servers don't check it (spec 5), and that you add your app by PR. Then a table `| App ID | App | Website | Contact |` with one row: `openradlr | OpenRadlr | https://openradlr.com | GitHub @RalfLeonFasler`. + +`README.md`: replace the "What will live here" section with "Contents": links to `spec/v0.md`, `routes/`, `schemas/`, `examples/`, `apps.md`, and the line "Run `python3 tools/validate.py` to check routes, schemas and examples." Keep the rest unchanged. + +`.github/workflows/validate.yml`: runs on `push` to main and on `pull_request`, with `permissions: contents: read`. One job on `ubuntu-latest`: checkout (pinned SHA), `python3 -m venv .venv`, `.venv/bin/pip install -r tools/requirements.txt`, `.venv/bin/python tools/validate.py`. + +- [ ] **Step 7: Commit** + +```bash +git add schemas routes tools apps.md README.md .github +git commit -m "Add route schema, velodrome-250 route and validation" +``` + +### Task 2: Message and stats schemas with examples + +**Files:** +- Create: `schemas/app-message.schema.json`, `schemas/server-message.schema.json`, `schemas/stats.schema.json` +- Create: `examples/app/{hello,hello-extra-field,subscribe,unsubscribe,join,update,leave}.json` +- Create: `examples/server/{welcome,snapshot,joined,updated,left,error}.json` +- Create: `examples/stats.json` +- Create: `examples/invalid/app/--.json` (list in Step 1) +- Modify: `tools/validate.py` + +**Interfaces:** +- Consumes: `tools/validate.py` from Task 1. +- Produces: `examples/app/*.json` (valid messages from apps) and `examples/invalid/app/--.json`, where the part before `--` is the exact error code a server MUST answer with. The server's protocol tests rely on this naming. + +- [ ] **Step 1: Write the examples** + +`examples/app/*`, `examples/server/*` and `examples/stats.json` are the spec's JSON blocks, verbatim (spec 6.1–7.6 and 8). The two objects in the spec 6.2 block become `subscribe.json` and `unsubscribe.json`. `hello-extra-field.json` is `hello.json` with `"platform": "web"` added. + +`examples/invalid/app/` (each with one defect, otherwise like the valid example): +- `invalid_app_id--uppercase.json`: hello with `app.id` `"OpenRadlr"` +- `invalid_message--hello-without-version.json` +- `invalid_message--missing-type.json`: `{"route": "velodrome-250"}` +- `unknown_type--ride.json`: `{"type": "ride"}` +- `invalid_room--uppercase.json`: subscribe with room `"Public"` +- `invalid_value--speed-too-high.json`: update with one rider, speed 45 +- `invalid_value--negative-lap.json`: update with one rider, lap −1 +- `invalid_value--fractional-lap.json`: update with one rider, lap 1.5 +- `invalid_value--name-too-long.json`: join with a 33-character name + +- [ ] **Step 2: Extend `tools/validate.py` and run it before the schemas exist** + +Add these checks: +- `examples/app/*` are valid against `app-message.schema.json`, and `examples/server/*` against `server-message.schema.json`. +- `examples/stats.json` is valid against `stats.schema.json`. +- Every file in `examples/invalid/app/` is **invalid** against `app-message.schema.json`, and its code prefix is one of the 14 codes in spec 7.6. +- Every ```` ```json ```` block in `spec/v0.md` is read as JSON (a block may hold several objects, one per line or spread over lines; use `json.JSONDecoder.raw_decode` in a loop). Each object must equal (`==` after parsing) the content of some file under `examples/` or `routes/`. + +Run: `python3 tools/validate.py` +Expected: exit 1, saying the message schemas are missing. + +- [ ] **Step 3: Write the three schemas** + +`app-message.schema.json`: `$defs` for `riderState` (the ranges from Global Constraints; `lap`, `distance`, `speed` required) and `ref`. The top level is a `oneOf` with one branch per `type` (`const`), so an unknown `type` matches no branch. Branches: +- `hello`: required `app`, with required `id` and `version` +- `subscribe` / `unsubscribe`: required `route`; optional `room` +- `join`: required `rider`, `route`, `name`, plus the state; optional `room` +- `update`: required `riders`, an array of objects with `rider` plus the state +- `leave`: required `rider` + +`server-message.schema.json`: `welcome`, `snapshot`, `joined`, `updated`, `left`, `error` as in spec 7. `left.reason` is an enum of `leave`, `timeout`, `disconnect`, and `error.code` is an enum of the 14 codes. A rider view is `id` + `app` + `name` + the state, and an updated entry is `id` + the state. `welcome.limits` requires all five limits as integers ≥ 1. + +`stats.schema.json`: `apps` is an array of objects with all seven fields from spec 8. Dates use the pattern `^\d{4}-\d{2}-\d{2}$`. + +- [ ] **Step 4: Run the validator** + +Run: `python3 tools/validate.py` +Expected: exit 0. Then temporarily change `"speed": 11.8` to `"speed": 12` in `examples/app/update.json`, and expect exit 1 with a spec-mismatch line for that block. Restore the file. + +- [ ] **Step 5: Commit** + +```bash +git add schemas examples tools +git commit -m "Add message and stats schemas with examples" +``` From eee50850be3e8b3b49bae15a8995db3732b824d7 Mon Sep 17 00:00:00 2001 From: Lethonium Dev Server <38733902+RalfLeonFasler@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:53:44 +0000 Subject: [PATCH 3/4] Add route schema, velodrome-250 route and validation Co-Authored-By: Claude Opus 5.5 --- .github/workflows/validate.yml | 21 +++ README.md | 13 +- apps.md | 9 ++ routes/velodrome-250.json | 7 + schemas/route.schema.json | 38 ++++++ tools/fixtures/invalid-routes/bad-id.json | 7 + .../distances-not-increasing.json | 7 + .../invalid-routes/first-point-not-zero.json | 7 + .../invalid-routes/last-point-not-length.json | 7 + .../loop-elevation-mismatch.json | 7 + tools/fixtures/misnamed-route/velodrome.json | 7 + tools/requirements.txt | 1 + tools/validate.py | 123 ++++++++++++++++++ 13 files changed, 249 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/validate.yml create mode 100644 apps.md create mode 100644 routes/velodrome-250.json create mode 100644 schemas/route.schema.json create mode 100644 tools/fixtures/invalid-routes/bad-id.json create mode 100644 tools/fixtures/invalid-routes/distances-not-increasing.json create mode 100644 tools/fixtures/invalid-routes/first-point-not-zero.json create mode 100644 tools/fixtures/invalid-routes/last-point-not-length.json create mode 100644 tools/fixtures/invalid-routes/loop-elevation-mismatch.json create mode 100644 tools/fixtures/misnamed-route/velodrome.json create mode 100644 tools/requirements.txt create mode 100644 tools/validate.py diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..6dd9a42 --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,21 @@ +name: Validate + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install validator dependencies + run: | + python3 -m venv .venv + .venv/bin/pip install -r tools/requirements.txt + - name: Validate routes, schemas and examples + run: .venv/bin/python tools/validate.py diff --git a/README.md b/README.md index ab5e9e7..a507b7c 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,16 @@ This repository holds the open protocol that lets indoor cycling apps share ride of different apps can meet on the same road. See the [organisation profile](https://github.com/OpenBikeNet) for the overall goal. -## What will live here +## Contents -- **The specification**: messages, transport, versioning. -- **Shared routes**: canonical route files with stable IDs, so that a position on a route means +- [`spec/v0.md`](spec/v0.md): the specification (messages, transport, versioning). +- [`routes/`](routes/): shared route files with stable IDs, so that a position on a route means the same spot in every app. -- **JSON schemas and examples** for the messages. -- **Conformance tests** that any client or server implementation can run. +- [`schemas/`](schemas/): JSON Schemas for routes and messages. +- [`examples/`](examples/): example messages, used as shared test data. +- [`apps.md`](apps.md): optional list of apps that speak the protocol. + +Run `python3 tools/validate.py` to check routes, schemas and examples. The reference server will live in its own repository. diff --git a/apps.md b/apps.md new file mode 100644 index 0000000..268d0fa --- /dev/null +++ b/apps.md @@ -0,0 +1,9 @@ +# Apps + +This list is optional. It exists only to help people find apps that speak the protocol. Servers +don't check it (spec 5), so an app works whether or not it is listed here. To add your app, open a +pull request that adds a row. + +| App ID | App | Website | Contact | +|---|---|---|---| +| openradlr | OpenRadlr | https://openradlr.com | GitHub @RalfLeonFasler | diff --git a/routes/velodrome-250.json b/routes/velodrome-250.json new file mode 100644 index 0000000..301a00a --- /dev/null +++ b/routes/velodrome-250.json @@ -0,0 +1,7 @@ +{ + "id": "velodrome-250", + "name": "Velodrome 250 m", + "length": 250, + "loop": true, + "profile": [[0, 0], [250, 0]] +} diff --git a/schemas/route.schema.json b/schemas/route.schema.json new file mode 100644 index 0000000..5df68af --- /dev/null +++ b/schemas/route.schema.json @@ -0,0 +1,38 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/OpenBikeNet/protocol/schemas/route.schema.json", + "title": "OpenBikeNet route", + "description": "A shared route file, routes/.json. See spec/v0.md section 4.", + "type": "object", + "required": ["id", "name", "length", "loop", "profile"], + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]{1,63}$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "length": { + "type": "number", + "exclusiveMinimum": 0 + }, + "loop": { + "type": "boolean" + }, + "profile": { + "type": "array", + "minItems": 2, + "items": { + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { + "type": "number" + } + } + } + } +} diff --git a/tools/fixtures/invalid-routes/bad-id.json b/tools/fixtures/invalid-routes/bad-id.json new file mode 100644 index 0000000..7c8fd68 --- /dev/null +++ b/tools/fixtures/invalid-routes/bad-id.json @@ -0,0 +1,7 @@ +{ + "id": "Velodrome_250", + "name": "Bad ID", + "length": 250, + "loop": true, + "profile": [[0, 0], [250, 0]] +} diff --git a/tools/fixtures/invalid-routes/distances-not-increasing.json b/tools/fixtures/invalid-routes/distances-not-increasing.json new file mode 100644 index 0000000..2807a2c --- /dev/null +++ b/tools/fixtures/invalid-routes/distances-not-increasing.json @@ -0,0 +1,7 @@ +{ + "id": "distances-not-increasing", + "name": "Distances not increasing", + "length": 250, + "loop": true, + "profile": [[0, 0], [100, 0], [100, 1], [250, 0]] +} diff --git a/tools/fixtures/invalid-routes/first-point-not-zero.json b/tools/fixtures/invalid-routes/first-point-not-zero.json new file mode 100644 index 0000000..038e0af --- /dev/null +++ b/tools/fixtures/invalid-routes/first-point-not-zero.json @@ -0,0 +1,7 @@ +{ + "id": "first-point-not-zero", + "name": "First point not zero", + "length": 250, + "loop": true, + "profile": [[10, 0], [250, 0]] +} diff --git a/tools/fixtures/invalid-routes/last-point-not-length.json b/tools/fixtures/invalid-routes/last-point-not-length.json new file mode 100644 index 0000000..362f6e7 --- /dev/null +++ b/tools/fixtures/invalid-routes/last-point-not-length.json @@ -0,0 +1,7 @@ +{ + "id": "last-point-not-length", + "name": "Last point not length", + "length": 250, + "loop": true, + "profile": [[0, 0], [200, 0]] +} diff --git a/tools/fixtures/invalid-routes/loop-elevation-mismatch.json b/tools/fixtures/invalid-routes/loop-elevation-mismatch.json new file mode 100644 index 0000000..cc42cb2 --- /dev/null +++ b/tools/fixtures/invalid-routes/loop-elevation-mismatch.json @@ -0,0 +1,7 @@ +{ + "id": "loop-elevation-mismatch", + "name": "Loop elevation mismatch", + "length": 250, + "loop": true, + "profile": [[0, 0], [250, 5]] +} diff --git a/tools/fixtures/misnamed-route/velodrome.json b/tools/fixtures/misnamed-route/velodrome.json new file mode 100644 index 0000000..301a00a --- /dev/null +++ b/tools/fixtures/misnamed-route/velodrome.json @@ -0,0 +1,7 @@ +{ + "id": "velodrome-250", + "name": "Velodrome 250 m", + "length": 250, + "loop": true, + "profile": [[0, 0], [250, 0]] +} diff --git a/tools/requirements.txt b/tools/requirements.txt new file mode 100644 index 0000000..89099e3 --- /dev/null +++ b/tools/requirements.txt @@ -0,0 +1 @@ +jsonschema==4.23.0 diff --git a/tools/validate.py b/tools/validate.py new file mode 100644 index 0000000..44d29e7 --- /dev/null +++ b/tools/validate.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Check the routes and the invalid fixtures of the OpenBikeNet protocol. + +Prints one line per problem as `: ` and exits 1 if there is any problem. +Paths are relative to the repository root. +""" +import json +import sys +from functools import lru_cache +from pathlib import Path + +from jsonschema import Draft202012Validator + +ROOT = Path(__file__).resolve().parent.parent +ROUTES = ROOT / "routes" +ROUTE_SCHEMA = ROOT / "schemas" / "route.schema.json" +INVALID_ROUTES = ROOT / "tools" / "fixtures" / "invalid-routes" +MISNAMED_ROUTES = ROOT / "tools" / "fixtures" / "misnamed-route" + + +def rel(path): + return path.relative_to(ROOT).as_posix() + + +def is_number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def is_point(value): + return isinstance(value, list) and len(value) == 2 and all(is_number(v) for v in value) + + +@lru_cache(maxsize=None) +def route_validator(): + return Draft202012Validator(json.loads(ROUTE_SCHEMA.read_text(encoding="utf-8"))) + + +def load_json(path): + """Return (value, None) or (None, problem) for a file that is not readable JSON.""" + try: + return json.loads(path.read_text(encoding="utf-8")), None + except (OSError, ValueError) as error: + return None, f"{rel(path)}: cannot read JSON: {error}" + + +def check_route(path, route): + name = rel(path) + if not isinstance(route, dict): + return [f"{name}: route must be a JSON object"] + + problems = [] + for error in route_validator().iter_errors(route): + where = "/".join(str(part) for part in error.path) or "(root)" + problems.append(f"{name}: {where}: {error.message}") + + profile = route.get("profile") + if isinstance(profile, list) and len(profile) >= 2 and all(is_point(p) for p in profile): + distances = [p[0] for p in profile] + if distances[0] != 0: + problems.append(f"{name}: first profile distance is {distances[0]}, expected 0") + length = route.get("length") + if is_number(length) and distances[-1] != length: + problems.append( + f"{name}: last profile distance is {distances[-1]}, expected length {length}" + ) + for before, after in zip(distances, distances[1:]): + if after <= before: + problems.append( + f"{name}: profile distances do not strictly increase ({before}, then {after})" + ) + if route.get("loop") is True and profile[0][1] != profile[-1][1]: + problems.append( + f"{name}: loop route starts at elevation {profile[0][1]} " + f"but ends at {profile[-1][1]}" + ) + + if route.get("id") != path.stem: + problems.append(f"{name}: file name does not match id {route.get('id')!r}") + + return problems + + +def main(): + problems = [] + + if not ROUTE_SCHEMA.is_file(): + problems.append(f"{rel(ROUTE_SCHEMA)}: route schema is missing") + return report(problems) + + ids = {} + for path in sorted(ROUTES.glob("*.json")): + route, error = load_json(path) + if error: + problems.append(error) + continue + problems.extend(check_route(path, route)) + route_id = route.get("id") if isinstance(route, dict) else None + if isinstance(route_id, str): + if route_id in ids: + problems.append( + f"{rel(path)}: duplicate id {route_id!r}, also in {rel(ids[route_id])}" + ) + else: + ids[route_id] = path + + for folder in (INVALID_ROUTES, MISNAMED_ROUTES): + for path in sorted(folder.glob("*.json")): + route, error = load_json(path) + if error or check_route(path, route): + continue + problems.append(f"{rel(path)}: expected invalid, but passed") + + return report(problems) + + +def report(problems): + for problem in problems: + print(problem) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) From a557731beb0c2e364814a7440ae2309b3c631511 Mon Sep 17 00:00:00 2001 From: Lethonium Dev Server <38733902+RalfLeonFasler@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:55:46 +0000 Subject: [PATCH 4/4] Add message and stats schemas with examples Co-Authored-By: Claude Opus 5.5 --- examples/app/hello-extra-field.json | 10 ++ examples/app/hello.json | 9 ++ examples/app/join.json | 10 ++ examples/app/leave.json | 4 + examples/app/subscribe.json | 5 + examples/app/unsubscribe.json | 5 + examples/app/update.json | 20 +++ .../app/invalid_app_id--uppercase.json | 9 ++ ...nvalid_message--hello-without-version.json | 8 + .../app/invalid_message--missing-type.json | 3 + .../invalid/app/invalid_room--uppercase.json | 5 + .../app/invalid_value--fractional-lap.json | 11 ++ .../app/invalid_value--name-too-long.json | 10 ++ .../app/invalid_value--negative-lap.json | 11 ++ .../app/invalid_value--speed-too-high.json | 11 ++ examples/invalid/app/unknown_type--ride.json | 3 + examples/server/error.json | 8 + examples/server/joined.json | 13 ++ examples/server/left.json | 7 + examples/server/snapshot.json | 16 ++ examples/server/updated.json | 14 ++ examples/server/welcome.json | 12 ++ examples/stats.json | 15 ++ schemas/app-message.schema.json | 110 +++++++++++++ schemas/server-message.schema.json | 144 ++++++++++++++++++ schemas/stats.schema.json | 34 +++++ tools/validate.py | 92 +++++++++++ 27 files changed, 599 insertions(+) create mode 100644 examples/app/hello-extra-field.json create mode 100644 examples/app/hello.json create mode 100644 examples/app/join.json create mode 100644 examples/app/leave.json create mode 100644 examples/app/subscribe.json create mode 100644 examples/app/unsubscribe.json create mode 100644 examples/app/update.json create mode 100644 examples/invalid/app/invalid_app_id--uppercase.json create mode 100644 examples/invalid/app/invalid_message--hello-without-version.json create mode 100644 examples/invalid/app/invalid_message--missing-type.json create mode 100644 examples/invalid/app/invalid_room--uppercase.json create mode 100644 examples/invalid/app/invalid_value--fractional-lap.json create mode 100644 examples/invalid/app/invalid_value--name-too-long.json create mode 100644 examples/invalid/app/invalid_value--negative-lap.json create mode 100644 examples/invalid/app/invalid_value--speed-too-high.json create mode 100644 examples/invalid/app/unknown_type--ride.json create mode 100644 examples/server/error.json create mode 100644 examples/server/joined.json create mode 100644 examples/server/left.json create mode 100644 examples/server/snapshot.json create mode 100644 examples/server/updated.json create mode 100644 examples/server/welcome.json create mode 100644 examples/stats.json create mode 100644 schemas/app-message.schema.json create mode 100644 schemas/server-message.schema.json create mode 100644 schemas/stats.schema.json diff --git a/examples/app/hello-extra-field.json b/examples/app/hello-extra-field.json new file mode 100644 index 0000000..ef7279e --- /dev/null +++ b/examples/app/hello-extra-field.json @@ -0,0 +1,10 @@ +{ + "type": "hello", + "app": { + "id": "openradlr", + "version": "0.3.1", + "name": "OpenRadlr", + "url": "https://openradlr.com", + "platform": "web" + } +} diff --git a/examples/app/hello.json b/examples/app/hello.json new file mode 100644 index 0000000..629c5a0 --- /dev/null +++ b/examples/app/hello.json @@ -0,0 +1,9 @@ +{ + "type": "hello", + "app": { + "id": "openradlr", + "version": "0.3.1", + "name": "OpenRadlr", + "url": "https://openradlr.com" + } +} diff --git a/examples/app/join.json b/examples/app/join.json new file mode 100644 index 0000000..840e6db --- /dev/null +++ b/examples/app/join.json @@ -0,0 +1,10 @@ +{ + "type": "join", + "rider": "u-1842", + "route": "velodrome-250", + "room": "public", + "name": "Anna", + "lap": 0, + "distance": 0, + "speed": 0 +} diff --git a/examples/app/leave.json b/examples/app/leave.json new file mode 100644 index 0000000..afa62a4 --- /dev/null +++ b/examples/app/leave.json @@ -0,0 +1,4 @@ +{ + "type": "leave", + "rider": "u-1842" +} diff --git a/examples/app/subscribe.json b/examples/app/subscribe.json new file mode 100644 index 0000000..4ea3e52 --- /dev/null +++ b/examples/app/subscribe.json @@ -0,0 +1,5 @@ +{ + "type": "subscribe", + "route": "velodrome-250", + "room": "public" +} diff --git a/examples/app/unsubscribe.json b/examples/app/unsubscribe.json new file mode 100644 index 0000000..495d152 --- /dev/null +++ b/examples/app/unsubscribe.json @@ -0,0 +1,5 @@ +{ + "type": "unsubscribe", + "route": "velodrome-250", + "room": "public" +} diff --git a/examples/app/update.json b/examples/app/update.json new file mode 100644 index 0000000..be66976 --- /dev/null +++ b/examples/app/update.json @@ -0,0 +1,20 @@ +{ + "type": "update", + "riders": [ + { + "rider": "u-1842", + "lap": 3, + "distance": 112.4, + "speed": 11.8, + "power": 245, + "cadence": 92, + "heart_rate": 151 + }, + { + "rider": "u-2077", + "lap": 1, + "distance": 20.0, + "speed": 9.6 + } + ] +} diff --git a/examples/invalid/app/invalid_app_id--uppercase.json b/examples/invalid/app/invalid_app_id--uppercase.json new file mode 100644 index 0000000..f82fa81 --- /dev/null +++ b/examples/invalid/app/invalid_app_id--uppercase.json @@ -0,0 +1,9 @@ +{ + "type": "hello", + "app": { + "id": "OpenRadlr", + "version": "0.3.1", + "name": "OpenRadlr", + "url": "https://openradlr.com" + } +} diff --git a/examples/invalid/app/invalid_message--hello-without-version.json b/examples/invalid/app/invalid_message--hello-without-version.json new file mode 100644 index 0000000..f42338e --- /dev/null +++ b/examples/invalid/app/invalid_message--hello-without-version.json @@ -0,0 +1,8 @@ +{ + "type": "hello", + "app": { + "id": "openradlr", + "name": "OpenRadlr", + "url": "https://openradlr.com" + } +} diff --git a/examples/invalid/app/invalid_message--missing-type.json b/examples/invalid/app/invalid_message--missing-type.json new file mode 100644 index 0000000..b0d7820 --- /dev/null +++ b/examples/invalid/app/invalid_message--missing-type.json @@ -0,0 +1,3 @@ +{ + "route": "velodrome-250" +} diff --git a/examples/invalid/app/invalid_room--uppercase.json b/examples/invalid/app/invalid_room--uppercase.json new file mode 100644 index 0000000..3ed5bec --- /dev/null +++ b/examples/invalid/app/invalid_room--uppercase.json @@ -0,0 +1,5 @@ +{ + "type": "subscribe", + "route": "velodrome-250", + "room": "Public" +} diff --git a/examples/invalid/app/invalid_value--fractional-lap.json b/examples/invalid/app/invalid_value--fractional-lap.json new file mode 100644 index 0000000..1fb02c9 --- /dev/null +++ b/examples/invalid/app/invalid_value--fractional-lap.json @@ -0,0 +1,11 @@ +{ + "type": "update", + "riders": [ + { + "rider": "u-1842", + "lap": 1.5, + "distance": 112.4, + "speed": 11.8 + } + ] +} diff --git a/examples/invalid/app/invalid_value--name-too-long.json b/examples/invalid/app/invalid_value--name-too-long.json new file mode 100644 index 0000000..8f927c0 --- /dev/null +++ b/examples/invalid/app/invalid_value--name-too-long.json @@ -0,0 +1,10 @@ +{ + "type": "join", + "rider": "u-1842", + "route": "velodrome-250", + "room": "public", + "name": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "lap": 0, + "distance": 0, + "speed": 0 +} diff --git a/examples/invalid/app/invalid_value--negative-lap.json b/examples/invalid/app/invalid_value--negative-lap.json new file mode 100644 index 0000000..87acfe1 --- /dev/null +++ b/examples/invalid/app/invalid_value--negative-lap.json @@ -0,0 +1,11 @@ +{ + "type": "update", + "riders": [ + { + "rider": "u-1842", + "lap": -1, + "distance": 112.4, + "speed": 11.8 + } + ] +} diff --git a/examples/invalid/app/invalid_value--speed-too-high.json b/examples/invalid/app/invalid_value--speed-too-high.json new file mode 100644 index 0000000..7a3a544 --- /dev/null +++ b/examples/invalid/app/invalid_value--speed-too-high.json @@ -0,0 +1,11 @@ +{ + "type": "update", + "riders": [ + { + "rider": "u-1842", + "lap": 3, + "distance": 112.4, + "speed": 45 + } + ] +} diff --git a/examples/invalid/app/unknown_type--ride.json b/examples/invalid/app/unknown_type--ride.json new file mode 100644 index 0000000..926744d --- /dev/null +++ b/examples/invalid/app/unknown_type--ride.json @@ -0,0 +1,3 @@ +{ + "type": "ride" +} diff --git a/examples/server/error.json b/examples/server/error.json new file mode 100644 index 0000000..084c3b2 --- /dev/null +++ b/examples/server/error.json @@ -0,0 +1,8 @@ +{ + "type": "error", + "code": "invalid_value", + "message": "distance must be below 250", + "ref": "42", + "rider": "u-1842", + "fatal": false +} diff --git a/examples/server/joined.json b/examples/server/joined.json new file mode 100644 index 0000000..8bcdff3 --- /dev/null +++ b/examples/server/joined.json @@ -0,0 +1,13 @@ +{ + "type": "joined", + "route": "velodrome-250", + "room": "public", + "rider": { + "id": "r7Kx2", + "app": "incyclist", + "name": "Ben", + "lap": 0, + "distance": 0, + "speed": 0 + } +} diff --git a/examples/server/left.json b/examples/server/left.json new file mode 100644 index 0000000..898f0d1 --- /dev/null +++ b/examples/server/left.json @@ -0,0 +1,7 @@ +{ + "type": "left", + "route": "velodrome-250", + "room": "public", + "id": "r7Kx2", + "reason": "timeout" +} diff --git a/examples/server/snapshot.json b/examples/server/snapshot.json new file mode 100644 index 0000000..ee7466e --- /dev/null +++ b/examples/server/snapshot.json @@ -0,0 +1,16 @@ +{ + "type": "snapshot", + "route": "velodrome-250", + "room": "public", + "riders": [ + { + "id": "r7Kx2", + "app": "incyclist", + "name": "Ben", + "lap": 5, + "distance": 201.3, + "speed": 12.1, + "power": 260 + } + ] +} diff --git a/examples/server/updated.json b/examples/server/updated.json new file mode 100644 index 0000000..011ad17 --- /dev/null +++ b/examples/server/updated.json @@ -0,0 +1,14 @@ +{ + "type": "updated", + "route": "velodrome-250", + "room": "public", + "riders": [ + { + "id": "r7Kx2", + "lap": 5, + "distance": 213.4, + "speed": 12.1, + "power": 262 + } + ] +} diff --git a/examples/server/welcome.json b/examples/server/welcome.json new file mode 100644 index 0000000..27d9834 --- /dev/null +++ b/examples/server/welcome.json @@ -0,0 +1,12 @@ +{ + "type": "welcome", + "protocol": "0.1", + "connection": "c9Qe4", + "limits": { + "max_update_hz": 4, + "rider_timeout_s": 10, + "max_riders": 200, + "max_subscriptions": 16, + "max_message_bytes": 65536 + } +} diff --git a/examples/stats.json b/examples/stats.json new file mode 100644 index 0000000..cd48c3e --- /dev/null +++ b/examples/stats.json @@ -0,0 +1,15 @@ +{ + "apps": [ + { + "id": "openradlr", + "versions": [ + "0.3.1" + ], + "connections": 1, + "riders": 4, + "first_seen": "2026-11-20", + "last_seen": "2026-11-21", + "rider_minutes_30d": 812 + } + ] +} diff --git a/schemas/app-message.schema.json b/schemas/app-message.schema.json new file mode 100644 index 0000000..84867ea --- /dev/null +++ b/schemas/app-message.schema.json @@ -0,0 +1,110 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/OpenBikeNet/protocol/schemas/app-message.schema.json", + "title": "OpenBikeNet message from an app", + "description": "A message an app sends to a server. See spec/v0.md sections 3 and 6.", + "type": "object", + "required": ["type"], + "$defs": { + "ref": { "type": "string", "maxLength": 64 }, + "route": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{1,63}$" }, + "room": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{0,31}$" }, + "riderId": { "type": "string", "minLength": 1, "maxLength": 64 }, + "riderState": { + "type": "object", + "required": ["lap", "distance", "speed"], + "properties": { + "lap": { "type": "integer", "minimum": 0 }, + "distance": { "type": "number", "minimum": 0 }, + "speed": { "type": "number", "minimum": 0, "maximum": 30 }, + "power": { "type": "integer", "minimum": 0, "maximum": 3000 }, + "cadence": { "type": "integer", "minimum": 0, "maximum": 250 }, + "heart_rate": { "type": "integer", "minimum": 20, "maximum": 250 } + } + } + }, + "oneOf": [ + { + "title": "hello", + "properties": { + "type": { "const": "hello" }, + "ref": { "$ref": "#/$defs/ref" }, + "app": { + "type": "object", + "required": ["id", "version"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{1,31}$" }, + "version": { "type": "string", "minLength": 1, "maxLength": 32 }, + "name": { "type": "string", "maxLength": 32 }, + "url": { "type": "string", "maxLength": 200 } + } + } + }, + "required": ["type", "app"] + }, + { + "title": "subscribe", + "properties": { + "type": { "const": "subscribe" }, + "ref": { "$ref": "#/$defs/ref" }, + "route": { "$ref": "#/$defs/route" }, + "room": { "$ref": "#/$defs/room" } + }, + "required": ["type", "route"] + }, + { + "title": "unsubscribe", + "properties": { + "type": { "const": "unsubscribe" }, + "ref": { "$ref": "#/$defs/ref" }, + "route": { "$ref": "#/$defs/route" }, + "room": { "$ref": "#/$defs/room" } + }, + "required": ["type", "route"] + }, + { + "title": "join", + "allOf": [{ "$ref": "#/$defs/riderState" }], + "properties": { + "type": { "const": "join" }, + "ref": { "$ref": "#/$defs/ref" }, + "rider": { "$ref": "#/$defs/riderId" }, + "route": { "$ref": "#/$defs/route" }, + "room": { "$ref": "#/$defs/room" }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "pattern": "^[^\\u0000-\\u001f\\u007f]+$" + } + }, + "required": ["type", "rider", "route", "name"] + }, + { + "title": "update", + "properties": { + "type": { "const": "update" }, + "ref": { "$ref": "#/$defs/ref" }, + "riders": { + "type": "array", + "items": { + "allOf": [{ "$ref": "#/$defs/riderState" }], + "type": "object", + "properties": { "rider": { "$ref": "#/$defs/riderId" } }, + "required": ["rider"] + } + } + }, + "required": ["type", "riders"] + }, + { + "title": "leave", + "properties": { + "type": { "const": "leave" }, + "ref": { "$ref": "#/$defs/ref" }, + "rider": { "$ref": "#/$defs/riderId" } + }, + "required": ["type", "rider"] + } + ] +} diff --git a/schemas/server-message.schema.json b/schemas/server-message.schema.json new file mode 100644 index 0000000..cc34a01 --- /dev/null +++ b/schemas/server-message.schema.json @@ -0,0 +1,144 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/OpenBikeNet/protocol/schemas/server-message.schema.json", + "title": "OpenBikeNet message from a server", + "description": "A message a server sends to an app. See spec/v0.md sections 3 and 7.", + "type": "object", + "required": ["type"], + "$defs": { + "route": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{1,63}$" }, + "room": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{0,31}$" }, + "serverId": { "type": "string", "minLength": 1, "maxLength": 16 }, + "state": { + "type": "object", + "required": ["lap", "distance", "speed"], + "properties": { + "lap": { "type": "integer", "minimum": 0 }, + "distance": { "type": "number", "minimum": 0 }, + "speed": { "type": "number", "minimum": 0, "maximum": 30 }, + "power": { "type": "integer", "minimum": 0, "maximum": 3000 }, + "cadence": { "type": "integer", "minimum": 0, "maximum": 250 }, + "heart_rate": { "type": "integer", "minimum": 20, "maximum": 250 } + } + }, + "riderView": { + "allOf": [{ "$ref": "#/$defs/state" }], + "type": "object", + "required": ["id", "app", "name"], + "properties": { + "id": { "$ref": "#/$defs/serverId" }, + "app": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{1,31}$" }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "pattern": "^[^\\u0000-\\u001f\\u007f]+$" + } + } + }, + "riderUpdate": { + "allOf": [{ "$ref": "#/$defs/state" }], + "type": "object", + "required": ["id"], + "properties": { "id": { "$ref": "#/$defs/serverId" } } + } + }, + "oneOf": [ + { + "title": "welcome", + "properties": { + "type": { "const": "welcome" }, + "protocol": { "type": "string", "minLength": 1 }, + "connection": { "$ref": "#/$defs/serverId" }, + "limits": { + "type": "object", + "required": [ + "max_update_hz", + "rider_timeout_s", + "max_riders", + "max_subscriptions", + "max_message_bytes" + ], + "properties": { + "max_update_hz": { "type": "integer", "minimum": 1 }, + "rider_timeout_s": { "type": "integer", "minimum": 1 }, + "max_riders": { "type": "integer", "minimum": 1 }, + "max_subscriptions": { "type": "integer", "minimum": 1 }, + "max_message_bytes": { "type": "integer", "minimum": 1 } + } + } + }, + "required": ["type", "protocol", "connection", "limits"] + }, + { + "title": "snapshot", + "properties": { + "type": { "const": "snapshot" }, + "route": { "$ref": "#/$defs/route" }, + "room": { "$ref": "#/$defs/room" }, + "riders": { "type": "array", "items": { "$ref": "#/$defs/riderView" } } + }, + "required": ["type", "route", "room", "riders"] + }, + { + "title": "joined", + "properties": { + "type": { "const": "joined" }, + "route": { "$ref": "#/$defs/route" }, + "room": { "$ref": "#/$defs/room" }, + "rider": { "$ref": "#/$defs/riderView" } + }, + "required": ["type", "route", "room", "rider"] + }, + { + "title": "updated", + "properties": { + "type": { "const": "updated" }, + "route": { "$ref": "#/$defs/route" }, + "room": { "$ref": "#/$defs/room" }, + "riders": { "type": "array", "items": { "$ref": "#/$defs/riderUpdate" } } + }, + "required": ["type", "route", "room", "riders"] + }, + { + "title": "left", + "properties": { + "type": { "const": "left" }, + "route": { "$ref": "#/$defs/route" }, + "room": { "$ref": "#/$defs/room" }, + "id": { "$ref": "#/$defs/serverId" }, + "reason": { "enum": ["leave", "timeout", "disconnect"] } + }, + "required": ["type", "route", "room", "id", "reason"] + }, + { + "title": "error", + "properties": { + "type": { "const": "error" }, + "code": { + "enum": [ + "hello_required", + "hello_repeated", + "invalid_message", + "unknown_type", + "invalid_app_id", + "unknown_route", + "invalid_room", + "rider_exists", + "unknown_rider", + "invalid_value", + "rate_limited", + "limit_exceeded", + "message_too_large", + "too_many_errors" + ] + }, + "message": { "type": "string" }, + "ref": { "type": "string", "maxLength": 64 }, + "rider": { "type": "string", "minLength": 1, "maxLength": 64 }, + "fatal": { "type": "boolean" } + }, + "required": ["type", "code", "message", "fatal"] + } + ] +} diff --git a/schemas/stats.schema.json b/schemas/stats.schema.json new file mode 100644 index 0000000..c2277e8 --- /dev/null +++ b/schemas/stats.schema.json @@ -0,0 +1,34 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/OpenBikeNet/protocol/schemas/stats.schema.json", + "title": "OpenBikeNet usage statistics", + "description": "The body of GET /v0/stats. See spec/v0.md section 8.", + "type": "object", + "required": ["apps"], + "properties": { + "apps": { + "type": "array", + "items": { + "type": "object", + "required": [ + "id", + "versions", + "connections", + "riders", + "first_seen", + "last_seen", + "rider_minutes_30d" + ], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{1,31}$" }, + "versions": { "type": "array", "items": { "type": "string", "maxLength": 32 } }, + "connections": { "type": "integer", "minimum": 0 }, + "riders": { "type": "integer", "minimum": 0 }, + "first_seen": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }, + "last_seen": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }, + "rider_minutes_30d": { "type": "integer", "minimum": 0 } + } + } + } + } +} diff --git a/tools/validate.py b/tools/validate.py index 44d29e7..c54b4c4 100644 --- a/tools/validate.py +++ b/tools/validate.py @@ -5,6 +5,7 @@ Paths are relative to the repository root. """ import json +import re import sys from functools import lru_cache from pathlib import Path @@ -16,6 +17,16 @@ ROUTE_SCHEMA = ROOT / "schemas" / "route.schema.json" INVALID_ROUTES = ROOT / "tools" / "fixtures" / "invalid-routes" MISNAMED_ROUTES = ROOT / "tools" / "fixtures" / "misnamed-route" +SCHEMAS = ROOT / "schemas" +EXAMPLES = ROOT / "examples" +SPEC = ROOT / "spec" / "v0.md" +MESSAGE_SCHEMAS = ("app-message", "server-message", "stats") +# The 14 error codes of spec 7.6. +ERROR_CODES = { + "hello_required", "hello_repeated", "invalid_message", "unknown_type", "invalid_app_id", + "unknown_route", "invalid_room", "rider_exists", "unknown_rider", "invalid_value", + "rate_limited", "limit_exceeded", "message_too_large", "too_many_errors", +} def rel(path): @@ -35,6 +46,20 @@ def route_validator(): return Draft202012Validator(json.loads(ROUTE_SCHEMA.read_text(encoding="utf-8"))) +@lru_cache(maxsize=None) +def schema_validator(name): + path = SCHEMAS / f"{name}.schema.json" + return Draft202012Validator(json.loads(path.read_text(encoding="utf-8"))) + + +def schema_problems(path, value, name): + """Problem lines for `value` checked against schemas/.schema.json.""" + return [ + f"{rel(path)}: {'/'.join(str(part) for part in error.path) or '(root)'}: {error.message}" + for error in schema_validator(name).iter_errors(value) + ] + + def load_json(path): """Return (value, None) or (None, problem) for a file that is not readable JSON.""" try: @@ -80,6 +105,72 @@ def check_route(path, route): return problems +def spec_objects(): + """Yield (block number, line number, object) for every JSON object in the spec's json blocks.""" + text = SPEC.read_text(encoding="utf-8") + decoder = json.JSONDecoder() + for number, match in enumerate(re.finditer(r"```json\n(.*?)```", text, re.S), 1): + line = text.count("\n", 0, match.start(1)) + 1 + body = match.group(1) + position = 0 + while True: + while position < len(body) and body[position].isspace(): + position += 1 + if position >= len(body): + break + try: + value, position = decoder.raw_decode(body, position) + except ValueError as error: + yield number, line, error + break + yield number, line, value + + +def check_valid(path, schema, problems): + value, error = load_json(path) + if error: + problems.append(error) + else: + problems.extend(schema_problems(path, value, schema)) + + +def check_messages(problems): + missing = [n for n in MESSAGE_SCHEMAS if not (SCHEMAS / f"{n}.schema.json").is_file()] + for name in missing: + problems.append(f"schemas/{name}.schema.json: message schema is missing") + if missing: + return + + for folder, schema in (("app", "app-message"), ("server", "server-message")): + for path in sorted((EXAMPLES / folder).glob("*.json")): + check_valid(path, schema, problems) + check_valid(EXAMPLES / "stats.json", "stats", problems) + + for path in sorted((EXAMPLES / "invalid" / "app").glob("*.json")): + code, separator, _ = path.stem.partition("--") + if not separator or code not in ERROR_CODES: + problems.append(f"{rel(path)}: file name must start with an error code from spec 7.6 and --") + value, error = load_json(path) + if error: + problems.append(error) + elif not schema_problems(path, value, "app-message"): + problems.append(f"{rel(path)}: expected invalid, but passed") + + examples = [] + for path in sorted([*EXAMPLES.rglob("*.json"), *ROUTES.glob("*.json")]): + value, error = load_json(path) + if not error: + examples.append(value) + for number, line, value in spec_objects(): + if isinstance(value, ValueError): + problems.append(f"spec/v0.md:{line}: json block {number} is not valid JSON: {value}") + elif value not in examples: + problems.append( + f"spec/v0.md:{line}: json block {number}: spec mismatch, " + f"no file in examples/ or routes/ has the object {json.dumps(value)[:70]}" + ) + + def main(): problems = [] @@ -110,6 +201,7 @@ def main(): continue problems.append(f"{rel(path)}: expected invalid, but passed") + check_messages(problems) return report(problems)