Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/beacon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ import (
var version = "dev"

// @title MeshCore Beacon API
// @version 2.3.3
// @version 2.3.4
// @description MeshCore network observation backend. Ingests LoRa packets from MQTT brokers, stores in PostgreSQL, and streams live events via WebSocket.
// @description REST requests share a configurable per-client rate limit (default 600/minute and a 600-request one-second burst cap). Exceeded limits return HTTP 429 with error.code=rate_limited and a Retry-After header in seconds. CORS preflights and WebSocket upgrades do not consume this API budget.
// @description WebSocket upgrade attempts at /ws have a configurable per-client limit (default 10/minute, including failed handshakes). Rate exhaustion returns HTTP 429 with Retry-After before upgrade. An accepted socket exceeding the concurrent cap closes with code 1013 before hello; established connections remain open.
Expand Down
4 changes: 2 additions & 2 deletions config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -428,9 +428,9 @@ cache:
# can raise it, never lower it. Strict X.Y.Z (no v, no suffix); anything else
# prevents startup. Default: empty, the built-in floor only.
#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

# Repeater polling: observers ask nearby repeaters for battery, temperature and counters, and
# Beacon picks which observer polls which repeater and stores the readings. Off by default.
Expand Down
7 changes: 4 additions & 3 deletions db/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ type radioCaps struct {
func loadRadioCaps(ctx context.Context, q sqlc.Querier, keys [][]byte, now time.Time, pollingOn bool) (radioCaps, error) {
since := ts(now.Add(-alerts.DataWindow * time.Second))
fresh := ts(now.Add(-alerts.ObserverFresh))
nodeFresh := ts(now.Add(-alerts.NodeFresh))
rc := radioCaps{node: map[string]sqlc.AlertNodeCapsRow{}, observer: map[string]sqlc.AlertObserverCapsRow{}}
nodes, err := q.AlertNodeCaps(ctx, sqlc.AlertNodeCapsParams{Since: since, Keys: keys, PollingEnabled: pollingOn})
nodes, err := q.AlertNodeCaps(ctx, sqlc.AlertNodeCapsParams{Since: since, FreshSince: nodeFresh, Keys: keys, PollingEnabled: pollingOn})
if err != nil {
return rc, err
}
Expand All @@ -74,11 +75,11 @@ func (rc radioCaps) pick(key, want string) (id uuid.UUID, kind string, c alerts.
n, isNode := rc.node[key]
o, isObs := rc.observer[key]
// What a radio reports only counts while it has a current source (the same test the evaluation applies).
nodeCaps := alerts.Caps{HasNode: true, NodeType: n.NodeType, Polled: n.Polled, Battery: n.Polled && n.HasBattery,
nodeCaps := alerts.Caps{HasNode: true, NodeType: n.NodeType, Polled: n.Polled, NodePolled: n.Polled, Battery: n.Polled && n.HasBattery,
Temperature: n.Polled && n.HasTemperature, Noise: n.Polled && n.HasNoise, Uptime: n.Polled && n.HasUptime}
obsCaps := alerts.Caps{Observer: true, Polled: o.Polled, Battery: o.Polled && o.HasBattery, Noise: o.Polled && o.HasNoise, Uptime: o.Polled && o.HasUptime}
if isNode && isObs {
c = alerts.Caps{Observer: true, HasNode: true, NodeType: n.NodeType, Polled: n.Polled || o.Polled,
c = alerts.Caps{Observer: true, HasNode: true, NodeType: n.NodeType, Polled: n.Polled || o.Polled, NodePolled: n.Polled,
Battery: nodeCaps.Battery || obsCaps.Battery, Temperature: nodeCaps.Temperature, Noise: nodeCaps.Noise || obsCaps.Noise,
Uptime: nodeCaps.Uptime || obsCaps.Uptime, ObsBattery: obsCaps.Battery, ObsNoise: obsCaps.Noise, ObsUptime: obsCaps.Uptime}
if want == alerts.TargetObserver {
Expand Down
5 changes: 3 additions & 2 deletions db/alerts_eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,14 @@ func (a AlertEval) LoadTargets(ctx context.Context, rules []alerts.RuleRow, now
since := ts(now.Add(-alerts.DataWindow * time.Second))

if len(nodeKeys) > 0 {
nodes, err := a.q.AlertNodesData(ctx, sqlc.AlertNodesDataParams{Keys: nodeKeys, PollingEnabled: !a.pollingOff.Load()})
nodes, err := a.q.AlertNodesData(ctx, sqlc.AlertNodesDataParams{Keys: nodeKeys, PollingEnabled: !a.pollingOff.Load(), FreshSince: ts(now.Add(-alerts.NodeFresh))})
if err != nil {
return nil, err
}
for _, n := range nodes {
td := alerts.TargetData{Name: n.Name}
td.Exists, td.Polled, td.LastHeard = true, n.Polled, tsTime(n.LastSeen)
td.Exists, td.Polled, td.LastHeard, td.LastReading = true, n.Polled, tsTime(n.LastSeen), tsTime(n.LastReadingAt)
td.PollingOff = a.pollingOff.Load()
out[alerts.TargetID(alerts.TargetNode, n.PublicKey)] = td
}
reads, err := a.q.AlertNodeReadings(ctx, sqlc.AlertNodeReadingsParams{Keys: nodeKeys, Since: since})
Expand Down
4 changes: 2 additions & 2 deletions db/alerts_eval_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -686,8 +686,8 @@ func ruleStateOf(t *testing.T, ctx context.Context, pool interface {
return st
}

// Readings from days ago do not make a radio polled: it needs a polling assignment (a repeater) or fresh status
// telemetry (an observer). The overview's flag and the evaluation use the same answer.
// Readings from days ago do not make a radio polled: it needs a polling assignment or a fresh reading (a repeater)
// or fresh status telemetry (an observer). The overview's flag and the evaluation use the same answer.
func TestAlertPolledNeedsACurrentSourcePostgres(t *testing.T) {
ctx, pool, s := userStore(t)
svc := alertSvc(s)
Expand Down
98 changes: 98 additions & 0 deletions db/alerts_final_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package db

import (
"slices"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -83,6 +84,91 @@ func TestAlertClockBreachBetweenPassesPostgres(t *testing.T) {
}
}

// A repeater nobody is assigned to, read by a poller this server does not manage: its trusted readings offer the
// telemetry kinds and their rules are judged. When the readings stop, telemetry_stopped fires and keeps firing.
func TestAlertTelemetryWithoutAssignmentPostgres(t *testing.T) {
ctx, pool, s := userStore(t)
svc := alertSvc(s)
u := newUser(t, ctx, s, "alice")
rep, silent := atlasKey(1), atlasKey(2)
insertNode(t, ctx, s, rep, 2, "Hilltop")
insertNode(t, ctx, s, silent, 2, "Valley")
insertReading(t, ctx, s, rep, time.Now().Add(-4*time.Hour), 3000, nil)
insertReading(t, ctx, s, rep, time.Now().Add(-5*time.Hour), 3000, nil)
pinAtlas(t, ctx, s, u, 0, api.StoredPin{Kind: "node", Key: rep}, api.StoredPin{Kind: "node", Key: silent})
ov, err := svc.Overview(ctx, u.ID)
if err != nil || len(ov.Targets) != 2 {
t.Fatalf("%+v %v", ov, err)
}
if got := ov.Targets[0]; !got.Caps.Polled || !slices.Contains(got.Available, "battery_low") || !slices.Contains(got.Available, "telemetry_stopped") {
t.Fatalf("a repeater with readings and no assignment: %+v", got)
}
if got := ov.Targets[1]; got.Caps.Polled || got.UnavailableCodes["battery_low"] != alerts.CodeNotPolled || got.UnavailableCodes["telemetry_stopped"] != alerts.CodeNotPolled {
t.Fatalf("a repeater with no readings: %+v", got)
}
// Any repeater takes the short gone_quiet windows.
if _, err := svc.PutRule(ctx, u.ID, alerts.RuleInput{TargetKind: "node", PublicKey: silent, Kind: "gone_quiet", Threshold: ipp(3), Enabled: true}); err != nil {
t.Fatalf("gone_quiet 3 on an unpolled repeater: %v", err)
}
for kind, th := range map[string]int{"battery_low": 3500, "telemetry_stopped": 6} {
if _, err := svc.PutRule(ctx, u.ID, alerts.RuleInput{TargetKind: "node", PublicKey: rep, Kind: kind, Threshold: ipp(th), Enabled: true}); err != nil {
t.Fatalf("%s: %v", kind, err)
}
}
task := alerts.NewTask(AlertEval{s}, time.Now)
run := func() {
t.Helper()
if err := task.Run(ctx); err != nil {
t.Fatal(err)
}
}
run()
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "firing" {
t.Fatalf("battery_low without an assignment: %s", got)
}
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped with a reading 4 hours old and a 6 hour limit: %s", got)
}
// The rule was set now, with the last reading 4 hours old: the clock starts at the rule, not in the past.
if _, err := pool.Exec(ctx, `UPDATE user_alert_rules SET cursor_at = now() - interval '3 hours' WHERE kind = 'telemetry_stopped'`); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET sampled_at = sampled_at - interval '3 hours' WHERE target_public_key = $1`, rep); err != nil {
t.Fatal(err)
}
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped 3 hours after it was set: %s", got)
}
// A month on there is no current source, so the battery rule is inactive, and the stopped rule fires.
if _, err := pool.Exec(ctx, `UPDATE user_alert_rules SET cursor_at = cursor_at - interval '30 days' WHERE kind = 'telemetry_stopped'`); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET sampled_at = sampled_at - interval '30 days', received_at = received_at - interval '30 days' WHERE target_public_key = $1`, rep); err != nil {
t.Fatal(err)
}
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "firing" {
t.Fatalf("telemetry_stopped a month after the last reading: %s", got)
}
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "inactive" {
t.Fatalf("battery_low with no current source: %s", got)
}
// Retention deletes the readings; the rule remembers when the last one was and keeps firing.
if _, err := pool.Exec(ctx, `DELETE FROM repeater_readings WHERE target_public_key = $1`, rep); err != nil {
t.Fatal(err)
}
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "firing" {
t.Fatalf("telemetry_stopped after retention deleted the readings: %s", got)
}
insertReading(t, ctx, s, rep, time.Now().Add(-time.Minute), 4000, nil)
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped after a new reading: %s", got)
}
}

// With polling switched off the assignment rows that remain are no current source: repeater telemetry kinds are
// unavailable (not_polled) and their rules read inactive. Observer status alerts do not depend on it.
func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) {
Expand All @@ -99,13 +185,21 @@ func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) {
VALUES ($1, 'node', $2, 'battery_low', 3500, now() - interval '3 days')`, u.ID, rep); err != nil {
t.Fatal(err)
}
// Set two days ago with a 1 hour limit: firing while polling is on.
if _, err := pool.Exec(ctx, `INSERT INTO user_alert_rules (user_id, target_kind, target_public_key, kind, threshold, cursor_at)
VALUES ($1, 'node', $2, 'telemetry_stopped', 3, now() - interval '2 days')`, u.ID, rep); err != nil {
t.Fatal(err)
}
task := alerts.NewTask(AlertEval{s}, time.Now)
if err := task.Run(ctx); err != nil {
t.Fatal(err)
}
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "firing" {
t.Fatalf("with polling on: %s", got)
}
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped with a reading 10 minutes old: %s", got)
}
s.SetPollingEnabled(false)
ov, err := svc.Overview(ctx, u.ID)
if err != nil || len(ov.Targets) != 1 || ov.Targets[0].Caps.Polled {
Expand All @@ -120,6 +214,10 @@ func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) {
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "inactive" {
t.Fatalf("rule with polling off: %s", got)
}
// The stopped rule would otherwise fire for every repeater once its hours passed.
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "inactive" {
t.Fatalf("telemetry_stopped with polling off: %s", got)
}
}

// The sender takes the notices of a finished pass only, so a pass that is still being evaluated is not split across
Expand Down
8 changes: 8 additions & 0 deletions db/migrations/096_alert_telemetry_stopped.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- Copyright 2026 Beacon Contributors
-- SPDX-License-Identifier: AGPL-3.0-or-later

-- A rule kind for a repeater whose readings stopped arriving.
ALTER TABLE user_alert_rules DROP CONSTRAINT IF EXISTS user_alert_rules_kind_check;
ALTER TABLE user_alert_rules ADD CONSTRAINT user_alert_rules_kind_check
CHECK (kind IN ('gone_quiet', 'back_online', 'telemetry_stopped', 'battery_low', 'battery_falling', 'rebooted',
'temperature', 'noise_high', 'clock', 'observer_offline'));
6 changes: 6 additions & 0 deletions db/migrations/097_repeater_readings_sensors.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- Copyright 2026 Beacon Contributors
-- SPDX-License-Identifier: AGPL-3.0-or-later

-- What a reading's sensor channels carried (humidity, pressure, gas, power monitors), decoded when it is stored.
-- NULL when it carried none, and on every reading stored before this.
ALTER TABLE repeater_readings ADD COLUMN IF NOT EXISTS sensors jsonb;
15 changes: 14 additions & 1 deletion db/polling.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sort"
Expand Down Expand Up @@ -366,6 +367,13 @@ func storeReading(ctx context.Context, q *sqlc.Queries, r polling.Reading, obser
if foreign != nil {
params.ForeignSource, params.EvidenceSince, params.ApprovedOnly = true, ts(foreign.evidenceSince), foreign.approvedOnly
}
if len(r.Sensors) > 0 {
b, err := json.Marshal(r.Sensors)
if err != nil {
return false, err
}
params.Sensors = b
}
n, err := q.InsertRepeaterReading(ctx, params)
return n > 0, err
}
Expand Down Expand Up @@ -855,7 +863,12 @@ func (l *PollingElectionLock) Close(ctx context.Context) {
}

func nodeReading(r sqlc.ListNodeReadingsRow) api.NodeReading {
var sensors []api.NodeSensor
if len(r.Sensors) > 0 {
_ = json.Unmarshal(r.Sensors, &sensors) // written by this server; a row it cannot read has no sensors
}
return api.NodeReading{
Sensors: sensors,
SampledAt: r.SampledAt.Time, Method: r.Method, Trusted: r.Trusted, Foreign: r.ForeignSource,
BatteryMV: r.BatteryMv, TemperatureC: r.TemperatureC, NoiseFloorDB: r.NoiseFloor, LastRSSIDB: r.LastRssi,
LastSNRDB: r.LastSnr, UptimeSeconds: r.UptimeSecs, QueueLength: r.TxQueue,
Expand Down Expand Up @@ -929,7 +942,7 @@ func (s *Store) GetNodePolling(ctx context.Context, nodeID uuid.UUID) (*api.Node
}
for _, f := range foreign {
o := api.NodePollingForeign{ObserverID: f.ObserverID, Name: f.Name, Signed: f.Signed,
Claimed: f.Claimed, LatestReadingAt: epochMs(f.LatestReadingAt)}
Claimed: f.Claimed, Local: f.IsLocal, LatestReadingAt: epochMs(f.LatestReadingAt)}
if f.PollHost != "" {
h := f.PollHost
o.PollHost = &h
Expand Down
6 changes: 4 additions & 2 deletions db/polling_foreign_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ func TestPollingForeignClaimsPostgres(t *testing.T) {
}
for _, f := range view.Foreign {
claimed := f.ObserverID == pollObserver(t, ctx, s, foreign.pub)
if f.Claimed != claimed || f.LatestReadingAt == nil || f.PollHost != nil || f.Signed {
// The one with no claim at all is local; a claim, even one naming other repeaters, is not.
if f.Claimed != claimed || f.Local == claimed || f.LatestReadingAt == nil || f.PollHost != nil || f.Signed {
t.Errorf("foreign reporter: %+v", f)
}
}
Expand Down Expand Up @@ -420,7 +421,8 @@ func TestPollingForeignClaimedIsPerTargetPostgres(t *testing.T) {
w.claimVia(d, foreignOtherBroker, 2, reqNode(pollKey(0xA2), false, "ok"))
for node, want := range map[uuid.UUID]bool{a: false, b: true} {
v, err := s.GetNodePolling(ctx, node)
if err != nil || len(v.Foreign) != 1 || v.Foreign[0].Claimed != want {
// It has a claim, so it is never local, whichever repeaters the claim names.
if err != nil || len(v.Foreign) != 1 || v.Foreign[0].Claimed != want || v.Foreign[0].Local {
t.Fatalf("claimed want %v: %+v %v", want, v.Foreign, err)
}
}
Expand Down
36 changes: 36 additions & 0 deletions db/polling_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
Expand Down Expand Up @@ -1412,6 +1413,41 @@ func trustedIndexValid(t *testing.T, ctx context.Context, pool *pgxpool.Pool) bo
return valid
}

// A reading's sensor channels are decoded when it is stored and read back with it; the position in the same LPP is
// not among them.
func TestReadingSensorsPostgres(t *testing.T) {
ctx, pool, s := pollStore(t)
obs, target := pollKey(1), pollKey(0xA)
oid := pollObserver(t, ctx, s, obs)
nodeID := uuid.New()
if _, err := pool.Exec(ctx, `INSERT INTO nodes (id, public_key, node_type, name) VALUES ($1, $2, 2, 'rep')`, nodeID, target); err != nil {
t.Fatal(err)
}
now := time.Now().UTC().Truncate(time.Second)
// 3.94 V on channel 1, a position, then 45.5 % and 1013.2 hPa on channel 2 and 8.70 V at 0.122 A on channel 3.
lpp, _ := hex.DecodeString("0174018a" + "018806f7c8f4b2e0002710" + "02685b" + "02732794" + "03740366" + "0375007a")
mv := 3940
plain := polling.Reading{Version: 2, Observer: obs, Target: target, Method: "status", SampledAt: now.Add(-2 * time.Hour), BatteryMV: &mv}
withLPP := polling.Reading{Version: 2, Observer: obs, Target: target, Method: "telemetry", SampledAt: now.Add(-time.Hour), BatteryMV: &mv,
LPP: lpp, Sensors: polling.DecodeSensors(lpp)}
for _, r := range []polling.Reading{plain, withLPP} {
if ok, err := s.InsertRepeaterReading(ctx, r, oid, r.SampledAt); err != nil || !ok {
t.Fatalf("insert: %v %v", ok, err)
}
}
got, _, _, err := s.GetNodeReadings(ctx, nodeID, now.Add(-24*time.Hour), time.Time{}, true)
if err != nil || len(got) != 2 {
t.Fatalf("%d readings, %v", len(got), err)
}
if got[0].Sensors != nil {
t.Fatalf("a reading without sensor channels: %+v", got[0].Sensors)
}
b, _ := json.Marshal(got[1].Sensors)
if want := `[{"channel":2,"humidityPct":45.5,"pressureHpa":1013.2},{"channel":3,"voltageV":8.7,"currentA":0.122,"powerW":1.061}]`; string(b) != want {
t.Fatalf("sensors %s", b)
}
}

func TestNodeReadingsPostgres(t *testing.T) {
ctx, pool, s := pollStore(t)
obs := pollKey(1)
Expand Down
8 changes: 6 additions & 2 deletions db/queries/alerts.sql
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,12 @@ SELECT n.id, n.public_key, n.node_type, COALESCE(n.name, '')::text AS name,
COALESCE(c.readings, 0)::int AS readings,
COALESCE(c.battery, false)::boolean AS has_battery, COALESCE(c.temperature, false)::boolean AS has_temperature,
COALESCE(c.noise, false)::boolean AS has_noise, COALESCE(c.uptime, false)::boolean AS has_uptime,
-- Polled is a current source, not history: some observer holds the repeater as a polling assignment, and polling is on.
(sqlc.arg(polling_enabled)::boolean AND EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key))::boolean AS polled
-- Polled is a current source, not history, while polling is on: some observer holds the repeater as a polling
-- assignment, or a trusted reading of it was taken since fresh_since (a poller this server does not assign).
(sqlc.arg(polling_enabled)::boolean AND (
EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key)
OR EXISTS (SELECT 1 FROM repeater_readings f WHERE f.target_public_key = n.public_key AND f.trusted
AND f.sampled_at >= sqlc.arg(fresh_since))))::boolean AS polled
FROM nodes n
LEFT JOIN LATERAL (
SELECT count(*) AS readings, bool_or(r.battery_mv IS NOT NULL) AS battery, bool_or(r.temperature_c IS NOT NULL) AS temperature,
Expand Down
Loading
Loading