Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

fix(monitoring): bind publication changes to captured providers

pulse-triage[bot]1f6b648107e8
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 18f15e5aa2..4c142665f2 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -7113,3 +7113,20 @@ checks each of those readers after a report-merge, against a control
exclusion that splits nothing, and `TestManualNodeLinkReplacesAnOperatorSplit`
covers the agents API's link after a split, a split after it, and a
resources API relink.
+
+### Resource publication ownership correction (10 October 2026)
+
+One refresh captures its store, binding generation, tenant and provider set once.
+Snapshot-source ownership, records and consume-once changes use that selection;
+changes are drained only after an admitted publication, into that pass's store.
+Replaced or ended-epoch collections and skipped read refreshes leave changes
+pending. An admitted old pass can finish its own history without consuming a
+replacement provider's events. Poll-provider replacement also invalidates pending
+collections. Provider callbacks run outside wiring, publication and adapter locks.
+Read refreshes share ingest publication ordering, retain fresh-generation skips
+and never queue behind a warm ingest; a cold read still builds its first registry.
+
+`resource_publication_ownership_test.go` supplies deterministic channel barriers,
+consume-once replacement-store controls, refused and skipped drains, read-provider
+re-entry, and duplicate/loss assertions, alongside the original initialization,
+tenant withdrawal, saved first-alert policy and joined-shutdown controls.
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 9977be5ec5..7cb9626f15 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -5692,10 +5692,11 @@ type readRefreshResourceStore interface {
// 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, scope mockModeScope) {
- m.mu.RLock()
- store := m.resourceStore
- m.mu.RUnlock()
-
+ if !scope.current() {
+ return
+ }
+ binding := m.captureResourceStoreBinding()
+ store := binding.store
if store == nil {
return
}
@@ -5705,25 +5706,48 @@ func (m *Monitor) updateResourceStoreForRead(state models.StateSnapshot, scope m
return
}
+ // Preserve the cheap fresh-read path and the cold-start build guarantee.
+ // A warm read never waits behind an ingest publication. Records themselves
+ // are repeatable; collect them outside both publication and adapter locks.
+ cold := false
+ if timed, ok := store.(interface{ LastRebuiltAt() time.Time }); ok {
+ last := timed.LastRebuiltAt()
+ cold = last.IsZero()
+ if !cold && time.Since(last) < readPathRegistryFreshness {
+ 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)
+ snapshotForStore := unifiedresources.SnapshotWithoutSources(state, binding.providers.ownedSnapshotSources(m))
+ recordsBySource := binding.providers.recordsBySource(m)
+ if cold {
+ m.resourcePublishMu.Lock()
+ } else if !m.resourcePublishMu.TryLock() {
+ return
+ }
+ if m.resourceWiringGeneration.Load() != binding.generation {
+ m.resourcePublishMu.Unlock()
+ return
}
rebuilt := false
mark, published := scope.publish(func() bool {
- rebuilt = readStore.TryReplaceRegistryForRead(snapshotForStore, readPathRegistryFreshness, m.collectSupplementalRecordsBySource)
- if rebuilt {
- recordSupplementalResourceChanges(store, m.collectSupplementalChanges())
- }
+ rebuilt = readStore.TryReplaceRegistryForRead(snapshotForStore, readPathRegistryFreshness, func() map[unifiedresources.DataSource][]unifiedresources.IngestRecord {
+ return recordsBySource
+ })
return rebuilt
})
+ m.resourcePublishMu.Unlock()
if !published || !rebuilt {
return
}
- m.syncPublishedResourceStore(store, scope, mark)
+ // Once admitted, this pass drains only its captured providers into its
+ // captured store, even if a replacement is now wiring or publishing.
+ recordSupplementalResourceChanges(store, binding.providers.changes(m))
+ if m.resourceWiringGeneration.Load() == binding.generation {
+ m.syncPublishedResourceStore(store, scope, mark)
+ }
}
// syncPublishedResourceStore runs the metric and alert syncs over the registry
@@ -5752,10 +5776,11 @@ func (m *Monitor) currentStateWithScope() (models.StateSnapshot, mockModeScope)
// broadcast hydration so every ReadState consumer observes the same snapshot.
// The scope must predate the read of state (see currentStateWithScope).
func (m *Monitor) updateResourceStore(state models.StateSnapshot, scope mockModeScope) {
- m.mu.RLock()
- store := m.resourceStore
- generation := m.resourceWiringGeneration.Load()
- m.mu.RUnlock()
+ if !scope.current() {
+ return
+ }
+ binding := m.captureResourceStoreBinding()
+ store, generation := binding.store, binding.generation
if store == nil {
log.Debug().Msg("[Resources] No resource store configured, skipping population")
@@ -5775,7 +5800,7 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot, scope mockMode
Msg("[Resources] Populating resource store from state snapshot")
snapshotForStore := state
- ownedSources := m.providerOwnedSnapshotSources()
+ ownedSources := binding.providers.ownedSnapshotSources(m)
if len(ownedSources) > 0 {
snapshotForStore = unifiedresources.SnapshotWithoutSources(state, ownedSources)
sourceNames := make([]string, 0, len(ownedSources))
@@ -5792,7 +5817,7 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot, scope mockMode
if !scope.current() {
return
}
- recordsBySource := m.collectSupplementalRecordsBySource()
+ recordsBySource := binding.providers.recordsBySource(m)
m.resourcePublishMu.Lock()
if m.resourceWiringGeneration.Load() != generation {
m.resourcePublishMu.Unlock()
@@ -5832,14 +5857,14 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot, scope mockMode
return true
})
m.resourcePublishMu.Unlock()
- if !published || m.resourceWiringGeneration.Load() != generation {
+ if !published {
// The snapshot belongs to the mode the monitor just left.
return
}
// Drain consume-once changes only for a pass that actually published. No
// provider callback runs under resourcePublishMu, and changes already
// drained remain history even if a subsequent rewire replaces the binding.
- recordSupplementalResourceChanges(store, m.collectSupplementalChanges())
+ recordSupplementalResourceChanges(store, binding.providers.changes(m))
if m.resourceWiringGeneration.Load() == generation {
m.syncPublishedResourceStore(store, scope, mark)
}
diff --git a/internal/monitoring/poll_providers.go b/internal/monitoring/poll_providers.go
index ed7d2fd1c3..ff38c2fc86 100644
--- a/internal/monitoring/poll_providers.go
+++ b/internal/monitoring/poll_providers.go
@@ -448,8 +448,15 @@ func (m *Monitor) RegisterPollProvider(provider PollProvider) error {
if m.pollProviders == nil {
m.pollProviders = make(map[InstanceType]PollProvider)
}
+ changed := !sameWiredValue(m.pollProviders[providerType], provider)
m.pollProviders[providerType] = provider
+ if changed {
+ m.resourceWiringGeneration.Add(1)
+ }
m.mu.Unlock()
+ if changed {
+ m.mockModeFence.advance()
+ }
m.refreshInstanceInfoCacheFromProviders()
return nil
@@ -815,10 +822,82 @@ func (m *Monitor) providerConnectionStatuses(provider PollProvider) map[string]b
return statuses
}
+// A resource pass owns one store and one immutable provider selection. Neither
+// records, snapshot ownership nor consume-once changes may resnapshot wiring
+// independently: a replacement between those calls can drain its events into
+// the old store. Capture under m.mu; all optional provider callbacks run after
+// releasing it, including mode filtering.
+type resourceStoreBinding struct {
+ store ResourceStoreInterface
+ generation uint64
+ providers supplementalProviderSet
+}
+
+type supplementalProviderSet struct {
+ poll []PollProvider
+ manual map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider
+ orgID string
+}
+
+func (m *Monitor) captureResourceStoreBinding() resourceStoreBinding {
+ if m == nil {
+ return resourceStoreBinding{providers: supplementalProviderSet{orgID: "default"}}
+ }
+ mode := mock.IsMockEnabled()
+ m.mu.RLock()
+ binding := resourceStoreBinding{store: m.resourceStore, generation: m.resourceWiringGeneration.Load()}
+ binding.providers.orgID = strings.TrimSpace(m.orgID)
+ if binding.providers.orgID == "" {
+ binding.providers.orgID = "default"
+ }
+ byType := make(map[InstanceType]PollProvider, len(m.pollProviders)+4)
+ for typ, provider := range m.pollProviders {
+ if provider != nil {
+ byType[typ] = provider
+ }
+ }
+ binding.providers.manual = make(map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider, len(m.supplementalProviders))
+ for source, provider := range m.supplementalProviders {
+ if provider != nil {
+ binding.providers.manual[source] = provider
+ }
+ }
+ m.mu.RUnlock()
+
+ for _, provider := range []PollProvider{newPVEPollProvider(), newPBSPollProvider(), newPMGPollProvider(), newAvailabilityPollProvider()} {
+ typ := provider.Type()
+ if _, exists := byType[typ]; !exists {
+ byType[typ] = provider
+ }
+ }
+ types := make([]string, 0, len(byType))
+ for typ := range byType {
+ types = append(types, string(typ))
+ }
+ sort.Strings(types)
+ for _, typ := range types {
+ binding.providers.poll = append(binding.providers.poll, byType[InstanceType(typ)])
+ }
+ for source, provider := range binding.providers.manual {
+ if bound, ok := provider.(interface{ SupplementalRecordsMockMode() bool }); ok && bound.SupplementalRecordsMockMode() != mode {
+ delete(binding.providers.manual, source)
+ }
+ }
+ return binding
+}
+
+func (m *Monitor) supplementalProviderSnapshot() map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider {
+ return m.captureResourceStoreBinding().providers.manual
+}
+
func (m *Monitor) providerOwnedSnapshotSources() []unifiedresources.DataSource {
+ return m.captureResourceStoreBinding().providers.ownedSnapshotSources(m)
+}
+
+func (p supplementalProviderSet) ownedSnapshotSources(m *Monitor) []unifiedresources.DataSource {
owned := make(map[string]unifiedresources.DataSource)
- providers := m.pollProviderSnapshotWithBuiltins()
+ providers := p.poll
for _, provider := range providers {
if provider == nil {
continue
@@ -843,13 +922,8 @@ func (m *Monitor) providerOwnedSnapshotSources() []unifiedresources.DataSource {
}
}
- orgID := "default"
- if m != nil {
- if trimmed := strings.TrimSpace(m.orgID); trimmed != "" {
- orgID = trimmed
- }
- }
- for _, provider := range m.supplementalProviderSnapshot() {
+ orgID := p.orgID
+ for _, provider := range p.manual {
if provider == nil {
continue
}
@@ -891,56 +965,18 @@ func (m *Monitor) providerOwnedSnapshotSources() []unifiedresources.DataSource {
return sources
}
-func (m *Monitor) supplementalProviderSnapshot() map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider {
- if m == nil {
- return nil
- }
-
- m.mu.RLock()
- if len(m.supplementalProviders) == 0 {
- m.mu.RUnlock()
- return nil
- }
- snapshot := make(map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider, len(m.supplementalProviders))
- for source, provider := range m.supplementalProviders {
- if provider == nil {
- continue
- }
- normalized := unifiedresources.DataSource(strings.ToLower(strings.TrimSpace(string(source))))
- if normalized == "" {
- continue
- }
- snapshot[normalized] = provider
- }
- m.mu.RUnlock()
-
- // The flag flips before the router's post-switch hook runs. Use one mode
- // for the pair, and keep these optional callbacks outside the monitor lock.
- mode := mock.IsMockEnabled()
- for source, provider := range snapshot {
- if bound, ok := provider.(interface{ SupplementalRecordsMockMode() bool }); ok && bound.SupplementalRecordsMockMode() != mode {
- delete(snapshot, source)
- }
- }
- if len(snapshot) == 0 {
- return nil
- }
- return snapshot
+func (m *Monitor) collectSupplementalRecordsBySource() map[unifiedresources.DataSource][]unifiedresources.IngestRecord {
+ return m.captureResourceStoreBinding().providers.recordsBySource(m)
}
-func (m *Monitor) collectSupplementalRecordsBySource() map[unifiedresources.DataSource][]unifiedresources.IngestRecord {
- providers := m.pollProviderSnapshotWithBuiltins()
- manualProviders := m.supplementalProviderSnapshot()
+func (p supplementalProviderSet) recordsBySource(m *Monitor) map[unifiedresources.DataSource][]unifiedresources.IngestRecord {
+ providers := p.poll
+ manualProviders := p.manual
if len(providers) == 0 && len(manualProviders) == 0 {
return nil
}
- orgID := "default"
- if m != nil {
- if trimmed := strings.TrimSpace(m.orgID); trimmed != "" {
- orgID = trimmed
- }
- }
+ orgID := p.orgID
recordsBySource := make(map[unifiedresources.DataSource][]unifiedresources.IngestRecord)
for _, provider := range providers {
@@ -994,18 +1030,17 @@ func (m *Monitor) collectSupplementalRecordsBySource() map[unifiedresources.Data
}
func (m *Monitor) collectSupplementalChanges() []unifiedresources.ResourceChange {
- providers := m.pollProviderSnapshotWithBuiltins()
- manualProviders := m.supplementalProviderSnapshot()
+ return m.captureResourceStoreBinding().providers.changes(m)
+}
+
+func (p supplementalProviderSet) changes(m *Monitor) []unifiedresources.ResourceChange {
+ providers := p.poll
+ manualProviders := p.manual
if len(providers) == 0 && len(manualProviders) == 0 {
return nil
}
- orgID := "default"
- if m != nil {
- if trimmed := strings.TrimSpace(m.orgID); trimmed != "" {
- orgID = trimmed
- }
- }
+ orgID := p.orgID
changes := make([]unifiedresources.ResourceChange, 0)
for _, provider := range providers {
diff --git a/internal/monitoring/resource_publication_ownership_test.go b/internal/monitoring/resource_publication_ownership_test.go
new file mode 100644
index 0000000000..b612fe4fae
--- /dev/null
+++ b/internal/monitoring/resource_publication_ownership_test.go
@@ -0,0 +1,284 @@
+package monitoring
+
+import (
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// Changes are genuinely consume-once, not the repeatable slice used by the
+// generic fixtures. A misplaced drain cannot be hidden by another refresh.
+type consumeOnceWiringProvider struct {
+ name string
+ beforeRecords func()
+ beforeChanges func(*Monitor)
+ mu sync.Mutex
+ pending bool
+ drains int
+}
+
+func (p *consumeOnceWiringProvider) SupplementalRecords(*Monitor, string) []unifiedresources.IngestRecord {
+ if p.beforeRecords != nil {
+ p.beforeRecords()
+ }
+ return wiringRecords(p.name)
+}
+
+func (p *consumeOnceWiringProvider) SupplementalChanges(m *Monitor, org string) []unifiedresources.ResourceChange {
+ if p.beforeChanges != nil {
+ p.beforeChanges(m)
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if !p.pending {
+ return nil
+ }
+ p.pending = false
+ p.drains++
+ return []unifiedresources.ResourceChange{{ResourceID: p.name, ResourceName: p.name, OrgID: org}}
+}
+
+func (p *consumeOnceWiringProvider) drainCount() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return p.drains
+}
+
+type wiringChangeStore struct {
+ *wiringPublicationStore
+ changeMu sync.Mutex
+ changes []string
+}
+
+func newWiringChangeStore() *wiringChangeStore {
+ return &wiringChangeStore{wiringPublicationStore: newWiringPublicationStore()}
+}
+
+func (s *wiringChangeStore) RecordChange(change unifiedresources.ResourceChange) error {
+ s.changeMu.Lock()
+ defer s.changeMu.Unlock()
+ s.changes = append(s.changes, change.ResourceID)
+ return nil
+}
+
+func assertWiringChanges(t *testing.T, s *wiringChangeStore, want ...string) {
+ t.Helper()
+ s.changeMu.Lock()
+ defer s.changeMu.Unlock()
+ if len(s.changes) != len(want) {
+ t.Fatalf("changes = %v, want %v", s.changes, want)
+ }
+ for i := range want {
+ if s.changes[i] != want[i] {
+ t.Fatalf("changes = %v, want %v", s.changes, want)
+ }
+ }
+}
+
+// Hold the first provider callback after the old publication. The returned
+// implementation called Type while taking a new provider snapshot; the fixed
+// implementation uses the captured set and goes straight to Changes. Both
+// reach this same channel barrier before the manual provider is drained.
+type changeSelectionBarrier struct {
+ testPollProvider
+ published *atomic.Bool
+ entered chan struct{}
+ release chan struct{}
+ once sync.Once
+}
+
+func (p *changeSelectionBarrier) hold() {
+ if p.published.Load() {
+ p.once.Do(func() { close(p.entered); <-p.release })
+ }
+}
+
+func (p *changeSelectionBarrier) Type() InstanceType {
+ p.hold()
+ return "barrier"
+}
+
+func (*changeSelectionBarrier) SupplementalSource() unifiedresources.DataSource {
+ return "barrier"
+}
+
+func (p *changeSelectionBarrier) SupplementalChanges(*Monitor, string) []unifiedresources.ResourceChange {
+ p.hold()
+ return nil
+}
+
+func TestResourcePublicationChangesStayWithTheirCapturedStoreAndProvider(t *testing.T) {
+ for _, read := range []bool{false, true} {
+ name := "ingest"
+ if read {
+ name = "read"
+ }
+ t.Run(name, func(t *testing.T) {
+ oldStore, newStore := newWiringChangeStore(), newWiringChangeStore()
+ oldProvider := &consumeOnceWiringProvider{name: "old-host", pending: true}
+ newProvider := &consumeOnceWiringProvider{name: "new-host", pending: true}
+ var published atomic.Bool
+ barrier := &changeSelectionBarrier{published: &published, entered: make(chan struct{}), release: make(chan struct{})}
+ // Read refresh uses the native MonitorAdapter; for it the first
+ // post-publication callback itself is the unambiguous boundary.
+ if read {
+ oldProvider.beforeChanges = func(*Monitor) { published.Store(true); barrier.hold() }
+ } else {
+ oldStore.before = func() { published.Store(true) }
+ }
+ m := &Monitor{state: models.NewState(), resourceStore: oldStore,
+ pollProviders: map[InstanceType]PollProvider{"barrier": barrier},
+ supplementalProviders: map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: oldProvider}}
+ newCollecting, releaseNew := make(chan struct{}), make(chan struct{})
+ var newOnce, releaseOldOnce, releaseNewOnce sync.Once
+ newProvider.beforeRecords = func() { newOnce.Do(func() { close(newCollecting); <-releaseNew }) }
+ unblockOld := func() { releaseOldOnce.Do(func() { close(barrier.release) }) }
+ unblockNew := func() { releaseNewOnce.Do(func() { close(releaseNew) }) }
+ defer unblockOld()
+ defer unblockNew()
+ oldDone, newDone := make(chan struct{}), make(chan struct{})
+ go func() {
+ defer close(oldDone)
+ state, scope := m.currentStateWithScope()
+ if read {
+ m.updateResourceStoreForRead(state, scope)
+ } else {
+ m.updateResourceStore(state, scope)
+ }
+ }()
+ waitForSignal(t, barrier.entered, 5*time.Second, "old publication did not reach change selection")
+ go func() {
+ defer close(newDone)
+ m.SetResourceStoreAndProviders(newStore, map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: newProvider})
+ }()
+ waitForSignal(t, newCollecting, 5*time.Second, "replacement did not attach and collect")
+ unblockOld()
+ waitForSignal(t, oldDone, 5*time.Second, "old pass did not finish")
+ assertWiringChanges(t, oldStore, "old-host")
+ assertWiringChanges(t, newStore)
+ if newProvider.drainCount() != 0 {
+ t.Fatal("replacement's unpublished change was consumed")
+ }
+ unblockNew()
+ waitForSignal(t, newDone, 5*time.Second, "replacement did not finish")
+ m.updateResourceStore(m.currentStateWithScope())
+ assertWiringChanges(t, oldStore, "old-host")
+ assertWiringChanges(t, newStore, "new-host")
+ if oldProvider.drainCount() != 1 || newProvider.drainCount() != 1 {
+ t.Fatal("an admitted change was lost or drained twice")
+ }
+ })
+ }
+}
+
+func TestResourcePublicationRefusedCollectionsDoNotDrainChanges(t *testing.T) {
+ for _, read := range []bool{false, true} {
+ for _, endEpoch := range []bool{false, true} {
+ name := "ingest-rewire"
+ if read {
+ name = "read-rewire"
+ }
+ if endEpoch {
+ name += "-ended-epoch"
+ }
+ t.Run(name, func(t *testing.T) {
+ oldStore, newStore := newWiringChangeStore(), newWiringChangeStore()
+ entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
+ var held, released sync.Once
+ unblock := func() { released.Do(func() { close(release) }) }
+ defer unblock()
+ p := &consumeOnceWiringProvider{name: "delayed-host", pending: true}
+ p.beforeRecords = func() { held.Do(func() { close(entered); <-release }) }
+ m := &Monitor{state: models.NewState(), resourceStore: oldStore,
+ supplementalProviders: map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: p}}
+ go func() {
+ defer close(done)
+ state, scope := m.currentStateWithScope()
+ if read {
+ m.updateResourceStoreForRead(state, scope)
+ } else {
+ m.updateResourceStore(state, scope)
+ }
+ }()
+ waitForSignal(t, entered, 5*time.Second, "records did not enter")
+ if endEpoch {
+ m.mockModeFence.advance()
+ } else {
+ m.SetResourceStoreAndProviders(newStore, map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: nil})
+ }
+ unblock()
+ waitForSignal(t, done, 5*time.Second, "refused collection did not return")
+ assertWiringChanges(t, oldStore)
+ if p.drainCount() != 0 || !oldStore.LastRebuiltAt().IsZero() {
+ t.Fatal("refused pass published or consumed a change")
+ }
+ // Reattach/retry in the current epoch: exactly one event survives.
+ m.SetResourceStoreAndProviders(newStore, map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: p})
+ assertWiringChanges(t, newStore, "delayed-host")
+ })
+ }
+ }
+}
+
+func TestResourcePublicationReadSkipsDoNotDrainOrQueue(t *testing.T) {
+ store := newWiringChangeStore()
+ store.MonitorAdapter.PopulateFromSnapshot(models.StateSnapshot{})
+ p := &consumeOnceWiringProvider{name: "pending-host", pending: true}
+ m := &Monitor{state: models.NewState(), resourceStore: store,
+ supplementalProviders: map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: p}}
+ m.updateResourceStoreForRead(m.currentStateWithScope())
+ assertWiringChanges(t, store)
+ if p.drainCount() != 0 {
+ t.Fatal("fresh read drained changes")
+ }
+ // An adapter without a LastRebuiltAt extension also must not queue behind
+ // the monitor publication lock. Its decline is not a successful publish.
+ declining := &decliningWiringReadStore{testSupplementalResourceStore: &testSupplementalResourceStore{}}
+ m.resourceStore = declining
+ m.resourcePublishMu.Lock()
+ done := make(chan struct{})
+ go func() { defer close(done); m.updateResourceStoreForRead(m.currentStateWithScope()) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ m.resourcePublishMu.Unlock()
+ t.Fatal("warm read queued behind an ingest publication")
+ }
+ m.resourcePublishMu.Unlock()
+ m.updateResourceStoreForRead(m.currentStateWithScope())
+ if p.drainCount() != 0 || len(declining.recordedChanges) != 0 {
+ t.Fatal("busy or declined read drained changes")
+ }
+ m.updateResourceStore(m.currentStateWithScope())
+ if p.drainCount() != 1 || len(declining.recordedChanges) != 1 {
+ t.Fatal("skipped reads lost the pending change")
+ }
+}
+
+type decliningWiringReadStore struct{ *testSupplementalResourceStore }
+
+func (*decliningWiringReadStore) TryReplaceRegistryForRead(models.StateSnapshot, time.Duration, func() map[unifiedresources.DataSource][]unifiedresources.IngestRecord) bool {
+ return false
+}
+
+func TestResourcePublicationReadProviderCanReenterWiring(t *testing.T) {
+ store := newWiringChangeStore()
+ newProvider := &consumeOnceWiringProvider{name: "new-host", pending: true}
+ oldProvider := &consumeOnceWiringProvider{name: "old-host", pending: true}
+ m := &Monitor{state: models.NewState(), resourceStore: store,
+ supplementalProviders: map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: oldProvider}}
+ oldProvider.beforeRecords = func() {
+ m.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, newProvider)
+ }
+ done := make(chan struct{})
+ go func() { defer close(done); m.updateResourceStoreForRead(m.currentStateWithScope()) }()
+ waitForSignal(t, done, 5*time.Second, "read provider re-entry deadlocked")
+ assertWiringChanges(t, store, "new-host")
+ if oldProvider.drainCount() != 0 {
+ t.Fatal("refused old read drained changes")
+ }
+}