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
1 change: 1 addition & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ linters:
# Test tables and helpers follow the existing test layout.
- path: _test\.go$
linters:
- dupl
- paralleltest
- lll
- wsl_v5
Expand Down
57 changes: 55 additions & 2 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,29 @@ package publiccode

import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"slices"
"strings"

"github.com/publiccodeyml/libpubliccode/v5/internal/httpclient"
)

// Causes of a failed network check. A [ValidationError] that reports an
// unreachable URL, logo or screenshot unwraps to one of them when the check
// failed for a reason that says nothing about the value, so callers can
// tell it apart with errors.Is and try the file again later.
// [ValidationResults] does not unwrap, so check each of its elements.
var (
// ErrRateLimited means the server kept rate limiting the request, with
// a 429 or a rate limit 403, after the parser's retries.
ErrRateLimited = errors.New("rate limited")
// ErrTimeout means the request did not complete within the parser's
// timeout or the caller's deadline.
ErrTimeout = errors.New("timed out")
)

// ParseError is generic parse error.
Expand All @@ -32,6 +49,9 @@ type ValidationError struct {
Description string `json:"description"`
Line int `json:"line"`
Column int `json:"column"`

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

func (e ValidationError) Error() string {
Expand All @@ -43,6 +63,12 @@ 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.
func (e ValidationError) Unwrap() error {
return e.cause
}

func (e ValidationError) MarshalJSON() ([]byte, error) {
type Ve ValidationError

Expand Down Expand Up @@ -72,6 +98,33 @@ func newValidationErrorf(key string, description string, args ...any) Validation
return newValidationError(key, fmt.Sprintf(description, args...))
}

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

return e
}

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

if errors.Is(err, context.DeadlineExceeded) {
return ErrTimeout
}

if timeout, ok := errors.AsType[interface {
error
Timeout() bool
}](err); ok && timeout.Timeout() {
return ErrTimeout
}

return nil
}

// ValidationWarning reports a condition that does not make a publiccode.yml file
// invalid, such as use of a deprecated field. It implements error so it can be
// returned alongside [ValidationError] values in [ValidationResults].
Expand Down Expand Up @@ -162,7 +215,7 @@ func position(err error) (int, int) {
// newUnreachableError reports that the URL in key did not answer. err
// gives the cause and does not name the URL, so the URL appears once.
func newUnreachableError(key string, u *URL, err error) ValidationError {
return newValidationErrorf(key, "'%s' not reachable: %s", (*url.URL)(u).String(), err.Error())
return newValidationErrorf(key, "'%s' not reachable: %s", (*url.URL)(u).String(), err.Error()).withCause(err)
}

// newNotImageError reports that the file value in key is not an image.
Expand All @@ -173,5 +226,5 @@ func newNotImageError(key string, value string, err error) ValidationError {
err = dlErr.Err
}

return newValidationErrorf(key, "'%s' is not an image: %s", value, err.Error())
return newValidationErrorf(key, "'%s' is not an image: %s", value, err.Error()).withCause(err)
}
25 changes: 25 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package publiccode

import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"testing"

"github.com/publiccodeyml/libpubliccode/v5/internal/httpclient"
)

func TestParseErrorError(t *testing.T) {
Expand Down Expand Up @@ -181,3 +185,24 @@ func TestValidationResultsHasErrors(t *testing.T) {
})
}
}

