Skip to content
Merged
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
15 changes: 11 additions & 4 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ var (
// ErrTimeout means the request did not complete within the parser's
// timeout or the caller's deadline.
ErrTimeout = errors.New("timed out")
// ErrServerUnavailable means a URL check received HTTP 502, 503 or 504.
// The server could not complete the request, so callers can retry later.
ErrServerUnavailable = errors.New("server unavailable")
)

// ParseError is a generic parse error.
Expand Down Expand Up @@ -55,7 +58,7 @@ type ValidationError struct {
Line int `json:"line"`
Column int `json:"column"`

// cause is ErrRateLimited, ErrTimeout or nil.
// cause is ErrRateLimited, ErrTimeout, ErrServerUnavailable or nil.
cause error
}

Expand All @@ -68,8 +71,8 @@ func (e ValidationError) Error() string {
return fmt.Sprintf("%s:%d:%d: error: %s%s", e.fileName(), e.Line, e.Column, key, e.Description)
}

// Unwrap returns [ErrRateLimited] or [ErrTimeout] when e reports a network
// check that failed for that reason, and nil otherwise.
// Unwrap returns [ErrRateLimited], [ErrTimeout] or [ErrServerUnavailable]
// when e reports a network check that failed for that reason, and nil otherwise.
func (e ValidationError) Unwrap() error {
return e.cause
}
Expand Down Expand Up @@ -104,14 +107,18 @@ func newValidationErrorf(key string, description string, args ...any) Validation
}

// withCause records why the network check behind e failed, when err says
// it was rate limited or timed out.
// it was rate limited, timed out or the server was unavailable.
func (e ValidationError) withCause(err error) ValidationError {
e.cause = networkCause(err)

return e
}

func networkCause(err error) error {
if errors.Is(err, httpclient.ErrServerUnavailable) {
return ErrServerUnavailable
}

if errors.Is(err, httpclient.ErrRateLimited) {
return ErrRateLimited
}
Expand Down
1 change: 1 addition & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ func TestNetworkCause(t *testing.T) {
err error
want error
}{
{"server unavailable", fmt.Errorf("downloading: %w", httpclient.ErrServerUnavailable), ErrServerUnavailable},
{"rate limited", fmt.Errorf("downloading: %w", httpclient.ErrRateLimited), ErrRateLimited},
{"deadline", fmt.Errorf("requesting: %w", context.DeadlineExceeded), ErrTimeout},
{"net timeout", &net.DNSError{Err: "i/o timeout", IsTimeout: true}, ErrTimeout},
Expand Down
12 changes: 8 additions & 4 deletions internal/httpclient/httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ const (
)

var (
ErrNotFound = errors.New("not found")
ErrForbidden = errors.New("forbidden")
ErrRateLimited = errors.New("rate limited")
ErrUnexpectedStatus = errors.New("unexpected status")
ErrNotFound = errors.New("not found")
ErrForbidden = errors.New("forbidden")
ErrRateLimited = errors.New("rate limited")
ErrUnexpectedStatus = errors.New("unexpected status")
ErrServerUnavailable = errors.New("server unavailable")

errInvalidHeader = errors.New("invalid header")
)
Expand Down Expand Up @@ -285,6 +286,9 @@ func checkStatus(resp *http.Response) error {
return ErrNotFound
case resp.StatusCode == http.StatusForbidden:
return ErrForbidden
case resp.StatusCode == http.StatusBadGateway ||
resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusGatewayTimeout:
return fmt.Errorf("%w %s", ErrServerUnavailable, resp.Status)
case resp.StatusCode < 200 || resp.StatusCode > 299:
return fmt.Errorf("%w %s", ErrUnexpectedStatus, resp.Status)
}
Expand Down
44 changes: 44 additions & 0 deletions internal/httpclient/httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,3 +521,47 @@ func TestGetKeepsTheSizeCap(t *testing.T) {
})
}
}

func TestGetServerUnavailable(t *testing.T) {
for _, status := range []int{
http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout,
http.StatusInternalServerError, http.StatusNotImplemented, http.StatusNotFound, http.StatusForbidden,
} {
t.Run(http.StatusText(status), func(t *testing.T) {
c, url, waits := newClient(t, step{status: status})
_, err := c.Get(url, nil)
want := status == 502 || status == 503 || status == 504
if errors.Is(err, ErrServerUnavailable) != want {
t.Errorf("Get() = %v, want server unavailable: %v", err, want)
}
if want && !strings.Contains(err.Error(), http.StatusText(status)) {
t.Errorf("error %v does not name the status", err)
}
if len(*waits) != 0 {
t.Errorf("waited %v, want no wait", *waits)
}
})
}
}

