feat(service): add passive peer-reachability probe handler

RunPeerReachabilityProbe is the post-migration replacement for the
active swUpdateUrl round-trip: register the device IP with the
in-process observer, nudge :8090/swUpdateCheck, and wait for any
inbound from that IP. No device-state mutation. Any inbound counts
as proof — on a migrated speaker, DNS interception routes the
daemon's outbounds through this service regardless of which URL it
resolved internally, so reachability reduces to "did the device
dial us at all."

PeerHit and the abstract observer interface live in setup alongside
the probe logic; handlers.peerObserver implements the interface and
the existing observer files now import from setup.

Route: POST /setup/peer-probe/{deviceId}. Timeout: 30s, surfaced as
result.ElapsedMs so the budget can be tuned from real data. The
pre-flight orchestrator gains the branch in the next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Tobias Gesellchen
2026-05-11 20:31:24 +02:00
co-authored by Claude Opus 4.7
parent dc924e351c
commit d74bb9b5ca
7 changed files with 330 additions and 22 deletions
+94
View File
@@ -0,0 +1,94 @@
package setup
import (
"errors"
"fmt"
"time"
)
// PeerHit is the payload the observer middleware delivers to a probe
// waiter when a request from a registered peer IP lands on the service.
type PeerHit struct {
Path string
At time.Time
}
// PeerObserverHandle is the abstract view of the peer-observer registry
// the probe needs: register interest in an IP, eventually forget it.
// The handlers package's peerObserver satisfies this implicitly.
type PeerObserverHandle interface {
Register(ip string) <-chan PeerHit
Forget(ip string)
}
// PeerProbeResult is the JSON-serializable outcome of a passive
// reachability probe. Reached is the canonical success bit the UI keys
// off; ObservedPath and ElapsedMs are diagnostic.
type PeerProbeResult struct {
Reached bool `json:"reached"`
ObservedPath string `json:"observed_path,omitempty"`
ElapsedMs int64 `json:"elapsed_ms"`
}
// RunPeerReachabilityProbe is the post-migration reachability check
// that replaces the active swUpdateUrl round-trip. The sequence:
//
// 1. Register the device IP with the observer.
// 2. Nudge :8090/swUpdateCheck on the device to make the swUpdate
// daemon fan out *something* sooner than its own ~5min timer.
// 3. Wait up to timeout for any inbound from that IP.
//
// Any inbound counts as proof of reachability — on a migrated speaker,
// DNS interception means the daemon's outbounds (update fan-out, marge
// polls, BMX registry calls) all funnel through this service regardless
// of which URL the daemon resolved internally. We don't need a specific
// URL to land; we just need *the device* to dial us.
//
// The nudge is fire-and-forget. If :8090 is unreachable, the request
// returns quickly and we still wait for the daemon's own next fan-out
// (or time out). No state on the device is mutated; the probe is safe
// to re-run.
func (m *Manager) RunPeerReachabilityProbe(deviceIP string, observer PeerObserverHandle, timeout time.Duration) (*PeerProbeResult, error) {
if observer == nil {
return nil, errors.New("peer probe not configured: observer is nil")
}
if deviceIP == "" {
return nil, errors.New("peer probe: deviceIP is required")
}
hitCh := observer.Register(deviceIP)
defer observer.Forget(deviceIP)
// Nudge the device. Fire-and-forget — we don't gate on the response
// because the swUpdateCheck endpoint returns immediately after
// enqueuing, and the daemon's fan-out is what we actually want to
// observe. HTTPGet can be nil in test contexts.
if m.HTTPGet != nil {
swCheckURL := fmt.Sprintf("http://%s:8090/swUpdateCheck", deviceIP)
go func() {
resp, err := m.HTTPGet(swCheckURL)
if err != nil {
return
}
_ = resp.Body.Close()
}()
}
start := time.Now()
result := &PeerProbeResult{}
select {
case hit := <-hitCh:
result.Reached = true
result.ObservedPath = hit.Path
case <-time.After(timeout):
result.Reached = false
}
result.ElapsedMs = time.Since(start).Milliseconds()
return result, nil
}
+142
View File
@@ -0,0 +1,142 @@
package setup
import (
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
)
// fakePeerObserver is a deterministic PeerObserverHandle for unit
// tests. It exposes the channel returned from Register so the test can
// signal it manually to simulate a device inbound landing.
type fakePeerObserver struct {
mu sync.Mutex
channels map[string]chan PeerHit
forgotten []string
}
func newFakePeerObserver() *fakePeerObserver {
return &fakePeerObserver{channels: map[string]chan PeerHit{}}
}
func (o *fakePeerObserver) Register(ip string) <-chan PeerHit {
o.mu.Lock()
defer o.mu.Unlock()
ch := make(chan PeerHit, 1)
o.channels[ip] = ch
return ch
}
func (o *fakePeerObserver) Forget(ip string) {
o.mu.Lock()
defer o.mu.Unlock()
delete(o.channels, ip)
o.forgotten = append(o.forgotten, ip)
}
func (o *fakePeerObserver) signal(ip string, hit PeerHit) {
o.mu.Lock()
defer o.mu.Unlock()
ch, ok := o.channels[ip]
if !ok {
return
}
select {
case ch <- hit:
default:
}
}
func peerProbeManager(onTrigger func()) *Manager {
return &Manager{
HTTPGet: func(url string) (*http.Response, error) {
if onTrigger != nil {
onTrigger()
}
rr := httptest.NewRecorder()
rr.WriteHeader(200)
return rr.Result(), nil
},
}
}
func TestRunPeerReachabilityProbe_HappyPath(t *testing.T) {
obs := newFakePeerObserver()
// On nudge, simulate the device fanning out to /updates/soundtouch
// which the middleware would signal as a hit on this IP.
m := peerProbeManager(func() {
obs.signal("192.168.1.42", PeerHit{Path: "/updates/soundtouch", At: time.Now()})
})
result, err := m.RunPeerReachabilityProbe("192.168.1.42", obs, 2*time.Second)
if err != nil {
t.Fatalf("RunPeerReachabilityProbe error: %v", err)
}
if !result.Reached {
t.Error("Reached = false, want true")
}
if result.ObservedPath != "/updates/soundtouch" {
t.Errorf("ObservedPath = %q, want %q", result.ObservedPath, "/updates/soundtouch")
}
if len(obs.forgotten) != 1 || obs.forgotten[0] != "192.168.1.42" {
t.Errorf("Forget not called for IP: forgotten = %v", obs.forgotten)
}
}
func TestRunPeerReachabilityProbe_Timeout(t *testing.T) {
obs := newFakePeerObserver()
m := peerProbeManager(nil) // nudge fires but device never responds
start := time.Now()
result, err := m.RunPeerReachabilityProbe("192.168.1.42", obs, 200*time.Millisecond)
elapsed := time.Since(start)
if err != nil {
t.Fatalf("RunPeerReachabilityProbe error: %v", err)
}
if result.Reached {
t.Error("Reached = true, want false (no hit)")
}
if elapsed < 200*time.Millisecond {
t.Errorf("returned early after %v; expected >= 200ms timeout", elapsed)
}
if len(obs.forgotten) != 1 {
t.Errorf("Forget not called after timeout: forgotten = %v", obs.forgotten)
}
}
func TestRunPeerReachabilityProbe_NilObserver(t *testing.T) {
m := peerProbeManager(nil)
_, err := m.RunPeerReachabilityProbe("192.168.1.42", nil, time.Second)
if err == nil {
t.Error("expected error for nil observer, got nil")
}
}
func TestRunPeerReachabilityProbe_EmptyIP(t *testing.T) {
m := peerProbeManager(nil)
obs := newFakePeerObserver()
_, err := m.RunPeerReachabilityProbe("", obs, time.Second)
if err == nil {
t.Error("expected error for empty deviceIP, got nil")
}
}
func TestRunPeerReachabilityProbe_NilHTTPGetTimesOut(t *testing.T) {
// With nil HTTPGet the nudge is skipped entirely; the probe just
// waits for the device to dial in on its own. Useful in tests and
// in environments where the trigger isn't safe to fire.
m := &Manager{} // HTTPGet nil
obs := newFakePeerObserver()
result, err := m.RunPeerReachabilityProbe("192.168.1.42", obs, 100*time.Millisecond)
if err != nil {
t.Fatalf("error: %v", err)
}
if result.Reached {
t.Error("Reached = true with no nudge and no signal")
}
}