mirror of
https://github.com/netbirdio/netbird.git
synced 2026-09-15 19:29:08 +02:00
The 1542-line tray.go grew into a 14-feature kitchen sink. Split it
into feature-coherent same-package siblings, give the daemon-stream
service a name that matches what it actually does, and trim the
cargo-cult context.WithCancel pattern from click handlers.
File layout (tray.go: 1542 → ~470 lines):
- tray_status.go onStatusEvent / applyStatus / status indicator
- tray_icon.go applyIcon / iconForState (tray icon painting)
- tray_events.go onSystemEvent + eventTitle / titleCase, plus a
shouldSkipSystemEvent helper that names the
three "daemon notification we don't surface"
filters
- tray_session.go session-expiry row + warning notification flow +
handleSessionExpired (moved from tray.go)
- tray_profiles.go loadConfig / loadProfiles / switchProfile
- tray_exitnodes.go exit-node submenu (rebuild / refresh / toggle)
Mutex split: the kitchen-sink t.mu becomes four domain-scoped mutexes
so a long-running gRPC call in one domain can't block status-push
readers in another:
- statusMu connected / lastStatus / lastDaemonVersion /
lastNetworksRevision / pendingConnectLogin
- sessionMu sessionExpiresAt (read by the 30s ticker,
written by applySessionExpiry on every status push)
- profileMu activeProfile / activeUsername /
notificationsEnabled / switchCancel
- exitNodesMu row cache (read in reapplyMenuState's Repaint copy)
- exitNodesRebuildMu serialises ListNetworks + submenu rebuild +
SetMenu (already separate, kept)
Service rename: the "Peers" service handled the daemon's full
SubscribeStatus snapshot (peers, daemon version, management/signal
link state, networks revision, SSO deadline) plus the SubscribeEvents
notification stream and the profile-switch suppression filter. Peers
was a misleading name for a daemon-stream fan-out service. Rename to
DaemonFeed in services/, profileswitcher's stored reference, the
TrayServices struct, main.go wiring, and every doc comment that
referenced it. peers.go → daemon_feed.go. The Status.Peers field
itself (the peer list in the snapshot) is unchanged.
Event constant renames (wire strings unchanged so the frontend keeps
working without regenerating bindings beyond the rename):
- EventStatus → EventStatusSnapshot
Payload is a full Status struct (daemon-wide snapshot), not just
a state-change ping — name the value-shape.
- EventSystem → EventDaemonNotification
Payload is a daemon SystemEvent meant to drive an OS toast or a
Recent Events row. "System" was too generic; "Notification"
matches what consumers do with it.
Concurrency fixes:
- WaitExtendAuthSession now preempts a previous in-flight wait
via the existing SetWaitCancel/CancelWait infrastructure on
PendingFlow, the same pattern WaitSSOLogin uses. The previous
waiter exits with codes.Canceled; the authsession service
translates that to ExtendResult{Preempted: true} so the tray
and the about-to-expire dialog stay silent on the losing flow
instead of showing a false-failure toast. Without this, both
a tray "Extend now" click and a dialog "Stay connected" click
on the same deadline started two parallel IdP polls, and
whichever lost the device-code check painted a bogus error.
- mgmClient.ExtendAuthSession drops the dead backoff retry loop.
The loop only retried on codes.Canceled, but the inner mgmCtx
was derived from context.Background() and never cancelled, so
every real error went straight to backoff.Permanent on the
first attempt. Replace with a single
context.WithTimeout(c.ctx, ConnectTimeout) call; daemon
shutdown now interrupts the RPC and behaviour on real errors
is unchanged.
Click-handler hygiene: six call sites used the cargo-cult
context.WithCancel(context.Background()) + defer cancel() pattern
without ever calling cancel() externally. Replace with
context.Background() directly (loadConfig, loadProfiles,
runExtendSession, dismissSessionWarning, handleConnect's Up,
handleDisconnect's Down). The one site that genuinely needs the
cancel — switchProfile, which stores it in t.switchCancel so
handleDisconnect can preempt the switch — keeps WithCancel.
Helper extraction: shouldSkipSystemEvent groups the three
"daemon notification we drop on the floor" checks
(new_version_available metadata, progress_window metadata, the
::/0 partner of an exit-node default-route event) behind a single
named predicate. Each had a comment explaining why; collecting
them moves the rationale into the helper docstring and shrinks
onSystemEvent to a router.
127 lines
4.3 KiB
Go
127 lines
4.3 KiB
Go
//go:build !android && !ios && !freebsd && !js
|
|
|
|
// Package updater carries the auto-update domain: the typed State the UI
|
|
// renders, the daemon-SystemEvent metadata schema, and the Holder that
|
|
// caches the latest state and broadcasts changes. Mirrors the layout of
|
|
// client/ui/i18n and client/ui/preferences — no Wails dependency, just an
|
|
// optional Emitter interface so callers can pass either the Wails event
|
|
// processor or a fake in tests.
|
|
package updater
|
|
|
|
import (
|
|
"sync"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"github.com/netbirdio/netbird/client/proto"
|
|
)
|
|
|
|
// EventStateChanged is the single Wails event the frontend and tray
|
|
// subscribe to. The payload is the full State snapshot, so consumers
|
|
// never need to combine multiple events to know what to render.
|
|
const EventStateChanged = "netbird:update:state"
|
|
|
|
// State is the typed snapshot of the daemon's update situation, covering
|
|
// the three branches the UI cares about:
|
|
//
|
|
// - Disabled / opt-in: Available=true, Enforced=false, Installing=false.
|
|
// Tray shows "Download latest", frontend shows a "Get installer" hint
|
|
// pointing at GitHub.
|
|
// - Enforced, user-driven: Available=true, Enforced=true, Installing=false.
|
|
// Tray shows "Install version X", frontend shows the install banner.
|
|
// - Forced, daemon already installing: Available=true, Enforced=true,
|
|
// Installing=true. Both surfaces show the install-in-progress UI.
|
|
//
|
|
// Installing is driven only by the daemon's progress_window:show event;
|
|
// a UI-side Update.Trigger() does not flip it. The frontend tracks its own
|
|
// "Trigger() in flight" state for the enforced flow.
|
|
type State struct {
|
|
Available bool `json:"available"`
|
|
Version string `json:"version"`
|
|
Enforced bool `json:"enforced"`
|
|
Installing bool `json:"installing"`
|
|
}
|
|
|
|
// Emitter is the dependency Holder needs to broadcast changes. The Wails
|
|
// app.Event processor satisfies this; tests pass nil or a fake. Same shape
|
|
// the preferences package uses, intentionally — both are "broadcast to the
|
|
// frontend" hooks with no other contract.
|
|
type Emitter interface {
|
|
Emit(name string, data ...any) bool
|
|
}
|
|
|
|
// Holder caches the latest update State and broadcasts changes. Fed by
|
|
// services.DaemonFeed, which forwards every daemon SystemEvent here via
|
|
// OnSystemEvent. The state is read by the Wails-bound services.Update
|
|
// facade (Get) and pushed to subscribers via the Emitter.
|
|
type Holder struct {
|
|
emitter Emitter
|
|
|
|
mu sync.Mutex
|
|
state State
|
|
}
|
|
|
|
// NewHolder constructs an empty-state Holder. The emitter is optional —
|
|
// pass nil in tests to skip the broadcast.
|
|
func NewHolder(emitter Emitter) *Holder {
|
|
return &Holder{emitter: emitter}
|
|
}
|
|
|
|
// Get returns a copy of the cached State. Used by the Wails facade so the
|
|
// frontend can pull the current value on mount before its push subscription
|
|
// has anything to deliver.
|
|
func (h *Holder) Get() State {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
return h.state
|
|
}
|
|
|
|
// OnSystemEvent inspects the daemon's SystemEvent metadata for the three
|
|
// update-related keys (new_version_available, enforced, progress_window
|
|
// plus version) and folds the result into the cached state. Emits
|
|
// EventStateChanged only when the state actually changed, so subscribers
|
|
// do not see redundant pushes when the daemon repeats a snapshot.
|
|
//
|
|
// The metadata schema is owned here and nowhere else — neither Peers nor
|
|
// the tray nor the frontend reaches into ev.Metadata directly.
|
|
func (h *Holder) OnSystemEvent(ev *proto.SystemEvent) {
|
|
md := ev.GetMetadata()
|
|
if len(md) == 0 {
|
|
return
|
|
}
|
|
|
|
h.mu.Lock()
|
|
changed := false
|
|
if v, ok := md["new_version_available"]; ok {
|
|
_, enforced := md["enforced"]
|
|
if !h.state.Available || h.state.Version != v || h.state.Enforced != enforced {
|
|
h.state.Available = true
|
|
h.state.Version = v
|
|
h.state.Enforced = enforced
|
|
changed = true
|
|
}
|
|
}
|
|
if md["progress_window"] == "show" {
|
|
if !h.state.Installing {
|
|
h.state.Installing = true
|
|
changed = true
|
|
}
|
|
if v, ok := md["version"]; ok && v != "" && h.state.Version != v {
|
|
h.state.Version = v
|
|
h.state.Available = true
|
|
changed = true
|
|
}
|
|
}
|
|
snap := h.state
|
|
h.mu.Unlock()
|
|
|
|
if !changed {
|
|
return
|
|
}
|
|
log.Infof("update state: available=%v version=%q enforced=%v installing=%v",
|
|
snap.Available, snap.Version, snap.Enforced, snap.Installing)
|
|
if h.emitter != nil {
|
|
h.emitter.Emit(EventStateChanged, snap)
|
|
}
|
|
}
|