diff --git a/errors.go b/errors.go index adb1bb2..c127f16 100644 --- a/errors.go +++ b/errors.go @@ -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. @@ -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 } @@ -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 } @@ -104,7 +107,7 @@ 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) @@ -112,6 +115,10 @@ func (e ValidationError) withCause(err error) ValidationError { } func networkCause(err error) error { + if errors.Is(err, httpclient.ErrServerUnavailable) { + return ErrServerUnavailable + } + if errors.Is(err, httpclient.ErrRateLimited) { return ErrRateLimited } diff --git a/errors_test.go b/errors_test.go index d81c207..fe639ae 100644 --- a/errors_test.go +++ b/errors_test.go @@ -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}, diff --git a/internal/httpclient/httpclient.go b/internal/httpclient/httpclient.go index 3efa256..9041708 100644 --- a/internal/httpclient/httpclient.go +++ b/internal/httpclient/httpclient.go @@ -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") ) @@ -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) } diff --git a/internal/httpclient/httpclient_test.go b/internal/httpclient/httpclient_test.go index aae1e73..cace9d8 100644 --- a/internal/httpclient/httpclient_test.go +++ b/internal/httpclient/httpclient_test.go @@ -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) + } + }) + } +} diff --git a/network_errors_test.go b/network_errors_test.go index 504a240..a3066b0 100644 --- a/network_errors_test.go +++ b/network_errors_test.go @@ -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(): @@ -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) { @@ -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)) } @@ -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) + } + } + }) + } +} diff --git a/testdata/v0/invalid/network/urls_server_unavailable.yml b/testdata/v0/invalid/network/urls_server_unavailable.yml new file mode 100644 index 0000000..4c0641b --- /dev/null +++ b/testdata/v0/invalid/network/urls_server_unavailable.yml @@ -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