Added CODE_CONVENTIONS.md and linters to enforce it, and applied it across the codebase

CODE_CONVENTIONS.md sets out the conventions for Go code in this
repository: naming, layout, comments, errors, logging, configuration and
tests. .golangci.json enables the linters that check the parts that can be
checked (each limited to the rules the conventions use); the rest is
applied by hand.

Applied across the codebase:
- Naming: full-word names in application code, initialisms in one case
  (BuyerID, PrintJSON, PrintYAML, ocdsGetBuyerID), no names shadowing
  built-ins (min/max are minGap/maxGap), mustRaw renamed rawJSON as it
  returns nil rather than panicking, and config.ConfigLevelToLogLevel
  renamed LevelToLogLevel.
- Layout: lines kept to 80 characters where possible, assignments taken
  out of if and for statements that don't fit, wrapped arguments all on
  one line or one per line, steps separated by blank lines, no else after
  a return, function and struct literals wrapped.
- Comments: doc comments on every exported name (including each section's
  Map, Flatten, TypeOf, ValueOf and SetValue), section banners, British
  spelling.
- Errors: a created error starts with its package name, a wrapping error
  adds only what was being done, sentinels in one commented var block,
  errors.Is and errors.As in place of == and type assertions, and no
  err := shadowing of a named result. That fixes the mock server losing
  its access log's close error.
- Logging: the fetcher passes its workers an untagged logger, so
  findatender's lines are tagged with their own component rather than
  with fetcher's as well; cmd/mock-fts logs "stopped" with slog.
- Configuration: util.WithTimeout (moved from the websocket package)
  applies a timeout of 0 or less as no limit, used for the websocket
  write and ping, TCP close and tcpserver shutdown timeouts; every setting
  documents what 0 or empty means, including the rate limit rule's keys
  in internal/config/README.md.
- Tests: related tests merged into table-driven ones with named cases.

Separately from CODE_CONVENTIONS.md, internal/store/README.md gains a soft
SQL style convention for the queries in internal/store/queries.go, and the
queries are reformatted to follow it.
This commit is contained in:
bwilliams committed 2026-10-15 16:26:42 +01:00
1 parent 465358609a
commit 67215a6aaa
104 files changed
+3189 -1206

No files matched your search

