Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion test/testutil/githubtestrepo/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
load("@rules_go//go:def.bzl", "go_library")
load("@rules_go//go:def.bzl", "go_library", "go_test")

go_library(
name = "go_default_library",
Expand All @@ -12,3 +12,14 @@ go_library(
"@org_golang_x_oauth2//:go_default_library",
],
)

go_test(
name = "go_default_test",
srcs = ["githubtestrepo_test.go"],
embed = [":go_default_library"],
deps = [
"//platform/http:go_default_library",
"@com_github_stretchr_testify//assert:go_default_library",
"@com_github_stretchr_testify//require:go_default_library",
],
)
252 changes: 215 additions & 37 deletions test/testutil/githubtestrepo/githubtestrepo.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
Expand All @@ -48,6 +51,13 @@ import (
phttp "github.com/uber/submitqueue/platform/http"
)

const (
maxAttempts = 4
// maxRetryAfter bounds how long a Retry-After header may ask a CI job to
// wait; a longer wait cannot help the job, so the response is returned.
maxRetryAfter = 60 * time.Second
)

const (
// TokenEnv names the variable holding a token with write access to the
// test repository.
Expand All @@ -74,8 +84,11 @@ type TestRepo struct {
repo string
trunk string
runID string
branches []string
pulls []int
// retryBaseDelay is the first backoff when a retry has no Retry-After; each
// further retry doubles it.
retryBaseDelay time.Duration
branches []string
pulls []int
}

// Pull is a fixture pull request.
Expand Down Expand Up @@ -112,13 +125,20 @@ func New(t testing.TB) *TestRepo {
Base: httpClient.Transport,
}

r := newTestRepo(t, httpClient, owner, repo)
r.token = token
return r
}

