diff --git a/internal/reconcile/list.go b/internal/reconcile/list.go index 993b4d5..1b96cd0 100644 --- a/internal/reconcile/list.go +++ b/internal/reconcile/list.go @@ -11,6 +11,7 @@ import ( "encoding/json" "fmt" "net/url" + "slices" "time" "github.com/tbhb-dev/github-metrics/internal/budget" @@ -22,6 +23,10 @@ const ( DefaultMaxPages = 50 // SweepMaxPages caps the daily sweep of one repository. SweepMaxPages = 200 + // MaxRepoPages caps the repository list. + MaxRepoPages = 10 + + repositoriesPath = "installation/repositories?per_page=100" ) // Getter is the part of ghclient.Client the lister uses. @@ -35,6 +40,12 @@ type Tags interface { Set(target, etag string) } +// Repository is one repository of the installation. +type Repository struct { + FullName string `json:"full_name"` //nolint:tagliatelle // GitHub field name. + ID int64 `json:"id"` +} + // ClosedPR is the list item of a pull request that has a close time. It // decodes straight from a list item. type ClosedPR struct { @@ -76,7 +87,7 @@ type Walked struct { Unchanged bool } -// Lister reads the updated-order walks. It isn't safe +// Lister reads the repository list and the updated-order walks. It isn't safe // for concurrent use. type Lister struct { client Getter @@ -84,6 +95,10 @@ type Lister struct { base *url.URL // stops holds the stop time of each repository's last clean walk. stops map[string]time.Time + // cached holds the last repository list, valid only when the last full + // read fit on one page and every page succeeded. + cached []Repository + valid bool } // NewLister returns a lister. The base URL must be the one the client uses, @@ -91,7 +106,35 @@ type Lister struct { // slash, such as /api/v3/, so the request paths stay under it. A page cap below // one reads one page. func NewLister(client Getter, tags Tags, base *url.URL) *Lister { - return &Lister{client: client, tags: tags, base: base, stops: map[string]time.Time{}} + return &Lister{client: client, tags: tags, base: base, cached: nil, valid: false, stops: map[string]time.Time{}} +} + +type repositoryPage struct { + Repositories []Repository `json:"repositories"` +} + +// Repositories returns the installation's repositories. Only a list that fit +// on one page keeps its first-page tag, since a tag on page one can't see a +// change confined to page two. A 304 then returns the cached list. For a +// longer list, or after a failed page, every page is read in full and the +// tags are cleared. The bool is true when the page cap cut the list short. +func (l *Lister) Repositories(ctx context.Context) ([]Repository, bool, error) { + if !l.valid { + l.clear(repositoriesPath) + } + + repos, truncated, single, err := l.readRepositories(ctx) + l.valid = err == nil && single + + if l.valid { + l.cached = slices.Clone(repos) + + return repos, truncated, nil + } + + l.clear(repositoriesPath) + + return repos, truncated, err } // Updated walks a repository's pull requests in `updated_at` order, newest @@ -147,6 +190,42 @@ func (l *Lister) fetch(ctx context.Context, priority budget.Priority, target str return resp, nil } +// readRepositories returns the cached list after a 304 of the first page. The +// second bool is true when the list fit on one page. +func (l *Lister) readRepositories(ctx context.Context) ([]Repository, bool, bool, error) { + repos := []Repository{} + target := repositoriesPath + + for page := 1; ; page++ { + resp, err := l.fetch(ctx, budget.Incremental, target, page) + if err != nil { + return nil, false, false, err + } + + if resp.NotModified() && page == 1 && l.valid { + return slices.Clone(l.cached), false, true, nil + } + + var decoded repositoryPage + + err = json.Unmarshal(resp.Body, &decoded) + if err != nil { + return nil, false, false, fmt.Errorf("decode repositories: %w", err) + } + + repos = append(repos, decoded.Repositories...) + + switch { + case resp.Next == "": + return repos, false, page == 1, nil + case page >= MaxRepoPages: + return repos, true, false, nil + } + + target = resp.Next + } +} + func (l *Lister) walk(ctx context.Context, repo, first string, opts WalkOptions) (Walked, error) { var walked Walked diff --git a/internal/reconcile/list_test.go b/internal/reconcile/list_test.go index fe952bf..2a4bad3 100644 --- a/internal/reconcile/list_test.go +++ b/internal/reconcile/list_test.go @@ -27,7 +27,10 @@ type fakeTokens struct{} func (fakeTokens) Token(context.Context) (string, error) { return "test-token", nil } func (fakeTokens) Renew(context.Context) (string, error) { return "test-token", nil } -const firstPage = "/repos/o/r/pulls?state=all&sort=updated&direction=desc&per_page=100" +const ( + firstPage = "/repos/o/r/pulls?state=all&sort=updated&direction=desc&per_page=100" + repoPage = "/installation/repositories?per_page=100" +) // rig is a lister on a real client, and what its fake server received. type rig struct { @@ -217,6 +220,67 @@ func TestUpdatedFirstPageTagOnly(t *testing.T) { } } +func TestRepositoriesSinglePageUsesTag(t *testing.T) { + t.Parallel() + + fake := newRig(t, func(resp http.ResponseWriter, req *http.Request, _ string) { + if req.Header.Get("If-None-Match") == `"list"` { + resp.WriteHeader(http.StatusNotModified) + + return + } + + resp.Header().Set("ETag", `"list"`) + write(t, resp, `{"repositories":[{"id":7,"full_name":"o/r"},{"id":8,"full_name":"o/s"}]}`) + }) + + for range 2 { + repos, truncated, err := fake.lister.Repositories(t.Context()) + if err != nil || truncated || len(repos) != 2 || repos[0].FullName != "o/r" || repos[0].ID != 7 { + t.Fatalf("repos = %+v, truncated = %v, err = %v", repos, truncated, err) + } + + // A caller editing its copy must not change the cached list. + repos[0] = repos[1] + } + + if len(fake.requests) != 2 || fake.tags[repoPage] != `"list"` { + t.Errorf("requests = %v, last tag = %q", fake.requests, fake.tags[repoPage]) + } +} + +func TestRepositoriesTwoPagesSendNoTag(t *testing.T) { + t.Parallel() + + fake := newRig(t, func(resp http.ResponseWriter, req *http.Request, host string) { + resp.Header().Set("ETag", `"`+req.URL.RequestURI()+`"`) + + if req.URL.Query().Get("page") == "" { + resp.Header().Set("Link", "<"+host+repoPage+`&page=2>; rel="next"`) + write(t, resp, `{"repositories":[{"id":1,"full_name":"o/a"}]}`) + + return + } + + write(t, resp, `{"repositories":[{"id":2,"full_name":"o/b"}]}`) + }) + + for range 2 { + repos, truncated, err := fake.lister.Repositories(t.Context()) + if err != nil || truncated || len(repos) != 2 { + t.Fatalf("repos = %+v, truncated = %v, err = %v", repos, truncated, err) + } + } + + if len(fake.requests) != 4 { + t.Fatalf("requests = %v, want both pages twice", fake.requests) + } + + if fake.tags[repoPage] != "" || fake.tags[repoPage+"&page=2"] != "" { + t.Errorf("tags = %v, want none", fake.tags) + } +} + func TestUpdatedWiderWindowReadsPastTag(t *testing.T) { t.Parallel() @@ -246,12 +310,23 @@ func TestUpdatedWiderWindowReadsPastTag(t *testing.T) { func TestListerKeepsBasePath(t *testing.T) { t.Parallel() - fake := newRigAt(t, "/api/v3/", func(resp http.ResponseWriter, _ *http.Request, _ string) { + fake := newRigAt(t, "/api/v3/", func(resp http.ResponseWriter, req *http.Request, _ string) { + if req.URL.Path == "/api/v3/installation/repositories" { + write(t, resp, `{"repositories":[{"id":1,"full_name":"o/r"}]}`) + + return + } + write(t, resp, "[]") }) - _, err := fake.lister.Updated(t.Context(), "o/r", opts(50)) - if want := []string{"/api/v3" + firstPage}; err != nil || !slices.Equal(fake.requests, want) { + _, _, err := fake.lister.Repositories(t.Context()) + if err == nil { + _, err = fake.lister.Updated(t.Context(), "o/r", opts(50)) + } + + if want := []string{"/api/v3/installation/repositories?per_page=100", "/api/v3/repos/o/r/pulls?" + + "state=all&sort=updated&direction=desc&per_page=100"}; err != nil || !slices.Equal(fake.requests, want) { t.Errorf("requests = %v, err = %v", fake.requests, err) } }