diff --git a/packages/cli/observability/watch.go b/packages/cli/observability/watch.go index 7aa22bc1..6ba78c18 100644 --- a/packages/cli/observability/watch.go +++ b/packages/cli/observability/watch.go @@ -53,6 +53,26 @@ func watchUsage() string { }) } +func newCloudEntries(seen map[string]bool, entries []client.AuditEntry) (fresh []client.AuditEntry, next map[string]bool) { + for _, e := range entries { + if seen[e.ID] { + continue + } + seen[e.ID] = true + fresh = append(fresh, e) + } + if len(seen) <= seenLimit { + return fresh, seen + } + + // The API returns the newest entries, so older IDs cannot re-enter the next window. + next = make(map[string]bool, len(entries)) + for _, e := range entries { + next[e.ID] = true + } + return fresh, next +} + func RunWatch(ctx context.Context, c *client.Client, p cliutil.ParsedArgs) (int, error) { // Anything RunWatch does not refuse here starts a loop that only Ctrl+C // ends, so a request for help, or a mistyped argument, must not reach it. @@ -132,15 +152,10 @@ func RunWatch(ctx context.Context, c *client.Client, p cliutil.ParsedArgs) (int, return } - if len(seen) > seenLimit { - seen = map[string]bool{} - } + entries, nextSeen := newCloudEntries(seen, res.Entries) + seen = nextSeen var rows []watchRow - for _, e := range res.Entries { - if seen[e.ID] { - continue - } - seen[e.ID] = true + for _, e := range entries { at, _ := parseTimestamp(e.CreatedAt) rows = append(rows, watchRow{ At: at, diff --git a/packages/cli/observability/watch_test.go b/packages/cli/observability/watch_test.go index 46340048..895616a6 100644 --- a/packages/cli/observability/watch_test.go +++ b/packages/cli/observability/watch_test.go @@ -35,6 +35,25 @@ func TestPrintWatchRowJSON(t *testing.T) { } } +func TestNewCloudEntriesShrinksAfterDedup(t *testing.T) { + seen := make(map[string]bool, seenLimit+1) + for i := 0; i <= seenLimit; i++ { + seen["old-"+strconv.Itoa(i)] = true + } + entries := []client.AuditEntry{{ID: "old-1"}, {ID: "new"}, {ID: "old-2"}} + + fresh, next := newCloudEntries(seen, entries) + if len(fresh) != 1 { + t.Fatalf("len(fresh) = %d, want 1", len(fresh)) + } + if fresh[0].ID != "new" { + t.Errorf("fresh[0].ID = %q, want new", fresh[0].ID) + } + if len(next) != 3 || !next["old-1"] || !next["new"] || !next["old-2"] { + t.Errorf("next = %v, want exactly the three batch IDs", next) + } +} + func TestPrintWatchRowText(t *testing.T) { cases := []struct { name string