func TestNetworkCause(t *testing.T) {
for _, tc := range []struct {
name string
err error
want error
}{
{"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},
{"not found", fmt.Errorf("downloading: %w", httpclient.ErrNotFound), nil},
{"refused", &net.OpError{Op: "dial", Err: errors.New("connection refused")}, nil},
{"nil", nil, nil},
} {
t.Run(tc.name, func(t *testing.T) {
if got := newValidationError("url", "not reachable").withCause(tc.err).Unwrap(); !errors.Is(got, tc.want) {
t.Errorf("Unwrap() = %v, want %v", got, tc.want)
}
})
}
}
6 changes: 3 additions & 3 deletions fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func validateFieldsV0(publiccode PublicCode, parser *Parser, network bool, baseU
if u != nil {
validLogo, err := parser.validLogo(*u, network)
if !validLogo {
vr = append(vr, newValidationError("logo", err.Error()))
vr = append(vr, newValidationError("logo", err.Error()).withCause(err))
}
}
}
Expand All @@ -77,7 +77,7 @@ func validateFieldsV0(publiccode PublicCode, parser *Parser, network bool, baseU
if u != nil {
validLogo, err := parser.validLogo(*u, network)
if !validLogo {
vr = append(vr, newValidationError("monochromeLogo", err.Error()))
vr = append(vr, newValidationError("monochromeLogo", err.Error()).withCause(err))
}
}
}
Expand Down Expand Up @@ -384,7 +384,7 @@ func validateFieldsV1(publiccode PublicCode, parser *Parser, network bool, baseU
if u != nil {
validLogo, err := parser.validLogo(*u, network)
if !validLogo {
vr = append(vr, newValidationError("logo", err.Error()))
vr = append(vr, newValidationError("logo", err.Error()).withCause(err))
}
}
}
Expand Down
161 changes: 161 additions & 0 deletions network_errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package publiccode

import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

func TestFailedNetworkChecksUnwrapToTheirCause(t *testing.T) {
release := make(chan struct{})

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/rate-limited":
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
case "/stalled":
select {
case <-r.Context().Done():
case <-release:
}
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(srv.Close)
t.Cleanup(func() { close(release) })

content := validPubliccode(t)
for old, path := range map[string]string{
`url: "https://github.com/italia/developers.italia.it.git"`: `url: "` + srv.URL + `/repository"`,
`landingURL: "https://developers.italia.it"`: `landingURL: "` + srv.URL + `/rate-limited"`,
`roadmap: "https://designers.italia.it/roadmap/"`: `roadmap: "` + srv.URL + `/stalled"`,
} {
if !bytes.Contains(content, []byte(old)) {
t.Fatalf("fixture has no %s", old)
}

content = bytes.Replace(content, []byte(old), []byte(path), 1)
}

content = bytes.Replace(content,
[]byte(`documentation: "https://raw.githubusercontent.com/`),
[]byte(`documentation: "`+srv.URL+`/missing/`), 1)

p, err := NewParser(ParserConfig{
BaseURL: "testdata/v0/valid/",
Timeout: 500 * time.Millisecond,
AllowNetworkToPrivateHosts: true,
})
if err != nil {
t.Fatal(err)
}

_, err = p.ParseStream(bytes.NewReader(content))

vr, ok := errors.AsType[ValidationResults](err)
if !ok {
t.Fatalf("got %v, want ValidationResults", err)
}

want := map[string]error{
"landingURL": ErrRateLimited,
"roadmap": ErrTimeout,
"description.en.documentation": nil,
}

for key, cause := range want {
found := false

for _, result := range vr {
valErr, ok := errors.AsType[ValidationError](result)
if !ok || valErr.Key != key || !strings.Contains(valErr.Description, "not reachable") {
continue
}

found = true

if got := valErr.Unwrap(); !errors.Is(got, cause) {
t.Errorf("%s: Unwrap() = %v, want %v", key, got, cause)
}

if cause != nil && !errors.Is(result, cause) {
t.Errorf("%s: errors.Is(%v, %v) = false", key, result, cause)
}

if errors.Is(result, ErrRateLimited) && !errors.Is(cause, ErrRateLimited) {
t.Errorf("%s: %v matches ErrRateLimited", key, result)
}
}

if !found {
t.Errorf("no unreachable error for %s in:\n%v", key, vr)
}
}
}

func TestLogoNetworkChecksUnwrapToTheirCause(t *testing.T) {
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/rate-limited.png" {
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)

return
}
select {
case <-r.Context().Done():
case <-release:
}
}))
t.Cleanup(srv.Close)
t.Cleanup(func() { close(release) })

for _, tc := range []struct {
name string
path string
cause error
}{
{"rate limited", "/rate-limited.png", ErrRateLimited},
{"timeout", "/stalled.png", ErrTimeout},
} {
t.Run(tc.name, func(t *testing.T) {
p, err := NewParser(ParserConfig{
BaseURL: srv.URL + "/",
Timeout: 50 * time.Millisecond,
AllowNetworkToPrivateHosts: true,
})
if err != nil {
t.Fatal(err)
}
content := "publiccodeYmlVersion: '0.8'\nlogo: " + srv.URL + tc.path +
"\nmonochromeLogo: " + srv.URL + tc.path + "\n"
_, err = p.ParseStream(strings.NewReader(content))
vr, ok := errors.AsType[ValidationResults](err)
if !ok {
t.Fatalf("got %v, want ValidationResults", err)
}
for _, key := range []string{"logo", "monochromeLogo"} {
found := false
for _, result := range vr {
valErr, ok := errors.AsType[ValidationError](result)
if !ok || valErr.Key != key {
continue
}
found = true
if !errors.Is(result, tc.cause) {
t.Errorf("%s: errors.Is(%v, %v) = false", key, result, tc.cause)
}
}
if !found {
t.Errorf("no validation error for %s in %v", key, vr)
}
}
})
}
}
2 changes: 1 addition & 1 deletion parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ func (p *Parser) parseAndValidate(in io.Reader, fileURL *url.URL) (PublicCode, e
Description: fmt.Sprintf("failed to get raw URL for code repository at %s: %s", publiccode.Url(), err),
Line: line,
Column: column,
})
}.withCause(err))

// Return early because proceeding with no base URL would result in a lot
// of duplicate errors stemming from its absence.
Expand Down
2 changes: 1 addition & 1 deletion parser_extra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ func TestParseStreamVersion06(t *testing.T) {
t.Fatal("expected a parsed document")
}
expected := ValidationResults{
ValidationWarning{"", "publiccodeYmlVersion", "v" + version + " is not the latest version, use '0'. Parsing this file as v0.8.", 1, 1},
ValidationWarning{Key: "publiccodeYmlVersion", Description: "v" + version + " is not the latest version, use '0'. Parsing this file as v0.8.", Line: 1, Column: 1},
}
if !reflect.DeepEqual(err, expected) {
t.Fatalf("unexpected diagnostics: got %#v, want %#v", err, expected)
Expand Down
Loading