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
85 changes: 78 additions & 7 deletions framework/components/dockercompose/chip_ingress_set/protos.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"

"github.com/google/go-github/v72/github"
"github.com/pkg/errors"
Expand Down Expand Up @@ -175,16 +177,85 @@ func cacheFilePath(owner, repository, ref string) (string, error) {
}

func resolveRefSHA(ctx context.Context, client *github.Client, owner, repository, ref string) (string, error) {
if refObj, _, err := client.Git.GetRef(ctx, owner, repository, "refs/tags/"+ref); err == nil {
return refObj.GetObject().GetSHA(), nil
// These lookups are expected to 404 when ref is a commit SHA; a miss only
// means "try the next form of ref".
for _, prefix := range []string{"refs/tags/", "refs/heads/"} {
refObj, _, err := client.Git.GetRef(ctx, owner, repository, prefix+ref)
if err == nil {
return refObj.GetObject().GetSHA(), nil
}
}
if refObj, _, err := client.Git.GetRef(ctx, owner, repository, "refs/heads/"+ref); err == nil {
return refObj.GetObject().GetSHA(), nil

commit, err := getCommitWithRetry(ctx, client, owner, repository, ref)
if err != nil {
if isNotFound(err) {
return "", fmt.Errorf("ref %q not found", ref)
}
// Surface the underlying failure: a rate limit or server error is not
// a missing ref, and must not be reported as one.
return "", fmt.Errorf("resolve commit %q: %w", ref, err)
}
if commit, _, err := client.Repositories.GetCommit(ctx, owner, repository, ref, nil); err == nil {
return commit.GetSHA(), nil
return commit.GetSHA(), nil
}

const (
commitLookupAttempts = 4
commitLookupBaseWait = 500 * time.Millisecond
)

// retryWait is a variable so tests can avoid sleeping.
var retryWait = func(ctx context.Context, d time.Duration) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(d):
return nil
}
}

func getCommitWithRetry(ctx context.Context, client *github.Client, owner, repository, ref string) (*github.RepositoryCommit, error) {
var lastErr error
for attempt := 0; attempt < commitLookupAttempts; attempt++ {
commit, _, err := client.Repositories.GetCommit(ctx, owner, repository, ref, nil)
if err == nil {
return commit, nil
}
lastErr = err
if attempt == commitLookupAttempts-1 || !isRetryable(err) {
break
}
if waitErr := retryWait(ctx, time.Duration(attempt+1)*commitLookupBaseWait); waitErr != nil {
return nil, waitErr
}
}
return nil, lastErr
}

func isNotFound(err error) bool {
var errResponse *github.ErrorResponse
return errors.As(err, &errResponse) &&
errResponse.Response != nil &&
errResponse.Response.StatusCode == http.StatusNotFound
}

func isRetryable(err error) bool {
var errResponse *github.ErrorResponse
if errors.As(err, &errResponse) {
if errResponse.Response == nil {
return false
}
switch code := errResponse.Response.StatusCode; {
case code >= 500, code == http.StatusTooManyRequests:
return true
case code == http.StatusForbidden:
// Secondary rate limits come back as 403s.
return strings.Contains(strings.ToLower(errResponse.Message), "rate limit")
}
return false
}
return "", fmt.Errorf("ref %q not found", ref)
// Transport failures (DNS, TLS, timeouts) are worth another attempt.
var netErr net.Error
return errors.As(err, &netErr)
}

func fetchFromGithub(ctx context.Context, clientFn func() *github.Client, owner, repository, ref string) (string, error) {
Expand Down
146 changes: 146 additions & 0 deletions framework/components/dockercompose/chip_ingress_set/protos_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package chipingressset

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"

"github.com/google/go-github/v72/github"
"github.com/stretchr/testify/require"
)

func testClient(t *testing.T, handler http.HandlerFunc) *github.Client {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)

base, err := url.Parse(srv.URL + "/")
require.NoError(t, err)

client := github.NewClient(nil)
client.BaseURL = base
return client
}

func noRetryWait(t *testing.T) {
t.Helper()
old := retryWait
retryWait = func(context.Context, time.Duration) error { return nil }
t.Cleanup(func() { retryWait = old })
}

func writeJSON(w http.ResponseWriter, status int, body string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = fmt.Fprint(w, body)
}

func TestResolveRefSHATag(t *testing.T) {
commitCalls := 0
client := testClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.Contains(r.URL.Path, "/git/ref/tags/"):
writeJSON(w, http.StatusOK, `{"ref":"refs/tags/v1.2.3","object":{"sha":"tag-sha"}}`)
case strings.Contains(r.URL.Path, "/commits/"):
commitCalls++
http.NotFound(w, r)
default:
http.NotFound(w, r)
}
})

sha, err := resolveRefSHA(context.Background(), client, "o", "r", "v1.2.3")
require.NoError(t, err)
require.Equal(t, "tag-sha", sha)
require.Zero(t, commitCalls)
}

func TestResolveRefSHABranch(t *testing.T) {
client := testClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.Contains(r.URL.Path, "/git/ref/tags/"):
http.NotFound(w, r)
case strings.Contains(r.URL.Path, "/git/ref/heads/"):
writeJSON(w, http.StatusOK, `{"ref":"refs/heads/main","object":{"sha":"branch-sha"}}`)
default:
http.NotFound(w, r)
}
})

sha, err := resolveRefSHA(context.Background(), client, "o", "r", "main")
require.NoError(t, err)
require.Equal(t, "branch-sha", sha)
}

func TestResolveRefSHAShortCommitSHA(t *testing.T) {
client := testClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.Contains(r.URL.Path, "/git/ref/"):
http.NotFound(w, r)
case strings.Contains(r.URL.Path, "/commits/fa1d775e2138"):
writeJSON(w, http.StatusOK, `{"sha":"fa1d775e21381de1c33baa11e9b378935c8e3a0e"}`)
default:
http.NotFound(w, r)
}
})

sha, err := resolveRefSHA(context.Background(), client, "o", "r", "fa1d775e2138")
require.NoError(t, err)
require.Equal(t, "fa1d775e21381de1c33baa11e9b378935c8e3a0e", sha)
}

func TestResolveRefSHANotFound(t *testing.T) {
client := testClient(t, func(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
})

_, err := resolveRefSHA(context.Background(), client, "o", "r", "deadbeef")
require.Error(t, err)
require.Contains(t, err.Error(), `ref "deadbeef" not found`)
}

func TestResolveRefSHASurfacesServerError(t *testing.T) {
noRetryWait(t)
attempts := 0
client := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/commits/") {
attempts++
writeJSON(w, http.StatusInternalServerError, `{"message":"Server Error"}`)
return
}
http.NotFound(w, r)
})

_, err := resolveRefSHA(context.Background(), client, "o", "r", "fa1d775e2138")
require.Error(t, err)
require.Contains(t, err.Error(), "500")
require.NotContains(t, err.Error(), "not found")
require.Equal(t, commitLookupAttempts, attempts)
}

func TestResolveRefSHARetriesTransientError(t *testing.T) {
noRetryWait(t)
attempts := 0
client := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/commits/") {
attempts++
if attempts == 1 {
writeJSON(w, http.StatusBadGateway, `{"message":"Bad Gateway"}`)
return
}
writeJSON(w, http.StatusOK, `{"sha":"full-sha"}`)
return
}
http.NotFound(w, r)
})

sha, err := resolveRefSHA(context.Background(), client, "o", "r", "fa1d775e2138")
require.NoError(t, err)
require.Equal(t, "full-sha", sha)
require.Equal(t, 2, attempts)
}
Loading