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.
JobSearch
JobSearch is a service for scraping for contract opportunities. It is primarily a re-write of the existing nodeJS JobSearch codebase.
It currently fetches releases from the UK Government Find a Tender service (FTS), which publishes them in the OCDS format. A mock of the FTS API is included for development.
Building
scripts/build.sh # build/job-search-<version>
scripts/build.sh --release # also package release/job-search-<version>-<arch>.tar.gz
The build script runs go generate ./... and stamps the version from the
latest git tag. A build from untagged commits is marked as a development build
and isn't packaged unless --force is also given.
During development, go run -tags sqlite_fts5 ./cmd/jobsearch works as well.
The sqlite_fts5 tag is needed for the database's title search (see
Testing).
Configuration
Configuration is read from, in increasing priority:
- Built-in defaults
config.yamlin/etc/job-searchor the working directory, or the file given with--configJOBSEARCH_*environment variables, e.g.JOBSEARCH_LOGGING_LEVEL=debug
A .env file in the working directory is loaded into the environment first,
and must exist.
Example config.yaml:
logging:
level: info
file: /var/log/job-search.log
database:
file: /var/lib/job-search/jobsearch.db
sources:
find_a_tender:
enabled: true
interval: 10m
See internal/config for every key and how the configuration code works.
Usage
Global flags: --config/-c (config file), --debug/-d and
--quiet/-q (errors only).
| Command | Purpose |
|---|---|
job-search fetch service |
Poll every enabled source on its interval until stopped (Ctrl+C or SIGTERM) |
job-search fetch once |
Fetch from Find a Tender once and print the releases as JSON |
job-search config init [path] |
Create a config file |
job-search config show |
Print the configuration (--json or --yaml for those formats) |
job-search config get <key> |
Print one value, e.g. logging.level |
job-search config set <key> <value> |
Validate and write one value to the config file |
job-search config set --unset <key> |
Remove a value from the config file |
job-search migrate |
Apply every pending database migration (same as migrate up) |
job-search migrate up |
Apply pending migrations (--steps N for only N; --create to create a missing database file without asking) |
job-search migrate down --steps N |
Roll back the last N migrations (--steps 0 rolls back all of them, deleting all data, and needs --yes) |
job-search migrate status |
Show the database version and which migrations are applied or pending |
job-search version |
Print version information |
fetch service logs to logging.file if it's set, or to the terminal with
--foreground. Both fetch commands take --since "YYYY-MM-DD[ hh:mm:ss]".
fetch once can be limited with --planning, --opportunities or
--awards, and with --ignore-rate-limit it fails on a rate limit instead
of waiting.
The migrate commands work on the database in database.file. The store
refuses to open a database that isn't at this build's schema version, so run
job-search migrate after installing a new version.
Mock Find a Tender server
To develop without using the real API, run the mock and enable the fts_mock
source:
go run ./cmd/mock-fts --min-gap 5s --max-gap 10s --rate-limit 1000
sources:
fts_mock:
enabled: true
interval: 1m
api_root: http://localhost:8080/api/1.0
See internal/mock for its options and behaviour.
Project layout
| Path | Contents |
|---|---|
cmd/jobsearch |
The job-search command |
cmd/mock-fts |
The mock FTS server |
internal/cli |
Cobra commands and shared CLI setup |
internal/config |
Configuration loading, validation and editing |
internal/fetcher |
Runs a worker per enabled source |
internal/store |
SQLite storage of opportunities, and its migrations (see internal/store) |
internal/findatender |
FTS API client and conversion from OCDS to JobSearch types |
internal/types |
JobSearch's own opportunity types |
internal/util |
The periodic Worker used by the fetcher |
internal/logging |
slog setup and the HTTP access log |
internal/mock |
Mock external services |
internal/version |
Version information set at build time |
Testing
The store's title search needs SQLite's FTS5 module, which is only compiled in
with the sqlite_fts5 build tag, so tests (and lint) need it. Without it the
store tests fail with no such module: fts5.
go test -race -tags sqlite_fts5 ./internal/...
go test -tags sqlite_fts5 -coverprofile=cover.out ./internal/... && go tool cover -func=cover.out
golangci-lint run --build-tags sqlite_fts5 ./...
Tests don't need network access; HTTP calls go to local httptest servers.
Addition of a new opportunities source
Using a source called example as an illustration:
- Configuration section: create
internal/config/conf_source_example.go, copying an existing source such asconf_source_ftsmock.go:- Add a
JSCKSourceExample = "example"constant. - Define
JobSearchConfigSourceExample, embeddingJobSearchConfigSource(forenabledandinterval), plus any fields of its own withcfgand optionaldefaulttags, e.g.APIRoot string `cfg:"api_root"`. - Implement the
Sectioninterface (seeinternal/config/section.go): copy theMap,Flatten,TypeOf,ValueOfandSetValuemethods from an existing source, under a// ---------- Section methods (see Section) ----------banner, renaming the receiver type and using the new constant inFlatten.
- Add a
- Register the section: add
Example JobSearchConfigSourceExample `cfg:"example"`toJobSearchConfigSourcesininternal/config/conf_sources.go. Thecfgtag must match the constant. The source's keys (sources.example.*) are then loaded, validated and available to theconfigcommands with no further code. - Client package: create a package that fetches from the source and
returns
[]*types.Opportunity(seeinternal/types). If the source publishes OCDS,internal/findatendermay already be suitable, as it is forfts_mock: create it with the source's own API root. - Worker: create
internal/fetcher/worker_example.go, followingworker_ftsmock.go:runExample(ctx, conf, since)builds autil.Workerwith the source's name,conf.Sources.Example.Intervaland a task, then callsRun.- The task fetches everything since its
sinceargument. Wrap blocking calls inutil.AwaitTaskso shutdown isn't held up, and returnErrNoNewReleaseswhen nothing is found, so the checkpoint still moves forward. Any other error makes the next run retry from the same point.
- Start it: in
Runininternal/fetcher/fetcher.go, addif conf.Sources.Example.Enabled { start("Example", runExample) } - Tests:
TestSectionschecks the new section implementsSectionand that its keys match itscfgtag, with no changes needed. Ininternal/config/conf_sections_test.go, add the section toTestConcreteSourceSectionsand update the key count inTestSourcesSection. Test the client and worker usinghttptestservers rather than the real service. - Docs: add the source and its keys to the key table in
internal/config/README.md.
Installation of dev tools
A number of tools have been used in the development of the project. Installation
of these tools can be done using go install.
To install the tools:
go install github.com/spf13/cobra-cli@latest
go install git.avsdev.uk/Go/go-ocds/cmd/ocdsgen@latest
go install github.com/pressly/goose/v3/cmd/goose@latest
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest
goose creates new migration files (see internal/store); the migrations
themselves are applied by job-search migrate. golangci-lint uses the
project's .golangci.json.
Ensure that the GOBIN path ($HOME/go/bin) is added to the environment before running any of the tools.