func newTestRepo(t testing.TB, httpClient *http.Client, owner, repo string) *TestRepo {
t.Helper()
r := &TestRepo{
t: t,
httpClient: httpClient,
token: token,
owner: owner,
repo: repo,
runID: fmt.Sprintf("%d", time.Now().UnixNano()),
t: t,
httpClient: httpClient,
owner: owner,
repo: repo,
runID: fmt.Sprintf("%d", time.Now().UnixNano()),
retryBaseDelay: time.Second,
}
var repoInfo struct {
DefaultBranch string `json:"default_branch"`
Expand Down Expand Up @@ -175,71 +195,156 @@ func (r *TestRepo) OpenStack(name string, n int) []Pull {
}

// OpenChain opens n pull requests stacked by base branch without creating a
// GitHub stack.
// GitHub stack. Each branch is created at the previous pull request's known
// head rather than at a re-read of its ref, which a lagging read could return
// stale and so break the chain's linear history.
func (r *TestRepo) OpenChain(name string, n int) []Pull {
base := r.trunk
r.t.Helper()
pulls := make([]Pull, 0, n)
base, baseSHA := r.trunk, r.branchSHA(r.trunk)
for i := 1; i <= n; i++ {
p := r.OpenPull(fmt.Sprintf("%s-%d", name, i), base)
p := r.openPullFrom(fmt.Sprintf("%s-%d", name, i), base, baseSHA)
pulls = append(pulls, p)
base = p.Branch
base, baseSHA = p.Branch, p.Head
}
return pulls
}

// OpenPull opens one pull request against base that adds a file unique to it.
func (r *TestRepo) OpenPull(name, base string) Pull {
r.t.Helper()
branch := fmt.Sprintf("sq-it/%s/%s", r.runID, name)
var baseRef struct {
return r.openPullFrom(name, base, r.branchSHA(base))
}

func (r *TestRepo) branchSHA(branch string) string {
r.t.Helper()
var ref struct {
Object struct {
SHA string `json:"sha"`
} `json:"object"`
}
r.call(http.MethodGet, r.path("/git/ref/heads/"+base), nil, &baseRef)
r.call(http.MethodPost, r.path("/git/refs"), map[string]string{"ref": "refs/heads/" + branch, "sha": baseRef.Object.SHA}, nil)
r.call(http.MethodGet, r.path("/git/ref/heads/"+branch), nil, &ref)
return ref.Object.SHA
}

func (r *TestRepo) openPullFrom(name, base, baseSHA string) Pull {
r.t.Helper()
branch := fmt.Sprintf("sq-it/%s/%s", r.runID, name)
r.createBranchAt(branch, baseSHA)
r.branches = append(r.branches, branch)

head := r.CommitFile(branch, r.FilePath(name), name)
number := r.createPull(name, branch, base)
r.pulls = append(r.pulls, number)
return Pull{Number: number, Branch: branch, Head: head}
}

// createBranchAt treats an "already exists" 422 as an earlier attempt having
// landed; fixture branch names carry the run ID, so nothing else owns the ref.
func (r *TestRepo) createBranchAt(branch, sha string) {
r.t.Helper()
path := r.path("/git/refs")
code, resp := r.send(http.MethodPost, path, map[string]string{"ref": "refs/heads/" + branch, "sha": sha}, nil)
if code == http.StatusUnprocessableEntity && strings.Contains(resp, "already exists") {
require.Equal(r.t, sha, r.branchSHA(branch), "branch %s exists at a different commit", branch)
return
}
require.True(r.t, code >= 200 && code < 300, "POST %s: status %d: %s", path, code, resp)
}

// createPull treats an "already exists" 422 as an earlier attempt having landed,
// like createBranchAt.
func (r *TestRepo) createPull(name, branch, base string) int {
r.t.Helper()
path := r.path("/pulls")
var pr struct {
Number int `json:"number"`
}
r.call(http.MethodPost, r.path("/pulls"), map[string]string{
code, resp := r.send(http.MethodPost, path, map[string]string{
"title": fmt.Sprintf("sq integration %s (%s)", name, r.runID),
"head": branch,
"base": base,
"body": "Opened by a SubmitQueue integration test; closed or merged automatically.",
}, &pr)
r.pulls = append(r.pulls, pr.Number)
return Pull{Number: pr.Number, Branch: branch, Head: head}
if code == http.StatusUnprocessableEntity && strings.Contains(resp, "already exists") {
var open []struct {
Number int `json:"number"`
}
query := url.Values{"head": {r.owner + ":" + branch}, "state": {"open"}}
r.call(http.MethodGet, r.path("/pulls?"+query.Encode()), nil, &open)
require.Len(r.t, open, 1, "pull request for branch %s after 422: %s", branch, resp)
return open[0].Number
}
require.True(r.t, code >= 200 && code < 300, "POST %s: status %d: %s", path, code, resp)
return pr.Number
}

// FilePath is the path of the file a fixture named name adds.
func (r *TestRepo) FilePath(name string) string {
return fmt.Sprintf("sq-it/%s/%s.txt", r.runID, name)
}

// CommitFile writes a file on branch and returns the new head commit.
// CommitFile writes a file on branch and returns the commit that wrote it. A
// transient failure retries the read-then-write as a unit; a file already
// holding the content is not rewritten and its last commit is returned.
func (r *TestRepo) CommitFile(branch, path, content string) string {
r.t.Helper()
want := content + "\n"
body := map[string]string{
"message": "sq integration " + path,
"content": base64.StdEncoding.EncodeToString([]byte(content + "\n")),
"content": base64.StdEncoding.EncodeToString([]byte(want)),
"branch": branch,
}
var existing struct {
SHA string `json:"sha"`
payload, err := json.Marshal(body)
require.NoError(r.t, err)
for attempt := 1; ; attempt++ {
var existing struct {
SHA string `json:"sha"`
Content string `json:"content"`
}
if code, _ := r.send(http.MethodGet, r.path("/contents/"+path+"?ref="+branch), nil, &existing); code == http.StatusOK {
if got, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(existing.Content, "\n", "")); err == nil && string(got) == want {
if head := r.lastCommitTouching(branch, path); head != "" {
return head
}
require.Less(r.t, attempt, maxAttempts, "no commit on %s writes %s", branch, path)
r.wait(r.retryBaseDelay << (attempt - 1))
continue
Comment thread
sbalabanov marked this conversation as resolved.
Resolved
}
body["sha"] = existing.SHA
payload, err = json.Marshal(body)
require.NoError(r.t, err)
}
resp, err := r.sendOnce(http.MethodPut, r.path("/contents/"+path), payload)
if err == nil && resp.code >= 200 && resp.code < 300 {
var out struct {
Commit struct {
SHA string `json:"sha"`
} `json:"commit"`
}
require.NoError(r.t, json.Unmarshal(resp.body, &out), "PUT %s", path)
return out.Commit.SHA
}
delay, retry := r.retryDelay(resp, err, attempt)
require.True(r.t, retry, "PUT %s: status %d: %s (error: %v)", path, resp.code, resp.body, err)
r.t.Logf("retrying PUT %s: status %d, attempt %d (error: %v)", path, resp.code, attempt, err)
r.wait(delay)
}
if code, _ := r.send(http.MethodGet, r.path("/contents/"+path+"?ref="+branch), nil, &existing); code == http.StatusOK {
body["sha"] = existing.SHA
}

// lastCommitTouching asks for the commit that wrote path, not the branch head,
// because a branch read can lag the write; "" means it is not visible yet.
func (r *TestRepo) lastCommitTouching(branch, path string) string {
r.t.Helper()
var commits []struct {
SHA string `json:"sha"`
}
var out struct {
Commit struct {
SHA string `json:"sha"`
} `json:"commit"`
query := url.Values{"sha": {branch}, "path": {path}, "per_page": {"1"}}
r.call(http.MethodGet, r.path("/commits?"+query.Encode()), nil, &commits)
if len(commits) == 0 {
return ""
}
r.call(http.MethodPut, r.path("/contents/"+path), body, &out)
return out.Commit.SHA
return commits[0].SHA
}

// AwaitPullHead waits until GitHub reports head as the pull request's head. A
Expand Down Expand Up @@ -335,6 +440,14 @@ func (r *TestRepo) call(method, path string, body, out any) {
require.True(r.t, code >= 200 && code < 300, "%s %s: status %d: %s", method, path, code, resp)
}

type response struct {
code int
body []byte
header http.Header
}

// send retries transient failures; see retryDelay for which. It returns status
// 0 when every attempt failed at the transport.
func (r *TestRepo) send(method, path string, body, out any) (int, string) {
r.t.Helper()
var payload []byte
Expand All @@ -343,13 +456,78 @@ func (r *TestRepo) send(method, path string, body, out any) (int, string) {
payload, err = json.Marshal(body)
require.NoError(r.t, err)
}
code, resp, err := phttp.SendRequest(context.Background(), r.httpClient, method, path, payload, githubapi.SetRESTHeaders)
for attempt := 1; ; attempt++ {
resp, err := r.sendOnce(method, path, payload)
delay, retry := r.retryDelay(resp, err, attempt)
if !retry {
if err != nil {
r.t.Logf("%s %s: %v", method, path, err)
return 0, ""
}
if out != nil && resp.code >= 200 && resp.code < 300 && len(resp.body) > 0 {
require.NoError(r.t, json.Unmarshal(resp.body, out), "%s %s", method, path)
}
return resp.code, string(resp.body)
}
r.t.Logf("retrying %s %s: status %d, attempt %d (error: %v)", method, path, resp.code, attempt, err)
r.wait(delay)
}
}

func (r *TestRepo) sendOnce(method, path string, payload []byte) (response, error) {
var reader io.Reader
if payload != nil {
reader = strings.NewReader(string(payload))
}
req, err := http.NewRequestWithContext(context.Background(), method, path, reader)
if err != nil {
return response{}, err
}
githubapi.SetRESTHeaders(req)
resp, err := r.httpClient.Do(req)
if err != nil {
r.t.Logf("%s %s: %v", method, path, err)
return 0, ""
return response{}, err
}
if out != nil && code >= 200 && code < 300 && len(resp) > 0 {
require.NoError(r.t, json.Unmarshal(resp, out), "%s %s", method, path)
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return response{}, err
}
return response{code: resp.StatusCode, body: respBody, header: resp.Header}, nil
}

// retryDelay retries transport errors, 500/502/503/504, and a 403 or 429 carrying
// Retry-After (a secondary rate limit); without one, waiting cannot help.
func (r *TestRepo) retryDelay(resp response, err error, attempt int) (time.Duration, bool) {
if attempt >= maxAttempts {
return 0, false
}
return code, string(resp)
backoff := r.retryBaseDelay << (attempt - 1)
retryAfter, hasRetryAfter := time.Duration(0), false
if secs, parseErr := strconv.Atoi(resp.header.Get("Retry-After")); parseErr == nil && secs >= 0 {
retryAfter, hasRetryAfter = time.Duration(secs)*time.Second, true
}
switch {
case err != nil:
return backoff, true
case resp.code == http.StatusForbidden || resp.code == http.StatusTooManyRequests:
if !hasRetryAfter || retryAfter > maxRetryAfter {
return 0, false
}
return retryAfter, true
case resp.code == http.StatusInternalServerError, resp.code == http.StatusBadGateway,
resp.code == http.StatusServiceUnavailable, resp.code == http.StatusGatewayTimeout:
if hasRetryAfter {
return retryAfter, retryAfter <= maxRetryAfter
}
Comment thread
sbalabanov marked this conversation as resolved.
Resolved
return backoff, true
}
return 0, false
}

// wait paces calls to GitHub; it does not synchronize goroutines.
func (r *TestRepo) wait(d time.Duration) {
timer := time.NewTimer(d)
defer timer.Stop()
<-timer.C
}
Loading