Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Serve state reads without queueing behind registry rebuilds
rcourtmanb32a0800605c
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 30171b6092..8c23da990d 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -3998,7 +3998,7 @@ func buildFrontendStateFromSnapshot(snapshot models.StateSnapshot) models.StateFfunc (m *Monitor) buildBroadcastFrontendStateFromSnapshot(snapshot models.StateSnapshot) models.StateFrontend {frontendState := buildFrontendStateFromSnapshot(snapshot)- m.updateResourceStore(snapshot)+ m.updateResourceStoreForRead(snapshot)if m != nil && m.alertManager != nil {if liveAlerts := m.activeAlertsSnapshot(); len(liveAlerts) > 0 || len(frontendState.ActiveAlerts) > 0 {frontendState.ActiveAlerts = liveAlerts@@ -4695,6 +4695,60 @@ func (m *Monitor) shouldSkipNodeMetrics(nodeName string) bool {return should}+// readPathRegistryFreshness bounds how stale the unified registry may be+// when a read path (state API, websocket hydrate) serves it without+// rebuilding. It only needs to be wide enough to collapse same-cycle rebuild+// storms (agent report + broadcast + state request); it must stay well under+// the poll cadence so every poll-cycle broadcast still publishes a fresh+// registry.+const readPathRegistryFreshness = 2 * time.Second++// readRefreshResourceStore is implemented by stores whose read paths can+// refresh without queueing behind ingest rebuilds (see MonitorAdapter).+type readRefreshResourceStore interface {+ TryReplaceRegistryForRead(snapshot models.StateSnapshot, maxAge time.Duration, supply func() map[unifiedresources.DataSource][]unifiedresources.IngestRecord) bool+}++// updateResourceStoreForRead keeps the resource store fresh on behalf of a+// read path. Ingest boundaries (agent reports) call updateResourceStore and+// always rebuild; serving state must not redo work an ingest just did, and+// above all must not queue behind an in-flight rebuild whose change-record+// and identity-pin persistence can take seconds per transaction on slow+// volumes (#1665: /api/state stuck for minutes with SQLite on NFS).+func (m *Monitor) updateResourceStoreForRead(state models.StateSnapshot) {+ m.mu.RLock()+ store := m.resourceStore+ m.mu.RUnlock()++ if store == nil {+ return+ }+ readStore, ok := store.(readRefreshResourceStore)+ if !ok {+ m.updateResourceStore(state)+ return+ }++ if thresholdStore, ok := store.(StaleThresholdResourceStore); ok {+ thresholdStore.SetStaleThresholds(m.resourceStaleThresholds())+ }+ snapshotForStore := state+ if ownedSources := m.providerOwnedSnapshotSources(); len(ownedSources) > 0 {+ snapshotForStore = unifiedresources.SnapshotWithoutSources(state, ownedSources)+ }+ rebuilt := readStore.TryReplaceRegistryForRead(snapshotForStore, readPathRegistryFreshness, m.collectSupplementalRecordsBySource)+ if !rebuilt {+ return+ }+ recordSupplementalResourceChanges(store, m.collectSupplementalChanges())+ m.syncUnifiedAgentMetrics(store)+ m.syncUnifiedVMMetrics(store)+ m.syncUnifiedStorageMetrics(store)+ m.syncUnifiedPhysicalDiskMetrics(store)+ m.syncUnifiedAppContainerMetrics(store)+ m.syncUnifiedResourceAlertsToState(store.GetAll())+}+// updateResourceStore populates the canonical resource store from current// monitoring state. Callers use it at accepted-ingest boundaries and before// broadcast hydration so every ReadState consumer observes the same snapshot.diff --git a/internal/unifiedresources/monitor_adapter.go b/internal/unifiedresources/monitor_adapter.goindex 4e3e8e2dd2..3fdbe0f768 100644--- a/internal/unifiedresources/monitor_adapter.go+++ b/internal/unifiedresources/monitor_adapter.go@@ -146,13 +146,69 @@ func (a *MonitorAdapter) ResolveCanonicalResourceID(ref string) (string, bool) {return canonicalID, ok}+// LastRebuiltAt returns when the registry last published a generation. Zero+// when no snapshot or supplemental ingest has completed yet.+func (a *MonitorAdapter) LastRebuiltAt() time.Time {+ if a == nil {+ return time.Time{}+ }+ a.mu.RLock()+ defer a.mu.RUnlock()+ return a.lastRebuiltAt+}++// TryReplaceRegistryForRead rebuilds the registry on behalf of a read path+// (/api/state, websocket hydrate). Unlike the ingest-driven populate methods+// it never queues behind an in-flight rebuild and skips entirely while the+// current generation is younger than maxAge, so serving state cannot stall+// on registry persistence (change records and identity pins write to SQLite,+// which can take seconds per transaction on slow volumes — #1665). The+// supplemental payload is only materialized via supply() once a rebuild is+// committed, keeping consume-once providers undrained on skipped refreshes.+// The one exception is a cold start: before the first generation exists a+// read path must block and build it, or first loads would render empty.+// Returns true when a rebuild ran.+func (a *MonitorAdapter) TryReplaceRegistryForRead(snapshot models.StateSnapshot, maxAge time.Duration, supply func() map[DataSource][]IngestRecord) bool {+ if a == nil {+ return false+ }+ if last := a.LastRebuiltAt(); !last.IsZero() {+ if maxAge > 0 && time.Since(last) < maxAge {+ return false+ }+ if !a.mutationMu.TryLock() {+ // An ingest rebuild is already publishing a generation at least+ // as fresh as this snapshot; serve the current one instead.+ return false+ }+ } else {+ a.mutationMu.Lock()+ }+ defer a.mutationMu.Unlock()+ // Re-check under the lock: another rebuild may have published while this+ // caller was acquiring it.+ if last := a.LastRebuiltAt(); !last.IsZero() && maxAge > 0 && time.Since(last) < maxAge {+ return false+ }+ var recordsBySource map[DataSource][]IngestRecord+ if supply != nil {+ recordsBySource = supply()+ }+ a.replaceRegistryLocked(snapshot, recordsBySource)+ return true+}+func (a *MonitorAdapter) replaceRegistry(snapshot models.StateSnapshot, recordsBySource map[DataSource][]IngestRecord) {if a == nil {return}a.mutationMu.Lock()defer a.mutationMu.Unlock()+ a.replaceRegistryLocked(snapshot, recordsBySource)+}+// replaceRegistryLocked is the rebuild body; callers must hold mutationMu.+func (a *MonitorAdapter) replaceRegistryLocked(snapshot models.StateSnapshot, recordsBySource map[DataSource][]IngestRecord) {registry := a.currentRegistry()if registry == nil {returndiff --git a/internal/unifiedresources/monitor_adapter_read_refresh_test.go b/internal/unifiedresources/monitor_adapter_read_refresh_test.gonew file mode 100644index 0000000000..00e0397ee6--- /dev/null+++ b/internal/unifiedresources/monitor_adapter_read_refresh_test.go@@ -0,0 +1,126 @@+package unifiedresources++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func readRefreshSnapshot(name string) models.StateSnapshot {+ return models.StateSnapshot{+ LastUpdate: time.Now().UTC(),+ VMs: []models.VM{{+ ID: "lab:node-a:101",+ VMID: 101,+ Name: name,+ Node: "node-a",+ Instance: "lab",+ Status: "running",+ LastSeen: time.Now().UTC(),+ }},+ }+}++func TestTryReplaceRegistryForReadColdStartBlocksAndBuilds(t *testing.T) {+ adapter := NewMonitorAdapter(NewRegistry(NewMemoryStore()))++ supplied := false+ rebuilt := adapter.TryReplaceRegistryForRead(readRefreshSnapshot("database"), time.Minute, func() map[DataSource][]IngestRecord {+ supplied = true+ return nil+ })+ if !rebuilt {+ t.Fatal("cold-start read refresh must build the first generation")+ }+ if !supplied {+ t.Fatal("committed rebuild must materialize the supplemental payload")+ }+ if adapter.LastRebuiltAt().IsZero() {+ t.Fatal("rebuild must publish a generation timestamp")+ }+ if len(adapter.GetAll()) != 1 {+ t.Fatalf("expected 1 resource after cold-start build, got %d", len(adapter.GetAll()))+ }+}++func TestTryReplaceRegistryForReadSkipsFreshGeneration(t *testing.T) {+ adapter := NewMonitorAdapter(NewRegistry(NewMemoryStore()))+ adapter.PopulateFromSnapshot(readRefreshSnapshot("database"))++ rebuilt := adapter.TryReplaceRegistryForRead(readRefreshSnapshot("renamed"), time.Minute, func() map[DataSource][]IngestRecord {+ t.Fatal("skipped refresh must not drain the supplemental payload")+ return nil+ })+ if rebuilt {+ t.Fatal("read refresh must skip while the generation is fresh")+ }+ if got := adapter.GetAll(); len(got) != 1 || got[0].Name != "database" {+ t.Fatalf("fresh generation must be served unchanged, got %+v", got)+ }+}++func TestTryReplaceRegistryForReadRebuildsStaleGeneration(t *testing.T) {+ adapter := NewMonitorAdapter(NewRegistry(NewMemoryStore()))+ adapter.PopulateFromSnapshot(readRefreshSnapshot("database"))++ time.Sleep(20 * time.Millisecond)+ rebuilt := adapter.TryReplaceRegistryForRead(readRefreshSnapshot("renamed"), 10*time.Millisecond, nil)+ if !rebuilt {+ t.Fatal("read refresh must rebuild once the generation is older than maxAge")+ }+ if got := adapter.GetAll(); len(got) != 1 || got[0].Name != "renamed" {+ t.Fatalf("stale refresh must publish the new snapshot, got %+v", got)+ }+}++func TestTryReplaceRegistryForReadDoesNotQueueBehindInflightRebuild(t *testing.T) {+ store := &blockingChangeStore{+ MemoryStore: NewMemoryStore(),+ entered: make(chan struct{}),+ release: make(chan struct{}),+ }+ adapter := NewMonitorAdapter(NewRegistry(store))+ // Publish a baseline generation so the read path is past cold start. An+ // empty snapshot records no changes, leaving the store helper armed for+ // the ingest rebuild below.+ adapter.PopulateFromSnapshot(models.StateSnapshot{LastUpdate: time.Now().UTC()})+ if adapter.LastRebuiltAt().IsZero() {+ t.Fatal("baseline rebuild must publish a generation")+ }++ ingestDone := make(chan struct{})+ go func() {+ adapter.PopulateFromSnapshot(readRefreshSnapshot("database"))+ close(ingestDone)+ }()++ select {+ case <-store.entered:+ case <-time.After(time.Second):+ t.Fatal("ingest rebuild did not reach change publication")+ }++ readDone := make(chan bool, 1)+ go func() {+ readDone <- adapter.TryReplaceRegistryForRead(readRefreshSnapshot("read"), time.Nanosecond, func() map[DataSource][]IngestRecord {+ return nil+ })+ }()++ select {+ case rebuilt := <-readDone:+ if rebuilt {+ t.Fatal("read refresh must not rebuild while an ingest rebuild is in flight")+ }+ case <-time.After(time.Second):+ t.Fatal("read refresh queued behind the in-flight ingest rebuild")+ }++ close(store.release)+ select {+ case <-ingestDone:+ case <-time.After(time.Second):+ t.Fatal("ingest rebuild did not complete after release")+ }+}