func TestCheckServerUnavailable(t *testing.T) {
for _, status := range []int{
http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout,
http.StatusInternalServerError, http.StatusNotImplemented, http.StatusNotFound, http.StatusForbidden,
} {
t.Run(http.StatusText(status), func(t *testing.T) {
c, url, waits := newClient(t, step{status: status})
err := c.Check(url, nil)
want := status == 502 || status == 503 || status == 504
if errors.Is(err, ErrServerUnavailable) != want {
t.Errorf("Check() = %v, want server unavailable: %v", err, want)
}
if want && !strings.Contains(err.Error(), http.StatusText(status)) {
t.Errorf("error %v does not name the status", err)
}
if len(*waits) != 0 {
t.Errorf("waited %v, want no wait", *waits)
}
})
}
}
49 changes: 48 additions & 1 deletion network_errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ func TestAuthorsFileNetworkChecksUnwrapToTheirCause(t *testing.T) {
case "/rate-limited":
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
case "/unavailable":
w.WriteHeader(http.StatusServiceUnavailable)
case "/stalled":
select {
case <-r.Context().Done():
Expand All @@ -192,6 +194,7 @@ func TestAuthorsFileNetworkChecksUnwrapToTheirCause(t *testing.T) {
}{
{"rate limited", "/rate-limited", ErrRateLimited},
{"timeout", "/stalled", ErrTimeout},
{"unavailable", "/unavailable", ErrServerUnavailable},
{"missing", "/missing", nil},
} {
t.Run(tc.name, func(t *testing.T) {
Expand Down Expand Up @@ -219,7 +222,7 @@ func TestAuthorsFileNetworkChecksUnwrapToTheirCause(t *testing.T) {
if !errors.Is(valErr.Unwrap(), tc.cause) {
t.Errorf("Unwrap() = %v, want %v", valErr.Unwrap(), tc.cause)
}
for _, cause := range []error{ErrTimeout, ErrRateLimited} {
for _, cause := range []error{ErrTimeout, ErrRateLimited, ErrServerUnavailable} {
if errors.Is(result, cause) != errors.Is(tc.cause, cause) {
t.Errorf("errors.Is(%v, %v) = %v", result, cause, errors.Is(result, cause))
}
Expand All @@ -231,3 +234,47 @@ func TestAuthorsFileNetworkChecksUnwrapToTheirCause(t *testing.T) {
})
}
}

func TestServerOutagesUnwrapToTheirCause(t *testing.T) {
for _, status := range []int{http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout} {
t.Run(http.StatusText(status), func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(status)
}))
t.Cleanup(srv.Close)
p, err := NewParser(ParserConfig{AllowNetworkToPrivateHosts: true})
if err != nil {
t.Fatal(err)
}
content, err := os.ReadFile("testdata/v0/invalid/network/urls_server_unavailable.yml")
if err != nil {
t.Fatal(err)
}
content = bytes.ReplaceAll(content, []byte("https://example.com"), []byte(srv.URL))
_, err = p.ParseStream(bytes.NewReader(content))
vr, ok := errors.AsType[ValidationResults](err)
if !ok {
t.Fatalf("got %v, want ValidationResults", err)
}
for _, key := range []string{"landingURL", "logo", "monochromeLogo", "description.en.screenshots[0]"} {
found := false
for _, result := range vr {
valErr, ok := errors.AsType[ValidationError](result)
if !ok || valErr.Key != key {
continue
}
found = true
if !errors.Is(result, ErrServerUnavailable) {
t.Errorf("%s: %v does not match ErrServerUnavailable", key, result)
}
if !strings.Contains(valErr.Description, http.StatusText(status)) {
t.Errorf("%s: %v does not name the status", key, result)
}
}
if !found {
t.Errorf("no error for %s in %v", key, vr)
}
}
})
}
}
8 changes: 8 additions & 0 deletions testdata/v0/invalid/network/urls_server_unavailable.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
publiccodeYmlVersion: '0.8'
landingURL: https://example.com
logo: https://example.com/logo.png
monochromeLogo: https://example.com/mono.svg
description:
en:
screenshots:
- https://example.com/shot.png