Code standard
How Hardcount code differs from standard practice. For the rest we follow Effective Go, Go Code Review Comments, and the React and TanStack Query docs.
New and changed code follows this page. Older code does not all follow it yet; small cleanup PRs bring it in line. A change to money or a billing state also follows the money-path playbook.
Go rules a tool checks
Section titled “Go rules a tool checks”CI runs these. forbidigo and nolintlint are linters in .. The rest are tests in internal/, and each top comment says how to pass.
- In the billing packages, time comes from the clock, not
time.:Now() s.in a service,clock. Now(ctx) clock.in a store. So one piece of work reads one time, and a test can fix it.Now(ctx) .lists the packages. (forbidigo)golangci. yml - Production code binds a real instant only by reading a clock:
clock., orEnsureEffectiveNow clock.for a payment’s result.AtArrival clock.is for tests; a place that must name an instant says why:WithEffectiveNow //. (forbidigo)nolint:forbidigo // real-instant: <reason> - A lint waiver names its linter and a reason:
//. (nolintlint)nolint:forbidigo // wall-clock: <reason> - A calendar date shown to a person is formatted in a named time zone:
t.. A real UTC or filename format carries a same-lineIn(loc). Format(... ) //tz:ok. (civil_)date_ timezone_ test. go internal/writes every error response and decodes every request body Hardcount defines. Return anapi/ respond errs., andDomainError respond.picks the status and error code. (FromError error_,writes_ test. go respond_; request bodies:error_ args_ test. go internal/)api/ strict_ bodies_ integration_ test. go - The SQL behind a list route has no fixed
LIMIT: it takeslimitandoffsetfromrespond.. (ParsePage sql_)row_ caps_ test. go - Every setting the code reads has a row in Settings reference, and the ones
config.owns are read only inLoad internal/. (config settings_,doc_ test. go config_)env_ reads_ test. go
Go rules checked in review
Section titled “Go rules checked in review”Money, tenants and the API
Section titled “Money, tenants and the API”- Money is
int64cents, in a field named..._. Never a float, even to print it. Round withcents internal/, which rounds half to even.platform/ money - Tenant data goes through a tenant transaction:
db.. The exceptions are in Architecture.BeginTx(ctx, postgres. TxTenant, tenantID) - API JSON fields are
snake_, and an ID carries its type:case postgres.givesNewID("hc_ cus") hc_.cus_... - A store returns
errs.for a missing row.ErrNotFound sql.never leaves the store.ErrNoRows - Work binds its one instant before it reads the clock: the API binds a request’s, and other work calls
clock.. A job reads the clock once before any bind, for the cutoff of its due list only, and each row it then works binds its own.EnsureEffectiveNow
Wiring and config
Section titled “Wiring and config”- A constructor takes every dependency: a nil field that means “skip this step” skips work in silence. Use a
Set...method only to break a real construction cycle. - Only
internal/andconfig cmd/read the environment. Each setting is parsed there once, with its default, and code that receives it adds no fallback.*/ main. go - A compose file does not repeat a default: write
${VAR:-}, so the default in Go applies. - No code exists only for a test: no branch, flag, constructor or package variable that a test flips. Tests use the interfaces production uses.
Errors, state and structure
Section titled “Errors, state and structure”- If you drop an error, write
_ =and the reason on the same line. A deferredrows.orClose() tx.needs no comment.Rollback() - Guard a state change in the write itself. Name the states the row may come from (
WHERE status = ANY($1)), not the ones it may not (status <> 'voided'): a deny-list lets in a state added later. Then check the row count: zero means another writer won. A check read before the write can be stale. See also playbook item 5. - Keep a function under about 200 lines and a file under about 3,000. Split money code only in a PR that changes nothing else.
- Pass a service straight in where it fits the caller’s interface. Write an adapter, in
internal/, only when the types differ.api/ adapters. go - Delete what no production path reaches, even if a test calls it: code, scripts, configs.
- A new dependency needs a reason in the PR.
- Log with
slog.and its siblings when you have a context: the log handler addsInfoContext request_andid tenant_.id
Work that outlives a request
Section titled “Work that outlives a request”Work that must finish after its request ends runs on context. with a timeout. context. drops the request ID and the tenant. Work that runs through many rows after its request has answered also drops the request’s instant (clock.), so each row binds its own.
A cancel during COMMIT can apply the commit and still return an error. So a transaction whose follow-up steps must run takes its own commitBudget context (30s) just before it starts, and nothing else runs on it:
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), commitBudget)defer cancel()err := s.store.Save(writeCtx, tenantID, inv) // one transactionCreate one stepsBudget context (5 minutes) after the commit, for every step that follows. A function that calls Stripe between two of its transactions, such as a refund, creates that context before its first transaction. Each budget is unexported in its package: copy the constants stepsBudget in internal/ and commitBudget in internal/.
Every goroutine has an owner that waits for it at shutdown, or a comment naming the job that retries its work.
Frontend (web-v2)
Section titled “Frontend (web-v2)”- New API calls use the client and types from orval, the generator
make genruns onapi/(workflow). A PR that changes how a page fetches data moves the whole page to that client. Add nothing toopenapi. yaml src/.lib/ api. ts - Never show a guessed value. No
?? 'USD'or|| 'UTC'on a required field, and nocatchthat returns an empty list. Show the loading or error state. - Decisions live in pure functions in
src/lib, each with a Vitest test: labels, dates, money, who may do what. - Type a status with its generated union and handle every value, so a new status fails
tsc -b. - A money dialog keeps its double-click guard and its idempotency key.
- A hand-written request uses
fetchWithTimeoutfromsrc/, never a rawlib/ api. ts fetch. - Do not disable the react-hooks eslint rule or hide an unused export from knip (the unused-code checker).
Scripts and CI
Section titled “Scripts and CI”- A new CI check fails the build, unless its PR says it only annotates, as
doc-styledoes. - A workflow follows GitHub’s secure use guide. Every job has
timeout-minutes, and every image is pinned to a version tag. - An image is scanned and signed before any public tag points at it.
Stuck, or found a bug? Ask in Discussions · Open an issue