| index ac95a3f01..05922b66d 100644 |
| --- a/internal/host/telemetry_pass_test.go |
| +++ b/internal/host/telemetry_pass_test.go |
| @@ -10,6 +10,7 @@ import ( |
| "path/filepath" |
| "slices" |
| "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| |
| @@ -43,127 +44,234 @@ type telemetryObservations struct{ obs []analytics.Obs } |
| |
| func (m *telemetryObservations) Observe(ob analytics.Obs) { m.obs = append(m.obs, ob) } |
| |
| -func TestTelemetryPassRecordOnlyRejectsOlderPublication(t *testing.T) { |
| +func TestTelemetryPassRecordOnlySerializesReadAndPublication(t *testing.T) { |
| for _, armed := range []bool{false, true} { |
| name := "disarmed" |
| if armed { |
| - name = "rearmed" |
| + name = "armed" |
| } |
| - t.Run(name, func(t *testing.T) { |
| - t.Setenv("CARLOS_EDGE_PROTECT", "block") |
| - ctx, cancel := context.WithCancel(context.Background()) |
| - defer cancel() |
| - s := newCICountingStore(t) |
| - reg := edgesTestRegistry(t) |
| - if err := reg.Upsert(registry.Route{ |
| - Host: "shop.example.com", Kind: "static", Account: "bab", App: "shop", Status: "ready", |
| - }); err != nil { |
| - t.Fatal(err) |
| + for _, beforeRead := range []bool{true, false} { |
| + phase := "after_read" |
| + if beforeRead { |
| + phase = "before_read" |
| } |
| - e, err := edge.New(reg, nil) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - root := t.TempDir() |
| - if err := os.MkdirAll(filepath.Join(root, "shop", "current"), 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - edge.WithLocalStatic(root)(e) |
| - if err := e.Reload(); err != nil { |
| - t.Fatal(err) |
| - } |
| - meter := &telemetryObservations{} |
| - e.EnableAnalytics(meter) |
| - prevA, prevP, prevO := analyticsSink.Load(), protectionSink.Load(), assetOwnersSource.Load() |
| - prevW := armedChangeWatch.Load() |
| - t.Cleanup(func() { |
| - analyticsSink.Store(prevA) |
| - protectionSink.Store(prevP) |
| - assetOwnersSource.Store(prevO) |
| - armedChangeWatch.Store(prevW) |
| - recordOnlyLast.reset() |
| + t.Run(name+"/"+phase, func(t *testing.T) { |
| + testTelemetryPassRecordOnlySerialized(t, armed, beforeRead) |
| }) |
| - recordOnlyLast.reset() |
| - setAnalyticsSink(e.SetAnalyticsOn) |
| - setProtectionSink(e.SetProtectionRecordOnly) |
| - setAssetOwnersSource(func() []registry.Route { |
| - return []registry.Route{{Account: "bdk", App: "cart"}} |
| - }) |
| - armedChangeWatch.Store(nil) |
| - if armed { |
| - armedChangeWatch.Store(release.NewChangeWatch(s)) |
| - } |
| - setOn := func(on bool) { |
| - t.Helper() |
| - if err := telemetry.Update(ctx, s, telemetry.AppKey("bab", "shop"), func(st *telemetry.Settings) { |
| - st.Analytics = &telemetry.Analytics{Count: telemetry.CountOff} |
| - st.Protection = nil |
| - if on { |
| - st.Analytics.Count = telemetry.CountEdge |
| - st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly} |
| - } |
| - }); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - setOn(false) |
| - // The far asset read follows shop's read, so the older pass holds |
| - // shop's off values while the newer pass reads and publishes on. |
| - blocked := &telemetryBlockingStore{ |
| - Store: s, key: telemetry.AppKey("bdk", "cart"), |
| - entered: make(chan struct{}), resume: make(chan struct{}), |
| - } |
| - done := make(chan struct{}) |
| - go func() { |
| - defer close(done) |
| - telemetryPass(ctx, blocked, reg) |
| - }() |
| - defer func() { |
| - cancel() |
| - <-done |
| - }() |
| - <-blocked.entered |
| - setOn(true) |
| - if armed { |
| - // Replacing the watch gives the newer pass its own reader; |
| - // publication ordering must outlive either reader's mutex. |
| - armedChangeWatch.Store(release.NewChangeWatch(s)) |
| - } |
| - telemetryPass(ctx, s, reg) |
| - assertOn := func() { |
| - t.Helper() |
| - w := httptest.NewRecorder() |
| - r := httptest.NewRequest("GET", "http://shop.example.com/.env", nil) |
| - n := len(meter.obs) |
| - e.ServeHTTP(w, r) |
| - if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" { |
| - t.Errorf("record-only request = %d %q, want static 404 without a protection reference", w.Code, w.Body.String()) |
| - } |
| - if len(meter.obs) != n+1 { |
| - t.Errorf("analytics observations = %d, want %d", len(meter.obs), n+1) |
| - } |
| - recordOnlyLast.mu.Lock() |
| - remembered := recordOnlyLast.m["bab/shop"] |
| - recordOnlyLast.mu.Unlock() |
| - if !remembered { |
| - t.Error("remembered record-only value is off, want on") |
| - } |
| + } |
| + } |
| +} |
| + |
| +func testTelemetryPassRecordOnlySerialized(t *testing.T, armed, beforeRead bool) { |
| + t.Setenv("CARLOS_EDGE_PROTECT", "block") |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + s := newCICountingStore(t) |
| + reg := edgesTestRegistry(t) |
| + if err := reg.Upsert(registry.Route{ |
| + Host: "shop.example.com", Kind: "static", Account: "bab", App: "shop", Status: "ready", |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := edge.New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + root := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(root, "shop", "current"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + edge.WithLocalStatic(root)(e) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + meter := &telemetryObservations{} |
| + e.EnableAnalytics(meter) |
| + prevA, prevP, prevO := analyticsSink.Load(), protectionSink.Load(), assetOwnersSource.Load() |
| + prevW := armedChangeWatch.Load() |
| + t.Cleanup(func() { |
| + analyticsSink.Store(prevA) |
| + protectionSink.Store(prevP) |
| + assetOwnersSource.Store(prevO) |
| + armedChangeWatch.Store(prevW) |
| + recordOnlyLast.reset() |
| + }) |
| + recordOnlyLast.reset() |
| + armedChangeWatch.Store(nil) |
| + if armed { |
| + armedChangeWatch.Store(release.NewChangeWatch(s)) |
| + } |
| + setOn := func(on bool) { |
| + t.Helper() |
| + if err := telemetry.Update(ctx, s, telemetry.AppKey("bab", "shop"), func(st *telemetry.Settings) { |
| + st.Analytics = &telemetry.Analytics{Count: telemetry.CountOff} |
| + st.Protection = nil |
| + if on { |
| + st.Analytics.Count = telemetry.CountEdge |
| + st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly} |
| } |
| - assertOn() |
| - close(blocked.resume) |
| - <-done |
| - assertOn() |
| - // A failed read must reuse the newer remembered value too. |
| - armedChangeWatch.Store(nil) |
| - failed := &keysFailingStore{ciCountingStore: s} |
| - failed.failing(telemetry.AppKey("bab", "shop")) |
| - telemetryPass(ctx, failed, reg) |
| - w := httptest.NewRecorder() |
| - e.ServeHTTP(w, httptest.NewRequest("GET", "http://shop.example.com/.env", nil)) |
| - if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" { |
| - t.Errorf("failed read undid record-only: %d %q", w.Code, w.Body.String()) |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + setOn(beforeRead) |
| + |
| + paused, resume := make(chan struct{}), make(chan struct{}) |
| + published, finishPublish := make(chan struct{}), make(chan struct{}) |
| + releaseRead := sync.OnceFunc(func() { close(resume) }) |
| + releasePublish := sync.OnceFunc(func() { close(finishPublish) }) |
| + var workers sync.WaitGroup |
| + t.Cleanup(func() { |
| + cancel() |
| + releaseRead() |
| + releasePublish() |
| + workers.Wait() |
| + }) |
| + await := func(ch <-chan struct{}) { |
| + t.Helper() |
| + select { |
| + case <-ch: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("telemetry pass did not reach the handshake") |
| + } |
| + } |
| + assertLocked := func() { |
| + t.Helper() |
| + // This pins exclusion without depending on whether the waiting |
| + // goroutine has been scheduled yet. |
| + if telemetryPassMu.TryLock() { |
| + telemetryPassMu.Unlock() |
| + t.Error("telemetry pass mutex is not held through read and publication") |
| + } |
| + } |
| + type event struct { |
| + stage string |
| + on bool |
| + } |
| + events := make(chan event, 12) |
| + var ownerCalls, protectionCalls atomic.Int32 |
| + secondEntered := make(chan struct{}) |
| + setAssetOwnersSource(func() []registry.Route { |
| + assertLocked() |
| + events <- event{stage: "owners"} |
| + if ownerCalls.Add(1) == 1 { |
| + if beforeRead { |
| + close(paused) |
| + <-resume |
| } |
| - }) |
| + } else { |
| + close(secondEntered) |
| + } |
| + return []registry.Route{{Account: "bdk", App: "cart"}} |
| + }) |
| + setAnalyticsSink(func(m map[string]bool) { |
| + assertLocked() |
| + e.SetAnalyticsOn(m) |
| + events <- event{"analytics", m["bab/shop"]} |
| + }) |
| + setProtectionSink(func(m map[string]bool) { |
| + assertLocked() |
| + e.SetProtectionRecordOnly(m) |
| + events <- event{"record-only", m["bab/shop"]} |
| + if protectionCalls.Add(1) == 1 { |
| + close(published) |
| + <-finishPublish |
| + assertLocked() |
| + } |
| + }) |
| + var firstStore release.Store = s |
| + if !beforeRead { |
| + // The far asset read follows shop's read, so the first pass has |
| + // already read off while its publication is held back. |
| + firstStore = &telemetryBlockingStore{ |
| + Store: s, key: telemetry.AppKey("bdk", "cart"), entered: paused, resume: resume, |
| + } |
| + } |
| + firstDone, secondDone := make(chan struct{}), make(chan struct{}) |
| + workers.Add(1) |
| + go func() { |
| + defer workers.Done() |
| + defer close(firstDone) |
| + telemetryPass(ctx, firstStore, reg) |
| + }() |
| + await(paused) |
| + assertLocked() |
| + secondStarted := make(chan struct{}) |
| + workers.Add(1) |
| + go func() { |
| + defer workers.Done() |
| + defer close(secondDone) |
| + assertLocked() |
| + close(secondStarted) |
| + telemetryPass(ctx, s, reg) |
| + }() |
| + await(secondStarted) |
| + if beforeRead { |
| + // A started first but has not read yet; B has started too. A must |
| + // read and publish before B can enter the owners hook. |
| + setOn(false) |
| + } else { |
| + setOn(true) |
| + } |
| + releaseRead() |
| + await(published) |
| + assertLocked() |
| + select { |
| + case <-secondEntered: |
| + t.Error("second pass entered before the first finished publishing") |
| + default: |
| + } |
| + recordOnlyLast.mu.Lock() |
| + firstRemembered := recordOnlyLast.m["bab/shop"] |
| + recordOnlyLast.mu.Unlock() |
| + if firstRemembered { |
| + t.Error("first pass remembered on, want the off value it read") |
| + } |
| + setOn(true) |
| + if armed { |
| + // A new reader must still obey the process-wide pass lock. |
| + armedChangeWatch.Store(release.NewChangeWatch(s)) |
| + } |
| + releasePublish() |
| + await(firstDone) |
| + await(secondDone) |
| + var got []event |
| + for len(events) > 0 { |
| + got = append(got, <-events) |
| + } |
| + want := []event{ |
| + {stage: "owners"}, {"analytics", false}, {"record-only", false}, |
| + {stage: "owners"}, {"analytics", true}, {"record-only", true}, |
| + } |
| + if !slices.Equal(got, want) { |
| + t.Errorf("pass order and values = %v, want %v", got, want) |
| + } |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, httptest.NewRequest("GET", "http://shop.example.com/.env", nil)) |
| + if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" { |
| + t.Errorf("record-only request = %d %q, want static 404 without a protection reference", w.Code, w.Body.String()) |
| + } |
| + if len(meter.obs) != 1 { |
| + t.Errorf("analytics observations = %d, want 1", len(meter.obs)) |
| + } |
| + recordOnlyLast.mu.Lock() |
| + remembered := recordOnlyLast.m["bab/shop"] |
| + recordOnlyLast.mu.Unlock() |
| + if !remembered { |
| + t.Error("remembered record-only value is off, want the latest read's on value") |
| + } |
| + // A failed read must reuse the newer remembered value too. |
| + assetOwnersSource.Store(nil) |
| + setAnalyticsSink(e.SetAnalyticsOn) |
| + setProtectionSink(e.SetProtectionRecordOnly) |
| + armedChangeWatch.Store(nil) |
| + failed := &keysFailingStore{ciCountingStore: s} |
| + failed.failing(telemetry.AppKey("bab", "shop")) |
| + telemetryPass(ctx, failed, reg) |
| + w = httptest.NewRecorder() |
| + e.ServeHTTP(w, httptest.NewRequest("GET", "http://shop.example.com/.env", nil)) |
| + if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" { |
| + t.Errorf("failed read undid record-only: %d %q", w.Code, w.Body.String()) |
| } |
| } |
| |