package main import ( "context" "encoding/base64" "encoding/json" "errors" "net/http" "regexp" "strconv" "strings" "sync/atomic" "testing" "time" "github.com/modelcontextprotocol/go-sdk/jsonrpc" ) func githubHeadFixture(head, rollup string, updated time.Time) map[string]any { return map[string]any{"pullRequest": map[string]any{ "title": "Fix widgets", "url": "https://github.com/acme/widgets/pull/42", "state": "OPEN", "updatedAt": updated, "headRefOid": head, "commits": map[string]any{"nodes": []any{map[string]any{"commit": map[string]any{"statusCheckRollup": map[string]string{"state": rollup}}}}}, }} } func githubItems(count int) []any { items := make([]any, count) for i := range items { item := githubSearchItem() item["number"] = i + 1 items[i] = item } return items } func githubTimelineFixture(number int) []any { return []any{map[string]any{"id": number, "event": "commented", "created_at": githubTestTime, "user": map[string]string{"login": "erin"}, "body": "completed"}} } func TestGitHubBudgetPartialContinuationRestart(t *testing.T) { var search, fast, slow atomic.Int32 retry := atomic.Bool{} handler := func(w http.ResponseWriter, r *http.Request) { switch { case r.URL.Path == "/search/issues": search.Add(1) githubJSON(t, w, map[string]any{"total_count": 3, "items": githubItems(3)}) case strings.HasSuffix(r.URL.Path, "/timeline"): number, _ := strconv.Atoi(strings.Split(r.URL.Path, "/")[5]) if number == 2 && !retry.Load() { slow.Add(1) <-r.Context().Done() return } fast.Add(1) githubJSON(t, w, githubTimelineFixture(number)) default: githubJSON(t, w, githubPullFixture()) } } g, server := testGitHub(t, handler) g.pollTimeout = 100 * time.Millisecond args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"comment"}} since := githubTestTime.Add(-time.Minute) started := time.Now() page, err := g.FetchPage(context.Background(), activityName, args, since, "") if err != nil || !page.Complete || page.Truncated || len(page.Events) != 2 || page.Continuation == "" || !page.CheckedTo.Equal(githubTestTime) { t.Fatalf("page=%+v err=%v", page, err) } if elapsed := time.Since(started); elapsed > time.Second { t.Fatalf("budget not bounded: %v", elapsed) } c, err := githubResume(page.Continuation, subscriptionKey(activityName, args), since, githubTestTime) if err != nil || len(c.Pending) != 1 || c.Pending[0].Number != 2 { t.Fatalf("pending=%+v err=%v", c, err) } // A fresh Source has no token/cache/known state from the prior page. retry.Store(true) fresh := &GitHub{client: server.Client(), baseURL: server.URL, token: "private-token", login: "erin", now: func() time.Time { return githubTestTime.Add(time.Minute) }} last, err := fresh.FetchPage(context.Background(), activityName, args, since, page.Continuation) if err != nil || !last.Complete || last.Continuation != "" || len(last.Events) != 1 || !last.CheckedTo.Equal(githubTestTime) { t.Fatalf("last=%+v err=%v", last, err) } if search.Load() != 1 || fast.Load() != 3 || slow.Load() != 1 { t.Fatalf("search=%d fast=%d slow=%d", search.Load(), fast.Load(), slow.Load()) } for _, earlier := range page.Events { if earlier.EventID == last.Events[0].EventID { t.Error("reprocessed completed PR") } } } func TestGitHubBoundedConcurrencyAndChangedOnly(t *testing.T) { var active, peak, timelines atomic.Int32 g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/search/issues" { githubJSON(t, w, map[string]any{"total_count": 12, "items": githubItems(12)}) return } n := active.Add(1) defer active.Add(-1) for { old := peak.Load() if n <= old || peak.CompareAndSwap(old, n) { break } } select { case <-time.After(10 * time.Millisecond): case <-r.Context().Done(): return } if strings.HasSuffix(r.URL.Path, "/timeline") { timelines.Add(1) number, _ := strconv.Atoi(strings.Split(r.URL.Path, "/")[5]) githubJSON(t, w, githubTimelineFixture(number)) } else { githubJSON(t, w, githubPullFixture()) } }) args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"comment"}} page, err := g.Fetch(context.Background(), activityName, args, githubTestTime.Add(-time.Minute)) if err != nil || len(page.Events) != 12 || timelines.Load() != 12 || peak.Load() > githubWorkers || peak.Load() < 2 { t.Fatalf("events=%d err=%v timelines=%d peak=%d", len(page.Events), err, timelines.Load(), peak.Load()) } } func TestGitHubNoProgressFailsAndSearchFailureDoesNotPage(t *testing.T) { for _, phase := range []string{"search", "pull"} { t.Run(phase, func(t *testing.T) { g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if phase == "search" || r.URL.Path != "/search/issues" { w.WriteHeader(503) return } githubJSON(t, w, map[string]any{"total_count": 1, "items": []any{githubSearchItem()}}) }) page, err := g.Fetch(context.Background(), activityName, Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"review"}}, githubTestTime) if err == nil || page.Complete || len(page.Events) != 0 || page.Continuation != "" { t.Fatalf("page=%+v err=%v", page, err) } }) } } func TestGitHubContinuationValidation(t *testing.T) { args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"comment"}} key := subscriptionKey(activityName, args) c := githubContinuation{Version: 1, Scope: key, Since: githubTestTime.Add(-time.Minute), Cutoff: githubTestTime, Pending: []githubPending{{Repo: "acme/widgets", Number: 1}}} encoded, err := githubPause(c) if err != nil { t.Fatal(err) } mutations := []string{"garbage", strings.Repeat("a", githubContinuationLimit+1), base64.RawURLEncoding.EncodeToString([]byte(`{"v":1,"extra":true}`))} for _, mutation := range mutations { if _, err := githubResume(mutation, key, c.Since, githubTestTime); err == nil { t.Error("accepted invalid continuation") } } for _, mutate := range []func(*githubContinuation){ func(c *githubContinuation) { c.Version = 2 }, func(c *githubContinuation) { c.Scope = "another" }, func(c *githubContinuation) { c.Since = c.Since.Add(2 * time.Minute) }, func(c *githubContinuation) { c.Cutoff = githubTestTime.Add(time.Second) }, func(c *githubContinuation) { c.Pending[0].Repo = "evil/../../repos" }, func(c *githubContinuation) { c.Pending[0].Number = 0 }, func(c *githubContinuation) { c.Pending[0].Rollup = "unknown" }, func(c *githubContinuation) { c.Pending = append(c.Pending, c.Pending[0]) }, } { copy := c copy.Pending = append([]githubPending(nil), c.Pending...) mutate(©) bad, _ := githubPause(copy) if _, err := githubResume(bad, key, c.Since, githubTestTime); err == nil { t.Errorf("accepted %+v", copy) } } if _, err := githubResume(encoded, key, c.Since, githubTestTime); err != nil { t.Fatal(err) } g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { t.Error("invalid continuation made request") }) _, err = g.FetchPage(context.Background(), activityName, Arguments{Repos: []string{"other/repo"}}, c.Since, encoded) if err == nil { t.Error("scope mismatch accepted") } } func TestGitHubRequestBudgetKeepsCompletedPulls(t *testing.T) { g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/search/issues" { githubJSON(t, w, map[string]any{"total_count": 16, "items": githubItems(16)}) return } parts := strings.Split(r.URL.Path, "/") number, _ := strconv.Atoi(parts[5]) if strings.HasSuffix(r.URL.Path, "/timeline") || strings.HasSuffix(r.URL.Path, "/comments") { if number != 1 { w.Header().Set("Link", "<"+"http://"+r.Host+r.URL.RequestURI()+">; rel=\"next\"") } if strings.HasSuffix(r.URL.Path, "/timeline") { githubJSON(t, w, githubTimelineFixture(number)) } else { githubJSON(t, w, []any{}) } } else { githubJSON(t, w, githubPullFixture()) } }) args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"comment", "review_comment"}} since := githubTestTime.Add(-time.Minute) page, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || !page.Complete || page.Continuation == "" || len(page.Events) == 0 || g.requests != githubRequestLimit { t.Fatalf("events=%d complete=%v cont=%v requests=%d err=%v", len(page.Events), page.Complete, page.Continuation != "", g.requests, err) } pending, err := githubResume(page.Continuation, subscriptionKey(activityName, args), since, githubTestTime) if err != nil { t.Fatal(err) } for _, candidate := range pending.Pending { if candidate.Number == 1 { t.Error("finished PR retained") } } for _, event := range page.Events { var activity githubActivity if err := json.Unmarshal(event.Data, &activity); err != nil { t.Fatal(err) } for _, candidate := range pending.Pending { if candidate.Number == activity.Number { t.Error("partial PR leaked events") } } } } func TestGitHubNarrowedContinuationKeepsOriginalSnapshot(t *testing.T) { args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"comment"}} oldSince := githubTestTime.Add(-time.Minute) c := githubContinuation{Version: 1, Scope: subscriptionKey(activityName, args), Since: oldSince, Cutoff: githubTestTime, Pending: []githubPending{{Repo: "acme/widgets", Number: 1}}} encoded, err := githubPause(c) if err != nil { t.Fatal(err) } g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, "/timeline") { githubJSON(t, w, githubTimelineFixture(1)) } else { githubJSON(t, w, githubPullFixture()) } }) page, err := g.FetchPage(context.Background(), activityName, args, githubTestTime.Add(time.Minute), encoded) if err != nil || !page.Complete || len(page.Events) != 0 || page.Continuation != "" || !page.CheckedTo.Equal(c.Cutoff) { t.Fatalf("page=%+v err=%v", page, err) } if _, err := githubResume(encoded, c.Scope, oldSince.Add(-time.Second), githubTestTime); err == nil { t.Error("allowed widened resume to claim unsearched range") } } func TestGitHubQuietHeadBaselineAndPushReset(t *testing.T) { state, head := "SUCCESS", "abcdef" g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/search/issues": if strings.Contains(r.URL.Query().Get("q"), "is:open") { githubJSON(t, w, map[string]any{"total_count": 1, "items": []any{githubSearchItem()}}) } else { githubJSON(t, w, map[string]any{"total_count": 0, "items": []any{}}) } case "/graphql": githubJSON(t, w, map[string]any{"data": map[string]any{"p0": githubHeadFixture(head, state, githubTestTime.Add(-time.Hour))}}) default: t.Errorf("quiet head scanned deeply: %s", r.URL) } }) var ticks atomic.Int64 g.now = func() time.Time { return githubTestTime.Add(time.Duration(ticks.Add(1)) * time.Millisecond) } args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"check_suite"}} since := githubTestTime.Add(-time.Minute) fetch := func(want int) FetchResult { t.Helper() page, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || len(page.Events) != want { t.Fatalf("events=%d want=%d err=%v", len(page.Events), want, err) } return page } fetch(0) // Already terminal unknown head is a baseline, not historical completion. head = "111111" fetch(0) // A new head resets that baseline even if already terminal. state = "PENDING" fetch(0) state = "FAILURE" page := fetch(1) if !page.Events[0].Timestamp.After(page.CheckedTo) { t.Error("CI observation timestamp should not pretend to be the earlier search cutoff") } if page.Events[0].EventID != stableID(activityName, "acme/widgets", "42", "check_suite", head, state) { t.Error("unstable CI identity") } fetch(0) } func TestGitHubWaitingFetchHonorsContext(t *testing.T) { entered, release := make(chan struct{}), make(chan struct{}) g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { close(entered); <-release; githubJSON(t, w, []any{}) }) finished := make(chan error, 1) go func() { _, err := g.Fetch(context.Background(), notificationsName, Arguments{}, githubTestTime) finished <- err }() <-entered ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() started := time.Now() page, err := g.Fetch(ctx, notificationsName, Arguments{}, githubTestTime) close(release) if firstErr := <-finished; firstErr != nil { t.Fatal(firstErr) } if !errors.Is(err, context.DeadlineExceeded) || page.Complete || time.Since(started) > time.Second { t.Fatalf("page=%+v err=%v elapsed=%v", page, err, time.Since(started)) } } func TestGitHubIncrementalLatencyAndRequestCost(t *testing.T) { var searches, timelines, requests atomic.Int32 aliasPattern := regexp.MustCompile(`p([0-9]+): repository\(.*?pullRequest\(number:([0-9]+)\)`) g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { requests.Add(1) select { case <-time.After(5 * time.Millisecond): case <-r.Context().Done(): return } switch { case r.URL.Path == "/search/issues": searches.Add(1) count := 4 if strings.Contains(r.URL.Query().Get("q"), "is:open") { count = 84 } githubJSON(t, w, map[string]any{"total_count": count, "items": githubItems(count)}) case r.URL.Path == "/graphql": var payload struct { Query string `json:"query"` } if json.NewDecoder(r.Body).Decode(&payload) != nil { t.Error("invalid GraphQL body") } data := make(map[string]any) for _, match := range aliasPattern.FindAllStringSubmatch(payload.Query, -1) { data["p"+match[1]] = githubHeadFixture("abcdef", "PENDING", githubTestTime.Add(-time.Hour)) } githubJSON(t, w, map[string]any{"data": data}) case strings.HasSuffix(r.URL.Path, "/timeline"): timelines.Add(1) githubJSON(t, w, []any{}) case strings.HasSuffix(r.URL.Path, "/comments"): githubJSON(t, w, []any{}) case strings.HasSuffix(r.URL.Path, "/check-suites"): githubJSON(t, w, map[string]any{"check_suites": []any{map[string]any{"status": "in_progress"}}}) default: githubJSON(t, w, githubPullFixture()) } }) var measured atomic.Int32 g.ObserveRequest = func(metric GitHubRequestMetric) { measured.Add(1) if metric.Duration <= 0 || strings.Contains(metric.Path, "private-token") || strings.Contains(metric.Path, "?") { t.Errorf("unsafe metric %+v", metric) } } args := Arguments{} since := githubTestTime.Add(-time.Minute) for _, label := range []string{"cold", "warm"} { before, deep := requests.Load(), timelines.Load() started := time.Now() page, err := g.Fetch(context.Background(), activityName, args, since) elapsed := time.Since(started) if err != nil || !page.Complete || page.Continuation != "" || timelines.Load()-deep != 4 { t.Fatalf("%s page=%+v err=%v deep=%d", label, page, err, timelines.Load()-deep) } want := int32(20) if label == "cold" { want = 22 } if requests.Load()-before != want { t.Fatalf("%s requests=%d want=%d", label, requests.Load()-before, want) } t.Logf("%s: 4 changed + 80 quiet PRs; %d requests, 4 timelines, %s wall time (5ms simulated per request)", label, requests.Load()-before, elapsed) } if searches.Load() != 8 || measured.Load() != requests.Load() { t.Fatalf("searches=%d metrics=%d requests=%d", searches.Load(), measured.Load(), requests.Load()) } } func TestGitHubCIReplayRestoresOldRollupAfterRestart(t *testing.T) { state := "PENDING" handler := func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/graphql" { githubJSON(t, w, map[string]any{"data": map[string]any{"p0": githubHeadFixture("abcdef", state, githubTestTime.Add(-time.Hour))}}) return } count := 0 if strings.Contains(r.URL.Query().Get("q"), "is:open") { count = 1 } githubJSON(t, w, map[string]any{"total_count": count, "items": githubItems(count)}) } g, server := testGitHub(t, handler) args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"check_suite"}} since := githubTestTime.Add(-time.Minute) if _, err := g.Fetch(context.Background(), activityName, args, since); err != nil { t.Fatal(err) } state = "SUCCESS" page, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || len(page.Events) != 1 || page.Replay == "" { t.Fatalf("page=%+v err=%v", page, err) } replay, err := githubResume(page.Replay, subscriptionKey(activityName, args), since, githubTestTime) if err != nil || replay.Pending[0].Head != "abcdef" || replay.Pending[0].Rollup != "PENDING" { t.Fatalf("replay=%+v err=%v", replay, err) } fresh := &GitHub{client: server.Client(), baseURL: server.URL, token: "private-token", login: "erin", now: func() time.Time { return githubTestTime }} rebuilt, err := fresh.FetchPage(context.Background(), activityName, args, since, page.Replay) if err != nil || len(rebuilt.Events) != 1 || rebuilt.Events[0].EventID != page.Events[0].EventID { t.Fatalf("rebuilt=%+v err=%v", rebuilt, err) } if fresh.known[subscriptionKey(activityName, args)].discovered { t.Error("resuming pending work suppressed restart CI bootstrap") } } func TestGitHubQuietBatchCeiling(t *testing.T) { var batches atomic.Int32 aliasPattern := regexp.MustCompile(`p([0-9]+): repository\(.*?pullRequest\(number:([0-9]+)\)`) g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/graphql" { batches.Add(1) var payload struct { Query string `json:"query"` } json.NewDecoder(r.Body).Decode(&payload) matches := aliasPattern.FindAllStringSubmatch(payload.Query, -1) if len(matches) > githubCIBatch { t.Errorf("unbounded CI batch: %d", len(matches)) } data := make(map[string]any) for _, match := range matches { data["p"+match[1]] = githubHeadFixture("abcdef", "PENDING", githubTestTime.Add(-time.Hour)) } githubJSON(t, w, map[string]any{"data": data}) return } count := 0 if strings.Contains(r.URL.Query().Get("q"), "is:open") { count = 101 } githubJSON(t, w, map[string]any{"total_count": count, "items": githubItems(count)}) }) args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"check_suite"}} since := githubTestTime.Add(-time.Minute) first, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || !first.Complete || first.Continuation == "" || first.Truncated { t.Fatalf("first=%+v err=%v", first, err) } last, err := g.FetchPage(context.Background(), activityName, args, since, first.Continuation) if err != nil || !last.Complete || last.Continuation != "" || last.Truncated || batches.Load() != 2 || len(g.known[subscriptionKey(activityName, args)].pulls) != 101 { t.Fatalf("last=%+v err=%v batches=%d", last, err, batches.Load()) } } func TestGitHubPerRequestTimeoutPreservesOtherPulls(t *testing.T) { g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/search/issues" { githubJSON(t, w, map[string]any{"total_count": 2, "items": githubItems(2)}) return } if strings.HasSuffix(r.URL.Path, "/issues/1/timeline") { <-r.Context().Done() return } if strings.HasSuffix(r.URL.Path, "/timeline") { githubJSON(t, w, githubTimelineFixture(2)) } else { githubJSON(t, w, githubPullFixture()) } }) g.pollTimeout = time.Second g.requestTimeout = 20 * time.Millisecond started := time.Now() page, err := g.Fetch(context.Background(), activityName, Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"comment"}}, githubTestTime.Add(-time.Minute)) if err != nil || !page.Complete || len(page.Events) != 1 || page.Continuation == "" || time.Since(started) > 500*time.Millisecond { t.Fatalf("page=%+v err=%v elapsed=%v", page, err, time.Since(started)) } } func TestGitHubTokenChangeClearsPrincipalScope(t *testing.T) { g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") == "Bearer private-token" { w.WriteHeader(401) return } switch r.URL.Path { case "/notifications": githubJSON(t, w, []any{}) case "/user": githubJSON(t, w, map[string]string{"login": "alex"}) case "/search/issues": if strings.Contains(r.URL.Query().Get("q"), "erin") { t.Error("old principal scope reused") } githubJSON(t, w, map[string]any{"total_count": 0, "items": []any{}}) default: t.Errorf("unexpected %s", r.URL) } }) g.tokenProvider = func(context.Context) (string, error) { return "replacement-token", nil } g.remember("old", map[string]githubCandidate{"old#1": {repo: "acme/widgets", number: 1}}) page, err := g.Fetch(context.Background(), notificationsName, Arguments{}, githubTestTime) if err != nil || !page.Complete || g.login != "" || len(g.known) != 0 { t.Fatalf("page=%+v err=%v login=%s scopes=%d", page, err, g.login, len(g.known)) } if _, err := g.Fetch(context.Background(), activityName, Arguments{Kinds: []string{"review"}}, githubTestTime); err != nil { t.Fatal(err) } if g.login != "alex" { t.Errorf("principal=%s", g.login) } } func TestGitHubClosureAfterCutoffRetainsReviewScopeBridge(t *testing.T) { clock := githubTestTime closedAt := githubTestTime.Add(30 * time.Second) firstWindow := true var timelines, batches atomic.Int32 g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/search/issues": count := 0 if firstWindow && strings.Contains(r.URL.Query().Get("q"), "review-requested:") { count = 1 } item := githubSearchItem() items := []any{} if count == 1 { items = append(items, item) } githubJSON(t, w, map[string]any{"total_count": count, "items": items}) case "/repos/acme/widgets/pulls/42": pull := githubPullFixture() pull["user"] = map[string]string{"login": "alex"} pull["state"], pull["merged_at"], pull["updated_at"] = "closed", closedAt, closedAt pull["requested_reviewers"] = []any{} githubJSON(t, w, pull) case "/repos/acme/widgets/issues/42/timeline": timelines.Add(1) githubJSON(t, w, []any{map[string]any{"id": 1, "event": "merged", "created_at": closedAt, "actor": map[string]string{"login": "alex"}}}) case "/graphql": batches.Add(1) repository := githubHeadFixture("abcdef", "SUCCESS", closedAt) repository["pullRequest"].(map[string]any)["state"] = "MERGED" githubJSON(t, w, map[string]any{"data": map[string]any{"p0": repository}}) default: t.Errorf("unexpected %s", r.URL) w.WriteHeader(404) } }) g.now = func() time.Time { return clock } args := Arguments{Kinds: []string{"merged"}} key := subscriptionKey(activityName, args) first, err := g.Fetch(context.Background(), activityName, args, githubTestTime.Add(-time.Minute)) if err != nil || !first.Complete || len(first.Events) != 0 || len(g.known[key].pulls) != 1 { t.Fatalf("first=%+v err=%v known=%+v", first, err, g.known[key]) } clock = githubTestTime.Add(time.Minute) firstWindow = false bridge, err := g.Fetch(context.Background(), activityName, args, githubTestTime) if err != nil || !bridge.Complete || bridge.Continuation == "" { t.Fatalf("bridge=%+v err=%v", bridge, err) } last, err := g.FetchPage(context.Background(), activityName, args, githubTestTime, bridge.Continuation) if err != nil || !last.Complete || len(last.Events) != 1 || !last.Events[0].Timestamp.Equal(closedAt) || len(g.known[key].pulls) != 0 { t.Fatalf("last=%+v err=%v known=%+v", last, err, g.known[key]) } if _, err := g.Fetch(context.Background(), activityName, args, clock); err != nil { t.Fatal(err) } if timelines.Load() != 2 || batches.Load() != 1 { t.Fatalf("closed PR remained a history stream: timelines=%d batch=%d", timelines.Load(), batches.Load()) } } func TestGitHubRememberPreservesDiscoveredAndHeadBaselines(t *testing.T) { g := &GitHub{now: func() time.Time { return githubTestTime }} candidate := githubCandidate{repo: "acme/widgets", number: 42, head: "abcdef", rollup: "PENDING"} if g.remember("scope", map[string]githubCandidate{candidate.key(): candidate}) { t.Fatal("initial scope refused") } scope := g.known["scope"] scope.discovered = true g.known["scope"] = scope if g.remember("scope", scope.pulls) { t.Fatal("refresh scope refused") } remembered := g.known["scope"] if !remembered.discovered || remembered.pulls[candidate.key()].head != candidate.head || remembered.pulls[candidate.key()].rollup != candidate.rollup { t.Fatalf("metadata reset: %+v", remembered) } } func TestGitHubColdRecentOwnReviewIsReviewOnly(t *testing.T) { var ownSearches, reviewReads atomic.Int32 g, server := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/search/issues": q := r.URL.Query().Get("q") count := 0 if strings.Contains(q, " reviewed-by:") { if strings.Contains(q, "is:open") { t.Error("reviewed-by included in open bootstrap") } ownSearches.Add(1) count = 1 } items := []any{} if count == 1 { items = append(items, githubSearchItem()) } githubJSON(t, w, map[string]any{"total_count": count, "items": items}) case "/repos/acme/widgets/pulls/42": pull := githubPullFixture() pull["user"] = map[string]string{"login": "alex"} pull["requested_reviewers"] = []any{} githubJSON(t, w, pull) case "/repos/acme/widgets/pulls/42/reviews": reviewReads.Add(1) githubJSON(t, w, []any{ map[string]any{"id": 123, "user": map[string]string{"login": "erin"}, "state": "APPROVED", "body": "own review", "submitted_at": githubTestTime}, map[string]any{"id": 124, "user": map[string]string{"login": "alex"}, "state": "APPROVED", "submitted_at": githubTestTime}, map[string]any{"id": 125, "user": map[string]string{"login": "erin"}, "state": "APPROVED", "submitted_at": githubTestTime.Add(-time.Hour)}, map[string]any{"id": 126, "user": map[string]string{"login": "erin"}, "state": "APPROVED", "submitted_at": githubTestTime.Add(time.Hour)}, }) default: t.Errorf("review-only bridge must not publish comments/CI or scan timelines: %s", r.URL) w.WriteHeader(404) } }) args := Arguments{} since := githubTestTime.Add(-time.Minute) for i := 0; i < 2; i++ { source := g if i == 1 { source = &GitHub{client: server.Client(), baseURL: server.URL, token: "private-token", login: "erin", now: func() time.Time { return githubTestTime }} } page, err := source.Fetch(context.Background(), activityName, args, since) if err != nil || !page.Complete || len(page.Events) != 1 || page.Events[0].EventID != stableID(activityName, "acme/widgets", "42", "review", "123") { t.Fatalf("page=%+v err=%v", page, err) } if len(source.known[subscriptionKey(activityName, args)].pulls) != 0 { t.Error("review-only PR became permanent CI/activity scope") } } if ownSearches.Load() != 2 || reviewReads.Load() != 2 { t.Fatalf("search=%d reviews=%d", ownSearches.Load(), reviewReads.Load()) } } func TestGitHubContinuationByteBoundMakesProgress(t *testing.T) { repo := "acme/" + strings.Repeat("r", 100) g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/search/issues" { items := githubItems(1000) for _, item := range items { item.(map[string]any)["repository_url"] = "https://api.github.com/repos/" + repo } githubJSON(t, w, map[string]any{"total_count": 1000, "items": items}) } else if strings.HasSuffix(r.URL.Path, "/timeline") { number, _ := strconv.Atoi(strings.Split(r.URL.Path, "/")[5]) githubJSON(t, w, githubTimelineFixture(number)) } else { githubJSON(t, w, githubPullFixture()) } }) args := Arguments{Repos: []string{repo}, Kinds: []string{"comment"}} since := githubTestTime.Add(-time.Minute) page, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || !page.Complete || !page.Truncated || len(page.Events) != githubPullBatch || page.Continuation == "" || len(page.Replay) > githubContinuationLimit || len(page.Continuation) > githubContinuationLimit { t.Fatalf("events=%d replay=%d cont=%d complete=%v gap=%v err=%v", len(page.Events), len(page.Replay), len(page.Continuation), page.Complete, page.Truncated, err) } c, err := githubResume(page.Replay, subscriptionKey(activityName, args), since, githubTestTime) if err != nil || len(c.Pending) == 0 || len(c.Pending) >= 1000 { t.Fatalf("pending=%d err=%v", len(c.Pending), err) } withHeads := c withHeads.Pending = append([]githubPending(nil), c.Pending...) for i := range withHeads.Pending { withHeads.Pending[i].Head = strings.Repeat("a", 128) withHeads.Pending[i].Rollup = "SUCCESS" } bounded, err := githubBoundPending(withHeads) if err != nil || len(bounded.Pending) >= len(c.Pending) || len(bounded.Pending) == 0 { t.Fatalf("head baseline bound=%d original=%d err=%v", len(bounded.Pending), len(c.Pending), err) } if encoded, err := githubPause(bounded); err != nil || len(encoded) > githubContinuationLimit { t.Fatalf("encoded=%d err=%v", len(encoded), err) } } func TestGitHubPostCutoffClosureDoesNotSkipOlderUnreadReview(t *testing.T) { clock := githubTestTime closedAt := githubTestTime.Add(time.Second) reviewAt := githubTestTime.Add(-3 * time.Minute) g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/search/issues": githubJSON(t, w, map[string]any{"total_count": 0, "items": []any{}}) case "/graphql": repository := githubHeadFixture("abcdef", "SUCCESS", closedAt) repository["pullRequest"].(map[string]any)["state"] = "CLOSED" githubJSON(t, w, map[string]any{"data": map[string]any{"p0": repository}}) case "/repos/acme/widgets/pulls/42": pull := githubPullFixture() pull["state"], pull["updated_at"] = "closed", closedAt githubJSON(t, w, pull) case "/repos/acme/widgets/issues/42/timeline": githubJSON(t, w, []any{ map[string]any{"id": 1, "event": "reviewed", "submitted_at": reviewAt, "state": "approved", "user": map[string]string{"login": "erin"}}, map[string]any{"id": 2, "event": "closed", "created_at": closedAt, "actor": map[string]string{"login": "alex"}}, }) default: t.Errorf("unexpected %s", r.URL) w.WriteHeader(404) } }) g.now = func() time.Time { return clock } args := Arguments{Kinds: []string{"closed", "review"}} key := subscriptionKey(activityName, args) known := githubCandidate{repo: "acme/widgets", number: 42, head: "abcdef"} g.remember(key, map[string]githubCandidate{known.key(): known}) oldSince := githubTestTime.Add(-5 * time.Minute) first, err := g.Fetch(context.Background(), activityName, args, oldSince) if err != nil || !first.Complete || first.Continuation == "" { t.Fatalf("older unread range prematurely completed: page=%+v err=%v", first, err) } oldRange, err := g.FetchPage(context.Background(), activityName, args, oldSince, first.Continuation) if err != nil || len(oldRange.Events) != 1 || !oldRange.Events[0].Timestamp.Equal(reviewAt) || oldRange.Continuation != "" || len(g.known[key].pulls) != 1 { t.Fatalf("oldRange=%+v err=%v known=%+v", oldRange, err, g.known[key]) } clock = githubTestTime.Add(time.Minute) nextSince := githubTestTime.Add(-2 * time.Minute) next, err := g.Fetch(context.Background(), activityName, args, nextSince) if err != nil || next.Continuation == "" { t.Fatalf("next=%+v err=%v", next, err) } closed, err := g.FetchPage(context.Background(), activityName, args, nextSince, next.Continuation) if err != nil || len(closed.Events) != 1 || !closed.Events[0].Timestamp.Equal(closedAt) || closed.Continuation != "" || len(g.known[key].pulls) != 0 { t.Fatalf("closed=%+v err=%v known=%+v", closed, err, g.known[key]) } } func TestGitHubInvalidContinuationIsInvalidParams(t *testing.T) { g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { t.Error("invalid continuation made an API request") }) for _, name := range []string{activityName, notificationsName} { page, err := g.FetchPage(context.Background(), name, Arguments{Repos: []string{"acme/widgets"}}, githubTestTime, "malformed") var rpc *jsonrpc.Error if !errors.As(err, &rpc) || rpc.Code != -32602 || page.Complete { t.Fatalf("name=%s page=%+v err=%v", name, page, err) } } } func TestGitHubKnownHeadNullRollupToTerminal(t *testing.T) { terminal := false g, _ := testGitHub(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/search/issues": count := 0 if strings.Contains(r.URL.Query().Get("q"), "is:open") { count = 1 } githubJSON(t, w, map[string]any{"total_count": count, "items": githubItems(count)}) case "/graphql": repository := githubHeadFixture("abcdef", "SUCCESS", githubTestTime.Add(-time.Hour)) if !terminal { pull := repository["pullRequest"].(map[string]any) commits := pull["commits"].(map[string]any)["nodes"].([]any) commits[0].(map[string]any)["commit"].(map[string]any)["statusCheckRollup"] = nil } githubJSON(t, w, map[string]any{"data": map[string]any{"p0": repository}}) default: t.Errorf("quiet head fetched deeply: %s", r.URL) w.WriteHeader(404) } }) args := Arguments{Repos: []string{"acme/widgets"}, Kinds: []string{"check_suite"}} since := githubTestTime.Add(-time.Minute) baseline, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || len(baseline.Events) != 0 { t.Fatalf("baseline=%+v err=%v", baseline, err) } known := g.known[subscriptionKey(activityName, args)].pulls["acme/widgets#1"] if known.head != "abcdef" || known.rollup != "" { t.Fatalf("expected null-rollup baseline: %+v", known) } terminal = true completed, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || len(completed.Events) != 1 { t.Fatalf("completed=%+v err=%v", completed, err) } unchanged, err := g.Fetch(context.Background(), activityName, args, since) if err != nil || len(unchanged.Events) != 0 { t.Fatalf("unchanged=%+v err=%v", unchanged, err) } }