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:
1 parent
465358609a
commit
67215a6aaa
104 files changed
+3189
-1206
No files matched your search
@@ -33,7 +33,8 @@ func WithLogger(logger *slog.Logger) Option {
|
||||
}
|
||||
|
||||
// logger returns the logger Run logs to: the given one, or slog.Default().
|
||||
// It isn't tagged here; each worker adds its source.
|
||||
// It isn't tagged here, as it is also given to the clients the workers
|
||||
// create, which add their own component; see tagged.
|
||||
func (opts options) logger() *slog.Logger {
|
||||
if opts.log == nil {
|
||||
return slog.Default()
|
||||
@@ -41,8 +42,15 @@ func (opts options) logger() *slog.Logger {
|
||||
return opts.log
|
||||
}
|
||||
|
||||
// runFunc runs one source's worker until ctx is cancelled, logging to
|
||||
// logger.
|
||||
// tagged returns logger tagged with the fetcher's component, for the lines
|
||||
// Run and its workers log themselves.
|
||||
func tagged(logger *slog.Logger) *slog.Logger {
|
||||
return logger.With("component", "fetcher")
|
||||
}
|
||||
|
||||
// runFunc runs one source's worker until ctx is cancelled. logger is
|
||||
// untagged: the worker tags its own lines with tagged, and passes logger as
|
||||
// it is to any client it creates.
|
||||
type runFunc func(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
@@ -68,7 +76,7 @@ func Run(
|
||||
for _, opt := range opts {
|
||||
opt(&settings)
|
||||
}
|
||||
logger := settings.logger().With("component", "fetcher")
|
||||
logger := settings.logger()
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
@@ -76,15 +84,16 @@ func Run(
|
||||
errs []error
|
||||
)
|
||||
|
||||
start := func(
|
||||
name string,
|
||||
run runFunc,
|
||||
) {
|
||||
start := func(name string, run runFunc) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := run(ctx, logger, conf, since); err != nil {
|
||||
logger.Error("source stopped, shutting down", "source", name, "error", err)
|
||||
tagged(logger).Error(
|
||||
"source stopped, shutting down",
|
||||
"source", name,
|
||||
"error", err,
|
||||
)
|
||||
mu.Lock()
|
||||
errs = append(errs, fmt.Errorf("%s: %w", name, err))
|
||||
mu.Unlock()
|
||||
@@ -104,5 +113,6 @@ func Run(
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// Keep worker and fetch log lines out of the test output.
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
slog.SetDefault(slog.New(slog.DiscardHandler))
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
@@ -38,18 +38,22 @@ const onePackage = `{
|
||||
const emptyPackage = `{"uri": "x", "releases": []}`
|
||||
|
||||
// ftsServer serves body (with status) for every request and counts requests.
|
||||
func ftsServer(t *testing.T, status int, body string) (*httptest.Server, *atomic.Int32) {
|
||||
func ftsServer(
|
||||
t *testing.T, status int, body string,
|
||||
) (*httptest.Server, *atomic.Int32) {
|
||||
t.Helper()
|
||||
var hits atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
if r.URL.Path != "/ocdsReleasePackages" {
|
||||
t.Errorf("unexpected path %q", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
io.WriteString(w, body)
|
||||
}))
|
||||
srv := httptest.NewServer(
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
if r.URL.Path != "/ocdsReleasePackages" {
|
||||
t.Errorf("unexpected path %q", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
io.WriteString(w, body)
|
||||
}),
|
||||
)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, &hits
|
||||
}
|
||||
@@ -83,7 +87,8 @@ func TestFetchFunctions(t *testing.T) {
|
||||
"nil",
|
||||
},
|
||||
{"no releases", http.StatusOK, emptyPackage, func(err error) bool {
|
||||
return errors.Is(err, ErrNoNewReleases) && errors.Is(err, util.ErrWorkerNoWork)
|
||||
return errors.Is(err, ErrNoNewReleases) &&
|
||||
errors.Is(err, util.ErrWorkerNoWork)
|
||||
}, "ErrNoNewReleases wrapping ErrWorkerNoWork"},
|
||||
{"bad body", http.StatusInternalServerError, "oops", func(err error) bool {
|
||||
return err != nil && !errors.Is(err, util.ErrWorkerNoWork)
|
||||
@@ -119,8 +124,11 @@ func TestFetchUsesConfiguredAPIRoot(t *testing.T) {
|
||||
|
||||
fetchFindAOpportunity(context.Background(), slog.Default(), conf, time.Time{})
|
||||
if fatHits.Load() != 1 || mockHits.Load() != 0 {
|
||||
t.Fatalf("FindAOpportunity hits: fat=%d mock=%d", fatHits.Load(), mockHits.Load())
|
||||
t.Fatalf(
|
||||
"FindAOpportunity hits: fat=%d mock=%d", fatHits.Load(), mockHits.Load(),
|
||||
)
|
||||
}
|
||||
|
||||
fetchFTSMock(context.Background(), slog.Default(), conf, time.Time{})
|
||||
if fatHits.Load() != 1 || mockHits.Load() != 1 {
|
||||
t.Fatalf("FTSMock hits: fat=%d mock=%d", fatHits.Load(), mockHits.Load())
|
||||
@@ -144,9 +152,12 @@ func TestFetchCancelled(t *testing.T) {
|
||||
|
||||
func TestSleepCancelled(t *testing.T) {
|
||||
for _, block := range []bool{false, true} {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
ctx, cancel := context.WithTimeout(
|
||||
context.Background(), 10*time.Millisecond,
|
||||
)
|
||||
defer cancel()
|
||||
if err := sleep(ctx, block, time.Hour); !errors.Is(err, context.DeadlineExceeded) {
|
||||
err := sleep(ctx, block, time.Hour)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("block=%v: err = %v, want context.DeadlineExceeded", block, err)
|
||||
}
|
||||
}
|
||||
@@ -198,7 +209,9 @@ func TestRunWorkersRejectZeroInterval(t *testing.T) {
|
||||
"Sleeper": runSleeper,
|
||||
}
|
||||
for name, run := range runs {
|
||||
if err := run(context.Background(), slog.Default(), conf, time.Time{}); err == nil {
|
||||
if err := run(
|
||||
context.Background(), slog.Default(), conf, time.Time{},
|
||||
); err == nil {
|
||||
t.Errorf("%s: expected an error for a zero interval", name)
|
||||
}
|
||||
}
|
||||
@@ -228,7 +241,9 @@ func TestRunLogsSourceErrors(t *testing.T) {
|
||||
t.Errorf("returned error %v; want it to include %s", err, name)
|
||||
}
|
||||
}
|
||||
if n := strings.Count(buf.String(), "interval must be greater than 0"); n != 3 {
|
||||
if n := strings.Count(
|
||||
buf.String(), "interval must be greater than 0",
|
||||
); n != 3 {
|
||||
t.Errorf("logged %d interval errors; want 3: %s", n, &buf)
|
||||
}
|
||||
}
|
||||
@@ -236,11 +251,14 @@ func TestRunLogsSourceErrors(t *testing.T) {
|
||||
func TestRunNoSourcesEnabled(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
if err := Run(context.Background(), &config.JobSearchConfig{}, time.Time{}); err != nil {
|
||||
if err := Run(
|
||||
context.Background(), &config.JobSearchConfig{}, time.Time{},
|
||||
); err != nil {
|
||||
t.Errorf("Run = %v; want nil", err)
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
@@ -275,6 +293,7 @@ func TestRunShutsDownOnWorkerError(t *testing.T) {
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run did not shut down after a worker failed")
|
||||
}
|
||||
|
||||
// FTSMock either polled once before the shutdown or never started a run.
|
||||
if n := mockHits.Load(); n > 1 {
|
||||
t.Errorf("FTSMock polled %d times; want at most 1", n)
|
||||
@@ -307,7 +326,9 @@ func TestRunEnabledSources(t *testing.T) {
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for fatHits.Load() == 0 || mockHits.Load() == 0 {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("sources not polled: fat=%d mock=%d", fatHits.Load(), mockHits.Load())
|
||||
t.Fatalf(
|
||||
"sources not polled: fat=%d mock=%d", fatHits.Load(), mockHits.Load(),
|
||||
)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ func runFindAOpportunity(
|
||||
since time.Time,
|
||||
) error {
|
||||
worker := util.Worker{
|
||||
Logger: logger,
|
||||
Logger: tagged(logger),
|
||||
Name: "FindAOpportunity",
|
||||
Interval: conf.Sources.FindATender.Interval,
|
||||
Task: func(ctx context.Context, since time.Time) error {
|
||||
@@ -40,15 +40,16 @@ func fetchFindAOpportunity(
|
||||
conf *config.JobSearchConfig,
|
||||
since time.Time,
|
||||
) error {
|
||||
opportunities, err := util.AwaitTask(ctx, func() ([]*types.Opportunity, error) {
|
||||
findATender := findatender.New(
|
||||
conf,
|
||||
conf.Sources.FindATender.APIRoot,
|
||||
findatender.WithLogger(logger),
|
||||
)
|
||||
defer findATender.Shutdown()
|
||||
return findATender.With(ctx).FetchAll(since, true)
|
||||
})
|
||||
opportunities, err := util.AwaitTask(
|
||||
ctx,
|
||||
func() ([]*types.Opportunity, error) {
|
||||
findATender := findatender.New(
|
||||
conf, conf.Sources.FindATender.APIRoot, findatender.WithLogger(logger),
|
||||
)
|
||||
defer findATender.Shutdown()
|
||||
return findATender.With(ctx).FetchAll(since, true)
|
||||
},
|
||||
)
|
||||
if errors.Is(err, findatender.ErrNoReleases) {
|
||||
return ErrNoNewReleases
|
||||
}
|
||||
@@ -56,7 +57,7 @@ func fetchFindAOpportunity(
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Info("fetched opportunities", "count", len(opportunities))
|
||||
tagged(logger).Info("fetched opportunities", "count", len(opportunities))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -21,7 +21,7 @@ func runFTSMock(
|
||||
since time.Time,
|
||||
) error {
|
||||
worker := util.Worker{
|
||||
Logger: logger,
|
||||
Logger: tagged(logger),
|
||||
Name: "FTSMock",
|
||||
Interval: conf.Sources.FTSMock.Interval,
|
||||
Task: func(ctx context.Context, since time.Time) error {
|
||||
@@ -40,15 +40,16 @@ func fetchFTSMock(
|
||||
conf *config.JobSearchConfig,
|
||||
since time.Time,
|
||||
) error {
|
||||
opportunities, err := util.AwaitTask(ctx, func() ([]*types.Opportunity, error) {
|
||||
findATender := findatender.New(
|
||||
conf,
|
||||
conf.Sources.FTSMock.APIRoot,
|
||||
findatender.WithLogger(logger),
|
||||
)
|
||||
defer findATender.Shutdown()
|
||||
return findATender.With(ctx).FetchAll(since, true)
|
||||
})
|
||||
opportunities, err := util.AwaitTask(
|
||||
ctx,
|
||||
func() ([]*types.Opportunity, error) {
|
||||
findATender := findatender.New(
|
||||
conf, conf.Sources.FTSMock.APIRoot, findatender.WithLogger(logger),
|
||||
)
|
||||
defer findATender.Shutdown()
|
||||
return findATender.With(ctx).FetchAll(since, true)
|
||||
},
|
||||
)
|
||||
if errors.Is(err, findatender.ErrNoReleases) {
|
||||
return ErrNoNewReleases
|
||||
}
|
||||
@@ -56,7 +57,7 @@ func fetchFTSMock(
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Info("fetched opportunities", "count", len(opportunities))
|
||||
tagged(logger).Info("fetched opportunities", "count", len(opportunities))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -22,15 +22,14 @@ func runSleeper(
|
||||
) error {
|
||||
blockShutdown := conf.Sources.Sleeper.BlockShutdown
|
||||
worker := util.Worker{
|
||||
Logger: logger,
|
||||
Logger: tagged(logger),
|
||||
Name: "Sleeper",
|
||||
Interval: conf.Sources.Sleeper.Interval,
|
||||
Task: func(taskCtx context.Context, since time.Time) error {
|
||||
if blockShutdown {
|
||||
return sleep(taskCtx, true, sleepDuration)
|
||||
} else {
|
||||
return sleep(ctx, false, sleepDuration)
|
||||
}
|
||||
return sleep(ctx, false, sleepDuration)
|
||||
},
|
||||
}
|
||||
return worker.Run(ctx, since)
|
||||
@@ -47,8 +46,10 @@ func sleep(
|
||||
time.Sleep(duration)
|
||||
return nil
|
||||
}
|
||||
|
||||
timer := time.NewTimer(duration)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-timer.C:
|
||||
return nil
|
||||
|
||||
Reference in new issue
Block a user