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
fix(api): isolate tenant resource store construction
pulse-triage[bot]3b91896371a3
diff --git a/internal/api/resourceapi/resources.go b/internal/api/resourceapi/resources.goindex 505e2c0b8d..25365bd6f6 100644--- a/internal/api/resourceapi/resources.go+++ b/internal/api/resourceapi/resources.go@@ -21,12 +21,18 @@ import (unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rs/zerolog/log"+ "golang.org/x/sync/singleflight")// QueryService provides HTTP handlers for the unified resource API.type QueryService struct {- cfg *config.Config- storeMu sync.Mutex+ cfg *config.Config+ // storeLifecycle prevents eviction from overtaking in-flight constructors.+ storeLifecycle sync.RWMutex+ storeOpening singleflight.Group+ storeMu sync.Mutex+ // openStore is an optional constructor seam, set only before serving requests.+ openStore func(string, string) (unified.ResourceStore, error)stores map[string]unified.ResourceStorecacheMu sync.MutexregistryCache map[string]registryCacheEntry@@ -1318,25 +1324,50 @@ func NormalizeDataSourceAlias(source unified.DataSource) unified.DataSource {}func (h *QueryService) getStore(orgID string) (unified.ResourceStore, error) {- h.storeMu.Lock()- defer h.storeMu.Unlock()- if h.stores == nil {- h.stores = make(map[string]unified.ResourceStore)- }+ h.storeLifecycle.RLock()+ defer h.storeLifecycle.RUnlock()key := cacheKey(orgID)- if store, ok := h.stores[key]; ok {- return store, nil+ lookup := func() (unified.ResourceStore, bool) {+ h.storeMu.Lock()+ defer h.storeMu.Unlock()+ store, ok := h.stores[key]+ return store, ok}- dataDir := ""- if h.cfg != nil {- dataDir = h.cfg.DataPath+ if store, ok := lookup(); ok {+ return store, nil}- store, err := unified.NewSQLiteResourceStore(dataDir, key)+ // Deduplicate only this tenant. An unrelated tenant's cold constructor must+ // not hold the cache mutex or delay already-open stores.+ value, err, _ := h.storeOpening.Do(key, func() (any, error) {+ if store, ok := lookup(); ok {+ return store, nil+ }+ dataDir := ""+ if h.cfg != nil {+ dataDir = h.cfg.DataPath+ }+ open := h.openStore+ if open == nil {+ open = func(dir, org string) (unified.ResourceStore, error) {+ return unified.NewSQLiteResourceStore(dir, org)+ }+ }+ store, err := open(dataDir, key)+ if err != nil {+ return nil, err+ }+ h.storeMu.Lock()+ if h.stores == nil {+ h.stores = make(map[string]unified.ResourceStore)+ }+ h.stores[key] = store+ h.storeMu.Unlock()+ return store, nil+ })if err != nil {return nil, err}- h.stores[key] = store- return store, nil+ return value.(unified.ResourceStore), nil}// InvalidateCache clears a tenant's resource registry and presentation cache@@ -1363,12 +1394,14 @@ func (h *QueryService) CloseTenantStore(orgID string) error {}key := cacheKey(orgID)+ h.storeLifecycle.Lock()h.storeMu.Lock()store, ok := h.stores[key]if ok {delete(h.stores, key)}h.storeMu.Unlock()+ h.storeLifecycle.Unlock()h.invalidateCache(orgID)@@ -1385,6 +1418,7 @@ func (h *QueryService) CloseStores() error {return nil}+ h.storeLifecycle.Lock()h.storeMu.Lock()stores := make(map[string]unified.ResourceStore, len(h.stores))for key, store := range h.stores {@@ -1392,6 +1426,7 @@ func (h *QueryService) CloseStores() error {}h.stores = make(map[string]unified.ResourceStore)h.storeMu.Unlock()+ h.storeLifecycle.Unlock()var errs []errorfor key, store := range stores {diff --git a/internal/api/resourceapi/resources_store_concurrency_test.go b/internal/api/resourceapi/resources_store_concurrency_test.gonew file mode 100644index 0000000000..759862a0ba--- /dev/null+++ b/internal/api/resourceapi/resources_store_concurrency_test.go@@ -0,0 +1,165 @@+package resourceapi++import (+ "errors"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++// These tests exercise API coordination only; no durable store is opened.+type coordinationStore struct {+ unified.ResourceStore+ closed atomic.Int32+}++func (s *coordinationStore) Close() error { s.closed.Add(1); return nil }++func TestStoreConstructionDoesNotBlockOtherTenants(t *testing.T) {+ h := NewQueryService(nil)+ warm := &coordinationStore{}+ h.stores[cacheKey("warm")] = warm+ entered, release := make(chan struct{}), make(chan struct{})+ var once sync.Once+ unblock := func() { once.Do(func() { close(release) }) }+ defer unblock()+ h.openStore = func(_, key string) (unified.ResourceStore, error) {+ if key == "cold" {+ close(entered)+ <-release+ }+ return &coordinationStore{}, nil+ }+ coldDone := make(chan struct{})+ go func() { defer close(coldDone); _, _ = h.getStore("cold") }()+ <-entered+ for _, key := range []string{"warm", "independent"} {+ done := make(chan error, 1)+ go func(key string) { _, err := h.getStore(key); done <- err }(key)+ select {+ case err := <-done:+ if err != nil {+ t.Fatal(err)+ }+ case <-time.After(time.Second):+ unblock()+ <-coldDone+ t.Fatalf("tenant %s waited for unrelated cold construction", key)+ }+ }+ unblock()+ <-coldDone+ if err := h.CloseStores(); err != nil {+ t.Fatal(err)+ }+}++func TestStoreConstructionDeduplicatesAndCoordinatesClose(t *testing.T) {+ for _, all := range []bool{false, true} {+ name := "tenant"+ if all {+ name = "all"+ }+ t.Run(name, func(t *testing.T) {+ h := NewQueryService(nil)+ entered, release := make(chan struct{}), make(chan struct{})+ var calls atomic.Int32+ store := &coordinationStore{}+ h.openStore = func(_, _ string) (unified.ResourceStore, error) {+ if calls.Add(1) == 1 {+ close(entered)+ }+ <-release+ return store, nil+ }+ var wg sync.WaitGroup+ for i := 0; i < 12; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, err := h.getStore("same")+ if err != nil {+ t.Error(err)+ }+ }()+ }+ <-entered+ close(release)+ wg.Wait()+ if calls.Load() != 1 {+ t.Fatalf("constructors=%d", calls.Load())+ }+ // A second blocked construction must finish before either eviction method returns.+ entered, release = make(chan struct{}), make(chan struct{})+ pendingStore := &coordinationStore{}+ h.openStore = func(_, _ string) (unified.ResourceStore, error) {+ close(entered)+ <-release+ return pendingStore, nil+ }+ done := make(chan struct{})+ go func() { defer close(done); _, _ = h.getStore("pending") }()+ <-entered+ closed := make(chan error, 1)+ go func() {+ if all {+ closed <- h.CloseStores()+ } else {+ closed <- h.CloseTenantStore("pending")+ }+ }()+ select {+ case err := <-closed:+ close(release)+ <-done+ t.Fatalf("close returned before pending constructor: %v", err)+ case <-time.After(50 * time.Millisecond):+ }+ close(release)+ <-done+ if err := <-closed; err != nil {+ t.Fatal(err)+ }+ if _, ok := h.stores[cacheKey("pending")]; ok {+ t.Fatal("pending store survived eviction")+ }+ if pendingStore.closed.Load() != 1 {+ t.Fatalf("pending store closed %d times", pendingStore.closed.Load())+ }+ if err := h.CloseStores(); err != nil {+ t.Fatal(err)+ }+ if store.closed.Load() != 1 {+ t.Fatalf("original store closed %d times", store.closed.Load())+ }+ })+ }+}++func TestStoreConstructionFailureCanRetry(t *testing.T) {+ h := NewQueryService(nil)+ failure := errors.New("synthetic constructor failure")+ calls := 0+ h.openStore = func(_, _ string) (unified.ResourceStore, error) {+ calls+++ if calls == 1 {+ return nil, failure+ }+ return &coordinationStore{}, nil+ }+ if _, err := h.getStore("retry"); !errors.Is(err, failure) {+ t.Fatalf("got %v", err)+ }+ if _, err := h.getStore("retry"); err != nil {+ t.Fatal(err)+ }+ if calls != 2 {+ t.Fatalf("calls=%d", calls)+ }+ if err := h.CloseStores(); err != nil {+ t.Fatal(err)+ }+}