feat(fleet): add shared WireGuard profiles and bounded rover transport

Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent bec20d63e2
commit e06ff9a214
180 changed files with 20140 additions and 400 deletions
@@ -0,0 +1,284 @@
package node
// One egress budget for optional application traffic. Control and critical
// telemetry never acquire permits. No OS routes, queues or motor leases change.
import (
"encoding/json"
"errors"
"math"
"net/http"
"os"
"path/filepath"
"sync"
"time"
)
// The aggregate burst covers the four bounded class buckets. A smaller
// shared bucket allows an always-first video requester to starve bulk even
// when bulk has earned tokens (packetization/rounding). No per-peer queues.
const linkClassBurst = 4096
const linkBurst = 4 * linkClassBurst
const linkPacket = 2048
const linkOverhead = 256
// Inventory cannot compete packet-by-packet with short DEV polls. Both remain
// optional: these are shares of the same aggregate, not extra bandwidth.
var linkWeights = map[string]float64{"video": 7, "cloud": 2, "bulk": 1, "inventory": 1}
type LinkPolicy struct {
Schema string `json:"schema"`
CeilingKbps int `json:"ceiling_kbps"`
ReserveKbps int `json:"reserve_kbps"`
}
type linkClass struct {
wanted float64
tokens float64
seen time.Time
bytes uint64
deferred uint64
}
type LinkBudget struct {
mu sync.Mutex
policy LinkPolicy
path string
now func() time.Time
at time.Time
tokens float64
classes map[string]*linkClass
producers map[string]linkProducer
effective float64
baseline time.Duration
baselineAt time.Time
changed time.Time
healthy time.Time
runtime linkRuntime
}
func OpenLinkBudget(dir string) (*LinkBudget, error) {
b := &LinkBudget{policy: LinkPolicy{"missioncore.link-budget/v1", 0, 512}, now: time.Now,
classes: map[string]*linkClass{"video": {}, "cloud": {}, "bulk": {}, "inventory": {}},
producers: map[string]linkProducer{}, runtime: linkRuntime{lastProtected: true, reason: "startup"}}
if dir != "" {
b.path = filepath.Join(dir, "link-budget.json")
data, err := os.ReadFile(b.path)
if err == nil {
if len(data) > 1024 || json.Unmarshal(data, &b.policy) != nil {
return nil, errors.New("invalid link budget")
}
} else if !os.IsNotExist(err) {
return nil, err
}
}
if err := validLinkPolicy(b.policy); err != nil {
return nil, err
}
b.effective = math.Min(4000, b.ceiling())
b.at = b.now()
return b, nil
}
func validLinkPolicy(p LinkPolicy) error {
if p.Schema != "missioncore.link-budget/v1" || (p.CeilingKbps != 0 && (p.CeilingKbps < 1024 || p.CeilingKbps > 100000)) || p.ReserveKbps < 512 || p.ReserveKbps > 50000 || (p.CeilingKbps != 0 && p.ReserveKbps > p.CeilingKbps/2) {
return errors.New("link budget requires ceiling 0 (automatic) or 1024..100000 kbps and reserve 512..ceiling/2 kbps")
}
return nil
}
func (b *LinkBudget) Configure(p LinkPolicy) error {
if err := validLinkPolicy(p); err != nil {
return err
}
b.mu.Lock()
defer b.mu.Unlock()
if b.path != "" {
raw, _ := json.Marshal(p)
if err := os.WriteFile(b.path+".tmp", raw, 0600); err != nil {
return err
}
if err := os.Rename(b.path+".tmp", b.path); err != nil {
return err
}
}
b.policy = p
// Raising the configured ceiling does not erase observed congestion.
b.effective = math.Min(b.effective, b.ceiling())
b.effective = math.Max(b.effective, float64(p.ReserveKbps+128))
b.tokens = 0
for _, c := range b.classes {
c.tokens = 0
}
b.at = b.now()
return nil
}
func (b *LinkBudget) refill(now time.Time) {
dt := math.Max(0, now.Sub(b.at).Seconds())
protected := b.protected(now)
if protected && !b.runtime.lastProtected {
b.tokens = 0
for _, c := range b.classes {
c.tokens = 0
}
}
b.runtime.lastProtected = protected
rates := b.classRates(now)
rate := b.optional(now) * 125
b.tokens = math.Min(linkBurst, b.tokens+dt*rate)
for k, c := range b.classes {
if rates[k] == 0 {
c.tokens = 0
continue
}
c.tokens = math.Min(linkClassBurst, c.tokens+dt*rates[k]/8)
}
b.at = now
}
// Try is nonblocking, consumes actual bytes plus conservative packet overhead,
// and has fixed memory regardless of peer/request count. Denials are not queued.
func (b *LinkBudget) Try(class string, size int) (bool, time.Duration) {
if b == nil {
return true, 0
} // Unwired unit fixtures only; production always owns a budget.
b.mu.Lock()
defer b.mu.Unlock()
return b.tryLocked(class, size)
}
func (b *LinkBudget) tryLocked(class string, size int) (bool, time.Duration) {
c := b.classes[class]
if c == nil || size <= 0 || size > linkPacket {
return false, time.Second
}
now := b.now()
b.refill(now)
c.seen = now
if b.commandLimited(now) && class != "video" {
c.deferred++
return false, 10 * time.Millisecond
}
cost := float64(size + linkOverhead) // UDP/IP, encryption and overlay allowance; not a wire measurement.
// Borrow idle optional credit only; the aggregate and control reserve remain
// hard gates. Preserve a packet of credit for each donor's next useful burst.
if c.tokens < cost && b.tokens >= cost {
for k, other := range b.classes {
if k != class && now.Sub(other.seen) > 100*time.Millisecond {
take := math.Min(math.Max(0, other.tokens-float64(linkPacket+linkOverhead)), cost-c.tokens)
other.tokens -= take
c.tokens += take
}
}
}
if h := &b.runtime.feedback; h.enabled && h.sent-h.acknowledged+uint64(cost) > h.window {
c.deferred++
return false, 10 * time.Millisecond
}
if b.tokens >= cost && c.tokens >= cost {
if b.runtime.feedback.enabled {
b.runtime.feedback.sent += uint64(cost)
}
b.tokens -= cost
c.tokens -= cost
c.bytes += uint64(size)
return true, 0
}
c.deferred++
return false, 10 * time.Millisecond
}
func (b *LinkBudget) Snapshot() map[string]any {
b.mu.Lock()
defer b.mu.Unlock()
now := b.now()
rates := b.classRates(now)
classes := map[string]any{}
counts := map[string]int{}
for _, p := range b.producers {
if b.now().Sub(p.seen) < producerTTL {
counts[p.class]++
}
}
for k, c := range b.classes {
classes[k] = map[string]any{"granted_bytes": c.bytes, "deferrals": c.deferred, "producers": counts[k], "allocation_bps": int(rates[k])}
}
return map[string]any{"policy": b.policy, "effective_kbps": int(b.effective), "optional_kbps": int(b.optional(now)), "runtime": b.runtimeView(now),
"baseline_rtt_ms": b.baseline.Milliseconds(), "burst_bytes": linkBurst, "max_packet_bytes": linkPacket, "classes": classes}
}
// Trusted local plugin socket exposes permits/status only, no configuration or
// control authority. The existing authenticated UI API owns policy changes.
func (b *LinkBudget) Handler() http.Handler {
mux := http.NewServeMux()
b.producerRoutes(mux)
mux.HandleFunc("GET /status", func(w http.ResponseWriter, r *http.Request) { reply(w, 200, b.Snapshot()) })
mux.HandleFunc("GET /events", func(w http.ResponseWriter, r *http.Request) {
b.mu.Lock()
events := append([]linkDecision{}, b.runtime.events...)
b.mu.Unlock()
reply(w, 200, events)
})
mux.HandleFunc("POST /permit", func(w http.ResponseWriter, r *http.Request) {
var v struct {
Class string `json:"class"`
Bytes int `json:"bytes"`
Producer string `json:"producer_id"`
}
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256))
d.DisallowUnknownFields()
if d.Decode(&v) != nil || (v.Class != "video" && v.Class != "cloud" && v.Class != "bulk") || v.Bytes <= 0 || v.Bytes > linkPacket {
reply(w, 400, map[string]string{"error": "invalid permit"})
return
}
b.mu.Lock()
valid := true
if v.Producer != "" {
p, exists := b.producers[v.Producer]
valid = exists && p.class == v.Class && b.now().Sub(p.seen) < producerTTL
}
if b.commandLimited(b.now()) && v.Class == "video" {
valid = valid && v.Producer != "" && v.Producer == b.primaryVideo(b.now())
}
granted, delay := false, 10*time.Millisecond
if valid {
granted, delay = b.tryLocked(v.Class, v.Bytes)
}
b.mu.Unlock()
reply(w, 200, map[string]any{"granted": granted, "retry_ms": delay.Milliseconds()})
})
return mux
}
func (s *Server) linkBudgetRoutes(mux *http.ServeMux) {
if s.Budget == nil {
return
}
mux.HandleFunc("GET /api/network/budget", func(w http.ResponseWriter, r *http.Request) {
if s.authorized(w, r) {
reply(w, 200, s.Budget.Snapshot())
}
})
mux.HandleFunc("PUT /api/network/budget", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
var p LinkPolicy
if !decode(w, r, &p) {
return
}
if err := s.Budget.Configure(p); err != nil {
reply(w, 400, map[string]string{"error": err.Error()})
return
}
reply(w, 200, s.Budget.Snapshot())
})
}
// Budget waits are part of upload time, not network failure. Size includes
// every paced packet's overhead at the lowest allocation with all classes busy.
// This is a per-request bound, never a recording/session duration limit.
func pacedTimeout(size int) time.Duration {
packets := (size + linkPacket - 1) / linkPacket
cost := size + packets*linkOverhead
total := 0.0
for _, weight := range linkWeights {
total += weight
}
seconds := float64(cost) / (128 * 125 / total)
return 8*time.Second + time.Duration(math.Ceil(seconds*1.25))*time.Second
}
@@ -0,0 +1,152 @@
package node
import (
"bytes"
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
)
func testBudget(t *testing.T) (*LinkBudget, *time.Time) {
t.Helper()
b, err := OpenLinkBudget("")
if err != nil {
t.Fatal(err)
}
now := time.Now()
b.now = func() time.Time { return now }
b.at = now
return b, &now
}
func TestLinkAggregateAndWeightedProgress(t *testing.T) {
b, now := testBudget(t)
counts := map[string]int{}
// Deterministic virtual time, no host/network load or sleeping.
for tick := 0; tick < 1000; tick++ {
*now = now.Add(10 * time.Millisecond)
for _, k := range []string{"video", "cloud", "bulk"} {
for attempt := 0; attempt < 10; attempt++ {
if ok, _ := b.Try(k, 1000); ok {
counts[k]++
}
}
}
}
total := counts["video"] + counts["cloud"] + counts["bulk"]
if total*(1000+linkOverhead) > (4000-512)*125*10+linkBurst {
t.Fatal("aggregate budget exceeded", counts)
}
if counts["bulk"] < 100 || counts["cloud"] < counts["bulk"] || counts["video"] < 2*counts["cloud"] {
t.Fatal("class starvation/priority", counts)
}
}
func TestLinkCongestionDoesNotChangeMotionState(t *testing.T) {
b, now := testBudget(t)
s := newRoverStreamState(*now)
s.budget = b
b.Observe(300*time.Millisecond, true)
*now = now.Add(time.Second)
b.Observe(600*time.Millisecond, true)
if b.effective != 4000 {
t.Fatal("isolated delay reduced budget")
}
for i := 0; i < 15; i++ {
*now = now.Add(200 * time.Millisecond)
b.Observe(600*time.Millisecond, true)
}
if b.effective >= 4000 {
t.Fatal("sustained congestion ignored")
}
low := b.effective
for i := 0; i < 100; i++ {
*now = now.Add(100 * time.Millisecond)
b.Try("video", 1000)
b.Observe(300*time.Millisecond, true)
}
if b.effective <= low {
t.Fatal("recovery missing")
}
if s.command != nil || s.stopRevision != 1 || !s.stopPending {
t.Fatal("budget changed authority")
}
}
func TestLinkConfigAndLocalCapability(t *testing.T) {
b, _ := OpenLinkBudget(t.TempDir())
p := LinkPolicy{"missioncore.link-budget/v1", 8000, 512}
if err := b.Configure(p); err != nil {
t.Fatal(err)
}
restored, err := OpenLinkBudget(b.path[:len(b.path)-len("/link-budget.json")])
if err != nil || restored.policy != p {
t.Fatal("policy not durable", err)
}
for _, body := range []string{`{"class":"control","bytes":100}`, `{"class":"video","bytes":99999}`, `{"class":"bulk","bytes":0}`} {
r := httptest.NewRequest("POST", "/permit", bytes.NewBufferString(body))
w := httptest.NewRecorder()
b.Handler().ServeHTTP(w, r)
if w.Code != 400 {
t.Fatal("untrusted permit accepted")
}
}
w := httptest.NewRecorder()
b.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/login", nil))
if w.Code != 404 {
t.Fatal("media socket acquired launcher authority")
}
}
func TestBudgetReaderCancellationAndDevBound(t *testing.T) {
b, _ := testBudget(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
r := &budgetReader{ctx: ctx, budget: b, class: "bulk", source: bytes.NewReader(make([]byte, 100))}
if _, err := r.Read(make([]byte, 4096)); err != context.Canceled {
t.Fatal("blocked cancellation", err)
}
rows := []any{}
for i := 0; i < 24; i++ {
rows = append(rows, map[string]any{"record_sequence": i, "value": strings.Repeat("x", 1000)})
}
packet := map[string]any{"id": "capture", "frames": rows, "storage": map[string]any{"closed": false}, "export": map[string]any{"data": "data"}}
bounded := boundedDevPacket(packet)
raw, _ := json.Marshal(bounded)
if len(raw) > 12*1024 || len(bounded["frames"].([]any)) == 0 || len(packet["frames"].([]any)) != 24 || bounded["export"] == nil {
t.Fatal("invalid network view")
}
}
func TestLinkBaselineRelearnsAfterNetworkHandover(t *testing.T) {
b, now := testBudget(t)
b.Observe(10*time.Millisecond, true)
for i := 0; i < 15; i++ {
*now = now.Add(200 * time.Millisecond)
b.Observe(300*time.Millisecond, true)
}
low := b.effective
*now = now.Add(31 * time.Second)
for i := 0; i < 60; i++ {
*now = now.Add(100 * time.Millisecond)
b.Try("video", 1000)
b.Observe(300*time.Millisecond, true)
}
if b.baseline != 300*time.Millisecond || b.effective <= low {
t.Fatal("old LAN minimum pinned new route", b.baseline, b.effective)
}
}
func TestDevLargeExportDoesNotRemoveLiveRowsOrExceedRequestLimit(t *testing.T) {
rows := []any{map[string]any{"record_sequence": 1, "event": "sample"}}
for _, size := range []int{87384, 200000} {
packet := map[string]any{"id": "capture", "frames": rows, "export": map[string]any{"data": strings.Repeat("A", size)}}
bounded := boundedDevPacket(packet)
raw, _ := json.Marshal(bounded)
if len(raw) > 108*1024 || len(bounded["frames"].([]any)) != 1 {
t.Fatal("export exceeded bounded lane or starved live evidence")
}
if size == 87384 && bounded["export"] == nil {
t.Fatal("valid export lost")
}
}
}
@@ -0,0 +1,99 @@
package node
import "time"
// This is optional-traffic admission, never a motor lease or a replacement for
// the stream watchdog. A healthy telemetry socket cannot certify command flow.
const commandPressureAfter = 150 * time.Millisecond
const commandRecoveryWindow = 200 * time.Millisecond
const commandBackoffAfter = 200 * time.Millisecond
type linkCommandHealth struct {
seen, healthy, pressure time.Time
gap, age time.Duration
limited bool
}
func (b *LinkBudget) commandPressure(now time.Time, reason string) {
h := &b.runtime.command
// Invalidate old credit once on entering pressure. Repeated moderate-age
// samples must not erase the selected camera's low-rate packet credit every
// 50 ms: at 128 kbps a 1100-byte datagram needs longer than one sample period.
// Moving the refill anchor prevents pre-pressure time recreating that credit.
if !h.limited {
b.tokens = 0
for _, c := range b.classes {
c.tokens = 0
}
b.at = now
}
h.limited = true
h.healthy = time.Time{}
if h.pressure.IsZero() {
h.pressure = now
}
// An isolated jitter sample is reason to yield, not evidence that the
// sustainable channel capacity fell by 25%. Require continuing pressure
// for an estimate reduction; fresh receipt ends that evidence immediately.
if now.Sub(h.pressure) < commandBackoffAfter {
return
}
b.healthy = time.Time{}
if now.Sub(b.changed) >= time.Second {
next := max(float64(b.policy.ReserveKbps+128), b.effective*.75)
if next < b.effective {
b.decision(now, reason, next)
}
}
}
// age is the conservative Core-clock upper bound, not synchronized wall-clock
// latency. It can safely overestimate pressure but cannot grant motion authority.
func (b *LinkBudget) ObserveCommandFrame(gap, age time.Duration) {
if b == nil {
return
}
b.mu.Lock()
defer b.mu.Unlock()
now := b.now()
h := &b.runtime.command
h.seen, h.gap, h.age = now, gap, age
if !b.protected(now) {
h.limited, h.healthy, h.pressure = false, time.Time{}, time.Time{}
return
}
if gap >= commandPressureAfter || age >= commandPressureAfter {
b.commandPressure(now, "command_stream_pressure")
return
}
h.pressure = time.Time{}
if h.limited {
if h.healthy.IsZero() {
h.healthy = now
}
if now.Sub(h.healthy) >= commandRecoveryWindow {
h.limited = false
// Several fresh arrivals over real elapsed time are required: a
// queued burst cannot reopen optional traffic in a single instant.
// Isolated jitter must not erase the independent exchange estimator's
// recovery progress either. Sustained pressure resets it above.
}
}
}
// Called by the existing local tick, even while the stream reader is blocked.
func (b *LinkBudget) ObserveCommandSilence() {
if b == nil {
return
}
b.mu.Lock()
defer b.mu.Unlock()
now := b.now()
if b.protected(now) && !b.runtime.command.seen.IsZero() && now.Sub(b.runtime.command.seen) >= commandPressureAfter {
b.commandPressure(now, "command_stream_silence")
}
}
func (b *LinkBudget) commandLimited(now time.Time) bool {
return b.protected(now) && b.runtime.command.limited
}
@@ -0,0 +1,264 @@
package node
import (
"context"
"encoding/json"
"net/http"
"os"
"testing"
"time"
)
func TestRedactedCommandJitterReplayPreservesAvailableCapacity(t *testing.T) {
// Timings only: no UTC, identities, commands, locations or device values.
// Replay the real admission code in virtual time, without sockets/motors.
raw, err := os.ReadFile("testdata/command-jitter-redacted.json")
if err != nil {
t.Fatal(err)
}
var rows [][3]float64 // elapsed receipt ms, inter-frame gap ms, conservative age ms
if err = json.Unmarshal(raw, &rows); err != nil || len(rows) < 1000 {
t.Fatal("invalid receipt fixture", err)
}
b, now := testBudget(t)
start := *now
initial := b.effective
b.SetControl(true)
blocked, total := time.Duration(0), time.Duration(0)
// Independent 50 ms local watchdog ticks, just as on Node. They may pause
// admission while the stream reader is blocked; fresh telemetry cannot hide it.
nextTick := start.Add(50 * time.Millisecond)
advance := func(at time.Time) {
delta := at.Sub(*now)
total += delta
if b.commandLimited(*now) {
blocked += delta
}
*now = at
b.SetControl(true)
}
for _, row := range rows {
at := start.Add(time.Duration(row[0] * float64(time.Millisecond)))
for !nextTick.After(at) {
advance(nextTick)
b.ObserveCommandSilence()
nextTick = nextTick.Add(50 * time.Millisecond)
}
advance(at)
b.ObserveCommandFrame(time.Duration(row[1]*float64(time.Millisecond)), time.Duration(row[2]*float64(time.Millisecond)))
}
ratio := float64(blocked) / float64(total)
t.Logf("optional admission paused %.1f%%; capacity %.0f -> %.0f kbps", ratio*100, initial, b.effective)
if ratio > .35 || b.effective < initial*.9 {
t.Fatal("isolated jitter still starves media", ratio, b.effective)
}
}
func TestBudgetDiagnosticsAreBoundedAndDevOnly(t *testing.T) {
b, now := testBudget(t)
s := newRoverStreamState(*now)
s.budget = b
s.recordBudgetDev(*now)
if len(s.devEvents) != 0 {
t.Fatal("DEV-off recorded budget")
}
s.setDev(map[string]any{"id": testClockID, "enabled": true})
for i := 0; i < 20; i++ {
s.recordBudgetDev(now.Add(time.Duration(i) * 100 * time.Millisecond))
}
if len(s.devEvents) != 2 || s.devEvents[0]["event"] != "link_budget" {
t.Fatal("budget evidence rate is not bounded", len(s.devEvents))
}
s.setDev(map[string]any{"id": testClockID, "enabled": false})
s.recordBudgetDev(now.Add(3 * time.Second))
if len(s.devEvents) != 2 {
t.Fatal("recording continued after DEV stop")
}
}
func TestCommandSilenceBlocksOptionalBytesDespiteHealthyTelemetry(t *testing.T) {
b, now := testBudget(t)
b.SetControl(true)
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
for _, class := range []string{"video", "cloud", "inventory", "bulk"} {
b.Try(class, 1000)
}
*now = now.Add(150 * time.Millisecond)
b.ObserveExchange(50*time.Millisecond, 0, true)
b.ObserveCommandSilence()
for _, class := range []string{"video", "cloud", "inventory", "bulk"} {
if ok, _ := b.Try(class, 100); ok {
t.Fatal("optional cached credit escaped command pressure", class)
}
}
if b.optional(*now) != 0 || b.reserve(*now) < 512 || !b.commandLimited(*now) {
t.Fatal("critical stream was not independently protected")
}
// A reply on another socket cannot reopen the gate or raise the estimate.
low := b.effective
for i := 0; i < 40; i++ {
*now = now.Add(100 * time.Millisecond)
b.SetControl(true)
b.ObserveExchange(20*time.Millisecond, 0, true)
}
if b.optional(*now) != 0 || b.effective > low {
t.Fatal("healthy telemetry concealed absent commands")
}
}
func TestCommandRecoveryNeedsContinuousFreshFramesNotOneLateBurst(t *testing.T) {
b, now := testBudget(t)
b.SetControl(true)
b.ObserveCommandFrame(200*time.Millisecond, 20*time.Millisecond)
low := b.effective
for i := 0; i < 30; i++ {
*now = now.Add(10 * time.Millisecond)
b.ObserveCommandFrame(0, 200*time.Millisecond)
}
if !b.commandLimited(*now) {
t.Fatal("buffered old frames reopened optional traffic")
}
for i := 0; i < 21; i++ {
*now = now.Add(50 * time.Millisecond)
b.SetControl(true)
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
if i < 4 && !b.commandLimited(*now) {
t.Fatal("recovery dwell skipped", i)
}
}
if b.commandLimited(*now) || b.effective > low || b.optional(*now) <= 0 {
t.Fatal("fresh recovery did not resume at reduced budget")
}
}
func TestIsolatedCommandJitterYieldsWithoutCollapsingCapacity(t *testing.T) {
b, now := testBudget(t)
b.SetControl(true)
initial := b.effective
// One delayed frame per second, with fresh command flow in between. This
// formerly held the gate shut forever and drove capacity to its floor.
for cycle := 0; cycle < 20; cycle++ {
*now = now.Add(150 * time.Millisecond)
b.SetControl(true)
b.ObserveCommandFrame(150*time.Millisecond, 170*time.Millisecond)
if ok, _ := b.Try("video", 100); ok {
t.Fatal("delayed command did not yield optional traffic")
}
for i := 0; i < 17; i++ {
*now = now.Add(50 * time.Millisecond)
b.ObserveCommandFrame(50*time.Millisecond, 80*time.Millisecond)
}
if b.commandLimited(*now) || b.effective != initial {
t.Fatal("isolated jitter was mistaken for sustained congestion", cycle, b.effective)
}
if ok, _ := b.Try("video", 100); !ok {
t.Fatal("fresh command flow did not return optional capacity")
}
}
}
func TestSustainedCommandPressureStillReducesCapacity(t *testing.T) {
for _, silence := range []bool{false, true} {
b, now := testBudget(t)
b.SetControl(true)
initial := b.effective
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
for i := 0; i < 30; i++ {
*now = now.Add(50 * time.Millisecond)
b.SetControl(true)
if silence {
b.ObserveCommandSilence()
} else {
b.ObserveCommandFrame(50*time.Millisecond, 200*time.Millisecond)
}
}
if !b.commandLimited(*now) || b.effective >= initial || b.optional(*now) != 0 {
t.Fatal("sustained command pressure was ignored", silence)
}
}
}
func TestIsolatedCommandJitterDoesNotEraseCapacityRecovery(t *testing.T) {
b, now := testBudget(t)
b.effective = 1000
for i := 0; i < 400; i++ {
*now = now.Add(50 * time.Millisecond)
b.SetControl(true)
b.allocateDemand(testClockID, "video", true, 5000000)
age := 80 * time.Millisecond
if i%20 == 0 {
age = 170 * time.Millisecond
}
b.ObserveCommandFrame(50*time.Millisecond, age)
b.ObserveExchange(80*time.Millisecond, 0, true)
}
if b.effective < 4000 || b.reserve(*now) < 512 {
t.Fatal("isolated command jitter erased measured exchange recovery", b.effective)
}
}
func TestIdleObservationDoesNotSacrificeVideoForCommandJitter(t *testing.T) {
b, now := testBudget(t)
b.SetControl(false)
before := b.optional(*now)
b.ObserveCommandFrame(time.Second, time.Second)
*now = now.Add(time.Second)
b.ObserveCommandSilence()
if b.commandLimited(*now) || b.optional(*now) != before {
t.Fatal("idle command gap degraded observation")
}
}
func TestLocalCommandPressurePreservesExpiryAndNoAutomaticRearm(t *testing.T) {
sensors, model, s, at := localDeliveryFixture(t)
b, now := testBudget(t)
*now = at
b.at = at
s.budget = b
s.devID, s.devEnabled = testClockID, true
s.receivedFrame(streamIntent(1331, 10000, 10400), at)
calls := 0
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
calls++
return testSensorReply(map[string]any{"state": "driving"}), nil
})
var d roverLocalDelivery
d.run(context.Background(), sensors, model, s, "relay", at)
*now = at.Add(160 * time.Millisecond)
d.run(context.Background(), sensors, model, s, "relay", *now)
if calls != 1 || !b.commandLimited(*now) {
t.Fatal("pressure changed duplicate delivery or ignored local tick")
}
*now = at.Add(401 * time.Millisecond)
d.run(context.Background(), sensors, model, s, "relay", *now)
if calls != 2 || s.stopCause != "command_deadline_expired" {
t.Fatal("command expiry changed")
}
late := streamIntent(1332, 10401, 10801)
s.accept(late)
s.receivedFrame(late, *now)
_, command, _ := s.delivery(*now)
if command != nil || s.devEvents[len(s.devEvents)-1]["retired"] != true {
t.Fatal("late input revived authority or missing receipt evidence")
}
}
func TestReceiptEvidenceIsDevOnlyAndUsesCoreClockBound(t *testing.T) {
for _, enabled := range []bool{false, true} {
at := time.Now()
s := newRoverStreamState(at)
s.sampleClock(roverClock{testClockID, 10020}, at, at.Add(40*time.Millisecond))
acknowledgeStop(s, at)
s.devID, s.devEnabled = testClockID, enabled
s.receivedFrame(streamIntent(1, 10050, 10400), at.Add(100*time.Millisecond))
if !enabled && len(s.devEvents) != 0 {
t.Fatal("DEV-off stored per-frame evidence")
}
if enabled {
row := s.devEvents[0]
if row["age_upper_ms"].(float64) < 70 || row["received_mono_ms"] != float64(100) {
t.Fatal("receipt clock bound lost", row)
}
}
}
}
@@ -0,0 +1,164 @@
package node
// Independently bound optional egress when command UDP remains healthy but the
// return path is congested. Probes never wait for permits; no authority lives here.
import "time"
const feedbackMinWindow = uint64(linkPacket + linkOverhead)
const feedbackMaxWindow = uint64(128 * 1024)
type linkDatagramFeedback struct {
enabled bool
seen, adjusted, healthy, delayed time.Time
sent, acknowledged, window uint64
rtt time.Duration
limited bool
pressure linkFeedbackPressure
}
// Retain only the last initiating pressure event. Later healthy samples must
// not erase why media was paused; this is evidence, never admission credit.
type linkFeedbackPressure struct {
count uint64
at time.Time
reason string
gap, rtt, threshold time.Duration
window uint64
}
func (h *linkDatagramFeedback) recordPressure(now time.Time, reason string, gap, rtt, threshold time.Duration) {
if h.limited {
return
}
h.pressure = linkFeedbackPressure{count: h.pressure.count + 1, at: now,
reason: reason, gap: gap, rtt: rtt, threshold: threshold, window: h.window}
}
func (h *linkDatagramFeedback) pressureView(now time.Time) any {
p := h.pressure
if p.at.IsZero() {
return nil
}
return map[string]any{"count": p.count, "reason": p.reason, "age_ms": now.Sub(p.at).Milliseconds(),
"gap_ms": p.gap.Milliseconds(), "rtt_ms": p.rtt.Milliseconds(),
"threshold_ms": p.threshold.Milliseconds(), "window_bytes": p.window}
}
func (b *LinkBudget) EnableDatagramFeedback() {
if b == nil {
return
}
b.mu.Lock()
defer b.mu.Unlock()
if !b.runtime.feedback.enabled {
b.runtime.feedback = linkDatagramFeedback{enabled: true, seen: b.now(), window: linkClassBurst}
}
}
func (b *LinkBudget) DisableDatagramFeedback() {
if b == nil {
return
}
b.mu.Lock()
defer b.mu.Unlock()
b.runtime.feedback = linkDatagramFeedback{}
}
func (b *LinkBudget) DatagramFeedbackMark() uint64 {
if b == nil {
return 0
}
b.mu.Lock()
defer b.mu.Unlock()
return b.runtime.feedback.sent
}
func (b *LinkBudget) feedbackLimited(now time.Time) bool {
h := &b.runtime.feedback
if !h.enabled {
return false
}
if now.Sub(h.seen) > max(250*time.Millisecond, b.baseline+150*time.Millisecond) {
h.recordPressure(now, "feedback_silence", now.Sub(h.seen), h.rtt, max(250*time.Millisecond, b.baseline+150*time.Millisecond))
// A silent return path invalidates the previously grown send window.
// Latch pressure before updating seen: one fresh ACK after a blackout
// must not release old optional credit as a burst. Caller holds b.mu.
h.limited = true
h.healthy = time.Time{}
h.window = min(h.window, uint64(linkClassBurst))
h.adjusted = now
b.healthy = time.Time{}
b.tokens = 0
for _, c := range b.classes {
c.tokens = 0
}
b.at = now
}
return h.limited
}
func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float64, mark uint64) {
if b == nil {
return
}
// Use the existing exchange estimator with the measured Core scheduling wait
// removed. No RTT/2 correction is used for command or observation clocks.
b.ObserveExchange(elapsed, coreMS, true)
b.mu.Lock()
defer b.mu.Unlock()
h := &b.runtime.feedback
if !h.enabled || mark > h.sent || mark < h.acknowledged {
return
}
now := b.now()
b.feedbackLimited(now)
outstanding := h.sent - h.acknowledged
gap := now.Sub(h.seen)
h.acknowledged = mark
h.seen = now
if coreMS >= 0 && coreMS <= float64(elapsed.Microseconds())/1000 {
elapsed -= time.Duration(coreMS * float64(time.Millisecond))
}
h.rtt = elapsed
if elapsed > b.baseline+75*time.Millisecond {
if h.delayed.IsZero() {
h.delayed = now
}
// Moderate jitter shrinks outstanding optional bytes without turning a
// viable video stream off. Full suspension is reserved for severe delay
// or silence; neither condition changes command authority or watchdogs.
if elapsed > max(250*time.Millisecond, b.baseline+150*time.Millisecond) {
h.recordPressure(now, "feedback_rtt", gap, elapsed, max(250*time.Millisecond, b.baseline+150*time.Millisecond))
h.limited = true
h.healthy = time.Time{}
}
b.healthy = time.Time{}
// Delay-based admission must not mistake isolated RTT jitter for a
// growing queue. Require a sustained trend before reducing its window;
// severe delay and silence still suspend optional traffic immediately.
if h.limited || now.Sub(h.delayed) >= 200*time.Millisecond {
if h.adjusted.IsZero() || now.Sub(h.adjusted) >= 200*time.Millisecond {
h.window = max(feedbackMinWindow, h.window/2)
h.adjusted = now
}
b.tokens = 0
for _, c := range b.classes {
c.tokens = 0
}
b.at = now
}
return
}
h.delayed = time.Time{}
if h.limited {
if h.healthy.IsZero() {
h.healthy = now
}
if now.Sub(h.healthy) < 200*time.Millisecond {
return
}
h.limited = false
}
// Grow only when useful demand used the window, at most once per probe
// period. ACK bursts after a stall cannot manufacture a large new window.
if elapsed <= b.baseline+25*time.Millisecond && outstanding >= h.window/2 && (h.adjusted.IsZero() || now.Sub(h.adjusted) >= 100*time.Millisecond) {
h.window = min(feedbackMaxWindow, h.window+linkPacket)
h.adjusted = now
}
}
@@ -0,0 +1,157 @@
package node
import (
"testing"
"time"
)
func TestDatagramFeedbackBoundsOptionalBytesDespiteHealthyDownlink(t *testing.T) {
b, now := testBudget(t)
b.EnableDatagramFeedback()
b.SetControl(true)
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
initial := b.runtime.feedback.window
// Pre-fill tokens as an already active producer; acknowledgement credit
// remains the independent upper bound across all optional classes.
for _, class := range []string{"video", "bulk", "cloud", "inventory"} {
b.classes[class].tokens = linkClassBurst
b.classes[class].seen = *now
b.classes[class].wanted = 1000000
}
b.tokens = linkBurst
for i := 0; i < 20; i++ {
b.Try("video", 1100)
}
sent := b.DatagramFeedbackMark()
if sent == 0 || sent > initial {
t.Fatal("window bypass", sent, initial)
}
*now = now.Add(300 * time.Millisecond)
b.ObserveCommandFrame(50*time.Millisecond, 10*time.Millisecond)
if !b.feedbackLimited(*now) {
t.Fatal("fresh downlink erased return-path silence")
}
if ok, _ := b.Try("video", 1100); ok {
t.Fatal("video bypassed feedback silence")
}
b.ObserveDatagramFeedback(300*time.Millisecond, 0, sent)
if !b.runtime.feedback.limited {
t.Fatal("delayed echo did not apply pressure")
}
for i := 0; i < 3; i++ {
b.ObserveDatagramFeedback(100*time.Millisecond, 0, sent)
}
if !b.runtime.feedback.limited {
t.Fatal("queued ACK burst reopened video")
}
*now = now.Add(201 * time.Millisecond)
b.ObserveDatagramFeedback(100*time.Millisecond, 0, sent)
if b.runtime.feedback.limited {
t.Fatal("sustained fresh feedback did not recover")
}
if b.runtime.feedback.window < feedbackMinWindow {
t.Fatal("packet cannot fit")
}
b.DisableDatagramFeedback()
if b.feedbackLimited(now.Add(time.Hour)) {
t.Fatal("closed channel retained feedback gate")
}
}
func TestDatagramFeedbackSilenceLatchesBeforeFreshEcho(t *testing.T) {
for _, poll := range []bool{false, true} {
t.Run(map[bool]string{false: "idle-budget", true: "active-producer"}[poll], func(t *testing.T) {
b, now := testBudget(t)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
b.runtime.feedback.window = feedbackMaxWindow
b.tokens = linkBurst
b.classes["video"].tokens = linkClassBurst
*now = now.Add(time.Second)
if poll {
b.Snapshot()
}
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
if !b.runtime.feedback.limited || b.runtime.feedback.window > linkClassBurst {
t.Fatal("fresh echo restored the old send window", b.runtime.feedback)
}
if b.tokens != 0 || b.classes["video"].tokens != 0 {
t.Fatal("old burst credit survived silence")
}
for i := 0; i < 20; i++ {
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
}
if !b.runtime.feedback.limited {
t.Fatal("ACK burst recovered without elapsed healthy time")
}
*now = now.Add(201 * time.Millisecond)
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
if b.runtime.feedback.limited {
t.Fatal("continuous healthy feedback did not recover")
}
})
}
}
func TestDatagramFeedbackModerateJitterPreservesVideoAllocation(t *testing.T) {
b, now := testBudget(t)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
b.runtime.feedback.window = 32768
*now = now.Add(100 * time.Millisecond)
b.ObserveDatagramFeedback(110*time.Millisecond, 0, 0)
if b.runtime.feedback.limited || b.optional(*now) <= 0 {
t.Fatal("one moderate delay disabled optional media")
}
if b.runtime.feedback.window != 32768 {
t.Fatal("isolated jitter collapsed the media window")
}
for i := 0; i < 2; i++ {
*now = now.Add(100 * time.Millisecond)
b.ObserveDatagramFeedback(110*time.Millisecond, 0, 0)
}
if b.runtime.feedback.window >= 32768 || b.optional(*now) <= 0 {
t.Fatal("sustained moderate delay must reduce, not disable, media")
}
*now = now.Add(100 * time.Millisecond)
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
if !b.runtime.feedback.limited || b.optional(*now) != 0 {
t.Fatal("severe return delay did not suspend media")
}
}
func TestDatagramFeedbackRetainsInitiatingPressureAcrossRecovery(t *testing.T) {
b, now := testBudget(t)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
if b.runtime.feedback.pressureView(*now) != nil {
t.Fatal("invented pressure")
}
*now = now.Add(300 * time.Millisecond)
b.feedbackLimited(*now)
first := b.runtime.feedback.pressure
if first.count != 1 || first.reason != "feedback_silence" || first.gap != 300*time.Millisecond || first.threshold != 250*time.Millisecond {
t.Fatal("missing initiating silence", first)
}
b.feedbackLimited(*now)
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
if b.runtime.feedback.pressure != first {
t.Fatal("poll or delayed ACK overwrote initiating event")
}
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
*now = now.Add(201 * time.Millisecond)
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
if b.runtime.feedback.limited || b.runtime.feedback.pressure != first {
t.Fatal("recovery lost evidence or retained gate")
}
*now = now.Add(100 * time.Millisecond)
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
second := b.runtime.feedback.pressure
if second.count != 2 || second.reason != "feedback_rtt" || second.rtt != 300*time.Millisecond || second.gap != 100*time.Millisecond {
t.Fatal("new pressure not retained", second)
}
b.DisableDatagramFeedback()
if b.runtime.feedback.pressureView(*now) != nil {
t.Fatal("new transport would inherit old diagnostic identity")
}
}
@@ -0,0 +1,183 @@
package node
import (
"bytes"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestExplicitOperatorViewPrecedesResidualTraffic(t *testing.T) {
b, now := testBudget(t)
primary, secondary, cloud := "11111111111111111111111111111111", "22222222222222222222222222222222", "33333333333333333333333333333333"
b.allocateRole(secondary, "video", true, 5000000, false)
b.allocateRole(primary, "video", true, 5000000, true)
b.allocateRole(cloud, "cloud", true, 2000000, false)
b.RequestDemand("inventory", 1000)
b.Try("inventory", 1000)
b.RequestDemand("bulk", 1000)
b.Try("bulk", 1000)
a, _ := b.allocateRole(primary, "video", true, 5000000, true)
c, _ := b.allocateRole(secondary, "video", true, 5000000, false)
rates := b.classRates(*now)
if a["allocation_bps"].(int) <= 0 || c["allocation_bps"] != 0 || rates["cloud"] != 0 || rates["bulk"] != 0 || rates["inventory"] <= 0 || a["class_producers"] != 2 {
t.Fatal(a, c, rates)
}
*now = now.Add(time.Millisecond)
b.allocateRole(secondary, "video", true, 5000000, true)
if b.primaryVideo(*now) != secondary {
t.Fatal("selection did not supersede earlier primary")
}
b.allocateRole(secondary, "video", false, 5000000, true)
if b.primaryVideo(*now) != primary {
t.Fatal("released view retained priority")
}
*now = now.Add(producerTTL)
if b.primaryVideo(*now) != "" {
t.Fatal("expired view retained priority")
}
}
func TestSelectedViewHasBoundedModerateJitterProfileAndEmergencyYield(t *testing.T) {
b, now := testBudget(t)
primary := "11111111111111111111111111111111"
b.allocateRole(primary, "video", true, 5000000, true)
b.SetControl(true)
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
*now = now.Add(160 * time.Millisecond)
b.ObserveCommandSilence()
if rate := b.optional(*now); rate <= 0 || rate > 384 {
t.Fatal("invalid low profile", rate)
}
permit := func(id string) bool {
raw, _ := json.Marshal(map[string]any{"class": "video", "bytes": 100, "producer_id": id})
w := httptest.NewRecorder()
b.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/permit", bytes.NewReader(raw)))
var reply map[string]any
json.Unmarshal(w.Body.Bytes(), &reply)
return reply["granted"] == true
}
if permit("") {
t.Fatal("unidentified video borrowed priority")
}
if permit(primary) {
t.Fatal("pre-pressure time restored discarded credit")
}
*now = now.Add(20 * time.Millisecond)
if !permit(primary) {
t.Fatal("selected video could not use low profile")
}
for _, class := range []string{"cloud", "bulk", "inventory"} {
if ok, _ := b.Try(class, 100); ok {
t.Fatal("background escaped pressure", class)
}
}
*now = now.Add(70 * time.Millisecond)
b.ObserveCommandSilence()
if b.optional(*now) != 0 || permit(primary) {
t.Fatal("video escaped 250 ms emergency yield")
}
}
func TestLocalRecorderSendsOnlyLifecycleAndStopsPollingClosedFile(t *testing.T) {
s := newRoverStreamState(time.Now())
options := map[string]any{"live": false, "network": true}
s.setDev(map[string]any{"id": testClockID, "enabled": true, "options": options})
s.recordDev("network", map[string]any{})
if len(s.devRequest()["relay_events"].([]map[string]any)) != 1 {
t.Fatal("local evidence omitted")
}
p := s.devPayload()
if len(p["relay_events"].([]any)) != 0 || len(p["frames"].([]any)) != 0 || diagnosticTrafficClass(p) != "inventory" {
t.Fatal("local recording streamed events", p)
}
s.devPacket = map[string]any{"sequence": 100, "storage": map[string]any{"closed": true}}
s.setDev(map[string]any{"id": testClockID, "enabled": false, "options": options, "after": 0})
if s.devRequest() != nil {
t.Fatal("closed local recording kept polling")
}
if diagnosticTrafficClass(map[string]any{"export": map[string]any{"data": "abc"}}) != "bulk" {
t.Fatal("export escaped bulk lane")
}
}
// Real-drive regression: a selected view used all optional capacity forever,
// so a closed local recording could not export even with control inactive.
func TestObservedPrimaryAllowsBoundedExportAtCongestedFloor(t *testing.T) {
b, now := testBudget(t)
b.effective = 640
primary := "11111111111111111111111111111111"
left, inventory, video := 108*1024, 0, 0
b.RequestDemand("bulk", left)
b.RequestDemand("inventory", 40*1024)
deadline := pacedTimeout(left)
for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond {
*now = now.Add(10 * time.Millisecond)
b.SetControl(false)
b.allocateRole(primary, "video", true, 5000000, true)
// Persistent demand, including primary video always attempting first.
for n := 0; n < 4; n++ {
if ok, _ := b.Try("video", 1200); ok {
video += 1200
}
}
if inventory < 40*1024 {
size := min(linkPacket, 40*1024-inventory)
if ok, _ := b.Try("inventory", size); ok {
inventory += size
}
}
if left > 0 {
if ok, _ := b.Try("bulk", min(linkPacket, left)); ok {
left -= min(linkPacket, left)
}
}
}
if left != 0 || inventory != 40*1024 || video == 0 {
t.Fatal("observer export/metadata starved", left, inventory, video)
}
var bytes uint64
for _, c := range b.classes {
bytes += c.bytes
}
if float64(bytes) > 128*125*deadline.Seconds()+linkBurst {
t.Fatal("shared budget exceeded", bytes)
}
b.SetControl(true)
b.Try("bulk", 1000)
if b.classRates(*now)["bulk"] != 0 {
t.Fatal("export displaced primary during active control")
}
}
func TestCommandPrimaryLowRateProgressUnderPersistentModerateAge(t *testing.T) {
b, now := testBudget(t)
b.effective = 640 // Existing floor: 512 reserved + 128 optional kbps.
primary := "11111111111111111111111111111111"
b.allocateRole(primary, "video", true, 4000000, true)
b.SetControl(true)
handler := b.Handler()
admitted := 0
for step := 0; step < 400; step++ {
*now = now.Add(5 * time.Millisecond)
if step%10 == 0 {
b.SetControl(true)
b.ObserveCommandFrame(50*time.Millisecond, 180*time.Millisecond)
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, httptest.NewRequest("POST", "/permit", strings.NewReader(`{"class":"video","bytes":1100,"producer_id":"11111111111111111111111111111111"}`)))
var reply struct {
Granted bool `json:"granted"`
}
json.Unmarshal(rr.Body.Bytes(), &reply)
if reply.Granted {
admitted += 1100
}
}
t.Logf("moderate-age primary payload over 2 s: %d bytes; optional %.0f kbps", admitted, b.optional(*now))
if admitted < 1100 || admitted+admitted/1100*linkOverhead > 32000 {
t.Fatal("declared low profile starved or exceeded its aggregate budget", admitted)
}
}
@@ -0,0 +1,154 @@
package node
// Producer leases provide sizing advice from the existing class budget. They
// never reserve packet tokens, add queues, change control, or outlive a process.
import (
"encoding/hex"
"encoding/json"
"errors"
"math"
"net/http"
"time"
)
const producerTTL = 3 * time.Second
const maxLinkProducers = 32
type linkProducer struct {
class string
seen time.Time
demand int
since time.Time
primary bool
selected time.Time
}
func (b *LinkBudget) allocate(id, class string, active bool) (map[string]any, error) {
return b.allocateDemand(id, class, active, 0)
}
func (b *LinkBudget) allocateDemand(id, class string, active bool, demand int) (map[string]any, error) {
return b.allocateRole(id, class, active, demand, false)
}
func (b *LinkBudget) primaryVideo(now time.Time) string {
selected := ""
for id, p := range b.producers {
if p.class != "video" || !p.primary || now.Sub(p.seen) >= producerTTL {
continue
}
if selected == "" || p.selected.After(b.producers[selected].selected) || (p.selected.Equal(b.producers[selected].selected) && id < selected) {
selected = id
}
}
return selected
}
func (b *LinkBudget) allocateRole(id, class string, active bool, demand int, operatorPrimary bool) (map[string]any, error) {
if operatorPrimary && class != "video" {
return nil, errors.New("primary must be video")
}
if demand < 0 || demand > 100000000 {
return nil, errors.New("invalid media demand")
}
if demand == 0 {
demand = 5000000
if class == "cloud" {
demand = 2000000
}
}
if raw, err := hex.DecodeString(id); err != nil || len(raw) != 16 || (class != "video" && class != "cloud") {
return nil, errors.New("invalid media producer")
}
b.mu.Lock()
defer b.mu.Unlock()
now := b.now()
for key, p := range b.producers {
if now.Sub(p.seen) >= producerTTL {
delete(b.producers, key)
}
}
if old, exists := b.producers[id]; exists && old.class != class {
return nil, errors.New("producer class changed")
}
if !active {
delete(b.producers, id)
return map[string]any{"schema": "missioncore.media-budget/v1", "allocation_bps": 0, "ttl_ms": 0}, nil
}
if _, exists := b.producers[id]; !exists && len(b.producers) >= maxLinkProducers {
return nil, errors.New("media producer capacity")
}
b.refill(now)
since := now
if old, exists := b.producers[id]; exists {
since = old.since
}
selected := now
if old, exists := b.producers[id]; exists && old.primary == operatorPrimary {
selected = old.selected
}
b.producers[id] = linkProducer{class: class, seen: now, demand: demand, since: since, primary: operatorPrimary, selected: selected}
weights, demands := map[string]float64{}, map[string]float64{}
primary := ""
for key, p := range b.producers {
if p.class != class {
continue
}
weights[key] = 1
demands[key] = float64(p.demand)
if primary == "" || p.since.Before(b.producers[primary].since) || (p.since.Equal(b.producers[primary].since) && key < primary) {
primary = key
}
}
explicit := b.primaryVideo(now)
if class == "video" && explicit != "" {
primary = explicit
}
rate := b.classRates(now)[class]
// When there is insufficient useful video for every viewer, retain the oldest
// active view. Additional viewers wait without resetting acquisition/recording.
count := len(weights)
minimum := 512000.0
shares := map[string]float64{}
if class == "video" && explicit != "" {
shares[primary] = math.Min(rate, demands[primary])
delete(weights, primary)
delete(demands, primary)
for key, value := range waterfill(rate-shares[primary], weights, demands) {
shares[key] = value
}
} else if class == "video" && rate < minimum*float64(len(weights)) {
shares[primary] = math.Min(rate, demands[primary])
} else {
shares = waterfill(rate, weights, demands)
}
mode := "observing"
if b.protected(now) {
mode = "control_reserved"
}
return map[string]any{"schema": "missioncore.media-budget/v1", "allocation_bps": int(shares[id]),
"ttl_ms": producerTTL.Milliseconds(), "class_producers": count, "mode": mode,
"primary": id == primary, "reason": b.runtime.reason}, nil
}
func (b *LinkBudget) producerRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /producer", func(w http.ResponseWriter, r *http.Request) {
var v struct {
ID string `json:"id"`
Class string `json:"class"`
Active *bool `json:"active"`
Demand int `json:"demand_bps"`
Primary bool `json:"primary"`
}
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256))
d.DisallowUnknownFields()
if d.Decode(&v) != nil || v.Active == nil {
reply(w, 400, map[string]string{"error": "invalid media producer"})
return
}
result, err := b.allocateRole(v.ID, v.Class, *v.Active, v.Demand, v.Primary)
if err != nil {
reply(w, 409, map[string]string{"error": err.Error()})
return
}
reply(w, 200, result)
})
}
@@ -0,0 +1,68 @@
package node
import (
"fmt"
"testing"
"time"
)
func TestMediaProducersShareOneBudgetAndExpire(t *testing.T) {
b, _ := OpenLinkBudget("")
now := time.Now()
b.now = func() time.Time { return now }
b.at = now
id := func(i int) string { return fmt.Sprintf("%032x", i) }
for i := 1; i <= 2; i++ {
if _, err := b.allocate(id(i), "video", true); err != nil {
t.Fatal(err)
}
}
if _, err := b.allocate(id(3), "cloud", true); err != nil {
t.Fatal(err)
}
b.Try("bulk", 100)
a, _ := b.allocate(id(1), "video", true)
c, _ := b.allocate(id(3), "cloud", true)
if a["allocation_bps"] != 1220800 || c["allocation_bps"] != 697600 || b.tokens != 0 {
t.Fatal("advice must divide existing class budget without minting permits", a, c, b.tokens)
}
b.allocate(id(2), "video", false)
a, _ = b.allocate(id(1), "video", true)
if a["allocation_bps"] != 2441600 {
t.Fatal(a)
}
now = now.Add(4 * time.Second)
a, _ = b.allocate(id(1), "video", true)
if len(b.producers) != 1 || a["allocation_bps"] != 3488000 {
t.Fatal("expired producer retained capacity", a)
}
for i := 0; i < 3; i++ {
now = now.Add(time.Second)
b.Observe(time.Second, false)
}
a, _ = b.allocate(id(1), "video", true)
if a["allocation_bps"].(int) >= 3488000 {
t.Fatal("allocation ignored congestion", a)
}
}
func TestMediaProducerAdmissionIsBoundedAndHasNoControlClass(t *testing.T) {
b, _ := OpenLinkBudget("")
for i := 0; i < maxLinkProducers; i++ {
if _, err := b.allocate(fmt.Sprintf("%032x", i), "video", true); err != nil {
t.Fatal(err)
}
}
if _, err := b.allocate(fmt.Sprintf("%032x", 99), "video", true); err == nil {
t.Fatal("unbounded producer registry")
}
if _, err := b.allocate(fmt.Sprintf("%032x", 0), "cloud", true); err == nil {
t.Fatal("producer changed class")
}
if _, err := b.allocate(fmt.Sprintf("%032x", 0), "control", true); err == nil {
t.Fatal("control allocation admitted")
}
if _, err := b.allocate("bad", "video", true); err == nil {
t.Fatal("bad identifier admitted")
}
}
@@ -0,0 +1,338 @@
package node
// Runtime policy for the existing egress gate. Rates are send budgets, not a
// claim to have measured physical link capacity. No command authority lives here.
import (
"math"
"time"
)
type linkSample struct {
at time.Time
elapsed time.Duration
ok bool
}
type linkDecision struct {
AtMS int64 `json:"at_ms"`
Reason string `json:"reason"`
Kbps int `json:"kbps"`
}
type linkRuntime struct {
feedback linkDatagramFeedback
command linkCommandHealth
criticalAt time.Time
criticalBytes int
criticalKbps float64
lastProtected bool
control bool
modeAt time.Time
samples []linkSample
errors int
reason string
events []linkDecision
started time.Time
coreMS float64
}
func (b *LinkBudget) ceiling() float64 {
if b.policy.CeilingKbps == 0 {
return 100000
} // Contract bound, not inferred capacity.
return float64(b.policy.CeilingKbps)
}
func (b *LinkBudget) protected(now time.Time) bool {
return b.runtime.modeAt.IsZero() || now.Sub(b.runtime.modeAt) > 2*time.Second || b.runtime.control
}
func (b *LinkBudget) reserve(now time.Time) float64 {
if b.protected(now) {
return math.Max(float64(b.policy.ReserveKbps), b.runtime.criticalKbps*1.5)
}
if b.runtime.criticalAt.IsZero() {
return float64(b.policy.ReserveKbps)
}
return math.Max(64, b.runtime.criticalKbps*1.5) // Actual critical traffic plus margin, never an idle constant alone.
}
// Critical bytes are observed, never paced or rejected by this regulator.
func (b *LinkBudget) ObserveCriticalBytes(size int) {
if b == nil || size <= 0 {
return
}
b.mu.Lock()
defer b.mu.Unlock()
now := b.now()
if b.runtime.criticalAt.IsZero() {
b.runtime.criticalAt = now
b.runtime.criticalKbps = float64(b.policy.ReserveKbps) / 1.5
}
b.runtime.criticalBytes += size + ((size+1199)/1200)*linkOverhead
elapsed := now.Sub(b.runtime.criticalAt).Seconds()
if elapsed >= 1 {
rate := float64(b.runtime.criticalBytes) * 8 / 1000 / elapsed
// Follow growth immediately; decay slowly so a quiet sample cannot under-size admission.
b.runtime.criticalKbps = math.Max(rate, b.runtime.criticalKbps*.8)
b.runtime.criticalAt = now
b.runtime.criticalBytes = 0
}
}
func (b *LinkBudget) optional(now time.Time) float64 {
if b.feedbackLimited(now) {
return 0
}
ceiling := math.Max(0, b.effective-b.reserve(now))
if b.runtime.feedback.enabled {
// A bounded acknowledgement window constrains useful optional traffic.
// This is admission credit, never a claim of measured wire capacity.
period := max(100*time.Millisecond, b.baseline)
ceiling = math.Min(ceiling, float64(b.runtime.feedback.window)*8/period.Seconds()/1000)
}
if b.commandLimited(now) {
// A selected operator view gets only a bounded low profile during
// moderate jitter. At 250 ms silence/age all optional payload yields.
// The 400 ms command lease and 350/200 ms watchdogs are unchanged.
h := b.runtime.command
emergency := h.gap >= 250*time.Millisecond || h.age >= 250*time.Millisecond ||
(!h.seen.IsZero() && now.Sub(h.seen) >= 250*time.Millisecond)
if emergency || b.primaryVideo(now) == "" {
return 0
}
return math.Min(384, ceiling)
}
return ceiling
}
func (b *LinkBudget) SetControl(active bool) {
if b == nil {
return
}
b.mu.Lock()
defer b.mu.Unlock()
now := b.now()
was := b.protected(now)
b.runtime.control, b.runtime.modeAt = active, now
if !active {
// An intentionally closed observer stream is not packet loss. Do not
// retain pressure/old receipt timestamps across completed sessions.
b.runtime.command = linkCommandHealth{}
}
if !was && active {
b.tokens = 0
for _, c := range b.classes {
c.tokens = 0
}
}
}
func (b *LinkBudget) decision(now time.Time, reason string, next float64) {
if b.runtime.started.IsZero() {
b.runtime.started = now
}
if next < b.effective {
b.tokens = 0
for _, c := range b.classes {
c.tokens = 0
}
}
b.effective = next
b.changed = now
b.runtime.reason = reason
b.runtime.events = append(b.runtime.events, linkDecision{now.Sub(b.runtime.started).Milliseconds(), reason, int(next)})
if len(b.runtime.events) > 32 {
b.runtime.events = b.runtime.events[len(b.runtime.events)-32:]
}
}
// Observe remains for transport failures / older Core peers. Application errors
// are deliberately excluded by the caller; they are not bandwidth evidence.
func (b *LinkBudget) Observe(elapsed time.Duration, ok bool) { b.ObserveExchange(elapsed, 0, ok) }
func (b *LinkBudget) ObserveExchange(elapsed time.Duration, coreMS float64, ok bool) {
if b == nil {
return
}
b.mu.Lock()
defer b.mu.Unlock()
now := b.now()
if math.IsNaN(coreMS) || math.IsInf(coreMS, 0) || coreMS < 0 || coreMS > float64(elapsed.Microseconds())/1000 {
coreMS = 0
}
b.runtime.coreMS = coreMS
elapsed -= time.Duration(coreMS * float64(time.Millisecond))
samples := b.runtime.samples[:0]
for _, v := range b.runtime.samples {
if now.Sub(v.at) < 30*time.Second {
samples = append(samples, v)
}
}
samples = append(samples, linkSample{now, elapsed, ok})
if len(samples) > 320 {
samples = samples[len(samples)-320:]
}
b.runtime.samples = samples
b.baseline = 0
for _, v := range samples {
if v.ok && (b.baseline == 0 || v.elapsed < b.baseline) {
b.baseline = v.elapsed
}
}
if ok {
b.runtime.errors = 0
} else {
b.runtime.errors++
}
total, bad := 0, 0
var first time.Time
for _, v := range samples {
if now.Sub(v.at) > 2*time.Second {
continue
}
if first.IsZero() {
first = v.at
}
total++
if !v.ok || v.elapsed > b.baseline+150*time.Millisecond {
bad++
}
}
ready := total >= 4 && now.Sub(first) >= time.Second
congested := b.runtime.errors >= 3 || (ready && bad*2 >= total)
if congested && now.Sub(b.changed) >= time.Second {
next := math.Max(float64(b.policy.ReserveKbps+128), b.effective*.75)
if next < b.effective {
b.refill(now)
b.decision(now, "sustained_delay_or_transport_loss", next)
}
b.healthy = time.Time{}
} else if ready && bad*5 <= total && !b.commandLimited(now) && !b.feedbackLimited(now) {
if b.healthy.IsZero() {
b.healthy = now
}
if now.Sub(b.healthy) >= 2*time.Second && now.Sub(b.changed) >= 2*time.Second {
// Bounded useful-traffic probing. Do not manufacture dummy network load or
// ramp indefinitely on a quiet scene / when nobody requests optional data.
demand := b.demand(now)/1000 + b.reserve(now)
next := math.Min(b.ceiling(), math.Min(demand, b.effective+math.Max(128, b.effective*.20)))
if next > b.effective {
b.refill(now)
b.decision(now, "healthy_demand_probe", next)
}
}
}
// An isolated outlier neither reduces the budget nor erases recovery progress.
}
func (b *LinkBudget) runtimeView(now time.Time) map[string]any {
mode := "observing"
if b.protected(now) {
mode = "control_reserved"
}
return map[string]any{"schema": "missioncore.link-runtime/v1", "direction": "node_egress",
"feedback_limited": b.feedbackLimited(now), "feedback_window_bytes": b.runtime.feedback.window, "feedback_outstanding_bytes": b.runtime.feedback.sent - b.runtime.feedback.acknowledged, "feedback_rtt_ms": b.runtime.feedback.rtt.Milliseconds(),
"feedback_pressure": b.runtime.feedback.pressureView(now),
"command_limited": b.commandLimited(now), "command_gap_ms": b.runtime.command.gap.Milliseconds(),
"command_age_upper_ms": b.runtime.command.age.Milliseconds(),
"mode": mode, "reserve_kbps": int(b.reserve(now)), "reason": b.runtime.reason,
"core_processing_ms": b.runtime.coreMS, "samples": len(b.runtime.samples), "automatic": b.policy.CeilingKbps == 0,
"critical_offered_kbps": int(b.runtime.criticalKbps), "capacity_measured": false}
}
// Weighted water filling with demand caps redistributes unused allocations.
// Class packet admission and producer sizing use the same result.
func waterfill(total float64, weights, demands map[string]float64) map[string]float64 {
out := map[string]float64{}
active := map[string]float64{}
for k, w := range weights {
if demands[k] > 0 && w > 0 {
active[k] = w
}
}
remaining := total
for len(active) > 0 && remaining > 0 {
sum := 0.0
for _, w := range active {
sum += w
}
capped := []string{}
for k, w := range active {
if demands[k] <= remaining*w/sum {
capped = append(capped, k)
}
}
if len(capped) == 0 {
for k, w := range active {
out[k] = remaining * w / sum
}
break
}
for _, k := range capped {
out[k] = demands[k]
remaining -= demands[k]
delete(active, k)
}
}
return out
}
func (b *LinkBudget) demands(now time.Time) map[string]float64 {
d := map[string]float64{}
for _, p := range b.producers {
if now.Sub(p.seen) < producerTTL {
d[p.class] += float64(p.demand)
}
}
for k, c := range b.classes {
if now.Sub(c.seen) <= 2*time.Second && (k == "inventory" || k == "bulk" || d[k] == 0) {
d[k] = c.wanted
if d[k] == 0 {
d[k] = b.ceiling() * 1000
}
}
}
return d
}
func (b *LinkBudget) demand(now time.Time) float64 {
total := 0.0
for _, v := range b.demands(now) {
total += v
}
return total
}
func (b *LinkBudget) classRates(now time.Time) map[string]float64 {
total := b.optional(now) * 1000
demands := b.demands(now)
if b.commandLimited(now) {
return map[string]float64{"video": math.Min(total, demands["video"])}
}
if b.primaryVideo(now) == "" {
return waterfill(total, linkWeights, demands)
}
// During observation, explicitly requested recording transfer must make
// bounded progress even when the selected camera demands all capacity.
// Its floor is at most the ordinary 1/11 share and 32 kbit/s, taken from
// the SAME optional budget. Active/stale control and command pressure
// retain strict primary-video priority; exports never borrow its reserve.
rates := map[string]float64{}
if !b.protected(now) {
rates["bulk"] = math.Min(demands["bulk"], math.Min(32000, total/11))
total -= rates["bulk"]
demands["bulk"] -= rates["bulk"]
}
rates["inventory"] = math.Min(total, math.Min(32000, demands["inventory"]))
total -= rates["inventory"]
rates["video"] = math.Min(total, demands["video"])
total -= rates["video"]
for key, value := range waterfill(total, map[string]float64{"cloud": 1, "bulk": 1}, demands) {
rates[key] += value
}
return rates
}
// Existing serialized HTTP lanes declare finite body demand rather than
// permanently competing as unlimited streams. This never mints packet credit.
func (b *LinkBudget) RequestDemand(class string, size int) {
if b == nil || size <= 0 {
return
}
b.mu.Lock()
defer b.mu.Unlock()
if c := b.classes[class]; c != nil {
wire := size + ((size+linkPacket-1)/linkPacket)*linkOverhead
c.wanted = math.Min(b.ceiling()*1000, math.Max(64000, float64(wire)*8))
}
}
@@ -0,0 +1,103 @@
package node
import (
"fmt"
"testing"
"time"
)
func TestRuntimeRecoversWithPeriodicOutliersAndRespectsExplicitCeiling(t *testing.T) {
for _, limit := range []int{0, 4000} {
b, now := testBudget(t)
b.Configure(LinkPolicy{"missioncore.link-budget/v1", limit, 512})
b.effective = 640
for i := 0; i < 600; i++ {
*now = now.Add(100 * time.Millisecond)
b.allocateDemand(fmt.Sprintf("%032x", 1), "video", true, 8000000)
delay := 50 * time.Millisecond
if i%80 == 0 {
delay = 500 * time.Millisecond
}
b.Observe(delay, true)
}
if b.effective < 4000 || (limit == 0 && b.effective <= 4000) || (limit > 0 && b.effective > float64(limit)) {
t.Fatal("recovery/cap", limit, b.effective)
}
if len(b.runtime.events) > 32 || len(b.runtime.samples) > 320 {
t.Fatal("unbounded diagnostics")
}
}
}
func TestRuntimeSubtractsCoreProcessingAndNeverTreatsItAsLinkLoss(t *testing.T) {
b, now := testBudget(t)
for i := 0; i < 60; i++ {
*now = now.Add(100 * time.Millisecond)
core := float64(i%6) * 100
b.ObserveExchange(time.Duration(50+core)*time.Millisecond, core, true)
}
if b.effective != 4000 || b.baseline != 50*time.Millisecond {
t.Fatal("server processing misclassified", b.effective, b.baseline)
}
}
func TestControlReserveActivatesBeforeIntentAndReturnsOnStaleState(t *testing.T) {
b, now := testBudget(t)
b.runtime.criticalAt = *now
b.runtime.criticalKbps = 50
b.SetControl(false)
if b.reserve(*now) != 75 {
t.Fatal("idle critical rate ignored")
}
b.Try("bulk", 1000)
*now = now.Add(time.Second)
b.Try("bulk", 1000)
b.SetControl(true)
if b.tokens != 0 || b.reserve(*now) != 512 {
t.Fatal("first intent can inherit idle burst")
}
b.SetControl(false)
*now = now.Add(3 * time.Second)
if b.reserve(*now) != 512 {
t.Fatal("stale state released control reserve")
}
b.runtime.criticalKbps = 600
if b.reserve(*now) != 900 {
t.Fatal("actual critical demand clipped")
}
}
func TestDemandRedistributionAndUsefulVideoAdmission(t *testing.T) {
b, now := testBudget(t)
first, second := fmt.Sprintf("%032x", 1), fmt.Sprintf("%032x", 2)
b.allocateDemand(first, "video", true, 1000000)
a, _ := b.allocateDemand(second, "video", true, 5000000)
if a["allocation_bps"] != 2488000 {
t.Fatal("unused producer demand not lent", a)
}
b.effective = 1000
a, _ = b.allocateDemand(first, "video", true, 1000000)
c, _ := b.allocateDemand(second, "video", true, 5000000)
if a["allocation_bps"] != 488000 || c["allocation_bps"] != 0 {
t.Fatal("all video degraded instead of admitting one", a, c)
}
*now = now.Add(4 * time.Second)
c, _ = b.allocateDemand(second, "video", true, 5000000)
if c["allocation_bps"] != 488000 {
t.Fatal("expired viewer retained priority", c)
}
}
func TestWaterfillIsBoundedAndDemandCapped(t *testing.T) {
rates := waterfill(100, map[string]float64{"a": 1, "b": 1, "c": 1}, map[string]float64{"a": 5, "b": 10, "c": 200})
if rates["a"] != 5 || rates["b"] != 10 || rates["c"] != 85 {
t.Fatal(rates)
}
}
func TestSmallInventoryDoesNotReserveAnUnlimitedStream(t *testing.T) {
b, now := testBudget(t)
b.allocateDemand(fmt.Sprintf("%032x", 1), "video", true, 5000000)
b.RequestDemand("inventory", 6000)
b.Try("inventory", 1000)
rates := b.classRates(*now)
if rates["inventory"] != 64000 || rates["video"] != 3424000 {
t.Fatal("small metadata held camera bandwidth", rates)
}
}
@@ -0,0 +1,40 @@
package node
import (
"testing"
"time"
)
func TestTenStopRecoveryCyclesPreserveVideoAdmissionBounds(t *testing.T) {
b, now := testBudget(t)
const primary = "11111111111111111111111111111111"
for run := 0; run < 10; run++ {
b.SetControl(true)
b.allocateRole(primary, "video", true, 5000000, true)
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
*now = now.Add(250 * time.Millisecond)
b.ObserveCommandSilence()
if b.optional(*now) != 0 {
t.Fatal("expired commands admitted video", run)
}
for _, class := range []string{"video", "bulk", "cloud", "inventory"} {
if ok, _ := b.Try(class, 100); ok {
t.Fatal("cached credit bypassed pause", run, class)
}
}
// Confirmed absence of authority ends command-specific pressure; it
// does not increase capacity or remove other feedback/bandwidth caps.
capacity := b.effective
b.SetControl(false)
if b.optional(*now) <= 0 || b.effective != capacity {
t.Fatal("observation failed to resume within cap", run)
}
b.SetControl(true)
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
*now = now.Add(50 * time.Millisecond)
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
if b.optional(*now) <= 0 || b.reserve(*now) < float64(b.policy.ReserveKbps) {
t.Fatal("fresh neutral recovery lost reserve", run)
}
}
}
@@ -0,0 +1,478 @@
package node
// Network preferences belong to this board. Core observes acknowledged generations.
import (
"bufio"
"context"
"encoding/json"
"errors"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"time"
)
type NetworkPending struct {
Deadline int64 `json:"deadline"`
PreviousEndpoint string `json:"previous_endpoint"`
Provider string `json:"provider"`
ServerID string `json:"server_id"`
Config json.RawMessage `json:"config,omitempty"`
Local bool `json:"local,omitempty"`
}
type NetworkProfile struct {
BindingID string `json:"binding_id"`
Revision int64 `json:"revision"`
Provider string `json:"provider"`
ServerID string `json:"server_id,omitempty"`
Config json.RawMessage `json:"config,omitempty"`
TailscaleEndpoint string `json:"tailscale_endpoint,omitempty"`
OperationID string `json:"operation_id,omitempty"`
Phase string `json:"phase"`
PublicKey string `json:"public_key,omitempty"`
Error string `json:"error,omitempty"`
Pending *NetworkPending `json:"pending,omitempty"`
}
type NetworkCommand struct {
ID string `json:"id"`
Action string `json:"action"`
Provider string `json:"provider"`
ServerID string `json:"server_id"`
ExpectedRevision int64 `json:"expected_revision"`
ExpiresAt int64 `json:"expires_at"`
CoreEndpoint string `json:"core_endpoint,omitempty"`
Config json.RawMessage `json:"config,omitempty"`
}
var networkID = regexp.MustCompile(`^wg_[a-f0-9]{32}$`)
var networkOperationID = regexp.MustCompile(`^[a-f0-9]{32}$`)
func networkHelper(action, identity string, fields map[string]any) (map[string]json.RawMessage, error) {
connection, err := net.DialTimeout("unix", "/run/mission-core-wireguard/control.sock", 3*time.Second)
if err != nil {
return nil, errors.New("Системная служба WireGuard недоступна. Обновите Node.")
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(25 * time.Second))
body := map[string]any{"action": action, "server_id": identity}
for key, value := range fields {
body[key] = value
}
if err = json.NewEncoder(connection).Encode(body); err != nil {
return nil, err
}
var result struct {
OK bool `json:"ok"`
Result map[string]json.RawMessage `json:"result"`
Error string `json:"error"`
}
data, err := bufio.NewReaderSize(connection, 16385).ReadSlice('\n')
if err != nil || len(data) > 16384 || json.Unmarshal(data, &result) != nil {
return nil, errors.New("Нет подтверждения сетевой службы.")
}
if !result.OK {
return nil, errors.New("Не удалось подготовить WireGuard на борту.")
}
return result.Result, nil
}
func (p *Pairing) callNetwork(action, identity string, fields map[string]any) (map[string]json.RawMessage, error) {
if p.networkCall != nil {
return p.networkCall(action, identity, fields)
}
return networkHelper(action, identity, fields)
}
func (p *Pairing) networkPath() string {
return filepath.Join(filepath.Dir(p.path), "network-profile.json")
}
func (p *Pairing) loadNetworkLocked() error {
if p.network != nil {
if p.state.Binding == nil || p.network.BindingID == p.state.Binding.BindingID {
return nil
}
p.network = nil
}
value := NetworkProfile{Provider: "tailscale", Phase: "applied"}
raw, err := os.ReadFile(p.networkPath())
if err == nil {
info, e := os.Lstat(p.networkPath())
if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 {
return errors.New("Invalid network configuration permissions")
}
}
if err == nil {
if len(raw) > 16384 || json.Unmarshal(raw, &value) != nil {
return errors.New("Invalid network configuration")
}
} else if !os.IsNotExist(err) {
return err
}
if p.state.Binding != nil {
if value.BindingID != p.state.Binding.BindingID {
value = NetworkProfile{BindingID: p.state.Binding.BindingID, Provider: "tailscale", Phase: "applied"}
}
endpoint, _ := url.Parse(p.state.Binding.Endpoint)
if tailnetAddress(endpoint.Hostname()) {
value.TailscaleEndpoint = p.state.Binding.Endpoint
}
}
p.network = &value
return nil
}
func (p *Pairing) saveNetworkLocked() error { return savePrivateJSON(p.networkPath(), p.network) }
func (p *Pairing) networkViewLocked() map[string]any {
if p.loadNetworkLocked() != nil {
return map[string]any{"phase": "unavailable"}
}
n := p.network
result := map[string]any{"provider": n.Provider, "server_id": n.ServerID, "revision": n.Revision, "phase": n.Phase,
"operation_id": n.OperationID, "public_key": n.PublicKey, "tailscale_endpoint": n.TailscaleEndpoint, "error": n.Error}
if n.Pending != nil {
result["pending_provider"] = n.Pending.Provider
result["rollback_at"] = n.Pending.Deadline
}
return result
}
func (p *Pairing) networkSnapshot() map[string]any {
p.mu.Lock()
defer p.mu.Unlock()
return p.networkViewLocked()
}
func (p *Pairing) networkEndpointLocked(endpoint string) error {
b := p.state.Binding
if b == nil || p.state.Phase != "paired" || !privateEndpoint(endpoint, CorePort) {
return errors.New("Binding unavailable")
}
if b.Endpoint == endpoint {
return nil
}
if b.EndpointRevision >= 1000000000 {
return errors.New("Endpoint revision exhausted")
}
next := p.state
copy := *b
copy.Endpoint = endpoint
copy.EndpointRevision++
next.Binding = &copy
if err := p.save(next); err != nil {
return err
}
p.connection = "offline"
p.lastSeen = 0
return nil
}
func (p *Pairing) rollbackNetwork() {
p.mu.Lock()
if p.loadNetworkLocked() != nil || p.network.Pending == nil {
p.mu.Unlock()
return
}
n := p.network
pending := *n.Pending
identity := pending.ServerID
op := n.OperationID
p.mu.Unlock()
if networkID.MatchString(identity) {
if _, err := p.callNetwork("rollback", identity, map[string]any{"operation_id": op}); err != nil {
return
}
}
p.mu.Lock()
defer p.mu.Unlock()
if p.network.Pending == nil || p.network.OperationID != op {
return
}
if p.networkEndpointLocked(pending.PreviousEndpoint) != nil {
return
}
n.Pending = nil
n.Phase = "rolled_back"
n.Error = "Новое подключение не подтверждено. Восстановлен прежний профиль."
_ = p.saveNetworkLocked()
}
func (p *Pairing) networkWatch(ctx context.Context) {
// A restart during a transaction restores the last confirmed endpoint.
p.rollbackNetwork()
timer := time.NewTicker(time.Second)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
p.mu.Lock()
expired := p.network != nil && p.network.Pending != nil && p.network.Pending.Deadline <= time.Now().Unix()
p.mu.Unlock()
if expired {
p.rollbackNetwork()
}
}
}
}
func (p *Pairing) networkFailure(op string, err error) {
p.mu.Lock()
pending := p.network != nil && p.network.Pending != nil
p.mu.Unlock()
if pending {
p.rollbackNetwork()
return
}
p.mu.Lock()
defer p.mu.Unlock()
if p.network != nil && p.network.OperationID == op {
p.network.Phase = "failed"
p.network.Error = err.Error()
_ = p.saveNetworkLocked()
}
}
func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
if len(raw) == 0 || string(raw) == "null" {
return
}
var c NetworkCommand
if decodeRoverJSON(raw, &c) != nil || !networkOperationID.MatchString(c.ID) || c.ExpiresAt <= time.Now().Unix() || c.ExpiresAt > time.Now().Unix()+180 {
return
}
p.mu.Lock()
if p.loadNetworkLocked() != nil || p.state.Binding == nil || p.state.Phase != "paired" {
p.mu.Unlock()
return
}
n := p.network
if c.Action == "abort" && n.OperationID == c.ID {
p.mu.Unlock()
p.rollbackNetwork()
return
}
if c.Action == "commit" && n.OperationID == c.ID && n.Phase == "applied" {
p.mu.Unlock()
return
}
if c.ExpectedRevision != n.Revision || (c.Provider != "tailscale" && c.Provider != "wireguard") || (c.Provider == "wireguard" && !networkID.MatchString(c.ServerID)) {
p.mu.Unlock()
return
}
if n.Pending != nil && n.OperationID != c.ID {
p.mu.Unlock()
return
}
if c.Action == "prepare" {
if n.OperationID == c.ID && n.Phase == "prepared" {
p.mu.Unlock()
return
}
n.OperationID = c.ID
n.Phase = "preparing"
n.Error = ""
_ = p.saveNetworkLocked()
p.mu.Unlock()
reply, err := p.callNetwork("prepare", c.ServerID, nil)
if err != nil {
p.networkFailure(c.ID, err)
return
}
var public string
_ = json.Unmarshal(reply["public_key"], &public)
p.mu.Lock()
defer p.mu.Unlock()
if p.network.OperationID != c.ID || p.state.Binding == nil || p.network.BindingID != p.state.Binding.BindingID {
return
}
p.network.PublicKey = public
p.network.Phase = "prepared"
_ = p.saveNetworkLocked()
return
}
if c.Action == "apply" {
if n.OperationID == c.ID && (n.Phase == "verifying" || n.Phase == "applied") {
p.mu.Unlock()
return
}
if c.Provider == "tailscale" {
if c.CoreEndpoint != n.TailscaleEndpoint || c.CoreEndpoint == "" {
p.mu.Unlock()
return
}
} else {
var config struct {
ServerID string `json:"server_id"`
Address string `json:"address"`
Subnet string `json:"subnet"`
Role string `json:"role"`
Allowed []string `json:"allowed_ips"`
}
if json.Unmarshal(c.Config, &config) != nil || config.ServerID != c.ServerID || config.Role != "node" {
p.mu.Unlock()
return
}
_, network, err := net.ParseCIDR(config.Subnet)
u, e := url.Parse(c.CoreEndpoint)
if err != nil || e != nil || !privateEndpoint(c.CoreEndpoint, CorePort) || !network.Contains(net.ParseIP(u.Hostname())) {
p.mu.Unlock()
return
}
found := false
for _, address := range config.Allowed {
if address == u.Hostname()+"/32" {
found = true
}
}
if !found {
p.mu.Unlock()
return
}
}
n.OperationID = c.ID
n.Phase = "preparing"
n.Error = ""
n.Pending = &NetworkPending{Deadline: time.Now().Unix() + 100, PreviousEndpoint: p.state.Binding.Endpoint, Provider: c.Provider, ServerID: c.ServerID, Config: c.Config}
if p.saveNetworkLocked() != nil {
p.mu.Unlock()
return
}
p.mu.Unlock()
if c.Provider == "wireguard" {
var config map[string]any
_ = json.Unmarshal(c.Config, &config)
if _, err := p.callNetwork("stage", c.ServerID, map[string]any{"config": config, "operation_id": c.ID}); err != nil {
p.networkFailure(c.ID, err)
return
}
}
p.mu.Lock()
defer p.mu.Unlock()
if p.network.OperationID != c.ID || p.network.Pending == nil || p.state.Binding == nil || p.network.BindingID != p.state.Binding.BindingID {
return
}
if err := p.networkEndpointLocked(c.CoreEndpoint); err != nil {
p.network.Phase = "failed"
p.network.Error = "Не удалось сохранить адрес Core."
} else {
p.network.Phase = "verifying"
}
_ = p.saveNetworkLocked()
return
}
if c.Action == "commit" && n.OperationID == c.ID && n.Phase == "verifying" && n.Pending != nil {
pending := *n.Pending
oldServer := n.ServerID
p.mu.Unlock()
if pending.Provider == "wireguard" {
if _, err := p.callNetwork("confirm", pending.ServerID, map[string]any{"operation_id": c.ID}); err != nil {
p.networkFailure(c.ID, err)
return
}
}
p.mu.Lock()
defer p.mu.Unlock()
if p.network.Pending == nil || p.network.OperationID != c.ID {
return
}
n = p.network
previous := *n
n.Provider = pending.Provider
n.ServerID = pending.ServerID
n.Config = pending.Config
n.Pending = nil
n.Phase = "applied"
n.Revision++
n.Error = ""
if err := p.saveNetworkLocked(); err != nil {
*n = previous
return
}
if oldServer != "" && oldServer != pending.ServerID {
// The confirmed endpoint is durable before retiring the previous tunnel.
_, _ = p.callNetwork("disable", oldServer, nil)
}
return
}
p.mu.Unlock()
}
func (p *Pairing) networkAddressLocked(address string) bool {
if p.network == nil || p.network.Provider != "wireguard" {
return tailnetAddress(address)
}
var config struct {
Address string `json:"address"`
}
return json.Unmarshal(p.network.Config, &config) == nil && config.Address == address
}
func (p *Pairing) networkPeerLocked(address string) bool {
if tailnetAddress(address) {
return true
}
for _, raw := range []json.RawMessage{func() json.RawMessage {
if p.network != nil {
return p.network.Config
}
return nil
}(), func() json.RawMessage {
if p.network != nil && p.network.Pending != nil {
return p.network.Pending.Config
}
return nil
}()} {
var config struct {
Allowed []string `json:"allowed_ips"`
}
if json.Unmarshal(raw, &config) == nil {
for _, peer := range config.Allowed {
if peer == address+"/32" {
return true
}
}
}
}
return false
}
func (p *Pairing) networkLocalRoutes(mux *http.ServeMux, s *Server) {
mux.HandleFunc("GET /api/network/profile", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
reply(w, 200, p.networkSnapshot())
})
mux.HandleFunc("POST /api/network/profile/tailscale", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
p.mu.Lock()
_ = p.loadNetworkLocked()
if p.network == nil || p.network.TailscaleEndpoint == "" {
p.mu.Unlock()
reply(w, 409, map[string]string{"error": "Нет сохранённого подключения Tailscale."})
return
}
op := digest(token())[:32]
command := NetworkCommand{ID: op, Action: "apply", Provider: "tailscale", ExpectedRevision: p.network.Revision, ExpiresAt: time.Now().Unix() + 110, CoreEndpoint: p.network.TailscaleEndpoint}
p.mu.Unlock()
raw, _ := json.Marshal(command)
p.applyNetworkCommand(raw)
p.mu.Lock()
if p.network.Pending != nil && p.network.OperationID == op {
p.network.Pending.Local = true
_ = p.saveNetworkLocked()
}
p.mu.Unlock()
reply(w, 200, p.networkSnapshot())
})
}
// Only a successful authenticated heartbeat through the selected endpoint can
// confirm the local recovery action. It cannot authorize a remote arbitrary path.
func (p *Pairing) networkLocalAcknowledged(binding CoreBinding) {
p.mu.Lock()
n := p.network
if n == nil || n.Pending == nil || !n.Pending.Local || n.Phase != "verifying" || p.state.Binding == nil || p.state.Binding.Endpoint != binding.Endpoint {
p.mu.Unlock()
return
}
c := NetworkCommand{ID: n.OperationID, Action: "commit", Provider: n.Pending.Provider, ServerID: n.Pending.ServerID, ExpectedRevision: n.Revision, ExpiresAt: time.Now().Unix() + 30}
p.mu.Unlock()
raw, _ := json.Marshal(c)
p.applyNetworkCommand(raw)
}
@@ -0,0 +1,105 @@
package node
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"testing"
"time"
)
func networkFixture(t *testing.T) (*Pairing, NetworkCommand, *[]string) {
p, _ := testPairing(t)
b := testCoreBinding(t, p)
b.Endpoint = "https://100.64.1.2:8782"
b.EndpointRevision = 7
if err := p.save(PairState{Schema: PairSchema, Phase: "paired", Binding: &b}); err != nil {
t.Fatal(err)
}
actions := []string{}
p.networkCall = func(action, id string, fields map[string]any) (map[string]json.RawMessage, error) {
actions = append(actions, action)
return map[string]json.RawMessage{"public_key": json.RawMessage(`"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE="`)}, nil
}
config := json.RawMessage(`{"server_id":"wg_11111111111111111111111111111111","address":"10.203.1.3","subnet":"10.203.1.0/24","role":"node","allowed_ips":["10.203.1.1/32","10.203.1.2/32"]}`)
c := NetworkCommand{ID: "22222222222222222222222222222222", Action: "apply", Provider: "wireguard", ServerID: "wg_11111111111111111111111111111111", ExpectedRevision: 0, ExpiresAt: time.Now().Unix() + 110, CoreEndpoint: "https://10.203.1.2:8782", Config: config}
return p, c, &actions
}
func networkSend(p *Pairing, c NetworkCommand) { raw, _ := json.Marshal(c); p.applyNetworkCommand(raw) }
func TestNetworkCommitIsIdempotentAndUsesNewEndpoint(t *testing.T) {
p, c, actions := networkFixture(t)
networkSend(p, c)
if p.network.Phase != "verifying" || p.network.Provider != "tailscale" || p.state.Binding.Endpoint != c.CoreEndpoint {
t.Fatal("unconfirmed profile became active")
}
revision := p.state.Binding.EndpointRevision
networkSend(p, c)
if p.state.Binding.EndpointRevision != revision {
t.Fatal("repeat changed endpoint revision")
}
c.Action = "commit"
networkSend(p, c)
networkSend(p, c)
if p.network.Revision != 1 || p.network.Provider != "wireguard" || p.network.Pending != nil {
t.Fatal("commit failed")
}
if len(*actions) != 2 || (*actions)[0] != "stage" || (*actions)[1] != "confirm" {
t.Fatal(*actions)
}
}
func TestNetworkRestartAndFailedStageRestoreConfirmedBinding(t *testing.T) {
p, c, _ := networkFixture(t)
networkSend(p, c)
p.network = nil // Reload durable state, exactly as a new Node process.
p.rollbackNetwork()
if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Phase != "rolled_back" || p.state.Binding.EndpointRevision != 9 {
t.Fatal("restart did not restore prior endpoint")
}
p, c, _ = networkFixture(t)
p.networkCall = func(action, id string, fields map[string]any) (map[string]json.RawMessage, error) {
if action == "stage" {
return nil, errors.New("test fault")
}
return nil, nil
}
networkSend(p, c)
if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Pending != nil {
t.Fatal("failed stage changed confirmed endpoint")
}
}
func TestNetworkRejectsStaleAndUnrelatedEndpoint(t *testing.T) {
for _, change := range []func(*NetworkCommand){func(c *NetworkCommand) { c.ExpectedRevision = 8 }, func(c *NetworkCommand) { c.CoreEndpoint = "https://192.168.1.10:8782" }, func(c *NetworkCommand) { c.ExpiresAt = time.Now().Unix() - 1 }} {
p, c, actions := networkFixture(t)
change(&c)
networkSend(p, c)
if len(*actions) != 0 || p.state.Binding.Endpoint != "https://100.64.1.2:8782" {
t.Fatal("invalid change reached root helper")
}
}
}
func TestNetworkCommitStorageFailureKeepsRollbackState(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("permission fault requires unprivileged qualification")
}
p, c, _ := networkFixture(t)
networkSend(p, c)
dir := filepath.Dir(p.networkPath())
if err := os.Chmod(dir, 0500); err != nil {
t.Fatal(err)
}
defer os.Chmod(dir, 0700)
c.Action = "commit"
networkSend(p, c)
if p.network.Provider != "tailscale" || p.network.Revision != 0 || p.network.Pending == nil || p.network.Phase != "verifying" {
t.Fatal("failed persistence changed confirmed state")
}
if err := os.Chmod(dir, 0700); err != nil {
t.Fatal(err)
}
p.rollbackNetwork()
if p.network.Provider != "tailscale" || p.network.Pending != nil || p.state.Binding.Endpoint != "https://100.64.1.2:8782" {
t.Fatal("rollback after storage failure failed")
}
}
+7 -1
View File
@@ -13,6 +13,8 @@ import (
"sort"
"sync"
"time"
"nodedc.local/mission-core/node-agent/internal/routers"
)
type Invitation struct {
@@ -41,10 +43,14 @@ type PairState struct {
Revocations []CoreBinding `json:"revocations,omitempty"`
}
type Pairing struct {
Budget *LinkBudget
Routers *routers.Collector
RoverConfiguration *RoverConfigurationStore
Monitor *Monitor
Sensors *Sensors
DeviceEnrollment *DeviceEnrollment
networkCall func(string, string, map[string]any) (map[string]json.RawMessage, error)
network *NetworkProfile
mu sync.Mutex
path string
store *Store
@@ -148,7 +154,7 @@ func (p *Pairing) status() map[string]any {
defer p.mu.Unlock()
_ = p.expire()
id, _ := p.store.Public()
out := map[string]any{"phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": p.addresses(), "pending_revocations": len(p.state.Revocations)}
out := map[string]any{"network_profile": p.networkViewLocked(), "phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": p.addresses(), "pending_revocations": len(p.state.Revocations)}
if i := p.state.Invitation; i != nil {
out["invitation"] = map[string]any{"id": i.ID, "endpoint": i.Endpoint, "expires_at": i.ExpiresAt}
}
@@ -0,0 +1,147 @@
package node
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestLinkHeartbeatWithDevAtFloor(t *testing.T) {
for _, devSize := range []int{0, 400, linkPacket} {
b, now := testBudget(t)
b.effective = float64(b.policy.ReserveKbps + 128)
delivered, devBytes := 0, 0
deadline := pacedTimeout(40 * 1024)
for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond {
*now = now.Add(10 * time.Millisecond)
// Persistent congestion must not erase earned tokens at the floor.
if elapsed%time.Second == 0 {
b.Observe(time.Second, false)
}
b.Try("video", 1200)
b.Try("cloud", 1200)
if devSize > 0 {
if ok, _ := b.Try("bulk", devSize); ok {
devBytes += devSize
}
}
if delivered < 40*1024 {
size := min(linkPacket, 40*1024-delivered)
if ok, _ := b.Try("inventory", size); ok {
delivered += size
}
}
}
t.Logf("DEV packet=%d: heartbeat=%d/40960, DEV=%d, deadline=%v", devSize, delivered, devBytes, deadline)
if delivered != 40*1024 || (devSize > 0 && devBytes == 0) {
t.Fatal("optional traffic starved")
}
var charged uint64
for _, class := range b.classes {
charged += class.bytes
}
if float64(charged) > 128*125*deadline.Seconds()+linkBurst {
t.Fatal("aggregate allowance exceeded")
}
}
}
func TestLinkPacedTimeoutCoversLargestDiagnosticBlock(t *testing.T) {
b, now := testBudget(t)
b.effective = float64(b.policy.ReserveKbps + 128)
left := 108 * 1024
deadline := pacedTimeout(left)
for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond {
*now = now.Add(10 * time.Millisecond)
for _, class := range []string{"video", "cloud", "inventory"} {
b.Try(class, 1200)
}
size := min(linkPacket, left)
if ok, _ := b.Try("bulk", size); ok {
left -= size
}
if left == 0 {
return
}
}
t.Fatal("export deadline below worst-case budget", left)
}
func TestHeartbeatLivenessDuringBlockedSnapshot(t *testing.T) {
p, _ := testPairing(t)
binding := testCoreBinding(t, p)
p.state = PairState{Phase: "paired", Binding: &binding}
var lives atomic.Int64
started := make(chan struct{})
release := make(chan struct{})
p.clients[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = &http.Client{
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/v1/node/liveness" {
raw, _ := io.ReadAll(r.Body)
var envelope map[string]any
json.Unmarshal(raw, &envelope)
if len(raw) > 2048 || envelope["host"] != nil || envelope["sensor_results"] != nil || envelope["monitor"] != nil {
t.Error("large snapshot or acknowledgements leaked into liveness")
}
if lives.Add(1) == 2 {
close(release)
}
} else {
close(started)
select {
case <-release:
case <-r.Context().Done():
return nil, r.Context().Err()
}
}
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), Header: make(http.Header)}, nil
}),
}
ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
defer cancel()
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID,
"node_id": "test", "execution_binding": map[string]string{"agent_instance_id": "test"},
"core_endpoint": binding.Endpoint, "endpoint_revision": 0,
"host": strings.Repeat("x", 40*1024), "monitor": strings.Repeat("x", 100*1024)}
_, status, err := p.sendHeartbeat(ctx, binding, payload)
if err != nil || status != 200 || lives.Load() != 2 {
t.Fatal("snapshot blocked liveness", status, err, lives.Load())
}
select {
case <-started:
default:
t.Fatal("snapshot was not sent")
}
if p.lastSeen == 0 || p.connection != "online" {
t.Fatal("live binding remained offline")
}
}
func TestHeartbeatCancelledUploadJoinsBeforeReturn(t *testing.T) {
p, _ := testPairing(t)
binding := testCoreBinding(t, p)
p.state = PairState{Phase: "paired", Binding: &binding}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var finished atomic.Bool
p.clients[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = &http.Client{
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/v1/node/heartbeat" {
cancel()
<-r.Context().Done()
finished.Store(true)
return nil, r.Context().Err()
}
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil
}),
}
_, _, err := p.sendHeartbeat(ctx, binding, map[string]any{})
if err == nil || !finished.Load() {
t.Fatal("upload leaked after cancellation")
}
}
@@ -0,0 +1,72 @@
package node
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
)
func TestHeartbeatCompressionNegotiatedOnExistingAuthenticatedChannel(t *testing.T) {
for _, supported := range []bool{false, true} {
p, _ := testPairing(t)
b := testCoreBinding(t, p)
p.state = PairState{Phase: "paired", Binding: &b}
if supported {
budget, now := testBudget(t)
budget.tokens = linkBurst
budget.classes["inventory"].tokens = linkClassBurst
budget.classes["inventory"].seen = *now
p.Budget = budget
}
payload := map[string]any{"node_id": "fixture", "host": strings.Repeat("metadata", 8000)}
raw, _ := json.Marshal(payload)
seen := 0
p.clients[b.BindingID+b.Endpoint+digest(b.ClientPEM)] = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
response := `{"ok":true}`
if r.URL.Path == "/v1/node/liveness" {
if supported {
response = `{"ok":true,"heartbeat_encoding":"gzip"}`
}
} else {
seen++
wire, err := io.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
decoded := wire
if supported {
if r.Header.Get("Content-Encoding") != "gzip" || len(wire) >= len(raw)/10 {
t.Error("heartbeat not compressed")
}
reader, err := gzip.NewReader(bytes.NewReader(wire))
if err != nil {
t.Fatal(err)
}
decoded, err = io.ReadAll(reader)
reader.Close()
if err != nil {
t.Fatal(err)
}
} else if r.Header.Get("Content-Encoding") != "" {
t.Error("old Core received unsupported encoding")
}
if !bytes.Equal(decoded, raw) || r.ContentLength != int64(len(wire)) {
t.Error("snapshot or framing changed")
}
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(response))}, nil
})}
_, status, err := p.sendHeartbeat(context.Background(), b, payload)
if err != nil || status != 200 || seen != 1 {
t.Fatal(status, err, seen)
}
if supported && p.Budget.classes["inventory"].bytes == 0 {
t.Fatal("compressed body bypassed shared budget")
}
}
}
@@ -0,0 +1,77 @@
package node
import (
"context"
"encoding/json"
"time"
)
// A bounded keepalive on the existing authenticated Node HTTP transport.
// It cannot carry inventory, operation receipts or a motor lease. Old Core
// returns 404; full heartbeat remains backward-compatible. No retry queue.
func (p *Pairing) sendHeartbeat(ctx context.Context, b CoreBinding, payload map[string]any) (map[string]json.RawMessage, int, error) {
live := map[string]any{}
for _, key := range []string{"schema", "node_id", "binding_id", "execution_binding", "core_endpoint", "endpoint_revision"} {
live[key] = payload[key]
}
compressed := false
keepalive := func() {
result, status, err := p.send(ctx, b, "/v1/node/liveness", live)
var encoding string
if err == nil && status == 200 {
_ = json.Unmarshal(result["heartbeat_encoding"], &encoding)
}
compressed = encoding == "gzip"
p.mu.Lock()
defer p.mu.Unlock()
if p.sameBinding(b) && err == nil && status == 200 {
p.connection, p.lastSeen = "online", p.now().Unix()
}
}
// Initializes the shared two-connection client before the concurrent upload;
// the client map is owned by channel, and only read until this upload joins.
keepalive()
call, cancel := context.WithCancel(ctx)
defer cancel()
type outcome struct {
body map[string]json.RawMessage
status int
err error
}
done := make(chan outcome, 1)
go func(compress bool) {
body, status, err := p.sendEncoded(call, b, "/v1/node/heartbeat", payload, compress)
done <- outcome{body, status, err}
}(compressed)
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case result := <-done:
return result.body, result.status, result.err
case <-ctx.Done():
cancel()
result := <-done
return result.body, result.status, result.err
case <-ticker.C:
p.mu.Lock()
current := p.sameBinding(b)
p.mu.Unlock()
if !current {
cancel()
result := <-done
return result.body, result.status, result.err
}
keepalive()
}
}
}
// Caller holds p.mu. Endpoint revisions and certificate rotation invalidate an
// in-flight snapshot; an old upload cannot refresh a replacement binding.
func (p *Pairing) sameBinding(b CoreBinding) bool {
current := p.state.Binding
return p.state.Phase == "paired" && current != nil &&
current.BindingID == b.BindingID && current.Endpoint == b.Endpoint &&
current.EndpointRevision == b.EndpointRevision && current.ClientPEM == b.ClientPEM
}
@@ -50,7 +50,10 @@ func (p *Pairing) recoveryHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil || !tailnetAddress(host) || r.TLS == nil {
p.mu.Lock()
allowedNetwork := p.networkPeerLocked(host)
p.mu.Unlock()
if err != nil || !allowedNetwork || r.TLS == nil {
http.Error(w, "Private authenticated channel required", 403)
return
}
@@ -80,7 +83,7 @@ func (p *Pairing) recoveryHandler() http.Handler {
case "/v1/channel/inspect":
case "/v1/channel/migrate":
u, err := url.Parse(body.Endpoint)
if err != nil || !privateEndpoint(body.Endpoint, CorePort) || !tailnetAddress(u.Hostname()) || u.Hostname() != host {
if err != nil || !privateEndpoint(body.Endpoint, CorePort) || !p.networkPeerLocked(u.Hostname()) || u.Hostname() != host {
http.Error(w, "Endpoint must address the authenticated Core transport", 400)
return
}
@@ -169,6 +169,9 @@ func TestOldHeartbeatCannotRevokeMigratedBinding(t *testing.T) {
entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
p.clients[old.BindingID+old.Endpoint+digest(old.ClientPEM)] = &http.Client{
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/v1/node/liveness" {
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil
}
close(entered)
<-release
return &http.Response{StatusCode: 410, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil
@@ -2,6 +2,7 @@ package node
import (
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"encoding/json"
@@ -151,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler {
}
func (p *Pairing) Run(ctx context.Context) {
go p.networkWatch(ctx)
go p.channel(ctx)
go p.roverChannel(ctx)
var server *http.Server
@@ -181,7 +183,7 @@ func (p *Pairing) Run(ctx context.Context) {
}
if p.state.Phase == "paired" && p.state.Binding != nil {
for _, address := range p.addresses() {
if tailnetAddress(address) {
if p.networkAddressLocked(address) {
desired = "https://" + address + ":" + PairPort
copy := *p.state.Binding
recovery = &copy
@@ -230,6 +232,10 @@ func (p *Pairing) Run(ctx context.Context) {
}
}
func (p *Pairing) send(ctx context.Context, b CoreBinding, path string, payload any) (map[string]json.RawMessage, int, error) {
return p.sendEncoded(ctx, b, path, payload, false)
}
func (p *Pairing) sendEncoded(ctx context.Context, b CoreBinding, path string, payload any, compress bool) (map[string]json.RawMessage, int, error) {
config, e := bindingTLS(b, p.store.pairingKey())
if e != nil {
return nil, 0, e
@@ -237,19 +243,55 @@ func (p *Pairing) send(ctx context.Context, b CoreBinding, path string, payload
cacheKey := b.BindingID + b.Endpoint + digest(b.ClientPEM)
client := p.clients[cacheKey]
if client == nil {
transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 15 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext}
client = &http.Client{Transport: transport, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirects forbidden") }}
transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 2, MaxIdleConnsPerHost: 2, IdleConnTimeout: 15 * time.Second, ResponseHeaderTimeout: 8 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext}
client = &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirects forbidden") }}
p.clients[cacheKey] = client
}
data, e := json.Marshal(payload)
if e != nil {
return nil, 0, e
}
request, e := http.NewRequestWithContext(ctx, "POST", b.Endpoint+path, bytes.NewReader(data))
if len(data) > 8*1024*1024 {
return nil, 0, errors.New("Core envelope exceeds limit")
}
// Compress metadata only after the authenticated Core advertises support.
// Budget the actual wire body, retaining admission even if it shrinks below
// 4 KiB. The control reserve, transport and full-snapshot ACK stay unchanged.
paced := len(data) > 4096 && p.Budget != nil
encoding := ""
if compress && path == "/v1/node/heartbeat" && len(data) > 4096 {
var encoded bytes.Buffer
writer, _ := gzip.NewWriterLevel(&encoded, gzip.BestSpeed)
_, _ = writer.Write(data)
_ = writer.Close()
if encoded.Len() < len(data) {
data, encoding = encoded.Bytes(), "gzip"
}
}
timeout := 8 * time.Second
class := "bulk"
if path == "/v1/node/heartbeat" {
class = "inventory"
}
if paced {
timeout = pacedTimeout(len(data))
}
call, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ctx = call
var body io.Reader = bytes.NewReader(data)
if paced {
body = &budgetReader{ctx: ctx, source: body, budget: p.Budget, class: class}
}
request, e := http.NewRequestWithContext(ctx, "POST", b.Endpoint+path, body)
if e != nil {
return nil, 0, e
}
request.ContentLength = int64(len(data))
request.Header.Set("Content-Type", "application/json")
if encoding != "" {
request.Header.Set("Content-Encoding", encoding)
}
response, e := client.Do(request)
if e != nil {
return nil, 0, e
@@ -304,6 +346,7 @@ func (p *Pairing) channel(ctx context.Context) {
if p.RoverConfiguration != nil {
payload["rover_configuration"] = p.RoverConfiguration.Snapshot()
}
payload["network_profile"] = p.networkSnapshot()
payload["core_endpoint"] = binding.Endpoint
payload["endpoint_revision"] = binding.EndpointRevision
if p.Sensors != nil {
@@ -322,11 +365,18 @@ func (p *Pairing) channel(ctx context.Context) {
if p.Monitor != nil {
payload["monitor"] = p.Monitor.Snapshot()
}
result, status, e := p.send(ctx, *binding, "/v1/node/heartbeat", payload)
if p.Routers != nil {
payload["routers"] = p.Routers.Snapshot()
}
result, status, e := p.sendHeartbeat(ctx, *binding, payload)
var networkChange json.RawMessage
var configurationChange json.RawMessage
var routerCommands json.RawMessage
p.mu.Lock()
if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision {
if e == nil && status == 200 {
networkChange = result["network_profile_change"]
routerCommands = result["router_commands"]
if p.RoverConfiguration != nil {
configurationChange = result["rover_configuration_change"]
}
@@ -375,11 +425,16 @@ func (p *Pairing) channel(ctx context.Context) {
next.Phase = "revoked"
_ = p.save(next)
p.connection = "revoked"
} else {
} else if p.now().Unix()-p.lastSeen >= 20 {
p.connection = "offline"
}
}
p.mu.Unlock()
if e == nil && status == http.StatusOK {
p.networkLocalAcknowledged(*binding)
}
p.applyNetworkCommand(networkChange)
p.applyRouterCommands(routerCommands)
// Durable preference IO must not hold the pairing/control mutex.
if p.RoverConfiguration != nil {
p.RoverConfiguration.Apply(configurationChange)
+106 -35
View File
@@ -12,7 +12,6 @@ import (
"errors"
"io"
"log"
"net"
"net/http"
"sync"
"time"
@@ -57,12 +56,7 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
if err != nil {
return
}
transport := func() *http.Transport {
return &http.Transport{TLSClientConfig: config, Proxy: nil,
MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second,
TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second,
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext}
}
transport := func() *http.Transport { return newRoverHTTPTransport(config) }
telemetry := &http.Client{Transport: transport(), Timeout: 300 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect forbidden") }}
stream := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
defer telemetry.CloseIdleConnections()
@@ -76,10 +70,14 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
base := map[string]any{"schema": PairSchema, "node_id": id, "binding_id": b.BindingID,
"core_endpoint": b.Endpoint, "endpoint_revision": b.EndpointRevision, "relay_id": relay}
state := newRoverStreamState(time.Now())
state.budget = p.Budget
ctx, cancel := context.WithCancel(parent)
var workers sync.WaitGroup
defer func() { cancel(); workers.Wait() }()
workers.Add(2)
workers.Add(3)
optional := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
defer optional.CloseIdleConnections()
go func() { defer workers.Done(); roverDiagnosticsLane(ctx, optional, b.Endpoint, base, state) }()
go func() { defer workers.Done(); roverTelemetry(ctx, telemetry, b.Endpoint, base, state) }()
go func() { defer workers.Done(); roverCommands(ctx, stream, b.Endpoint, base, state) }()
var model *sensorModel
@@ -92,32 +90,17 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
if model == nil {
return
}
var diagnostic roverDiagnostics
workers.Add(1)
go func() { defer workers.Done(); p.roverDev(ctx, model, state) }()
diagnostic := roverDiagnostics{lane: "local", epoch: relay, started: state.origin}
var delivery roverLocalDelivery
for ctx.Err() == nil && sameRoverBinding(&b, p.roverBinding()) {
select {
case <-state.wake:
default:
}
started := time.Now()
watch, command, stop := state.delivery(started)
frame := roverFrame{}
if command != nil {
frame.Session, _ = command["id"].(string)
frame.Sequence, _ = command["sequence"].(float64)
frame.TTLMS, _ = command["ttl_ms"].(float64)
}
call, done := context.WithTimeout(ctx, 25*time.Millisecond)
result, driverErr := p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay})
done()
frame.DriverMS = time.Since(started).Milliseconds()
if driverErr != nil {
state.stopStream()
frame.Stage = "driver_transport"
state.delivered(map[string]any{}, 0)
} else {
state.delivered(result, stop)
frame.State, _ = result["state"].(string)
}
frame := delivery.run(ctx, p.Sensors, model, state, relay, started)
diagnostic.record(started, frame)
// New intent and stop signals bypass the periodic watchdog tick. The
// buffered wake channel coalesces arrivals; it never queues commands.
@@ -135,30 +118,86 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
done()
}
func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
var diagnostic roverDiagnostics
epoch, _ := base["relay_id"].(string)
diagnostic := roverDiagnostics{lane: "telemetry", epoch: epoch, started: state.origin}
var budgetAt time.Time
var metadata roverMetadataEncoder
connected := false
for ctx.Err() == nil {
if !connected {
connected = roverConnectTelemetry(ctx, client, endpoint, base, state)
budgetAt = time.Time{}
metadata.reset()
if !connected {
if !roverWait(ctx, 250*time.Millisecond) {
return
}
continue
}
}
// Keep transport liveness separate from sample freshness. A stamped
// observation ages in transit; waiting for its reply cannot renew motion.
started := time.Now()
snapshot, _ := state.view()
snapshot, sampleClock := state.telemetryView()
payload := make(map[string]any, len(base)+1)
for k, v := range base {
payload[k] = v
}
payload["rover"] = snapshot
state.mu.Lock()
budgetInterval := state.budgetInterval
compact := state.roverDetails
state.mu.Unlock()
if compact {
live, details := metadata.encode(snapshot, started)
if details != nil {
payload["rover"], payload["rover_details_v1"] = live, details
}
}
if state.budget != nil && (!budgetInterval || budgetAt.IsZero() || started.Sub(budgetAt) >= time.Second) {
payload["link_budget"] = state.budget.Snapshot()
budgetAt = started
}
requestClient := *client
if sampleClock != nil {
payload["sample_clock"] = sampleClock
requestClient.Timeout = 2 * time.Second
}
state.mu.Lock()
dedicated := state.diagnosticLane
state.mu.Unlock()
payload["diagnostic_lane_v1"] = dedicated
payload["diagnostic_options_v1"] = true
if !dedicated {
if dev := state.devPayload(); dev != nil {
payload["diagnostics"] = dev
payload["diagnostic_relay_ack_v1"] = true
}
}
marshalAt := time.Now()
raw, _ := json.Marshal(payload)
marshalMS := float64(time.Since(marshalAt).Microseconds()) / 1000
state.budget.ObserveCriticalBytes(len(raw))
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover", bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
frame := roverFrame{}
var trace *roverHTTPTrace
if state.devTraceEnabled() {
trace = newRoverHTTPTrace(started, len(raw))
req = req.WithContext(trace.context(req.Context()))
}
frame := roverFrame{MarshalMS: marshalMS, RequestBytes: len(raw), ReleaseConfirmed: roverReleaseEvidence(snapshot)}
frame.State, _ = snapshot["state"].(string)
if frame.State == "preparing" || frame.State == "ready" || frame.State == "driving" || frame.State == "stopping" {
frame.Session, _ = snapshot["session_id"].(string)
}
response, err := client.Do(req)
processingMS := 0.0
response, err := requestClient.Do(req)
if err != nil {
frame.Stage = "telemetry_transport"
} else {
frame.Status = response.StatusCode
var out roverStreamReply
readErr := json.NewDecoder(io.LimitReader(response.Body, 32768)).Decode(&out)
readErr := json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&out)
response.Body.Close()
if readErr != nil || response.StatusCode != 200 {
frame.Stage = "telemetry_response"
@@ -166,10 +205,29 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
frame.Stage = "clock_invalid"
state.stopStream()
} else {
processingMS = out.CoreProcessingMS
state.mu.Lock()
state.diagnosticPending = out.DiagnosticsPending
hasIntent := state.command != nil
state.mu.Unlock()
state.budget.SetControl(roverControlActive(snapshot, hasIntent, out.ControlActive))
state.setWatch(out.Watch)
state.setDev(out.Diagnostics)
}
}
if frame.Stage != "" {
connected = false
}
frame.CoreProcessingMS = processingMS
frame.CoreMS = time.Since(started).Milliseconds()
if frame.Stage == "" || frame.Stage == "telemetry_transport" {
state.budget.ObserveExchange(time.Since(started), processingMS, frame.Stage == "")
}
details := map[string]any{"elapsed_ms": frame.CoreMS, "http_status": frame.Status, "error_stage": frame.Stage, "reason": roverErrorKind(err), "marshal_ms": marshalMS, "request_bytes": len(raw), "core_processing_ms": processingMS, "epoch": epoch, "sample_mono_ms": float64(started.Sub(state.origin).Microseconds()) / 1000}
if trace != nil {
details["transport"] = trace.snapshot()
}
state.recordDev("telemetry", details)
diagnostic.record(started, frame)
_, watch := state.view()
delay := 500 * time.Millisecond
@@ -182,18 +240,29 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
}
}
func roverCommands(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
defer state.budget.DisableDatagramFeedback()
for ctx.Err() == nil {
_, watch := state.view()
if !watch {
state.budget.DisableDatagramFeedback()
if !roverWait(ctx, 50*time.Millisecond) {
return
}
continue
}
err := roverReadStream(ctx, client, endpoint, base, state)
state.mu.Lock()
datagram := state.latestDatagram
state.mu.Unlock()
var err error
if datagram {
err = roverReadDatagram(ctx, client, endpoint, base, state)
} else {
err = roverReadStream(ctx, client, endpoint, base, state)
}
state.stopStream()
if err != nil && ctx.Err() == nil {
log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\"}")
log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\",\"reason\":%q}", roverErrorKind(err))
state.recordDev("stream_disconnected", map[string]any{"reason": roverErrorKind(err)})
}
if !roverWait(ctx, 250*time.Millisecond) {
return
@@ -223,6 +292,7 @@ func roverReadStream(parent context.Context, client *http.Client, endpoint strin
first := true
for {
line, err := reader.ReadSlice('\n')
received := time.Now()
if err != nil {
return err
}
@@ -239,6 +309,7 @@ func roverReadStream(parent context.Context, client *http.Client, endpoint strin
if !state.accept(out) {
return errors.New("invalid stream intent")
}
state.receivedFrame(out, received)
if !out.Watch {
return nil
}
@@ -0,0 +1,20 @@
package node
// A terminal status is history, not continuing command authority. The driver
// reports its actual worker/lease, including cleanup before the worker exits.
// Older drivers use explicit known states; an unknown projection reserves
// control until a fresh authoritative snapshot arrives.
func roverControlActive(snapshot map[string]any, hasIntent bool, coreActive *bool) bool {
if hasIntent || (coreActive != nil && *coreActive) {
return true
}
if active, ok := snapshot["control_active"].(bool); ok {
return active
}
switch snapshot["state"] {
case "observing", "stopped", "receiver", "fault":
return false
default:
return true
}
}
@@ -0,0 +1,75 @@
package node
import (
"testing"
"time"
)
func TestRoverActivitySeparatesTerminalHistoryFromLiveAuthority(t *testing.T) {
yes, no := true, false
for _, state := range []string{"fault", "stopped", "receiver", "observing"} {
for _, explicit := range []bool{false, true} {
snapshot := map[string]any{"state": state, "release_confirmed": false}
if explicit {
snapshot["control_active"] = false
}
if roverControlActive(snapshot, false, &no) {
t.Fatal("terminal history took control reserve", state)
}
if !roverControlActive(snapshot, true, &no) || !roverControlActive(snapshot, false, &yes) {
t.Fatal("live intent lost priority", state)
}
snapshot["control_active"] = true
if !roverControlActive(snapshot, false, &no) {
t.Fatal("live cleanup worker lost priority", state)
}
}
}
for _, state := range []string{"preparing", "ready", "driving", "stopping", "", "future-state"} {
if !roverControlActive(map[string]any{"state": state}, false, nil) {
t.Fatal("legacy active/unknown state lost reserve", state)
}
}
}
func TestTerminalFaultAllowsInventoryWithoutAnObservatoryOrCommandFrames(t *testing.T) {
b, now := testBudget(t)
b.SetControl(true)
b.ObserveCommandFrame(200*time.Millisecond, 20*time.Millisecond)
if !b.commandLimited(*now) {
t.Fatal("missing initial command pressure")
}
b.effective = float64(b.policy.ReserveKbps + 128)
delivered := 0
stopped := map[string]any{"state": "fault", "control_active": false, "release_confirmed": false}
for elapsed := time.Duration(0); elapsed < 20*time.Second; elapsed += 10 * time.Millisecond {
*now = now.Add(10 * time.Millisecond)
// A closed observatory intentionally sends no stream frames. Driver and
// board telemetry still refresh their actual inactive state.
if elapsed%(500*time.Millisecond) == 0 {
b.SetControl(roverControlActive(stopped, false, nil))
}
b.ObserveCommandSilence()
if b.commandLimited(*now) {
t.Fatal("closed observer starved inventory again")
}
if delivered < 40*1024 {
size := min(linkPacket, 40*1024-delivered)
if ok, _ := b.Try("inventory", size); ok {
delivered += size
}
}
}
if delivered != 40*1024 {
t.Fatal("inventory never recovered", delivered)
}
// Resuming real control must still respond to a new delayed frame.
b.SetControl(true)
b.ObserveCommandFrame(151*time.Millisecond, 20*time.Millisecond)
if ok, _ := b.Try("inventory", 100); ok {
t.Fatal("inventory bypassed active command pressure")
}
if b.reserve(*now) < 512 {
t.Fatal("control reserve changed")
}
}
@@ -0,0 +1,218 @@
package node
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/url"
"strconv"
"time"
)
type roverDatagramGrant struct {
Channel string `json:"channel"`
SendKey string `json:"send_key"`
ReceiveKey string `json:"receive_key"`
Port int `json:"port"`
MaxPacket int `json:"max_packet"`
Lifetime int `json:"lifetime_s"`
}
type roverDatagramFrame struct {
Probe uint64 `json:"probe"`
ProbeClock roverClock `json:"probe_clock"`
Reply roverStreamReply `json:"reply"`
}
type roverDatagramReceived struct {
raw []byte
counter uint64
at time.Time
}
func roverReadDatagram(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) error {
// Only the paired mTLS connection can disclose the ephemeral keys. No UDP
// packet establishes identity, grants motion or chooses a different endpoint.
raw, _ := json.Marshal(base)
setup, cancel := context.WithTimeout(ctx, 2500*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(setup, "POST", endpoint+"/v1/node/rover-datagram", bytes.NewReader(raw))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
response, err := client.Do(req)
if err != nil {
return err
}
var grant roverDatagramGrant
err = json.NewDecoder(io.LimitReader(response.Body, 2048)).Decode(&grant)
response.Body.Close()
if err != nil || response.StatusCode != 200 || grant.Port < 1 || grant.Port > 65535 || grant.MaxPacket != roverDatagramLimit || grant.Lifetime != 86400 {
return errors.New("datagram negotiation rejected")
}
tx, err := newRoverDatagramCipher(grant.Channel, grant.SendKey)
if err != nil {
return err
}
rx, err := newRoverDatagramCipher(grant.Channel, grant.ReceiveKey)
if err != nil {
return err
}
parsed, err := url.Parse(endpoint)
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" {
return errors.New("invalid datagram endpoint")
}
address, err := net.ResolveUDPAddr("udp4", net.JoinHostPort(parsed.Hostname(), strconv.Itoa(grant.Port)))
if err != nil {
return err
}
conn, err := net.DialUDP("udp4", nil, address)
if err != nil {
return err
}
return roverReceiveDatagrams(ctx, conn, tx, rx, grant.Channel, state)
}
func roverReceiveDatagrams(ctx context.Context, conn *net.UDPConn, tx, rx *roverDatagramCipher, channel string, state *roverStreamState) error {
// A one-element mailbox replaces unread datagrams; no old command backlog
// is replayed after a scheduling pause. Only authenticated packets enter it.
incoming := make(chan roverDatagramReceived, 1)
done := make(chan struct{})
go func() {
defer close(done)
for {
packet := make([]byte, roverDatagramLimit+1)
n, err := conn.Read(packet)
if err != nil {
return
}
at := time.Now()
raw, counter, ok := rx.open(packet[:n])
if !ok {
continue
}
item := roverDatagramReceived{raw, counter, at}
select {
case incoming <- item:
default:
select {
case <-incoming:
default:
}
select {
case incoming <- item:
default:
}
}
}
}()
defer func() { conn.Close(); <-done }()
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
// Startup has no command authority. Once a valid first frame arrives, the
// exact same 350 ms authority guard applies. Silence does not close a
// usable UDP socket; a separate 2 s bound renegotiates expired transport keys.
lastFrame := time.Now()
seenFrame, suspended := false, false
guard := time.NewTimer(2 * time.Second)
defer guard.Stop()
state.budget.EnableDatagramFeedback()
suspend := func() {
if suspended {
return
}
state.stopStream() // Retire authority now; never replay it on recovery.
suspended = true
state.recordDev("stream_suspended", map[string]any{"reason": "datagram_stream_deadline", "channel": channel})
}
type probeSample struct {
at time.Time
optionalBytes uint64
}
probes := map[uint64]probeSample{}
send := func() error {
packet, err := tx.seal([]byte("{}"))
if err != nil {
return err
}
now := time.Now()
probes[tx.sent] = probeSample{now, state.budget.DatagramFeedbackMark()}
state.budget.ObserveCriticalBytes(len(packet))
for seq, sample := range probes {
if now.Sub(sample.at) > 2*time.Second {
delete(probes, seq)
}
}
conn.SetWriteDeadline(now.Add(25 * time.Millisecond))
_, err = conn.Write(packet)
return err
}
if err := send(); err != nil {
return err
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
return errors.New("datagram socket closed")
case <-guard.C:
// A stale mailbox item may have suspended authority before this
// timer branch runs. Only elapsed silence expires the transport;
// suspension itself is never evidence of a 2 s link outage.
if time.Since(lastFrame) >= 2*time.Second {
return errors.New("datagram link timeout")
}
suspend()
guard.Reset(max(0, 2*time.Second-time.Since(lastFrame)))
case <-ticker.C:
if err := send(); err != nil {
return err
}
case item := <-incoming:
// Check elapsed time even when both a packet and the timer are ready.
// Receipt can restore transport health, never an interrupted lease.
if time.Since(lastFrame) >= 2*time.Second {
return errors.New("datagram link timeout")
}
if seenFrame && time.Since(lastFrame) >= 350*time.Millisecond {
suspend()
}
if time.Since(item.at) >= 350*time.Millisecond {
suspend()
continue // Discard delayed local work without closing the receiver.
}
var frame roverDatagramFrame
if json.Unmarshal(item.raw, &frame) != nil {
return errors.New("invalid datagram frame")
}
if sent, ok := probes[frame.Probe]; ok {
if !state.sampleClock(frame.ProbeClock, sent.at, item.at) {
return errors.New("invalid datagram clock")
}
state.budget.ObserveDatagramFeedback(item.at.Sub(sent.at), frame.Reply.Clock.MonotonicMS-frame.ProbeClock.MonotonicMS, sent.optionalBytes)
for seq := range probes {
if seq <= frame.Probe {
delete(probes, seq)
}
}
}
if !state.accept(frame.Reply) {
return errors.New("invalid datagram intent")
}
state.receivedFrame(frame.Reply, item.at)
state.recordDev("datagram_received", map[string]any{"channel": channel, "packet_sequence": item.counter, "bytes": len(item.raw) + 44})
if !frame.Reply.Watch {
return nil
}
if suspended {
state.recordDev("stream_resumed", map[string]any{"channel": channel, "gap_ms": float64(item.at.Sub(lastFrame).Microseconds()) / 1000})
}
lastFrame, seenFrame, suspended = item.at, true, false
guard.Reset(max(0, 350*time.Millisecond-time.Since(item.at)))
}
}
}
@@ -0,0 +1,68 @@
package node
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"encoding/hex"
"errors"
)
const roverDatagramLimit = 1200
const roverDatagramCounterLimit = 1<<32 - 1
// Keys are independent in each direction and exist only for this negotiated
// generation. The authenticated counter is both nonce and anti-replay order.
type roverDatagramCipher struct {
channel []byte
aead cipher.AEAD
sent, received uint64
}
func newRoverDatagramCipher(channel, key string) (*roverDatagramCipher, error) {
id, e1 := hex.DecodeString(channel)
raw, e2 := hex.DecodeString(key)
if e1 != nil || e2 != nil || len(id) != 16 || len(raw) != 32 {
return nil, errors.New("invalid datagram key")
}
block, err := aes.NewCipher(raw)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &roverDatagramCipher{channel: id, aead: aead}, nil
}
func (c *roverDatagramCipher) seal(raw []byte) ([]byte, error) {
if len(raw)+44 > roverDatagramLimit || c.sent >= roverDatagramCounterLimit {
return nil, errors.New("datagram bound exceeded")
}
c.sent++
header := make([]byte, 28)
copy(header, "MCR1")
copy(header[4:], c.channel)
binary.BigEndian.PutUint64(header[20:], c.sent)
nonce := make([]byte, 12)
copy(nonce[4:], header[20:])
return c.aead.Seal(header, nonce, raw, header), nil
}
func (c *roverDatagramCipher) open(packet []byte) ([]byte, uint64, bool) {
if len(packet) <= 44 || len(packet) > roverDatagramLimit || string(packet[:4]) != "MCR1" || !bytes.Equal(packet[4:20], c.channel) {
return nil, 0, false
}
counter := binary.BigEndian.Uint64(packet[20:28])
if counter <= c.received || counter > roverDatagramCounterLimit {
return nil, 0, false
}
nonce := make([]byte, 12)
copy(nonce[4:], packet[20:28])
raw, err := c.aead.Open(nil, nonce, packet[28:], packet[:28])
if err != nil {
return nil, 0, false
}
c.received = counter
return raw, counter, true
}
@@ -0,0 +1,43 @@
package node
import (
"bytes"
"encoding/hex"
"testing"
)
func TestRoverDatagramAuthenticationAndOrdering(t *testing.T) {
channel := "11111111111111111111111111111111"
key := "2222222222222222222222222222222222222222222222222222222222222222"
tx, _ := newRoverDatagramCipher(channel, key)
rx, _ := newRoverDatagramCipher(channel, key)
a, _ := tx.seal([]byte("{}"))
b, _ := tx.seal([]byte("{\"fresh\":true}"))
corrupt := append([]byte(nil), b...)
corrupt[len(corrupt)-1] ^= 1
if _, _, ok := rx.open(corrupt); ok {
t.Fatal("forgery accepted")
}
if raw, seq, ok := rx.open(b); !ok || seq != 2 || !bytes.Equal(raw, []byte("{\"fresh\":true}")) {
t.Fatal("fresh frame rejected")
}
for _, packet := range [][]byte{a, b, append(b, 0), b[:20]} {
if _, _, ok := rx.open(packet); ok {
t.Fatal("stale/malformed accepted")
}
}
other, _ := newRoverDatagramCipher(channel, "3333333333333333333333333333333333333333333333333333333333333333")
if _, _, ok := other.open(b); ok {
t.Fatal("opposite direction accepted")
}
tx.sent = roverDatagramCounterLimit
if _, err := tx.seal([]byte("{}")); err == nil {
t.Fatal("counter wrapped")
}
if _, err := rx.seal(make([]byte, 1200)); err == nil {
t.Fatal("oversized datagram")
}
if hex.EncodeToString(a) != "4d43523111111111111111111111111111111111000000000000000108b7c9b2eb8c526f9dc03ac92264617fd09b" {
t.Fatal("Python/Go vector mismatch")
}
}
@@ -0,0 +1,218 @@
package node
// Bounded loopback receiver tests. No driver, serial port or physical actuator.
import (
"context"
"encoding/json"
"fmt"
"net"
"testing"
"time"
)
type continuityRig struct {
t *testing.T
state *roverStreamState
peer *net.UDPConn
address *net.UDPAddr
tx, rx *roverDatagramCipher
result chan error
ended bool
origin time.Time
}
func newContinuityRig(t *testing.T) *continuityRig {
t.Helper()
peer, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.1")})
if err != nil {
t.Fatal(err)
}
conn, err := net.DialUDP("udp4", nil, peer.LocalAddr().(*net.UDPAddr))
if err != nil {
peer.Close()
t.Fatal(err)
}
const channel = "11111111111111111111111111111111"
const a = "2222222222222222222222222222222222222222222222222222222222222222"
const b = "3333333333333333333333333333333333333333333333333333333333333333"
tx, _ := newRoverDatagramCipher(channel, a)
rx, _ := newRoverDatagramCipher(channel, b)
ptx, _ := newRoverDatagramCipher(channel, b)
prx, _ := newRoverDatagramCipher(channel, a)
now := time.Now()
s := newRoverStreamState(now)
s.budget, err = OpenLinkBudget("")
if err != nil {
t.Fatal(err)
}
s.setDev(map[string]any{"id": testClockID, "enabled": true})
f := &continuityRig{t: t, state: s, peer: peer, tx: ptx, rx: prx, result: make(chan error, 1), origin: now}
ctx, cancel := context.WithCancel(context.Background())
go func() { f.result <- roverReceiveDatagrams(ctx, conn, tx, rx, channel, s) }()
t.Cleanup(func() {
cancel()
peer.Close()
if !f.ended {
select {
case <-f.result:
case <-time.After(time.Second):
t.Error("receiver leaked")
}
}
})
f.send("", 0)
f.ackStop()
return f
}
func (f *continuityRig) clock() roverClock {
return roverClock{testClockID, 10000 + float64(time.Since(f.origin).Microseconds())/1000}
}
func (f *continuityRig) send(id string, seq float64) []byte {
f.t.Helper()
f.peer.SetReadDeadline(time.Now().Add(time.Second))
packet := make([]byte, 1201)
n, addr, err := f.peer.ReadFromUDP(packet)
if err != nil {
f.t.Fatal(err)
}
_, probe, ok := f.rx.open(packet[:n])
if !ok {
f.t.Fatal("invalid probe")
}
f.address = addr
clock := f.clock()
reply := roverStreamReply{Watch: true, Clock: clock}
if id != "" {
reply.Command = map[string]any{"id": id, "sequence": seq, "left": float64(0), "right": float64(0), "settings": map[string]any{}, "expires_mono_ms": clock.MonotonicMS + 400}
}
raw, _ := json.Marshal(roverDatagramFrame{Probe: probe, ProbeClock: clock, Reply: reply})
sealed, err := f.tx.seal(raw)
if err != nil {
f.t.Fatal(err)
}
f.state.mu.Lock()
before := f.state.streamReceived
f.state.mu.Unlock()
if _, err = f.peer.WriteToUDP(sealed, addr); err != nil {
f.t.Fatal(err)
}
f.wait(func() bool { f.state.mu.Lock(); defer f.state.mu.Unlock(); return f.state.streamReceived.After(before) }, time.Second)
return sealed
}
func (f *continuityRig) wait(check func() bool, limit time.Duration) {
f.t.Helper()
until := time.Now().Add(limit)
for time.Now().Before(until) {
if check() {
return
}
select {
case err := <-f.result:
f.ended = true
f.t.Fatalf("transport ended instead of staying connected: %v", err)
default:
}
time.Sleep(time.Millisecond)
}
f.t.Fatal("bounded condition not reached")
}
func (f *continuityRig) ackStop() {
_, _, revision := f.state.delivery(time.Now())
f.state.delivered(map[string]any{"state": "stopped", "release_confirmed": true}, revision)
}
func (f *continuityRig) command() map[string]any { _, c, _ := f.state.delivery(time.Now()); return c }
func (f *continuityRig) awaitSafetyStop() {
f.t.Helper()
f.wait(func() bool { f.state.mu.Lock(); defer f.state.mu.Unlock(); return f.state.stopPending }, 450*time.Millisecond)
if c := f.command(); c != nil {
f.t.Fatal("motion authority retained after silence")
}
}
func TestRoverDatagramSilenceStopsAuthorityWithoutClosingTransport(t *testing.T) {
f := newContinuityRig(t)
old := "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
f.send(old, 1)
if f.command() == nil {
t.Fatal("neutral fixture not admitted")
}
f.awaitSafetyStop()
f.ackStop()
f.send(old, 2)
if f.command() != nil {
t.Fatal("retired authority revived")
}
f.send("cccccccccccccccccccccccccccccccc", 1)
if c := f.command(); c == nil || c["left"] != float64(0) || c["right"] != float64(0) {
t.Fatal("fresh neutral identity not admitted on existing transport")
}
}
func TestRoverDatagramReplayCannotKeepAuthorityAlive(t *testing.T) {
f := newContinuityRig(t)
raw := f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1)
for n := 0; n < 8; n++ {
time.Sleep(50 * time.Millisecond)
f.peer.WriteToUDP(raw, f.address)
}
f.awaitSafetyStop()
f.ackStop()
f.send("cccccccccccccccccccccccccccccccc", 1)
if f.command() == nil {
t.Fatal("authenticated channel failed to recover")
}
}
func TestRoverDatagramProlongedSilenceRenegotiatesAfterSafetyStop(t *testing.T) {
f := newContinuityRig(t)
f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1)
f.awaitSafetyStop()
f.ackStop()
select {
case err := <-f.result:
f.ended = true
if err == nil || err.Error() != "datagram link timeout" {
t.Fatalf("wrong reconnect cause: %v", err)
}
case <-time.After(2100 * time.Millisecond):
t.Fatal("silent transport did not renegotiate")
}
if f.command() != nil {
t.Fatal("authority retained during reconnect")
}
}
// Both the expired guard and a stale mailbox item can be ready after local
// scheduling pauses. Exercise both select orders without a physical driver.
func TestRoverDatagramDelayedLocalWorkRetainsRecoveryWindow(t *testing.T) {
for attempt := 0; attempt < 12; attempt++ {
t.Run(fmt.Sprint(attempt), func(t *testing.T) {
f := newContinuityRig(t)
f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1)
f.state.mu.Lock()
previousCommand := f.state.command
f.state.mu.Unlock()
queue := func() {
raw, _ := json.Marshal(roverDatagramFrame{Reply: roverStreamReply{Watch: true, Clock: f.clock(), Command: previousCommand}})
packet, err := f.tx.seal(raw)
if err != nil {
t.Fatal(err)
}
if _, err = f.peer.WriteToUDP(packet, f.address); err != nil {
t.Fatal(err)
}
}
func() {
f.state.mu.Lock()
defer f.state.mu.Unlock()
queue()
time.Sleep(30 * time.Millisecond)
queue()
time.Sleep(400 * time.Millisecond)
}()
f.awaitSafetyStop()
f.ackStop()
f.send("cccccccccccccccccccccccccccccccc", 1)
if f.command() == nil {
t.Fatal("fresh neutral authority not admitted after local pause")
}
})
}
}
+206
View File
@@ -0,0 +1,206 @@
package node
// Optional recorder transport is independent of the 25 ms motor-delivery path.
// No files, controller queries, command retries or lease changes originate here.
import (
"context"
"encoding/json"
"errors"
"io"
"net"
"time"
)
func roverErrorKind(err error) string {
if err == nil {
return ""
}
if errors.Is(err, context.DeadlineExceeded) {
return "deadline"
}
if errors.Is(err, context.Canceled) {
return "cancelled"
}
if errors.Is(err, io.EOF) {
return "eof"
}
var n net.Error
if errors.As(err, &n) && n.Timeout() {
return "network_timeout"
}
switch err.Error() {
case "stream rejected", "invalid command frame", "invalid stream clock", "invalid stream intent", "stream deadline":
return err.Error()
// These fixed, locally generated failures must remain distinguishable.
// Never emit arbitrary transport errors: they can contain paired URLs.
case "datagram negotiation rejected":
return "datagram_negotiation_rejected"
case "invalid datagram endpoint":
return "datagram_endpoint_invalid"
case "datagram socket closed":
return "datagram_socket_closed"
case "datagram link timeout":
return "datagram_link_timeout"
case "datagram stream deadline":
return "datagram_stream_deadline"
case "invalid datagram frame":
return "datagram_frame_invalid"
case "invalid datagram clock":
return "datagram_clock_invalid"
case "datagram receipt stale":
return "datagram_receipt_stale"
case "invalid datagram intent":
return "datagram_intent_invalid"
}
return "transport_error" // Raw errors can contain private URLs; never emit them.
}
func (s *roverStreamState) setDev(value map[string]any) {
s.mu.Lock()
defer s.mu.Unlock()
if value == nil {
return
}
id, ok := value["id"].(string)
enabled, valid := value["enabled"].(bool)
if !ok || len(id) != 32 || !valid {
return
}
if s.devID != id {
s.devID = id
s.devSequence = 0
s.devRelayAfter = 0
s.devEvents = nil
s.devPacket = nil
s.devBudgetAt = time.Time{}
}
s.devEnabled = enabled
s.devDesired = make(map[string]any, len(value))
for k, v := range value {
if k != "relay_after" {
s.devDesired[k] = v
}
}
if ack, ok := finiteNumber(value["relay_after"]); ok && ack >= 0 && ack <= float64(s.devSequence) {
s.devRelayAfter = max(s.devRelayAfter, int64(ack))
}
s.devAfter = value["after"]
}
func devOption(options any, key string) bool {
if value, ok := options.(map[string]any); ok {
if flag, ok := value[key].(bool); ok {
return flag
}
}
return true // Legacy capture keeps its original explicit behavior.
}
func (s *roverStreamState) recordDev(event string, data map[string]any) {
s.mu.Lock()
defer s.mu.Unlock()
if s.devID == "" || !s.devEnabled || !devOption(s.devDesired["options"], "network") {
return
}
// UTC microseconds fit exactly in JSON and keep sequence unique across relay restarts.
s.devSequence = max(s.devSequence+1, time.Now().UnixMicro())
row := map[string]any{"source": "node", "event": event, "record_sequence": s.devSequence,
"at_utc": time.Now().UTC().Format(time.RFC3339Nano), "monotonic_ms": float64(time.Since(s.origin).Microseconds()) / 1000}
for k, v := range data {
row[k] = v
}
s.devEvents = append(s.devEvents, row)
if len(s.devEvents) > 64 {
s.devEvents = s.devEvents[len(s.devEvents)-64:]
}
}
func (s *roverStreamState) devRequest() map[string]any {
s.mu.Lock()
defer s.mu.Unlock()
if s.devID == "" {
return nil
}
if !s.devEnabled && s.devDesired["export"] == nil {
if storage, ok := s.devPacket["storage"].(map[string]any); ok && storage["closed"] == true && (!devOption(s.devDesired["options"], "live") || s.devAfter == s.devPacket["sequence"]) {
return nil
}
}
result := map[string]any{}
for k, v := range s.devDesired {
result[k] = v
}
result["relay_events"] = append([]map[string]any{}, s.devEvents...)
return result
}
func (s *roverStreamState) devPayload() map[string]any {
s.mu.Lock()
defer s.mu.Unlock()
if s.devID == "" {
return nil
}
result := map[string]any{"id": s.devID, "frames": []any{}, "vehicle": s.devDesired["vehicle"]}
for k, v := range s.devPacket {
result[k] = v
}
if !s.devEnabled && s.devDesired["export"] == nil {
if storage, ok := s.devPacket["storage"].(map[string]any); ok && storage["closed"] == true && (!devOption(s.devDesired["options"], "live") || s.devAfter == s.devPacket["sequence"]) {
return map[string]any{"id": s.devID, "active": false, "storage": storage, "frames": []any{}}
}
}
pending := []map[string]any{}
for _, event := range s.devEvents {
if seq, ok := event["record_sequence"].(int64); ok && seq > s.devRelayAfter {
pending = append(pending, event)
}
}
if devOption(s.devDesired["options"], "live") {
result["relay_events"] = pending
} else {
result["relay_events"] = []any{}
result["frames"] = []any{}
}
return result
}
func (p *Pairing) roverDev(ctx context.Context, model *sensorModel, state *roverStreamState) {
for ctx.Err() == nil {
state.recordBudgetDev(time.Now())
if request := state.devRequest(); request != nil {
call, done := context.WithTimeout(ctx, 3*time.Second)
result, err := p.Sensors.modelDriver(call, model, "/drive-trace", request)
done()
if err == nil {
raw, _ := json.Marshal(result)
if len(raw) <= 256*1024 {
state.mu.Lock()
state.devPacket = result
state.mu.Unlock()
}
} else {
state.recordDev("diagnostics_transport", map[string]any{"reason": roverErrorKind(err)})
state.mu.Lock()
if state.devPacket == nil {
state.devPacket = map[string]any{}
}
state.devPacket["transport_error"] = roverErrorKind(err)
state.mu.Unlock()
}
}
if !roverWait(ctx, 100*time.Millisecond) {
return
}
}
}
// Budget evidence belongs to the optional local recorder lane, never to the
// motor delivery loop. One snapshot per second, and none outside DEV.
func (s *roverStreamState) recordBudgetDev(now time.Time) {
s.mu.Lock()
active := s.devEnabled && s.devID != "" && s.budget != nil &&
(s.devBudgetAt.IsZero() || now.Sub(s.devBudgetAt) >= time.Second)
if active {
s.devBudgetAt = now
}
s.mu.Unlock()
if active {
s.recordDev("link_budget", map[string]any{"budget": s.budget.Snapshot()})
}
}
@@ -0,0 +1,73 @@
package node
import (
"testing"
"time"
)
func TestDevCaptureOptInAndOff(t *testing.T) {
s := newRoverStreamState(time.Now())
s.recordDev("delivery", nil)
if s.devRequest() != nil || len(s.devEvents) != 0 {
t.Fatal("disabled recorder must be inert")
}
s.setDev(map[string]any{"id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "enabled": true, "after": float64(0)})
s.recordDev("delivery", map[string]any{"sequence": 42})
if len(s.devEvents) != 1 || s.devRequest()["enabled"] != true {
t.Fatal("capture not enabled")
}
if s.devEvents[0]["sequence"] != 42 || s.devEvents[0]["record_sequence"].(int64) <= 42 {
t.Fatal("command and trace cursors collide")
}
s.setDev(map[string]any{"id": s.devID, "enabled": false, "after": float64(0)})
s.recordDev("late", nil)
if len(s.devEvents) != 1 {
t.Fatal("capture continues after off")
}
s.devPacket = map[string]any{"sequence": float64(0), "storage": map[string]any{"closed": true}}
if s.devRequest() != nil {
t.Fatal("finished capture keeps polling driver")
}
if _, ok := s.devPayload()["relay_events"]; ok {
t.Fatal("finished capture keeps sending verbose events")
}
}
func TestDevDoesNotExtendMotionLease(t *testing.T) {
s := newRoverStreamState(time.Now())
before := s.stopRevision
s.setDev(map[string]any{"id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "enabled": true, "after": float64(0)})
if s.command != nil || s.stopRevision != before || !s.stopPending {
t.Fatal("DEV changed motion authority")
}
for i := 0; i < 100; i++ {
s.recordDev("sample", nil)
}
if len(s.devEvents) != 64 {
t.Fatal("unbounded relay RAM")
}
}
func TestDevNetworkAcknowledgementDoesNotDropOnboardRecords(t *testing.T) {
s := newRoverStreamState(time.Now())
id := "cccccccccccccccccccccccccccccccc"
s.setDev(map[string]any{"id": id, "enabled": true, "after": float64(0)})
s.recordDev("first", nil)
first := s.devSequence
s.recordDev("second", nil)
s.setDev(map[string]any{"id": id, "enabled": true, "after": float64(0), "relay_after": float64(first)})
network := s.devPayload()["relay_events"].([]map[string]any)
if len(network) != 1 || network[0]["event"] != "second" {
t.Fatal("acknowledged network events retransmitted")
}
request := s.devRequest()
if _, exists := request["relay_after"]; exists {
t.Fatal("Core ack leaked into native protocol")
}
if len(request["relay_events"].([]map[string]any)) != 2 {
t.Fatal("network ack discarded records before onboard writer")
}
s.setDev(map[string]any{"id": "dddddddddddddddddddddddddddddddd", "enabled": true, "after": float64(0)})
if s.devRelayAfter != 0 {
t.Fatal("ack leaked across sessions")
}
}
@@ -1,7 +1,7 @@
package node
// A bounded memory flight recorder. It never stores endpoints, certificates,
// payloads or raw HTTP errors, and never changes admission or lease deadlines.
// A bounded memory flight recorder. No endpoints, credentials or raw payloads.
// Both lanes use the relay epoch and one origin. Reporting never renews a lease.
import (
"encoding/json"
"log"
@@ -9,32 +9,51 @@ import (
)
type roverFrame struct {
AtMS int64 `json:"at_ms"`
GapMS int64 `json:"gap_ms"`
BindingMS int64 `json:"binding_ms"`
CoreMS int64 `json:"core_ms"`
DriverMS int64 `json:"driver_ms"`
Status int `json:"http_status"`
Stage string `json:"error_stage,omitempty"`
Session string `json:"session,omitempty"`
Sequence float64 `json:"sequence"`
TTLMS float64 `json:"ttl_ms"`
State string `json:"state"`
Delivery string `json:"delivery_mode,omitempty"`
Index uint64 `json:"index"`
AtMS int64 `json:"at_ms"`
GapMS int64 `json:"gap_ms"`
BindingMS int64 `json:"binding_ms"`
CoreMS int64 `json:"core_ms"`
DriverMS int64 `json:"driver_ms"`
Status int `json:"http_status"`
Stage string `json:"error_stage,omitempty"`
Reason string `json:"reason,omitempty"`
Session string `json:"session,omitempty"`
Sequence float64 `json:"sequence"`
TTLMS float64 `json:"ttl_ms"`
State string `json:"state"`
ReleaseConfirmed *bool `json:"release_confirmed"`
MarshalMS float64 `json:"marshal_ms,omitempty"`
RequestBytes int `json:"request_bytes,omitempty"`
CoreProcessingMS float64 `json:"core_processing_ms,omitempty"`
}
type roverDiagnostics struct {
frames []roverFrame
last time.Time
started time.Time
state string
session string
emit func([]byte)
frames []roverFrame
last time.Time
started time.Time
state string
session string
lane string
epoch string
stage string
pendingReason string
release *bool
lastEmit time.Time
activeUntil time.Time
controlSession string
index uint64
emitted uint64
emit func([]byte)
}
func (d *roverDiagnostics) record(at time.Time, frame roverFrame) {
if d.started.IsZero() {
d.started = at
}
d.index++
frame.Index = d.index
frame.AtMS = at.Sub(d.started).Milliseconds()
if !d.last.IsZero() {
frame.GapMS = at.Sub(d.last).Milliseconds()
@@ -44,18 +63,78 @@ func (d *roverDiagnostics) record(at time.Time, frame roverFrame) {
if len(d.frames) > 128 {
d.frames = d.frames[len(d.frames)-128:]
}
active := frame.Session != "" || d.session != ""
if frame.Session != "" {
d.activeUntil = at.Add(5 * time.Second)
d.controlSession = frame.Session
}
// Retirement used to suppress the ensuing stopping/fault/release result.
// Keep a bounded post-control window; idle observation remains silent.
active := frame.Session != "" || d.session != "" || at.Before(d.activeUntil)
changed := frame.State != d.state || frame.Session != d.session
if active && (changed || frame.Stage != "" || frame.GapMS >= 200) {
reason := d.pendingReason
releaseChanged := (frame.ReleaseConfirmed == nil) != (d.release == nil)
if frame.ReleaseConfirmed != nil && d.release != nil {
releaseChanged = *frame.ReleaseConfirmed != *d.release
}
if releaseChanged {
reason = "release_changed"
}
if d.stage != "" && frame.Stage == "" {
reason = "stage_recovered"
}
if changed {
reason = "state_changed"
}
if frame.GapMS >= 200 {
reason = "cycle_gap"
}
if frame.Stage != "" {
reason = frame.Stage
}
if frame.Reason != "" {
reason = frame.Reason
}
terminal := frame.State == "stopped" || frame.State == "stopping" || frame.State == "fault" || frame.State == "receiver"
urgent := releaseChanged || frame.Session != d.session || (changed && terminal) || frame.Stage != d.stage || frame.Delivery == "stop"
if active {
d.pendingReason = reason
} else {
d.pendingReason = ""
}
if active && reason != "" && (urgent || d.lastEmit.IsZero() || at.Sub(d.lastEmit) >= time.Second) {
// Emit newly captured frames plus at most two preceding context frames.
// Indexes expose both deduplication and any overwritten bounded history.
first := 0
if d.emitted > 2 {
for first < len(d.frames)-1 && d.frames[first].Index <= d.emitted-2 {
first++
}
}
raw, _ := json.Marshal(struct {
Event string `json:"event"`
Frames []roverFrame `json:"frames"`
}{"rover-channel", d.frames})
Event string `json:"event"`
Schema string `json:"schema"`
Epoch string `json:"epoch"`
Lane string `json:"lane"`
Origin string `json:"origin_utc"`
Reason string `json:"reason"`
ControlSession string `json:"control_session,omitempty"`
Frames []roverFrame `json:"frames"`
}{"rover-channel", "missioncore.rover-timeline/v1", d.epoch, d.lane,
d.started.UTC().Format(time.RFC3339Nano), reason, d.controlSession, d.frames[first:]})
if d.emit != nil {
d.emit(raw)
} else {
log.Printf("%s", raw)
}
d.lastEmit, d.emitted = at, d.index
d.pendingReason = ""
}
d.state, d.session = frame.State, frame.Session
d.state, d.session, d.stage, d.release = frame.State, frame.Session, frame.Stage, frame.ReleaseConfirmed
}
func roverReleaseEvidence(snapshot map[string]any) *bool {
if value, ok := snapshot["release_confirmed"].(bool); ok {
return &value
}
return nil
}
@@ -0,0 +1,194 @@
package node
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"time"
)
// Paces actual reads by net/http in bounded chunks. It holds no control/state
// locks and cancellation interrupts the wait. Content-Length stays explicit.
type budgetReader struct {
started bool
ctx context.Context
source io.Reader
budget *LinkBudget
class string
}
func (r *budgetReader) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
if !r.started {
r.started = true
if source, ok := r.source.(interface{ Len() int }); ok {
r.budget.RequestDemand(r.class, source.Len())
}
}
n, err := r.source.Read(p[:min(len(p), linkPacket)])
if n == 0 {
return n, err
}
for {
if e := r.ctx.Err(); e != nil {
return 0, e
}
granted, wait := r.budget.Try(r.class, n)
if granted {
return n, err
}
if !roverWait(r.ctx, wait) {
return 0, r.ctx.Err()
}
}
}
// Fit a network view without discarding the complete onboard session file.
// Export and lifecycle metadata come first. Live-view gaps remain explicit at
// Core; only delivered record sequences are acknowledged. Live rows use 12 KB;
// one negotiated 64 KiB export block has a separate bounded allowance.
func boundedDevPacket(packet map[string]any) map[string]any {
if packet == nil {
return nil
}
out := make(map[string]any, len(packet))
for k, v := range packet {
if k != "frames" && k != "relay_events" {
out[k] = v
}
}
export, _ := json.Marshal(out["export"])
if len(export) > 90*1024 {
delete(out, "export")
export = nil
}
liveBytes := 12 * 1024
if options, ok := packet["options"].(map[string]any); ok {
if rate, ok := finiteNumber(options["live_kbps"]); ok && rate >= 8 && rate <= 64 {
liveBytes = min(liveBytes, int(rate*125))
}
}
// The operator limit applies to event rows only. Lifecycle metadata and
// export have separate accounting; subtracting them here can reduce every
// 8-kbit/s live view to zero. Share unused capacity across both row sources.
allowance := liveBytes - 4 // Two JSON array delimiters; row commas counted below.
for _, key := range []string{"frames", "relay_events"} {
rows := []any{}
switch v := packet[key].(type) {
case []any:
rows = v
case []map[string]any:
for _, row := range v {
rows = append(rows, row)
}
}
kept := []any{}
used := 0
// Network view is latest-first admission, chronological delivery. A large
// old row must not permanently block newer evidence; full rows stay on disk.
for i := len(rows) - 1; i >= 0; i-- {
raw, _ := json.Marshal(rows[i])
if used+len(raw)+1 > allowance {
continue
}
kept = append(kept, rows[i])
used += len(raw) + 1
}
for i, j := 0, len(kept)-1; i < j; i, j = i+1, j-1 {
kept[i], kept[j] = kept[j], kept[i]
}
out[key] = kept
allowance -= used
}
return out
}
// A successful exchange has delivered this immutable block. Until Core asks
// for the next offset, send only the small status poll, never the same 64 KiB
// again. Failed exchanges retain the block for retry with the same identity.
func devExportKey(packet map[string]any) string {
export, ok := packet["export"].(map[string]any)
if !ok {
return ""
}
key, _ := json.Marshal([]any{export["capture_id"], export["token"], export["offset"], export["next"], export["sha256"]})
return string(key)
}
// Recorder lifecycle/status is a bounded metadata request. Live records and
// export bytes still use residual bulk capacity; they cannot hide in this lane.
func diagnosticTrafficClass(packet map[string]any) string {
if packet["export"] != nil {
return "bulk"
}
for _, key := range []string{"frames", "relay_events"} {
switch rows := packet[key].(type) {
case []any:
if len(rows) > 0 {
return "bulk"
}
case []map[string]any:
if len(rows) > 0 {
return "bulk"
}
}
}
return "inventory"
}
func roverDiagnosticsLane(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
lastExport := ""
for ctx.Err() == nil {
state.mu.Lock()
enabled := state.diagnosticLane && (state.diagnosticPending == nil || *state.diagnosticPending || state.devEnabled)
state.mu.Unlock()
if !enabled {
if !roverWait(ctx, 250*time.Millisecond) {
return
}
continue
}
payload := make(map[string]any, len(base)+1)
for k, v := range base {
payload[k] = v
}
packet := state.devPayload()
exportKey := devExportKey(packet)
if exportKey != "" && exportKey == lastExport {
delete(packet, "export")
}
payload["diagnostic_export_v2"] = true
payload["diagnostics"] = boundedDevPacket(packet)
raw, _ := json.Marshal(payload)
// On capable peers idle DEV sleeps until the existing telemetry reply
// announces work. Legacy peers keep polling. No recorder rows or exports
// travel on the critical lane; only a boolean wake hint does.
call, cancel := context.WithTimeout(ctx, pacedTimeout(len(raw)))
reader := &budgetReader{ctx: call, source: bytes.NewReader(raw), budget: state.budget, class: diagnosticTrafficClass(packet)}
req, _ := http.NewRequestWithContext(call, "POST", endpoint+"/v1/node/rover-diagnostics", reader)
req.ContentLength = int64(len(raw))
req.Header.Set("Content-Type", "application/json")
response, err := client.Do(req)
if err == nil {
var reply struct {
Diagnostics map[string]any `json:"diagnostics"`
}
err = json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&reply)
response.Body.Close()
if err == nil && response.StatusCode == 200 {
state.setDev(reply.Diagnostics)
if exportKey != "" {
lastExport = exportKey
}
}
}
cancel()
if !roverWait(ctx, time.Second) {
return
}
}
}
@@ -0,0 +1,63 @@
package node
import (
"encoding/json"
"strings"
"testing"
)
func TestDevMinimumRateDoesNotChargeLifecycleOrExportAgainstEvents(t *testing.T) {
for _, exported := range []bool{false, true} {
packet := map[string]any{
"id": "capture",
"options": map[string]any{"live_kbps": float64(8)},
"storage": map[string]any{"file": strings.Repeat("metadata", 180), "closed": false},
"frames": []any{map[string]any{"record_sequence": 1, "event": "capture_started"}},
"relay_events": []any{
map[string]any{"record_sequence": 2, "event": "oversized", "data": strings.Repeat("x", 2000)},
map[string]any{"record_sequence": 3, "event": "network", "data": strings.Repeat("x", 580)},
},
}
if exported {
packet["export"] = map[string]any{"data": strings.Repeat("A", 87384)}
}
bounded := boundedDevPacket(packet)
frames, relay := bounded["frames"].([]any), bounded["relay_events"].([]any)
if len(frames) != 1 || len(relay) != 1 || relay[0].(map[string]any)["record_sequence"] != 3 {
t.Fatal("minimum event rate starved by metadata or an oversized row", bounded["frames"], bounded["relay_events"])
}
eventBytes := 0
for _, rows := range [][]any{frames, relay} {
for _, row := range rows {
raw, _ := json.Marshal(row)
eventBytes += len(raw) + 1
}
}
if eventBytes > 1000 {
t.Fatal("event rate exceeded", eventBytes)
}
if bounded["storage"] == nil || (exported && bounded["export"] == nil) {
t.Fatal("lifecycle/export lost")
}
}
}
func TestDevMinimumRateAdmitsNearKilobyteMotorSample(t *testing.T) {
sample := map[string]any{"record_sequence": 1, "event": "sample", "data": ""}
raw, _ := json.Marshal(sample)
sample["data"] = strings.Repeat("x", 985-len(raw))
packet := map[string]any{
"options": map[string]any{"live_kbps": float64(8)},
"storage": map[string]any{"file": strings.Repeat("metadata", 180)},
"frames": []any{sample},
}
bounded := boundedDevPacket(packet)
frames := bounded["frames"].([]any)
if len(frames) != 1 {
t.Fatal("real-sized motor sample cannot pass minimum rate")
}
raw, _ = json.Marshal(frames)
if len(raw) > 1000 {
t.Fatal("sample exceeds event rate", len(raw))
}
}
@@ -61,3 +61,86 @@ func TestRoverDiagnosticsRecordsBindingWaitAndDriverTerminalState(t *testing.T)
t.Fatal(last)
}
}
func TestRoverTimelineSharesOriginAndKeepsReleaseAfterRetirement(t *testing.T) {
origin := time.Unix(100, 0)
var events []map[string]any
d := roverDiagnostics{started: origin, epoch: "relay", lane: "local", emit: func(raw []byte) {
var event map[string]any
if err := json.Unmarshal(raw, &event); err != nil {
t.Fatal(err)
}
events = append(events, event)
}}
d.record(origin.Add(time.Second), roverFrame{Session: "intent", State: "driving"})
d.record(origin.Add(1100*time.Millisecond), roverFrame{Delivery: "stop", Reason: "intent_expired", State: "stopping"})
no, yes := false, true
d.record(origin.Add(1500*time.Millisecond), roverFrame{State: "fault", ReleaseConfirmed: &no})
d.record(origin.Add(2500*time.Millisecond), roverFrame{State: "stopped", ReleaseConfirmed: &yes})
if len(events) != 4 {
t.Fatalf("lost release after retirement: %d", len(events))
}
for _, event := range events {
if event["epoch"] != "relay" || event["lane"] != "local" || event["origin_utc"] != origin.UTC().Format(time.RFC3339Nano) {
t.Fatal(event)
}
if event["control_session"] != "intent" {
t.Fatal("retired session correlation lost")
}
}
first := events[0]["frames"].([]any)[0].(map[string]any)
if first["at_ms"] != float64(1000) || first["release_confirmed"] != nil {
t.Fatal(first)
}
for i := 0; i < 200; i++ {
d.record(origin.Add(time.Duration(7+i)*time.Second), roverFrame{State: "stopped", Stage: "idle_error"})
}
if len(events) != 4 || len(d.frames) != 128 {
t.Fatal("post-control window must be bounded")
}
}
func TestRoverTimelineAvoidsRepeatedFullRingOnStateFlapping(t *testing.T) {
count, rows := 0, 0
var previous uint64
d := roverDiagnostics{emit: func(raw []byte) {
var event struct {
Frames []roverFrame `json:"frames"`
}
if err := json.Unmarshal(raw, &event); err != nil {
t.Fatal(err)
}
count++
rows += len(event.Frames)
if previous > 2 && event.Frames[0].Index < previous-1 {
t.Fatal("repeated older context")
}
previous = event.Frames[len(event.Frames)-1].Index
}}
at := time.Unix(100, 0)
for i := 0; i < 200; i++ {
state := "ready"
if i%2 == 0 {
state = "driving"
}
d.record(at.Add(time.Duration(i)*50*time.Millisecond), roverFrame{Session: "live", State: state})
}
d.record(at.Add(10*time.Second), roverFrame{Session: "live", State: "driving"})
if count > 11 || rows > 225 || previous != 201 {
t.Fatalf("events=%d rows=%d last=%d", count, rows, previous)
}
}
func TestRoverReleaseEvidencePreservesUnknownFalseTrue(t *testing.T) {
for _, value := range []any{nil, "false", 0} {
if roverReleaseEvidence(map[string]any{"release_confirmed": value}) != nil {
t.Fatal("invalid release became proof")
}
}
for _, value := range []bool{false, true} {
got := roverReleaseEvidence(map[string]any{"release_confirmed": value})
if got == nil || *got != value {
t.Fatal("release truth changed")
}
}
}
@@ -0,0 +1,44 @@
package node
import (
"context"
"errors"
"fmt"
"net/url"
"testing"
)
func TestDatagramFailureReasonsAreDistinctAndRedacted(t *testing.T) {
cases := map[string]string{
"datagram negotiation rejected": "datagram_negotiation_rejected",
"invalid datagram endpoint": "datagram_endpoint_invalid",
"datagram socket closed": "datagram_socket_closed",
"datagram link timeout": "datagram_link_timeout",
"datagram stream deadline": "datagram_stream_deadline",
"invalid datagram frame": "datagram_frame_invalid",
"invalid datagram clock": "datagram_clock_invalid",
"datagram receipt stale": "datagram_receipt_stale",
"invalid datagram intent": "datagram_intent_invalid",
}
seen := map[string]bool{}
for message, want := range cases {
got := roverErrorKind(errors.New(message))
if got != want || seen[got] {
t.Fatalf("reason %q: got %q, want unique %q", message, got, want)
}
seen[got] = true
}
// Transport errors may embed private endpoints. Only the timeout category
// may survive wrapping; never copy the raw URL, query or nested error.
private := &url.Error{Op: "Post", URL: "https://private.invalid/pair?secret=synthetic", Err: errors.New("connection failed")}
if got := roverErrorKind(private); got != "transport_error" {
t.Fatalf("private error leaked: %q", got)
}
private.Err = fmt.Errorf("request: %w", context.DeadlineExceeded)
if got := roverErrorKind(private); got != "deadline" {
t.Fatalf("wrapped deadline: %q", got)
}
if got := roverErrorKind(errors.New("datagram stream deadline: secret=synthetic")); got != "transport_error" {
t.Fatalf("prefix is not an allowlist: %q", got)
}
}
@@ -0,0 +1,84 @@
package node
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func TestDevExportSendsAcknowledgedBlockOnceAndRetriesFailedExchange(t *testing.T) {
for _, failFirst := range []bool{false, true} {
t.Run(map[bool]string{false: "acknowledged", true: "failed-then-acknowledged"}[failFirst], func(t *testing.T) {
var calls, blocks atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
if json.NewDecoder(r.Body).Decode(&body) != nil {
t.Error("invalid lane request")
}
packet := body["diagnostics"].(map[string]any)
if packet["export"] != nil {
blocks.Add(1)
}
n := calls.Add(1)
if failFirst && n == 1 {
w.WriteHeader(503)
}
json.NewEncoder(w).Encode(map[string]any{"diagnostics": nil})
}))
defer server.Close()
state := newRoverStreamState(time.Now())
state.diagnosticLane = true
state.devID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
state.devDesired = map[string]any{"export": map[string]any{"offset": 0}}
state.devPacket = map[string]any{"id": state.devID, "frames": []any{}, "export": map[string]any{
"capture_id": state.devID, "token": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "offset": 0, "next": 3, "data": "YWJj"}}
ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
defer cancel()
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state)
expected := int64(1)
if failFirst {
expected = 2
}
if calls.Load() < 3 || blocks.Load() != expected {
t.Fatal("unbounded duplicate or lost retry", calls.Load(), blocks.Load())
}
if state.devPacket["export"] == nil {
t.Fatal("network suppression modified retained source")
}
})
}
}
func TestIdleDiagnosticLaneSleepsUntilTelemetryAnnouncesWork(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
json.NewEncoder(w).Encode(map[string]any{"diagnostics": nil})
}))
defer server.Close()
state := newRoverStreamState(time.Now())
state.diagnosticLane = true
idle := false
state.diagnosticPending = &idle
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state)
cancel()
if calls.Load() != 0 {
t.Fatal("disabled DEV generated bulk polls")
}
busy := true
state.diagnosticPending = &busy
ctx, cancel = context.WithTimeout(context.Background(), 150*time.Millisecond)
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state)
cancel()
if calls.Load() == 0 {
t.Fatal("capture/export wake hint ignored")
}
if state.command != nil || !state.stopPending {
t.Fatal("diagnostics affected control")
}
}
@@ -0,0 +1,64 @@
package node
// DEV-only transport timing. Never record endpoints, headers, keys or raw errors.
import (
"context"
"crypto/tls"
"net/http/httptrace"
"sync"
"time"
)
type roverHTTPTrace struct {
mu sync.Mutex
started time.Time
fields map[string]any
}
func newRoverHTTPTrace(started time.Time, requestBytes int) *roverHTTPTrace {
return &roverHTTPTrace{started: started, fields: map[string]any{"phase": "waiting_connection", "request_bytes": requestBytes}}
}
func (t *roverHTTPTrace) mark(phase string, values map[string]any) {
t.mu.Lock()
defer t.mu.Unlock()
t.fields["phase"] = phase
t.fields[phase+"_ms"] = float64(time.Since(t.started).Microseconds()) / 1000
for key, value := range values {
t.fields[key] = value
}
}
func (t *roverHTTPTrace) context(ctx context.Context) context.Context {
return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
DNSStart: func(httptrace.DNSStartInfo) { t.mark("dns_start", nil) },
DNSDone: func(v httptrace.DNSDoneInfo) { t.mark("dns_done", map[string]any{"dns_error": roverErrorKind(v.Err)}) },
ConnectStart: func(_, _ string) { t.mark("connect_start", nil) },
ConnectDone: func(_, _ string, err error) {
t.mark("connect_done", map[string]any{"connect_error": roverErrorKind(err)})
},
TLSHandshakeStart: func() { t.mark("tls_start", nil) },
TLSHandshakeDone: func(_ tls.ConnectionState, err error) {
t.mark("tls_done", map[string]any{"tls_error": roverErrorKind(err)})
},
GotConn: func(v httptrace.GotConnInfo) {
t.mark("connection_ready", map[string]any{"reused": v.Reused, "was_idle": v.WasIdle})
},
WroteRequest: func(v httptrace.WroteRequestInfo) {
t.mark("request_written", map[string]any{"write_error": roverErrorKind(v.Err)})
},
GotFirstResponseByte: func() { t.mark("first_response_byte", nil) },
})
}
func (t *roverHTTPTrace) snapshot() map[string]any {
t.mu.Lock()
defer t.mu.Unlock()
result := make(map[string]any, len(t.fields))
for key, value := range t.fields {
result[key] = value
}
return result
}
func (s *roverStreamState) devTraceEnabled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.devID != "" && s.devEnabled && devOption(s.devDesired["options"], "network")
}
@@ -0,0 +1,83 @@
package node
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestRoverHTTPTraceConnectionReuseAndPrivacy(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) }))
defer server.Close()
client := &http.Client{Transport: &http.Transport{}, Timeout: time.Second}
defer client.CloseIdleConnections()
for i := 0; i < 2; i++ {
trace := newRoverHTTPTrace(time.Now(), 7)
req, _ := http.NewRequestWithContext(trace.context(context.Background()), "POST", server.URL+"/private-path", strings.NewReader("private"))
req.Header.Set("Authorization", "private-key")
response, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
_, err = io.Copy(io.Discard, response.Body)
response.Body.Close()
if err != nil {
t.Fatal(err)
}
fields := trace.snapshot()
if fields["reused"] != (i == 1) || fields["phase"] != "first_response_byte" || fields["request_bytes"] != 7 {
t.Fatalf("unexpected timing: %v", fields)
}
for _, key := range []string{"connection_ready_ms", "request_written_ms", "first_response_byte_ms"} {
if _, ok := fields[key].(float64); !ok {
t.Fatalf("missing timing %s: %v", key, fields)
}
}
for _, value := range fields {
if str, ok := value.(string); ok && (strings.Contains(str, "private") || strings.Contains(str, server.URL)) {
t.Fatal("private request data escaped into diagnostic")
}
}
}
}
func TestRoverHTTPTraceDistinguishesWaitingForResponse(t *testing.T) {
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-release }))
defer server.Close()
defer close(release)
client := &http.Client{Timeout: 200 * time.Millisecond}
trace := newRoverHTTPTrace(time.Now(), 0)
req, _ := http.NewRequestWithContext(trace.context(context.Background()), "GET", server.URL, nil)
response, err := client.Do(req)
if response != nil {
response.Body.Close()
}
if roverErrorKind(err) != "deadline" {
t.Fatalf("expected deadline, got %v", err)
}
fields := trace.snapshot()
if fields["phase"] != "request_written" {
t.Fatalf("lost failing phase: %v", fields)
}
if _, ok := fields["first_response_byte_ms"]; ok {
t.Fatal("response was never sent")
}
}
func TestRoverHTTPTraceOnlyEnabledDuringDev(t *testing.T) {
state := newRoverStreamState(time.Now())
if state.devTraceEnabled() {
t.Fatal("trace enabled outside DEV")
}
state.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": true})
if !state.devTraceEnabled() {
t.Fatal("DEV trace absent")
}
state.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": false})
if state.devTraceEnabled() {
t.Fatal("trace survived session stop")
}
}
@@ -0,0 +1,66 @@
package node
// Establish the authenticated HTTP connection separately from fresh snapshots.
// A probe returns a clock sample but cannot publish telemetry or renew a lease.
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"time"
)
func roverConnectTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) bool {
started := time.Now()
raw, _ := json.Marshal(base)
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover-link", bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
var trace *roverHTTPTrace
if state.devTraceEnabled() {
trace = newRoverHTTPTrace(started, len(raw))
req = req.WithContext(trace.context(req.Context()))
}
// Share the exact authenticated transport/pool. The normal client's timeout
// stays unchanged; no connection or command queue is added.
connectClient := &http.Client{Transport: client.Transport, Timeout: 2500 * time.Millisecond, CheckRedirect: client.CheckRedirect}
response, err := connectClient.Do(req)
ok := false
status := 0
if err == nil {
status = response.StatusCode
var reply struct {
LatestDatagram bool `json:"latest_datagram_v1"`
RoverDetails bool `json:"rover_details_v1"`
BudgetInterval bool `json:"budget_interval_v1"`
DiagnosticLane bool `json:"diagnostic_lane_v1"`
Connected bool `json:"connected"`
SampleClock bool `json:"sample_clock_v1"`
Clock roverClock `json:"control_clock"`
}
err = json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&reply)
response.Body.Close()
ok = err == nil && status == 200 && reply.Connected
stamped := ok && reply.SampleClock
if stamped {
ok = state.sampleClock(reply.Clock, started, time.Now())
}
state.mu.Lock()
state.telemetryStamped = stamped && ok
state.diagnosticLane = ok && reply.DiagnosticLane
state.budgetInterval = ok && reply.BudgetInterval
state.roverDetails = ok && reply.RoverDetails
state.latestDatagram = state.latestDatagram || (ok && reply.LatestDatagram)
state.diagnosticPending = nil // One discovery exchange on every authenticated reconnect.
state.mu.Unlock()
}
if !ok && status == 0 {
state.budget.Observe(time.Since(started), false)
}
details := map[string]any{"elapsed_ms": time.Since(started).Milliseconds(), "http_status": status, "connected": ok, "reason": roverErrorKind(err)}
if trace != nil {
details["transport"] = trace.snapshot()
}
state.recordDev("link_connect", details)
return ok
}
@@ -0,0 +1,148 @@
package node
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func TestRoverTelemetryCapturesFreshSnapshotAfterSlowConnection(t *testing.T) {
state := newRoverStreamState(time.Now())
state.delivered(map[string]any{"generation": float64(1)}, 0)
received := make(chan map[string]any, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if r.URL.Path == "/v1/node/rover-link" {
if _, ok := body["rover"]; ok {
t.Error("probe must not carry a stale snapshot")
}
if _, ok := body["command"]; ok {
t.Error("probe cannot command a motor")
}
_ = json.NewEncoder(w).Encode(map[string]bool{"connected": true})
return
}
if r.URL.Path != "/v1/node/rover" {
t.Error("unexpected path")
}
select {
case received <- body:
default:
}
_ = json.NewEncoder(w).Encode(roverStreamReply{Clock: roverClock{testClockID, 10000}})
}))
defer server.Close()
var dials atomic.Int32
transport := &http.Transport{MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
dials.Add(1)
// Connection takes longer than the snapshot budget. Data changes meanwhile.
if !roverWait(ctx, 150*time.Millisecond) {
return nil, ctx.Err()
}
state.delivered(map[string]any{"generation": float64(2)}, 0)
return (&net.Dialer{}).DialContext(ctx, network, address)
}}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 75 * time.Millisecond}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan struct{})
go func() { defer close(done); roverTelemetry(ctx, client, server.URL, map[string]any{}, state) }()
select {
case body := <-received:
if body["rover"].(map[string]any)["generation"] != float64(2) {
t.Fatal("stale pre-connect snapshot was transmitted")
}
case <-time.After(2 * time.Second):
t.Fatal("connection never recovered beyond snapshot deadline")
}
cancel()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("cancelled telemetry worker leaked")
}
if dials.Load() != 1 {
t.Fatalf("warm connection was not reused: %d", dials.Load())
}
if client.Timeout != 75*time.Millisecond {
t.Fatal("snapshot deadline was relaxed")
}
}
func TestRoverDelayedReplyKeepsConnectionWithoutExtendingCommandDeadline(t *testing.T) {
state := newRoverStreamState(time.Now())
state.delivered(map[string]any{"generation": float64(1)}, 0)
origin := time.Now()
var probes atomic.Int32
var snapshots atomic.Int32
done := make(chan struct{}, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clock := func() roverClock {
return roverClock{testClockID, 10000 + float64(time.Since(origin).Microseconds())/1000}
}
if r.URL.Path == "/v1/node/rover-link" {
probes.Add(1)
_ = json.NewEncoder(w).Encode(map[string]any{"connected": true, "sample_clock_v1": true, "control_clock": clock()})
return
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["sample_clock"] == nil {
t.Error("long transport deadline without capture age")
}
// A valid observation reply exceeds the former 300 ms cutoff.
time.Sleep(400 * time.Millisecond)
_ = json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: clock()})
if snapshots.Add(1) == 2 {
done <- struct{}{}
}
}))
defer server.Close()
transport := &http.Transport{MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 75 * time.Millisecond}
ctx, cancel := context.WithCancel(context.Background())
workerDone := make(chan struct{})
go func() { defer close(workerDone); roverTelemetry(ctx, client, server.URL, map[string]any{}, state) }()
select {
case <-done:
case <-time.After(3 * time.Second):
t.Error("delayed response caused retry loop")
}
cancel()
<-workerDone
if probes.Load() != 1 {
t.Fatalf("unnecessary reconnects: %d", probes.Load())
}
if client.Timeout != 75*time.Millisecond {
t.Fatal("shared command/client timeout changed")
}
if state.command != nil {
t.Fatal("observation created motion authority")
}
}
func TestSampleTimeUsesConservativeLowerClockSeparateFromCommandUpper(t *testing.T) {
origin := time.Now()
s := newRoverStreamState(origin)
if !s.sampleClock(roverClock{testClockID, 10000}, origin, origin.Add(400*time.Millisecond)) {
t.Fatal("clock")
}
s.telemetryStamped = true
captured := origin.Add(450 * time.Millisecond)
s.deliveredAt(map[string]any{}, 0, captured)
_, clock := s.telemetryView()
if clock == nil || clock.MonotonicMS > 10050 || clock.MonotonicMS < 10040 {
t.Fatalf("incorrect capture bound: %+v", clock)
}
if s.upperMS < 10000 {
t.Fatal("command upper bound was replaced by lower bound")
}
}
@@ -0,0 +1,84 @@
package node
import (
"context"
"time"
)
// The local tick checks expiry even when no newer operator intent has arrived.
// It owns no independent lease and cannot extend the Core's original deadline.
type roverLocalDelivery struct {
session string
sequence float64
sent bool
}
func (d *roverLocalDelivery) run(ctx context.Context, sensors *Sensors, model *sensorModel, state *roverStreamState, relay string, started time.Time) roverFrame {
state.budget.ObserveCommandSilence()
watch, command, stop := state.delivery(started)
frame := roverFrame{}
mode := "observe"
if stop != 0 {
mode = "stop"
frame.Reason, _ = state.stopDetails()["reason"].(string)
if state.devTraceEnabled() {
state.recordDev("delivery_stop", state.stopDetails())
}
}
if command != nil {
state.budget.SetControl(true) // Reserve before the first local intent, not after telemetry catches up.
mode = "intent"
frame.Session, _ = command["id"].(string)
frame.Sequence, _ = command["sequence"].(float64)
frame.TTLMS, _ = command["ttl_ms"].(float64)
}
// A successful RPC already carried this exact input to the owner. The
// VESC owner's input lease rejects duplicates anyway. Do not turn a redundant
// snapshot request into a second opportunity to retire valid authority.
// delivery() above still enforces expiry/stop/clock barriers every tick;
// skipping must NOT refresh the last snapshot's capture timestamp.
if command != nil && d.sent && d.session == frame.Session && d.sequence == frame.Sequence {
snapshot, _ := state.view()
frame.State, _ = snapshot["state"].(string)
frame.ReleaseConfirmed = roverReleaseEvidence(snapshot)
frame.Delivery = "unchanged"
state.recordDev("delivery", map[string]any{"session_id": frame.Session, "sequence": frame.Sequence,
"ttl_ms": frame.TTLMS, "driver_ms": 0, "state": frame.State, "error_stage": "", "delivery_mode": frame.Delivery})
return frame
}
frame.Delivery = mode
call, done := context.WithTimeout(ctx, 25*time.Millisecond)
var trace *roverHTTPTrace
if state.devTraceEnabled() {
trace = newRoverHTTPTrace(started, 0)
call = trace.context(call)
}
result, err := sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay})
reason := roverErrorKind(call.Err())
if reason == "" && err != nil {
reason = roverErrorKind(err)
}
done()
frame.DriverMS = time.Since(started).Milliseconds()
if err != nil {
d.sent = false
state.stopStream()
frame.Stage = "driver_transport"
state.deliveredAt(map[string]any{}, 0, started)
} else {
d.sent = command != nil
d.session, d.sequence = frame.Session, frame.Sequence
state.deliveredAt(result, stop, started)
frame.State, _ = result["state"].(string)
frame.ReleaseConfirmed = roverReleaseEvidence(result)
}
details := map[string]any{"session_id": frame.Session, "sequence": frame.Sequence, "ttl_ms": frame.TTLMS,
"driver_ms": frame.DriverMS, "state": frame.State, "error_stage": frame.Stage, "delivery_mode": mode, "reason": reason}
if trace != nil {
timing := trace.snapshot()
delete(timing, "request_bytes") // Encoding belongs to modelDriver; its size is not measured here.
details["transport"] = timing
}
state.recordDev("delivery", details)
return frame
}
@@ -0,0 +1,184 @@
package node
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptrace"
"testing"
"time"
)
func localDeliveryFixture(t *testing.T) (*Sensors, *sensorModel, *roverStreamState, time.Time) {
t.Helper()
sensors := isolatedSensors(t)
var model *sensorModel
for i := range sensorModels {
if sensorModels[i].ID == "vesc.controller" {
model = &sensorModels[i]
break
}
}
if model == nil {
t.Fatal("missing VESC")
}
at := time.Now()
state := newRoverStreamState(at)
state.sampleClock(roverClock{testClockID, 10000}, at, at)
acknowledgeStop(state, at)
state.accept(streamIntent(1331, 10000, 10400))
return sensors, model, state, at
}
func TestRoverLocalDeliveryDoesNotResendAlreadyDeliveredIntent(t *testing.T) {
sensors, model, state, at := localDeliveryFixture(t)
calls := 0
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if calls > 1 {
return nil, context.DeadlineExceeded
}
return testSensorReply(map[string]any{"state": "driving", "instance": "same", "session_id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}), nil
})
var delivery roverLocalDelivery
delivery.run(context.Background(), sensors, model, state, "relay", at)
before, _ := state.view()
sampled := state.snapshotAt
delivery.run(context.Background(), sensors, model, state, "relay", at.Add(50*time.Millisecond))
_, command, stop := state.delivery(at.Add(75 * time.Millisecond))
if calls != 1 || command == nil || stop != 0 {
t.Fatalf("duplicate RPC retired live intent: calls=%d command=%v stop=%d", calls, command, stop)
}
after, _ := state.view()
if after["instance"] != before["instance"] || !state.snapshotAt.Equal(sampled) {
t.Fatal("skipped RPC refreshed/replaced telemetry")
}
if command["ttl_ms"].(float64) >= 325 {
t.Fatal("duplicate extended the original deadline")
}
}
func TestRoverLocalDeliveryStillSendsExpiryAndExplicitStop(t *testing.T) {
for _, explicit := range []bool{false, true} {
t.Run(map[bool]string{false: "expiry", true: "explicit"}[explicit], func(t *testing.T) {
sensors, model, state, at := localDeliveryFixture(t)
var requests []map[string]any
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
requests = append(requests, body)
deadline, ok := r.Context().Deadline()
if !ok || time.Until(deadline) > 25*time.Millisecond {
t.Fatal("local RPC deadline relaxed")
}
return testSensorReply(map[string]any{"state": "driving"}), nil
})
var delivery roverLocalDelivery
delivery.run(context.Background(), sensors, model, state, "relay", at)
next := at.Add(450 * time.Millisecond)
if explicit {
state.stopStream()
next = at.Add(50 * time.Millisecond)
}
delivery.run(context.Background(), sensors, model, state, "relay", next)
if len(requests) != 2 || requests[1]["command"] != nil {
t.Fatal("cached delivery suppressed stop")
}
state.accept(streamIntent(1332, 10450, 10850))
_, command, _ := state.delivery(next)
if command != nil {
t.Fatal("retired session resumed")
}
})
}
}
func TestRoverLocalDeliveryNewIntentFailureRemainsTerminal(t *testing.T) {
sensors, model, state, at := localDeliveryFixture(t)
calls := 0
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if calls == 2 {
return nil, errors.New("synthetic failure")
}
return testSensorReply(map[string]any{"state": "driving"}), nil
})
var delivery roverLocalDelivery
delivery.run(context.Background(), sensors, model, state, "relay", at)
state.accept(streamIntent(1332, 10100, 10500))
frame := delivery.run(context.Background(), sensors, model, state, "relay", at.Add(100*time.Millisecond))
_, command, stop := state.delivery(at.Add(150 * time.Millisecond))
if calls != 2 || frame.Stage != "driver_transport" || command != nil || stop == 0 || delivery.sent {
t.Fatal("fresh intent failure no longer retires authority")
}
delivery.run(context.Background(), sensors, model, state, "relay", at.Add(150*time.Millisecond))
if state.stopPending {
t.Fatal("explicit stop not acknowledged")
}
}
func TestRoverLocalDeliveryNewInputAfterSkippedTickIsNotCoalescedAway(t *testing.T) {
sensors, model, state, at := localDeliveryFixture(t)
var sequences []float64
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
sequences = append(sequences, body["command"].(map[string]any)["sequence"].(float64))
return testSensorReply(map[string]any{"state": "driving"}), nil
})
var delivery roverLocalDelivery
delivery.run(context.Background(), sensors, model, state, "relay", at)
skipped := delivery.run(context.Background(), sensors, model, state, "relay", at.Add(50*time.Millisecond))
state.accept(streamIntent(1332, 10060, 10460))
delivery.run(context.Background(), sensors, model, state, "relay", at.Add(60*time.Millisecond))
if len(sequences) != 2 || sequences[0] != 1331 || sequences[1] != 1332 || skipped.Delivery != "unchanged" {
t.Fatal("new input was suppressed", sequences)
}
}
func TestRoverLocalDeliveryDeadlineTraceIsDevOnly(t *testing.T) {
for _, dev := range []bool{false, true} {
t.Run(map[bool]string{false: "off", true: "on"}[dev], func(t *testing.T) {
sensors, model, state, at := localDeliveryFixture(t)
if dev {
state.devID = testClockID
state.devEnabled = true
}
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
tr := httptrace.ContextClientTrace(r.Context())
if (tr != nil) != dev {
t.Fatal("trace state disagrees with DEV")
}
if tr != nil {
tr.WroteRequest(httptrace.WroteRequestInfo{})
}
<-r.Context().Done()
return nil, r.Context().Err()
})
var delivery roverLocalDelivery
delivery.run(context.Background(), sensors, model, state, "relay", at)
if !dev {
if len(state.devEvents) != 0 {
t.Fatal("DEV-off retained trace")
}
return
}
if len(state.devEvents) != 1 {
t.Fatal("trace missing")
}
row := state.devEvents[0]
timing := row["transport"].(map[string]any)
if row["reason"] != "deadline" || timing["phase"] != "request_written" || row["delivery_mode"] != "intent" {
t.Fatal(row)
}
if _, ok := timing["request_bytes"]; ok {
t.Fatal("invented request size")
}
})
}
}
@@ -0,0 +1,89 @@
package node
import (
"bytes"
"encoding/json"
"time"
)
// Only presentation/identity metadata is cached. Every measured value, age,
// attachment session, authority flag and release result stays in every frame.
var roverMetadataFields = []string{"supported", "control_modes", "profile"}
var roverDeviceMetadataFields = []string{"uuid", "slot", "label"}
type roverMetadataEncoder struct {
instance string
previous []byte
revision uint64
sentAt time.Time
}
func (e *roverMetadataEncoder) reset() { e.sentAt = time.Time{} }
func (e *roverMetadataEncoder) encode(snapshot map[string]any, now time.Time) (map[string]any, map[string]any) {
readings, ok := snapshot["devices"].([]any)
instance, _ := snapshot["instance"].(string)
if !ok || instance == "" {
e.reset()
return snapshot, nil
}
if e.instance != instance {
e.instance = instance
e.reset()
}
details := map[string]any{}
compact := make(map[string]any, len(snapshot))
for k, v := range snapshot {
compact[k] = v
}
for _, k := range roverMetadataFields {
if v, exists := compact[k]; exists {
details[k] = v
delete(compact, k)
}
}
devices := map[string]any{}
live := make([]any, 0, len(readings))
for _, value := range readings {
row, valid := value.(map[string]any)
id, _ := row["id"].(string)
session, _ := row["session_id"].(string)
if !valid || id == "" || session == "" {
e.reset()
return snapshot, nil
}
if _, duplicate := devices[id]; duplicate {
e.reset()
return snapshot, nil
}
metadata, current := map[string]any{}, map[string]any{}
for k, v := range row {
current[k] = v
}
for _, k := range roverDeviceMetadataFields {
if v, exists := current[k]; exists {
metadata[k] = v
delete(current, k)
}
}
devices[id] = metadata
live = append(live, current)
}
details["devices"], compact["devices"] = devices, live
raw, err := json.Marshal(details)
if err != nil {
e.reset()
return snapshot, nil
}
if !bytes.Equal(raw, e.previous) {
e.previous = raw
e.revision++
e.reset()
}
envelope := map[string]any{"revision": e.revision}
if e.sentAt.IsZero() || now.Sub(e.sentAt) >= time.Second {
envelope["details"] = details
e.sentAt = now
}
return compact, envelope
}
@@ -0,0 +1,83 @@
package node
import (
"encoding/json"
"reflect"
"testing"
"time"
)
func metadataSnapshot() map[string]any {
return map[string]any{"instance": "driver", "supported": true, "control_modes": []any{"duty"},
"profile": map[string]any{"revision": float64(2)}, "state": "stopped", "release_confirmed": false,
"devices": []any{map[string]any{"id": "motor", "session_id": "attached", "uuid": "physical", "label": "Left", "slot": "left.1", "age_ms": float64(25),
"values": map[string]any{"erpm": float64(123), "motor_current_a": 0.2}}}}
}
func TestRoverMetadataKeepsLiveTruthAndRefreshesOnChange(t *testing.T) {
var encoder roverMetadataEncoder
at := time.Unix(100, 0)
snapshot := metadataSnapshot()
before, _ := json.Marshal(snapshot)
first, details := encoder.encode(snapshot, at)
if details["details"] == nil || details["revision"] != uint64(1) {
t.Fatal(details)
}
current := first["devices"].([]any)[0].(map[string]any)
if first["release_confirmed"] != false || current["age_ms"] != float64(25) || current["session_id"] != "attached" {
t.Fatal(first)
}
if !reflect.DeepEqual(current["values"], snapshot["devices"].([]any)[0].(map[string]any)["values"]) {
t.Fatal("live values changed")
}
if _, ok := current["uuid"]; ok {
t.Fatal("metadata repeated")
}
after, _ := json.Marshal(snapshot)
if string(before) != string(after) {
t.Fatal("snapshot mutated")
}
_, ref := encoder.encode(snapshot, at.Add(100*time.Millisecond))
if len(ref) != 1 || ref["revision"] != uint64(1) {
t.Fatal(ref)
}
_, refresh := encoder.encode(snapshot, at.Add(time.Second))
if refresh["details"] == nil {
t.Fatal("metadata not refreshed")
}
snapshot["profile"] = map[string]any{"revision": float64(3)}
_, changed := encoder.encode(snapshot, at.Add(1100*time.Millisecond))
if changed["details"] == nil || changed["revision"] != uint64(2) {
t.Fatal("configuration change delayed")
}
encoder.reset()
_, reconnect := encoder.encode(snapshot, at.Add(1200*time.Millisecond))
if reconnect["details"] == nil {
t.Fatal("reconnect needs full metadata")
}
snapshot["instance"] = "restarted-driver"
_, restarted := encoder.encode(snapshot, at.Add(1300*time.Millisecond))
if restarted["details"] == nil {
t.Fatal("driver restart must refresh metadata even with an identical profile")
}
}
func TestRoverMetadataCannotHideMalformedRoster(t *testing.T) {
for _, change := range []string{"missing_session", "duplicate", "missing_instance"} {
snapshot := metadataSnapshot()
row := snapshot["devices"].([]any)[0].(map[string]any)
switch change {
case "missing_session":
delete(row, "session_id")
case "duplicate":
snapshot["devices"] = []any{row, row}
case "missing_instance":
delete(snapshot, "instance")
}
var encoder roverMetadataEncoder
live, details := encoder.encode(snapshot, time.Now())
if details != nil || !reflect.DeepEqual(live, snapshot) {
t.Fatal("malformed snapshot hidden")
}
}
}
@@ -0,0 +1,34 @@
package node
import "time"
// Record receipt before local delivery, including retired frames. This closes
// the evidence gap between Core's socket write and the driver's input receipt.
func (s *roverStreamState) receivedFrame(reply roverStreamReply, at time.Time) {
s.mu.Lock()
s.observeLowerClock(reply.Clock, at)
gap := time.Duration(0)
if !s.streamReceived.IsZero() {
gap = at.Sub(s.streamReceived)
}
s.streamReceived = at
upper := float64(at.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(at.Sub(s.anchored).Microseconds())/1e6
age := max(0, upper-reply.Clock.MonotonicMS)
id, _ := reply.Command["id"].(string)
retired, pending := s.retired[id], s.stopPending
s.mu.Unlock()
s.budget.ObserveCommandFrame(gap, time.Duration(age*float64(time.Millisecond)))
if s.devTraceEnabled() {
s.recordDev("stream_frame_received", map[string]any{"session_id": id, "sequence": reply.Command["sequence"],
"received_mono_ms": float64(at.Sub(s.origin).Microseconds()) / 1000,
"core_clock_ms": reply.Clock.MonotonicMS, "gap_ms": float64(gap.Microseconds()) / 1000,
"age_upper_ms": age, "retired": retired, "stop_pending": pending})
}
}
func (s *roverStreamState) stopDetails() map[string]any {
s.mu.Lock()
defer s.mu.Unlock()
return map[string]any{"reason": s.stopCause, "stop_revision": s.stopRevision,
"last_frame_mono_ms": float64(s.streamReceived.Sub(s.origin).Microseconds()) / 1000}
}
@@ -12,29 +12,54 @@ type roverClock struct {
MonotonicMS float64 `json:"monotonic_ms"`
}
type roverStreamReply struct {
Watch bool `json:"watch"`
Command map[string]any `json:"command"`
Clock roverClock `json:"control_clock"`
CoreProcessingMS float64 `json:"core_processing_ms"`
ControlActive *bool `json:"control_active"`
DiagnosticsPending *bool `json:"diagnostics_pending"`
Diagnostics map[string]any `json:"diagnostics,omitempty"`
Watch bool `json:"watch"`
Command map[string]any `json:"command"`
Clock roverClock `json:"control_clock"`
}
// Clock bounds use the request-send time, never RTT/2 or synchronized wall
// clocks. Server time was sampled after that send, so it gives an upper bound
// on server-minus-local monotonic offset even on an asymmetric network.
type roverStreamState struct {
mu sync.Mutex
origin time.Time
clockID string
upperMS float64
anchored time.Time
clockSeen time.Time
command map[string]any
watch bool
stopPending bool
stopRevision uint64
snapshot map[string]any
retired map[string]bool
inhibited bool
wake chan struct{}
budget *LinkBudget
latestDatagram bool
roverDetails bool
diagnosticLane bool
budgetInterval bool
diagnosticPending *bool
devID string
devEnabled bool
devDesired map[string]any
devAfter any
devRelayAfter int64
devSequence int64
devEvents []map[string]any
devPacket map[string]any
devBudgetAt time.Time
mu sync.Mutex
origin time.Time
clockID string
upperMS float64
anchored time.Time
clockSeen time.Time
streamReceived time.Time
stopCause string
command map[string]any
watch bool
stopPending bool
stopRevision uint64
snapshotAt time.Time
telemetryStamped bool
lowerClockMS float64
lowerClockAt time.Time
snapshot map[string]any
retired map[string]bool
inhibited bool
wake chan struct{}
}
func newRoverStreamState(now time.Time) *roverStreamState {
@@ -58,17 +83,41 @@ func (s *roverStreamState) sampleClock(c roverClock, sent, received time.Time) b
defer s.mu.Unlock()
upper := c.MonotonicMS - float64(sent.Sub(s.origin).Microseconds())/1000 + 1
if c.Instance != s.clockID {
s.invalidate()
s.invalidateCause("core_clock_changed")
s.clockID = c.Instance
s.lowerClockAt = time.Time{}
s.upperMS = upper
s.anchored = received
} else if s.clockSeen.IsZero() || received.Sub(s.clockSeen) > 2*time.Second || upper < s.upperMS+float64(received.Sub(s.anchored).Microseconds())/1e6 {
s.upperMS = upper
s.anchored = received
}
s.observeLowerClock(c, received)
s.clockSeen = received
return true
}
// Called with s.mu held. Every authenticated Core clock is a lower bound at
// local receipt. A slow response cannot erase a tighter bound already learned
// from another exchange or the command stream. Advance the old bound with the
// same conservative 1000 ppm drift allowance as telemetryView; never use RTT/2.
// This only timestamps observations. It does not touch the command-clock upper
// bound, clockSeen, original expiry, stop barrier or any motion authority.
func (s *roverStreamState) observeLowerClock(c roverClock, received time.Time) {
if c.Instance != s.clockID || math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 {
return
}
lower := c.MonotonicMS
if !s.lowerClockAt.IsZero() {
delta := float64(received.Sub(s.lowerClockAt).Microseconds()) / 1000
if delta < 0 {
return
}
lower = math.Max(lower, s.lowerClockMS+delta-delta*.001)
}
s.lowerClockMS, s.lowerClockAt = lower, received
}
func (s *roverStreamState) accept(reply roverStreamReply) bool {
s.mu.Lock()
defer s.mu.Unlock()
@@ -77,7 +126,7 @@ func (s *roverStreamState) accept(reply roverStreamReply) bool {
}
if reply.Command == nil {
if s.command != nil {
s.invalidate()
s.invalidateCause("core_withdrew_command")
}
return true
}
@@ -139,6 +188,10 @@ func (s *roverStreamState) retire(id string) {
s.retired[id] = true
}
func (s *roverStreamState) invalidate() {
s.invalidateCause("stream_unavailable")
}
func (s *roverStreamState) invalidateCause(cause string) {
s.stopCause = cause
wake := !s.stopPending || s.command != nil
if s.command != nil {
if id, ok := s.command["id"].(string); ok {
@@ -162,7 +215,7 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64
return s.watch, nil, 0
}
if now.Sub(s.clockSeen) > 2*time.Second {
s.invalidate()
s.invalidateCause("clock_sample_stale")
return s.watch, nil, s.stopRevision
}
expires, _ := finiteNumber(s.command["expires_mono_ms"])
@@ -171,7 +224,7 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64
serverUpper := float64(now.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(now.Sub(s.anchored).Microseconds())/1e6
ttl := math.Min(400, expires-serverUpper-25)
if ttl <= 0 {
s.invalidate()
s.invalidateCause("command_deadline_expired")
return s.watch, nil, s.stopRevision
}
out := make(map[string]any, 6)
@@ -184,8 +237,12 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64
return s.watch, out, 0
}
func (s *roverStreamState) delivered(snapshot map[string]any, stop uint64) {
s.deliveredAt(snapshot, stop, time.Now())
}
func (s *roverStreamState) deliveredAt(snapshot map[string]any, stop uint64, sampled time.Time) {
s.mu.Lock()
defer s.mu.Unlock()
s.snapshotAt = sampled
s.snapshot = snapshot
if stop != 0 && stop == s.stopRevision {
s.stopPending = false
@@ -197,3 +254,20 @@ func (s *roverStreamState) view() (map[string]any, bool) {
return s.snapshot, s.watch
}
func (s *roverStreamState) setWatch(watch bool) { s.mu.Lock(); s.watch = watch; s.mu.Unlock() }
// Conservative capture time in the Core epoch: the reply clock was sampled
// before local receipt. Subtract drift/quantization margin, never RTT/2.
// This is observation age only; command authority still uses its upper bound.
func (s *roverStreamState) telemetryView() (map[string]any, *roverClock) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.telemetryStamped || s.lowerClockAt.IsZero() || s.snapshotAt.IsZero() {
return s.snapshot, nil
}
delta := float64(s.snapshotAt.Sub(s.lowerClockAt).Microseconds()) / 1000
stamp := s.lowerClockMS + delta - 5 - math.Abs(delta)*.001
if stamp < 0 {
stamp = 0
}
return s.snapshot, &roverClock{s.clockID, stamp}
}
@@ -233,3 +233,44 @@ func TestRoverStreamReadsMultipleFramesOnOneResponse(t *testing.T) {
t.Fatal(err)
}
}
func TestDelayedHTTPClockCannotMakeNewTelemetryArtificiallyStale(t *testing.T) {
origin := time.Unix(100, 0)
s := newRoverStreamState(origin)
s.telemetryStamped = true
s.sampleClock(roverClock{testClockID, 10000}, origin, origin.Add(50*time.Millisecond))
// Fast command-stream receipt and a fresh local measurement, followed by
// a late HTTP response sampled much earlier on Core.
s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 10750}}, origin.Add(800*time.Millisecond))
s.deliveredAt(map[string]any{"state": "observing"}, 0, origin.Add(850*time.Millisecond))
s.sampleClock(roverClock{testClockID, 10050}, origin.Add(50*time.Millisecond), origin.Add(900*time.Millisecond))
_, stamp := s.telemetryView()
if stamp == nil || stamp.MonotonicMS < 10790 || stamp.MonotonicMS > 10850 {
t.Fatal("late response rolled the observation clock backwards", stamp)
}
// No new measurement: advancing the bounds cannot rejuvenate the sample.
before := stamp.MonotonicMS
s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 11750}}, origin.Add(1800*time.Millisecond))
_, stale := s.telemetryView()
if stale.MonotonicMS > before+2 || s.command != nil {
t.Fatal("old sample/authority renewed", stale, s.command)
}
}
func TestObservationClockEpochAndInvalidSamplesCannotReuseOldBound(t *testing.T) {
origin := time.Unix(100, 0)
s := newRoverStreamState(origin)
s.telemetryStamped = true
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
s.receivedFrame(roverStreamReply{Clock: roverClock{"foreign", 99999}}, origin.Add(time.Millisecond))
if s.lowerClockMS != 10000 {
t.Fatal("foreign clock changed lower bound")
}
next := "cccccccccccccccccccccccccccccccc"
s.sampleClock(roverClock{next, 10}, origin.Add(time.Second), origin.Add(time.Second))
s.deliveredAt(map[string]any{}, 0, origin.Add(time.Second))
_, stamp := s.telemetryView()
if stamp.Instance != next || stamp.MonotonicMS > 10 || s.command != nil {
t.Fatal("old epoch retained", stamp)
}
}
@@ -0,0 +1,22 @@
package node
import (
"crypto/tls"
"net"
"net/http"
"time"
)
const roverConnectTimeout = 2 * time.Second
// Each rover lane owns its connection pool. Establishing a connection grants
// neither a command lease nor permission to revive an interrupted session.
func newRoverHTTPTransport(config *tls.Config) *http.Transport {
return &http.Transport{TLSClientConfig: config, Proxy: nil,
MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second,
TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second,
// A one-second connect deadline races the initial SYN retransmission.
// Allow that retry; the probe's 2.5 s context and lane cancellation still
// bound establishment. This never extends a command or the stream guard.
DialContext: (&net.Dialer{Timeout: roverConnectTimeout}).DialContext}
}
@@ -0,0 +1,37 @@
package node
import (
"io"
"net/http"
"strings"
"testing"
)
func TestSensorFailureKeepsNativeEvidenceForCore(t *testing.T) {
root := t.TempDir()
s, _ := OpenSensors(root, "node_test")
isolateSensorHost(t, s)
c := sensorTestCommand()
s.operations[c.ID] = &SensorOperation{Command: c, State: "running", Remote: true}
s.client = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
body := `{"items":[{"id":"` + c.Session.DeviceID + `"}]}`
if r.URL.Path == "/operation" {
body = `{"state":"error","error":"Read failed","result":{"failure":{"native_rpc":{"method":"diagnostic","command":"hw_status","error":"No response"}}}}`
}
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil
})}
s.execute(c)
value := s.Get(c.ID)
if value.State != "error" || value.Error != "Read failed" || value.Result == nil {
t.Fatalf("Lost driver failure: %+v", value)
}
failure := value.Result.(map[string]any)["failure"].(map[string]any)
rpc := failure["native_rpc"].(map[string]any)
if rpc["command"] != "hw_status" {
t.Fatal("Wrong native request retained")
}
reopened, err := OpenSensors(root, "node_test")
if err != nil || reopened.Get(c.ID) == nil || reopened.Get(c.ID).Result == nil {
t.Fatal("Failure evidence lost after restart", err)
}
}
@@ -33,7 +33,7 @@ func actions(names ...string) map[string]bool {
}
var sensorModels = []sensorModel{
{ID: "realsense.d455", Name: "RealSense D455", Prefix: "rsd455", Plugin: "missioncore.realsense", Version: "0.6.6",
{ID: "realsense.d455", Name: "RealSense D455", Prefix: "rsd455", Plugin: "missioncore.realsense", Version: "0.6.7",
Vendor: "8086", Product: "0b5c", Socket: "/run/mission-core-sensors/driver.sock",
PrepareUnit: "mission-core-node-realsense-prepare.service", Report: "/var/lib/mission-core-node-drivers/preparation.json",
Actions: actions("prepare", "details", "rename", "verify", "start", "replay", "stop", "option", "offer", "close-peer")},
@@ -46,11 +46,15 @@ var sensorModels = []sensorModel{
PrepareUnit: "mission-core-node-insta360-x4-profile.service", Report: "/var/lib/mission-core-node-profiles/insta360-x4/preparation.json",
ActionTimeouts: map[string]time.Duration{"power.wake": 55 * time.Second},
Actions: actions("prepare", "details", "rename", "verify", "preview.start", "preview.stop", "record.start", "record.stop", "photo.capture", "settings.read", "settings.apply", "files.list", "offer", "close-peer", "recovery.configure", "power.wake")},
{ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.7.4",
{ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.20.11",
Vendor: "0483", Product: "5740", USBName: "ChibiOS/RT Virtual COM Port", Socket: "/run/mission-core-vesc/driver.sock",
PrepareUnit: "mission-core-node-vesc-prepare.service", Report: "/var/lib/mission-core-node-profiles/vesc/preparation.json",
ActionTimeouts: map[string]time.Duration{"vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second},
ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")},
ActionTimeouts: map[string]time.Duration{"vesc.packages.apply": 350 * time.Second, "vesc.packages.prepare": 70 * time.Second, "vesc.packages.status": 70 * time.Second, "vesc.packages.restore": 70 * time.Second, "vesc.packages.reconcile": 70 * time.Second, "vesc.packages.remove_prepare": 70 * time.Second, "vesc.code.apply": 180 * time.Second, "vesc.firmware.apply": 300 * time.Second, "vesc.configuration.apply": 60 * time.Second, "vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second},
ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview", "vesc.bms.configuration.apply", "vesc.bms.configuration.reconcile", "vesc.bms.configuration.restore", "vesc.packages.catalog", "vesc.packages.inspect", "vesc.packages.download", "vesc.packages.begin", "vesc.packages.chunk", "vesc.packages.load", "vesc.packages.forget", "vesc.packages.status", "vesc.packages.prepare", "vesc.packages.remove_prepare", "vesc.packages.restore", "vesc.packages.apply", "vesc.packages.reconcile", "vesc.packages.refresh", "vesc.samples.start", "vesc.samples.status", "vesc.samples.fetch", "vesc.samples.stop", "vesc.samples.read", "vesc.qml.begin", "vesc.qml.chunk", "vesc.qml.render", "vesc.qml.open", "vesc.qml.frame", "vesc.qml.close", "vesc.code.read", "vesc.code.begin", "vesc.code.chunk", "vesc.code.prepare", "vesc.code.erase_prepare", "vesc.code.apply", "vesc.code.reconcile", "vesc.code.control_prepare", "vesc.code.control_apply", "vesc.code.stats", "vesc.code.restore", "vesc.bms.read", "vesc.bms.prepare", "vesc.bms.apply", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.reconcile", "vesc.firmware.backup", "vesc.firmware.target", "vesc.firmware.catalog", "vesc.firmware.catalog_prepare", "vesc.firmware.begin", "vesc.firmware.chunk", "vesc.firmware.seal", "vesc.firmware.discard", "vesc.firmware.apply", "vesc.firmware.status", "vesc.firmware.cancel", "vesc.firmware.reconcile", "vesc.diagnostics.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")},
{ID: "waveshare.usb-can-fd-b", Name: "Waveshare USB-CAN-FD-B", Prefix: "usbcan", Kind: "waveshare.usb-can-fd-b", Plugin: "missioncore.usb-can", Version: "0.2.7",
Vendor: "04d8", Product: "0053", USBName: "USB CANFD DEBUG", Socket: "/run/mission-core-usb-can/driver.sock",
PrepareUnit: "mission-core-node-usb-can-prepare.service", Report: "/var/lib/mission-core-node-profiles/usb-can/preparation.json",
ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop")},
}
func modelForDevice(id string) *sensorModel {
@@ -0,0 +1,67 @@
package node
import (
"encoding/json"
"strings"
"time"
)
// Configuration browsing is a bounded snapshot, not a durable backup or write receipt.
func sensorSnapshot(action string) bool {
return strings.HasPrefix(action, "can.") || action == "vesc.qml.open" || action == "vesc.qml.frame" || action == "vesc.qml.close" || action == "vesc.samples.start" || action == "vesc.samples.status" || action == "vesc.samples.fetch" || action == "vesc.samples.stop" || action == "vesc.samples.read" || action == "vesc.qml.begin" || action == "vesc.qml.chunk" || action == "vesc.qml.render" || action == "vesc.packages.catalog" || action == "vesc.packages.inspect" || action == "vesc.packages.download" || action == "vesc.packages.begin" || action == "vesc.packages.chunk" || action == "vesc.packages.load" || action == "vesc.packages.forget" || action == "vesc.packages.status" || action == "vesc.packages.prepare" || action == "vesc.packages.remove_prepare" || action == "vesc.packages.restore" || action == "vesc.packages.reconcile" || action == "vesc.packages.refresh" || action == "vesc.bms.configuration.read" || action == "vesc.bms.configuration.preview" || action == "vesc.bms.configuration.reconcile" || action == "vesc.bms.configuration.restore" || action == "vesc.code.read" || action == "vesc.code.begin" || action == "vesc.code.chunk" || action == "vesc.code.prepare" || action == "vesc.code.erase_prepare" || action == "vesc.code.reconcile" || action == "vesc.code.control_prepare" || action == "vesc.code.stats" || action == "vesc.code.restore" || action == "vesc.firmware.backup" || action == "vesc.firmware.target" || action == "vesc.bms.read" || action == "vesc.bms.prepare" || action == "vesc.firmware.catalog" || action == "vesc.tools.read" || action == "vesc.terminal.read" || action == "vesc.firmware.status" || action == "vesc.configuration.read" || action == "vesc.configuration.preview" || action == "vesc.diagnostics.read"
}
func expiredSensorSnapshot(value SensorOperation) SensorOperation {
value.State = "error"
value.Error = "Снимок больше не хранится. Прочитайте данные заново."
value.Result = nil
return value
}
// Caller owns s.mu. Retain at most eight payloads (8 MiB); never evict an
// unacknowledged remote result to admit a new request. Tombstones retain
// operation identity, so retrying an old ID cannot execute hardware work again.
func (s *Sensors) writeOperation(value *SensorOperation) error {
// CAN requests/results are bounded RAM. On restart every USB generation is
// replaced; queued old-session commands cannot execute or replay TX.
if strings.HasPrefix(value.Command.Action, "can.") && value.Result == nil { return nil }
if !sensorSnapshot(value.Command.Action) || value.Result == nil {
return s.write(value.Command.ID+".json", value)
}
for {
count, bytes := 0, 0
var oldest *SensorOperation
for _, entry := range s.operations {
if !sensorSnapshot(entry.Command.Action) || entry.Result == nil {
continue
}
raw, err := json.Marshal(entry.Result)
if err != nil {
return err
}
count++
bytes += len(raw)
if entry != value && !entry.Remote && (oldest == nil || entry.Updated < oldest.Updated) {
oldest = entry
}
}
if count <= 8 && bytes <= 8*1024*1024 {
break
}
if oldest == nil {
*value = expiredSensorSnapshot(*value)
break
}
*oldest = expiredSensorSnapshot(*oldest)
}
// Payloads expire even if the operator leaves this panel open overnight.
for _, entry := range s.operations {
if sensorSnapshot(entry.Command.Action) && entry.Result != nil && !entry.Remote && time.Now().Unix()-entry.Updated >= 600 {
*entry = expiredSensorSnapshot(*entry)
}
}
if strings.HasPrefix(value.Command.Action, "can.") { return nil }
persisted := expiredSensorSnapshot(*value)
return s.write(value.Command.ID+".json", &persisted)
}
@@ -0,0 +1,61 @@
package node
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestSensorConfigurationSnapshotsBoundedAndNotPersisted(t *testing.T) {
s := &Sensors{root: t.TempDir(), operations: map[string]*SensorOperation{}}
for i := 0; i < 12; i++ {
id := strings.Repeat("a", i+1)
op := &SensorOperation{Command: SensorCommand{ID: id, Action: "vesc.configuration.read"}, State: "complete", Result: map[string]any{"xml": strings.Repeat("x", 100)}, Updated: time.Now().Unix() + int64(i)}
s.operations[id] = op
if err := s.writeOperation(op); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(s.root, id+".json"))
if err != nil {
t.Fatal(err)
}
var disk SensorOperation
if err = json.Unmarshal(raw, &disk); err != nil {
t.Fatal(err)
}
if disk.Result != nil || disk.State != "error" {
t.Fatal("read payload was persisted")
}
}
count := 0
for _, op := range s.operations {
if op.Result != nil {
count++
}
}
if count != 8 {
t.Fatalf("snapshot count %d", count)
}
if s.operations["a"].State != "error" {
t.Fatal("old snapshot remained live")
}
}
func TestConfigurationBackupsRemainDurable(t *testing.T) {
s := &Sensors{root: t.TempDir(), operations: map[string]*SensorOperation{}}
op := &SensorOperation{Command: SensorCommand{ID: "backup", Action: "vesc.config.backup"}, State: "complete", Result: map[string]any{"backup": true}}
if err := s.writeOperation(op); err != nil {
t.Fatal(err)
}
raw, _ := os.ReadFile(filepath.Join(s.root, "backup.json"))
var disk SensorOperation
if err := json.Unmarshal(raw, &disk); err != nil {
t.Fatal(err)
}
if disk.Result == nil || disk.State != "complete" {
t.Fatal("backup receipt was discarded")
}
}
@@ -0,0 +1,38 @@
package node
import (
"context"
"net/http"
"time"
)
// Only the existing observer owns USB sampling. This endpoint renews bounded
// read interest; it cannot pass a relay, command, action or input lease.
func (s *Sensors) telemetryRoutes(mux *http.ServeMux, server *Server) {
mux.HandleFunc("GET /api/devices/telemetry", func(w http.ResponseWriter, r *http.Request) {
if !server.authorized(w, r) {
return
}
w.Header().Set("Cache-Control", "no-store")
var model *sensorModel
for i := range sensorModels {
if sensorModels[i].ID == "vesc.controller" {
model = &sensorModels[i]
break
}
}
if model == nil {
reply(w, 503, map[string]string{"error": "Интеграция VESC недоступна."})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
defer cancel()
result, err := s.modelDriver(ctx, model, "/observe", nil)
if err != nil {
reply(w, 503, map[string]string{"error": "Нет свежих показаний контроллеров."})
return
}
result["fresh"] = true
reply(w, 200, result)
})
}
@@ -0,0 +1,40 @@
package node
import (
"errors"
"net/http"
"testing"
"time"
)
func TestTelemetryReadCannotCarryControlOrRenewInputLease(t *testing.T) {
server := newTestServer(t)
server.Sensors = isolatedSensors(t)
calls := 0
model := modelForDevice("vesc_00000000000000000000000000000000")
server.Sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if r.Method != "GET" || r.URL.Path != "/observe" || r.Body != nil {
t.Fatal("read became a command", r)
}
deadline, ok := r.Context().Deadline()
if !ok || time.Until(deadline) > 800*time.Millisecond {
t.Fatal("unbounded read")
}
return testSensorReply(map[string]any{"instance": "synthetic", "devices": []any{}}), nil
})
if response := call(server, "GET", "/api/devices/telemetry", "", nil); response.Code != 401 || calls != 0 {
t.Fatal("unauthorized read", response.Code, calls)
}
cookie := login(t, server)
if response := call(server, "GET", "/api/devices/telemetry", "", cookie); response.Code != 200 || calls != 1 || response.Header().Get("Cache-Control") != "no-store" {
t.Fatal("snapshot", response.Code, calls)
}
if response := call(server, "POST", "/api/devices/telemetry", `{"command":{"left":1}}`, cookie); response.Code == 200 || calls != 1 {
t.Fatal("command accepted")
}
server.Sensors.clients[model.ID].Transport = sensorRoundTrip(func(*http.Request) (*http.Response, error) { return nil, errors.New("offline") })
if response := call(server, "GET", "/api/devices/telemetry", "", cookie); response.Code != 503 {
t.Fatal("offline became fresh", response.Code)
}
}
@@ -0,0 +1,60 @@
package node
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"time"
)
// This is the upstream VESC Tool catalogue URL. The publisher currently serves
// it over HTTP. Treat every byte as untrusted code/data: fetching updates only
// the catalogue, never installs or executes a controller application.
const vescPackageCatalogueURL = "http://home.vedder.se/vesc_pkg/vesc_pkg_all.rcc"
const vescPackageCatalogueMax = 8 * 1024 * 1024
func fetchVescPackageCatalogue(ctx context.Context, client *http.Client) ([]byte,error) {
request,err:=http.NewRequestWithContext(ctx,http.MethodGet,vescPackageCatalogueURL,nil)
if err!=nil{return nil,err}
response,err:=client.Do(request)
if err!=nil{return nil,errors.New("Каталог автора недоступен. Сохранённый каталог остаётся доступным.")}
defer response.Body.Close()
if response.StatusCode!=http.StatusOK{return nil,errors.New("Автор каталога не вернул архив. Сохранённый каталог не изменён.")}
data,err:=io.ReadAll(io.LimitReader(response.Body,vescPackageCatalogueMax+1))
if err!=nil||len(data)>vescPackageCatalogueMax||!bytes.HasPrefix(data,[]byte("qres")){return nil,errors.New("Получен некорректный или слишком большой каталог.")}
return data,nil
}
func (s *Sensors) refreshVescPackages(c SensorCommand) (any,error) {
if len(c.Parameters)!=0{return nil,errors.New("Обновление использует только официальный каталог VESC.")}
deadline,_:=time.Parse(time.RFC3339Nano,c.Deadline)
ctx,cancel:=context.WithDeadline(context.Background(),deadline);defer cancel()
// No user URL, proxy environment, cookies, credentials or redirects. The USB
// driver keeps its PrivateNetwork sandbox and never performs Internet I/O.
transport:=&http.Transport{Proxy:nil,MaxIdleConns:1,DisableKeepAlives:true,ResponseHeaderTimeout:15*time.Second}
defer transport.CloseIdleConnections()
client:=&http.Client{Transport:transport,Timeout:35*time.Second,CheckRedirect:func(*http.Request,[]*http.Request)error{return http.ErrUseLastResponse}}
data,err:=fetchVescPackageCatalogue(ctx,client);if err!=nil{return nil,err}
sum:=sha256.Sum256(data)
step:=0
call:=func(action string,parameters map[string]any)(map[string]any,error){
child:=c;step++;id:=sha256.Sum256([]byte(fmt.Sprintf("%s/packages/%d",c.ID,step)));child.ID="op_"+hex.EncodeToString(id[:16]);child.Idempotency=child.ID;child.Action="vesc.packages."+action;child.Parameters=parameters
response,e:=s.modelDriver(ctx,modelForDevice(c.Session.DeviceID),"/operation",child)
if e!=nil{return nil,e};if response["state"]!="complete"{return nil,errors.New("Не удалось проверить новый каталог. Предыдущий каталог сохранён.")}
value,ok:=response["result"].(map[string]any);if !ok{return nil,errors.New("Некорректный ответ каталога.")};return value,nil
}
begin,err:=call("begin",map[string]any{"kind":"catalog","name":"vesc_pkg_all.rcc","size":len(data),"sha256":hex.EncodeToString(sum[:]),"library":false,"source":"upstream"});if err!=nil{return nil,err}
upload,ok:=begin["upload_id"].(string);if !ok{return nil,errors.New("Передача каталога не начата.")}
for offset:=0;offset<len(data);offset+=16384 {
end:=offset+16384;if end>len(data){end=len(data)}
result,e:=call("chunk",map[string]any{"upload_id":upload,"offset":offset,"data":base64.StdEncoding.EncodeToString(data[offset:end])});if e!=nil{return nil,e}
accepted,ok:=result["offset"].(float64);if !ok||int(accepted)!=end{return nil,errors.New("Передача каталога не подтверждена.")}
}
return call("load",map[string]any{"upload_id":upload})
}
@@ -0,0 +1,10 @@
package node
import("context";"io";"net/http";"strings";"testing")
type packageRoundTripper func(*http.Request)(*http.Response,error)
func(f packageRoundTripper)RoundTrip(r *http.Request)(*http.Response,error){return f(r)}
func TestPackageCatalogueFixedSourceAndBound(t *testing.T){
for _,test:=range []struct{body string;status int;valid bool}{{"qres-test",200,true},{"<html>",200,false},{"qres",503,false},{"qres"+strings.Repeat("a",vescPackageCatalogueMax),200,false}}{
client:=&http.Client{Transport:packageRoundTripper(func(r *http.Request)(*http.Response,error){if r.URL.String()!=vescPackageCatalogueURL||r.Method!="GET"||r.Header.Get("Authorization")!=""{t.Fatal("unexpected source/request")};return &http.Response{StatusCode:test.status,Body:io.NopCloser(strings.NewReader(test.body)),Header:make(http.Header)},nil})}
_,err:=fetchVescPackageCatalogue(context.Background(),client);if (err==nil)!=test.valid{t.Fatalf("expected valid %v, got %v",test.valid,err)}
}
}
+103 -14
View File
@@ -12,20 +12,26 @@ import (
"testing"
)
func TestVESCDeclaredVersionMatchesBundledDriver(t *testing.T) {
model := modelForDevice("vesc_00000000000000000000000000000000")
root := filepath.Join("..", "..", "..", "..", "plugins", "vesc")
driver, err := os.ReadFile(filepath.Join(root, "runtime", "__init__.py"))
if err != nil {
t.Fatal(err)
}
match := regexp.MustCompile(`(?m)^VERSION = "([^"]+)"`).FindSubmatch(driver)
if model == nil || len(match) != 2 || model.Version != string(match[1]) {
t.Fatal("Node must admit the exact driver shipped in the same release", model, string(driver))
}
preparation, err := os.ReadFile(filepath.Join(root, "packaging", "prepare.py"))
if err != nil || !strings.Contains(string(preparation), `"version": "`+model.Version+`"`) {
t.Fatal("VESC preparation must declare the bundled driver version", err)
func TestProtocolModelVersionsMatchBundledDrivers(t *testing.T) {
// A mismatched declaration silently replaces a healthy protocol device
// with USB discovery and a second, offline saved identity in Inventory.
for _, plugin := range []struct{ prefix, directory string }{
{"vesc", "vesc"}, {"usbcan", "usb-can"},
} {
t.Run(plugin.directory, func(t *testing.T) {
model := modelForDevice(plugin.prefix + "_00000000000000000000000000000000")
root := filepath.Join("..", "..", "..", "..", "plugins", plugin.directory)
driver, err := os.ReadFile(filepath.Join(root, "runtime", "__init__.py"))
if err != nil { t.Fatal(err) }
match := regexp.MustCompile(`(?m)^VERSION = "([^"]+)"`).FindSubmatch(driver)
if model == nil || len(match) != 2 || model.Version != string(match[1]) {
t.Fatal("Node must admit the exact driver shipped in the same release", model, string(driver))
}
preparation, err := os.ReadFile(filepath.Join(root, "packaging", "prepare.py"))
if err != nil || !strings.Contains(string(preparation), `"version": "`+model.Version+`"`) {
t.Fatal("Preparation must declare the bundled driver version", err)
}
})
}
}
@@ -139,3 +145,86 @@ func TestVESCPreparePromotesAttachmentToProtocolUUID(t *testing.T) {
t.Fatal("unplugged driver observation accepted")
}
}
func TestVESCCANAndOfflineAssignmentsDoNotRequireDirectUSB(t *testing.T) {
s := isolatedSensors(t)
model := modelForDevice("vesc_00000000000000000000000000000000")
uuid := strings.Repeat("01", 12)
id := modelDeviceID(model, "uuid:"+uuid)
item := s.discovery(id, "—", false)
item["prepared"], item["verified"] = true, false
status := map[string]any{
"identity": map[string]any{"uuid": uuid}, "connected": false,
"board_settings_supported": true,
"drive_profile": map[string]any{"bindings": map[string]any{"left.1": map[string]any{"device_id": id, "uuid": uuid}}},
}
item["vesc_status"] = status
s.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
return testSensorReply(map[string]any{"items": []any{item}}), nil
})
check := func(want bool) {
t.Helper()
all := s.Inventory()["items"].([]any)
items := []any{}
for _, raw := range all { if raw.(map[string]any)["kind"] == "vesc.controller" { items = append(items, raw) } }
if (len(items) == 1) != want {
t.Fatalf("unexpected transport projection: %v", items)
}
if want && items[0].(map[string]any)["prepared"] != true {
t.Fatal("driver metadata lost")
}
}
check(true)
item["online"], item["verified"], status["connected"] = true, true, true
route := map[string]any{"kind": "can", "uuid": uuid, "adapter_id": "usbcan_synthetic", "channel": 0, "can_id": 74, "bitrate": 500000}
status["control_transport"] = map[string]any{"routes": map[string]any{id: route}}
endpoint := map[string]any{"device_id": id, "uuid": uuid, "route": route, "verified": true, "session_id": sensorSessionID(item)}
status["control_endpoints"] = []any{endpoint}
fakeUSB(t, s.usbRoot, "2-8", "", "USB CANFD DEBUG", "8")
for key, value := range map[string]string{"idVendor": "04d8", "idProduct": "0053"} {
if err := os.WriteFile(filepath.Join(s.usbRoot, "2-8", key), []byte(value), 0600); err != nil { t.Fatal(err) }
}
adapterAttachment := discoverSensors(s.usbRoot)[0].id
status["control_adapters"] = []any{map[string]any{"id": "usbcan_synthetic", "attachment_id": adapterAttachment}}
check(true)
fakeVESC(t, s, "1-2", "3")
attachment := discoverSensors(s.usbRoot)[0].id
status["control_endpoints"] = []any{endpoint, map[string]any{
"device_id": id, "uuid": uuid, "attachment_id": attachment, "verified": true,
"route": map[string]any{"kind": "usb", "uuid": uuid},
}}
check(true) // Both wires still produce exactly one logical controller.
if err := os.RemoveAll(filepath.Join(s.usbRoot, "1-2")); err != nil {
t.Fatal(err)
}
status["control_endpoints"] = []any{endpoint}
endpoint["session_id"] = "stale"
check(false)
endpoint["session_id"] = sensorSessionID(item)
status["control_adapters"] = []any{}
check(true)
status["control_adapters"] = []any{map[string]any{"id": "usbcan_synthetic", "attachment_id": adapterAttachment}}
// Cached driver says online, but the selected OS adapter was unplugged.
if err := os.RemoveAll(filepath.Join(s.usbRoot, "2-8")); err != nil { t.Fatal(err) }
items := s.Inventory()["items"].([]any)
if len(items) != 1 { t.Fatal("assigned UUID metadata must survive adapter detach", items) }
offline := items[0].(map[string]any)
offstatus := offline["vesc_status"].(map[string]any)
if offline["online"] != false || offline["verified"] != false || offstatus["connected"] != false || offstatus["telemetry_ready"] != false {
t.Fatal("cached CAN driver outlived its physical adapter", offline)
}
// Reconnecting another USB generation must not revive the old CAN session.
fakeUSB(t, s.usbRoot, "2-8", "", "USB CANFD DEBUG", "9")
for key, value := range map[string]string{"idVendor": "04d8", "idProduct": "0053"} {
if err := os.WriteFile(filepath.Join(s.usbRoot, "2-8", key), []byte(value), 0600); err != nil { t.Fatal(err) }
}
for _, raw := range s.Inventory()["items"].([]any) {
it := raw.(map[string]any)
if it["id"] == id && it["online"] != false { t.Fatal("old adapter generation revived", it) }
}
route["kind"] = "usb"
check(false) // A stale direct USB observation never uses the CAN exception.
item["online"], item["verified"], status["connected"] = false, false, false
status["identity"] = map[string]any{"uuid": strings.Repeat("02", 12)}
check(false)
}
@@ -0,0 +1,141 @@
package node
import (
"encoding/json"
"regexp"
)
var vescUUID = regexp.MustCompile(`^[a-f0-9]{24}$`)
// Only the current installed VESC driver may project assigned offline metadata
// or a verified CAN endpoint. USB projections retain their existing OS guard.
func vescNonUSBProjection(item map[string]any, model *sensorModel) bool {
if model.ID != "vesc.controller" || !currentCameraSnapshot(item, model) {
return false
}
status, _ := item["vesc_status"].(map[string]any)
identity, _ := status["identity"].(map[string]any)
uuid, _ := identity["uuid"].(string)
id, _ := item["id"].(string)
if !vescUUID.MatchString(uuid) || modelDeviceID(model, "uuid:"+uuid) != id {
return false
}
drive, _ := status["drive_profile"].(map[string]any)
bindings, _ := drive["bindings"].(map[string]any)
assigned := false
for _, raw := range bindings {
binding, _ := raw.(map[string]any)
assigned = assigned || (binding["device_id"] == id && binding["uuid"] == uuid)
}
if !assigned || status["board_settings_supported"] != true {
return false
}
if item["online"] == false && item["verified"] == false && status["connected"] == false {
return true // Metadata only, never an available control endpoint.
}
if item["online"] != true || item["verified"] != true || status["connected"] != true {
return false
}
profile, _ := status["control_transport"].(map[string]any)
routes, _ := profile["routes"].(map[string]any)
route, _ := routes[id].(map[string]any)
if route["kind"] != "can" || route["uuid"] != uuid {
return false
}
adapterID, _ := route["adapter_id"].(string)
adapters, _ := status["control_adapters"].([]any)
present := false
for _, raw := range adapters {
adapter, _ := raw.(map[string]any)
present = present || (adapterID != "" && adapter["id"] == adapterID)
}
if !present {
return false
}
selected, err := json.Marshal(route)
if err != nil {
return false
}
endpoints, _ := status["control_endpoints"].([]any)
for _, raw := range endpoints {
endpoint, _ := raw.(map[string]any)
actual, err := json.Marshal(endpoint["route"])
if err == nil && endpoint["device_id"] == id && endpoint["uuid"] == uuid &&
endpoint["verified"] == true && endpoint["session_id"] == sensorSessionID(item) &&
string(actual) == string(selected) {
return true
}
}
return false
}
// A verified USB endpoint of the same MCU is an alias, not a second controller
// when its selected route is CAN or temporarily unavailable.
func vescUSBEndpointAlias(item map[string]any, model *sensorModel, attachment string) bool {
if model.ID != "vesc.controller" {
return false
}
status, _ := item["vesc_status"].(map[string]any)
identity, _ := status["identity"].(map[string]any)
uuid, _ := identity["uuid"].(string)
if !vescUUID.MatchString(uuid) || item["id"] != modelDeviceID(model, "uuid:"+uuid) {
return false
}
endpoints, _ := status["control_endpoints"].([]any)
for _, raw := range endpoints {
e, _ := raw.(map[string]any)
route, _ := e["route"].(map[string]any)
if e["device_id"] == item["id"] && e["uuid"] == uuid && e["verified"] == true &&
e["attachment_id"] == attachment && route["kind"] == "usb" && route["uuid"] == uuid {
return true
}
}
return false
}
// Invalidate a selected CAN route in the same OS inventory that loses its USB
// adapter, even while the VESC discovery thread is waiting for a reply/cleanup.
// Preserve UUID/configuration metadata; absence never changes the saved route.
func vescReconcileCANPresence(item map[string]any, model *sensorModel, usb []usbSensor) {
if model.ID != "vesc.controller" || !currentCameraSnapshot(item, model) { return }
status, _ := item["vesc_status"].(map[string]any)
profile, _ := status["control_transport"].(map[string]any)
routes, _ := profile["routes"].(map[string]any)
id, _ := item["id"].(string)
route, _ := routes[id].(map[string]any)
if route["kind"] != "can" { return }
adapters, _ := status["control_adapters"].([]any)
live := map[string]bool{}
current := []any{}
for _, raw := range adapters {
adapter, _ := raw.(map[string]any)
aid, _ := adapter["id"].(string)
attachment, _ := adapter["attachment_id"].(string)
for _, physical := range usb {
if aid != "" && attachment != "" && physical.model.ID == "waveshare.usb-can-fd-b" && physical.id == attachment {
live[aid] = true
current = append(current, raw)
break
}
}
}
status["control_adapters"] = current
endpoints, _ := status["control_endpoints"].([]any)
for _, raw := range endpoints {
endpoint, _ := raw.(map[string]any)
r, _ := endpoint["route"].(map[string]any)
aid, _ := r["adapter_id"].(string)
if r["kind"] == "can" && !live[aid] { endpoint["verified"] = false }
}
aid, _ := route["adapter_id"].(string)
if live[aid] { return }
item["online"], item["verified"] = false, false
status["connected"], status["readable"], status["telemetry_ready"], status["test_supported"] = false, false, false, false
status["telemetry"] = nil
status["message"] = "CAN-адаптер недоступен."
snapshot, _ := item["snapshot"].(map[string]any)
if snapshot != nil {
snapshot["connectivity"] = "offline"
snapshot["message"] = status["message"]
}
}
+26 -11
View File
@@ -247,6 +247,7 @@ func (s *Sensors) Inventory() map[string]any {
if !currentCameraSnapshot(item, model) {
continue
}
vescReconcileCANPresence(item, model, usb)
attachment, _ := item["attachment_id"].(string)
matched := false
for _, candidate := range usb {
@@ -254,10 +255,17 @@ func (s *Sensors) Inventory() map[string]any {
matched = true
}
}
if !matched {
if !matched && !vescNonUSBProjection(item, model) {
continue
}
seen[attachment] = true
if matched {
seen[attachment] = true
}
for _, candidate := range usb {
if candidate.model == model && vescUSBEndpointAlias(item, model, candidate.id) {
seen[candidate.id] = true
}
}
}
s.mu.Lock()
if model.PrepareUnit != "" && !model.ProtocolIdentity {
@@ -354,7 +362,7 @@ func (s *Sensors) discovery(id, speed string, online bool) map[string]any {
}
func sensorViewAction(action string) bool {
return action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list" || action == "vesc.telemetry.read" || action == "vesc.limits.read" || action == "vesc.config.backup"
return action == "can.status" || action == "vesc.firmware.status" || action == "vesc.firmware.cancel" || action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list" || action == "vesc.telemetry.read" || action == "vesc.limits.read" || action == "vesc.configuration.read" || action == "vesc.diagnostics.read" || action == "vesc.config.backup"
}
func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) {
@@ -388,10 +396,10 @@ func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error)
return nil, errors.New("Срок команды истёк. Устройство не изменено.")
}
for _, v := range s.operations {
if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model {
if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && c.Action != "vesc.motor.stop" && c.Action != "can.stop" && c.Action != "can.transmit.stop" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model {
return nil, errors.New("Подготовка модели ещё выполняется.")
}
if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) {
if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && c.Action != "vesc.motor.stop" && c.Action != "can.stop" && c.Action != "can.transmit.stop" && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) {
return nil, errors.New("Другая операция устройства ещё выполняется.")
}
}
@@ -407,7 +415,7 @@ func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error)
return nil, errors.New("Журнал операций заполнен. Повторите позже.")
}
value := &SensorOperation{Command: c, State: "running", Remote: remote, Updated: time.Now().Unix()}
if e = s.write(c.ID+".json", value); e != nil {
if e = s.writeOperation(value); e != nil {
return nil, e
}
s.operations[c.ID] = value
@@ -444,6 +452,8 @@ func (s *Sensors) execute(c SensorCommand) {
} else if c.Action == "prepare" {
result, err = s.prepare(c, item)
uncertain = errors.Is(err, errPreparationUncertain)
} else if c.Action == "vesc.packages.refresh" {
result, err = s.refreshVescPackages(c)
} else if c.Action == "rename" {
name, ok := c.Parameters["name"].(string)
if !ok || strings.TrimSpace(name) == "" || len([]rune(name)) > 80 || strings.ContainsAny(name, "\n\r\t") {
@@ -463,9 +473,8 @@ func (s *Sensors) execute(c SensorCommand) {
cancel()
uncertain = err != nil || v["state"] == "unknown"
if err == nil {
if v["state"] == "complete" {
result = v["result"]
} else {
result = v["result"]
if v["state"] != "complete" {
message, _ := v["error"].(string)
err = errors.New(message)
}
@@ -487,6 +496,8 @@ func (s *Sensors) execute(c SensorCommand) {
}
v := s.operations[c.ID]
v.Updated = time.Now().Unix()
// Preserve bounded driver diagnostics on error as well as successful data.
v.Result = result
if err != nil {
v.State = "error"
if uncertain {
@@ -497,7 +508,7 @@ func (s *Sensors) execute(c SensorCommand) {
v.State = "complete"
v.Result = result
}
if s.write(c.ID+".json", v) != nil {
if s.writeOperation(v) != nil {
v.State = "unknown"
v.Error = "Не удалось сохранить результат операции. Обновите состояние устройства."
}
@@ -506,6 +517,9 @@ func (s *Sensors) Get(id string) *SensorOperation {
s.mu.Lock()
defer s.mu.Unlock()
if v := s.operations[id]; v != nil {
if sensorSnapshot(v.Command.Action) && v.Result != nil && time.Now().Unix()-v.Updated >= 600 {
*v = expiredSensorSnapshot(*v)
}
copy := *v
return &copy
}
@@ -525,6 +539,7 @@ func (s *Sensors) RemoteResults() []any {
}
func (s *Sensors) Routes(mux *http.ServeMux, server *Server) {
s.configurationRoutes(mux, server)
s.telemetryRoutes(mux, server)
mux.HandleFunc("GET /api/devices/events", func(w http.ResponseWriter, r *http.Request) { s.stream(w, r, server) })
mux.HandleFunc("GET /api/devices", func(w http.ResponseWriter, r *http.Request) {
if server.authorized(w, r) {
@@ -567,7 +582,7 @@ func (s *Sensors) Acknowledge(ids []string) {
for _, id := range ids {
if v := s.operations[id]; v != nil && v.State != "running" {
v.Remote = false
_ = s.write(id+".json", v)
_ = s.writeOperation(v)
}
}
}
+4
View File
@@ -13,6 +13,7 @@ import (
)
type Server struct {
Budget *LinkBudget
Monitor *Monitor
Store *Store
Pairing *Pairing
@@ -82,6 +83,8 @@ func reply(w http.ResponseWriter, status int, v any) {
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
s.routerRoutes(mux)
s.linkBudgetRoutes(mux)
s.localPreviewRoutes(mux)
s.monitorRoutes(mux)
if s.Presentation != nil {
@@ -95,6 +98,7 @@ func (s *Server) Handler() http.Handler {
}
if s.Pairing != nil {
s.Pairing.localRoutes(mux, s)
s.Pairing.networkLocalRoutes(mux, s)
}
if s.Access != nil {
s.accessRoutes(mux)
File diff suppressed because it is too large Load Diff