ICD-002 — Cathode Ray producer API
|
|
| Interface |
producers (scripts, devices, Grafana) → Cathode Ray server |
| API version |
2 (path prefix /api/v2) |
| Document revision |
2.2 (draft for review) |
| Normative artefacts |
this document, schema/icd-002.schema.json, examples/ |
| Related |
ICD-001 v2 (viewer protocol): how pushed data reaches the glasses. ICD-003 (admin): managing keys. |
The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119.
1. Purpose
This is how data gets into Cathode Ray without touching server config:
| What |
Endpoint |
Typical producer |
| Values: "show me this number" |
POST /api/v2/values |
a script on a client's system, a test rig, an ESP32 |
| Activities: "this is in progress" |
PUT /api/v2/activities/{id} |
a backup script, a long build, a soak test |
| Alerts from Grafana |
POST /api/v2/alerts/grafana |
Grafana's webhook contact point |
Design rules:
- One request, no setup. The first push creates the channel. Nothing is configured on the server first.
- Latest value only. Nothing is recorded: values live in memory and are gone after a restart or idle expiry. History belongs in InfluxDB.
- Configure once, push fast. Unit, label, ttl and thresholds stick to the channel, so later pushes can be a bare number.
- A push key can't do anything but push. It can't read views, see other prefixes, or trigger actions.
2. Keys and scopes
Both ICDs use the same key registry. Keys are managed on the server's admin page (ICD-003). Changes take effect immediately, with no restart.
The server stores keys in its state volume (/data/keys.json) and only stores the SHA-256 hash of each secret. A key looks like this (KeyEntry in the schema):
Stored entries also carry the lifecycle fields from ICD-003: enabled, created, rotated, last_used and secret_hint. No plaintext secret is persisted.
{ "name": "acme-project", "sha256": "9a0e…", "scopes": ["push", "activity"], "prefixes": ["acme"] }
| Scope |
Allows |
ICD |
view, ack, edit, control |
viewer protocol |
ICD-001 v2 §12 |
push |
POST/DELETE /values, GET /values for its own prefixes |
§4 |
activity |
PUT/DELETE /activities for its own prefixes |
§5 |
alerts |
POST /alerts/grafana |
§6 |
read |
GET /values for all prefixes |
§4.4 |
Rules:
- A key with
push or activity MUST have prefixes. Each prefix is a single ChannelId segment (acme). A key may only touch ids whose first segment is one of its prefixes.
- Secrets are generated by the server when a key is created or rotated, and shown once. They're 32 random bytes, base62-encoded, with a readable type prefix:
vk_ if the key has a viewer scope, gk_ for alerts-only keys, pk_ otherwise.
- Disabling or deleting a key takes effect immediately. Open WebSocket sessions using it are closed with
4001, and its next HTTP request gets 401. Values it pushed stay until they expire.
- Keys are sent only as
Authorization: Bearer <secret>, never in a URL. The server compares hashes in constant time and never logs secrets.
- First start: with an empty registry, the producer and viewer APIs reject everything. Create the first keys on the admin page.
3. Conventions
| Item |
Rule |
| Base URL |
https://crt.lucavs.nl/api/v2 (TLS only) |
| Bodies |
application/json, UTF-8, except §4.2 (text/plain) |
| Body size |
≤ 64 KiB, else 413 |
| Rate |
20 requests/s per key, burst 40, else 429 with Retry-After |
| Failed auth |
10 requests/min per client IP with a missing or unknown key, then 429 with Retry-After for that IP for 5 min. The 401 body is identical for every failure. |
| Unknown JSON fields |
ignored (must-ignore), except inside value specs (§4.1), where they're rejected to catch typos |
| Atomicity |
a request is validated completely before anything is applied. One bad entry rejects the whole request. |
| Idempotency |
all writes are upserts; repeating a request is safe |
3.1 Errors
Every 4xx/5xx body is:
{ "error": { "code": "INVALID", "message": "2 values rejected", "details": [ { "path": "acme.bus_v.ttl", "reason": "must be 1..86400" } ] } }
| HTTP |
code |
When |
| 400 |
BAD_REQUEST |
not JSON, wrong top-level type |
| 401 |
UNAUTHORIZED |
missing or unknown key |
| 403 |
FORBIDDEN |
key lacks the scope, or id outside its prefixes |
| 404 |
NOT_FOUND |
DELETE of an unknown id |
| 409 |
CONFLICT |
the id belongs to a configured (non-pushed) channel |
| 413 |
TOO_LARGE |
body or entry count over limit |
| 415 |
UNSUPPORTED_MEDIA |
wrong Content-Type |
| 422 |
INVALID |
schema or rule violation; details lists each problem |
| 429 |
RATE_LIMITED |
see Retry-After |
| 500 |
INTERNAL |
server bug |
4. Values
4.1 POST /values: push one or more values (scope push)
Body: an object mapping ChannelId → value input, 1–50 entries.
curl https://crt.lucavs.nl/api/v2/values \
-H "Authorization: Bearer $CATHODE_RAY_PUSH_KEY" \
-d '{
"acme.bus_v": { "value": 23.98, "unit": "V", "ttl": 5, "label": "Bus" },
"acme.bus_a": 1.42,
"acme.state": "charging"
}'
A value input is either a bare value (number, string or boolean) or a value spec object:
| Field |
Type |
Default |
Meaning |
value |
number | string | boolean | null |
— (required) |
null means "no data right now" (state nodata) |
unit |
string ≤ 8 |
sticky |
"" clears it |
label |
string ≤ 16 |
sticky; initially the id without its prefix (bus_v) |
shown on the glasses |
ttl |
integer 1–86400 s |
sticky; none |
the value is live: if no push arrives within ttl, it goes stale (§4.6) |
decimals |
integer 0–6 |
sticky; automatic (§4.5) |
fixed number of decimals |
warn, crit |
number |
sticky; none |
thresholds → warn/crit state (display only) |
direction |
above | below |
sticky; above |
which side of the threshold is bad |
progress |
number 0..1 |
not sticky |
draws a bar where the layout allows |
Sticky means the server remembers the field on the channel. A later bare push like {"acme.bus_v": 24.01} keeps the unit, label, ttl and thresholds. Send the field as null to reset it to its default.
Rules:
- Ids follow ICD-001 v2 §7.1 (
acme.bus_v, max 4 levels). The first segment MUST be one of the key's prefixes (403).
- Ids that belong to configured channels are rejected with
409.
- Numbers MUST be finite: no NaN or Infinity (
422). Strings MUST be ≤ 32 characters (422, no silent truncation).
- At most 1000 pushed channels server-wide. Creating more gives
413, until old ones expire or are deleted.
Response 200:
{ "accepted": 3, "created": ["acme.state"], "updated": ["acme.bus_v", "acme.bus_a"] }
4.2 POST /values/{id}: one value as plain text (scope push)
For shells and microcontrollers that don't want to build JSON:
curl https://crt.lucavs.nl/api/v2/values/acme.bus_v?ttl=5 \
-H "Authorization: Bearer $CATHODE_RAY_PUSH_KEY" -H "Content-Type: text/plain" -d "23.98 V"
- Body:
<value> or <value> <unit>, separated by the first space.
<value> is parsed as a number when it's a valid decimal number (-12, 3.3, 1e-6), else as a string.
- The literals
true/false become booleans, and an empty body means null.
- Query parameters (all optional):
ttl, label, decimals, warn, crit, direction. Same meaning and stickiness as §4.1. They're not secrets, so a URL is fine here.
- Response:
204.
4.3 DELETE /values/{id} and DELETE /values?prefix=acme (scope push)
Removes one channel, or all channels under a prefix the key owns. Returns 204, or 404 for an unknown id. Views that referenced a deleted channel show it as nodata.
4.4 GET /values (scope push for own prefixes, read for all)
{ "values": [ { "id": "acme.bus_v", "label": "Bus", "text": "23.98", "unit": "V", "state": "ok",
"age_s": 1.2, "ttl": 5, "created": 1791200000.0 } ] }
Optional ?prefix=acme. This is for debugging ("what does the server think I sent?"). Nothing in it is recorded history.
4.5 How values are displayed (normative)
The server formats text for the glasses. Formatting is server-side, so every viewer shows the same thing.
| Input |
text |
| integer |
as is: 1500 |
float, decimals set |
fixed: decimals: 2 → 23.98, 24.00 |
| float, automatic |
up to 6 significant digits, trailing zeros removed, no exponent when 0.001 ≤ |x| < 1 000 000 (23.98, 0.0042, 125000). Otherwise exponent form, 1.2e-05. |
| boolean |
on / off |
| string |
as is |
null |
-- (state nodata) |
Set decimals for values that change quickly. Fixed width stops the digits jumping around on the glasses.
4.6 State, staleness and alerts
The channel's state is computed from these rules, first match wins:
nodata: value is null.
stale: ttl is set and the last push is older than ttl.
crit / warn: the threshold is crossed (numbers only).
ok
Staleness alerts. When a channel with ttl goes stale, the server raises an alert (ICD-001 v2 §8.1):
origin: server
severity: warning
id: stale:<channel>; if this exceeds 64 characters, replace <channel> with the first 58 hex characters of its SHA-256 digest
title: "<channel> stale"
- linked to the Live view
It resolves itself on the next push. That's the "should be live, isn't" rule, and it needs no threshold.
Thresholds only change the display state. They never raise alerts: alerting on data that matters belongs in Grafana (§6).
4.7 Lifetime
- In memory only. Never written to disk, InfluxDB or logs. A server restart clears everything, and producers simply push again.
- Idle expiry: a channel with no push for
idle_expiry (server config, default 12 h) is removed, together with its staleness alert.
- On the glasses: pushed channels appear in the Live view in creation order, and in the phone's channel picker for quick views.
5. Activities
For "something is in progress", shown on the Now page (ICD-001 v2 §8.2).
5.1 PUT /activities/{id} (scope activity)
curl -X PUT https://crt.lucavs.nl/api/v2/activities/acme.flash \
-H "Authorization: Bearer $CATHODE_RAY_PUSH_KEY" \
-d '{ "title": "Flashing", "text": "board 3/8", "progress": 0.375, "ttl": 120 }'
| Field |
Type |
Req. |
Meaning |
title |
string ≤ 24 |
yes |
|
text |
string ≤ 32 |
yes |
|
progress |
number 0..1 |
no |
|
state |
ok | warn | crit |
no |
default ok |
ttl |
integer 1–86400 s |
no |
if no PUT arrives within ttl, the activity shows stale, and after another ttl it's removed. Without ttl it stays until deleted or idle expiry. |
link |
{ "view": Id } |
no |
where tapping it on the Now page goes |
Ids follow the ChannelId format and the prefix rule. Each PUT replaces the whole activity. Response 204.
At most 20 activities may exist at once, including configured-source activities. Creating another gives 413.
5.2 DELETE /activities/{id} (scope activity)
Marks it done and removes it. Returns 204, or 404 for an unknown id.
6. Grafana alerts
Grafana stays the alerting brain for everything in the InfluxDB stack. Its rules, pending periods, silences and history are all better than anything Cathode Ray would build. Cathode Ray only displays the alerts.
6.1 Grafana setup
- Contact point: Alerting → Contact points → New.
- Integration: Webhook
- URL:
https://crt.lucavs.nl/api/v2/alerts/grafana
- HTTP method:
POST
- Optional settings → Authorization header: scheme
Bearer, credentials: the gk_ key
- Notification policy: route alerts with label
cr = yes to this contact point, with continue matching on if they should also go elsewhere. Suggested timing:
- group wait 10 s
- group interval 30 s
- repeat interval 1 h
- Per alert rule: add the label
cr = yes, plus the optional labels and annotations below.
6.2 POST /alerts/grafana (scope alerts)
Body: Grafana's webhook payload ("version": "1"). The server reads only the fields below and ignores the rest.
| Grafana field |
Cathode Ray Alert (ICD-001 v2 §8.1) |
alerts[].fingerprint |
id = grafana:<fingerprint> |
alerts[].status |
firing → create or update. resolved → remove. |
alerts[].labels.severity |
severity: critical, warning or info. Missing or other → warning. |
alerts[].labels.cr_interrupt |
interrupt: none, banner or takeover. Missing → server default (ICD-001 v2 §8.3). |
alerts[].labels.cr_view |
link.view |
alerts[].labels.cr_channel |
link.channel |
alerts[].annotations.summary |
title, cut to 32 characters with …. Missing → labels.alertname. |
alerts[].annotations.description |
detail, cut to 80 characters |
alerts[].startsAt |
since |
Rules:
-
Upserts are idempotent. Grafana's repeat notifications refresh existing alerts without resetting acked.
-
A resolved alert is removed. If the same fingerprint fires again later, it's a new, unacked alert.
-
Lost contact: if alerts are firing and nothing has arrived from Grafana for grafana_quiet (server config, default 3 × repeat interval), the server raises its own alert:
id: server:grafana-quiet
severity: warning
title: "Grafana alerts not refreshed"
It keeps the Grafana alerts as they are. Nothing disappears silently.
-
Payloads with truncatedAlerts > 0 are accepted with whatever alerts they contain.
Response 200:
{ "accepted": 2, "firing": 1, "resolved": 1 }
6.3 Data Grafana can't see
Grafana can only alert on what's in InfluxDB:
- OctoPrint (hotend runaway, bed heater fault): add Telegraf's
inputs.http against OctoPrint's /api/printer. You also get print history in Grafana.
- Pushed values are deliberately not in InfluxDB. Their only alert is staleness (§4.6).
7. Producer recipes (informative)
Shell function (put in ~/.bashrc on any machine):
dash() { # usage: dash acme.bus_v 23.98 V (optional: DASH_TTL=5 dash …)
curl -fsS "https://crt.lucavs.nl/api/v2/values/$1${DASH_TTL:+?ttl=$DASH_TTL}" \
-H "Authorization: Bearer $CATHODE_RAY_PUSH_KEY" -H "Content-Type: text/plain" -d "$2${3:+ $3}"
}
Python loop (read an instrument, push every second):
import os, time, requests
URL = "https://crt.lucavs.nl/api/v2/values"
s = requests.Session()
s.headers["Authorization"] = f"Bearer {os.environ['CATHODE_RAY_PUSH_KEY']}"
# once: describe the channel (sticky)
s.post(URL, json={"lab.psu_v": {"value": None, "unit": "V", "ttl": 3, "decimals": 3, "label": "PSU"}})
while True:
s.post(URL, json={"lab.psu_v": read_psu_voltage()}) # unit/ttl/decimals are sticky
time.sleep(1)
MicroPython (ESP32):
import urequests
urequests.post("https://crt.lucavs.nl/api/v2/values/bench.temp?ttl=30",
headers={"Authorization": "Bearer " + KEY, "Content-Type": "text/plain"},
data="{:.1f} °C".format(temp)).close()
8. Security
- TLS only. nginx terminates TLS, and the server trusts
X-Forwarded-For only from the proxy network.
This API is reachable from anywhere on the internet, by design: producers are scripts, devices and clients' systems on unknown networks. The key is the only gate; there is no IP allow-list unless a key sets allow_from (item 5).
- Scopes and prefixes (§2) isolate producers. A leaked push key can write wrong numbers under its own prefix, and nothing else.
- Producer endpoints send no CORS headers. They're for scripts and devices, not browser pages.
- Limits (§3) protect the in-memory store. Secrets never appear in logs. Request logs show the key name, never the secret.
- Optional per-key
allow_from CIDR list (set on the admin page), for keys that should only work from known networks.
9. Conformance
examples/ holds request and response bodies, named <SchemaDef>__<case>.json. They validate against #/$defs/<SchemaDef>. examples/invalid/ must fail.
- The server's test suite MUST:
- validate its responses against the schema
- run every example request through the real endpoints, checking status codes per §3.1
- cover stickiness, staleness alerts, prefix isolation and the Grafana mapping
10. Change log
| Rev |
Date |
Change |
| 2.0 |
2026-10-05 |
Draft: values (JSON and plain text), sticky metadata, ttl staleness alerts, activities, Grafana webhook ingestion, scoped keys with prefixes. Replaces the v1 POST /api/v1/push/{key}. |
| 2.1 |
2026-10-05 |
Keys managed live through the admin page (ICD-003) instead of keys.yaml. |
| 2.2 |
2026-10-06 |
Stated that the API is internet-reachable by design; added the failed-auth limit per client IP (§3). |