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

+66 -36
View File
@@ -22,17 +22,17 @@ import (
// Store keeps every release in memory and appends each new one to a JSON Lines
// file, so releases survive restarts. Releases are kept in date order.
type Store struct {
mu sync.RWMutex
f *os.File
releases []ocds.Release
times []time.Time
latest map[string]int // ocid -> index of its most recent release
lastNum map[int]int // year -> highest notice number used
mu sync.RWMutex
file *os.File
releases []ocds.Release
times []time.Time
latest map[string]int // ocid -> index of its most recent release
lastNumber map[int]int // year -> highest notice number used
// Procedures not yet awarded, as a slice plus positions so that adding,
// removing and picking one at random are all constant time.
open []string
openPos map[string]int
open []string
openPosition map[string]int
opts options
}
@@ -44,11 +44,12 @@ type Store struct {
// It logs to slog.Default() unless given WithLogger.
func OpenStore(path string, opts ...Option) (*Store, error) {
store := &Store{
latest: map[string]int{},
lastNum: map[int]int{},
openPos: map[string]int{},
opts: applyOptions(opts),
latest: map[string]int{},
lastNumber: map[int]int{},
openPosition: map[string]int{},
opts: applyOptions(opts),
}
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
return nil, err
}
@@ -57,6 +58,7 @@ func OpenStore(path string, opts ...Option) (*Store, error) {
if err != nil {
return nil, err
}
// The file is written in order, but sort anyway in case it was hand-edited.
sort.SliceStable(releases, func(i, other int) bool {
return releases[i].Date.Before(releases[other].Date)
@@ -69,9 +71,10 @@ func OpenStore(path string, opts ...Option) (*Store, error) {
store.index(i, release)
}
if store.f, err = openForAppend(path); err != nil {
if store.file, err = openForAppend(path); err != nil {
return nil, err
}
return store, nil
}
@@ -106,6 +109,7 @@ func readReleases(logger *slog.Logger, path string) ([]ocds.Release, error) {
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("reading %s: %w", path, err)
}
return releases, nil
}
@@ -113,18 +117,25 @@ func readReleases(logger *slog.Logger, path string) ([]ocds.Release, error) {
// mid-write, it ends the partial record so the next one starts on a fresh
// line.
func openForAppend(path string) (*os.File, error) {
file, err := os.OpenFile(filepath.Clean(path), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0o600)
file, err := os.OpenFile(
filepath.Clean(path), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0o600,
)
if err != nil {
return nil, err
}
if info, err := file.Stat(); err == nil && info.Size() > 0 {
last := make([]byte, 1)
if _, err := file.ReadAt(last, info.Size()-1); err == nil && last[0] != '\n' {
_, readErr := file.ReadAt(last, info.Size()-1)
if readErr == nil && last[0] != '\n' {
if _, err := file.Write([]byte("\n")); err != nil {
return nil, errors.Join(fmt.Errorf("repairing %s: %w", path, err), file.Close())
return nil, errors.Join(
fmt.Errorf("repairing %s: %w", path, err), file.Close(),
)
}
}
}
return file, nil
}
@@ -133,51 +144,58 @@ func openForAppend(path string) (*os.File, error) {
// highest notice number used each year.
func (s *Store) index(i int, release ocds.Release) {
s.latest[release.OCID] = i
if len(release.Tag) > 0 && release.Tag[0] == "award" {
s.closeProcedure(release.OCID)
} else if _, ok := s.openPos[release.OCID]; !ok {
s.openPos[release.OCID] = len(s.open)
} else if _, ok := s.openPosition[release.OCID]; !ok {
s.openPosition[release.OCID] = len(s.open)
s.open = append(s.open, release.OCID)
}
if numberText, year, ok := strings.Cut(release.ID, "-"); ok {
number, numberErr := strconv.Atoi(numberText)
yearNumber, yearErr := strconv.Atoi(year)
if numberErr == nil && yearErr == nil && number > s.lastNum[yearNumber] {
s.lastNum[yearNumber] = number
if numberErr == nil && yearErr == nil && number > s.lastNumber[yearNumber] {
s.lastNumber[yearNumber] = number
}
}
}
// closeProcedure removes ocid from the open procedures, if it is there.
func (s *Store) closeProcedure(ocid string) {
position, ok := s.openPos[ocid]
position, ok := s.openPosition[ocid]
if !ok {
return
}
last := len(s.open) - 1
s.open[position] = s.open[last]
s.openPos[s.open[position]] = position
s.openPosition[s.open[position]] = position
s.open = s.open[:last]
delete(s.openPos, ocid)
delete(s.openPosition, ocid)
}
// Append persists a release and flushes it to disk.
func (s *Store) Append(release ocds.Release) error { return s.append(release, true) }
func (s *Store) Append(release ocds.Release) error {
return s.append(release, true)
}
// AppendNoSync persists a release without an fsync; call Sync afterwards.
// Used for bulk catch-up, where a sync per record would be very slow.
func (s *Store) AppendNoSync(release ocds.Release) error { return s.append(release, false) }
func (s *Store) AppendNoSync(release ocds.Release) error {
return s.append(release, false)
}
// Sync flushes appended releases to disk. Call it after AppendNoSync.
func (s *Store) Sync() error {
s.mu.Lock()
defer s.mu.Unlock()
return s.f.Sync()
return s.file.Sync()
}
// append stores release, syncing the file to disk if sync is true. A date earlier
// than the newest stored release (for example after a clock change) is moved
// up so the order stays valid.
// append stores release, syncing the file to disk if sync is true. A date
// earlier than the newest stored release (for example after a clock change) is
// moved up so the order stays valid.
func (s *Store) append(release ocds.Release, sync bool) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -186,27 +204,34 @@ func (s *Store) append(release ocds.Release, sync bool) error {
if count := len(s.times); count > 0 && release.Date.Before(s.times[count-1]) {
release.Date = s.times[count-1]
}
data, err := json.Marshal(release)
if err != nil {
return err
}
if _, err := s.f.Write(append(data, '\n')); err != nil {
if _, err := s.file.Write(append(data, '\n')); err != nil {
return err
}
if sync {
if err := s.f.Sync(); err != nil {
if err := s.file.Sync(); err != nil {
return err
}
}
s.releases = append(s.releases, release)
s.times = append(s.times, release.Date)
s.index(len(s.releases)-1, release)
return nil
}
// Page returns up to limit releases dated in [from, upper], starting no earlier
// than position start, plus the position to continue from and whether more exist.
func (s *Store) Page(from, upper time.Time, start, limit int) ([]ocds.Release, int, bool) {
// than position start, plus the position to continue from and whether more
// exist.
func (s *Store) Page(
from, upper time.Time,
start, limit int,
) ([]ocds.Release, int, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
@@ -216,12 +241,15 @@ func (s *Store) Page(from, upper time.Time, start, limit int) ([]ocds.Release, i
if start > i {
i = start
}
out := make([]ocds.Release, 0, limit)
for i < len(s.releases) && len(out) < limit && !s.times[i].After(upper) {
out = append(out, s.releases[i])
i++
}
more := i < len(s.releases) && !s.times[i].After(upper)
return out, i, more
}
@@ -255,13 +283,15 @@ func (s *Store) HasOCID(ocid string) bool {
func (s *Store) NextNoticeID(year int) string {
s.mu.RLock()
defer s.mu.RUnlock()
return fmt.Sprintf("%06d-%d", s.lastNum[year]+1, year)
return fmt.Sprintf("%06d-%d", s.lastNumber[year]+1, year)
}
// RandomOpen picks a procedure that has not been awarded and whose latest
// release is after since. Procedures idle since before then are dropped from
// the open set, as if they had been abandoned.
func (s *Store) RandomOpen(rng *rand.Rand, since time.Time) (ocds.Release, bool) {
func (s *Store) RandomOpen(
rng *rand.Rand, since time.Time,
) (ocds.Release, bool) {
s.mu.Lock()
defer s.mu.Unlock()
for len(s.open) > 0 {
@@ -279,5 +309,5 @@ func (s *Store) RandomOpen(rng *rand.Rand, since time.Time) (ocds.Release, bool)
func (s *Store) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
return s.f.Close()
return s.file.Close()
}