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

+5 -1
View File
@@ -12,15 +12,19 @@ import (
func TestCommandTree(t *testing.T) {
root := newRootCmd()
var names []string
for _, c := range root.Commands() {
names = append(names, c.Name())
}
for _, want := range []string{"config", "fetch", "migrate", "version", "wsserve"} {
commands := []string{"config", "fetch", "migrate", "version", "wsserve"}
for _, want := range commands {
if !slices.Contains(names, want) {
t.Errorf("job-search has no %q command; has %v", want, names)
}
}
for _, flag := range []string{"config", "debug", "quiet"} {
if root.PersistentFlags().Lookup(flag) == nil {
t.Errorf("job-search has no --%s flag", flag)
+52 -30
View File
@@ -52,7 +52,7 @@ type options struct {
rateWindow time.Duration
accessLogPath string
logFormat string
tz string
timeZone string
}
const longHelp = `Mock of the Find a Tender (FTS) OCDS release package endpoint:
@@ -170,10 +170,19 @@ func newRootCmd() *cobra.Command {
"maximum time between generated releases",
)
flags.IntVar(&opts.rateLimit, "rate-limit", 12, "requests allowed per window per client")
flags.DurationVar(&opts.rateWindow, "rate-window", 5*time.Minute, "rate limit window length")
flags.IntVar(
&opts.rateLimit, "rate-limit", 12, "requests allowed per window per client",
)
flags.DurationVar(
&opts.rateWindow, "rate-window", 5*time.Minute, "rate limit window length",
)
flags.StringVar(&opts.accessLogPath, "access-log", "-", `access log file, or "-" for stdout`)
flags.StringVar(
&opts.accessLogPath,
"access-log",
"-",
`access log file, or "-" for stdout`,
)
flags.StringVar(
&opts.logFormat,
"log-format",
@@ -181,7 +190,7 @@ func newRootCmd() *cobra.Command {
`access log format: "combined" or "common"`,
)
flags.StringVar(
&opts.tz,
&opts.timeZone,
"tz",
"Europe/London",
`time zone for updatedFrom/updatedTo without an offset ("Local" for this machine's)`,
@@ -193,34 +202,40 @@ func newRootCmd() *cobra.Command {
// validate checks flag values before anything is started.
func (o *options) validate() error {
if o.logFormat != "combined" && o.logFormat != "common" {
return fmt.Errorf(`--log-format must be "combined" or "common", got %q`, o.logFormat)
return fmt.Errorf(
`--log-format must be "combined" or "common", got %q`, o.logFormat,
)
}
if o.minGap <= 0 || o.maxGap < o.minGap {
return errors.New("--min-gap must be positive and no larger than --max-gap")
}
if o.rateLimit < 1 || o.rateWindow <= 0 {
return errors.New("--rate-limit must be at least 1 and --rate-window positive")
return errors.New(
"--rate-limit must be at least 1 and --rate-window positive",
)
}
if _, err := time.LoadLocation(o.tz); err != nil {
if _, err := time.LoadLocation(o.timeZone); err != nil {
return fmt.Errorf("--tz: %w", err)
}
return nil
}
// run starts the mock and blocks until ctx is cancelled or the server fails.
func run(ctx context.Context, opts *options) (err error) {
location, err := time.LoadLocation(opts.tz) // already validated
location, err := time.LoadLocation(opts.timeZone) // already validated
if err != nil {
return fmt.Errorf("--tz: %w", err)
}
if err := os.MkdirAll(opts.dataDir, 0o750); err != nil {
return err
if err = os.MkdirAll(opts.dataDir, 0o750); err != nil {
return fmt.Errorf("creating data directory: %w", err)
}
// ---------- catalog ----------
// Load the catalog.
catalog, err := mock.LoadCatalog()
if err != nil {
return err
return fmt.Errorf("loading catalog: %w", err)
}
slog.Info(
"catalog loaded",
@@ -231,27 +246,30 @@ func run(ctx context.Context, opts *options) (err error) {
"classifications", len(catalog.Classifications),
)
// ---------- store ----------
// Open (or reset) the store.
storePath := filepath.Join(opts.dataDir, mock.ReleasesFile)
if opts.reset {
if err := os.Remove(storePath); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
if err = os.Remove(storePath); err != nil &&
!errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("resetting store: %w", err)
}
slog.Info("store reset", "path", storePath)
}
store, err := mock.OpenStore(storePath)
if err != nil {
return err
return fmt.Errorf("opening store: %w", err)
}
defer func() {
err = errors.Join(err, store.Close())
}()
// ---------- generator ----------
// Backfill releases, then keep generating them.
generator := mock.NewGenerator(catalog, store, time.Now().UnixNano())
generated, err := generator.CatchUp(time.Now(), opts.backfill, opts.minGap, opts.maxGap)
generated, err := generator.CatchUp(
time.Now(), opts.backfill, opts.minGap, opts.maxGap,
)
if err != nil {
return err
return fmt.Errorf("backfilling releases: %w", err)
}
slog.Info("store ready", "releases", store.Len(), "generated", generated)
@@ -267,10 +285,11 @@ func run(ctx context.Context, opts *options) (err error) {
generator.Run(ctx, opts.minGap, opts.maxGap)
}()
// ---------- HTTP ----------
// Serve the API.
out := os.Stdout
if opts.accessLogPath != "-" {
logFile, err := os.OpenFile(
var logFile *os.File
logFile, err = os.OpenFile(
opts.accessLogPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600,
)
if err != nil {
@@ -288,12 +307,15 @@ func run(ctx context.Context, opts *options) (err error) {
rateLimiter := mock.NewRateLimiter(opts.rateLimit, opts.rateWindow)
mux := http.NewServeMux()
mux.HandleFunc(
mock.BasePath, rateLimiter.Middleware(mock.NewHandler(store, opts.baseURL, location)),
mock.BasePath,
rateLimiter.Middleware(mock.NewHandler(store, opts.baseURL, location)),
)
httpSrv := &http.Server{
Addr: opts.addr,
Handler: logging.AccessLog(accessLogger, opts.logFormat == "combined", mux),
httpServer := &http.Server{
Addr: opts.addr,
Handler: logging.AccessLog(
accessLogger, opts.logFormat == "combined", mux,
),
ReadHeaderTimeout: 10 * time.Second,
}
go func() {
@@ -303,7 +325,7 @@ func run(ctx context.Context, opts *options) (err error) {
context.WithoutCancel(ctx), 5*time.Second,
)
defer cancelShutdown()
if err := httpSrv.Shutdown(shutdownCtx); err != nil {
if err := httpServer.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown failed", "error", err)
}
}()
@@ -314,15 +336,15 @@ func run(ctx context.Context, opts *options) (err error) {
"path", mock.BasePath,
"time_zone", location.String(),
)
serveErr := httpSrv.ListenAndServe()
serveErr := httpServer.ListenAndServe()
cancel() // stop the worker (and the shutdown goroutine) if the server failed
<-workerDone
if serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
return serveErr
return fmt.Errorf("serving: %w", serveErr)
}
log.Print("stopped")
slog.Info("stopped")
return nil
}