Cover concurrent settings writes and unrelated monitor visits

Exercise the actual settings handler with concurrent partial saves while an independent operator-state-style iterator runs and another tenant remains admitted but unpublished. Check final persisted intent, runtime cadence, public URL and revoked private grants across live, admitted and later tenants.

Contract-Neutral: Regression evidence for existing coherent instance settings and tenant isolation; no contract or public surface changes.
Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-04 15:42:40 +00:00
parent 6f8ea19a47
commit 85f3ccc62c

View File

@@ -2,6 +2,7 @@ package api
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
@@ -214,3 +215,146 @@ func TestTenantInitializationSettingsSaveReachesAdmittedMonitor(t *testing.T) {
t.Fatalf("saved settings not preserved: %+v", persisted)
}
}
// An operator-state visitor is independent of settings saves. It must not read
// the mutable base config while the real handler writes it, or turn a partial
// update into an admitted tenant's runtime snapshot. Concurrent partial saves
// must also preserve each other's saved fields.
func TestTenantInitializationConcurrentSettingsPublication(t *testing.T) {
dir := t.TempDir()
mtp := config.NewMultiTenantPersistence(dir)
persistence, err := mtp.GetPersistence("default")
if err != nil {
t.Fatal(err)
}
for _, id := range []string{"live", "starting", "later"} {
if err := mtp.SaveOrganization(&models.Organization{ID: id, DisplayName: id}); err != nil {
t.Fatal(err)
}
}
initial := config.DefaultSystemSettings()
initial.WebhookAllowedPrivateCIDRs = "192.0.2.0/24"
initial.PublicURL = "https://old.pulse.invalid"
if err := persistence.SaveSystemSettings(*initial); err != nil {
t.Fatal(err)
}
const token = "concurrent-settings-test-token"
cfg := &config.Config{DataPath: dir, ConfigPath: dir,
PublicURL: initial.PublicURL, PBSPollingInterval: time.Minute, PMGPollingInterval: time.Minute,
APITokens: []config.APITokenRecord{{ID: "concurrent-test", Hash: auth.HashAPIToken(token)}},
}
manager := monitoring.NewMultiTenantMonitor(cfg, mtp, nil)
t.Cleanup(manager.Stop)
live, err := manager.GetMonitor("live")
if err != nil {
t.Fatal(err)
}
entered, release, initialized := make(chan struct{}), make(chan struct{}), make(chan struct{})
var releaseOnce sync.Once
manager.SetMonitorInitializer(func(m *monitoring.Monitor) {
if m.GetOrgID() == "starting" {
close(entered)
<-release
}
})
var starting *monitoring.Monitor
var initErr error
go func() { starting, initErr = manager.GetMonitor("starting"); close(initialized) }()
t.Cleanup(func() { releaseOnce.Do(func() { close(release) }); <-initialized })
select {
case <-entered:
case <-time.After(10 * time.Second):
t.Fatal("constructor did not reach held phase")
}
handler := NewSystemSettingsHandler(cfg, persistence, nil, manager, live, nil, nil)
save := func(body string) {
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(body))
req.Header.Set("X-API-Token", token)
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "live"))
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("save = %d %s", rec.Code, rec.Body.String())
}
}
// Start an unrelated synchronous iterator first, and keep it active until
// every actual config mutation completes. It never reads config itself.
stopVisits, visitsDone, visitsStarted := make(chan struct{}), make(chan struct{}), make(chan struct{})
go func() {
defer close(visitsDone)
close(visitsStarted)
for {
select {
case <-stopVisits:
return
default:
}
manager.ForEachMonitor(func(m *monitoring.Monitor) {
if m != live {
t.Error("unrelated visitor observed an unfinished monitor")
}
})
}
}()
<-visitsStarted
var writers sync.WaitGroup
writers.Add(2)
go func() {
defer writers.Done()
for i := 0; i < 16; i++ {
save(fmt.Sprintf(`{"pbsPollingInterval":%d,"publicURL":"https://saved-%d.pulse.invalid"}`, 300+i, i))
}
}()
go func() {
defer writers.Done()
for i := 0; i < 16; i++ {
save(fmt.Sprintf(`{"pmgPollingInterval":%d,"backupPollingInterval":%d,"backupPollingEnabled":true,"webhookAllowedPrivateCIDRs":""}`, 420+i, 600+i))
}
}()
writersDone := make(chan struct{})
go func() { writers.Wait(); close(writersDone) }()
select {
case <-writersDone:
case <-time.After(20 * time.Second):
// Joining still matters on failure; releasing the fixture breaks an old
// constructor wait but does not excuse a blocked settings handler.
releaseOnce.Do(func() { close(release) })
t.Error("settings saves waited for a held constructor")
<-writersDone
}
close(stopVisits)
<-visitsDone
persisted, err := persistence.LoadSystemSettings()
if err != nil {
t.Fatal(err)
}
if persisted.PBSPollingInterval != 315 || persisted.PMGPollingInterval != 435 ||
persisted.BackupPollingInterval != 615 || persisted.PublicURL != "https://saved-15.pulse.invalid" ||
persisted.WebhookAllowedPrivateCIDRs != "" {
t.Errorf("concurrent partial saves lost committed intent: %+v", persisted)
}
releaseOnce.Do(func() { close(release) })
<-initialized
if initErr != nil {
t.Fatal(initErr)
}
later, err := manager.GetMonitor("later")
if err != nil {
t.Fatal(err)
}
for _, m := range []*monitoring.Monitor{live, starting, later} {
if got := m.BasePollInterval(monitoring.InstanceTypePBS); got != 315*time.Second {
t.Errorf("%s: PBS = %v, want 315s", m.GetOrgID(), got)
}
if got := m.BasePollInterval(monitoring.InstanceTypePMG); got != 435*time.Second {
t.Errorf("%s: PMG = %v, want 435s", m.GetOrgID(), got)
}
if got := m.GetNotificationManager().GetPublicURL(); got != "https://saved-15.pulse.invalid" {
t.Errorf("%s: public URL = %q", m.GetOrgID(), got)
}
if m.GetNotificationManager().ValidateWebhookURL("https://192.0.2.10/hook") == nil {
t.Errorf("%s: revoked grant survived settings publication", m.GetOrgID())
}
}
t.Log("CONCURRENT_SETTINGS: 32 actual partial saves, independent visitor, live/starting/later runtime and persisted readback")
}