diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..83ee371 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 IUCLabs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile index 37ad41d..ff60560 100644 --- a/Makefile +++ b/Makefile @@ -24,7 +24,7 @@ build: go build ./... # Unit tests. The container-backed integration tests skip themselves under -# -short, which is how CI runs them: the Kubernetes runners have no Docker. +# -short, which is how CI runs them: the runners have no Docker. test: go test -race -count=1 -short ./... @@ -61,7 +61,7 @@ clean: rm -f cover.out cover.filtered.out # Bump helpers — read the latest semver tag and create the next one. Consumers -# pin the resulting v* tag with `go get git.unkin.net/unkin/golib@vX.Y.Z`. +# pin the resulting v* tag with `go get github.com/IUCLabs/golib@vX.Y.Z`. _LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1) _BASE := $(if $(_LATEST),$(_LATEST),v0.0.0) _MAJ := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f1) diff --git a/README.md b/README.md index b483163..b56fc4d 100644 --- a/README.md +++ b/README.md @@ -1,187 +1,54 @@ # golib -Shared Go library for the unkin estate: the plumbing that was being copy-pasted -between services, kept in one place with one set of tests. +Batteries for Go services at IUCLabs. -golib is a library only. It ships no binaries and no container images, holds no -service configuration, and takes on dependencies grudgingly — every service that -imports it inherits them. - -## Modules +## Packages | Import | What it does | | --- | --- | -| `git.unkin.net/unkin/golib/pg` | Postgres: DSN from the environment, pgxpool construction, read/write splitting across a primary and a replica, and the estate's migration runner. | -| `git.unkin.net/unkin/golib/pg/pgtest` | A throwaway Postgres container for a consumer's own `_test.go` files. Test-only. | -| `git.unkin.net/unkin/golib/keyring` | Encrypts secrets at rest with a key held in the Linux kernel user keyring, scoped to the current boot and uid. | -| `git.unkin.net/unkin/golib/colour` | jq-style JSON and yq-style YAML highlighting for CLI output, preserving the input byte for byte, plus the TTY/`NO_COLOR` check. | +| `github.com/IUCLabs/golib/pg` | Postgres: DSN from the environment, pgxpool construction, read/write splitting across a primary and a replica, and an advisory-locked migration runner. | +| `github.com/IUCLabs/golib/pg/pgtest` | A throwaway Postgres container for your own `_test.go` files. Test-only. | +| `github.com/IUCLabs/golib/keyring` | Encrypts secrets at rest with a key held in the Linux kernel user keyring, scoped to the current boot and uid. | +| `github.com/IUCLabs/golib/colour` | jq-style JSON and yq-style YAML highlighting for CLI output, preserving the input byte for byte, plus the TTY/`NO_COLOR` check. | + +``` +go get github.com/IUCLabs/golib@latest +``` + +## Usage ### pg ```go -dsn, err := pg.DSNFromEnv("ENCAPI_") +dsn, err := pg.DSNFromEnv("MYAPP_") // MYAPP_DATABASE_URL, MYAPP_DBHOST, ..., then PG* if err != nil { return err } pool, err := pg.NewMigrated(ctx, dsn, migrations.FS, pg.MigrateOptions{ - LockName: "encapi-migrations", + LockName: "myapp-migrations", Logger: log, }) ``` -`pg.DSNFromEnv(prefix)` resolves a connection string from the environment. -Precedence, highest first: - -1. `DATABASE_URL` — used verbatim. -2. `DATABASE_URL` — likewise. -3. `DBHOST`, `DBPORT`, `DBUSER`, `DBPASS`, - `DBNAME`, `DBSSL`. -4. libpq's `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`, `PGSSLMODE`. -5. Defaults: `localhost`, `5432`, `sslmode=disable`. - -Levels 3 to 5 resolve per field, so a deployment can set the password from a -secret and leave the rest to `PG*`. User and database name have no default — -an unset one is an error naming the variables that were checked. An empty prefix -reads the bare `DBHOST`/`DBPORT`/… names the estate's services already use, so -the rendered DSN is unchanged from the `fmt.Sprintf` builders this replaces. - -`pg.New` opens a pgxpool and pings it, so an unreachable server fails at startup -rather than on the first query. `pg.NewMigrated` does that and then migrates. - -`pg.Migrate(ctx, pool, fsys, opts)` applies the `.sql` files at the root of -`fsys` in lexical filename order. Every replica calls it at startup: - -- The run holds a cluster-wide `pg_advisory_lock` keyed on FNV-1a/64 of - `opts.LockName`, on one dedicated pooled connection, because the lock is - session-scoped. Replicas that queue behind the winner find the set already - recorded and do nothing. -- Each file is applied together with its `schema_migrations` row in a single - transaction, so a failure leaves neither a half-tracked migration nor a - tracking row that would skip it next time. -- A file missing from `schema_migrations` is re-applied even if the live - database already has it, which is how a schema applied out of band is adopted. - Write migrations `IF NOT EXISTS`-guarded so that re-run is a no-op. -- If the unlock does not land, the connection is discarded rather than returned - to the pool, so a session that may still hold the lock cannot be reused. - -`pg.LockKey(name)` exposes the derivation, so a service migrating off a -hardcoded key can assert the two agree before switching over. - -#### Read/write splitting - -`pg.Cluster` wraps a primary pool and an optional read-replica pool: +Split reads to a replica with `pg.Cluster`; routing is explicit and an +unhealthy or missing replica falls back to the primary: ```go -primaryDSN, replicaDSN, err := pg.ClusterDSNsFromEnv("ENCAPI_") -if err != nil { - return err -} -db, err := pg.NewCluster(ctx, pg.ClusterConfig{ - PrimaryDSN: primaryDSN, - ReplicaDSN: replicaDSN, - Logger: log, -}) -if err != nil { - return err -} +primaryDSN, replicaDSN, err := pg.ClusterDSNsFromEnv("MYAPP_") // replica from MYAPP_DB_RO_HOST +db, err := pg.NewCluster(ctx, pg.ClusterConfig{PrimaryDSN: primaryDSN, ReplicaDSN: replicaDSN}) defer db.Close() -if err := db.Migrate(ctx, migrations.FS, pg.MigrateOptions{LockName: "encapi-migrations"}); err != nil { - return err -} - -rows, err := db.Read().Query(ctx, "SELECT id, name FROM nodes") // replica when healthy -tag, err := db.Write().Exec(ctx, "UPDATE nodes SET ...") // always the primary -row := db.Primary().QueryRow(ctx, "SELECT ... WHERE id = $1", id) // read-your-writes +rows, err := db.Read().Query(ctx, "SELECT id, name FROM widgets") // replica when healthy +tag, err := db.Write().Exec(ctx, "UPDATE widgets SET ...") // always the primary ``` -| Call | Goes to | -| --- | --- | -| `Write()` | The primary, always. | -| `Read()` | The replica when one is configured and healthy; the primary otherwise. | -| `Primary()` | The primary. Same pool as `Write()`, named for reads that must not be stale. | - -**Routing is explicit; nothing inspects SQL.** Deciding from the statement text -gets it wrong in both directions: a CTE with an `INSERT` in it reads as a -`SELECT`, and `SELECT ... FOR UPDATE` takes row locks a replica cannot grant. -The caller knows which it wants, so the caller picks. - -**Replica lag is real.** A replica serves a slightly stale snapshot, so a read -that has to observe a write this process just made goes to `Primary()`. The -usual shape is a handler that writes and then re-reads what it wrote, or a -redirect straight into a `GET` of the row just created — both need the primary. -Everything else (list endpoints, dashboards, reports, background aggregation) -can take the replica. - -**A missing replica is not an error.** With `ReplicaDSN` empty, `Read()` returns -the primary and the `Cluster` is an ordinary single-pool handle, so a service -can use `Cluster` unconditionally and let the deployment decide whether reads -split. A `ReplicaDSN` equal to `PrimaryDSN` does the same rather than opening a -second pool to the same place. - -**An unhealthy replica falls back.** The `Cluster` keeps a small circuit over -the replica: - -- A replica that fails its startup ping does not fail startup; reads begin on - the primary and move over once it answers a probe. -- `db.ReportReplicaError(err)` — pass the error from a query run on the pool - `Read()` handed out — trips the circuit, and reads move to the primary. -- While tripped, `Read()` issues no probes until the backoff window expires; the - next `Read()` after that pays for one probe that either promotes the replica - or doubles the window. The window runs from `ReplicaRetryMin` to - `ReplicaRetryMax` (5s to 2m by default) and resets on recovery. A healthy - replica is never probed at all, so the split costs nothing on the read path. -- Reporting is advisory. A caller that never reports still routes correctly; it - just does not react to a replica that dies mid-flight. - -**Migrations always target the primary.** `Cluster.Migrate` runs through -`Write()`. A replica is physically read-only, and a schema change has to -originate on the primary to reach the replica at all. - -`pg.ClusterDSNsFromEnv(prefix)` returns both connection strings. The primary -follows `DSNFromEnv` exactly. The replica resolves, highest first: - -1. `DATABASE_RO_URL` — used verbatim. -2. `DATABASE_RO_URL` — likewise. -3. `DB_RO_HOST`, or bare `DB_RO_HOST` — the primary's port, user, - password, database and sslmode with that host substituted. -4. Nothing set — an empty replica DSN, so the `Cluster` runs single-pool. - -Nothing is derived. The read-only host is never rewritten out of the primary's, -because a wrong guess silently sends reads somewhere unintended. Setting only -`DB_RO_HOST` while the primary comes from a whole `DATABASE_URL` is an error, -not a guess: the fields to substitute into are not known. - -CloudNativePG publishes exactly the two endpoints this expects — `-rw` -routes to the primary and `-ro` to the replicas — so a Deployment names -both: - -```yaml -env: - - name: ENCAPI_DBHOST - value: encapi-db-rw - - name: ENCAPI_DB_RO_HOST - value: encapi-db-ro - - name: ENCAPI_DBNAME - value: encapi - - name: ENCAPI_DBUSER - valueFrom: { secretKeyRef: { name: encapi-db-app, key: username } } - - name: ENCAPI_DBPASS - valueFrom: { secretKeyRef: { name: encapi-db-app, key: password } } -``` - -Dropping `ENCAPI_DB_RO_HOST` turns the split off without a code change. - ### pgtest -`pgtest` starts `postgres:17-alpine` via testcontainers. Import it only from -`_test.go` files. The estate's CI runs on Kubernetes with no Docker socket, so -container-backed tests must skip themselves under `-short`: +Starts `postgres:17-alpine` via testcontainers (needs Docker); skips under `-short`. ```go func TestSomething(t *testing.T) { - ctx := context.Background() - dsn := pgtest.MustStartPostgres(ctx, t) // skips under -short, cleans up after + dsn := pgtest.MustStartPostgres(context.Background(), t) ... } ``` @@ -189,7 +56,7 @@ func TestSomething(t *testing.T) { ### keyring ```go -kr, err := keyring.Open("golib:vault-tools") // get-or-create the key +kr, err := keyring.Open("golib:mytool") // get-or-create the key sealed, err := kr.Seal(token) token, err := kr.Unseal(sealed) if errors.Is(err, keyring.ErrKeyUnavailable) { @@ -197,44 +64,22 @@ if errors.Is(err, keyring.ErrKeyUnavailable) { } ``` -The key is 32 random bytes stored as a `user` key in the uid's user keyring -(`@u`), so every login shell, terminal and systemd user service of that uid -shares it until reboot. Its permissions grant the uid read access as well as the -possessor, because processes whose session keyring does not link `@u` do not -possess it. Data is AES-256-GCM in a versioned envelope; a missing, revoked or -different key returns `ErrKeyUnavailable`, damaged data returns `ErrCorrupt`. -`Forget` revokes the key. Non-Linux builds return `errors.ErrUnsupported`. +Linux only; other platforms return `errors.ErrUnsupported`. -## Consuming +### colour -golib is versioned with semver tags and consumed like any Go module. Pin a tag: - -``` -go get git.unkin.net/unkin/golib@v0.1.0 +```go +if colour.Enabled(colour.Auto, os.Stdout) { + err = colour.JSON(os.Stdout, data) +} else { + _, err = os.Stdout.Write(data) +} ``` -Nothing is released until a `v*` tag exists; `make patch`, `make minor` and -`make major` cut and push the next one. +## Requirements -Because everything shares one module path, a consumer that imports only `pg` -still resolves golib's full dependency set in its module graph. That is the -reason to keep the dependency list short, and the reason `pgtest`'s -testcontainers dependency is the exception rather than the pattern. +Go 1.25 or later. -## Development +## License -``` -make build # compile every package -make test # unit tests (-short: no container needed) -make test-all # everything, including the container-backed integration tests -make cover # unit tests with the coverage gate -make lint # golangci-lint -``` - -New code needs meaningful tests. `make cover` fails below **90% statement -coverage**, measured over the shipped packages from the unit tests alone — the -integration tests do not count towards it, so the bar has to be cleared without -a database. `pg/pgtest` is excluded: it is test scaffolding for other repos, and -is covered by the integration tests the gate does not run. - -CI runs `test`, `pre-commit` and `build` on every pull request. +MIT — see [LICENSE](LICENSE). diff --git a/go.mod b/go.mod index abdf329..54168b9 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module git.unkin.net/unkin/golib +module github.com/IUCLabs/golib go 1.25.0 diff --git a/pg/dsn.go b/pg/dsn.go index bbb30ac..b07c975 100644 --- a/pg/dsn.go +++ b/pg/dsn.go @@ -41,8 +41,8 @@ var ( // DSNFromEnv builds a libpq/pgx connection string from the environment. // // prefix is prepended to every custom variable name, so a service can namespace -// its settings ("ENCAPI_" reads ENCAPI_DBHOST); an empty prefix reads the bare -// names the estate's services already use (DBHOST, DBPORT, ...). +// its settings ("MYAPP_" reads MYAPP_DBHOST); an empty prefix reads the bare +// names (DBHOST, DBPORT, ...). // // Precedence, highest first: // @@ -161,7 +161,7 @@ func connPartsFromEnv(prefix string) (connParts, error) { return p, nil } -// DSN renders the estate's standard connection string. User and password are +// DSN renders the standard connection string. User and password are // percent-escaped, so a password containing "@" or "/" does not truncate the // host; for values without reserved characters the result is byte-identical to // the fmt.Sprintf builders this replaces. diff --git a/pg/dsn_test.go b/pg/dsn_test.go index 47e4491..456c985 100644 --- a/pg/dsn_test.go +++ b/pg/dsn_test.go @@ -49,11 +49,11 @@ func TestDSNFromEnv(t *testing.T) { name: "bare custom vars with an empty prefix", prefix: "", env: map[string]string{ - "DBHOST": "pg", "DBPORT": "5432", "DBUSER": "encapi", - "DBPASS": "encapi", "DBNAME": "encapi", "DBSSL": "disable", + "DBHOST": "pg", "DBPORT": "5432", "DBUSER": "myapp", + "DBPASS": "myapp", "DBNAME": "myapp", "DBSSL": "disable", }, // Byte-identical to the fmt.Sprintf builder this replaces. - want: "postgres://encapi:encapi@pg:5432/encapi?sslmode=disable", + want: "postgres://myapp:myapp@pg:5432/myapp?sslmode=disable", }, { name: "libpq vars fill in", diff --git a/pg/integration_test.go b/pg/integration_test.go index 017586e..dbebb7b 100644 --- a/pg/integration_test.go +++ b/pg/integration_test.go @@ -9,8 +9,8 @@ import ( "testing/fstest" "time" - "git.unkin.net/unkin/golib/pg" - "git.unkin.net/unkin/golib/pg/pgtest" + "github.com/IUCLabs/golib/pg" + "github.com/IUCLabs/golib/pg/pgtest" ) // migrations is a two-file set exercising the things the runner promises: diff --git a/pg/migrate_test.go b/pg/migrate_test.go index ce6ba26..ba8be2f 100644 --- a/pg/migrate_test.go +++ b/pg/migrate_test.go @@ -132,18 +132,18 @@ func (f *fakeDB) discardCount() int { return f.discards } -// arrproxy pinned its advisory lock key as a literal derived from -// FNV-1a/64("arrproxy-migrations"). LockKey must reproduce it exactly, or -// adopting this package would silently stop excluding the old deployment. -func TestLockKey_MatchesTheEstatesPinnedKey(t *testing.T) { - const arrproxyKey int64 = 7816645656172167846 - if got := LockKey("arrproxy-migrations"); got != arrproxyKey { - t.Fatalf("LockKey(%q) = %d, want %d", "arrproxy-migrations", got, arrproxyKey) +// A service that hardcoded its advisory lock key as FNV-1a/64 of its lock name +// must keep getting the same key from LockKey, or adopting this package would +// silently stop excluding the old deployment. +func TestLockKey_MatchesPinnedKey(t *testing.T) { + const pinnedKey int64 = -8597821083387989636 + if got := LockKey("myapp-migrations"); got != pinnedKey { + t.Fatalf("LockKey(%q) = %d, want %d", "myapp-migrations", got, pinnedKey) } } func TestLockKey_IsFNV1a64(t *testing.T) { - for _, name := range []string{"", "encapi-migrations", "a much longer lock name"} { + for _, name := range []string{"", "myapp-migrations", "a much longer lock name"} { h := fnv.New64a() if _, err := h.Write([]byte(name)); err != nil { t.Fatalf("hash: %v", err) @@ -157,7 +157,7 @@ func TestLockKey_IsFNV1a64(t *testing.T) { // Distinct names must not collide, or two services sharing a cluster would // serialise against each other by accident. func TestLockKey_DistinctNamesDistinctKeys(t *testing.T) { - if LockKey("encapi-migrations") == LockKey("artifactapi-migrations") { + if LockKey("myapp-migrations") == LockKey("otherapp-migrations") { t.Fatal("two different lock names produced the same key") } } diff --git a/pg/pg.go b/pg/pg.go index 74c9cdb..a178606 100644 --- a/pg/pg.go +++ b/pg/pg.go @@ -1,4 +1,4 @@ -// Package pg holds the estate's shared Postgres plumbing: environment-driven +// Package pg holds shared Postgres plumbing: environment-driven // DSN construction, pgxpool construction, read/write splitting across a primary // and a read replica, and the migration runner every service uses to bring its // own schema up to date at startup. diff --git a/pg/pgtest/pgtest.go b/pg/pgtest/pgtest.go index 7c4b9c8..07e6373 100644 --- a/pg/pgtest/pgtest.go +++ b/pg/pgtest/pgtest.go @@ -2,8 +2,8 @@ // tests. Import it only from _test.go files so testcontainers never reaches a // production binary. // -// The estate's CI runs on Kubernetes with no Docker socket, so tests that need -// a container must skip themselves under -short. SkipIfShort does exactly that, +// CI without a Docker socket runs tests with -short, so tests that need a +// container must skip themselves under -short. SkipIfShort does exactly that, // and StartPostgres reports a plain error when no container runtime is // reachable, leaving it to the caller whether that is a skip or a failure. package pgtest @@ -20,7 +20,7 @@ import ( "github.com/testcontainers/testcontainers-go/wait" ) -// Image is the Postgres the estate targets; every service runs the same major. +// Image is the Postgres image the container runs. const Image = "postgres:17-alpine" const (