From 15c686cba560507f3a07a02dc3a84269be6b45e7 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 20:12:25 -0500 Subject: [PATCH 1/7] docs: local flag on a repeater's outside observers --- docs/api-contract.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index 8b3df4a..29e0240 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -550,7 +550,7 @@ Who polls this node right now. A `400` for a `nodeId` that is not a UUID and a ` | `latestReadingAt` | Time of the newest trusted reading, epoch ms. `null` when there is none, even if untrusted readings exist. | | `poller` | The observer ranked first: `observerId` and `name`. `null` when nobody is assigned. | | `standbys` | The other assigned observers, in rank order, each with `observerId`, `name` and `rank` (1, 2, ...). An empty array when there are none. The poller has no `rank` field. | -| `foreign` | [Foreign observers](#foreign-observers) that check the node: a live foreign claim names it, or one delivered a reading of it in the last 24 hours. Each has `observerId`, `name`, `pollHost` (the server it says it follows, or `null`), `signed` (its claim's signature checked out), `claimed` (`false` for one that only sends readings) and `latestReadingAt` (its newest reading of the node, epoch ms or `null`). By name. They are never the poller or a standby. An empty array when there are none, which is always the case with `polling.foreign_claims: off`. From 2.3.1. | +| `foreign` | [Foreign observers](#foreign-observers) that check the node: a live foreign claim names it, or one delivered a reading of it in the last 24 hours. Each has `observerId`, `name`, `pollHost` (the server it says it follows, or `null`), `signed` (its claim's signature checked out), `claimed` (`true` when it has a live claim that names this node; `false` when its claim is stale, names other repeaters only, or it has none), `local` (from 2.3.4: `true` when it has no stored claim at all and only sends readings, as the firmware's local mode does; treat a missing value as unknown) and `latestReadingAt` (its newest reading of the node, epoch ms or `null`). By name. They are never the poller or a standby. An empty array when there are none, which is always the case with `polling.foreign_claims: off`. From 2.3.1. | `name` is the observer's display name, or the first 8 hex characters of its public key when it has none. From 6a29d83163ec4f632cc66f08ab6a6b77e7e88b08 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 20:51:36 -0500 Subject: [PATCH 2/7] docs(alerts): telemetry stopped alert, alerts without a polling assignment --- docs/alerts.md | 15 +++++++++------ docs/api-contract.md | 15 ++++++++------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/docs/alerts.md b/docs/alerts.md index 04f458b..20db903 100644 --- a/docs/alerts.md +++ b/docs/alerts.md @@ -41,14 +41,15 @@ failing channel never holds back the other. A user sets rules per radio on their Atlas. A radio has one rule per kind. Which kinds a radio offers depends on what it is and what Beacon has seen it report. Kinds that need readings are -offered for a repeater only while Beacon is polling it, meaning an observer holds it as a polling -assignment right now; the user is told to request telemetry for it first (see -[Requested telemetry](telemetry-requests.md)). +offered for a repeater only while telemetry is arriving for it: an observer holds it as a polling +assignment right now, or a trusted reading of it is under 36 hours old. Otherwise the user is told +to request telemetry for it first (see [Requested telemetry](telemetry-requests.md)). | Kind | Radios | Threshold | |---|---|---| -| `gone_quiet` | all | Hours: 12, 24 or 48. Also 3 and 6 for observers and polled repeaters. | +| `gone_quiet` | all | Hours: 3, 6, 12, 24 or 48. A repeater nobody polls is only heard through its adverts, so a short window can false-alarm on one; pick to suit the radio. | | `back_online` | all | None. Needs an enabled `gone_quiet` rule on the same radio. Notifies when that rule recovers. | +| `telemetry_stopped` | repeaters and room servers with telemetry | Hours without a reading: 3, 6, 12, 24 or 48. Any trusted reading counts, status or telemetry. The clock runs from the newest reading or from when the rule was set, whichever is later, so there is no alert about the past. It clears on the next reading and keeps firing however long the readings stay away, also after `polling.reading_retention` has deleted the last one. | | `clock` | repeaters, room servers | Seconds of drift: 300, 3600 or 86400. Fires after two adverts in a row beyond it. Beacon keeps the drift of each repeater's last 16 adverts, so a breach that came and went between two passes still fires once. | | `battery_low` | with a battery reading | Millivolts, 2500 to 5000. | | `battery_falling` | with a battery reading | Millivolts per day: 100, 200 or 300. | @@ -70,8 +71,10 @@ no alert about the past. Taking a radio off the Atlas deletes its rules. A `back `gone_quiet` rule is turned off or deleted reads `inactive` and sends nothing. The overview marks each radio `polled` while it has a current source of telemetry, which is what -offers the 3 and 6 hour `gone_quiet` thresholds and the telemetry kinds. A repeater is polled while -an observer holds it as a polling assignment (a standby counts). An observer is polled only if it +offers the telemetry kinds. A repeater is polled while an observer holds it as a polling assignment +(a standby counts), or while its newest trusted reading is under 36 hours old. The second case +covers a repeater read by a poller this server does not assign (see +[Repeater polling](repeater-polling.md)). An observer is polled only if it sent status telemetry in the last 24 hours. Old readings alone do not count, so a radio that was polled can turn `polled: false`; its telemetry kinds then move to `unavailable` with code `not_polled` (repeater) or `observer_no_data` (observer), and its telemetry rules read `inactive`. diff --git a/docs/api-contract.md b/docs/api-contract.md index 29e0240..6b44e21 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -1588,7 +1588,7 @@ GET /api/v1/me/alerts "push": { "available": true, "enabled": true, "hasDevice": true } }, "targets": [ { "id": "uuid or null", "kind": "node", "publicKey": "<64 hex>", "name": "Hilltop", "polled": true, - "available": ["gone_quiet", "back_online", "clock", "battery_low"], + "available": ["gone_quiet", "back_online", "telemetry_stopped", "clock", "battery_low"], "unavailable": { "temperature": "This repeater does not report a temperature." }, "unavailableCodes": { "temperature": "no_data" }, "rules": [ @@ -1599,11 +1599,11 @@ GET /api/v1/me/alerts One target per Atlas pin, in Atlas order. `id` is the node's or observer's id as used by `/nodes/{id}` and `/observers/{id}`, or `null` when the radio no longer exists. `polled` is true while the radio has a current source of telemetry: for a repeater, an observer holds it as a polling -assignment now; for an observer, it sent status telemetry in the last 24 hours. Old readings do not +assignment now or its newest trusted reading is under 36 hours old (a poller this server does not +assign); for an observer, it sent status telemetry in the last 24 hours. Older readings do not count, so a target that was polled can read `polled: false`, its telemetry kinds then move to `unavailable` with `not_polled` (repeater) or `observer_no_data` (observer), and its telemetry rules -read `inactive`. It is what offers the telemetry kinds and, for a repeater, the 3 and 6 hour -`gone_quiet` thresholds. `available` is always an array and `unavailable` always an object of kind to +read `inactive`. It is what offers the telemetry kinds. `available` is always an array and `unavailable` always an object of kind to English reason. `unavailableCodes` is always an object with the same keys, kind to a stable code a client can translate; fall back to the sentence for a code it does not know. @@ -1627,7 +1627,7 @@ Reason codes (`unavailableCodes`, and `reasonCode` in the `kind_unavailable` err |---|---| | `observer_no_data` | An observer does not report this value. | | `repeaters_only` | Only repeaters report this value; the radio is not one. | -| `not_polled` | No observer holds this repeater as a polling assignment now; request telemetry for it first. | +| `not_polled` | No telemetry is arriving for this repeater: no observer holds it as a polling assignment and it has no trusted reading from the last 36 hours. Request telemetry for it first. | | `no_data` | A polled repeater does not report this value. | | `observer_no_clock` | Observers have no clock drift value. | | `clock_repeaters_only` | Only repeaters and room servers report a clock. | @@ -1638,8 +1638,9 @@ Kinds, thresholds and ranges (`threshold` is null where none is taken): | `kind` | Unit | Accepted | |---|---|---| -| `gone_quiet` | hours | 12, 24, 48; also 3 and 6 for observers and polled repeaters | +| `gone_quiet` | hours | 3, 6, 12, 24, 48 | | `back_online` | none | null. Needs an enabled `gone_quiet` rule on the radio. | +| `telemetry_stopped` | hours | 3, 6, 12, 24, 48 (repeaters and room servers with telemetry). Hours since the newest trusted reading, or since the rule was set if that is later. | | `clock` | seconds | 300, 3600, 86400 | | `battery_low` | millivolts | 2500 to 5000 | | `battery_falling` | millivolts per day | 100, 200, 300 | @@ -1751,7 +1752,7 @@ with associated data `"beacon-push/v1:" + pushId`. It opens to the notice, not t |---|---| | `kind` | An alert kind from the table above, or `request_attention`. Ignore a notice of a kind you do not know. | | `name` | The radio's name, already cleaned and cut to 40 characters (see [Names in alerts](alerts.md#names-in-alerts)). Cap it again before showing it. | -| `value` | The figure the sentence gives, in the kind's unit: hours for `gone_quiet`, millivolts for the battery kinds, tenths of a degree C for `temperature`, dBm for `noise_high`, seconds for `clock`, minutes for `observer_offline`. Always `null` for `back_online`, `rebooted` and `request_attention`, which give no figure. | +| `value` | The figure the sentence gives, in the kind's unit: hours for `gone_quiet` and `telemetry_stopped`, millivolts for the battery kinds, tenths of a degree C for `temperature`, dBm for `noise_high`, seconds for `clock`, minutes for `observer_offline`. Always `null` for `back_online`, `rebooted` and `request_attention`, which give no figure. | | `detail` | For `request_attention`: `login_failed`, `admin_stopped` or `disabled`. Otherwise empty. | | `targetKind`, `publicKey`, `id` | The radio, to open it on tap: by `id` when present, else by key. | | `tempUnit` | `c` or `f`, the instance's display unit for temperatures. | From 6af0cd62fb74836c6b33c4eadffa28c08b8a43ce Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 21:13:14 -0500 Subject: [PATCH 3/7] docs: sensor channels in node telemetry and the sensor Atlas tiles --- docs/api-contract.md | 41 +++++++++++++++++++++++++++++++++++++--- docs/atlas.md | 10 ++++++++-- docs/repeater-polling.md | 2 +- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index 6b44e21..84237e8 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -471,9 +471,41 @@ Any other value of `range`, `interval` or `include`, or a `nodeId` that is not a | `airtimeTxSecs`, `airtimeRxSecs` | Seconds of radio time spent sending and receiving. Increase within the bucket, covering `counterSpanSecs`. | | `packetsReceived`, `packetsSent`, `receiveErrors` | Packet counts. Increase within the bucket, covering `counterSpanSecs`. | | `counterSpanSecs` | Seconds of elapsed time that the five counter increases in this point cover. Left out when zero. See below. | +| `sensors` | The repeater's sensor channels, averaged over the bucket. Left out when no reading in the bucket carried one. See [Sensor channels](#sensor-channels). | Every field after `readings` is left out when no reading in the bucket carried it. Repeaters do not all report every field. +#### Sensor channels + +A repeater with extra sensors sends them in its telemetry reply, one channel per sensor. `sensors` +lists the channels a bucket saw, lowest first: + +```json +"sensors": [ + { "channel": 2, "temperatureC": 21.4, "humidityPct": 45.5, "pressureHpa": 1013.2, "iaq": 50, "iaqAccuracy": 3 }, + { "channel": 3, "voltageV": 8.7, "currentA": 0.122, "powerW": 1.061 } +] +``` + +| Field | Meaning | +|---|---| +| `channel` | 1 is the repeater's own board. Added sensors take 2 and up, in the order the firmware found them. The firmware sends no sensor names, so a client labels a channel by its number and by what it carries. | +| `temperatureC` | Degrees C, one decimal. The board's own temperature stays in the point's `temperatureC` and is not repeated on channel 1. | +| `humidityPct` | Relative humidity, 0 to 100, one decimal. | +| `pressureHpa` | Barometric pressure in hPa, one decimal. | +| `gasOhms` | A gas sensor's raw resistance in ohms. | +| `iaq`, `iaqAccuracy` | An air quality index, 0 to 500, sent instead of `gasOhms` by firmware that computes one, and its accuracy 0 to 3 (3 is calibrated). In a bucket the accuracy is the lowest seen. A channel has `gasOhms` or `iaq`, never both. | +| `voltageV`, `currentA` | A power monitor's bus voltage (two decimals) and current (three decimals). A reverse current is negative. | +| `powerW` | Watts, three decimals. Voltage times current of each reading when the channel carried both, since the firmware's own figure is whole watts. | +| `distanceM`, `percent`, `luminosityLux` | A range finder's distance in metres, a moisture sensor's percentage and a light sensor's lux. | + +Every field but `channel` is left out when the channel did not carry it. Averages are per channel +and per field, over the readings that carried the field. Sensor channels are decoded when a reading +is stored, so readings stored before a server had this carry none; nothing is filled in afterwards. + +A reply can also hold the repeater's position and an altitude. Beacon never decodes either, and no +route returns the raw reply, so neither can be read from the API. + The five counters (`airtimeTxSecs`, `airtimeRxSecs`, `packetsReceived`, `packetsSent`, `receiveErrors`) are running totals on the repeater. Beacon turns them into increases one pair at a time. A status reading is a reading whose stored `method` is `status`, whether or not it carries any counter: a status reply too short to carry counters is still a status reading. A pair is two consecutive status readings. A status reading without counters therefore takes part in a pair and breaks it (the pair adds nothing), and the next pair starts from that reading, not from the last one that had counters. Telemetry readings (`method` `telemetry`) are never part of a pair. The increases of a pair are credited to the bucket of the later reading. A pair gives the same answer whatever `range` was asked for, so the first pair of a range uses the newest status reading (by `method`) before the range as its earlier half. A pair either contributes all of its counters or none of them. It contributes when all of these hold: @@ -1049,7 +1081,7 @@ Public, no key. Counts against the normal rate limit and is sent with `Cache-Con ```json { "minAppVersion": "2.3.0", "minWebVersion": "2.3.0", "serverVersion": "2.3.0", - "features": { "polling": true, "accounts": "off", "registration": false, "telemetryRequests": false, "alerts": false, "alertChannels": { "email": false, "push": false }, "atlasTelemetry": true, "atlasPoller": true, "atlas7d": true, "mapTelemetry": true, "appDeviceLabel": true }, + "features": { "polling": true, "accounts": "off", "registration": false, "telemetryRequests": false, "alerts": false, "alertChannels": { "email": false, "push": false }, "atlasTelemetry": true, "sensors": true, "atlasPoller": true, "atlas7d": true, "mapTelemetry": true, "appDeviceLabel": true }, "display": { "temperatureUnit": "c", "distanceUnit": "metric" }, "limits": { "atlas": 20 } } @@ -1077,6 +1109,7 @@ Swagger shows. Servers older than this endpoint return `404`. See | `alertChannels` | `{"email": bool, "push": bool}`: the channels this server sends alerts by. Always present. | | `push` | `{"server": "https://push.meshcorebeacon.ca", "pushId": "inst_…"}`: the push server the app gets a device handle from, and this server's Push ID there. Present only while `alertChannels.push` is true. See [Push delivery](#push-delivery). | | `atlasTelemetry` | True when the server accepts the `telemetry` Atlas view and `telemetryTiles` on node pins, and the `72h` [node telemetry](#node-telemetry) range. Always true on servers that have it. | +| `sensors` | True when [node telemetry](#node-telemetry) points carry `sensors` and `telemetryTiles` takes the sensor tiles `humidity`, `pressure`, `gas`, `power`, `current` and `sensorVoltage`. Always true on servers that have it. A client sends those tile ids only when it is true; an older server answers them with `422`. | | `atlasPoller` | True when the server accepts the `poller` Atlas view on node pins. Always true on servers that have it. | | `atlas7d` | True when the server accepts the `7d` range on [`/me/atlas`](#atlas-sync). Always true on servers that have it. | | `mapTelemetry` | True when the server has [latest node telemetry](#latest-node-telemetry). Always true on servers that have it. It stays true when polling is off. A client shows its map telemetry toggle only when both `mapTelemetry` and `polling` are true. | @@ -1434,7 +1467,8 @@ client reads `168h` in hourly buckets: `/nodes/{id}/activity?range=168h`, and `observerPublicKey`. `observerId` is the observer record with that key, or `null`. `tiles` (exactly four distinct metric ids, see [Atlas](atlas.md#choosing-the-observer-tiles)) and `view` (`heard`, `observer`, `telemetry` or `poller`, node pins only) are left out when not set. `telemetryTiles` (node pins only) is exactly four distinct ids from `battery`, `noise`, `uptime`, -`airtime`, `temperature`, `packets`, `signal` and `errors`; it holds the Telemetry view's tiles, +`airtime`, `temperature`, `packets`, `signal`, `errors` and, where `features.sensors` is true, the +sensor tiles `humidity`, `pressure`, `gas`, `power`, `current` and `sensorVoltage`; it holds the Telemetry view's tiles, apart from `tiles`, which stay the Observer view's. It is left out when the default applies. A client ignores a `view` or field it does not know. An observer pin whose key now has a node record comes back as a node pin. @@ -2030,7 +2064,8 @@ malformed reading (no `node_id`, an unknown `method`, a missing or unreadable `s 160 bytes, and `battery_mv` and `temperature_c` when decoded). Any other value drops the message. Each `stats` key is present only if the repeater's reply was long enough to hold it. - A `battery_mv` of 0 means no voltage and is stored as none. -- Beacon decodes the parts of `lpp` that parse and keeps the bytes. +- Beacon decodes the parts of `lpp` that parse and keeps the bytes: the board's voltage and + temperature, and the [sensor channels](#sensor-channels). A position or altitude in it is skipped. - A reading is stored once per repeater, observer, `tag` and `method`. With no `tag`, `sampled_at` stands in for it. The same reading arriving twice is stored once. - Beacon keeps at most one new reading per observer, repeater and `method` every 5 minutes of diff --git a/docs/atlas.md b/docs/atlas.md index 411e85c..568d27d 100644 --- a/docs/atlas.md +++ b/docs/atlas.md @@ -143,7 +143,11 @@ On a server with [repeater polling](repeater-polling.md) on (`features.polling`) repeater or room server gets a **Telemetry** tab when an observer is assigned to poll it, or when it has readings from the last 30 days. The tab keeps its own four tiles, chosen from battery, noise floor, uptime, airtime, temperature, packets, signal and errors, separate from the Observer -view's tiles. A new card shows battery, noise floor, uptime and airtime. Both the tab and the +view's tiles. A repeater with extra sensors also offers humidity, pressure, gas, power, current and +sensor voltage, each only while it has readings of it in the window. A sensor tile shows the lowest +sensor channel that carries its value and names that channel; the node's Telemetry panel charts +every channel. The gas tile reads Air quality when the sensor sends an index instead of a +resistance. A new card shows battery, noise floor, uptime and airtime. Both the tab and the tiles are saved with the card as `view: "telemetry"` and `telemetryTiles`. A card pinned to Telemetry that loses the tab opens on Analytics. @@ -204,7 +208,9 @@ picker ignores the field. `telemetryTiles` is optional on a node card and works the same way for the Telemetry tab: four different IDs, in tile order, from `battery`, `noise`, `uptime`, `airtime`, `temperature`, -`packets`, `signal` and `errors`, left out for the default layout. +`packets`, `signal`, `errors`, `humidity`, `pressure`, `gas`, `power`, `current` and +`sensorVoltage`, left out for the default layout. The last six need a server with +`features.sensors`; a client does not send them to one without it. `view` is optional on a node card: `heard`, `observer`, `telemetry` or `poller`, the tab the card opens on, left out when that is Analytics. Any other value is dropped on import and the card is kept, diff --git a/docs/repeater-polling.md b/docs/repeater-polling.md index 82b5118..5671a43 100644 --- a/docs/repeater-polling.md +++ b/docs/repeater-polling.md @@ -190,7 +190,7 @@ requests. To change how much polling happens, use these instead (see |---|---| | Each observer's latest claim and its target list | Used while the claim is under 65 minutes old. Removed 24 hours after it was received. | | Who polls and who stands by for each repeater | Rebuilt every minute. | -| Readings: battery, temperature, the repeater's counters, raw sensor bytes and which observer sent them | `polling.reading_retention`, 31 days by default. | +| Readings: battery, temperature, the repeater's counters, its decoded sensor channels (humidity, pressure, gas, power monitors), raw sensor bytes and which observer sent them | `polling.reading_retention`, 31 days by default. | | Operator flags per observer | Until you change them. | A reading is stored once per repeater, observer and sample. The same reading arriving twice, for From d74eb831bd1a01987ea23cf9ff4f8f4989cc885e Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 21:54:49 -0500 Subject: [PATCH 4/7] docs(atlas): calibration chip on the air quality tile --- docs/atlas.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/atlas.md b/docs/atlas.md index 568d27d..a7560e1 100644 --- a/docs/atlas.md +++ b/docs/atlas.md @@ -145,9 +145,10 @@ it has readings from the last 30 days. The tab keeps its own four tiles, chosen noise floor, uptime, airtime, temperature, packets, signal and errors, separate from the Observer view's tiles. A repeater with extra sensors also offers humidity, pressure, gas, power, current and sensor voltage, each only while it has readings of it in the window. A sensor tile shows the lowest -sensor channel that carries its value and names that channel; the node's Telemetry panel charts -every channel. The gas tile reads Air quality when the sensor sends an index instead of a -resistance. A new card shows battery, noise floor, uptime and airtime. Both the tab and the +sensor channel that carries its value; the node's Telemetry panel charts every channel. The gas tile reads Air quality when the sensor sends an index instead of a +resistance, and carries a chip in its corner with how far the sensor's own calibration has got, from 0/3 to +3/3: below 3 the index is the sensor's estimate. The Telemetry panel's air quality chart carries +the same status in words. A new card shows battery, noise floor, uptime and airtime. Both the tab and the tiles are saved with the card as `view: "telemetry"` and `telemetryTiles`. A card pinned to Telemetry that loses the tab opens on Analytics. From fce792cfbe9d66c708af525556e789279dedc83e Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 23:00:25 -0500 Subject: [PATCH 5/7] docs(api): client version floors are 2.3.4 --- docs/api-contract.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index 84237e8..6c6696d 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -1080,7 +1080,7 @@ Public, no key. Counts against the normal rate limit and is sent with `Cache-Con ```json { - "minAppVersion": "2.3.0", "minWebVersion": "2.3.0", "serverVersion": "2.3.0", + "minAppVersion": "2.3.4", "minWebVersion": "2.3.4", "serverVersion": "2.3.4", "features": { "polling": true, "accounts": "off", "registration": false, "telemetryRequests": false, "alerts": false, "alertChannels": { "email": false, "push": false }, "atlasTelemetry": true, "sensors": true, "atlasPoller": true, "atlas7d": true, "mapTelemetry": true, "appDeviceLabel": true }, "display": { "temperatureUnit": "c", "distanceUnit": "metric" }, "limits": { "atlas": 20 } @@ -1089,7 +1089,7 @@ Public, no key. Counts against the normal rate limit and is sent with `Cache-Con `minAppVersion` and `minWebVersion` are the oldest BEACON Mobile and Beacon Web releases allowed to use this server, as strict `X.Y.Z` strings. Each is the higher of the server's built-in floor -(`2.3.0` for both since server 2.3.0) and the operator's `mobile.min_app_version` / +(`2.3.4` for both since server 2.3.4) and the operator's `mobile.min_app_version` / `web.min_web_version`. Older servers can send `null` for no requirement, so keep handling it. With `websocket.require_origin` on, `minAppVersion` is at least `2.1.1`, the first release that sends a [WebSocket ticket](#websocket-ticket); the built-in floor is already above that. `serverVersion` is the server's API version (`X.Y.Z`, no `v`), the same value From 4bb41f443c03a4fb5f30878b257c1e5f5836c3a6 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 23:23:05 -0500 Subject: [PATCH 6/7] docs: upgrade note for 2.3.4 --- docs/upgrading.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/upgrading.md b/docs/upgrading.md index 5d3f698..13d5b74 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -154,6 +154,25 @@ shows how to check it. If you enforce the [fail2ban jails](../app_config/fail2ba add `protocol="tcp,udp"` to the ban action as shown there: the default bans TCP only, so a banned address could still reach the site over HTTP/3. +## Upgrading to 2.3.4 from 2.3.3 + +Server 2.3.4 pairs with Beacon Web 2.3.4 and BEACON Mobile 2.3.4, and raises both minimum client +versions to 2.3.4. Upgrade the web with the server. An older web page is told to reload; an older +app asks its user to update before it connects, so check that the 2.3.4 app is in the stores your +users install from before you upgrade a public server. + +There are no config changes. Migrations 096 and 097 run on start and take seconds: one widens the +list of alert kinds, the other adds a nullable `sensors` column to `repeater_readings`. + +What it adds: + +- Sensor channels. A polled repeater's extra sensors (humidity, pressure, gas or air quality, power + monitors) are decoded when a reading is stored and shown as charts and Atlas tiles. Readings stored + before the upgrade carry none; nothing is filled in afterwards. See + [Sensor channels](api-contract.md#sensor-channels). +- Alerts on repeaters this server does not assign a poller to, and a `telemetry_stopped` alert. See + [Alerts](alerts.md). + ## Upgrading to 2.3.3 from 2.3.2 Server 2.3.3 pairs with Beacon Web 2.3.2. There are no config changes. Migration 095 runs on start From 0b6145054bdfebab136ebf6a6e657255d4826269 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 23:37:11 -0500 Subject: [PATCH 7/7] docs: check every page against 2.3.4 and tidy the wording --- .github/PULL_REQUEST_TEMPLATE.md | 6 +- CONTRIBUTING.md | 69 ++++- README.md | 41 ++- SECURITY.md | 14 +- app_config/config.yaml.example | 4 +- app_config/fail2ban/README.md | 6 +- deploy/push/README.md | 2 +- docker-deployment-type2/README.md | 17 +- docker-deployment-type2/web/.env.example | 4 +- docs/accounts.md | 4 +- docs/alerts.md | 40 ++- docs/api-contract.md | 146 +++++---- docs/atlas.md | 73 +++-- docs/backup-export.md | 14 +- docs/configuration.md | 47 +-- docs/getting-packets-in.md | 6 +- docs/high-level-design.md | 369 +++++++++++++++-------- docs/operations.md | 188 +++++++----- docs/profiling.md | 16 +- docs/releases.md | 10 +- docs/repeater-polling.md | 79 +++-- docs/reverse-proxy.md | 11 +- docs/troubleshooting.md | 6 +- docs/upgrading.md | 21 +- 24 files changed, 774 insertions(+), 419 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index b0c3428..025fb67 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -12,11 +12,13 @@ A clear description of the change and why it was made. ## Checklist -- [ ] Docs match the actual files in `docker-deployment-*/` and `app_config/` -- [ ] Variable tables in the README are in sync with the example config files +- [ ] This PR targets `dev`, not `main` +- [ ] Docs match the actual files in `docker-deployment-*/` and `app_config/`, and the code where the behaviour lives there +- [ ] Variable tables in the README and `docs/configuration.md` are in sync with the example config files - [ ] Internal and external links resolve - [ ] Any changed `docker-compose.yml` passes `docker compose config` - [ ] No real secrets, passwords, channel keys, or MQTT credentials committed +- [ ] No em dashes - [ ] I have read [CONTRIBUTING.md](../CONTRIBUTING.md) ## Notes for reviewers diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e857619..bff50eb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,7 @@ # Contributing to Beacon -Thank you for your interest in contributing. This page is the shared workflow for all three -Beacon repositories: +Thank you for your interest in contributing. This page is the shared workflow for every Beacon +repository: - [beacon-docs](https://github.com/MeshCore-Beacon/beacon-docs), this repo: deployment, configuration and operator documentation. @@ -11,14 +11,22 @@ Beacon repositories: - [beacon-web](https://github.com/MeshCore-Beacon/beacon-web): the frontend. Its own [CONTRIBUTING.md](https://github.com/MeshCore-Beacon/beacon-web/blob/main/CONTRIBUTING.md) covers TypeScript style, tests and the feature layout. +- [beacon-flutter-app](https://github.com/MeshCore-Beacon/beacon-flutter-app): BEACON Mobile, the + iOS and Android app. Its own + [CONTRIBUTING.md](https://github.com/MeshCore-Beacon/beacon-flutter-app/blob/main/CONTRIBUTING.md) + covers Dart style, tests and app releases. +- [beacon-push](https://github.com/MeshCore-Beacon/beacon-push): the push server that forwards + alerts to the app. Its own + [CONTRIBUTING.md](https://github.com/MeshCore-Beacon/beacon-push/blob/main/CONTRIBUTING.md) + covers what the relay may and may not do. Please read this before opening a PR anywhere. ## Before you start -**Talk first for anything bigger than a small fix.** On beacon-server and beacon-web, open or -comment on an issue before starting work, so maintainers can say if something is already in -progress or out of scope. Issues are disabled on beacon-docs; for a docs restructure, a new +**Talk first for anything bigger than a small fix.** On the code repos, open or comment on an +issue before starting work, so maintainers can say if something is already in progress or out of +scope. Issues are disabled on beacon-docs; for a docs restructure, a new deployment type or a correction you are unsure about, reach out on the [MeshCore Canada Discord](https://discord.gg/Gz3KvJx2hf). For typos, broken links and small clarifications, just open a PR. @@ -33,24 +41,46 @@ appear to be unreviewed AI output may be closed without further comment. ## Branches -Every Beacon repo, docs included: +Every Beacon repo, docs included, has the same two branches: -- `main` holds stable releases only and is protected. Never target it directly. -- `dev` is active development. All PRs target `dev`. +- `dev` is where all work lands. Contributors open pull requests against `dev`; maintainers + commit to it directly. +- `main` holds releases only and is protected. It changes one way: a release pull request from + `dev` into `main`, merged as a merge commit by a maintainer. A check in every repo + (`main-source-guard.yml`) fails any pull request into `main` that does not come from that + repo's own `dev` branch, so never target `main` with a change. In beacon-docs, `main` describes the current release and `dev` describes what is coming next. +The release steps are in [Releases and versioning](docs/releases.md). ## Workflow -1. Fork, or create a branch from `dev`. +1. Fork the repo and create a branch from `dev`. 2. Make your change. -3. Run that repo's checklist (below for docs; in each code repo's CONTRIBUTING for code). -4. Open a pull request with a clear description of what changed and why, referencing any - related issue. +3. Run that repo's checks (the table below). +4. Open a pull request against `dev` with a clear description of what changed and why, + referencing any related issue. + +## Checks before you open a pull request + +CI runs these on every pull request. Run them first; each repo's own CONTRIBUTING explains them. + +| Repo | Run | +|---|---| +| beacon-server | `go build ./...`, `gofmt -l .` (must print nothing), `go vet ./...`, `go test ./...`, `govulncheck ./...`. After changing SQL under `db/`, `sqlc generate`. After changing a handler or an API type, `swag init -g cmd/beacon/main.go -o docs --parseInternal --parseDependency`; CI fails when the committed Swagger is out of date. | +| beacon-web | `npm run build` (the only real typecheck), `npm run lint`, `npm test` | +| beacon-flutter-app | `dart format --set-exit-if-changed .`, `flutter analyze`, `flutter test` | +| beacon-push | `go build ./...`, `gofmt -l .` (must print nothing), `go vet ./...`, `go test -race ./...` | +| beacon-docs | The [docs checklist](#checklist-before-opening-a-docs-pr) below | + +beacon-server's CI also runs a selected set of integration tests and query plan checks against +PostgreSQL 16, which a plain `go test ./...` skips. If your change touches SQL, read the server's +CONTRIBUTING for how to run them locally, and watch CI on your pull request. ## Running the full stack locally -Most changes to either code repo are easier to check against the other one running next to it. +Most changes to a client or to the server are easier to check against the other running next to +it. **beacon-server**, with a throwaway PostgreSQL in Docker: @@ -90,6 +120,19 @@ you would rather have the browser talk to `localhost:8080` directly, add `websocket: {allowed_origins: [http://localhost:5173]}` to the server's `config.yaml` instead. Open `http://localhost:5173`. +**beacon-flutter-app**, against the same server: + +```bash +git clone https://github.com/MeshCore-Beacon/beacon-flutter-app.git && cd beacon-flutter-app +flutter pub get +flutter run +``` + +The app has no built-in server. On first launch tap **Add server** and enter the address of +your local beacon-server as the device sees it: your computer's LAN address (for example +`http://192.168.1.20:8080`) on a phone, or `http://10.0.2.2:8080` on the Android emulator, where +`localhost` is the emulator itself. + ## Checklist before opening a docs PR - **Docs match reality.** If you change a variable, path, command or image name, check it diff --git a/README.md b/README.md index d07bad3..52edbdd 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,25 @@ Beacon watches a MeshCore mesh from above. It listens to the MQTT brokers that observers publish into, decodes every LoRa packet it hears, stores it, and shows the network live: packets, -channels, nodes, observers, routes, traces and stats, on a map and in lists. +channels, nodes, observers, routes, traces and stats, on a map and in lists. The same server +feeds the web app and BEACON Mobile, the iOS and Android app. + +A plain install does all of that with no sign-in. The rest is optional and off until you turn +it on: + +- [Repeater polling](docs/repeater-polling.md): observers ask nearby repeaters for battery, + temperature, counters and sensor readings, and Beacon stores and charts them. +- [User accounts](docs/accounts.md): sign-in for the web app and the mobile app, with an + [Atlas](docs/atlas.md) watchlist that follows the account. +- [Requested telemetry](docs/telemetry-requests.md): signed-in users ask for a repeater to be + polled. +- [Alerts](docs/alerts.md): email and push notices when a radio on a user's Atlas goes quiet, + runs low on battery, reboots and more. This repo is where you deploy and operate it. The code lives in -[beacon-server](https://github.com/MeshCore-Beacon/beacon-server) (the API and ingest) and -[beacon-web](https://github.com/MeshCore-Beacon/beacon-web) (the frontend). +[beacon-server](https://github.com/MeshCore-Beacon/beacon-server) (the API and ingest), +[beacon-web](https://github.com/MeshCore-Beacon/beacon-web) (the web frontend) and +[beacon-flutter-app](https://github.com/MeshCore-Beacon/beacon-flutter-app) (BEACON Mobile). > **Coming from 1.x?** 2.0.0 needs a fresh database and a few config changes. Read > [Upgrading](docs/upgrading.md) before you pull new images. @@ -136,7 +150,7 @@ The `app` and `web` services pull public images from GitHub Container Registry `docker login` is needed. The compose files use `latest`, which follows stable releases. To decide for yourself when to -upgrade, pin both images to the same release line (`:2.0`) or an exact release (`:2.0.0`); server +upgrade, pin both images to the same release line (`:2.3`) or an exact release (`:2.3.4`); server and web share `major.minor`. Tags, versioning and the release process are in [Releases and versioning](docs/releases.md). A `403 Forbidden` on pull means the package has gone private; see [Troubleshooting](docs/troubleshooting.md#docker-compose-up-fails-with-403-forbidden-pulling-an-image). @@ -154,7 +168,7 @@ gone private; see [Troubleshooting](docs/troubleshooting.md#docker-compose-up-fa - [Reverse proxy](docs/reverse-proxy.md): Caddy, nginx, Apache, rate limits, split origins, and an RSA certificate for observers. - [Securing a deployment](docs/security.md): the admin key, the listener, origins, bans. - [Day-to-day operations](docs/operations.md): health, logs, retention, backup and restore. -- [Upgrading](docs/upgrading.md): 2.0.0 from 1.x, 2.1, 2.3.0 from 2.2.0, 2.3.1 from 2.3.0, and routine upgrades. +- [Upgrading](docs/upgrading.md): 2.0.0 from 1.x, 2.1, each release from 2.3.0 to 2.3.4, and routine upgrades. - [Troubleshooting](docs/troubleshooting.md): symptom, cause, fix. - [Releases and versioning](docs/releases.md): image tags and how releases are cut. @@ -162,12 +176,18 @@ gone private; see [Troubleshooting](docs/troubleshooting.md#docker-compose-up-fa - [High level design](docs/high-level-design.md): how it works, the schema, the ingest pipeline. - [API contract](docs/api-contract.md): REST, WebSocket, admin endpoints, errors. +- [Observer directory](docs/observer-directory.md): the observer list endpoint with traffic counts for a time window. - [Atlas](docs/atlas.md): the watchlist of nodes and observers (per browser, or synced to an account), what its cards mean, and its export file. - [Backup and export](docs/backup-export.md) and [CPU profiling](docs/profiling.md). +**BEACON Mobile** + +- [Support](docs/mobile/support.md) and [privacy policy](docs/mobile/privacy.md): the pages the + app stores link to. + **Change it** -- [Contributing](CONTRIBUTING.md): the workflow for all three repos and running the full stack +- [Contributing](CONTRIBUTING.md): the workflow for every Beacon repo and running the full stack locally. - beacon-server: [historical stats](https://github.com/MeshCore-Beacon/beacon-server/blob/main/docs/historical-stats.md), how the hourly rollups work. @@ -175,17 +195,20 @@ gone private; see [Troubleshooting](docs/troubleshooting.md#docker-compose-up-fa adding a language. Deployment folders are `docker-deployment-type1/` and `docker-deployment-type2/`; templates -and proxy configs (`.env`, `config.yaml`, Caddy, nginx, Apache, fail2ban) are in `app_config/`; -brand assets are in `logos/`. +and proxy configs (`.env`, `config.yaml`, Caddy, nginx, Apache, [fail2ban](app_config/fail2ban/README.md)) +are in `app_config/`; brand assets are in `logos/`. `deploy/push/` holds the files for the project's +own [push server](deploy/push/README.md); a Beacon server does not need them. ## Source repositories - **beacon-server** (API and ingest): [github.com/MeshCore-Beacon/beacon-server](https://github.com/MeshCore-Beacon/beacon-server), image `ghcr.io/meshcore-beacon/beacon-server` - **beacon-web** (frontend): [github.com/MeshCore-Beacon/beacon-web](https://github.com/MeshCore-Beacon/beacon-web), image `ghcr.io/meshcore-beacon/beacon-web` +- **beacon-flutter-app** (BEACON Mobile, iOS and Android): [github.com/MeshCore-Beacon/beacon-flutter-app](https://github.com/MeshCore-Beacon/beacon-flutter-app) +- **beacon-push** (the push server that forwards alerts to the app): [github.com/MeshCore-Beacon/beacon-push](https://github.com/MeshCore-Beacon/beacon-push) ## Maintainers: publishing images -Container images are published automatically by each repo's `docker-publish.yml` workflow on +The server and web images are published automatically by each repo's `docker-publish.yml` workflow on pushes to `main` and `dev` and on `v*` tags. GHCR packages are private by default, which makes anonymous `docker pull` fail with `403 Forbidden`. To make a package publicly pullable, once per package: diff --git a/SECURITY.md b/SECURITY.md index 490af4f..da11b8d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,8 +2,7 @@ This is the **documentation and deployment** repository for Beacon. If you have found a vulnerability in the Beacon application itself (server, web, mobile app or -push server), please -report it against the relevant code repository: +push server), please report it against the relevant code repository: - [beacon-server](https://github.com/MeshCore-Beacon/beacon-server) - [beacon-web](https://github.com/MeshCore-Beacon/beacon-web) @@ -12,8 +11,8 @@ report it against the relevant code repository: ## Reporting a Vulnerability -Please do not report security issues through public GitHub. Issues are disabled -on this repository. +Please do not report security issues through public GitHub issues or pull +requests, in any Beacon repository. Issues are disabled on this one. Instead, contact the maintainers directly via the MeshCore Canada Discord server: [MeshCore Canada Discord](https://discord.gg/Gz3KvJx2hf); reach out to @@ -32,7 +31,10 @@ The Docker deployments in this repo expose `db`, `redis`, and `app` only on `127.0.0.1`, with Caddy terminating TLS on ports 80/443. Beacon's REST reads and WebSocket feed are public by design; only `/api/v1/admin/*` needs a bearer key (`BEACON_API_KEY`), and abuse is limited by per-IP rate limits. With user -accounts on, the `/api/v1/auth` and `/api/v1/me` routes need a signed-in user. It is -intended to sit behind that reverse proxy, listed in `server.trusted_proxies`. +accounts on, the sign-up, sign-in and password reset routes under +`/api/v1/auth` take no credentials and have their own per-IP limits, and the +`/api/v1/me` routes need a signed-in user. The server is meant to sit +behind that reverse proxy, with the proxy listed in `server.trusted_proxies`. Keep this in mind when assessing the severity of any findings, and never expose the database, Redis, or the raw app port to the public internet. +[Securing a deployment](docs/security.md) has the full checklist. diff --git a/app_config/config.yaml.example b/app_config/config.yaml.example index 1d09e3b..a052ba4 100644 --- a/app_config/config.yaml.example +++ b/app_config/config.yaml.example @@ -381,9 +381,9 @@ websocket: # prevents startup. Omitted or empty (default) means the built-in floor only. # Takes effect on restart. #mobile: -# min_app_version: "2.3.0" # BEACON Mobile; built-in floor: 2.3.0 +# min_app_version: "2.3.4" # BEACON Mobile; built-in floor: 2.3.4 #web: -# min_web_version: "2.3.0" # Beacon Web; built-in floor: 2.3.0 +# min_web_version: "2.3.4" # Beacon Web; built-in floor: 2.3.4 # CORS configuration. # Controls which origins, methods and headers are allowed for cross-origin requests. diff --git a/app_config/fail2ban/README.md b/app_config/fail2ban/README.md index 68540d2..85073c7 100644 --- a/app_config/fail2ban/README.md +++ b/app_config/fail2ban/README.md @@ -7,7 +7,7 @@ Two deployment shapes, two file sets: | Shape | Edge | Files | |---|---|---| -| Caddy in Docker (type 1, e.g. dev.meshcore.ca) | `docker-deployment-type1/data/Caddy/…` | `fail2ban/caddy/` | +| Caddy in Docker (type 1, e.g. dev.meshcore.ca; the type 2 server host has the same Caddy files under `docker-deployment-type2/server/`) | `docker-deployment-type1/data/Caddy/…` | `fail2ban/caddy/` | | Host Apache in front of the containers (analyzer.meshmapper.net) | `app_config/apache/analyzer-vhost.snippet.conf` | `fail2ban/apache/` | ## 1. Edge: log + client-IP hygiene + manual block list @@ -55,7 +55,9 @@ Three jails per box, same thresholds: | `beacon-api-sustained` | every `/api/` request | 1,000 in 1 h | a paced scraper (the day-0 Pi ran ~135/min for hours) never trips the flood rule; real sessions peak ~300/h | All three use `backend = polling` (the Debian default `systemd` cannot tail files) and a flat 10 min ban. -Install: +The jail files expect the log at `/opt/docker/beacon/data/Caddy/logs/access.json` (Caddy) or +`/var/log/apache2/analyzer-ssl-access.log` (Apache); change `logpath` in `jail.d/beacon-http.conf` +if yours is elsewhere. Install from `fail2ban/caddy/` or `fail2ban/apache/`, whichever matches the box: ```bash sudo cp filter.d/*.conf /etc/fail2ban/filter.d/ diff --git a/deploy/push/README.md b/deploy/push/README.md index 4f2e08f..2d9673c 100644 --- a/deploy/push/README.md +++ b/deploy/push/README.md @@ -42,7 +42,7 @@ starting point. ``` 3. Create `.env` from the relay's - [`.env.example`](https://github.com/MeshCore-Beacon/beacon-push/blob/dev/.env.example) and + [`.env.example`](https://github.com/MeshCore-Beacon/beacon-push/blob/main/.env.example) and `chmod 600 .env`. The compose file already sets the listen address, database path and key paths. Set at least `PUSH_PUBLIC_URL`, `PUSH_TRUST_PROXY=true`, the `PUSH_APNS_*` IDs and topic (`meshcorebeacon.app`), the `PUSH_SMTP_*` settings and `PUSH_ADMIN_EMAIL`. diff --git a/docker-deployment-type2/README.md b/docker-deployment-type2/README.md index baad96f..13cfc9e 100644 --- a/docker-deployment-type2/README.md +++ b/docker-deployment-type2/README.md @@ -37,15 +37,17 @@ docker-deployment-type2/ nano .env ``` - Set `DOMAIN` to the API hostname (`api.example.com`) and add one line this stack needs that - the all-in-one one does not: + Set `DOMAIN` to the API hostname (`api.example.com`) and uncomment or add the one line this + stack needs that the all-in-one stack does not: ``` WEB_DOMAIN=beacon.example.com ``` - Caddy redirects anything that is not `/api/*`, `/ws` or `/.well-known/beacon-push` to that host. The password inside - `POSTGRES_DSN` must match `POSTGRES_PASSWORD` in `docker-compose.yml`. + Caddy redirects anything that is not `/api/*`, `/ws` or `/.well-known/beacon-push` to that + host, and the server uses it for the links in account and alert mail. The stack does not start + without it. The password inside `POSTGRES_DSN` must match `POSTGRES_PASSWORD` in + `docker-compose.yml`. For MeshMapper imports, set `MESHMAPPER_API_KEY` in this server host's `.env`. Your local MeshMapper regional or grouped-region admin can generate the regional or @@ -87,7 +89,7 @@ docker-deployment-type2/ | Variable | Value | |---|---| | `DOMAIN` | the web hostname, `beacon.example.com` | - | `BEACON_WEB_IMAGE` | `ghcr.io/meshcore-beacon/beacon-web:latest` to follow releases like the server half does. To pin instead, pin both halves to the same release line, for example `:2.0` here and `beacon-server:2.0` in `server/docker-compose.yml`. | + | `BEACON_WEB_IMAGE` | `ghcr.io/meshcore-beacon/beacon-web:latest` to follow releases like the server half does. To pin instead, pin both halves to the same release line, for example `:2.3` here and `beacon-server:2.3` in `server/docker-compose.yml`. | | `VITE_API_BASE` | `https://api.example.com/api/v1` | | `VITE_WS_URL` | `wss://api.example.com/ws` | @@ -107,7 +109,10 @@ docker-deployment-type2/ ## How the two connect The browser talks to the API host directly; the web host only serves files. That is why the -API host has to allow the web origin for WebSocket. REST CORS allows any origin by default. +API host has to allow the web origin for WebSocket. REST CORS allows any origin by default, +which covers the public pages. If you turn on [user accounts](../docs/accounts.md), signed-in +requests cross origins too and need the `cors` settings in +[Same site, and a web app on another origin](../docs/accounts.md#same-site-and-a-web-app-on-another-origin). Rate limits and connection caps work the same as in the all-in-one stack because each host's Caddy sets `X-Real-IP` and is trusted through `server.trusted_proxies`; see [Reverse proxy](../docs/reverse-proxy.md). diff --git a/docker-deployment-type2/web/.env.example b/docker-deployment-type2/web/.env.example index 4cbea05..67a5873 100644 --- a/docker-deployment-type2/web/.env.example +++ b/docker-deployment-type2/web/.env.example @@ -1,8 +1,8 @@ # Domain for Caddy TLS -DOMAIN=web.example.com +DOMAIN=beacon.example.com # Image to run. :latest follows releases, like the server half's compose file. To pin, use the -# same release line on both halves (e.g. :2.0 here and beacon-server:2.0 on the server host). +# same release line on both halves (e.g. :2.3 here and beacon-server:2.3 on the server host). BEACON_WEB_IMAGE=ghcr.io/meshcore-beacon/beacon-web:latest # BEACON REST API base URL diff --git a/docs/accounts.md b/docs/accounts.md index 7adf63d..86ec79c 100644 --- a/docs/accounts.md +++ b/docs/accounts.md @@ -34,7 +34,9 @@ accounts: The server also needs to know its public address, for the links it mails. It builds it from the environment: `https://` plus `WEB_DOMAIN`, or plus `DOMAIN` when `WEB_DOMAIN` is not set. -The Docker stacks already set `DOMAIN` in `.env`. Outside them, set it yourself. +The Docker stacks already set `DOMAIN` in `.env`. Outside them, set it yourself. Without it +startup stops. The old `accounts.public_url` key is no longer read: startup logs a warning and you +can delete it. Put the SMTP password in the environment, never in the file: diff --git a/docs/alerts.md b/docs/alerts.md index 20db903..406bf7b 100644 --- a/docs/alerts.md +++ b/docs/alerts.md @@ -24,7 +24,7 @@ alerts: | Channel | What it needs | |---|---| | `email.enabled` | `accounts.mode: local` with the [`mail` block](configuration.md#user-accounts) set. Any other mode stops startup. | -| `push.enabled` | A Push ID in `push.id` and the Push secret in `BEACON_PUSH_SECRET`, from registering the server with the push server. See [Push](#push). Without them Beacon does not start. | +| `push.enabled` | Accounts on, in any mode, plus a Push ID in `push.id` and the Push secret in `BEACON_PUSH_SECRET`, from registering the server with the push server. See [Push](#push). Without them Beacon does not start. | With both off (the default) every alert route answers `404 alerts_disabled`. With accounts off, alert routes answer `404 accounts_disabled`. The old `alerts.delivery` key stops startup with a @@ -42,14 +42,16 @@ failing channel never holds back the other. A user sets rules per radio on their Atlas. A radio has one rule per kind. Which kinds a radio offers depends on what it is and what Beacon has seen it report. Kinds that need readings are offered for a repeater only while telemetry is arriving for it: an observer holds it as a polling -assignment right now, or a trusted reading of it is under 36 hours old. Otherwise the user is told -to request telemetry for it first (see [Requested telemetry](telemetry-requests.md)). +assignment right now, or a trusted reading of it is under 36 hours old. The repeater does not have +to be assigned a poller by this server. Readings from an observer that polls it on its own count +too (see [Repeater polling](repeater-polling.md)). Otherwise the user is told to request telemetry +for it first (see [Requested telemetry](telemetry-requests.md)). | Kind | Radios | Threshold | |---|---|---| | `gone_quiet` | all | Hours: 3, 6, 12, 24 or 48. A repeater nobody polls is only heard through its adverts, so a short window can false-alarm on one; pick to suit the radio. | | `back_online` | all | None. Needs an enabled `gone_quiet` rule on the same radio. Notifies when that rule recovers. | -| `telemetry_stopped` | repeaters and room servers with telemetry | Hours without a reading: 3, 6, 12, 24 or 48. Any trusted reading counts, status or telemetry. The clock runs from the newest reading or from when the rule was set, whichever is later, so there is no alert about the past. It clears on the next reading and keeps firing however long the readings stay away, also after `polling.reading_retention` has deleted the last one. | +| `telemetry_stopped` | repeaters and room servers with telemetry | Hours without a reading: 3, 6, 12, 24 or 48. Any trusted reading counts, status or telemetry. The clock runs from the newest reading or from when the rule was set, whichever is later, so there is no alert about the past. It notifies once, stays `firing` however long the readings stay away, also after `polling.reading_retention` has deleted the last one, and clears on the next reading. | | `clock` | repeaters, room servers | Seconds of drift: 300, 3600 or 86400. Fires after two adverts in a row beyond it. Beacon keeps the drift of each repeater's last 16 adverts, so a breach that came and went between two passes still fires once. | | `battery_low` | with a battery reading | Millivolts, 2500 to 5000. | | `battery_falling` | with a battery reading | Millivolts per day: 100, 200 or 300. | @@ -64,8 +66,8 @@ One more announcement, `request_attention`, is not a rule. Every user who has a gets one notice when it moves to `login_failed`, `admin_stopped` or `disabled`, and another if it recovers and fails again. It is sent whenever alerts are on. -A rule is `ok`, `firing`, `inactive` (the data it needs is gone, for instance a repeater no -observer polls any more) or `unknown` (not enough data yet). +A rule is `ok`, `firing`, `inactive` (the data it needs is gone, for instance a repeater whose +telemetry stopped arriving) or `unknown` (not enough data yet). Changing a threshold or turning a rule on resets it to `unknown` and starts from now, so there is no alert about the past. Taking a radio off the Atlas deletes its rules. A `back_online` rule whose `gone_quiet` rule is turned off or deleted reads `inactive` and sends nothing. @@ -77,9 +79,16 @@ covers a repeater read by a poller this server does not assign (see [Repeater polling](repeater-polling.md)). An observer is polled only if it sent status telemetry in the last 24 hours. Old readings alone do not count, so a radio that was polled can turn `polled: false`; its telemetry kinds then move to `unavailable` with code -`not_polled` (repeater) or `observer_no_data` (observer), and its telemetry rules read `inactive`. +`not_polled` (repeater) or `observer_no_data` (observer), and its battery, temperature, noise and +reboot rules read `inactive`. A `telemetry_stopped` rule is the exception. It exists to report +exactly this, so once set it keeps its clock and its state: it cannot be turned on for a repeater +that is not polled, but one that is already on still fires when the readings stop and stays +`firing` after `polled` turns `false`. + With `polling.enabled: false` no repeater is polled: every repeater reads `polled: false`, its -telemetry kinds are `unavailable` with `not_polled` and its telemetry rules read `inactive`. Observer +telemetry kinds are `unavailable` with `not_polled` and its battery, temperature, noise and reboot +rules read `inactive`. So does a `telemetry_stopped` rule: with polling off no reading can arrive, +and saying so about every repeater would only be noise. Observer status alerts do not depend on polling and carry on. When a kind is not offered the overview gives the reason as an English sentence and as a stable code (`unavailableCodes`), so clients can translate it. The codes are listed in the [API contract](api-contract.md#alerts). @@ -91,9 +100,12 @@ clients can translate it. The codes are listed in the [API contract](api-contrac position is kept in the database. Every enabled rule is evaluated in the end. - A rule notifies when it changes into `firing`, and at most once every 6 hours. `rebooted` and `back_online` notify on the event itself, under the same 6 hour limit. -- A rule goes back to `ok` only when the reading is clear of the threshold by some margin: 100 mV - for battery, 3 dB for noise, 1 degree for temperature. This stops a value at the edge from - flapping. +- `battery_low`, `temperature` and `noise_high` fire when the two newest readings are both past + the limit, so one odd reading does not alert. With fewer than two readings the rule stays + `unknown`. +- Such a rule goes back to `ok` only when the newest reading is clear of the threshold by some + margin: 100 mV for battery, 3 dB for noise, 1 degree C for temperature. This stops a value at the + edge from flapping. - Notices are sent every minute, and only for an evaluation pass that has finished, so the notices of one pass reach a user together. Notices of a pass that never finished (the process stopped) are sent once that pass is 15 minutes old. @@ -115,8 +127,10 @@ clients can translate it. The codes are listed in the [API contract](api-contrac ## Email -One message per user for each evaluation pass: subject "Beacon: 1 alert" or "Beacon: n alerts", -one plain sentence per alert, and a link to `/?tab=Atlas`. The alert sender sends it +One message per user for each evaluation pass: subject "Beacon: 1 alert" or "Beacon: n alerts" +(with the instance's own name in place of "Beacon" when `VITE_APP_NAME` is set, see +[User accounts](accounts.md#turn-them-on)), one plain sentence per alert, and a link to +`/?tab=Atlas`. The alert sender sends it directly, not through the account mail queue, with a 30 second timeout for each message. A notice counts as mailed only once the SMTP server accepted it, and a mail that went out is never sent again, even when the push of the same notice is retried. A failed send is retried on the email channel's diff --git a/docs/api-contract.md b/docs/api-contract.md index 6c6696d..50de3ba 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -94,7 +94,7 @@ Some pages are served only from data the server prepares in the background. Whil | `/channels/{id}/messages` with a location filter (`iata`, `iatas`, `region` or `regionId`), or with `scope` and no `since`; `/messages` with a location filter (with or without `since` or `scope`), or with `scope`, no `since` and no location filter | the server trusts its `channel_message_iatas` read model | | `/observers/{observerId}/adverts` | every observation carries its payload type | -That happens during the first fill after an upgrade, during a repair, after a failed verification, until the observation payload-type backfill is done, and for as long as the operator turns a read model off (see [Operations](operations.md#pages-that-wait-for-a-read-model)). `/messages` with `iatas` and `since` or `scope` is in the table since 2.1: development builds of 2.1 served it from the observations whatever the read model's state, and answered `503` with `Retry-After: 5` when that pool was busy; that `503` is gone. +That happens during the first fill after an upgrade, during a repair, after a failed verification, until the observation payload-type backfill is done, and for as long as the operator turns a read model off (see [Operations](operations.md#pages-that-wait-for-a-read-model)). ``` HTTP/1.1 503 Service Unavailable @@ -117,6 +117,8 @@ All errors use one shape: { "error": { "code": "not_found", "message": "packet not found" } } ``` +The one exception is a path or method no route matches: the router answers those with a plain-text `404` or `405`, without the envelope. + `code` is the HTTP status text in snake_case, so match on it or on the status. The account routes add their own codes, listed under [User accounts](#user-accounts). Codes in use: `bad_request`, `unauthorized`, `not_found`, `conflict`, `request_entity_too_large`, `unsupported_media_type`, `rate_limited`, `internal_server_error`, `service_unavailable`, `gateway_timeout`, `insufficient_storage`, and `deadline_exceeded` (a `503` from the [cost guards](#cost-guards)). A `503` `service_unavailable` with `Retry-After` can also mean a page is [waiting for server data](#pages-that-wait-for-server-data). A `503` `deadline_exceeded` with `Retry-After` from any endpoint means its query ran out of time; retry later or ask for a shorter window. A response the server cannot encode is a `500` `internal_server_error`, never an empty `200`. A `404` means the requested thing doesn't exist. A database or other server-side failure is always a `500` (or `503` above), never a `404`, so clients can retry 5xx and treat 4xx as final. Empty lists are `200` with `[]`. @@ -140,21 +142,21 @@ A few lists return a plain array instead: the backfill endpoints, `/routes`, `/r A numeric `cursor` holds a millisecond, so rows that share the last row's millisecond can fall between two pages. `/packets`, `/nodes`, `/observers` and `/channels` also return `nextPageCursor` on a page with `hasMore`: an opaque string of at most 160 characters (512 on a -sorted `/nodes` list) that marks the exact last row. Send it back as `pageCursor`. A walk by `pageCursor` returns every row once, +sorted `/nodes` list, 64 on `/channels`) that marks the exact last row. Send it back as `pageCursor`. A walk by `pageCursor` returns every row once, including those ties. Don't parse or build it; today it reads `v1::` on `/packets` and `v1::` on `/nodes` and `/observers`. | Endpoint | `pageCursor` | `nextPageCursor` | |---|---|---| | `/packets` without `iata`, `iatas`, `region`, `regionId` or `hashPrefix` | Wins over `cursor` when both are sent. | When `hasMore` | -| `/packets` with `iata`, `iatas`, `region` or `regionId` (a region page), without `hashPrefix` | Wins over `cursor` when both are sent. | When `hasMore`, except on a page requested by a millisecond `cursor` alone that a sparse filter sent to the server's fallback statement | +| `/packets` with `iata`, `iatas`, `region` or `regionId` (a region page), without `hashPrefix` | Wins over `cursor` when both are sent. | When `hasMore` | | `/packets` with `hashPrefix` | Checked, then ignored; `cursor` pages. | Not returned | -| `/nodes`, `/observers` | Wins over `cursor` when both are sent. | When `hasMore` | +| `/nodes`, `/observers` | Wins over `cursor` when both are sent. A [sorted `/nodes` list](#nodes) takes `pageCursor` only. | When `hasMore` | | `/channels` | Can't be combined with a positive `cursor` (`400`). | When `hasMore` | -- `nextCursor` stays on every page with `hasMore` and keeps its meaning: rows strictly older than - that millisecond. Paging by `cursor` alone gives the same pages as before and still skips - rows tied on the boundary millisecond. +- `nextCursor` stays on every page with `hasMore` (except a sorted `/nodes` list, which has + none) and keeps its meaning: rows strictly older than that millisecond. Paging by `cursor` + alone gives the same pages as before and still skips rows tied on the boundary millisecond. - On `/packets`, `/nodes` and `/observers`, send both: `cursor` set to `nextCursor` and `pageCursor` set to `nextPageCursor` when the page has both, `cursor` alone otherwise. A server older than 2.1.0 ignores `pageCursor` and still moves forward by `cursor`. Treat @@ -163,7 +165,7 @@ on `/packets` and `v1::` on `/nodes` and `/observers`. model, which it checks again after every start and drops on any doubt; otherwise they answer `503` (see [Pages that wait for server data](#pages-that-wait-for-server-data)). Keep sending both cursors whenever a page has both. -- A malformed `pageCursor` is a `400` with message `invalid pageCursor` on those three +- A malformed `pageCursor` is a `400` with message `invalid pageCursor` on all four endpoints, on every path, including the `/packets` paths that ignore it. A sorted `/nodes` list says `invalid pageCursor for this sort`. Start again from the first page without it. An empty `pageCursor` counts as absent. @@ -318,7 +320,7 @@ Every shape has `type` and `raw` (payload hex). `type` uses the upper-case names | `CONTROL` | `flags`, `data`; other CONTROL sub-types | | `RAW` | Anything without a decoder (e.g. RAW_CUSTOM) | -`decrypted` in `parsedPayload` is always `null` today. Decrypted channel text is served by the messages endpoints; direct messages are not decrypted. +`decrypted` in `parsedPayload` is `null`, except on a `GROUP_TEXT` that Beacon decrypted into a stored channel message: packet detail then sets it to `{ "sender", "content", "sentAt" }` (`sentAt` in epoch ms). The messages endpoints serve the same text. Direct messages are not decrypted. An ADVERT payload: @@ -365,7 +367,23 @@ Adverts with a bad signature are not decoded and have no `parsedPayload`. | `GET /nodes/{nodeId}/polling` | Which observer polls the node and when it last got a trusted reading. See [Node polling](#node-polling). | | `GET /nodes/{nodeId}/poller` | For a node that is a poller: how many of its slots are used and the repeaters it polls. See [Node poller](#node-poller). | -`/nodes` params: `type` (1 companion, 2 repeater, 3 room server, 4 sensor) or `typeName`, the location filters, `name` (partial, case-insensitive), `scope`, `pubkey` (exact hex), `pubkeyPrefix`, `supportsMultibytePaths`, `supportsMultibyteTraces`, `poller` (`true` keeps only nodes with a stored polling claim, the server's own or a [foreign](#foreign-observers) one, and from 2.3.3 observers that sent readings and no claim in the last 24 hours, `false` drops them, omit for no filter; a value that is not a boolean answers `400`), `neighbors` (adds `neighborIds`), `sort`, `order`, `cursor`, `pageCursor`, `limit`. Summaries include `lastSeen` (when the node was last heard, epoch ms; list rows carry it from 2.1.1, node detail always has), `stale` (not seen within `nodes.stale_threshold`), `isPoller` (`true` when the node's public key has a stored polling claim, so it is an observer running polling firmware, assigned to a repeater or not; see [repeater polling](repeater-polling.md#seeing-the-readings)), `isForeignPoller` (`true` when that claim is a [foreign](#foreign-observers) one; from 2.3.1, treat a missing field as `false`), `defaultScope` (the transport scope last matched from the node's adverts, omitted when none; list rows carry it from 2.1.0, node detail always has) and, when `nodes.mark_foreign` is on, `possiblyForeign`. To list one scope's nodes, send `scope` rather than filtering rows: a server before 2.1.0 leaves `defaultScope` off list rows. +`/nodes` params: `type` (1 companion, 2 repeater, 3 room server, 4 sensor) or `typeName`, the location filters, `name` (partial, case-insensitive), `scope`, `pubkey` (exact hex), `pubkeyPrefix`, `supportsMultibytePaths`, `supportsMultibyteTraces`, `poller`, `neighbors` (adds `neighborIds`), `sort`, `order`, `cursor`, `pageCursor`, `limit`. + +`poller=true` keeps only pollers, the nodes whose `isPoller` is `true` (below); `poller=false` drops them; omit it for no filter. A value that is not a boolean answers `400`. + +Besides the identity fields, a node summary carries: + +| Field | Meaning | +|---|---| +| `lastSeen` | When the node was last heard, epoch ms. List rows carry it from 2.1.1; node detail always has. | +| `stale` | `true` when the node was not seen within `nodes.stale_threshold`. | +| `isPoller` | `true` when the node is an observer running polling firmware: its public key has a stored polling claim, the server's own or a [foreign](#foreign-observers) one, whether or not it is assigned a repeater, or (from 2.3.3) it is a local poller. See [repeater polling](repeater-polling.md#seeing-the-readings). | +| `isForeignPoller` | `true` when that claim is a [foreign](#foreign-observers) one. From 2.3.1; treat a missing field as `false`. | +| `isLocalPoller` | `true` when the observer has no stored claim of either kind and sent a foreign reading in the last 24 hours, as the firmware's local mode does. `isForeignPoller` is then `false`. From 2.3.3; treat a missing field as `false`. | +| `defaultScope` | The transport scope last matched from the node's adverts, omitted when none. List rows carry it from 2.1.0; node detail always has. | +| `possiblyForeign` | Only when `nodes.mark_foreign` is on. See [Foreign repeater indication](#foreign-repeater-indication). | + +To list one scope's nodes, send `scope` rather than filtering rows: a server before 2.1.0 leaves `defaultScope` off list rows. Sorted node lists (2.1.0): `sort` is `lastSeen` (the default), `name`, `type` or `neighbors`, and `order` is `asc` (the default) or `desc`. `lastSeen` defaults to `desc`, the newest-first list; from 2.1.1 it also takes `asc`, oldest heard first, which is a sorted list like the others (a server before 2.1.1 answers it with a `400`). Every page says which order it is in with `sort` and `order` (`lastSeen` and `desc` by default). The orders match what the web's node table shows: @@ -431,7 +449,7 @@ The readings that observers took from a repeater or room server when [repeater p | `interval` | `1h`, `6h`, `24h` | `1h` for `24h` and `72h`, `6h` for `168h`, `24h` for `720h` | | `include` | `untrusted` | none | -Any other value of `range`, `interval` or `include`, or a `nodeId` that is not a UUID, is a `400`. An unknown node is a `404`. A node with no readings is a `200` with `polled` false and `points` empty. With polling off on the server the route still checks the node, so an unknown node is a `404`, and otherwise answers as for a node with no readings: `{"range":"168h","interval":"6h","polled":false,"untrustedReadings":0,"points":[]}`, with `range` and `interval` as asked or defaulted. A client can ask without checking `features` first. +Any other value of `range`, `interval` or `include`, or a `nodeId` that is not a UUID, is a `400`. An unknown node is a `404`. A node with no readings is a `200` with `polled` false and `points` empty. With polling off on the server the route still checks the node, so an unknown node is a `404`, and otherwise answers as for a node with no readings: `{"range":"168h","interval":"6h","polled":false,"untrustedReadings":0,"foreign":"none","points":[]}`, with `range` and `interval` as asked or defaulted. A client can ask without checking `features` first. ```json { @@ -475,6 +493,27 @@ Any other value of `range`, `interval` or `include`, or a `nodeId` that is not a Every field after `readings` is left out when no reading in the bucket carried it. Repeaters do not all report every field. +The five counters (`airtimeTxSecs`, `airtimeRxSecs`, `packetsReceived`, `packetsSent`, `receiveErrors`) are running totals on the repeater. Beacon turns them into increases one pair at a time. A status reading is a reading whose stored `method` is `status`, whether or not it carries any counter: a status reply too short to carry counters is still a status reading. A pair is two consecutive status readings. A status reading without counters therefore takes part in a pair and breaks it (the pair adds nothing), and the next pair starts from that reading, not from the last one that had counters. Telemetry readings (`method` `telemetry`) are never part of a pair. The increases of a pair are credited to the bucket of the later reading. A pair gives the same answer whatever `range` was asked for, so the first pair of a range uses the newest status reading (by `method`) before the range as its earlier half. + +A pair either contributes all of its counters or none of them. It contributes when all of these hold: + +- The later reading is after the earlier one and no more than 48 hours later. A longer gap cannot be placed in a bucket. +- At least one counter is present in both readings. +- No counter is negative, in either reading. A negative value cannot be a running total, so the whole pair is refused. +- The counters do not disagree. Either none went down, or the repeater rebooted and none went up. A reboot is seen when both readings carry uptime and the later uptime is lower than the earlier, or is shorter than the time between the two readings. +- The span is at least one second. +- No increase is faster than its cap: 1 second per second for `airtimeTxSecs` and `airtimeRxSecs`, 10 per second for `receiveErrors`, 50 per second for `packetsReceived` and `packetsSent`. + +The increase of a counter is the later total minus the earlier total. When the pair spans a reboot and every counter went down, the counters restarted from zero, so the increase is the later total, and the span is the later uptime if that is shorter than the time between the readings. A counter that is present in only one of the two readings is skipped for that pair. A pair that does not contribute adds nothing, so it never produces a zero. + +Counters only arrive on status readings, which are hours apart (6 hours by default, up to 24). An increase can therefore cover more time than the bucket it lands in, so it is not a rate per bucket. `counterSpanSecs` says how much time the increases in a point cover. Divide an increase by it to get a rate. For example, `airtimeRxSecs / counterSpanSecs` is the share of time the repeater spent receiving. Do not divide by the bucket length. + +`counterSpanSecs` is the sum of the spans of the pairs that contributed to the bucket, so all the counters in a point share one span. A counter field is left out of a point when any contributing pair in that bucket lacked it, because its increase would cover less time than the span and understate the rate. When no pair contributed, `counterSpanSecs` and all five counters are left out. That includes a bucket that holds only telemetry readings, the first status reading Beacon has for a node, and a bucket whose pairs were all dropped. A client should treat such a point as having no value for the counters, not as zero. + +One case cannot be detected. A corrupt reading that is lower than the truth but passes the rate check can make the following pair read high. + +A reading is trusted when, at the moment it was stored, its observer was assigned to that repeater and Beacon had itself heard the repeater directly through that observer. The decision is made once, when the reading is stored, and does not change later, so a chart does not shift when assignments change. Readings stored before this was recorded were judged against the assignments as they stood when the server was upgraded. Only trusted readings are in `points` by default, so an observer that merely claims a repeater cannot put numbers on its chart. `include=untrusted` adds the rest and `untrustedReadings` tells a client how many it left out. + #### Sensor channels A repeater with extra sensors sends them in its telemetry reply, one channel per sensor. `sensors` @@ -506,27 +545,6 @@ is stored, so readings stored before a server had this carry none; nothing is fi A reply can also hold the repeater's position and an altitude. Beacon never decodes either, and no route returns the raw reply, so neither can be read from the API. -The five counters (`airtimeTxSecs`, `airtimeRxSecs`, `packetsReceived`, `packetsSent`, `receiveErrors`) are running totals on the repeater. Beacon turns them into increases one pair at a time. A status reading is a reading whose stored `method` is `status`, whether or not it carries any counter: a status reply too short to carry counters is still a status reading. A pair is two consecutive status readings. A status reading without counters therefore takes part in a pair and breaks it (the pair adds nothing), and the next pair starts from that reading, not from the last one that had counters. Telemetry readings (`method` `telemetry`) are never part of a pair. The increases of a pair are credited to the bucket of the later reading. A pair gives the same answer whatever `range` was asked for, so the first pair of a range uses the newest status reading (by `method`) before the range as its earlier half. - -A pair either contributes all of its counters or none of them. It contributes when all of these hold: - -- The later reading is after the earlier one and no more than 48 hours later. A longer gap cannot be placed in a bucket. -- At least one counter is present in both readings. -- No counter is negative, in either reading. A negative value cannot be a running total, so the whole pair is refused. -- The counters do not disagree. Either none went down, or the repeater rebooted and none went up. A reboot is seen when both readings carry uptime and the later uptime is lower than the earlier, or is shorter than the time between the two readings. -- The span is at least one second. -- No increase is faster than its cap: 1 second per second for `airtimeTxSecs` and `airtimeRxSecs`, 10 per second for `receiveErrors`, 50 per second for `packetsReceived` and `packetsSent`. - -The increase of a counter is the later total minus the earlier total. When the pair spans a reboot and every counter went down, the counters restarted from zero, so the increase is the later total, and the span is the later uptime if that is shorter than the time between the readings. A counter that is present in only one of the two readings is skipped for that pair. A pair that does not contribute adds nothing, so it never produces a zero. - -Counters only arrive on status readings, which are hours apart (6 hours by default, up to 24). An increase can therefore cover more time than the bucket it lands in, so it is not a rate per bucket. `counterSpanSecs` says how much time the increases in a point cover. Divide an increase by it to get a rate. For example, `airtimeRxSecs / counterSpanSecs` is the share of time the repeater spent receiving. Do not divide by the bucket length. - -`counterSpanSecs` is the sum of the spans of the pairs that contributed to the bucket, so all the counters in a point share one span. A counter field is left out of a point when any contributing pair in that bucket lacked it, because its increase would cover less time than the span and understate the rate. When no pair contributed, `counterSpanSecs` and all five counters are left out. That includes a bucket that holds only telemetry readings, the first status reading Beacon has for a node, and a bucket whose pairs were all dropped. A client should treat such a point as having no value for the counters, not as zero. - -One case cannot be detected. A corrupt reading that is lower than the truth but passes the rate check can make the following pair read high. - -A reading is trusted when, at the moment it was stored, its observer was assigned to that repeater and Beacon had itself heard the repeater directly through that observer. The decision is made once, when the reading is stored, and does not change later, so a chart does not shift when assignments change. Readings stored before this was recorded were judged against the assignments as they stood when the server was upgraded. Only trusted readings are in `points` by default, so an observer that merely claims a repeater cannot put numbers on its chart. `include=untrusted` adds the rest and `untrustedReadings` tells a client how many it left out. - #### Latest node telemetry ``` @@ -563,7 +581,7 @@ The answer has one item for each node that has a trusted reading in the last 7 d GET /api/v1/nodes/{nodeId}/polling ``` -Who polls this node right now. A `400` for a `nodeId` that is not a UUID and a `404` for an unknown node. With polling off it still checks the node (an unknown node is a `404`) and then answers `{"polled":false,"latestReadingAt":null,"poller":null,"standbys":[]}`, the same as for a node nobody polls. +Who polls this node right now. A `400` for a `nodeId` that is not a UUID and a `404` for an unknown node. With polling off it still checks the node (an unknown node is a `404`) and then answers `{"polled":false,"latestReadingAt":null,"poller":null,"standbys":[],"foreign":[]}`, the same as for a node nobody polls. ```json { @@ -572,7 +590,7 @@ Who polls this node right now. A `400` for a `nodeId` that is not a UUID and a ` "poller": { "observerId": "8f0c6a52-0d56-4a47-9c36-3e8f1c2f4b11", "name": "HOWL V4.2" }, "standbys": [ { "observerId": "5b1d0f1e-7c3a-4d0e-8a56-9f2b6c1d7a20", "name": "Ridge West", "rank": 1 } ], "foreign": [ { "observerId": "0c9e2f6b-1d34-4b7e-9a11-6f3d2c8b5e40", "name": "Lakeside", "pollHost": "other.example.org", - "signed": true, "claimed": true, "latestReadingAt": 1794702000000 } ] + "signed": true, "claimed": true, "local": false, "latestReadingAt": 1794702000000 } ] } ``` @@ -582,7 +600,18 @@ Who polls this node right now. A `400` for a `nodeId` that is not a UUID and a ` | `latestReadingAt` | Time of the newest trusted reading, epoch ms. `null` when there is none, even if untrusted readings exist. | | `poller` | The observer ranked first: `observerId` and `name`. `null` when nobody is assigned. | | `standbys` | The other assigned observers, in rank order, each with `observerId`, `name` and `rank` (1, 2, ...). An empty array when there are none. The poller has no `rank` field. | -| `foreign` | [Foreign observers](#foreign-observers) that check the node: a live foreign claim names it, or one delivered a reading of it in the last 24 hours. Each has `observerId`, `name`, `pollHost` (the server it says it follows, or `null`), `signed` (its claim's signature checked out), `claimed` (`true` when it has a live claim that names this node; `false` when its claim is stale, names other repeaters only, or it has none), `local` (from 2.3.4: `true` when it has no stored claim at all and only sends readings, as the firmware's local mode does; treat a missing value as unknown) and `latestReadingAt` (its newest reading of the node, epoch ms or `null`). By name. They are never the poller or a standby. An empty array when there are none, which is always the case with `polling.foreign_claims: off`. From 2.3.1. | +| `foreign` | [Foreign observers](#foreign-observers) that check the node: a live foreign claim names it, or one delivered a reading of it in the last 24 hours. Ordered by name. They are never the poller or a standby. An empty array when there are none, which is always the case with `polling.foreign_claims: off`. From 2.3.1. | + +Each `foreign` entry: + +| Field | Notes | +|---|---| +| `observerId`, `name` | The observer. | +| `pollHost` | The server it says it follows, or `null`. | +| `signed` | `true` when its claim's signature checked out. | +| `claimed` | `true` when it has a live claim that names this node; `false` when its claim is stale, names other repeaters only, or it has none. | +| `local` | `true` when it has no stored claim at all and only sends readings, as the firmware's local mode does. From 2.3.4; treat a missing value as unknown. | +| `latestReadingAt` | Its newest reading of the node, epoch ms or `null`. | `name` is the observer's display name, or the first 8 hex characters of its public key when it has none. @@ -592,7 +621,7 @@ Who polls this node right now. A `400` for a `nodeId` that is not a UUID and a ` GET /api/v1/nodes/{nodeId}/poller ``` -The other side of [Node polling](#node-polling): what an observer that polls says it holds, read from its last stored [claim](#claim-message). A `400` for a `nodeId` that is not a UUID and a `404` for an unknown node. A node with no stored claim answers `{"claim":null,"readings24h":0,"targets":[]}`. With polling off the route still checks the node (an unknown node is a `404`) and then gives that same answer. Not cached. +The other side of [Node polling](#node-polling): what an observer that polls says it holds, read from its last stored [claim](#claim-message). A `400` for a `nodeId` that is not a UUID and a `404` for an unknown node. A node with no stored claim and no readings answers `{"claim":null,"readings24h":0,"foreignReadings24h":0,"targets":[]}`. With polling off the route still checks the node (an unknown node is a `404`) and then gives that same answer. Not cached. ```json { @@ -744,7 +773,7 @@ Before, it came from the last status message and was missing when the last row h walk by `cursor` skipped most observers. Paging by `cursor` alone can still skip observers that share a millisecond (presence updates often stamp many at once); `pageCursor` reaches all of them. -The telemetry response is an array ordered by time. `interval=1h` returns the stored snapshots as they +The `points` of the telemetry response are ordered by time. `interval=1h` returns the stored snapshots as they are: one per `telemetry.resolution` window (15 minutes by default), plus one stored at once when the observer reboots, so points are not evenly spaced. `6h` and `24h` return buckets. `airtimeTxSecs` and `airtimeRxSecs` are seconds of radio time as reported by the observer: cumulative since boot on @@ -792,9 +821,9 @@ hours behind and `[rolledUntil, rawFrom)` is unknown, not quiet; show it as a ga assumes; it is `null` when those parameters are unknown, in which case `airtimeMs` is `null` on every bucket too (airtime cannot be costed without them). `snrAvg`, `snrMin` and `rssiAvg` are `null` for buckets whose observations carried no usable signal readings. The `payloadTypes` counts cover the same -window and their total matches the sum of `observations` across `points`. On sub-hour intervals only, -observations with an undetermined payload type are counted in `observations` but omitted from the -breakdown; none exist within the retention window in practice. +window and their total matches the sum of `observations` across `points`. Observations with an +undetermined payload type are counted under `payloadType` `-1`; none exist within the retention +window in practice. `airtimeMs` sums only the observations that could be costed. The migration that introduced airtime backfills the trailing 7 days, so for the first 30 days after deploy buckets older than 7 days may be @@ -850,7 +879,7 @@ packets and the last complete hour: | `GET /messages` | Page of messages across channels, newest first. | | `GET /messages/backfill?afterId=` | Messages after that ID, oldest first, plain array. Default limit 100. | -`/channels` params: `hash` (channel byte hex), `iata`/`iatas`, `keyKnown` (`true` for channels Beacon can decrypt, `false` for hash-only), `cursor`, `pageCursor`, `limit` (default 50). An IATA filter lists channels MeshMapper lists there, configured channels scoped to a region containing it, and Beacon-wide configured channels. The page adds `nextPageCursor`, an opaque string that keeps timestamp ties and precision; prefer it over the numeric `cursor` (the two can't be combined). A channel's `messageCount` is a lifetime total; packet retention does not reduce it. +`/channels` params: `hash` (channel byte hex), `iata`/`iatas`, `keyKnown` (`true` for channels Beacon can decrypt, `false` for hash-only), `cursor`, `pageCursor`, `limit` (default 50). An IATA filter lists channels MeshMapper lists there, configured channels scoped to a region containing it, and Beacon-wide configured channels. The page adds `nextPageCursor`, an opaque string that keeps timestamp ties and precision; prefer it over the numeric `cursor` (it can't be combined with a positive `cursor`). A channel's `messageCount` is a lifetime total; packet retention does not reduce it. Message lists take `since`, the location filters, `scope`, `cursor` (message ID) and `limit` (default 50). `/messages` also takes `channelID` or `channelHash`. A message: @@ -895,9 +924,9 @@ Known routes are fully resolved multi-hop paths distilled from packet history. | Endpoint | Notes | |---|---| | `GET /routes` | Plain array, newest `lastSeen` first. Params: `iatas` (comma list, at most 100), `iata`, `hopCount`, `cursor` (last item's `lastSeen`, epoch ms), `cursorId` (last item's `id`), `limit` (default 50, larger values clamp to 200). A `hopCount` or `cursor` that is not a number is a `400`. With neither `iatas` nor `iata`, every IATA. | -| `GET /routes/search?from=&to=[&iatas=]` | Routes within one IATA between two node hash prefixes. `from`, `to` required (hex, 1–4 bytes; widths may differ). `iatas` optional: comma list, at most 100, omitted = every IATA; the single `iata` is still accepted. At most 500 results, shortest first. `hops` is trimmed to source…destination and `hopCount` = `hops.length`. | +| `GET /routes/search?from=&to=[&iatas=]` | Routes within one IATA between two node hash prefixes. `from`, `to` required (hex, 1–4 bytes; widths may differ). `iatas` optional: comma list, at most 100, omitted = every IATA; the single `iata` is still accepted. At most 500 results, ordered by the hop count of the whole stored route, shortest first, then newest `lastSeen`. `hops` is trimmed to source…destination and `hopCount` = `hops.length`, so the returned `hopCount` values are not always ascending. | | `GET /routes/cross?fromHash=&toHash=[&iatas=]` | Routes that cross from one IATA into another. `fromHash`, `toHash` required. `iatas` optional: 2–100 codes, omitted = every IATA. The legacy `fromIata`+`toIata` pair is still accepted, but not together with `iatas`. At most 500 results, sorted by `totalHops`, then `crossHop.lastSeen` newest first. | -| `GET /routes/{iata}/{pathKey}/observations` | Retained reports that match a saved route exactly. `pathKey` comes from a route response. Window: `range` (default `24h`, max `720h`) or `since`+`until` (max 30 days); `pageCursor` for the next page; `limit` default 50. The cursor keeps the hash size and path bytes the first page matched, so later pages follow the same path even if the route's stored prefixes change. A lookup past the statement limit answers `503` + `Retry-After` ([Cost guards](#cost-guards)). | +| `GET /routes/{iata}/{pathKey}/observations` | Retained reports that match a saved route exactly. `pathKey` comes from a route response. Window: `range` (default `24h`, max `720h`) or `since`+`until` (max 30 days); `pageCursor` for the next page; `limit` default 50. The cursor keeps the hash size and path bytes the first page matched, so later pages follow the same path even if the route's stored prefixes change. `404` when the IATA and `pathKey` name no saved route; `400` for a bad window, limit or cursor. A lookup past the statement limit answers `503` + `Retry-After` ([Cost guards](#cost-guards)). | To page `/routes`, send the last item's `lastSeen` as `cursor` and its `id` as `cursorId`. Routes share a millisecond often (one batch of upserts), and `cursorId` returns the ones that didn't fit on the previous page. `cursor` alone still works but can skip those ties. `cursorId` must be a positive integer and requires `cursor`; otherwise `400`. @@ -1130,7 +1159,7 @@ Swagger shows. Servers older than this endpoint return `404`. See The API itself stays in Celsius and metric whatever `display` says. Alert temperature limits are still stored and sent as tenths of a degree C. Clients convert for display. -A client must treat a missing `features`, as sent by an older server, as all off, a missing `registration` as `false`, and a missing `portalUrl` or `push` as none, a missing `alertChannels` as both off, a missing `atlasTelemetry` as `false`, a missing `atlasPoller` as `false` (keep a `poller` view local and do not send it), a missing `atlas7d` as `false` (do not offer `7d` or send it; a saved `7d` Atlas shows and sends `3d`), a missing `mapTelemetry` as `false` (hide the toggle), a missing `appDeviceLabel` as `false`, a missing `display` as `c` and `metric`, and a missing `limits.atlas` as 12, the cap before it was configurable. A client that does not know an `accounts` value other than `"off"` and `"local"` should treat it as `"off"`. +A client must treat a missing `features`, as sent by an older server, as all off, a missing `registration` as `false`, and a missing `portalUrl` or `push` as none, a missing `alertChannels` as both off, a missing `atlasTelemetry` as `false`, a missing `sensors` as `false` (ignore `sensors` on points and do not send the sensor tile ids), a missing `atlasPoller` as `false` (keep a `poller` view local and do not send it), a missing `atlas7d` as `false` (do not offer `7d` or send it; a saved `7d` Atlas shows and sends `3d`), a missing `mapTelemetry` as `false` (hide the toggle), a missing `appDeviceLabel` as `false`, a missing `display` as `c` and `metric`, and a missing `limits.atlas` as 12, the cap before it was configurable. A client that does not know an `accounts` value other than `"off"` and `"local"` should treat it as `"off"`. Beacon Web calls `/info` on load and again when the tab regains focus (at most once a minute). When its own version is lower than `minWebVersion` it shows a full-screen "reload" screen instead of the @@ -1161,10 +1190,10 @@ All under `/api/v1/admin/`, bearer key required (see [Auth](#auth)). | Endpoint | Notes | |---|---| -| `GET /admin/config` | Running CORS settings with defaults applied, `auth.configured`, `ingest.broker_count` (configured broker workers, not connection status), `mobile.min_app_version` and `web.min_web_version` (read-only effective floors, at least the built-in `2.3.0`), and `guards` (below). No credentials, broker addresses, channel material or database connection settings. | +| `GET /admin/config` | Running CORS settings with defaults applied, `auth.configured`, `ingest.broker_count` (configured broker workers, not connection status), `mobile.min_app_version` and `web.min_web_version` (read-only effective floors, at least the built-in `2.3.4`), and `guards` (below). No credentials, broker addresses, channel material or database connection settings. | | `PUT /admin/config` | Replaces `cors.allowed_origins`, `guards.enforce` or both until the next restart. JSON body up to 16 KiB. | | `GET /admin/db/statements` | `pg_stat_statements` for this database, summed by statement name. `503` when the extension is missing or not preloaded. | -| `GET /admin/db/planguard` | The last report of the daily plan check. `?fresh=true` runs it now, at most one run per 5 minutes. `404` while `planguard.daily_check` is off or before the first run; `500` when no run has succeeded. Details below. | +| `GET /admin/db/planguard` | The last report of the daily plan check. `?fresh=true` runs it now, at most one run per 5 minutes. `404` while `planguard.daily_check` is off or before the first successful run; with `fresh`, `500` when no run has succeeded. Details below. | | `GET /admin/users`, `PUT /admin/users/{id}`, `DELETE /admin/users/{id}` | Manage [user accounts](#operator-user-routes). `503` while accounts are off or the server is read-only. | | `GET /admin/accounts`, `POST /admin/accounts` | List or create operator account records (name only; not logins). | | `GET /admin/accounts/{id}`, `DELETE /admin/accounts/{id}` | Fetch or deactivate one. | @@ -1188,7 +1217,7 @@ may see the old settings. `guards` in the config reports the [cost guards](#cost-guards): ```json -{ "enforce": ["other", "routes"], "observe_only": false, "budget": "shadow", "api_plan_layout": "custom_all" } +{ "enforce": ["routes", "other"], "observe_only": false, "budget": "shadow", "api_plan_layout": "custom_all" } ``` `enforce` lists the families that refuse; every other family only counts. `observe_only` is true @@ -1372,7 +1401,7 @@ Notes: `DELETE /me/sessions/{id}` with an id that is not the user's changes nothing; a bad id is `422 invalid_input`; ending the current session also clears the cookie. - **App sign-in.** The user must be signed in on the web. `/auth/app/code` takes the base64url - SHA-256 of a random verifier as `codeChallenge` (S256 only), a `state` of at most 256 characters + SHA-256 of a random verifier as `codeChallenge` (S256 only), a `state` of at most 256 bytes and a `deviceLabel`, and returns a one-time `code` and `redirectUri`, always `meshcorebeacon://auth`. The app sends `code` and `codeVerifier` to `/auth/app/token`, and its own `deviceLabel` (such as `Beacon app on iOS`) when `/info` has `features.appDeviceLabel`. That label names the session; when it @@ -1428,7 +1457,7 @@ Error codes the account routes use: Bearer admin key, see [Auth](#auth). `503` while accounts are off or the server is read-only. - `GET /admin/users?search=&cursor=&limit=` lists users newest first. `limit` is 1 to 200, default 50; - `search` is part of a username or email, at most 100 characters. Returns `{items, nextCursor}`; + `search` is part of a username or email, at most 100 bytes. Returns `{items, nextCursor}`; `nextCursor` is missing on the last page. Each item is a user plus `disabled` and `lastLoginAt` (epoch ms or `null`). `400` for a `search` that is too long, a `limit` out of range or a bad `cursor`. @@ -1496,8 +1525,8 @@ Removing a radio from the Atlas deletes its alert rules in the same transaction. A user asks for a repeater or room server to be polled. See [Requested telemetry](telemetry-requests.md). With requests off (`features.telemetryRequests` is false) every route here answers -`404 requests_disabled`. All need a session, are cookie writes that pass the forgery check, and -answer `503 read_only` on a read-only server. +`404 requests_disabled`. All need a session. The writes (`POST`, `PATCH`, `DELETE`) pass the +forgery check and answer `503 read_only` on a read-only server. ``` GET /api/v1/me/telemetry-requests @@ -1598,7 +1627,7 @@ DELETE /api/v1/me/telemetry-requests/{id} |---|---|---| | 404 | `requests_disabled` | Requests are off. | | 409 | `foreign_poller` | A foreign observer already checks the repeater and `acknowledgeForeign` was not sent. From 2.3.1. | -| 404 | `not_found` | Unknown node, or an unknown or foreign request id. | +| 404 | `not_found` | Unknown node, or a request id that is unknown or another user's. | | 409 | `already_requested` | The user already has a request for this repeater (wins over the limit). | | 409 | `request_limit` | The user holds `limit` requests. | | 409 | `no_password_blocked` | The repeater gives admin to a blank login, so a request needs a guest password. Also when removing the password on such a repeater. | @@ -1739,14 +1768,14 @@ a key. | 422 | `invalid_threshold` | The threshold is out of range or the wrong shape for the kind. Also an unknown `kind` or `target.kind`. | | 422 | `invalid_input` | A bad key or rule id; a bad platform, push token or payload key; or a channels body with neither field. | | 404 | `push_disabled` | `POST /me/devices` on a server that does not send push. | -| 404 | `not_found` | Unknown or foreign rule id. | +| 404 | `not_found` | A rule id that is unknown or another user's. | | 403 | `app_session_required` | A device route called with a cookie session. | #### Push delivery Every Beacon server sends push through the MeshCore Beacon push server, `features.push.server` (the official one is `https://push.meshcorebeacon.ca`). Its API is documented in the -[beacon-push README](https://github.com/MeshCore-Beacon/beacon-push/blob/dev/README.md). The app: +[beacon-push README](https://github.com/MeshCore-Beacon/beacon-push/blob/main/README.md). The app: 1. Reads `features.push` from `/info`. Without it the server does not send push. 2. Gets its device token (APNs on iOS, FCM on Android), then `POST /v1/handles` @@ -2163,13 +2192,13 @@ All client messages have a `type` and an optional `id`, which replies echo. "regionSlugs": ["eastern-canada"], "payloadTypes": [4, 5], "channelHashes": ["f3"], - "events": ["packetObservation", "observerStatus"] + "events": ["packetObservation", "nodeUpdate"] } } ``` - `iatas`, plus the member IATAs of any `regionIds` (numeric IDs as strings) and `regionSlugs`. Unknown regions are skipped. If regions were given and they, together with `iatas`, yield no IATA, the subscription is still acknowledged with `subscribed` and receives no events. -- `payloadTypes`: numeric payload types. +- `payloadTypes`: numeric payload types. The filter applies to every event, not only `packetObservation`: a `nodeUpdate` counts as type 4 (advert), and `observerStatus` and `channelMessage` count as type 0. A subscription that wants those two with a `payloadTypes` list must include 0, or use a separate subscription without `payloadTypes`. - `channelHashes`: only filters `channelMessage` events. - `events`: any of `packetObservation`, `observerStatus`, `nodeUpdate`, `channelMessage`. @@ -2315,7 +2344,7 @@ Connections with `includeRepeats` also get repeats, which have `packet.isRepeat: } ``` -`lat`/`lng` omitted means the advert had no position (keep the one you have); `null` means the advert cleared it. `iatas` holds only the IATA that heard this advert, so merge it into what you have. `isPoller` is `true` when the node has a stored polling claim, the server's own or a foreign one. `possiblyForeign` is only sent when `nodes.mark_foreign` is on, and is omitted for a repeater advert with no position (keep the value you have). `defaultScope` and `radio` are omitted when unknown. +`lat`/`lng` omitted means the advert had no position (keep the one you have); `null` means the advert cleared it. `iatas` holds only the IATA that heard this advert, so merge it into what you have. `isPoller` means the same as on a [node summary](#nodes): a stored polling claim, the server's own or a foreign one, or a local poller. The event has no `isForeignPoller` or `isLocalPoller`; read those over REST. `possiblyForeign` is only sent when `nodes.mark_foreign` is on, and is omitted for a repeater advert with no position (keep the value you have). `defaultScope` and `radio` are omitted when unknown. **`channelMessage`**: a group text was decrypted into a new message. The `data` is the same shape as a REST message (see [Channels and messages](#channels-and-messages)) plus `channelId`, without `observationCount`. @@ -2369,7 +2398,8 @@ connects without one, which works on any server that leaves `websocket.require_o **Minimum app version.** The app calls `GET /info` on launch, on return to foreground and when the user switches servers. When the app's own version is lower than `minAppVersion` (compared numerically, part by part), it blocks that server behind an "update required" screen until the -app is updated. Other servers stay usable. `minAppVersion: null` means no requirement. A `404` +app is updated. Other servers stay usable. A beta or development build, whose version is not a +plain `X.Y.Z`, is never blocked. `minAppVersion: null` or a malformed value means no requirement. A `404` comes from a server that predates the endpoint and also means no requirement. Network errors, timeouts and other failures do not block: the app keeps using the server and checks again next time. diff --git a/docs/atlas.md b/docs/atlas.md index a7560e1..6b65d69 100644 --- a/docs/atlas.md +++ b/docs/atlas.md @@ -58,9 +58,9 @@ tabs that card has: Analytics, Heard by, Observer, Telemetry and Poller. Every t only the open one also shows its name, so the row fits a phone in any language. Hover or long-press an icon for its name. -The Analytics and Observer views end in a one-line footer. It never wraps: text that does not fit +Every view except Heard by ends in a one-line bottom row. It never wraps: text that does not fit is cut short, and the info tip at its end lists every fact in full, with absolute times, followed -by the help text. While a view's data is loading, or when it fails to load, the line says so. +by the help text. While a view's data is loading, or when it fails to load, the row says so. Clicking a tile's graph on the web, or tapping it in the app, opens a large graph of that metric with exact values and zoom. @@ -81,8 +81,8 @@ that node over the selected window: sparkline. The zero-RSSI / zero-SNR "no measurement" sentinel is excluded; a real zero SNR is included. These describe the receivers' side, not the node's radio health. - **Active hours**: hours in the window with at least one reception. -- The footer has when the node was last seen on the left, and **Mean hops** (the average hop - count of those receptions) and the node's neighbor count on the right. +- The bottom row has when the node was last heard on the left, and the mean hops (the average + hop count of those receptions) and the node's neighbor count on the right. - The dot before the name is green for recent and amber for stale. It is the server's `stale` verdict; the client does not infer online or offline. On an observer card it is online or offline. @@ -97,7 +97,7 @@ for it. **Observer** appears when the node is also an observer, and is the only view of an observer card. It shows what that observer received and reported over the window, in four tiles. A new card -shows Airtime, Battery, Packet types and Noise floor. The footer has **Online** or **Offline** +shows Airtime, Battery, Packet types and Noise floor. The bottom row has **Online** or **Offline** with the last status time on the left, and the radio frequency and spreading factor on the right. Its info tip adds the full radio settings, and the uptime when no tile is showing it. @@ -140,28 +140,51 @@ the info tip says so. ### The tab a card opens on On a server with [repeater polling](repeater-polling.md) on (`features.polling`), a card for a -repeater or room server gets a **Telemetry** tab when an observer is assigned to poll it, or when -it has readings from the last 30 days. The tab keeps its own four tiles, chosen from battery, -noise floor, uptime, airtime, temperature, packets, signal and errors, separate from the Observer -view's tiles. A repeater with extra sensors also offers humidity, pressure, gas, power, current and -sensor voltage, each only while it has readings of it in the window. A sensor tile shows the lowest -sensor channel that carries its value; the node's Telemetry panel charts every channel. The gas tile reads Air quality when the sensor sends an index instead of a -resistance, and carries a chip in its corner with how far the sensor's own calibration has got, from 0/3 to -3/3: below 3 the index is the sensor's estimate. The Telemetry panel's air quality chart carries -the same status in words. A new card shows battery, noise floor, uptime and airtime. Both the tab and the -tiles are saved with the card as `view: "telemetry"` and `telemetryTiles`. A card pinned to -Telemetry that loses the tab opens on Analytics. +repeater or room server gets a **Telemetry** tab when Beacon has telemetry for it: an observer is +assigned to poll it, or it has readings from the last 30 days, whichever observer took them. A +repeater nobody polls has no readings and no tab. + +The tab keeps its own four tiles, separate from the Observer view's tiles. A new card shows +battery, noise floor, uptime and airtime. Each tile's label opens the list of the others: + +- Battery, noise floor, uptime, airtime, packets, signal and errors are always offered. +- Temperature is offered while the repeater has temperature readings in the window. +- Humidity, pressure, gas, power, current and sensor voltage are the sensor tiles. Each is offered + only while the repeater has readings of it in the window, so a repeater without extra sensors + never lists them. A sensor tile shows the lowest sensor channel that carries its value; the + node's Telemetry panel charts every channel. + +The gas tile reads **Air quality** when the sensor sends an index instead of a resistance. It then +carries a chip that says how far the sensor's own calibration has got, from 0/3 to 3/3. Below 3 the +index is an estimate and can still change a lot. The Telemetry panel's air quality chart carries +the same status in words ("Calibrating (1/3)", "Calibrated (3/3)"). + +The tab's bottom row always says when the last reading was. While an observer is assigned it +reads "Polled", the time and the poller's name. With no observer assigned it reads "Last reading" +and the time, with "Not polled" on the right. Readings taken by an observer this server does not +manage are tagged in the same row: "Foreign source" or "Includes foreign readings", or "Local +source" or "Includes local readings" when the observer runs in local mode. The tag then stands in +for "Not polled", because the repeater is polled, only not by this server. See +[Foreign observers](repeater-polling.md#foreign-observers). + +Both the tab and the tiles are saved with the card as `view: "telemetry"` and `telemetryTiles`. A +card pinned to Telemetry that loses the tab opens on Analytics. On a server with polling on, a card for a node with the Poller tag gets a **Poller** tab, once the -node is linked to its observer. Its four tiles are fixed: **Slots** (how -many of its slots are used, split into its owner's own repeaters and requested ones, with a seat -meter), **Answering** (how many of the repeaters it holds report `ok`, with a dot for each), -**Readings** (readings Beacon received from it in the last 24 hours) and **Last claim** (when -Beacon last received its claim and whether it accepts requests). The footer says how many repeaters -it is the elected poller for. The card's open button opens the node on its Poller view. The tab is -saved as -`view: "poller"`, only to a server that reports `features.atlasPoller`; on another server the -choice stays in the browser or app. A card pinned to Poller that loses the tab opens on Analytics. +node is linked to its observer. Its four tiles are fixed: + +- **Slots**: how many of its slots are used, split into its owner's own repeaters and requested + ones, with a seat meter. +- **Answering**: how many of the repeaters it holds report `ok`, with a dot for each. +- **Readings**: readings Beacon received from it in the last 24 hours. +- **Last claim**: when Beacon last received its claim and whether it accepts requests. + +The bottom row says how many repeaters it is the elected poller for. An observer in local mode +sends no claim, so its Slots and Last claim tiles are empty, the second tile counts the repeaters +it sent readings for, and the bottom row says "Local mode". The card's open button opens the node +on its Poller view. The tab is saved as `view: "poller"`, only to a server that reports +`features.atlasPoller`; on another server the choice stays in the browser or app. A card pinned to +Poller that loses the tab opens on Analytics. In edit mode a card with more than one tab shows a pin. It is lit on the tab the card opens on. Press it on another tab to make the card open there; the choice is saved with the card. diff --git a/docs/backup-export.md b/docs/backup-export.md index 8acd70b..b09e850 100644 --- a/docs/backup-export.md +++ b/docs/backup-export.md @@ -16,9 +16,10 @@ Exactly three regular files: - `config.yaml`: the saved file byte-for-byte, read just before the snapshot. Avoid config edits during an export. -**It is sensitive and unencrypted** (keys, message data, user accounts and push device keys); keep it private. It is not a full -recovery package: `.env` and environment variables, `borderFile` and TLS files, runtime-only -changes, PostgreSQL roles and cluster settings, Redis and deployment files are not included. +**It is sensitive and unencrypted** (keys, message data, user accounts and push device keys); +keep it private. It is not a full recovery package: `.env` and environment variables, +`borderFile` and TLS files, runtime-only changes, PostgreSQL roles and cluster settings, Redis +and deployment files are not included. ## Requirements and limits @@ -27,13 +28,14 @@ changes, PostgreSQL roles and cluster settings, Redis and deployment files are n MeshMapper key because the YAML is included verbatim. Environment secrets remain excluded; preserve them separately for recovery. See [MeshMapper API key](configuration.md#meshmapper-api-key). - `pg_dump` must be in the **same runtime** as the exporter (the CLI's environment, or the - server's PATH for the download), with a major version at least as new as the database's. A client on - the Docker host or in another container doesn't count. + server's PATH for the download), with a major version at least as new as the database's. A + client on the Docker host or in another container doesn't count. - The published Docker image ships the PostgreSQL 16 client on an Alpine 3.24 base. For a PostgreSQL 17 or 18 database, build your own image from a beacon-server checkout, e.g. `docker build -f .build/Dockerfile --build-arg POSTGRES_CLIENT_MAJOR=17 -t beacon:pg17 .`, and point the stack's `image:` at that tag. -- The temp directory (`TMPDIR`) needs about twice the SQL limit free. A small tmpfs won't do. +- Staging needs about twice the SQL limit free. The download stages in the server's temp + directory (`TMPDIR`), where a small tmpfs won't do; the CLI stages next to its output file. - The output filesystem must support hard links (used to publish atomically). Existing destinations, symlinks included, are never replaced. Files are 0600 and staging dirs 0700; on Windows, restrict the directory ACLs yourself. diff --git a/docs/configuration.md b/docs/configuration.md index 0cf635c..4c03485 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -23,9 +23,9 @@ to open). | `MQTT_BROKER_1_PASSWORD` | unset | Subscriber password for broker 1. | | `MQTT_BROKER_2_URL`, `_USERNAME`, `_PASSWORD` | unset | The same for an optional second broker. A packet heard through both brokers is stored once. | | `MQTT_BROKER_1_NAME`, `MQTT_BROKER_2_NAME` | `mqtt1`, `mqtt2` | The name each broker is stored and shown under: on a packet's brokers, an observer's brokers, the broker filter and `GET /brokers`. 1 to 64 characters of `a-z`, `0-9`, `_` or `-`; the two must differ. Anything else stops startup. Data received before a change keeps its old name: a packet for good, an observer's broker list until the old name is 30 days unseen. | -| `MQTT_BROKER_1_REBROADCAST`, `MQTT_BROKER_2_REBROADCAST` | unset | `true` when that broker is a rebroadcaster. Beacon then connects to it with MQTT 5 and reads the source of each message. Anything but `true` or `false` stops startup. See [Behind a rebroadcaster](#behind-a-rebroadcaster). | -| `DOMAIN` | unset | The host observers and browsers reach the server at. The Docker stacks already set it for Caddy; the server reads the same value. Needed for [user accounts](#user-accounts) and for `polling.foreign_claims: check`. A scheme or trailing slash left on it is dropped. | -| `WEB_DOMAIN` | unset | The web app's host when it is not `DOMAIN` (deployment type 2). Used for the links in mail. | +| `MQTT_BROKER_1_REBROADCAST`, `MQTT_BROKER_2_REBROADCAST` | unset | `true` when that broker is a rebroadcaster. Beacon then connects to it with MQTT 5 and reads the source of each message. Unset or empty means `false`; a value that is not a boolean stops startup. See [Behind a rebroadcaster](#behind-a-rebroadcaster). | +| `DOMAIN` | unset | The host observers and browsers reach the server at. The Docker stacks already set it for Caddy; the server reads the same value. Needed for [user accounts](#user-accounts) and for `polling.foreign_claims: check`. One host name, with an optional port; a scheme or trailing slash left on it is dropped. | +| `WEB_DOMAIN` | unset | The web app's host when it is not `DOMAIN` (deployment type 2). Used for the links in mail and for the origin check on signed-in requests. | | `BEACON_API_KEY` | unset | Bearer key for `/api/v1/admin/*`. When set, even to an empty string, it replaces `auth.api_key` from the config file. See [Admin API key](#admin-api-key). | | `MESHMAPPER_API_KEY` | unset | Regional or grouped-region key for enabled MeshMapper imports. When set, even to an empty string, it replaces `meshmapper.api_key`. Missing keys leave imports unconfigured while Beacon keeps running. See [MeshMapper API key](#meshmapper-api-key). | | `BEACON_SECRET_KEY` | unset | 32 random bytes in base64. Seals the guest passwords of [telemetry requests](telemetry-requests.md). See [BEACON_SECRET_KEY](#beacon_secret_key). | @@ -62,7 +62,7 @@ These are read by `docker-compose.yml` and Caddy. The server reads `DOMAIN` and |---|---|---| | `DOMAIN` | Caddy and the server, both deployments | The public hostname Caddy serves and requests a certificate for. | | `WEB_DOMAIN` | Caddy and the server, type 2 server host only | The web frontend's hostname. Anything that is not `/api/*`, `/ws` or `/.well-known/beacon-push` is redirected there. | -| `BEACON_WEB_IMAGE` | type 2 web host | The image to run, for example `ghcr.io/meshcore-beacon/beacon-web:2.0`. Keep its `X.Y` equal to the server's. | +| `BEACON_WEB_IMAGE` | type 2 web host | The image to run, for example `ghcr.io/meshcore-beacon/beacon-web:2.3`. Keep its `X.Y` equal to the server's. | | `POSTGRES_PASSWORD` | the `db` service | Set in `docker-compose.yml`, not `.env`. It must match the password inside `POSTGRES_DSN`. | ## config.yaml @@ -98,14 +98,14 @@ which ones to read. | `analytics` | How long hourly stats rollups are kept. Default 90 days. They outlive raw packets. | You want longer stats windows. | | `presence` | How observer and packet last-seen timestamps are batched before writing. | Rarely. | | `routes` | How long known routes are kept, with a shorter window for routes seen only a few times, and `reconfirm_rows_per_hour`: how many routes an hour are rechecked for a departed or now-ambiguous hop (default `81000`, run in 5-minute slices; `0` or omitted means the default). | Rarely. | -| `websocket` | Connections per client, upgrade attempts per minute, the live-event send budget per connection, which other sites may open `/ws`, and `require_origin`: whether a client with no `Origin` needs a ticket from `/api/v1/ws-ticket` (off by default; on raises the minimum app version). | The web app is served from a different host than the API, real clients keep getting `lagged` notices from the send budget, or scripts with no `Origin` read the live feed. | +| `websocket` | Connections per client, upgrade attempts per minute, the live-event send budget per connection, which other sites may open `/ws`, and `require_origin`: whether a client with no `Origin` needs a ticket from `/api/v1/ws-ticket` (off by default; BEACON Mobile sends one from 2.1.1, which the built-in minimum app version already covers). | The web app is served from a different host than the API, real clients keep getting `lagged` notices from the send budget, or scripts with no `Origin` read the live feed. | | `nodes` | When a node is marked stale, when it is deleted, the clock-drift threshold, and the optional foreign repeater flag. | You want `possiblyForeign` on repeaters. | | `observers` | Optional deletion of observers not seen for a long time. Off by default. | Rarely. | -| `mobile` | `min_app_version`: the oldest BEACON Mobile release allowed to use this server. Older apps show an update screen. The server has a built-in floor (2.3.0 today); this can raise it, not lower it. | You need users on a newer app release. | -| `web` | `min_web_version`: the oldest Beacon Web release allowed to use this server. Older web builds show a blocking "reload" screen. The server has a built-in floor (2.3.0 today); this can raise it, not lower it. | Your web container lags the server and you want stale browsers to reload. | +| `mobile` | `min_app_version`: the oldest BEACON Mobile release allowed to use this server. Older apps show an update screen. The server has a built-in floor (2.3.4 today); this can raise it, not lower it. | You need users on a newer app release. | +| `web` | `min_web_version`: the oldest Beacon Web release allowed to use this server. Older web builds show a blocking "reload" screen. The server has a built-in floor (2.3.4 today); this can raise it, not lower it. | Your web container lags the server and you want stale browsers to reload. | | `cors` | Browser cross-origin rules for REST: `allowed_origins`, `allowed_methods`, `allowed_headers`, `allow_credentials`, `max_age`. Default allows any origin, read-only methods, no credentials. | You are building an admin UI on another origin, or the web app is on another origin than the API and uses accounts (see [Same site](accounts.md#same-site-and-a-web-app-on-another-origin)). | | `cache` | Redis TTLs per response category. | Rarely. | -| `ingest` | Only store packets from observers in listed countries or continents. | You run a regional instance and want to ignore the rest of the world. | +| `ingest` | Only store packets from observers in listed countries (`allow_countries`), continents (`allow_continents`) or single IATAs (`allow_iatas`). An observer passes if it matches any of them. | You run a regional instance and want to ignore the rest of the world. | | `background` | How often cleanup, route retention and preset rebuilds run. `reconfirm` (default `1h`) sets the route retention run, which also clears stale neighbor edges; the route recheck itself always runs every 5 minutes at `routes.reconfirm_rows_per_hour`. | Rarely. | ### Things that stop startup @@ -117,9 +117,10 @@ cannot honour. These are the ones people hit: - `server.trusted_proxies` entries that are not CIDRs. One host is `10.0.0.5/32`, not `10.0.0.5`. - `packets.retention` or `analytics.rollup_retention` under `24h`, or any negative duration (`observers.delete_after` is the exception: zero or negative turns it off). -- MeshMapper refresh intervals outside their range: `scopes.refresh_interval` and - `repeaters.refresh_interval` 1h to 24h, `zones.refresh_interval` and - `channels.refresh_interval` 24h to 168h. +- A MeshMapper refresh interval outside its range on an import that is enabled: + `scopes.refresh_interval` and `repeaters.refresh_interval` 1h to 24h, `zones.refresh_interval` + and `channels.refresh_interval` 24h to 168h. Also `meshmapper.zones.import_groups: true` + without `meshmapper.zones.enabled`. - A `borderFile` that is missing or not a valid GeoJSON Polygon or MultiPolygon Feature, or `nodes.mark_foreign: true` with no border source at all. - `display.temperature_unit` other than `c` or `f`, or `display.distance_unit` other than `metric` or `imperial`. @@ -136,6 +137,17 @@ cannot honour. These are the ones people hit: `routes.reconfirm_rows_per_hour`. A negative `websocket.max_connections_per_ip` is not caught at startup and rejects every connection instead, so leave it at a positive number. +- A `websocket.allowed_origins` entry that is not `scheme://host[:port]` or + `scheme://*.domain[:port]`, or an `ingest.allow_iatas` entry that is not a three-letter code. +- A value out of range in `readmodels.fill`, `polling`, `accounts`, `mail`, `alerts` or `atlas`. + The sections below give each range. The removed keys `accounts.smtp` and `alerts.delivery` + also stop startup. +- In the environment: `MQTT_BROKER_n_NAME` with characters outside `a-z`, `0-9`, `_` and `-`, two + brokers with the same name, `MQTT_BROKER_n_REBROADCAST` that is not a boolean, or a + `BEACON_SECRET_KEY` that does not decode to 32 bytes while telemetry requests are on. + +The error names the key. See +[Startup fails on a config value](troubleshooting.md#startup-fails-on-a-config-value). ## Database pools and cost guards @@ -278,9 +290,9 @@ upgrade, a repair, a failed verification), those pages answer `503` with `Retry- [Operations](operations.md#read-models-channel-messages-by-site). `readmodels.cmi.enabled: false` is the kill switch, for when you suspect the table serves wrong -pages. It turns those pages off: they answer `503` until the key is `true` again. Pages that do -not read the table (no `iatas`, `scope` with `since`, and `iatas` with `since` or `scope` -across every channel) are not affected. The server still maintains and repairs the table, so +pages. It turns those pages off: they answer `503` until the key is `true` again. That is every +message page with `iatas`, and every page with `scope` and no `since`. Pages that do not read the +table (no `iatas` and no `scope`, or `scope` with `since` and no `iatas`) are not affected. The server still maintains and repairs the table, so setting it back to `true` needs only a restart. Omitting the key means `true`. Like every key in this file, a change needs a restart. @@ -362,8 +374,8 @@ broker that observers publish to directly; nothing about that connection changes ## Repeater polling The `polling` block turns on [Repeater polling](repeater-polling.md). It is off by default. -Zero or omitted values use the default. A value out of range stops startup with an error naming -the key. +Zero or omitted values use the default, except `requests_per_user`, where `0` turns requests off. +A value out of range stops startup with an error naming the key. | Key | Default | Range | What it does | |---|---|---|---| @@ -425,8 +437,7 @@ A third mode, `portal`, exists for the project's own MeshMapper instance. It is other deployments. `local` sends its mail through the top-level `mail` block, which email alerts share. It is checked only -when `accounts.mode` is `local`. An `smtp` block left under `accounts` stops startup with a message saying it -moved. +when `accounts.mode` is `local`. | Key | Default | What it does | |---|---|---| diff --git a/docs/getting-packets-in.md b/docs/getting-packets-in.md index b484268..b575069 100644 --- a/docs/getting-packets-in.md +++ b/docs/getting-packets-in.md @@ -7,7 +7,7 @@ observers publish into, and stores what it hears. No broker, no data. An observer is a MeshCore device, or a bridge next to one, with a network link. It hears a LoRa packet, notes the signal strength, and publishes it to a broker under its own IATA (airport -code) and public key. Beacon connects to the broker over secure WebSocket MQTT, decodes each +code) and public key. Beacon connects to the broker over MQTT on a secure WebSocket (`wss://`), decodes each packet, works out whether it has already seen it through another observer or broker, stores it, and streams it to anyone connected to the web app. @@ -24,7 +24,7 @@ observation per observer. If you run the broker, serve it with an RSA certificate. Most observers are ESP32 devices, and an ESP32 verifies an RSA certificate chain much faster than an ECDSA one. The same goes -for the Beacon site when observers poll repeaters, where it was measured, see +for the Beacon site when observers poll repeaters, which is where it was measured; see [An RSA certificate for the devices](repeater-polling.md#an-rsa-certificate-for-the-devices). A broker can also be a rebroadcaster: one that forwards what other MeshCore brokers carry. Beacon @@ -56,7 +56,7 @@ Observers publish under `meshcore/{IATA}/{observer public key}/`: | `status` | Observer health, position and firmware | Update the observer record | | `neighbors` | The observer's neighbour list | Update neighbour links | | `polling` | An observer's claim: the repeaters it polls and how its polls went | Store it for [repeater polling](repeater-polling.md) and pick a poller per repeater. Ignored unless `polling.enabled` is true. | -| `telemetry` | A repeater reading from an observer | Store it when the observer has a live claim for that repeater. Ignored unless polling is on. | +| `telemetry` | A repeater reading from an observer | Store it when the observer has a live claim for that repeater. With `polling.foreign_claims: check`, a reading with no claim behind it is stored as foreign instead of dropped. Ignored unless polling is on. | | `battery` | The same reading in the older format | Handled like `telemetry`. | | `internal` | Owner details from the broker login | Ignored. A Role 2 account is not sent it anyway. | diff --git a/docs/high-level-design.md b/docs/high-level-design.md index 17e6f29..2a59111 100644 --- a/docs/high-level-design.md +++ b/docs/high-level-design.md @@ -2,7 +2,7 @@ A real-time packet analyzer and observer-of-observers for the MeshCore network. Beacon watches the mesh from above. It passively listens to MQTT brokers, decoding LoRa packets, mapping observer health and node firmware capabilities, and surfacing the network's pulse to web and mobile clients. -This is the single source of truth for the project; sub-documents (deployment, repo layout, frontend specs) reference back to this. +This page is the overview of how Beacon is built and why. The detail lives in the pages it links to: the [API contract](api-contract.md) for every endpoint and field, [Configuration](configuration.md) for every setting, and [Operations](operations.md) for running it. Where a default or a field name here disagrees with those pages or with the code, they are right and this page is behind. --- @@ -33,17 +33,18 @@ This is the single source of truth for the project; sub-documents (deployment, r - **Web client:** React 19 + Vite + TypeScript + Tailwind 4 + TanStack Query/Virtual, MapLibre GL for the map, ECharts for analytics charts, i18next for translations - **Mobile client:** Flutter (native iOS + Android) - **Edge:** Caddy for TLS and reverse proxy -- **Deployment:** Docker Compose with five services (app, db, redis, web, caddy) +- **Deployment:** Docker Compose with five services (app, db, redis, web, caddy), or the same split over two hosts - **Observability:** structured `slog` logs (text or JSON); opt-in, time-boxed CPU profiles written to a private directory ([CPU profiling](profiling.md)). There is no HTTP profiling endpoint. -- **MQTT brokers:** mqtt1.meshcore.ca + mqtt2.meshcore.ca over WSS, Role 2 SUBSCRIBER account auth (see Broker authentication below) +- **MQTT brokers:** one or two MeshCore brokers over WSS, each with a Role 2 SUBSCRIBER account (see Broker authentication below). The public instances read mqtt1.meshcore.ca and mqtt2.meshcore.ca. A broker can also be a rebroadcaster that forwards from other brokers (see [Source brokers](#source-brokers)). +- **Outbound, all optional:** an SMTP server for account and alert mail, the MeshCore Beacon push server for push alerts, and the MeshMapper API for imports ### Flow -The single Go binary connects to both MeshCore MQTT brokers over WSS with SUBSCRIBER credentials. It decodes each incoming packet, dedupes via a content-based packet hash (plus UNIQUE constraint on observations across both brokers), writes to Postgres, updates Redis caches, and fans out to connected WebSocket clients via internal Go channels. +The single Go binary connects to its MQTT brokers (one or two) over WSS with SUBSCRIBER credentials. It decodes each incoming packet, dedupes via a content-based packet hash (plus a UNIQUE constraint that keeps one observation per observer and packet, whichever broker delivers it), writes to Postgres, updates Redis caches, and fans out to connected WebSocket clients via internal Go channels. The same binary serves REST API endpoints for historical queries, hitting Redis first and falling back to Postgres on misses. Caddy terminates TLS and reverse-proxies HTTP and WebSocket traffic to the Go binary. Web and mobile clients connect through Caddy. -Three optional paths are not in the diagram below. With repeater polling on, observer firmware calls the same binary over HTTPS at `/api/guest-polling` for its policy and role, and publishes claims and readings on the brokers alongside packets. With accounts on, clients sign in under `/api/v1/auth` and `/api/v1/me`. With push alerts on, the binary makes outbound calls to the push server. See [Accounts, polling, telemetry requests and alerts](#accounts-polling-telemetry-requests-and-alerts). +Three optional paths are not in the diagram below. With repeater polling on, observer firmware calls the same binary over HTTPS at `/api/guest-polling` for its policy and role, and publishes claims and readings on the brokers alongside packets. With accounts on, clients sign in under `/api/v1/auth` and `/api/v1/me`. With alerts on, the binary sends mail through your SMTP server and makes outbound calls to the push server. See [Accounts, polling, telemetry requests and alerts](#accounts-polling-telemetry-requests-and-alerts). ### Diagram @@ -171,29 +172,34 @@ Long-range LoRa propagation means the same physical node can be heard from multi ### Observer types and detection -An "observer" in this system is any client that authenticates to the MeshCore MQTT broker with its own MeshCore keypair and publishes packets. Observers come in several distinct forms, each with their own quirks: +An "observer" in this system is any client that authenticates to the MeshCore MQTT broker with its own MeshCore keypair and publishes packets. Observers come in several forms: a repeater running MQTT-enabled firmware, a script or bridge connected to a radio over serial, a Home Assistant plugin talking to a companion device, and others. -| Type code | Description | -|---------------------------|--------------------------------------------------------------------------------| -| `meshcore-ha` | Home Assistant plugin talking to a companion device | -| `meshcore-repeater-mqtt` | Repeater running MQTT-enabled firmware (e.g. EastMesh `*_repeater_mqtt` builds)| -| `mctomqtt` | Python script connected to a repeater via serial | -| `meshcore-terminal` | Companion device addressed by a host program | -| `pymc` | Raspberry Pi acting as a repeater, publishing via MQTT | -| `unknown` | Fallback when no identifying signal is present | +The observer's type is free text that the observer reports about itself. Beacon does not keep a fixed list. -Each client identifies itself differently. The detection sources, in priority order: -1. Explicit `client_type` or `software` field in the observer's `/status` payload -2. Recognizable signature in `/status` metadata structure (e.g. specific keys only one client emits) -3. JWT claims at authentication time (if the broker forwards them through) -4. Manual override via the config file +1. A new observer starts as `unknown`. +2. When its `/status` message has a `source` field, the type is that value with any path prefix and version suffix removed: `meshcore-dev/meshcore-ha` becomes `meshcore-ha`, and `meshcoretomqtt:1.1.0` becomes `meshcoretomqtt`. +3. With no `source`, the type is the raw `client_version` string, which is how custom firmware usually shows up. -Observers publish to three subtopics under `meshcore/{IATA}/{pubkey}/`: -- `/packets`: the raw packet stream we use for everything else -- `/status`: periodic observer health (battery, uptime, queue depth, radio stats, software identity) -- `/internal`: PII (owner email/name from JWT). Admin-only on the broker. We use Role 2 so we do not subscribe to `/internal`. +A status message that carries neither leaves the stored type alone, so a known type is never downgraded to `unknown`. The observer list can be filtered by type, and the API returns the distinct types it has seen. -The ingest service subscribes to `meshcore/#` and routes by subtopic. Packets go to the observation pipeline; status messages update the observer row. +Observers publish under `meshcore/{IATA}/{pubkey}/`: + +| Subtopic | What Beacon does with it | +|---|---| +| `packets` | The raw packet stream. Decode, dedupe, store, stream. | +| `status` | Periodic observer health (battery, uptime, queue depth, radio stats, software identity). Updates the observer row and its telemetry history. | +| `neighbors` | The observer's zero-hop neighbour list. Updates `node_neighbors`. | +| `polling` | A repeater polling claim. Handled only with `polling.enabled`. | +| `telemetry`, `battery` | A repeater reading from polling, in the current and the older format. Handled only with `polling.enabled`. | +| `internal` | PII (owner email and name from the broker login). Admin-only on the broker. Beacon uses Role 2 and ignores it. | + +The ingest service subscribes to `meshcore/#` and routes by subtopic. [Getting packets in](getting-packets-in.md#topics) has the operator's view of the same table. + +### Source brokers + +Each broker connection has a name, `mqtt1` and `mqtt2` unless `MQTT_BROKER_n_NAME` sets another. The name is stored on every observation (`source_broker`), on the packet (`brokers`, every broker it arrived through) and per observer (`observer_brokers`), and the clients show it as a badge and a filter. + +A connection marked `MQTT_BROKER_n_REBROADCAST=true` reads a rebroadcaster: a broker that forwards what other MeshCore brokers carry. Beacon then connects with MQTT 5 and reads two user properties the rebroadcaster sets on each message, `source-broker` (a short name) and `source-host` (the host the message first arrived on). The stored broker name becomes the source broker's, so one connection can show many brokers. The source host is what lets repeater polling tell which broker an older observer's claim came through. A message without the properties is still accepted under the connection's own name. See [Behind a rebroadcaster](configuration.md#behind-a-rebroadcaster). ### Node firmware capability detection @@ -230,16 +236,16 @@ We use **`github.com/meshcore-go/meshcore-go`** (MIT, pure Go, v1.0.8) for all p - **`PacketHash()`** computes the canonical content-based dedup hash: SHA256(payload_type + [path_length for traces] + payload) truncated to 8 bytes. Matches the firmware's `Packet::calculatePacketHash`. This is exactly the `packet_hash` column in our `packets` table. - **`PathHashes()`** returns the per-hop hashes already split by hash_size, ready to feed into our path resolution function - **Per-payload-type sub-packages** for all 13 payload types: `Advert`, `TextMessage`, `GroupText`, `Trace`, `Ack`, `MultiPart`, `Path`, `Control`, `Request`, `Response`, `AnonReq`, `GroupData`, `RawCustom` -- **`crypto.go`** provides everything needed for group chat decryption with our `channel_keys` table: `DeriveSharedSecret`, `EncryptThenMAC`, `MACThenDecrypt`, AES-128-ECB +- **`crypto.go`** provides everything needed for group chat decryption with our channel keys: `DeriveSharedSecret`, `EncryptThenMAC`, `MACThenDecrypt`, AES-128-ECB - **`identity.go`** handles Ed25519 keys and signature verification on adverts - **`region.go`** derives MeshCore radio region keys and transport codes - Each source file has a `_test.go` counterpart; the library is well-tested -What our wrapper code still needs to do: +What our wrapper code does around it: - Subscribe to MQTT and pass hex payloads through `PacketFromBytes` - Map the decoded `*Packet` and per-payload structs into our DB rows (packets, packet_observations, nodes, channel_messages) - Apply our capability detection logic from `PathHashes()` against the observer's IATA -- Maintain our channel_keys table and pass keys to `GroupText.Decrypt` when needed +- Keep the channel keys (from `config.yaml` and the MeshMapper import) and pass them to `GroupText.Decrypt` when needed - Compute and store the `packet_hash` returned by `PacketHash()` What we don't need to use from the library: @@ -273,6 +279,11 @@ Reference: `github.com/michaelhart/meshcore-decoder` (TypeScript, used by letsme ## Database schema +The DDL below shows the core tables: the columns, keys and indexes as they stand after migration +`097`, without storage settings. It is a reading aid, not something to run. The schema itself is the +numbered migration files in beacon-server's `db/migrations/`, which the server applies at startup. +The tables left out are listed after the block. + ```sql -- ============================================================ -- IATA CODES (the primary geographic grouping) @@ -286,7 +297,8 @@ CREATE TABLE iata_codes ( display_name TEXT, approx_lat DOUBLE PRECISION, approx_lng DOUBLE PRECISION, - added_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + added_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + border JSONB -- outline for the border map, from a border file or MeshMapper ); -- ============================================================ @@ -308,7 +320,8 @@ CREATE TABLE regions ( center_lng DOUBLE PRECISION, zoom_level INT DEFAULT 8, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + imported BOOLEAN NOT NULL DEFAULT FALSE -- true for a region made from a MeshMapper zone group ); -- Many-to-many association between regions and IATAs @@ -319,29 +332,19 @@ CREATE TABLE region_iatas ( PRIMARY KEY (region_id, iata) ); -CREATE INDEX idx_region_iatas_iata ON region_iatas(iata); - -- ============================================================ -- OBSERVERS -- ============================================================ -- An observer is any client that authenticates to the MeshCore MQTT broker with a --- MeshCore keypair and publishes packets. Observer clients identify themselves with --- a string like "{stream}/{client}:{version}" or "{stream}/{version}". Known types: --- meshcoretomqtt - Python script connected to a repeater via serial --- meshcore - Firmware-native MQTT publisher (the repeater itself) --- meshcore-dev - Same as above but on the dev firmware stream --- meshcore-ha - Home Assistant plugin talking to a companion --- meshcore-packet-capture - Standalone Python packet-capture observer --- meshcore-custom-repeater - Custom repeater builds --- pymc - Raspberry Pi acting as a repeater, publishing via MQTT --- meshcore-terminal - Companion device addressed by a host program --- unknown - Fallback when we can't determine +-- MeshCore keypair and publishes packets. observer_type is free text taken from the +-- observer's /status message (see "Observer types and detection"), for example +-- "meshcoretomqtt" or "meshcore-ha". A new observer starts as "unknown". CREATE TABLE observers ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), public_key BYTEA UNIQUE NOT NULL, display_name TEXT, -- best-effort name from /status or packets - observer_type TEXT, -- one of the codes above; NULL until determined + observer_type TEXT, software_version TEXT, -- version of the observer client (script or native firmware) -- Hardware and MeshCore firmware of the underlying repeater (for non-native observers -- this is the connected device, not the observer process). All from /status. @@ -361,25 +364,29 @@ CREATE TABLE observers ( first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), observation_count BIGINT DEFAULT 0, - metadata JSONB -- raw JWT claims and other auth-time data + metadata JSONB, + region_scope TEXT, -- the observer's own transport scope, from its /neighbors report + last_iata CHAR(3), -- the IATA it last published packets under + last_iata_at TIMESTAMPTZ ); -CREATE INDEX idx_observers_last_seen ON observers(last_seen DESC); -CREATE INDEX idx_observers_pubkey ON observers(public_key); -CREATE INDEX idx_observers_type ON observers(observer_type) WHERE observer_type IS NOT NULL; +CREATE INDEX idx_observers_last_iata ON observers(last_iata) WHERE last_iata IS NOT NULL; -- Which broker(s) we've seen each observer publishing to. -- An observer can be configured to publish to multiple brokers simultaneously. +-- broker_name is the connection's name ("mqtt1", "mqtt2", or MQTT_BROKER_n_NAME), or +-- behind a rebroadcaster the name of the broker the message first arrived on. CREATE TABLE observer_brokers ( observer_id UUID NOT NULL REFERENCES observers(id) ON DELETE CASCADE, - broker_name TEXT NOT NULL, -- "mqtt1", "mqtt2" + broker_name TEXT NOT NULL, first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), last_packet_at TIMESTAMPTZ, -- last actual /packets message via this broker - auth_ok BOOLEAN DEFAULT TRUE, -- false if recent connections failed auth + auth_ok BOOLEAN DEFAULT TRUE, PRIMARY KEY (observer_id, broker_name) ); +-- Not written today; an observer's place is its last_iata. CREATE TABLE observer_locations ( observer_id UUID NOT NULL REFERENCES observers(id) ON DELETE CASCADE, iata CHAR(3) REFERENCES iata_codes(iata), @@ -391,16 +398,16 @@ CREATE TABLE observer_locations ( CREATE INDEX idx_observer_locations_recent ON observer_locations(observer_id, reported_at DESC); --- Time series of observer telemetry, one row per /status message. --- Subject to the same retention policy as packet_observations. +-- Time series of observer telemetry: one row per stored /status snapshot, at most one per +-- telemetry.resolution (default 15m) for each observer. Kept for telemetry.retention. -- Used to graph metrics over time on the observer detail page. CREATE TABLE observer_telemetry ( id BIGSERIAL PRIMARY KEY, observer_id UUID NOT NULL REFERENCES observers(id) ON DELETE CASCADE, reported_at TIMESTAMPTZ NOT NULL, battery_voltage_mv INT, - airtime_tx_secs REAL, - airtime_rx_secs REAL, + airtime_tx_secs REAL, + airtime_rx_secs REAL, noise_floor_db REAL, uptime_seconds BIGINT, queue_length INT, @@ -450,6 +457,7 @@ CREATE TABLE nodes ( -- These map to MeshCore firmware features that landed in known releases. supports_multibyte_paths BOOLEAN NOT NULL DEFAULT FALSE, -- seen in 2 or 3 byte regular packet paths (firmware 1.14.0+) supports_multibyte_traces BOOLEAN NOT NULL DEFAULT FALSE, -- seen in 2 or 4 byte trace paths (firmware 1.11.0+) + default_scope_id INT REFERENCES transport_scopes(id), -- Derived minimum firmware version from the capability flags above. -- Reports the strongest minimum we can prove from direct observation. min_firmware_version TEXT GENERATED ALWAYS AS ( @@ -461,17 +469,16 @@ CREATE TABLE nodes ( ) STORED, first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), - metadata JSONB -- raw appData from advert + radio_freq_mhz REAL, + radio_sf SMALLINT, + radio_bw_khz REAL, + metadata JSONB, -- raw appData from advert + -- How far the node's advert timestamp was from server time, for the newest advert and + -- the one before it. node_clock_drifts keeps the last 16 for the clock alert. + device_clock_drift_seconds BIGINT, + prev_clock_drift_seconds BIGINT ); -CREATE INDEX idx_nodes_type_last_seen ON nodes(node_type, last_seen DESC); -CREATE INDEX idx_nodes_location ON nodes(latitude, longitude) - WHERE latitude IS NOT NULL AND longitude IS NOT NULL; -CREATE INDEX idx_nodes_pubkey ON nodes(public_key); -CREATE INDEX idx_nodes_multibyte_paths ON nodes(supports_multibyte_paths) WHERE supports_multibyte_paths; -CREATE INDEX idx_nodes_multibyte_traces ON nodes(supports_multibyte_traces) WHERE supports_multibyte_traces; -CREATE INDEX idx_nodes_min_firmware ON nodes(min_firmware_version) WHERE min_firmware_version IS NOT NULL; - -- Tracks which IATAs have heard each node. A node can be heard from many IATAs -- (e.g. a Vancouver repeater heard by observers in both YVR and YYJ). CREATE TABLE node_iatas ( @@ -483,7 +490,7 @@ CREATE TABLE node_iatas ( PRIMARY KEY (node_id, iata) ); -CREATE INDEX idx_node_iatas_iata ON node_iatas(iata, last_heard DESC); +CREATE INDEX idx_node_iatas_iata ON node_iatas(iata); -- Pre-computed 4-byte prefix of each node's hash, per IATA they've been heard in. -- The single 4-byte prefix covers all path hash sizes used by MeshCore (1, 2, 3, or 4 bytes). @@ -509,32 +516,47 @@ CREATE INDEX idx_short_ids_p4 ON node_short_ids(iata, prefix_4); CREATE TABLE packets ( packet_hash BYTEA PRIMARY KEY, -- content-based hash from decoder - header_byte SMALLINT NOT NULL, -- raw header byte (VVPPPPRR bit-packed) - payload_type SMALLINT NOT NULL, -- 0x00..0x0F, bits 2-5 of header + payload_type SMALLINT NOT NULL CHECK (payload_type BETWEEN 0 AND 15), -- bits 2-5 of header payload_version SMALLINT NOT NULL, -- bits 6-7 of header - route_type SMALLINT NOT NULL, -- bits 0-1 of header (set by sender) + route_type SMALLINT NOT NULL CHECK (route_type BETWEEN 0 AND 3), -- bits 0-1 of header -- Transport codes (only present for TRANSPORT_FLOOD or TRANSPORT_DIRECT) transport_codes_present BOOLEAN DEFAULT FALSE, region_code INT, -- uint16 LE, optional sub_region_code INT, -- uint16 LE, optional + scope_id INT REFERENCES transport_scopes(id), -- the transport scope the codes matched, if any -- Content origin_pubkey BYTEA, -- if extractable (e.g. from advert payload) raw_payload BYTEA NOT NULL, + raw_header BYTEA NOT NULL, -- the header byte, then the transport codes when present parsed_payload JSONB, -- decoded structured data decrypted BOOLEAN DEFAULT FALSE, channel_hash BYTEA, -- 1-byte channel ID, if group/channel packet + trace_tag BYTEA, -- the trace's tag, if a trace packet first_heard_at TIMESTAMPTZ NOT NULL, last_heard_at TIMESTAMPTZ NOT NULL, - observation_count INT DEFAULT 0 -- denormalized count for UI + observation_count BIGINT NOT NULL DEFAULT 0, -- denormalized count for UI + brokers TEXT[] NOT NULL DEFAULT '{}' -- brokers the packet arrived through; empty for packets stored before this column ); CREATE INDEX idx_packets_first_heard_brin ON packets USING BRIN (first_heard_at); +CREATE INDEX idx_packets_last_heard ON packets(last_heard_at DESC); +CREATE INDEX idx_packets_last_heard_hash ON packets(last_heard_at DESC, packet_hash DESC); CREATE INDEX idx_packets_payload_type ON packets(payload_type, first_heard_at DESC); CREATE INDEX idx_packets_route_type ON packets(route_type, first_heard_at DESC); +CREATE INDEX idx_packets_type_last_heard ON packets(payload_type, route_type, last_heard_at DESC, packet_hash DESC); CREATE INDEX idx_packets_origin ON packets(origin_pubkey, first_heard_at DESC) WHERE origin_pubkey IS NOT NULL; +CREATE INDEX idx_packets_origin_last_heard ON packets(origin_pubkey, last_heard_at DESC) + WHERE origin_pubkey IS NOT NULL; CREATE INDEX idx_packets_channel ON packets(channel_hash, first_heard_at DESC) WHERE channel_hash IS NOT NULL; +CREATE INDEX idx_packets_scope ON packets(scope_id) WHERE scope_id IS NOT NULL; +CREATE INDEX idx_packets_scope_last_heard ON packets(scope_id, last_heard_at DESC, packet_hash DESC) + INCLUDE (payload_type, route_type, first_heard_at) WHERE scope_id IS NOT NULL; +CREATE INDEX idx_packets_trace_tag ON packets(trace_tag) WHERE trace_tag IS NOT NULL; +CREATE INDEX idx_packets_heard_inverted ON packets(first_heard_at) + INCLUDE (last_heard_at, packet_hash, payload_type, route_type, scope_id) + WHERE (first_heard_at > last_heard_at) IS TRUE; -- ============================================================ -- PACKET OBSERVATIONS (per-observer hearings) @@ -561,37 +583,47 @@ CREATE TABLE packet_observations ( bandwidth_khz REAL, coding_rate SMALLINT, -- Origin tracking - source_broker TEXT, -- "mqtt1" or "mqtt2" - -- Full wire-format bytes as received by this observer (header + optional transport - -- codes + path_length_byte + path_bytes + payload). Differs per observation because - -- path bytes accumulate as the packet hops through repeaters. - raw_packet BYTEA NOT NULL, - -- Dedup across both brokers - UNIQUE (packet_hash, observer_id, heard_at) + source_broker TEXT, -- the broker this hearing arrived through + payload_type SMALLINT, -- copy of the packet's type, for per-observer queries + airtime_ms REAL, -- time on air; NULL when the observer never reported usable radio settings + -- One hearing per observer per packet, whichever broker delivers it first + UNIQUE (packet_hash, observer_id) ); -CREATE INDEX idx_observations_heard_brin ON packet_observations USING BRIN (heard_at); +CREATE INDEX idx_observations_heard ON packet_observations(heard_at); CREATE INDEX idx_observations_iata_heard ON packet_observations(iata, heard_at DESC); CREATE INDEX idx_observations_observer ON packet_observations(observer_id, heard_at DESC); CREATE INDEX idx_observations_packet ON packet_observations(packet_hash); +CREATE INDEX idx_observations_adverts ON packet_observations(observer_id, id) WHERE payload_type = 4; +CREATE INDEX idx_observations_route_evidence ON packet_observations + (iata, hash_size, decode(md5(path_bytes), 'hex'), heard_at DESC, id DESC) + WHERE path_bytes IS NOT NULL AND payload_type IS NOT NULL AND payload_type <> 9 AND hop_count >= 2; -- ============================================================ -- CHANNELS AND CHAT MESSAGES (group text) -- ============================================================ +-- A 1-byte channel hash is shared by many channels, so a channel is identified by its +-- hash together with the fingerprint of its key. One row with no fingerprint per hash +-- holds the messages no known key decrypts. CREATE TABLE channels ( - id SERIAL PRIMARY KEY, - channel_hash BYTEA UNIQUE NOT NULL, - name TEXT, - is_hashtag BOOLEAN DEFAULT FALSE, - is_public BOOLEAN DEFAULT FALSE, - key_known BOOLEAN DEFAULT FALSE, - first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), - last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), - message_count BIGINT DEFAULT 0 + id SERIAL PRIMARY KEY, + channel_hash BYTEA NOT NULL, + key_fingerprint BYTEA, + name TEXT, + hashtag TEXT UNIQUE, + is_hashtag BOOLEAN DEFAULT FALSE, + is_public BOOLEAN DEFAULT FALSE, + key_known BOOLEAN DEFAULT FALSE, + first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), + message_count BIGINT NOT NULL DEFAULT 0, + UNIQUE (channel_hash, key_fingerprint) ); -CREATE INDEX idx_channels_last_seen ON channels(last_seen DESC); +CREATE INDEX idx_channels_hash ON channels(channel_hash); +CREATE UNIQUE INDEX idx_channels_hash_no_key ON channels(channel_hash) WHERE key_fingerprint IS NULL; +CREATE INDEX idx_channels_hashtag ON channels(hashtag) WHERE hashtag IS NOT NULL; -- Which IATAs each channel has been heard in, maintained at ingest and -- pruned on the packet retention cutoff. Backs the channel list IATA @@ -604,8 +636,6 @@ CREATE TABLE channel_iatas ( PRIMARY KEY (channel_hash, iata) ); -CREATE INDEX idx_channel_iatas_iata ON channel_iatas(iata, last_heard DESC); - CREATE TABLE trace_iatas ( trace_tag BYTEA NOT NULL, iata CHAR(3) NOT NULL REFERENCES iata_codes(iata) ON DELETE CASCADE, @@ -613,21 +643,23 @@ CREATE TABLE trace_iatas ( PRIMARY KEY (trace_tag, iata) ); -CREATE INDEX idx_trace_iatas_iata ON trace_iatas(iata, last_heard DESC); +CREATE INDEX idx_trace_iatas_iata ON trace_iatas(iata); --- Channel decryption keys, loaded from the server config file on startup. --- Adding or rotating a key requires updating the config and restarting. +-- Not written today. Channel keys are held in memory: the ones in config.yaml are read +-- at startup (adding or rotating one needs a restart) and MeshMapper's are swapped in as +-- they are imported. A channel row keeps only its key's fingerprint. CREATE TABLE channel_keys ( - channel_id INT PRIMARY KEY REFERENCES channels(id) ON DELETE CASCADE, - key_bytes BYTEA NOT NULL, - added_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - added_by TEXT -- "config" or, in the future, an admin user identifier + channel_id INT PRIMARY KEY REFERENCES channels(id) ON DELETE CASCADE, + key_bytes BYTEA NOT NULL, + key_fingerprint BYTEA NOT NULL, + added_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + added_by TEXT ); CREATE TABLE channel_messages ( id BIGSERIAL PRIMARY KEY, channel_id INT NOT NULL REFERENCES channels(id), - packet_hash BYTEA NOT NULL REFERENCES packets(packet_hash), + packet_hash BYTEA NOT NULL REFERENCES packets(packet_hash) ON DELETE CASCADE, sender_name TEXT, -- decrypted, from message body sender_pubkey BYTEA, -- if known/resolvable content TEXT, -- decrypted message body @@ -636,6 +668,8 @@ CREATE TABLE channel_messages ( ); CREATE INDEX idx_channel_messages_channel ON channel_messages(channel_id, sent_at DESC); +CREATE INDEX idx_channel_messages_channel_id ON channel_messages(channel_id, id DESC); +CREATE INDEX idx_channel_messages_sent ON channel_messages(sent_at); CREATE INDEX idx_channel_messages_sent_brin ON channel_messages USING BRIN (sent_at); -- ============================================================ @@ -651,6 +685,19 @@ CREATE INDEX idx_channel_messages_sent_brin ON channel_messages USING BRIN (sent -- Full contract: beacon-server docs/historical-stats.md. ``` +Tables not shown above: + +| Area | Tables | +|---|---| +| Routes and neighbours | `known_routes` (resolved multi-hop paths per IATA), `node_neighbors` (links between nodes, from trace hops and observers' `/neighbors` reports) | +| Traces | `trace_tags` (one summary row per trace tag) | +| Transport scopes | `transport_scopes`, `observer_scopes`, `channel_config_scopes` | +| Read models for region pages | `packet_sites` (one row per packet and IATA that heard it), `channel_message_iatas` (the same for channel messages). See [Operations](operations.md#read-models-packets-by-site). | +| Hourly rollups | The `analytics_hourly_*` tables and their bookkeeping (`analytics_rollup_hours`, `analytics_dirty_hours`, `analytics_state`, `analytics_raw_state`) | +| MeshMapper imports | `meshmapper_scope_catalogues`, `meshmapper_zone_lists`, `meshmapper_zone_boundaries`, `meshmapper_channel_catalogues`, `meshmapper_channel_members`, `meshmapper_repeater_sources`, `meshmapper_repeaters` | +| Housekeeping | `background_state` (positions and watermarks of background jobs), `accounts` (operator records for the admin API, not user accounts) | +| Accounts, polling, requests and alerts | Listed under [Accounts, polling, telemetry requests and alerts](#accounts-polling-telemetry-requests-and-alerts) | + --- ## Operations and configuration @@ -697,12 +744,16 @@ Optional, all under `meshmapper:` and off by default. Refreshes need a MeshMappe `MESHMAPPER_API_KEY`; see [MeshMapper API key](configuration.md#meshmapper-api-key). - `scopes` imports each known IATA's transport scope names from its MeshMapper site - (`get_scopes.php`). Manual `scopes:` stay authoritative. Refresh `1h`–`24h`. + (`get_scopes.php`). Manual `scopes:` stay authoritative. Refresh `1h` to `24h`, default `24h`. - `zones` imports each IATA's boundary (`get_geojson.php`), overriding `iatas.*.borderFile` on the border map and for `nodes.mark_foreign`. `import_groups` turns MeshMapper zone groups into - regions. Refresh `24h`–`168h`. + regions. Refresh `24h` to `168h`, default `24h`. - `channels` imports each IATA's public hashtag channels (`get_channels.php`); each key is checked - against its name before use and history is backfilled when a key first appears. Refresh `24h`–`168h`. + against its name before use and history is backfilled when a key first appears. Refresh `24h` to + `168h`, default `24h`. +- `repeaters` imports the site details MeshMapper admins entered for each repeater + (`get_repeaters.php`: power, hardware, antenna, heights, notes, confirmed scopes), shown on node + detail and matched by full public key. Refresh `1h` to `24h`, default `6h`. Sources are discovered per known IATA from MeshMapper's per-country zone list; there is nothing to list by hand. Imports and ETags persist in Postgres, and a failed refresh keeps the last good data. @@ -710,28 +761,77 @@ Out-of-range intervals fail startup. ### Accounts, polling, telemetry requests and alerts -Added in 2.3.0, all off by default. Each has its own page; this is only how they fit together. +All optional and off by default. They arrived in 2.3.0 and grew through 2.3.4. Each has its own +page; this is only how they fit together. - **[User accounts](accounts.md).** `accounts.mode: local` gives sign-up by email, sessions and - password reset. Routes are under `/api/v1/auth` and `/api/v1/me`. Account mail goes out through the `mail` block. + password reset. Routes are under `/api/v1/auth` and `/api/v1/me`. The web app signs in with a + session cookie; the mobile app opens the server's web sign-in page and gets its own app token + back. Account mail goes out through the `mail` block, and its links use the server's public + address from `DOMAIN` (or `WEB_DOMAIN` when the web app is on another host). - **Atlas sync.** A signed-in user's Atlas is stored on the server and follows the account ([Atlas](atlas.md#sync-to-an-account)). - **[Repeater polling](repeater-polling.md).** Observer firmware asks Beacon for its policy and role over HTTPS (`/api/guest-polling/policy` and `/owners`), publishes a claim of the repeaters it can poll and then the readings, both over MQTT. Beacon elects one poller per repeater every minute and stores the readings. It never talks to a repeater itself. + - *Readings.* A reading carries battery, temperature and the repeater's counters. From 2.3.4 it + also carries whatever sensor channels the repeater sends (humidity, pressure, gas, power + monitors), decoded when the reading is stored into `repeater_readings.sensors`. Node telemetry + returns them as `sensors`, and `/api/v1/info` says so with `features.sensors`. + - *Trust.* Only trusted readings are charted and alerted on: the observer was assigned to the + repeater, and Beacon had itself heard the repeater directly through that observer. + - *Own, foreign and local observers.* By default every claim is treated as this server's own. + With `polling.foreign_claims: check`, a claim is the server's own only when its signed + `poll_url` names this server's `DOMAIN`, or, for older firmware, when a rebroadcaster says it + arrived on one of `polling.mqtt_hosts`. Any other observer is foreign: it is never elected and + never handed a request, but its readings are stored, marked foreign, and shown once Beacon has + heard it receive the repeater directly. An observer that sends readings and no claim at all, as + the firmware's local mode does, is a local poller. Foreign claims live in their own tables so no + election ever sees them. + - *Signatures and limits.* Current firmware signs its claims and readings, and a signed message + that fails the check is dropped. A claim can also report how many repeaters the observer can + hold and how often it polls each. Beacon stores both, and counts the limit when it hands out + requested repeaters. - **[Requested telemetry](telemetry-requests.md).** A signed-in user asks for a repeater to be polled. Beacon hands it to an observer that hears it, with the guest password sealed under `BEACON_SECRET_KEY` and encrypted to that observer. - **[Alerts](alerts.md).** Rules on a user's Atlas radios are evaluated every 5 minutes and sent - every minute, by email and by push. Push goes through the MeshCore Beacon push server, which - forwards to Apple and Google; the Beacon server holds no Apple or Firebase key. - -Tables these add, in migrations `064` to `087` (the DDL above predates them): + every minute, by email and by push. Rules that read telemetry need trusted readings: the + repeater has a polling assignment, or a trusted reading of it under 36 hours old. + `telemetry_stopped` fires when those readings stop arriving. + +#### How push reaches a phone + +Only the app's publisher can send push notifications to BEACON Mobile, so no Beacon server talks +to Apple or Google. Every server sends through the MeshCore Beacon push server +(`https://push.meshcorebeacon.ca`, the [beacon-push](https://github.com/MeshCore-Beacon/beacon-push) +relay), which holds the Apple and Firebase keys. + +1. The operator registers the server with the push server once and gets a Push ID + (`alerts.push.id`) and a Push secret (`BEACON_PUSH_SECRET`). +2. The app reads the push server's address and the Push ID from `/api/v1/info`, gets a push token + from Apple or Google, and registers it with the push server. The push server answers with a + device handle that works for that one Beacon server. +3. The app gives its Beacon server the handle and a 32-byte key it made. Beacon stores both in + `user_devices`, tied to the app session. +4. When an alert fires, Beacon encrypts the notice with that device's key and posts it to the push + server with the handle, in batches of up to 100. The push server forwards it to Apple (APNs) or + Firebase and cannot read it. The app decrypts it and writes the sentence the user sees. +5. The push server reports each message as delivered, to retry, limited, refused, or the handle + gone. Beacon tracks delivery per device (`alert_outbox_devices`), retries push and email + separately, and deletes a device whose handle is gone. + +While push is on, Beacon also answers `GET /.well-known/beacon-push`, which the push server checks +daily to confirm the server's public URL and raise its sending limits. Limits, retries and what +the push server records are in [Alerts](alerts.md#push); the message format is in the +[API contract](api-contract.md#push-delivery). + +Tables these add, in migrations `064` to `097`: | Area | Tables | |---|---| -| Polling | `polling_claims`, `polling_candidates`, `polling_assignments`, `polling_targets`, `polling_observers`, `polling_state`, `polling_other_states`, `polling_admin_stops`, `polling_served_versions`, `repeater_readings` | +| Polling | `polling_claims`, `polling_candidates`, `polling_assignments`, `polling_targets`, `polling_observers`, `polling_state`, `polling_other_states`, `polling_admin_stops`, `polling_served_versions`, `polling_foreign_claims`, `polling_foreign_targets`, `repeater_readings` | | Accounts | `users`, `user_sessions`, `user_tokens`, `portal_states` | | Atlas sync | `user_atlas`, `user_atlas_pins` | | Telemetry requests | `telemetry_requests` | @@ -754,9 +854,11 @@ REDIS_ADDR=... # optional; unset = no cache MQTT_BROKER_1_URL=wss://mqtt1.meshcore.ca:443 MQTT_BROKER_1_USERNAME=... MQTT_BROKER_1_PASSWORD=... -MQTT_BROKER_2_URL=wss://mqtt2.meshcore.ca:443 -MQTT_BROKER_2_USERNAME=... -MQTT_BROKER_2_PASSWORD=... +MQTT_BROKER_1_NAME=... # optional, shown instead of mqtt1 +MQTT_BROKER_1_REBROADCAST=... # optional, true when this broker is a rebroadcaster +MQTT_BROKER_2_URL=... # optional second broker, with the same five variables +DOMAIN=beacon.example.com # the server's public host: mail links and polling.foreign_claims +WEB_DOMAIN=... # optional, the web app's host when it differs from DOMAIN BEACON_API_KEY=... # optional admin bearer key MESHMAPPER_API_KEY=... # optional, for MeshMapper imports BEACON_SECRET_KEY=... # optional, seals guest passwords for telemetry requests @@ -797,7 +899,8 @@ server: trusted_proxies: [172.30.0.0/24] # proxies allowed to set X-Real-IP ``` -The full reference with every key and default is [`app_config/config.yaml.example`](../app_config/config.yaml.example). +Every environment variable is in [Configuration](configuration.md#server-environment-variables). The +full reference with every `config.yaml` key and default is [`app_config/config.yaml.example`](../app_config/config.yaml.example). Invalid values (bad CIDRs, out-of-range MeshMapper intervals, scopes without a configured region, retention under 24h) fail startup rather than being ignored. @@ -842,31 +945,32 @@ Super-regions (the virtual containers in the `regions` table) are defined in the ## Ingestion pipeline -The ingest service subscribes to `meshcore/#` on both brokers and routes incoming messages by subtopic. +The ingest service subscribes to `meshcore/#` on each broker and routes incoming messages by subtopic. A topic whose IATA or observer key is malformed is dropped, and so is one whose IATA falls outside the `ingest` geographic filter when that is set. ### For `/packets` messages -1. Parse MQTT topic to extract `iata` and `publisher_pubkey` -2. Upsert `observers` row (by publisher_pubkey) -3. Upsert `observer_brokers` row for the source broker -4. Upsert `iata_codes` row if this IATA hasn't been seen before -5. Decode the raw hex packet from MQTT JSON: +1. Parse the MQTT topic to extract `iata` and `publisher_pubkey` +2. Decode the raw hex packet from the MQTT JSON: - Parse the bit-packed header (route_type, payload_type, payload_version) - If route_type is TRANSPORT_FLOOD or TRANSPORT_DIRECT, parse the 4-byte transport codes - Parse path_length byte → extract hash_size and hop_count - Read hash_size × hop_count path bytes - The remainder is the payload -6. Compute the content-based packet hash from the payload -7. UPSERT into `packets` ON CONFLICT (packet_hash) DO UPDATE SET last_heard_at, observation_count = observation_count + 1 -8. INSERT into `packet_observations` with the per-observation path data, RSSI, SNR, radio params. ON CONFLICT DO NOTHING using the UNIQUE constraint (handles dual-broker dedup) +3. Upsert the `observers` row (by publisher_pubkey), the `observer_brokers` row for the source broker, and the `iata_codes` row if this IATA hasn't been seen before +4. Compute the content-based packet hash from the payload +5. For TRANSPORT_FLOOD and TRANSPORT_DIRECT packets, match the transport codes against the known transport scopes +6. UPSERT into `packets` ON CONFLICT (packet_hash), bumping `last_heard_at` and adding the broker to `brokers` +7. Take `heard_at` from the observer's timestamp, or server time when it is missing or more than 30 minutes off +8. INSERT into `packet_observations` with the per-observation path data, RSSI, SNR, radio params. ON CONFLICT (packet_hash, observer_id) DO NOTHING, which is the cross-broker dedup 9. **Capability detection:** if the observation INSERT succeeded and `hash_size >= 2`, attempt path resolution against `node_short_ids` for the observer's IATA. If every hop resolves to exactly one node AND no two hops share the same hash prefix, then for each resolved node: - If `payload_type != 0x09` and `hash_size` is 2 or 3: set `supports_multibyte_paths = TRUE` - If `payload_type == 0x09` (trace) and `hash_size` is 2 or 4: set `supports_multibyte_traces = TRUE` Skip silently if the path has duplicate hashes or any ambiguous hops. Never downgrade an existing TRUE. -10. If payload_type is `0x04` (advert), upsert `nodes` with pubkey/name/role/location and update `node_iatas` + `node_short_ids` for the observer's IATA -11. If payload_type is `0x05` (group text), try to decrypt with known channel keys, store in `channel_messages` on success -12. If the observation INSERT actually succeeded (no conflict), fan out to live WebSocket subscribers via internal Go channel +10. A fully resolved multi-hop path is recorded in `known_routes`. For a trace, each pair of consecutive resolved hops also becomes a `node_neighbors` link with the SNR the trace measured +11. If payload_type is `0x04` (advert), upsert `nodes` with pubkey/name/role/location and update `node_iatas` + `node_short_ids` for the observer's IATA +12. If payload_type is `0x05` (group text), try to decrypt with known channel keys, store in `channel_messages` on success +13. If the observation INSERT actually succeeded (no conflict), fan out to live WebSocket subscribers via internal Go channel ### For `/status` messages @@ -876,12 +980,21 @@ The ingest service subscribes to `meshcore/#` on both brokers and routes incomin - `last_status_at` with current time - `battery_level`, `uptime_seconds` if present in the payload - `software_version` if present - - `observer_type` if we can detect it from explicit fields or signature heuristics (never downgrade from known to unknown) - - `display_name` if present and current value is NULL -3. Upsert `observer_brokers` row for the source broker + - `observer_type` from `source`, or `client_version` when there is no `source` (never downgraded from known to unknown) + - `display_name`, hardware model, firmware version and radio settings if present +3. Store a telemetry snapshot in `observer_telemetry`, at most one per `telemetry.resolution` +4. Fan out an `observerStatus` event to live WebSocket subscribers + +### For `/neighbors` messages + +Record the observer's own transport scope, then upsert a `node_neighbors` link for each zero-hop neighbour it reports, when both ends are known nodes. A neighbour missing from a report is not removed, because the report can be cut short. + +### For `/polling`, `/telemetry` and `/battery` messages + +Handled only when `polling.enabled` is true. A `/polling` message is an observer's claim and replaces its previous one. `/telemetry` and `/battery` carry repeater readings, which are checked (observer, claim, timestamps, signature when present) and stored in `repeater_readings`. See [Repeater polling](repeater-polling.md#what-beacon-stores). ### For `/internal` messages -Not subscribed (Role 2 access). +Not handled (Role 2 access does not receive them). --- @@ -965,7 +1078,7 @@ Covers REST endpoints (`/api/v1/`), auth and rate limits, WebSocket protocol (`/ ### Channels - List: `SELECT * FROM channels ORDER BY last_seen DESC` - Per-channel page: paginated `channel_messages` with decrypted content where `key_known`. These are the actual chat messages (payload type 0x05) sent to a channel, distinct from other packet types. -- **Key management:** channel keys are defined in the server config file. Adding or rotating a key requires updating the config and restarting. On startup, the service retroactively decrypts any existing packets that now have a known key. +- **Key management:** channel keys are defined in the server config file, and can also be imported from MeshMapper. Adding or rotating a key in the config requires a restart. After startup, the service decrypts, in the background, any stored packets that now have a known key. ### Nodes List - Three tabs filtered by `node_type`: Repeaters, Room Servers, Companions @@ -974,9 +1087,9 @@ Covers REST endpoints (`/api/v1/`), auth and rate limits, WebSocket protocol (`/ ### Observers List - `SELECT * FROM observers ORDER BY last_seen DESC` with `observer_brokers` joined for broker badges -- Per-observer columns: name, public key (truncated), **type** (with icon: HA, repeater, mctomqtt, terminal, pymc, or unknown), **broker badges** (mqtt1, mqtt2, or both), current IATA, last status time, observation count, last seen +- Per-observer columns: name, public key (truncated), **type** (as the observer reports it, or unknown), **broker badges** (one per broker it publishes through, by broker name), current IATA, last status time, observation count, last seen - Per-observer page: payload type breakdown of their contributions, recent observations, battery and uptime curves from `status_metadata` history (if we capture deltas), software version -- Filter pills: by observer type, by broker (mqtt1-only / mqtt2-only / both), by IATA or super-region +- Filter pills: by observer type, by broker, by IATA or super-region ### Routes - `known_routes`: fully resolved multi-hop paths per IATA, every hop high confidence. Listed by IATA and hop count, searchable between two node hashes, and across IATA boundaries. diff --git a/docs/operations.md b/docs/operations.md index 1ec018a..659c048 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -33,9 +33,9 @@ rotate on its own, so the deployment templates cap every service at three files A compose file of your own without that block does not rotate at all; add it, or set the cap for every container in `/etc/docker/daemon.json`. -Set `log.level` (`debug`, `info`, -`warn`, `error`; default `info`) and `log.format` (`text` or `json`) in `config.yaml`, or -override them with `LOG_LEVEL` and `LOG_FORMAT`. Invalid values stop startup. +Set `log.level` (`debug`, `info`, `warn`, `error`; default `info`) and `log.format` (`text` or +`json`) in `config.yaml`, or override them with `LOG_LEVEL` and `LOG_FORMAT`. Invalid values +stop startup. Every record has a `component`. Ingest records add the broker name; HTTP completion records add the validated client address, route, status and duration. Query strings and WebSocket @@ -53,7 +53,8 @@ docker compose logs -f caddy # the proxy ``` Caddy also writes a JSON access log to `data/Caddy/logs/access.json`, which the fail2ban rules -in [`app_config/fail2ban/`](../app_config/fail2ban/README.md) read. +in [`app_config/fail2ban/`](../app_config/fail2ban/README.md) read. Caddy rolls that file itself, +at 100 MiB, and keeps 20 files. ## Where the data lives @@ -73,17 +74,22 @@ Everything persistent is under `data/` next to `docker-compose.yml`: After every start, once the server listens, Beacon retries every stored channel message it could not decrypt against the configured keys, so a key added to `config.yaml` surfaces its channel's history. Keys a MeshMapper import adds queue their channels on the same background -job. It runs one pass at a time, in batches of 500 packets, paced by -[`readmodels.fill.duty`](#pacing-the-backfills) alone (no `min_pause`), and stops after 30 -minutes, pauses included; whatever it did not reach is retried after the next start. A packet it -has started is finished (within 30 s), so a stop does not leave a message half stored. The log shows `channel message backfill started` -with `packets`, then `channel message backfill done: N previously-undecrypted channel -message(s)` with `decrypted` and `duration` (or a `WARN` that it stopped after 30 minutes, or -`channel message backfill stopped by shutdown`). -Messages it stores are not broadcast over the WebSocket, and their hours are re-rolled for the -historical stats. A packet heard live before the backfill reaches it is decrypted by ingest -instead: its message is stored once either way, its hours are re-rolled too, and, as a live -message, it is broadcast over the WebSocket with its original `sentAt`. +job. + +- **Pace.** It runs one pass at a time, in batches of 500 packets, paced by + [`readmodels.fill.duty`](#pacing-the-backfills) alone (no `min_pause`). +- **Time limit.** A pass stops after 30 minutes, pauses included. Whatever it did not reach is + retried after the next start. A packet it has started is finished (within 30 s), so a stop + does not leave a message half stored. +- **Log.** `channel message backfill started` with `packets`, then + `channel message backfill done: N previously-undecrypted channel message(s)` with `decrypted` + and `duration`. A pass cut short logs a `WARN` that it stopped after 30 minutes, or + `channel message backfill stopped by shutdown`. +- **What clients see.** Messages the backfill stores are not broadcast over the WebSocket, and + their hours are re-rolled for the historical stats. A packet heard live before the backfill + reaches it is decrypted by ingest instead: its message is stored once either way, its hours + are re-rolled too, and, as a live message, it is broadcast over the WebSocket with its + original `sentAt`. ## Stopping the server @@ -116,7 +122,7 @@ if you want more history. | `packets.retention` | `168h` (7 days) | Packets, observations and channel messages | | `analytics.rollup_retention` | `2160h` (90 days) | Hourly stats rollups. Also the longest window the stats endpoints accept | | `telemetry.retention` | `744h` (31 days) | Observer telemetry snapshots | -| `polling.reading_retention` | `744h` (31 days) | Repeater readings from [repeater polling](repeater-polling.md). At least `1h` | +| `polling.reading_retention` | `744h` (31 days) | Repeater readings from [repeater polling](repeater-polling.md). At least `1h`. Readings are never deleted sooner than four times `polling.direct_window` (4 hours by default, 48 hours at most), which the poller checks need | | `routes.retention` | `336h` (14 days) | Known routes, counted from when a route was last seen | | `nodes.delete_after` | `720h` (30 days) | Nodes not heard from | | `observers.delete_after` | off | Observers not heard from. Opt in by setting a duration | @@ -151,10 +157,12 @@ log line. There are no other metrics for these features. | `users_cleanup` | 1 hour | accounts are on | Removes ended sessions, spent or expired links and stale unconfirmed sign-ups | | `polling_election` | 1 minute | polling is on | Picks the poller and standbys for each repeater | | `polling_corroborate` | 5 minutes | polling is on | Counts how many other observers heard each reading's reply | -| `polling_cleanup` | 1 hour | always | Removes claims a day after they were received and readings older than `polling.reading_retention`. It runs with polling off too, so what an earlier run stored still ages out | -| `requests_offline` | 1 hour | telemetry requests are on | Turns off requests for repeaters no observer has heard for `polling.offline_disable_days` | +| `polling_cleanup` | 1 hour | always | Removes claims (foreign ones included) a day after they were received, assignments whose observer no longer claims the repeater, and readings older than `polling.reading_retention`. It runs with polling off too, so what an earlier run stored still ages out | +| `requests_offline` | 1 hour | telemetry requests are on | Turns off requests for repeaters no observer has heard for `polling.offline_disable_days` days, and for repeaters that are themselves observers | | `alerts_eval` | 5 minutes | an alert channel can send | Evaluates the alert rules | -| `alerts_send` | 1 minute | an alert channel can send | Sends queued alert mail and push notices | +| `alerts_send` | 1 minute | an alert channel can send | Sends queued alert mail and push notices. A notice not delivered within 2 hours is dropped | + +None of these jobs run on a [read-only server](configuration.md#read-only-mode). Account mail (confirmation, reset and notice mail) is not a job. A worker sends it as it is queued, and a failure is logged as `mail not sent`. @@ -222,6 +230,13 @@ If you run the [daily plan check](#turning-on-the-daily-check), also confirm its before and after the deploy. Maintainers run the plan checks before every server release; see [Before a release](#before-a-release). +The migration notes in the rest of this section cover `004` to `061`, which 2.1.0 runs when +you upgrade from 2.0.x; skip them if you already run 2.1 or later. Migrations `062` to `097` +(the releases after 2.1.0, up to 2.3.4; there is no `088`) need no pre-build. Almost all of them +create tables or add columns and take seconds. The one index built on a large existing table is `086`, on `packets`; see +[Upgrading to 2.3.0](upgrading.md#upgrading-to-230-from-220). The steps for each release are in +[Upgrading](upgrading.md). + ### How startup migrations wait for locks Each migration statement runs with `lock_timeout = 30s`. When a statement times out on a lock, @@ -248,7 +263,7 @@ Migrations `011` to `024` (the small-table release) are one statement per file: Together they take seconds at boot. Each drop needs a brief lock on its table, so run the check above first and don't start an external `pg_dump` or a long transaction against those four tables during the upgrade; a blocked drop stops startup after about two minutes as -described below, and the next start resumes where it stopped. Afterwards, compact the two +described above, and the next start resumes where it stopped. Afterwards, compact the two tables once; see [Compacting observers and channels](#after-upgrading-compacting-observers-and-channels). Migration `058` sets `fillfactor = 50` on `nodes`. It only changes the table's settings (no @@ -730,13 +745,13 @@ FROM pg_stat_user_tables WHERE relname IN ('observers', 'channels', 'nodes'); ``` Between the two samples, nearly all new updates (`n_tup_hot_upd` growth over `n_tup_upd` -growth) should be HOT; before this release only a few percent were. Sessions holding long +growth) should be HOT; before the small-table release only a few percent were. Sessions holding long snapshots lower it somewhat. **Rollback.** None needed for the rewrite; it changes no data. -Type-filtered node pages (`/nodes` with a node type) are slower in this release on purpose. -They now read the whole `nodes` table like the unfiltered page: about 5-12 ms on a large +Type-filtered node pages (`/nodes` with a node type) are slower since the small-table release, +on purpose. They read the whole `nodes` table like the unfiltered page: about 5-12 ms on a large deployment's 68,000 nodes, against 1.4 ms with the dropped `(node_type, last_seen)` index. That index held `last_seen`, which every node advert rewrites (about 1.1 million times a day on that deployment). In a benchmark of 100,000 `last_seen` updates it added 31 % WAL and 22 % time, more @@ -777,10 +792,9 @@ reads exactly those and keeps the ones heard at a requested site. More, and it r 5,000 messages first, which fills the page for sites heard often; a page that leaves short is read from all the messages sent since then, which is what it asked for. Sender clocks put `sentAt` anywhere, so neither the message order nor a site's range bounds `since` by itself. -While the process does not trust the table, those pages answer `503` with `Retry-After: 30`; -until this release `/messages` with `iatas` and `since` or `scope` ran the previous statement -instead, trusted or not. Pages without `iatas` or `scope` never read the table. Responses are -the same as the previous statements' in every case. +While the process does not trust the table, those pages answer `503` with `Retry-After: 30`. +The other pages (no `iatas` and no `scope`, or `scope` with `since` and no `iatas`) never read +the table and are not affected. Responses are the same as the previous statements' in every case. On a production-size copy (warm): `/messages` with one busy site and a scope it never had went from 241,633 buffers (916 ms) to 6 buffers; a busy site and its busiest scope, five pages, from @@ -843,8 +857,8 @@ complete and the one-time verification has passed. It drops trust: Each restore after a drop logs `read model trusted again: its pages are served from it`. A reconcile that repairs rows logs `cmi reconcile repaired N pair(s): a writer bypassed the read model`. -Something stored messages without recording their sites. On a single server running this -release that should not happen. Running two server versions that both write to one database at +Something stored messages without recording their sites. On a single server that should not +happen. Running two server versions that both write to one database at the same time is not supported; if it happens, the pairs the older one leaves out are repaired within one reconcile interval. @@ -899,20 +913,33 @@ TRUNCATE channel_message_iatas; Then restart the server. It backfills and verifies again as on the first install. A later release will drop `idx_channel_messages_channel` and `idx_channel_messages_sent_brin`. -Run this release for at least a week before upgrading to that one. +Run a release with this read model (2.1.0 or later) for at least a week before upgrading to +that one. ## Read models: packets by site `packet_sites` holds one row for each packet and each site (IATA) that heard it, at that site's latest hearing. Each row also copies the packet's payload type, route type, scope and first hearing. The observation insert writes the row in the same statement, so a stored observation -always has its row. A background reconcile repairs the newest rows every 5 minutes, an hourly -audit refills a random older slice of 500,000 observations (picked by row, so every -observation is as likely to be audited however sparse the old ids are), and a front sweep every 30 seconds keeps the newest -index entries dense. On a large deployment (about 7.4 million rows) it takes about 1.6 GB: -heap 484 MB, primary key 285 MB, `idx_packet_sites_site` 419 MB, `idx_packet_sites_site_type` -353 MB, `idx_packet_sites_site_scope` 53 MB, `idx_packet_sites_late` 4 MB and -`idx_packet_sites_early` (about empty) 8 kB and `idx_packet_sites_site_scope_type` 61 MB. +always has its row. Three background jobs look after it: + +- a reconcile repairs the newest rows every 5 minutes; +- an hourly audit refills a random older slice of 500,000 observations (picked by row, so + every observation is as likely to be audited however sparse the old ids are); +- a front sweep every 30 seconds keeps the newest index entries dense. + +On a large deployment (about 7.4 million rows) the table takes about 1.6 GB: + +| Part | Size | +|---|---:| +| Heap | 484 MB | +| Primary key | 285 MB | +| `idx_packet_sites_site` | 419 MB | +| `idx_packet_sites_site_type` | 353 MB | +| `idx_packet_sites_site_scope_type` | 61 MB | +| `idx_packet_sites_site_scope` | 53 MB | +| `idx_packet_sites_late` | 4 MB | +| `idx_packet_sites_early` (about empty) | 8 kB | While the server process trusts the table, `/packets` pages with `iatas`, `iata`, `region` or `regionId` (region pages) read it: @@ -982,7 +1009,7 @@ On the first start the server fills the table in the background: `packet_sites backfill progress` line with `ids_done`, `ids_remaining`, `observations_done`, `observations_remaining` and `eta`, then `packet_sites backfill complete`. The observation counts are the planner's estimates from - the table statistics, and `eta` follows them, so it no longer counts empty ids as work. + the table statistics, and `eta` follows them, so empty ids do not count as work. On a large deployment (29.4 million observations over about 766 million ids) that is about 60 slices; expect roughly twice the fill work, about 10 to 40 minutes, longer on a slow disk or a lower `duty`, and a few GB of WAL. @@ -1032,7 +1059,7 @@ complete and the one-time verification has passed. It drops trust: Each restore after a drop logs `read model trusted again: its pages are served from it`. -On a single server running this release, repairs should not happen. Running two server versions +On a single server, repairs should not happen. Running two server versions that both write to one database at the same time is not supported; if it happens, the rows the older one leaves out are repaired within one reconcile interval, and trust returns two clean reconciles later. @@ -1108,7 +1135,7 @@ Three page families are served only from data the server prepares, and answer `5 | Pages | Ready when | Kill switch | |---|---|---| | `/packets` with `iatas`, `iata`, `region` or `regionId` | this process trusts `packet_sites` | `readmodels.packet_sites.enabled: false` | -| `/channels/{id}/messages` and `/messages` with `iatas`, or with `scope` and no `since` (not `/messages` with `iatas` and `since` or `scope`) | this process trusts `channel_message_iatas` | `readmodels.cmi.enabled: false` | +| `/channels/{id}/messages` and `/messages` with `iatas` (with or without `since` or `scope`), or with `scope` and no `since` | this process trusts `channel_message_iatas` | `readmodels.cmi.enabled: false` | | `/observers/{id}/adverts` | the [payload-type backfill](#after-upgrading-observation-payload-types) is done | none | A kill switch set to `false` keeps those pages off (`503`) until it is set back. Every other @@ -1139,7 +1166,7 @@ disk: on an 8 vCPU, 3.8 GB RAM test server with a rotational disk, the first `pa drove I/O pressure to `full avg10=78%` (`/proc/pressure/io`) and the whole machine stalled twice, sshd and journald included, until it was rebooted. -Each fill now paces itself by duty cycle. After each slice or batch it sleeps +Each fill paces itself by duty cycle. After each slice or batch it sleeps `max(min_pause, elapsed × (1 − duty) / duty)`, where `elapsed` is how long that slice took, so it is busy at most `duty` of the time. A slow disk makes each slice slower, which stretches the pauses on its own. Pacing changes only when the fills run: they write the same rows, the @@ -1185,37 +1212,45 @@ Region `/packets` pages with a window, scopes or types, and `/messages` pages wi `/messages` with `since`, at most the messages sent since then. The worst case is a quiet site with `since` near the oldest retained message: it reads every message sent since then, which for an old `since` is effectively the whole message history. On a production-size copy (196,000 -messages) that took 2,907 buffers and 148 ms. Until this release a region page whose bounded reads ran out of budget (a sparse filter such as -a narrow window, an `until` well in the past, or rare payload types over busy sites), and -`/messages` with `iatas` and `since` or `scope`, ran the previous release's statements on a -two-connection `api_slow` pool with a 120 s statement limit. That pool and its -`database.slow_pool_size` key are gone; those pages run on the pool their plan class picks -(`api_custom`, 35 s; `api_legacy` under the `single` layout), like every other page. - -A region page with a window seeks from it. Its rows are first heard in `[since, until]`, so -almost all of them were heard at a site within 30 minutes of that: each site's range is read -from `until` + 30 minutes (or the page cursor, when lower) down to `since` − 30 minutes, and -stops at the page. Two partial indexes hold the only rows that can lie outside those bounds: -`idx_packet_sites_late`, the rows heard at a site more than 30 minutes after their packet was -first heard (a re-hearing hours or days later; about 0.8 % of the rows), and -`idx_packet_sites_early`, the rows heard more than 30 minutes before it (ingest clamps hearing -times to 30 minutes of its own clock, so it stays about empty). A page reads about its own rows, -the 30 minutes above `until` and the late rows above that; a sparse filter reads at most its -window. Scoped pages do the same per site and scope. With a type filter, each site's (or site and -scope's) range is read per (payload type, route type) pair instead, on `idx_packet_sites_site_type` -or `idx_packet_sites_site_scope_type`, so a rare type reads at most a page per pair: a page costs -at most the pairs times its size, however sparse the filter. That holds up to 4,096 ranges (sites -times scopes times type pairs; a region page with up to 8 pairs is always under it). Above it the -page reads each site or site-and-scope range with the types as a filter, as an untyped page does: -cheap while the filter is dense, but a sparse filter then reads each range down to the window. -Only requests naming thousands of combinations get there; the worst measured, every known site -(562) with every scope (1,491) and one rare payload type, took 2.5 million buffers and 2.1 s -without a window and 5.0 million buffers and 3.0 s with `until` a day back, on a warm -production-size copy, nearly all of it probing the 838,000 mostly empty site-and-scope ranges. -Pages are full until the last, and the -rows, their order and `nextPageCursor` are those of the observations; where the previous -statement had ended a page short at its scan floor, the new page is full and the walk returns -the same rows in the same order. +messages) that took 2,907 buffers and 148 ms. + +These pages run on the pool their plan class picks (`api_custom`, 35 s; `api_legacy` under the +`single` layout), like every other page. The 2.1 development builds ran the sparse ones (a +narrow window, an `until` well in the past, rare payload types over busy sites, and `/messages` +with `iatas` and `since` or `scope`) on a separate `api_slow` pool with a 120 s statement +limit. That pool and its `database.slow_pool_size` key are gone. + +**A window.** A region page with a window seeks from it. Its rows are first heard in +`[since, until]`, so almost all of them were heard at a site within 30 minutes of that: each +site's range is read from `until` + 30 minutes (or the page cursor, when lower) down to +`since` − 30 minutes, and stops at the page. Two partial indexes hold the only rows that can lie +outside those bounds: + +- `idx_packet_sites_late`: the rows heard at a site more than 30 minutes after their packet was + first heard (a re-hearing hours or days later; about 0.8 % of the rows). +- `idx_packet_sites_early`: the rows heard more than 30 minutes before it. Ingest clamps + hearing times to 30 minutes of its own clock, so it stays about empty. + +A page reads about its own rows, the 30 minutes above `until` and the late rows above that; a +sparse filter reads at most its window. Scoped pages do the same per site and scope. + +**A type filter.** Each site's (or site and scope's) range is read per (payload type, route +type) pair instead, on `idx_packet_sites_site_type` or `idx_packet_sites_site_scope_type`, so a +rare type reads at most a page per pair: a page costs at most the pairs times its size, however +sparse the filter. + +**Very large requests.** That holds up to 4,096 ranges (sites times scopes times type pairs; a +region page with up to 8 pairs is always under it). Above it the page reads each site or +site-and-scope range with the types as a filter, as an untyped page does: cheap while the +filter is dense, but a sparse filter then reads each range down to the window. Only requests +naming thousands of combinations get there. The worst measured, every known site (562) with +every scope (1,491) and one rare payload type, took 2.5 million buffers and 2.1 s without a +window and 5.0 million buffers and 3.0 s with `until` a day back, on a warm production-size +copy, nearly all of it probing the 838,000 mostly empty site-and-scope ranges. + +**Results.** Pages are full until the last, and the rows, their order and `nextPageCursor` are +those of the observations. Where the previous statement had ended a page short at its scan +floor, the new page is full and the walk returns the same rows in the same order. Measured on a copy of a large production database (29.4 million observations; warm; every region and message statement a request runs, page by page): @@ -1764,8 +1799,8 @@ scope's lookup becomes two full scans of the scope rollup table. No older image needs the six indexes for its plans; rebuilding them after a rollback is optional. -Migration `053` drops `known_routes.last_reconfirmed_at`. No statement of this release reads -it: route reconfirm stopped stamping it and its index went in earlier releases. The old values +Migration `053` drops `known_routes.last_reconfirmed_at`. No statement reads it: route +reconfirm stopped stamping it and its index went in earlier releases. The old values are gone for good (no client ever saw them). Every older image needs the column back before it starts, because its route evidence statement lists it and 2.0.7's reconfirm writes it: @@ -1810,7 +1845,7 @@ databases: | Tier | Database | How it plans | Checks | Who runs it | |---|---|---|---|---| -| `fixture` | A synthetic database built through the migrations | Plain `EXPLAIN` | Plan shapes, against the committed `baseline/fixture` | CI, on every server pull request | +| `fixture` | A synthetic database built through the migrations | Plain `EXPLAIN` | Plan shapes, against the committed `baseline/fixture` | CI, on every push to the server's `dev` and `main` and on every pull request | | `local` | A copy of a large production database, or a restored dump | `EXPLAIN (ANALYZE, BUFFERS)`, read-only | Plan shapes and budgets, against your own `baseline/local` | Maintainers, before a release | | `prod` | A live production database | Plain `EXPLAIN`, read-only, 5 s per plan | Plan shapes only, no baseline | The server's [daily check](#turning-on-the-daily-check), or by hand through psql | @@ -1837,7 +1872,8 @@ results to `planguard-out/`. ### Fixture tier -CI builds the fixture and runs this tier on every pull request. To run it yourself you need an +CI builds the fixture and runs this tier on every push to `dev` and `main` and on every pull +request. To run it yourself you need an empty database with C collation on PostgreSQL 16 (CI pins 16.15): ```sql diff --git a/docs/profiling.md b/docs/profiling.md index a17477d..5d6f5ff 100644 --- a/docs/profiling.md +++ b/docs/profiling.md @@ -7,7 +7,7 @@ recorder with a warning without affecting ingest. ## Enable a session Create a dedicated `0700` directory writable by the container user, mount it, and set both -variables: +variables. The directory path must be absolute: ```yaml services: @@ -21,7 +21,9 @@ services: - The deadline is RFC 3339, at most 72 hours ahead. It survives restarts and is inactive once past. Don't generate a fresh deadline on every start. -- Changing either setting needs a restart. +- Changing either setting needs a restart. A setting Beacon cannot use (one variable without + the other, a deadline it cannot parse or more than 72 hours ahead, a directory that is not + private) logs `CPU profiling unavailable` at startup and the server runs without profiling. - Start with a deadline about a minute out, and compare process CPU, packet freshness, queue drops and database timeouts with an unprofiled period before running a longer session. - One Beacon process per directory. Keep it out of web roots, public backups and source @@ -38,16 +40,16 @@ services: - Background task stacks carry a `task` label. - Shutdown or the deadline ends the active sample early and saves it. -Limits: 8 MiB per profile; 256 MiB and 512 files per directory, counting metadata, leftovers -and unrelated regular files (subdirectories are ignored). The recorder reserves room for a -full capture first and stops at a limit. Nothing is deleted automatically. Files are `0600`; +Limits: 8 MiB per profile; 256 MiB and 512 entries per directory, counting metadata, leftovers +and unrelated files (a subdirectory counts as one entry; its contents and size do not). The +recorder reserves room for a full capture first and stops at a limit. Nothing is deleted automatically. Files are `0600`; a `.partial` file is an interrupted capture. ## Reading the output Each `.pprof` has a `.pprof.json` sidecar with UTC start and end, the trigger, Go version, -process CPU counters, goroutine count, and database-pool counters before and after (pool -values are cumulative, so subtract). No SQL text or credentials. +process CPU counters, goroutine count, and counters of the maintenance database pool before and +after (the acquire counts and wait time are cumulative, so subtract). No SQL text or credentials. Copy completed files off the host privately, noting the image revision and digest. Then: diff --git a/docs/releases.md b/docs/releases.md index 4166081..6e2f456 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -3,7 +3,11 @@ ## Version numbers From 2.0.0, beacon-server and beacon-web share the same major and minor version. Patch numbers -move on their own, so server 2.0.3 runs with web 2.0.1. Keep both on the same `X.Y`. +move on their own: server 2.3.3 shipped with web 2.3.2. Keep both on the same `X.Y`. + +A server release can raise the oldest Beacon Web and BEACON Mobile versions it accepts, as 2.3.4 +does. Its entry in [Upgrading](upgrading.md) says so; upgrade the web container with the server +then. The current minimums are `minWebVersion` and `minAppVersion` at `GET /api/v1/info`. The `/api/v1` in request paths is the API contract version. It does not change with releases; see the [API contract](api-contract.md#versioning). @@ -20,7 +24,7 @@ Both images live on GitHub Container Registry and are public, so no `docker logi | tag `vX.Y.Z` | `X.Y.Z`, `X.Y`, `sha-` | `latest` is the newest release on `main`. To decide for yourself when to upgrade, pin both -images to the same release line (`:2.0`) or an exact release (`:2.0.0`). `dev` follows the +images to the same release line (`:2.3`) or an exact release (`:2.3.4`). `dev` follows the development branch and can break between pushes. Prerelease tags (`v2.1.0-rc1`) get `2.1.0-rc1` but not `2.1`. @@ -38,7 +42,7 @@ signed. The flow is the same in both repos; only the version bump differs. with `swag init -g cmd/beacon/main.go -o docs --parseInternal --parseDependency`. - beacon-web: `version` in `package.json`. - Commit as `chore: bump version to vX.Y.Z`. + Commit as `chore: bump version to X.Y.Z`. 3. Open a PR from `dev` into `main` titled `Release vX.Y.Z` and merge it with **Create a merge commit**. `main` only accepts merge commits, so `dev`'s own commits land on `main` and the next release PR lists only what is new. diff --git a/docs/repeater-polling.md b/docs/repeater-polling.md index 5671a43..a3416e5 100644 --- a/docs/repeater-polling.md +++ b/docs/repeater-polling.md @@ -1,14 +1,29 @@ # Repeater polling -Some observers can ask nearby repeaters for their battery, uptime, noise floor and packet -counters, and publish the answers. Beacon decides which observer asks which repeater, so two -observers that both hear a repeater do not both spend airtime on it, and stores the readings. -Polling is off by default. - -This page is for an operator who runs Beacon and for someone who owns an observer. Beacon only -coordinates and stores. It does not talk to repeaters itself. Users can also ask for a repeater to be polled that no owner set up, see -[Requested telemetry](telemetry-requests.md). See [Seeing the readings](#seeing-the-readings) -for where the readings show up. +A repeater does not send its telemetry to Beacon. Its battery, uptime, noise floor, packet +counters and sensor readings (temperature, humidity, pressure and so on) reach Beacon only when +an observer polls it: the observer asks the repeater over the radio and publishes the answer to +MQTT, where Beacon reads and stores it. Beacon never talks to a repeater itself. Polling is off +by default. + +An observer polls a repeater for one of three reasons: + +- **Its owner set the repeater as a target, and Beacon assigned it.** Beacon decides which + observer asks which repeater, so two observers that both hear a repeater do not both spend + airtime on it. This page describes that. +- **A user requested it.** A signed-in user asks for a repeater no owner set up, and Beacon hands + it to an observer that accepts requests. See [Requested telemetry](telemetry-requests.md). +- **On its own.** The observer runs in the firmware's local mode, or follows another server, and + its readings arrive on a broker Beacon reads. Beacon does not direct it. Set + `polling.foreign_claims: check` so Beacon tells such an observer from its own and keeps the + readings of one that sends no claim. See [Foreign observers](#foreign-observers). + +A repeater that no observer polls has no telemetry in Beacon: no charts, no Telemetry tab, no +sensor tiles and no telemetry alerts. A repeater that is also an observer is the exception: it +reports its own status over MQTT, so Beacon does not have it polled. + +This page is for an operator who runs Beacon and for someone who owns an observer. See +[Seeing the readings](#seeing-the-readings) for where the readings show up. ## How it works @@ -18,11 +33,12 @@ for where the readings show up. answer (`GET /api/guest-polling/owners`). Until it has a policy it neither polls nor reports. 3. The observer publishes a claim to the MQTT broker, listing its targets and how its last polls went. -4. Every minute Beacon ranks the observers that claimed each repeater. Observers that Beacon saw hear - the repeater's zero-hop adverts come first, by mean SNR and then by number of adverts. This is - advert evidence. It counts adverts from the last 7 days (`polling.evidence_window`). Observers without evidence come after, by the signal they claim. - One observer is the poller. The others are standbys. With `polling.authority: approved` only - observers you approved take part (see [Trust](#trust)). +4. Every minute Beacon ranks the observers that claimed each repeater. Observers that Beacon saw + hear the repeater's zero-hop adverts come first, by mean SNR and then by number of adverts. + This is advert evidence. It counts adverts from the last 7 days (`polling.evidence_window`). + Observers without evidence come after, by the signal they claim. One observer is the poller. + The others are standbys. With `polling.authority: approved` only observers you approved take + part (see [Trust](#trust)). 5. The observer reads its role from the owners answer. The poller asks the repeater when the newest reading is older than the poll window. A standby waits the window plus one grace period for each rank, so it only polls if the poller has not. @@ -224,21 +240,26 @@ fails that check. ## Seeing the readings With polling enabled, a repeater's or room server's detail view in Beacon Web and in the mobile -app shows charts of its readings. An Atlas card for a repeater that is polled, or that has -readings from the last 30 days, gets a Telemetry tab with four tiles, see -[Atlas](atlas.md#the-tab-a-card-opens-on). With polling off, none of them appear. Beacon stores -and shows readings for room servers too, but the current polling firmware polls repeaters only. +app shows charts of its readings, with one chart for each sensor channel the repeater sends. An +Atlas card for a repeater that is polled, or that has readings from the last 30 days, gets a +Telemetry tab with four tiles, see [Atlas](atlas.md#the-tab-a-card-opens-on). With polling off, +none of them appear. Beacon stores and shows readings for room servers too, but the current +polling firmware polls repeaters only. Only trusted readings are charted. A reading is trusted when its observer was assigned to the repeater and Beacon had itself heard the repeater directly through that observer when the reading was stored. A foreign observer is never assigned, so its reading is trusted on the advert evidence alone (and, with `authority: approved`, your approval). Readings from any other observer are kept -but left out of the charts. To see them, -call the API with `include=untrusted`, for example +but left out of the charts. To see them, call the API with `include=untrusted`, for example `/api/v1/nodes/{nodeId}/telemetry?range=168h&include=untrusted`. The answer also says how many readings it left out. See the [API contract](api-contract.md#node-telemetry). -A Poller tag means a stored claim exists for that observer, whether or not it is assigned a repeater. The hourly cleanup removes a claim about a day after the last one received, and the tag goes with it. Claims from a blocked observer are not stored. An observer blocked after claiming keeps the tag until its claim is cleaned up. With polling off no new claims are stored, so existing tags clear within about a day. The API carries it as `isPoller` on nodes, and `GET /nodes` takes `poller=true|false`. +An observer's node carries a Poller tag while Beacon holds a claim from it, whether or not it is +assigned a repeater. The hourly cleanup removes a claim about a day after the last one was +received, and the tag goes with it. Claims from a blocked observer are not stored. An observer +blocked after claiming keeps the tag until its claim is cleaned up. With polling off no new +claims are stored, so existing tags clear within about a day. The API carries the tag as +`isPoller` on nodes, and `GET /nodes` takes `poller=true|false`. An observer that sends readings and no claim, as the firmware's local mode does, has the Poller tag marked Local (`isLocalPoller` in the API, from server 2.3.3). It keeps the tag while one of its @@ -247,9 +268,14 @@ for. It has no slots or login state to show, because those come from a claim. Wh from it, it becomes one of your own pollers or a foreign one instead. This needs `polling.foreign_claims: check`, since a reading with no claim behind it is only stored then. -An observer whose claim is foreign has the Poller tag marked Foreign (`isForeignPoller` in the API). A -repeater's telemetry is labelled as a foreign source when all of its readings came from foreign -observers, and as including foreign readings when some did. +An observer whose claim is foreign has the Poller tag marked Foreign (`isForeignPoller` in the +API). + +A repeater's telemetry is labelled "Foreign source" when all of the readings shown came from +observers this server does not manage, and "Includes foreign readings" when some did. When those +observers all run in local mode the label says Local instead of Foreign. The node's Telemetry +panel shows the label beside the range buttons. An Atlas card shows it in the Telemetry tab's +bottom row, which always says when the last reading was. An observer with the Poller tag also has a Poller view on its node, beside Node and Observer, in Beacon Web and the mobile app. It shows: @@ -268,7 +294,10 @@ Anyone who can open the node sees this, including which repeaters are requested Atlas card for the node has a Poller tab, see [Atlas](atlas.md#the-tab-a-card-opens-on). The route is `GET /nodes/{nodeId}/poller`, see the [API contract](api-contract.md#node-poller). -A gap in a chart means there is no usable value for that series in that bucket. The cause can be the poll cadence (status values arrive every few hours), a field the repeater does not report, a counter that was inconsistent and was dropped, or a missed poll. It does not mean the repeater was down. +A gap in a chart means there is no usable value for that series in that bucket. The cause can +be the poll cadence (status values arrive every few hours), a field the repeater does not +report, a counter that was inconsistent and was dropped, or a missed poll. It does not mean the +repeater was down. ## Pause, exclude and block diff --git a/docs/reverse-proxy.md b/docs/reverse-proxy.md index d021d49..bedb492 100644 --- a/docs/reverse-proxy.md +++ b/docs/reverse-proxy.md @@ -161,16 +161,19 @@ is accepted and then closed with code `1013` (try again later) before `hello`. A upgrade attempts per IP per minute: beyond that the handshake gets `429` with `Retry-After: 60`. Both are set under `websocket:` in `config.yaml`. -Behind a reverse proxy all of these only work with `server.trusted_proxies` set, or every -visitor counts as the proxy's IP. Without it every visitor shares the proxy's budget and the -site gets 429s under normal load. Beacon logs a warning at startup when limits are on and no +Behind a reverse proxy all of these only work with `server.trusted_proxies` set. Without it +every visitor counts as the proxy's IP and shares one budget, and the site gets 429s under +normal load. Beacon logs a warning at startup when limits are on and no proxy is trusted, and once at runtime when a request carries forwarding headers it is ignoring. ## Split origins When the web app and the API are on different hosts, browsers may only open `/ws` from the page's own host unless the web origin is listed in `websocket.allowed_origins` -(`https://*.example.com` covers every subdomain). REST CORS allows any origin by default. +(`https://*.example.com` covers every subdomain). REST CORS allows any origin by default, which +is enough for the public read-only API. With [user accounts](accounts.md) on, signed-in requests +from the other origin also need the CORS settings in +[Same site, and a web app on another origin](accounts.md#same-site-and-a-web-app-on-another-origin). ## Abuse controls diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 27e421c..8545c6e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -187,6 +187,6 @@ See [Backup and export](backup-export.md#requirements-and-limits). ## I changed a `VITE_*` value and nothing changed -Run `docker compose up -d web` (`docker compose up -d beacon-web` in the split deployment). The web container writes the values to `/config.js` when it -starts, so an edited `.env` does nothing until the container is recreated. Then hard-refresh -the page. +Run `docker compose up -d web` (`docker compose up -d beacon-web` in the split deployment). +The web container writes the values to `/config.js` when it starts, so an edited `.env` does +nothing until the container is recreated. Then hard-refresh the page. diff --git a/docs/upgrading.md b/docs/upgrading.md index 13d5b74..a3832e0 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -65,7 +65,8 @@ Other changes to review: `/api/v1/*` (IPv6 clients share a /64), answered with `429` and `Retry-After`. Behind a proxy, set `server.trusted_proxies` and have the proxy send `X-Real-IP` (see [Reverse proxy](reverse-proxy.md)); `X-Forwarded-For` and `True-Client-IP` are not trusted. - Tune or turn it off under `ratelimit:`. + Tune or turn it off under `ratelimit:`. Later builds default to 600; see + [REST rate limit raised to 600](#rest-rate-limit-raised-to-600). - **WebSocket upgrades are rate limited** to `websocket.max_connects_per_minute` (default 10) per client IP, on top of `max_connections_per_ip` (default 5). Only the page's own host may open `/ws` unless you list other origins in `websocket.allowed_origins`, for example when the @@ -170,8 +171,9 @@ What it adds: monitors) are decoded when a reading is stored and shown as charts and Atlas tiles. Readings stored before the upgrade carry none; nothing is filled in afterwards. See [Sensor channels](api-contract.md#sensor-channels). -- Alerts on repeaters this server does not assign a poller to, and a `telemetry_stopped` alert. See - [Alerts](alerts.md). +- Telemetry alerts on a repeater this server assigns no poller to, as long as a trusted reading of + it is under 36 hours old, and a new `telemetry_stopped` alert for when readings stop arriving. +- `gone_quiet` offers 3, 6, 12, 24 or 48 hours on every radio. See [Alert kinds](alerts.md#alert-kinds). ## Upgrading to 2.3.3 from 2.3.2 @@ -256,7 +258,8 @@ table, `078`, which copies one drift row per node into a new table, and `084` an only alert tables that are still empty on a 2.2.0 database. `086` is the only index built on an existing table: it builds an index on `packets` (`origin_pubkey`, -`last_heard_at`) with `CONCURRENTLY`, so ingest keeps running while it builds. It took about two +`last_heard_at`). Migrations run before the server starts ingesting or listening, so allow for +that pause. It took about two seconds on a test table of 4 million packets and added about a quarter of the table's size; allow more time and disk on a larger database. @@ -607,5 +610,11 @@ Beacon reads `config.yaml` once at startup. After editing it, run For environment changes in `.env`, use `docker compose up -d --force-recreate app` instead. A container restart reuses its old environment. -The one runtime-only setting is CORS origins: `PUT /api/v1/admin/config` changes them without a -restart, and nothing is written to the file, so a restart reloads whatever the file says. +Three things change without a restart, through the admin API: + +- CORS origins and the enforced guard families (`guards.enforce`), with + `PUT /api/v1/admin/config`. Nothing is written to the file, so a restart reloads whatever the + file says. Make the same change in `config.yaml` to keep it. +- The polling pause, exclusions and blocked observers, with `/api/v1/admin/polling`. These are + stored in the database and survive a restart. See + [Pause, exclude and block](repeater-polling.md#pause-exclude-and-block).