+47 -36
View File
@@ -22,17 +22,17 @@ import (
// Errors returned when fetching from the API.
var (
// ErrNoNext means a release package has no next page link.
ErrNoNext = errors.New("no next link")
ErrNoNext = errors.New("findatender: no next link")
// ErrNoReleases means the API returned no releases.
ErrNoReleases = errors.New("no releases")
ErrNoReleases = errors.New("findatender: no releases")
// ErrRateLimitExceeded means the API refused a request with 429 Too Many
// Requests, and waiting for it was not allowed or did not help.
ErrRateLimitExceeded = errors.New("rate limit has been exceeded")
ErrRateLimitExceeded = errors.New("findatender: rate limit has been exceeded")
// ErrFetchCancelled means the fetch's context was cancelled while waiting
// out a rate limit.
ErrFetchCancelled = errors.New("fetch cancelled")
ErrFetchCancelled = errors.New("findatender: fetch cancelled")
// ErrUnexpectedStatus wraps an API response status other than 200 OK.
ErrUnexpectedStatus = errors.New("unexpected response status")
ErrUnexpectedStatus = errors.New("findatender: unexpected response status")
)
// RequestOptions selects the releases a fetch asks for.
@@ -95,7 +95,7 @@ func repairDates(raw json.RawMessage) (json.RawMessage, error) {
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return nil, errors.New(
"repairing dates: unexpected data after the JSON value",
"findatender: repairing dates: unexpected data after the JSON value",
)
}
@@ -106,8 +106,8 @@ func repairDates(raw json.RawMessage) (json.RawMessage, error) {
return json.Marshal(doc)
}
// recursiveRepairDates fixes date fields in value in place and reports whether it
// changed anything.
// recursiveRepairDates fixes date fields in value in place and reports whether
// it changed anything.
func recursiveRepairDates(value any) bool {
changed := false
switch typed := value.(type) {
@@ -155,10 +155,12 @@ func releaseIDs(raw json.RawMessage) (ocid, id string, err error) {
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber() // a numeric id keeps its exact digits
if token, err := decoder.Token(); err != nil {
token, err := decoder.Token()
if err != nil {
return "", "", fmt.Errorf("reading release: %w", err)
} else if token != json.Delim('{') {
return "", "", errors.New("reading release: not a JSON object")
}
if token != json.Delim('{') {
return "", "", errors.New("findatender: reading release: not a JSON object")
}
var haveOCID, haveID bool
@@ -205,7 +207,7 @@ func decodeReleaseID(decoder *json.Decoder) (string, error) {
case json.Number:
return typed.String(), nil
default:
return "", fmt.Errorf("reading release id: unexpected %T", typed)
return "", fmt.Errorf("findatender: reading release id: unexpected %T", typed)
}
}
@@ -213,11 +215,11 @@ func decodeReleaseID(decoder *json.Decoder) (string, error) {
func missingIDsError(haveOCID, haveID bool) error {
switch {
case !haveOCID && !haveID:
return errors.New("reading release: no ocid or id")
return errors.New("findatender: reading release: no ocid or id")
case !haveOCID:
return errors.New("reading release: no ocid")
return errors.New("findatender: reading release: no ocid")
default:
return errors.New("reading release: no id")
return errors.New("findatender: reading release: no id")
}
}
@@ -227,8 +229,7 @@ func missingIDsError(haveOCID, haveID bool) error {
//
// This method takes ownership of the response body and closes it when done.
func safeUnpackReleases(
logger *slog.Logger,
response *resty.Response,
logger *slog.Logger, response *resty.Response,
) (*ocds.ReleasePackage, error) {
var releasePackage safeReleasePackage
@@ -251,7 +252,8 @@ func safeUnpackReleases(
}
// Correct PublishedDate of "" and "2006-01-02"
if releasePackage.PublishedDate != nil && len(*releasePackage.PublishedDate) > 0 {
if releasePackage.PublishedDate != nil &&
*releasePackage.PublishedDate != "" {
published, err := time.Parse(time.RFC3339, *releasePackage.PublishedDate)
if err != nil {
published, err = time.Parse(time.DateOnly, *releasePackage.PublishedDate)
@@ -304,9 +306,9 @@ func closeBody(res *resty.Response) {
}
}
// fetchURI performs a single GET of uri, using findATender's context, and traces it at
// debug level. Unlike the method of the same name it does not check the
// response status.
// fetchURI performs a single GET of uri, using findATender's context, and
// traces it at debug level. Unlike the method of the same name it does not
// check the response status.
func fetchURI(findATender *FindATender, uri string) (*resty.Response, error) {
withTrace := findATender.config.Logging.LogLevel() <= slog.LevelDebug
logger := findATender.logger()
@@ -345,17 +347,21 @@ func logTrace(logger *slog.Logger, res *resty.Response) {
if logging.IsJSONHandler(logger.Handler()) {
trace = res.Request.TraceInfo().JSON()
}
logger.Debug("fetched", "trace", trace, "status", res.Status(), "response", res.String())
logger.Debug(
"fetched",
"trace", trace,
"status", res.Status(),
"response", res.String(),
)
}
// fetchURI performs a fetch against the API. If the API returns with a rate limit
// reached response and allowRateLimit is true, then wait and retry like a good
// client. If allowRateLimit is false, return to the caller informing them of
// the rate limit exceeded error. If, after waiting, the API still thinks we
// fetchURI performs a fetch against the API. If the API returns with a rate
// limit reached response and allowRateLimit is true, then wait and retry like a
// good client. If allowRateLimit is false, return to the caller informing them
// of the rate limit exceeded error. If, after waiting, the API still thinks we
// have exceeded the rate limit, bail out anyway.
func (ft *FindATender) fetchURI(
uri string,
allowRateLimit bool,
uri string, allowRateLimit bool,
) (*resty.Response, error) {
res, err := fetchURI(ft, uri)
if err != nil {
@@ -381,7 +387,10 @@ func (ft *FindATender) fetchURI(
}
retryAfter := time.Duration(retryAfterSeconds) * time.Second
ft.logger().Warn("api rate limit hit, waiting as asked", "retry_after", retryAfter)
ft.logger().Warn(
"api rate limit hit, waiting as asked",
"retry_after", retryAfter,
)
if rateSleep(ctx, retryAfter) != nil {
return nil, ErrFetchCancelled
}
@@ -430,10 +439,9 @@ func (ft *FindATender) fetchWithOpts(
// ErrNoNext if there is no "Next" link; the caller can decide whether asking
// for it was an error.
func (ft *FindATender) fetchNext(
releasePackage *ocds.ReleasePackage,
allowRateLimit bool,
releasePackage *ocds.ReleasePackage, allowRateLimit bool,
) (*resty.Response, error) {
if releasePackage.Links == nil || len(releasePackage.Links.Next) == 0 {
if releasePackage.Links == nil || releasePackage.Links.Next == "" {
return nil, ErrNoNext
}
return ft.fetchURI(releasePackage.Links.Next, allowRateLimit)
@@ -478,16 +486,19 @@ func (ft *FindATender) fetchAll(opts RequestOptions) ([]ocds.Release, error) {
// one cannot loop forever.
seen := make(map[string]bool)
for {
if releasePackage.Links != nil && len(releasePackage.Links.Next) > 0 {
if releasePackage.Links != nil && releasePackage.Links.Next != "" {
if seen[releasePackage.Links.Next] {
ft.logger().Warn("stopping at repeated next link", "link", releasePackage.Links.Next)
ft.logger().Warn(
"stopping at repeated next link",
"link", releasePackage.Links.Next,
)
break
}
seen[releasePackage.Links.Next] = true
}
res, err := ft.fetchNext(releasePackage, opts.AllowRateLimit)
if err == ErrNoNext {
if errors.Is(err, ErrNoNext) {
break
}
if err != nil {
@@ -506,4 +517,4 @@ func (ft *FindATender) fetchAll(opts RequestOptions) ([]ocds.Release, error) {
}
return releases, nil
}
}