diff --git a/.agent/mise-tasks/check/go b/.agent/mise-tasks/check/go new file mode 100755 index 0000000..e1eedb4 --- /dev/null +++ b/.agent/mise-tasks/check/go @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's Go step, every gate in every module; gate names as arguments run only those" +# Runs scripts/check/go.sh, one step of the check. +set -euo pipefail +exec scripts/check/go.sh "$@" diff --git a/.agent/mise-tasks/check/lints b/.agent/mise-tasks/check/lints new file mode 100755 index 0000000..6e206f3 --- /dev/null +++ b/.agent/mise-tasks/check/lints @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's lints step, lint-context and lint-references at the root" +# Runs scripts/check/lints.sh, one step of the check. +set -euo pipefail +exec scripts/check/lints.sh "$@" diff --git a/.agent/mise-tasks/lint b/.agent/mise-tasks/lint new file mode 100755 index 0000000..968307d --- /dev/null +++ b/.agent/mise-tasks/lint @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's lint gate, golangci-lint with the integration tag, in every module" +# Runs the lint gate of scripts/check/go.sh. +set -euo pipefail +exec scripts/check/go.sh lint diff --git a/.agent/mise-tasks/test b/.agent/mise-tasks/test new file mode 100755 index 0000000..c927c6a --- /dev/null +++ b/.agent/mise-tasks/test @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's test gate, the unit tier with the race detector, in every module" +# Runs the test gate of scripts/check/go.sh. +set -euo pipefail +exec scripts/check/go.sh test diff --git a/.agent/mise-tasks/vet b/.agent/mise-tasks/vet new file mode 100755 index 0000000..c55d852 --- /dev/null +++ b/.agent/mise-tasks/vet @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's vet gate, go vet with the integration tag, in every module" +# Runs the vet gate of scripts/check/go.sh. +set -euo pipefail +exec scripts/check/go.sh vet diff --git a/.claude/marathon.toml b/.claude/marathon.toml index f776fa4..2157ba8 100644 --- a/.claude/marathon.toml +++ b/.claude/marathon.toml @@ -6,7 +6,8 @@ currency = "mise run currency" [remote] platform = "github" publish = "gh pr create" -merge = "gh pr checks --watch && gh pr merge --merge --delete-branch" +checks = "gh pr checks --watch" +merge = "gh pr merge --merge --delete-branch" ci = ''' sha=$(git rev-parse HEAD) for _ in $(seq 30); do diff --git a/.claude/settings.json b/.claude/settings.json index aedf229..c330116 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,5 +1,8 @@ { "plansDirectory": "./.claude/plans", + "env": { + "MISE_ENV": "agent" + }, "permissions": { "allow": [ "Bash(go test:*)", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 336063a..9c712cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v7.0.1 - - uses: jdx/mise-action@v5.3.0 + - uses: jdx/mise-action@v5.4.0 - name: mise run check run: mise run check diff --git a/.gitignore b/.gitignore index 44f8960..6cbecf2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .claude/plans/ -.claude/briefs/ +.agent/state/ mise.local.toml bin/ diff --git a/CHANGELOG.md b/CHANGELOG.md index f1533c6..d454e8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,22 @@ only; the `postgres` and `postgres/pgvector` sub-modules each keep their own. ## [Unreleased] +### Changed + +- **Breaking:** The `go-core` requirement is v0.14.0. Its v0.13.0 changes `EventKind.Raise` to take + an `event.RaiseOptions`, so an importer that calls it changes with this upgrade. The module's + own API is unchanged. +- Each package's unit tests sit in its `test/` directory as an external test package + (`/test/*_test.go`); the root package's are in `test/`. The tests of `admin` and `sweep` that + use an `export_test.go` hook stay beside it, and the fixtures both of a package's test packages + share sit in the internal packages `internal/admintest` and `internal/sweeptest`. No exported API + changes. +- The repository's check runs as step scripts in `scripts/check/` (`go.sh`, `lints.sh`), which + `mise run check` runs in turn. +- Agent tasks live in `.agent/mise-tasks/`, loaded only by the `agent` profile (`mise.agent.toml`, + under `MISE_ENV=agent`): one task per check step, and `test`, `vet`, and `lint`. The inline + `build`, `test`, `vet`, and `lint` tasks are removed; a person's other tasks are unchanged. + ## [v0.13.0] - 2026-11-24 ### Added diff --git a/README.md b/README.md index 054127c..5e6d096 100644 --- a/README.md +++ b/README.md @@ -62,15 +62,27 @@ principles: The repository uses a Go workspace and [mise](https://mise.jdx.dev): ``` -mise run check # build, vet, format, fix, tidy, test, and lint every module, then lint-context and lint-references; writes nothing -mise run currency # report tools, Go, requirements, actions, images, and Dockerfile source ARGs behind their latest, except a held one; writes nothing -mise run upgrade # move every pin currency reports to its latest, except a held one: tools, then Go and requirements, actions, images, and Dockerfile source ARGs -mise run db:up # build and start the compose PostgreSQL and wait until it is healthy -mise run db:down # stop PostgreSQL, discarding its data +mise run check # build, vet, format, fix, tidy, test, and lint every module, then lint-context and lint-references; writes nothing +mise run currency # report tools, Go, requirements, actions, images, and Dockerfile source ARGs behind their latest, except a held one; writes nothing +mise run upgrade # move every pin currency reports to its latest, except a held one: tools, then Go and requirements, actions, images, and Dockerfile source ARGs +mise run db:up # build and start the compose PostgreSQL and wait until it is healthy +mise run db:down # stop PostgreSQL, discarding its data mise run integration # run the integration tier against the running stack mise run acceptance # db:up, integration, then db:down whatever the result; prints the stack's log on failure +mise run fmt # format all Go source +mise run tidy # run go mod tidy in every module ``` +`mise run check` runs the step scripts in `scripts/check/`: `go.sh`, the Go gates in each module, +then `lints.sh`. Where `MISE_ENV=agent` is set, as `.claude/settings.json` sets it for the agent, +mise also loads the agent profile, `mise.agent.toml`, which adds the tasks in `.agent/mise-tasks/`: +`check:go` and `check:lints`, one per step, and `test`, `vet`, and `lint`, one gate each. + +Each package's tests sit in its `test/` directory as an external test package. In `admin` and +`sweep`, the tests that use an `export_test.go` hook stay beside it, and the fixtures both of the +package's test packages share sit in the internal packages `internal/admintest` and +`internal/sweeptest`. + `compose.yml` runs PostgreSQL with pgvector on port 5438; `POSTGRES_PORT` moves it, and `GO_DATABASE_DSN` in `mise.toml` follows it. The service builds from `compose/postgres/Dockerfile`, a copy of sqlate's canonical PostgreSQL image: its `FROM` line is diff --git a/STANDARDS.md b/STANDARDS.md index c8b32e7..6340b6e 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -15,4 +15,5 @@ The judgement calls the standards-reviewer applies to go-database, beyond what ` - `architecture/principles/service-tiers.md`: `DB.Conn`, `Config.Options`, and the `postgres` provider. - `architecture/principles/validation-first.md`: `Config.Finalize`, and `admin`'s verbs, which refuse an argument outside their domain before any I/O, and `pgvector.ParseMetric`, which refuses an unknown metric name before any I/O. - `architecture/principles/context-architecture.md`: the README and each `doc.go`. +- `architecture/principles/agent-separation.md`: the agent area in `.agent/`, the agent profile in `mise.agent.toml`, and `MISE_ENV=agent` in the Claude settings' `env`. - `architecture/principles/comments.md`: every comment. diff --git a/admin/ready_test.go b/admin/ready_test.go new file mode 100644 index 0000000..a9b2047 --- /dev/null +++ b/admin/ready_test.go @@ -0,0 +1,106 @@ +package admin_test + +import ( + "context" + "database/sql/driver" + "slices" + "sync" + "sync/atomic" + "testing" + + "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/go-database/internal/admintest" + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/sqltest" +) + +func behindService(t *testing.T) *admin.Service { + t.Helper() + s, _ := admintest.NewService(t, slices.Concat( + admintest.Clean(), []sqltest.Response{admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})}, + )...) + if err := s.Start(context.Background()); err != nil { + t.Fatalf("Start: %v", err) + } + if st, err := s.Status(context.Background()); err != nil || st.Ready { + t.Fatalf("Status = %+v, %v", st, err) + } + return s +} + +func TestReady_ConcurrentProbesVerifyOnce(t *testing.T) { + s := behindService(t) + var probes atomic.Int32 + admin.SetProbe(s, func(context.Context) error { + probes.Add(1) + return migrate.ErrPending + }) + var wg sync.WaitGroup + gate := make(chan struct{}) + for range 16 { + wg.Go(func() { + <-gate + _ = s.Ready() + }) + } + close(gate) + wg.Wait() + if n := probes.Load(); n != 1 { + t.Errorf("probes = %d, want 1", n) + } +} + +func TestReady_ProbesNeverOverlap(t *testing.T) { + s := behindService(t) + var probes atomic.Int32 + entered, release := make(chan struct{}), make(chan struct{}) + admin.SetProbe(s, func(context.Context) error { + if probes.Add(1) == 1 { + entered <- struct{}{} + <-release + } + return nil + }) + done := make(chan bool) + go func() { done <- s.Ready() }() + <-entered + admin.ExpireThrottle(s) + if s.Ready() || probes.Load() != 1 { + t.Errorf("a Ready during a probe verified again: probes = %d", probes.Load()) + } + close(release) + if !<-done { + t.Error("the probe's clean verify did not set Ready") + } +} + +func TestReady_ProbeYieldsToAConcurrentFinding(t *testing.T) { + s, _ := admintest.NewService(t, slices.Concat( + admintest.Clean(), + []sqltest.Response{admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})}, + []sqltest.Response{admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})}, + )...) + ctx := context.Background() + if err := s.Start(ctx); err != nil { + t.Fatalf("Start: %v", err) + } + if _, err := s.Status(ctx); err != nil { + t.Fatalf("Status: %v", err) + } + entered, release := make(chan struct{}), make(chan struct{}) + admin.SetProbe(s, func(context.Context) error { + entered <- struct{}{} + <-release + return nil + }) + done := make(chan bool) + go func() { done <- s.Ready() }() + <-entered + if st, err := s.Status(ctx); err != nil || st.Ready { + t.Fatalf("Status = %+v, %v", st, err) + } + close(release) + if <-done || s.Ready() { + t.Error("the probe's stale finding overwrote the status found behind") + } +} diff --git a/admin/extensions_test.go b/admin/test/extensions_test.go similarity index 93% rename from admin/extensions_test.go rename to admin/test/extensions_test.go index 291457f..5968e59 100644 --- a/admin/extensions_test.go +++ b/admin/test/extensions_test.go @@ -12,11 +12,12 @@ import ( "testing" "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/go-database/internal/admintest" "github.com/standards-lab/sqlate/migrate" "github.com/standards-lab/sqlate/sqltest" ) -type extensionDialect struct{ testDialect } +type extensionDialect struct{ admintest.Dialect } func (extensionDialect) ExtensionState(param string) string { return "SELECT installed, default, path FROM extensions WHERE name = " + param @@ -45,14 +46,14 @@ var ( func newExtensionService(t *testing.T, declared []migrate.Extension, opts admin.Options, responses ...sqltest.Response) fixture { t.Helper() - return newMigratorFixture(t, []migrate.Set{{Name: "app", Migrations: set}}, extensionDialect{}, + return newMigratorFixture(t, []migrate.Set{{Name: "app", Migrations: admintest.Migrations}}, extensionDialect{}, migrate.Options{Extensions: declared}, opts, responses...) } var vector = []migrate.Extension{{Name: "vector"}} func TestExtensions_StatusListsNoneWhenUndeclared(t *testing.T) { - s, _ := newService(t, current()...) + s, _ := admintest.NewService(t, current()...) st, err := s.Status(context.Background()) if err != nil { t.Fatalf("Status: %v", err) @@ -150,7 +151,7 @@ func TestExtensions_FaultIsAConflict(t *testing.T) { } }) t.Run(name+"/verify", func(t *testing.T) { - f := newExtensionService(t, vector, admin.Options{}, extCurrent, exists(true), applied(), fault.state) + f := newExtensionService(t, vector, admin.Options{}, extCurrent, admintest.Exists(true), admintest.Applied(), fault.state) ctx := context.Background() if err := f.service.Verify(ctx); err != nil || !f.service.Ready() { t.Fatalf("clean Verify = %v, ready %v", err, f.service.Ready()) @@ -163,7 +164,7 @@ func TestExtensions_FaultIsAConflict(t *testing.T) { t.Run(name+"/up", func(t *testing.T) { f := newExtensionService(t, vector, admin.Options{}, slices.Concat( current(), []sqltest.Response{extCurrent}, - []sqltest.Response{locked, created, applied(), fault.state, unlocked}, + []sqltest.Response{locked, created, admintest.Applied(), fault.state, unlocked}, current(), []sqltest.Response{fault.state}, )...) ctx := context.Background() @@ -184,7 +185,7 @@ func TestExtensions_StartLogsPendingBeforeApplying(t *testing.T) { f := newExtensionService(t, vector, admin.Options{Logger: slog.New(slog.NewTextHandler(&buf, nil))}, slices.Concat( []sqltest.Response{extMissing}, current(), []sqltest.Response{extMissing}, - []sqltest.Response{locked, created, applied(), extMissing, {}, {}, unlocked}, + []sqltest.Response{locked, created, admintest.Applied(), extMissing, {}, {}, unlocked}, []sqltest.Response{extCurrent}, current(), )...) if err := f.service.Start(context.Background()); err != nil { diff --git a/admin/seed_test.go b/admin/test/seed_test.go similarity index 80% rename from admin/seed_test.go rename to admin/test/seed_test.go index d497714..e3525bb 100644 --- a/admin/seed_test.go +++ b/admin/test/seed_test.go @@ -9,12 +9,13 @@ import ( "testing" "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/go-database/internal/admintest" "github.com/standards-lab/sqlate/migrate" "github.com/standards-lab/sqlate/sqltest" ) func TestSeed_NoSetRefuses(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{}}) n, err := f.service.Seed(context.Background(), "") if !errors.Is(err, admin.ErrSeedDisabled) || n != nil { t.Fatalf("Seed = %v, %v; want ErrSeedDisabled", n, err) @@ -25,7 +26,7 @@ func TestSeed_NoSetRefuses(t *testing.T) { } func TestSeed_NoSeederRefuses(t *testing.T) { - s, rec := newService(t) + s, rec := admintest.NewService(t) ctx := context.Background() if _, err := s.Seed(ctx, ""); !errors.Is(err, admin.ErrSeedDisabled) { t.Errorf("Seed = %v, want ErrSeedDisabled", err) @@ -45,7 +46,7 @@ func TestSeed_NoSeederRefuses(t *testing.T) { } func TestSeed_UnknownStateRefuses(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}) ctx := context.Background() _, err := f.service.Seed(ctx, "nope") if !errors.Is(err, admin.ErrUnknownState) || !strings.Contains(err.Error(), `"nope"`) { @@ -60,14 +61,14 @@ func TestSeed_UnknownStateRefuses(t *testing.T) { } func TestStates_ListsTheSeeders(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "empty"}}}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "empty"}}}) if got := f.service.States(); !slices.Equal(got, []string{"default", "empty"}) { t.Errorf("States = %v", got) } } func TestSeed_EmptyNameAppliesTheConfiguredSet(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}) n, err := f.service.Seed(context.Background(), "") if err != nil || n["things"] != 2 || !slices.Equal(f.seeder.seeded, []string{"default"}) { t.Errorf("Seed = %v, %v; seeded %v", n, err, f.seeder.seeded) @@ -75,7 +76,7 @@ func TestSeed_EmptyNameAppliesTheConfiguredSet(t *testing.T) { } func TestSeed_NamedSetAppliesWithoutConfiguration(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "demo"}}}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "demo"}}}) n, err := f.service.Seed(context.Background(), "demo") if err != nil || n["things"] != 2 || !slices.Equal(f.seeder.seeded, []string{"demo"}) { t.Errorf("Seed demo = %v, %v; seeded %v", n, err, f.seeder.seeded) @@ -83,7 +84,7 @@ func TestSeed_NamedSetAppliesWithoutConfiguration(t *testing.T) { } func TestStart_AppliesTheConfiguredSet(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}, clean()...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}, admintest.Clean()...) if err := f.service.Start(context.Background()); err != nil { t.Fatalf("Start: %v", err) } @@ -93,7 +94,7 @@ func TestStart_AppliesTheConfiguredSet(t *testing.T) { } func TestStart_UnknownConfiguredSetFailsStartup(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seed: "nope", Seeder: &fakeSeeder{}}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seed: "nope", Seeder: &fakeSeeder{}}) err := f.service.Start(context.Background()) if !errors.Is(err, admin.ErrUnknownState) { t.Fatalf("Start = %v, want ErrUnknownState", err) @@ -104,7 +105,7 @@ func TestStart_UnknownConfiguredSetFailsStartup(t *testing.T) { } func TestStart_SeedFailureFailsStartup(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{seedErr: errors.New("seed failed")}}, clean()...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{seedErr: errors.New("seed failed")}}, admintest.Clean()...) err := f.service.Start(context.Background()) if !errors.Is(err, f.seeder.seedErr) || !strings.HasPrefix(err.Error(), "seed: ") { t.Fatalf("Start = %v, want the seed's error", err) @@ -116,13 +117,13 @@ func TestStart_SeedFailureFailsStartup(t *testing.T) { func TestReset_EmptyNameUsesTheConfiguredSet(t *testing.T) { responses := slices.Concat(resetting(), applying(), current()) - f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}, responses...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}, responses...) tr, err := f.service.Reset(context.Background(), "") if err != nil || tr.State != "default" || !slices.Equal(f.seeder.seeded, []string{"default"}) { t.Fatalf("Reset = %+v, %v; seeded %v", tr, err, f.seeder.seeded) } - g := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}) + g := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{}}) if _, err := g.service.Reset(context.Background(), ""); !errors.Is(err, admin.ErrSeedDisabled) { t.Errorf("Reset without a configured set = %v, want ErrSeedDisabled", err) } @@ -130,7 +131,7 @@ func TestReset_EmptyNameUsesTheConfiguredSet(t *testing.T) { func TestStates_ReturnsACopy(t *testing.T) { states := []string{"default", "empty"} - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: states}}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{states: states}}) f.service.States()[0] = "changed" if states[0] != "default" { t.Errorf("seeder's states = %v, want them unchanged", states) @@ -139,7 +140,7 @@ func TestStates_ReturnsACopy(t *testing.T) { func TestReset_RevertsAppliesAndSeeds(t *testing.T) { responses := slices.Concat(resetting(), applying(), current()) - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "empty"}}}, responses...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "empty"}}}, responses...) tr, err := f.service.Reset(context.Background(), "empty") if err != nil { t.Fatalf("Reset: %v", err) @@ -166,11 +167,11 @@ func TestReset_RevertsAppliesAndSeeds(t *testing.T) { } func TestReset_DirtyHistoryStopsAtTheRevert(t *testing.T) { - dirty := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, - exists(true), applied(), + dirty := admintest.History([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{}}, + admintest.Exists(true), admintest.Applied(), locked, created, dirty, unlocked, - exists(true), dirty, + admintest.Exists(true), dirty, ) if err := f.service.Verify(context.Background()); err != nil || !f.service.Ready() { t.Fatalf("Verify = %v, ready %v", err, f.service.Ready()) @@ -187,10 +188,10 @@ func TestReset_DirtyHistoryStopsAtTheRevert(t *testing.T) { func TestReset_FailureAtTheApply(t *testing.T) { boom := errors.New("create failed") responses := slices.Concat(resetting(), - []sqltest.Response{locked, created, history(), {Err: boom}, unlocked}, - []sqltest.Response{exists(true), history()}, + []sqltest.Response{locked, created, admintest.History(), {Err: boom}, unlocked}, + []sqltest.Response{admintest.Exists(true), admintest.History()}, ) - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, responses...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{}}, responses...) _, err := f.service.Reset(context.Background(), "default") if !errors.Is(err, boom) || !strings.HasPrefix(err.Error(), "apply: ") { t.Fatalf("Reset = %v, want the apply's error", err) @@ -203,7 +204,7 @@ func TestReset_FailureAtTheApply(t *testing.T) { func TestReset_FailureAtTheSeed(t *testing.T) { boom := errors.New("seed failed") responses := slices.Concat(resetting(), applying(), current()) - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{seedErr: boom}}, responses...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{seedErr: boom}}, responses...) _, err := f.service.Reset(context.Background(), "default") if !errors.Is(err, boom) || !strings.HasPrefix(err.Error(), "seed: ") { t.Fatalf("Reset = %v, want the seed's error", err) @@ -243,7 +244,7 @@ func TestReset_HookRunsBetweenTheApplyAndTheSeed(t *testing.T) { Seeder: &fakeSeeder{states: []string{"default", "demo"}}, OnReset: recordHook(&f, &calls, nil), } - f = newFixture(t, testDialect{}, opts, slices.Concat(resetting(), applying(), current())...) + f = newFixture(t, admintest.Dialect{}, opts, slices.Concat(resetting(), applying(), current())...) tr, err := f.service.Reset(context.Background(), tc.request) if err != nil || tr.State != tc.want { t.Fatalf("Reset = %+v, %v", tr, err) @@ -269,7 +270,7 @@ func TestReset_FailureAtTheHook(t *testing.T) { Seeder: &fakeSeeder{}, OnReset: recordHook(&f, &calls, boom), } - f = newFixture(t, testDialect{}, opts, slices.Concat(resetting(), applying(), current())...) + f = newFixture(t, admintest.Dialect{}, opts, slices.Concat(resetting(), applying(), current())...) tr, err := f.service.Reset(context.Background(), "default") if !errors.Is(err, boom) || !strings.HasPrefix(err.Error(), "reset hook: ") { t.Fatalf("Reset = %+v, %v; want the hook's error", tr, err) @@ -280,14 +281,14 @@ func TestReset_FailureAtTheHook(t *testing.T) { } func TestOnReset_OtherVerbsNeverCallIt(t *testing.T) { - one := history([]driver.Value{int64(1), "a", false}) + one := admintest.History([]driver.Value{int64(1), "a", false}) responses := slices.Concat( - clean(), + admintest.Clean(), current(), applying(), current(), - []sqltest.Response{locked, created, applied(), {}, {}, {}, unlocked, exists(true), one}, - []sqltest.Response{locked, created, history(), {}, {}, unlocked, exists(true), one}, - []sqltest.Response{locked, {}, {}, {Affected: 1}, unlocked, exists(true), one}, + []sqltest.Response{locked, created, admintest.Applied(), {}, {}, {}, unlocked, admintest.Exists(true), one}, + []sqltest.Response{locked, created, admintest.History(), {}, {}, unlocked, admintest.Exists(true), one}, + []sqltest.Response{locked, {}, {}, {Affected: 1}, unlocked, admintest.Exists(true), one}, ) var calls int opts := admin.Options{ @@ -295,7 +296,7 @@ func TestOnReset_OtherVerbsNeverCallIt(t *testing.T) { Seeder: &fakeSeeder{}, OnReset: func(context.Context, string) error { calls++; return nil }, } - f := newFixture(t, testDialect{}, opts, responses...) + f := newFixture(t, admintest.Dialect{}, opts, responses...) ctx := context.Background() verbs := []struct { name string diff --git a/admin/service_test.go b/admin/test/service_test.go similarity index 64% rename from admin/service_test.go rename to admin/test/service_test.go index fac7460..7c849da 100644 --- a/admin/service_test.go +++ b/admin/test/service_test.go @@ -2,64 +2,31 @@ package admin_test import ( "context" - "database/sql" "database/sql/driver" "errors" "slices" "strings" - "sync" - "sync/atomic" "testing" - "testing/fstest" "github.com/standards-lab/go-core/lifecycle" "github.com/standards-lab/go-database" "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/go-database/internal/admintest" "github.com/standards-lab/sqlate" "github.com/standards-lab/sqlate/migrate" "github.com/standards-lab/sqlate/query" "github.com/standards-lab/sqlate/sqltest" ) -var set = []migrate.Migration{ - {Version: 1, Name: "a", Up: "CREATE TABLE a (x int)", Down: "DROP TABLE a", Transactional: true}, - {Version: 2, Name: "b", Up: "CREATE INDEX CONCURRENTLY ix ON a (x)", Down: "DROP INDEX CONCURRENTLY ix"}, -} - var ( - historyCols = []string{"version", "name", "dirty"} - locked = sqltest.Response{} - created = sqltest.Response{} - unlocked = sqltest.Response{Columns: []string{"unlock"}, Rows: [][]driver.Value{{true}}} + locked = sqltest.Response{} + created = sqltest.Response{} + unlocked = sqltest.Response{Columns: []string{"unlock"}, Rows: [][]driver.Value{{true}}} ) -func exists(yes bool) sqltest.Response { - n := int64(0) - if yes { - n = 1 - } - return sqltest.Response{Columns: []string{"count"}, Rows: [][]driver.Value{{n}}} -} - -func history(rows ...[]driver.Value) sqltest.Response { - return sqltest.Response{Columns: historyCols, Rows: rows} -} - -func applied() sqltest.Response { - var rows [][]driver.Value - for _, m := range set { - rows = append(rows, []driver.Value{int64(m.Version), m.Name, false}) - } - return history(rows...) -} - -func clean() []sqltest.Response { - return []sqltest.Response{exists(true), applied()} -} - func applying() []sqltest.Response { - rs := []sqltest.Response{locked, created, history()} - for _, m := range set { + rs := []sqltest.Response{locked, created, admintest.History()} + for _, m := range admintest.Migrations { if m.Transactional { rs = append(rs, sqltest.Response{}, sqltest.Response{}) } else { @@ -70,8 +37,8 @@ func applying() []sqltest.Response { } func resetting() []sqltest.Response { - rs := []sqltest.Response{locked, created, applied()} - for _, s := range slices.Backward(set) { + rs := []sqltest.Response{locked, created, admintest.Applied()} + for _, s := range slices.Backward(admintest.Migrations) { if s.Transactional { rs = append(rs, sqltest.Response{}, sqltest.Response{}) } else { @@ -82,29 +49,9 @@ func resetting() []sqltest.Response { } func current() []sqltest.Response { - return []sqltest.Response{exists(true), applied()} -} - -type testDialect struct{ sqltest.Dialect } - -func (testDialect) Lock(ctx context.Context, conn *sql.Conn, name string) error { - _, err := conn.ExecContext(ctx, "SELECT lock($1)", name) - return err + return []sqltest.Response{admintest.Exists(true), admintest.Applied()} } -func (testDialect) Unlock(ctx context.Context, conn *sql.Conn, name string) error { - var held bool - if err := conn.QueryRowContext(ctx, "SELECT unlock($1)", name).Scan(&held); err != nil { - return err - } - if !held { - return errors.New("lock not held") - } - return nil -} - -func (testDialect) ServerVersion() string { return "SELECT version()" } - type fakeSeeder struct { verifyErr error seedErr error @@ -135,24 +82,6 @@ var ( _ lifecycle.ReadinessChecker = (*admin.Service)(nil) ) -type fakeRegistry []admin.Entry - -func (r fakeRegistry) Registry() []admin.Entry { return r } - -func started(t *testing.T, pool *sql.DB) *database.DB { - t.Helper() - cfg := database.Config{Name: "test"} - if err := cfg.Finalize(""); err != nil { - t.Fatal(err) - } - base := database.New(pool, cfg) - if err := base.Start(context.Background()); err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = base.Shutdown(context.Background()) }) - return base -} - type fixture struct { service *admin.Service rec *sqltest.Recorder @@ -161,7 +90,7 @@ type fixture struct { func newFixture(t *testing.T, d sqlate.Dialect, opts admin.Options, responses ...sqltest.Response) fixture { t.Helper() - return newSetsFixture(t, []migrate.Set{{Name: "app", Migrations: set}}, d, opts, responses...) + return newSetsFixture(t, []migrate.Set{{Name: "app", Migrations: admintest.Migrations}}, d, opts, responses...) } func newSetsFixture(t *testing.T, sets []migrate.Set, d sqlate.Dialect, opts admin.Options, responses ...sqltest.Response) fixture { @@ -171,30 +100,14 @@ func newSetsFixture(t *testing.T, sets []migrate.Set, d sqlate.Dialect, opts adm func newMigratorFixture(t *testing.T, sets []migrate.Set, d sqlate.Dialect, mopts migrate.Options, opts admin.Options, responses ...sqltest.Response) fixture { t.Helper() - pool, rec := sqltest.Open(t, responses...) - db := sqlate.Wrap(pool, d) - m, err := migrate.New(db, sets, mopts) - if err != nil { - t.Fatalf("migrate.New: %v", err) - } - catalog := query.MustCatalog(query.Patterns()) - files := fstest.MapFS{"sql/ping.sql": {Data: []byte("--| tier: standard\nSELECT {{n:integer}}")}} - stmts := catalog.MustCompile(files, "sql", d) - f := fixture{rec: rec} + var f fixture if opts.Seeder != nil { f.seeder = opts.Seeder.(*fakeSeeder) } - opts.Registry = fakeRegistry{{Name: "ping", Statements: stmts}} - f.service = admin.New(started(t, pool), db, m, catalog, opts) + f.service, f.rec = admintest.New(t, sets, d, mopts, opts, responses...) return f } -func newService(t *testing.T, responses ...sqltest.Response) (*admin.Service, *sqltest.Recorder) { - t.Helper() - f := newFixture(t, testDialect{}, admin.Options{}, responses...) - return f.service, f.rec -} - func wantPanic(t *testing.T, want string, fn func()) { t.Helper() defer func() { @@ -209,13 +122,13 @@ func wantPanic(t *testing.T, want string, fn func()) { func TestNew_PanicsOnWiringDefects(t *testing.T) { pool, _ := sqltest.Open(t) - db := sqlate.Wrap(pool, testDialect{}) - m, err := migrate.New(db, []migrate.Set{{Name: "app", Migrations: set}}, migrate.Options{}) + db := sqlate.Wrap(pool, admintest.Dialect{}) + m, err := migrate.New(db, []migrate.Set{{Name: "app", Migrations: admintest.Migrations}}, migrate.Options{}) if err != nil { t.Fatal(err) } catalog := query.MustCatalog(query.Patterns()) - base := started(t, pool) + base := admintest.Started(t, pool) wantPanic(t, "nil pool", func() { admin.New(nil, db, m, catalog, admin.Options{}) }) wantPanic(t, "nil db", func() { admin.New(base, nil, m, catalog, admin.Options{}) }) @@ -225,7 +138,7 @@ func TestNew_PanicsOnWiringDefects(t *testing.T) { } func TestStart_CleanHistoryIsReady(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, clean()...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{}}, admintest.Clean()...) if f.service.Ready() { t.Fatal("ready before Start") } @@ -244,8 +157,8 @@ func TestStart_CleanHistoryIsReady(t *testing.T) { } func TestStart_PendingHistoryIsApplied(t *testing.T) { - responses := slices.Concat([]sqltest.Response{exists(false), exists(false)}, applying(), clean()) - s, rec := newService(t, responses...) + responses := slices.Concat([]sqltest.Response{admintest.Exists(false), admintest.Exists(false)}, applying(), admintest.Clean()) + s, rec := admintest.NewService(t, responses...) if err := s.Start(context.Background()); err != nil { t.Fatalf("Start: %v", err) } @@ -258,8 +171,8 @@ func TestStart_PendingHistoryIsApplied(t *testing.T) { } func TestStart_DirtyHistoryFailsStartup(t *testing.T) { - s, rec := newService(t, exists(true), - history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true})) + s, rec := admintest.NewService(t, admintest.Exists(true), + admintest.History([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true})) err := s.Start(context.Background()) if !errors.Is(err, migrate.ErrDirty) { t.Fatalf("Start = %v, want ErrDirty", err) @@ -270,7 +183,7 @@ func TestStart_DirtyHistoryFailsStartup(t *testing.T) { } func TestStart_SeederVerifyFailureClearsReady(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, clean()...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{}}, admintest.Clean()...) f.seeder.verifyErr = errors.New("seed statement does not prepare") err := f.service.Start(context.Background()) if err == nil || !strings.Contains(err.Error(), "does not prepare") { @@ -282,7 +195,7 @@ func TestStart_SeederVerifyFailureClearsReady(t *testing.T) { } func TestStatus_ReportsHeadAndPending(t *testing.T) { - s, rec := newService(t, exists(true), history([]driver.Value{int64(1), "a", false})) + s, rec := admintest.NewService(t, admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})) st, err := s.Status(context.Background()) if err != nil { t.Fatalf("Status: %v", err) @@ -303,9 +216,9 @@ func TestStatus_ReportsHeadAndPending(t *testing.T) { } func TestVerify_RefreshesReady(t *testing.T) { - s, _ := newService(t, - exists(true), history([]driver.Value{int64(1), "a", false}), - exists(true), applied(), + s, _ := admintest.NewService(t, + admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false}), + admintest.Exists(true), admintest.Applied(), ) err := s.Verify(context.Background()) if pending, ok := errors.AsType[*migrate.PendingError](err); !ok || !slices.Equal(pending.Versions, []int{2}) { @@ -320,7 +233,7 @@ func TestVerify_RefreshesReady(t *testing.T) { } func TestVerbs_ValidateBeforeIO(t *testing.T) { - s, rec := newService(t) + s, rec := admintest.NewService(t) ctx := context.Background() cases := map[string]func() (admin.Status, error){ "down 0": func() (admin.Status, error) { return s.Down(ctx, "app", 0) }, @@ -340,7 +253,7 @@ func TestVerbs_ValidateBeforeIO(t *testing.T) { func TestUp_ReturnsRefreshedStatus(t *testing.T) { responses := append(applying(), current()...) - s, rec := newService(t, responses...) + s, rec := admintest.NewService(t, responses...) st, err := s.Up(context.Background()) if err != nil { t.Fatalf("Up: %v", err) @@ -351,7 +264,7 @@ func TestUp_ReturnsRefreshedStatus(t *testing.T) { } func TestForce_OutsideTheSetIsRefusedBeforeIO(t *testing.T) { - s, rec := newService(t, clean()...) + s, rec := admintest.NewService(t, admintest.Clean()...) ctx := context.Background() if err := s.Verify(ctx); err != nil || !s.Ready() { t.Fatalf("Verify = %v, ready %v", err, s.Ready()) @@ -367,12 +280,12 @@ func TestForce_OutsideTheSetIsRefusedBeforeIO(t *testing.T) { } func TestSteps_AppliesAndReverts(t *testing.T) { - one := history([]driver.Value{int64(1), "a", false}) - s, rec := newService(t, - locked, created, history(), sqltest.Response{}, sqltest.Response{}, unlocked, - exists(true), one, - locked, created, applied(), sqltest.Response{}, sqltest.Response{}, sqltest.Response{}, unlocked, - exists(true), one, + one := admintest.History([]driver.Value{int64(1), "a", false}) + s, rec := admintest.NewService(t, + locked, created, admintest.History(), sqltest.Response{}, sqltest.Response{}, unlocked, + admintest.Exists(true), one, + locked, created, admintest.Applied(), sqltest.Response{}, sqltest.Response{}, sqltest.Response{}, unlocked, + admintest.Exists(true), one, ) ctx := context.Background() st, err := s.Steps(ctx, "app", 1) @@ -392,9 +305,9 @@ func TestSteps_AppliesAndReverts(t *testing.T) { } func TestDown_RevertsAndReportsStatus(t *testing.T) { - s, rec := newService(t, - locked, created, applied(), sqltest.Response{}, sqltest.Response{}, sqltest.Response{}, unlocked, - exists(true), history([]driver.Value{int64(1), "a", false}), + s, rec := admintest.NewService(t, + locked, created, admintest.Applied(), sqltest.Response{}, sqltest.Response{}, sqltest.Response{}, unlocked, + admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false}), ) st, err := s.Down(context.Background(), "app", 1) if err != nil || st.Sets[0].Version != 1 || !slices.Equal(st.Sets[0].Pending, []int{2}) || st.Ready { @@ -409,7 +322,7 @@ func TestDown_RevertsAndReportsStatus(t *testing.T) { } func TestReady_SurvivesAnAbortedOperation(t *testing.T) { - s, _ := newService(t, clean()...) + s, _ := admintest.NewService(t, admintest.Clean()...) if err := s.Start(context.Background()); err != nil || !s.Ready() { t.Fatalf("Start = %v, ready %v", err, s.Ready()) } @@ -430,9 +343,9 @@ func TestReady_SurvivesAnAbortedOperation(t *testing.T) { } func TestReady_ReverifiesACorrectedSchema(t *testing.T) { - s, rec := newService(t, slices.Concat( - clean(), - []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, + s, rec := admintest.NewService(t, slices.Concat( + admintest.Clean(), + []sqltest.Response{admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})}, current(), )...) ctx := context.Background() @@ -451,8 +364,8 @@ func TestReady_ReverifiesACorrectedSchema(t *testing.T) { } func TestReady_ReverifyIsThrottled(t *testing.T) { - behind := []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})} - s, rec := newService(t, slices.Concat(clean(), behind, behind)...) + behind := []sqltest.Response{admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})} + s, rec := admintest.NewService(t, slices.Concat(admintest.Clean(), behind, behind)...) ctx := context.Background() if err := s.Start(ctx); err != nil { t.Fatalf("Start: %v", err) @@ -469,106 +382,15 @@ func TestReady_ReverifyIsThrottled(t *testing.T) { } } -func behindService(t *testing.T) *admin.Service { - t.Helper() - s, _ := newService(t, slices.Concat( - clean(), []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, - )...) - if err := s.Start(context.Background()); err != nil { - t.Fatalf("Start: %v", err) - } - if st, err := s.Status(context.Background()); err != nil || st.Ready { - t.Fatalf("Status = %+v, %v", st, err) - } - return s -} - -func TestReady_ConcurrentProbesVerifyOnce(t *testing.T) { - s := behindService(t) - var probes atomic.Int32 - admin.SetProbe(s, func(context.Context) error { - probes.Add(1) - return migrate.ErrPending - }) - var wg sync.WaitGroup - gate := make(chan struct{}) - for range 16 { - wg.Go(func() { - <-gate - _ = s.Ready() - }) - } - close(gate) - wg.Wait() - if n := probes.Load(); n != 1 { - t.Errorf("probes = %d, want 1", n) - } -} - -func TestReady_ProbesNeverOverlap(t *testing.T) { - s := behindService(t) - var probes atomic.Int32 - entered, release := make(chan struct{}), make(chan struct{}) - admin.SetProbe(s, func(context.Context) error { - if probes.Add(1) == 1 { - entered <- struct{}{} - <-release - } - return nil - }) - done := make(chan bool) - go func() { done <- s.Ready() }() - <-entered - admin.ExpireThrottle(s) - if s.Ready() || probes.Load() != 1 { - t.Errorf("a Ready during a probe verified again: probes = %d", probes.Load()) - } - close(release) - if !<-done { - t.Error("the probe's clean verify did not set Ready") - } -} - -func TestReady_ProbeYieldsToAConcurrentFinding(t *testing.T) { - s, _ := newService(t, slices.Concat( - clean(), - []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, - []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, - )...) - ctx := context.Background() - if err := s.Start(ctx); err != nil { - t.Fatalf("Start: %v", err) - } - if _, err := s.Status(ctx); err != nil { - t.Fatalf("Status: %v", err) - } - entered, release := make(chan struct{}), make(chan struct{}) - admin.SetProbe(s, func(context.Context) error { - entered <- struct{}{} - <-release - return nil - }) - done := make(chan bool) - go func() { done <- s.Ready() }() - <-entered - if st, err := s.Status(ctx); err != nil || st.Ready { - t.Fatalf("Status = %+v, %v", st, err) - } - close(release) - if <-done || s.Ready() { - t.Error("the probe's stale finding overwrote the status found behind") - } -} - func TestReady_NoVerifyBeforeStart(t *testing.T) { - s, rec := newService(t) + s, rec := admintest.NewService(t) if s.Ready() || len(rec.Calls()) != 0 { t.Errorf("ready %v, calls %v", s.Ready(), rec.Ops()) } } func TestVerify_SeederFailureLeavesTheSchemaReady(t *testing.T) { - f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, clean()...) + f := newFixture(t, admintest.Dialect{}, admin.Options{Seeder: &fakeSeeder{}}, admintest.Clean()...) f.seeder.verifyErr = errors.New("seed statement does not prepare") if err := f.service.Verify(context.Background()); !errors.Is(err, f.seeder.verifyErr) { t.Fatalf("Verify = %v, want the seeder's error", err) @@ -579,8 +401,8 @@ func TestVerify_SeederFailureLeavesTheSchemaReady(t *testing.T) { } func TestUp_DirtySetIsAConflict(t *testing.T) { - dirty := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) - s, _ := newService(t, locked, created, dirty, unlocked, exists(true), dirty) + dirty := admintest.History([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) + s, _ := admintest.NewService(t, locked, created, dirty, unlocked, admintest.Exists(true), dirty) _, err := s.Up(context.Background()) if !errors.Is(err, admin.ErrConflict) || !errors.Is(err, migrate.ErrDirty) { t.Errorf("Up = %v, want ErrConflict and ErrDirty", err) @@ -591,7 +413,7 @@ func TestUp_DirtySetIsAConflict(t *testing.T) { } func TestDiagnose_FailingPing(t *testing.T) { - s, rec := newService(t) + s, rec := admintest.NewService(t) ctx, cancel := context.WithCancel(context.Background()) cancel() d, err := s.Diagnose(ctx) @@ -604,7 +426,7 @@ func TestDiagnose_FailingPing(t *testing.T) { } func TestDiagnose_ReadsTheVersionThroughTheCapability(t *testing.T) { - s, rec := newService(t, sqltest.Response{Columns: []string{"version"}, Rows: [][]driver.Value{{"TestDB 1.0"}}}) + s, rec := admintest.NewService(t, sqltest.Response{Columns: []string{"version"}, Rows: [][]driver.Value{{"TestDB 1.0"}}}) d, err := s.Diagnose(context.Background()) if err != nil { t.Fatalf("Diagnose: %v", err) @@ -629,7 +451,7 @@ func TestDiagnose_OmitsTheVersionWithoutTheCapability(t *testing.T) { } func TestCatalog_ReadsThePatternsWithoutIO(t *testing.T) { - s, rec := newService(t) + s, rec := admintest.NewService(t) c := s.Catalog() if !slices.Equal(c.Namespaces, []string{"sql"}) || len(c.Patterns) == 0 { t.Fatalf("catalog = %v, %d patterns", c.Namespaces, len(c.Patterns)) @@ -645,7 +467,7 @@ func TestCatalog_ReadsThePatternsWithoutIO(t *testing.T) { } func TestStatements_ReadTheRegistryWithoutIO(t *testing.T) { - s, rec := newService(t) + s, rec := admintest.NewService(t) inv := s.Statements() if len(inv.Domains) != 1 || inv.Domains[0].Name != "ping" || len(inv.Domains[0].Statements) != 1 { t.Fatalf("inventory = %+v", inv) @@ -661,12 +483,12 @@ func TestStatements_ReadTheRegistryWithoutIO(t *testing.T) { func TestStatements_NoRegistryReportsNoDomains(t *testing.T) { pool, _ := sqltest.Open(t) - db := sqlate.Wrap(pool, testDialect{}) - m, err := migrate.New(db, []migrate.Set{{Name: "app", Migrations: set}}, migrate.Options{}) + db := sqlate.Wrap(pool, admintest.Dialect{}) + m, err := migrate.New(db, []migrate.Set{{Name: "app", Migrations: admintest.Migrations}}, migrate.Options{}) if err != nil { t.Fatal(err) } - s := admin.New(started(t, pool), db, m, query.MustCatalog(query.Patterns()), admin.Options{}) + s := admin.New(admintest.Started(t, pool), db, m, query.MustCatalog(query.Patterns()), admin.Options{}) if inv := s.Statements(); inv.Domains == nil || len(inv.Domains) != 0 { t.Errorf("inventory = %+v", inv) } diff --git a/admin/sets_test.go b/admin/test/sets_test.go similarity index 80% rename from admin/sets_test.go rename to admin/test/sets_test.go index 3b26aa4..9b5853e 100644 --- a/admin/sets_test.go +++ b/admin/test/sets_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/go-database/internal/admintest" "github.com/standards-lab/sqlate/migrate" "github.com/standards-lab/sqlate/sqltest" ) @@ -23,20 +24,20 @@ var base = migrate.Set{ }, } -var twoSets = []migrate.Set{base, {Name: "app", Migrations: set}} +var twoSets = []migrate.Set{base, {Name: "app", Migrations: admintest.Migrations}} func baseApplied() sqltest.Response { - return history([]driver.Value{int64(1), "base", false}) + return admintest.History([]driver.Value{int64(1), "base", false}) } func bothCurrent() []sqltest.Response { - return []sqltest.Response{exists(true), baseApplied(), exists(true), applied()} + return []sqltest.Response{admintest.Exists(true), baseApplied(), admintest.Exists(true), admintest.Applied()} } func applyingBoth() []sqltest.Response { return []sqltest.Response{ locked, - created, history(), created, history(), + created, admintest.History(), created, admintest.History(), {}, {}, {}, {}, {}, {}, {}, @@ -46,12 +47,12 @@ func applyingBoth() []sqltest.Response { func newSetsService(t *testing.T, opts admin.Options, responses ...sqltest.Response) fixture { t.Helper() - return newSetsFixture(t, twoSets, testDialect{}, opts, responses...) + return newSetsFixture(t, twoSets, admintest.Dialect{}, opts, responses...) } func TestSets_StatusReportsEverySet(t *testing.T) { f := newSetsService(t, admin.Options{}, - exists(true), baseApplied(), exists(true), history([]driver.Value{int64(1), "a", false})) + admintest.Exists(true), baseApplied(), admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})) st, err := f.service.Status(context.Background()) if err != nil { t.Fatalf("Status: %v", err) @@ -72,8 +73,8 @@ func TestSets_StartLogsPendingBySet(t *testing.T) { var buf bytes.Buffer logger := slog.New(slog.NewTextHandler(&buf, nil)) responses := slices.Concat( - []sqltest.Response{exists(false)}, - []sqltest.Response{exists(false), exists(false)}, + []sqltest.Response{admintest.Exists(false)}, + []sqltest.Response{admintest.Exists(false), admintest.Exists(false)}, applyingBoth(), bothCurrent(), ) @@ -99,7 +100,7 @@ func TestSets_StartLogsPendingBySet(t *testing.T) { func TestSets_ResetRevertsInReverseOrder(t *testing.T) { resetting := []sqltest.Response{ locked, - created, baseApplied(), created, applied(), + created, baseApplied(), created, admintest.Applied(), {}, {}, {}, {}, {}, {}, @@ -133,14 +134,14 @@ func TestSets_ResetRevertsInReverseOrder(t *testing.T) { } func TestSets_ForceRepairsTheNamedDirtySet(t *testing.T) { - dirtyApp := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) + dirtyApp := admintest.History([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) responses := slices.Concat( []sqltest.Response{locked, created, baseApplied(), created, dirtyApp, unlocked}, - []sqltest.Response{exists(true), baseApplied(), exists(true), dirtyApp}, - []sqltest.Response{exists(true), baseApplied(), exists(true), dirtyApp}, + []sqltest.Response{admintest.Exists(true), baseApplied(), admintest.Exists(true), dirtyApp}, + []sqltest.Response{admintest.Exists(true), baseApplied(), admintest.Exists(true), dirtyApp}, []sqltest.Response{locked, {}, {}, {Affected: 1}, unlocked}, - []sqltest.Response{exists(true), baseApplied(), exists(true), history([]driver.Value{int64(1), "a", false})}, - []sqltest.Response{locked, created, baseApplied(), created, history([]driver.Value{int64(1), "a", false}), {}, {}, {}, unlocked}, + []sqltest.Response{admintest.Exists(true), baseApplied(), admintest.Exists(true), admintest.History([]driver.Value{int64(1), "a", false})}, + []sqltest.Response{locked, created, baseApplied(), created, admintest.History([]driver.Value{int64(1), "a", false}), {}, {}, {}, unlocked}, bothCurrent(), ) f := newSetsService(t, admin.Options{}, responses...) @@ -184,7 +185,7 @@ func TestSets_ForceRepairsTheNamedDirtySet(t *testing.T) { func TestSets_DownBelowAnAppliedSetIsRefused(t *testing.T) { f := newSetsService(t, admin.Options{}, slices.Concat( - []sqltest.Response{locked, created, baseApplied(), created, applied(), unlocked}, + []sqltest.Response{locked, created, baseApplied(), created, admintest.Applied(), unlocked}, bothCurrent(), )...) _, err := f.service.Down(context.Background(), "base", 1) @@ -223,11 +224,11 @@ func TestSets_UnknownSetRefusedBeforeIO(t *testing.T) { func TestSets_StartOverADirtySetLogsNoApply(t *testing.T) { var buf bytes.Buffer - dirtyApp := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) + dirtyApp := admintest.History([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) f := newSetsService(t, admin.Options{Logger: slog.New(slog.NewTextHandler(&buf, nil))}, - exists(false), - exists(false), exists(true), dirtyApp, - locked, created, history(), created, dirtyApp, unlocked, + admintest.Exists(false), + admintest.Exists(false), admintest.Exists(true), dirtyApp, + locked, created, admintest.History(), created, dirtyApp, unlocked, ) err := f.service.Start(context.Background()) if !errors.Is(err, migrate.ErrDirty) || !strings.Contains(err.Error(), `"app"`) { @@ -239,9 +240,9 @@ func TestSets_StartOverADirtySetLogsNoApply(t *testing.T) { } func TestSets_StatusOverAnUnknownRowClearsReady(t *testing.T) { - newer := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", false}, []driver.Value{int64(3), "c", false}) + newer := admintest.History([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", false}, []driver.Value{int64(3), "c", false}) f := newSetsService(t, admin.Options{}, - slices.Concat(bothCurrent(), []sqltest.Response{exists(true), baseApplied(), exists(true), newer})...) + slices.Concat(bothCurrent(), []sqltest.Response{admintest.Exists(true), baseApplied(), admintest.Exists(true), newer})...) ctx := context.Background() if err := f.service.Verify(ctx); err != nil || !f.service.Ready() { t.Fatalf("Verify = %v, ready %v", err, f.service.Ready()) diff --git a/go.mod b/go.mod index f853716..457ad26 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,6 @@ module github.com/standards-lab/go-database go 1.27 require ( - github.com/standards-lab/go-core v0.12.0 + github.com/standards-lab/go-core v0.14.0 github.com/standards-lab/sqlate v0.8.0 ) diff --git a/go.sum b/go.sum index 3ddda1c..c2a49aa 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,4 @@ -github.com/standards-lab/go-core v0.12.0 h1:sqrzK6QSppEYpwvVAyiWgzNuOsjfK0Kwe86GPuZpHsU= -github.com/standards-lab/go-core v0.12.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= +github.com/standards-lab/go-core v0.14.0 h1:n8FRpoCqE0HErfo5V1iWASipo3ORx36V6ESQhgFZ27E= +github.com/standards-lab/go-core v0.14.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= github.com/standards-lab/sqlate v0.8.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= diff --git a/internal/admintest/admintest.go b/internal/admintest/admintest.go new file mode 100644 index 0000000..2d6408d --- /dev/null +++ b/internal/admintest/admintest.go @@ -0,0 +1,127 @@ +package admintest + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "testing" + "testing/fstest" + + "github.com/standards-lab/go-database" + "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/sqlate" + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/query" + "github.com/standards-lab/sqlate/sqltest" +) + +// Migrations is the migration set the fixtures run as set "app": version 1 +// is transactional, version 2 is not. +var Migrations = []migrate.Migration{ + {Version: 1, Name: "a", Up: "CREATE TABLE a (x int)", Down: "DROP TABLE a", Transactional: true}, + {Version: 2, Name: "b", Up: "CREATE INDEX CONCURRENTLY ix ON a (x)", Down: "DROP INDEX CONCURRENTLY ix"}, +} + +// Exists is the response to the check for the history table, reporting it +// present when yes. +func Exists(yes bool) sqltest.Response { + n := int64(0) + if yes { + n = 1 + } + return sqltest.Response{Columns: []string{"count"}, Rows: [][]driver.Value{{n}}} +} + +// History is the response to a read of the history table holding rows, each +// a version, a name, and a dirty flag. +func History(rows ...[]driver.Value) sqltest.Response { + return sqltest.Response{Columns: []string{"version", "name", "dirty"}, Rows: rows} +} + +// Applied is the response to a read of the history table with every one of +// [Migrations] applied cleanly. +func Applied() sqltest.Response { + var rows [][]driver.Value + for _, m := range Migrations { + rows = append(rows, []driver.Value{int64(m.Version), m.Name, false}) + } + return History(rows...) +} + +// Clean is the script of a status read over a current schema. +func Clean() []sqltest.Response { + return []sqltest.Response{Exists(true), Applied()} +} + +// Dialect is a sqltest dialect whose lock blocks, whose unlock reports +// whether the lock was held, and which reads the server version. +type Dialect struct{ sqltest.Dialect } + +// Lock takes the named lock. +func (Dialect) Lock(ctx context.Context, conn *sql.Conn, name string) error { + _, err := conn.ExecContext(ctx, "SELECT lock($1)", name) + return err +} + +// Unlock releases the named lock, failing when it was not held. +func (Dialect) Unlock(ctx context.Context, conn *sql.Conn, name string) error { + var held bool + if err := conn.QueryRowContext(ctx, "SELECT unlock($1)", name).Scan(&held); err != nil { + return err + } + if !held { + return errors.New("lock not held") + } + return nil +} + +// ServerVersion is the query that reads the server's version. +func (Dialect) ServerVersion() string { return "SELECT version()" } + +// Registry is a statement registry over fixed entries. +type Registry []admin.Entry + +// Registry returns the entries. +func (r Registry) Registry() []admin.Entry { return r } + +// Started returns a database over pool, started, and shut down when the +// test ends. +func Started(t *testing.T, pool *sql.DB) *database.DB { + t.Helper() + cfg := database.Config{Name: "test"} + if err := cfg.Finalize(""); err != nil { + t.Fatal(err) + } + base := database.New(pool, cfg) + if err := base.Start(context.Background()); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = base.Shutdown(context.Background()) }) + return base +} + +// New builds an admin service over sets on a pool scripted with responses, +// with a registry holding one compiled statement, and returns it with the +// pool's recorder. +func New(t *testing.T, sets []migrate.Set, d sqlate.Dialect, mopts migrate.Options, opts admin.Options, responses ...sqltest.Response) (*admin.Service, *sqltest.Recorder) { + t.Helper() + pool, rec := sqltest.Open(t, responses...) + db := sqlate.Wrap(pool, d) + m, err := migrate.New(db, sets, mopts) + if err != nil { + t.Fatalf("migrate.New: %v", err) + } + catalog := query.MustCatalog(query.Patterns()) + files := fstest.MapFS{"sql/ping.sql": {Data: []byte("--| tier: standard\nSELECT {{n:integer}}")}} + stmts := catalog.MustCompile(files, "sql", d) + opts.Registry = Registry{{Name: "ping", Statements: stmts}} + return admin.New(Started(t, pool), db, m, catalog, opts), rec +} + +// NewService builds an admin service over [Migrations] as set "app" with +// [Dialect] and no options, on a pool scripted with responses. +func NewService(t *testing.T, responses ...sqltest.Response) (*admin.Service, *sqltest.Recorder) { + t.Helper() + return New(t, []migrate.Set{{Name: "app", Migrations: Migrations}}, Dialect{}, migrate.Options{}, admin.Options{}, responses...) +} diff --git a/internal/admintest/doc.go b/internal/admintest/doc.go new file mode 100644 index 0000000..bee8bca --- /dev/null +++ b/internal/admintest/doc.go @@ -0,0 +1,15 @@ +// Package admintest holds the fixtures admin's two test packages share: the +// probe-hook tests beside admin's export_test.go and the black-box tests in +// admin/test. It scripts an admin service over the sqltest driver with a +// blocking-lock dialect. +// +// The package exports: +// +// - [Migrations], the two-migration set, one transactional and one not +// - [Exists], [History], [Applied], and [Clean], scripted reads of the +// history table's existence and rows +// - [Dialect], a sqltest dialect with a blocking lock and a server version +// - [Registry], a statement registry over fixed entries +// - [Started], which starts a database over a scripted pool +// - [New] and [NewService], which build an admin service on a scripted pool +package admintest diff --git a/internal/sweeptest/doc.go b/internal/sweeptest/doc.go new file mode 100644 index 0000000..7d662fc --- /dev/null +++ b/internal/sweeptest/doc.go @@ -0,0 +1,17 @@ +// Package sweeptest holds the fixtures sweep's two test packages share: the +// clock-hook tests beside sweep's export_test.go and the black-box tests in +// sweep/test. It builds a sweeper over the sqltest driver and scripts its +// reclaimers. +// +// The package exports: +// +// - [Reclaimer], a reclaimer whose passes follow a script of [Result]s +// - [Reports], which records the passes a sweeper reports +// - [Logs], which captures what a sweeper logs +// - [Waiting], a gate that signals when a pass begins to wait on it +// - [Fixture], [NewFixture], and [Reg], which build a sweeper on a +// scripted pool +// - [Flag] and [Claimed], the responses to a lock's claim and release +// - [Try] and [Unlock], the lock calls [WantLocks] checks +// - [Await] and [Shutdown], which bound a wait and a drain +package sweeptest diff --git a/internal/sweeptest/sweeptest.go b/internal/sweeptest/sweeptest.go new file mode 100644 index 0000000..a3a2c12 --- /dev/null +++ b/internal/sweeptest/sweeptest.go @@ -0,0 +1,215 @@ +package sweeptest + +import ( + "bytes" + "context" + "database/sql" + "database/sql/driver" + "log/slog" + "slices" + "sync" + "testing" + "time" + + "github.com/standards-lab/go-core/reactor" + "github.com/standards-lab/go-database/sweep" + "github.com/standards-lab/sqlate" + "github.com/standards-lab/sqlate/sqltest" +) + +// Try and Unlock are the SQL of the sqltest locking dialect's try-lock and +// unlock, each followed by a space and the lock's name in a recorded call. +const ( + Try = "SELECT try_lock($1) " + Unlock = "SELECT unlock($1) " +) + +// Flag is the response to a try-lock or an unlock, granting or confirming +// it when b. +func Flag(b bool) sqltest.Response { + return sqltest.Response{Columns: []string{"ok"}, Rows: [][]driver.Value{{b}}} +} + +// Claimed is the script of a lock claimed and released. +func Claimed() []sqltest.Response { return []sqltest.Response{Flag(true), Flag(true)} } + +// Result is the outcome a [Reclaimer]'s pass returns. +type Result struct { + More bool + Err error +} + +// Reclaimer is a sweep.Reclaimer whose passes return Results in order, +// then a finished pass. Each pass appends "pass " and Name to Log when Log +// is set, and runs Block when it is set, failing with Block's error. +type Reclaimer struct { + Results []Result + Block func(ctx context.Context) error + Log *[]string + Name string + + mu sync.Mutex + budgets []int +} + +// Pass records its budget and runs the next scripted result. +func (r *Reclaimer) Pass(ctx context.Context, budget int) (bool, error) { + r.mu.Lock() + r.budgets = append(r.budgets, budget) + if r.Log != nil { + *r.Log = append(*r.Log, "pass "+r.Name) + } + var res Result + if len(r.Results) > 0 { + res, r.Results = r.Results[0], r.Results[1:] + } + block := r.Block + r.mu.Unlock() + if block != nil { + if err := block(ctx); err != nil { + return false, err + } + } + return res.More, res.Err +} + +// Passes returns the number of passes run. +func (r *Reclaimer) Passes() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.budgets) +} + +// Budgets returns the budget of each pass run, in order. +func (r *Reclaimer) Budgets() []int { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.budgets) +} + +// Reports records the passes a sweeper reports through [Reports.Hook]. +type Reports struct { + mu sync.Mutex + got []sweep.Pass +} + +// Hook is a sweep.Options OnPass that records pass. +func (p *Reports) Hook(_ context.Context, pass sweep.Pass) { + p.mu.Lock() + defer p.mu.Unlock() + p.got = append(p.got, pass) +} + +// All returns the passes recorded, in order. +func (p *Reports) All() []sweep.Pass { + p.mu.Lock() + defer p.mu.Unlock() + return slices.Clone(p.got) +} + +// Logs captures the text a logger writes. +type Logs struct { + mu sync.Mutex + buf bytes.Buffer +} + +// Write appends p to the captured text. +func (l *Logs) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.Write(p) +} + +// String returns the captured text. +func (l *Logs) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.String() +} + +// Logger returns a text logger that writes to l. +func (l *Logs) Logger() *slog.Logger { return slog.New(slog.NewTextHandler(l, nil)) } + +// Waiting is a sweep gate over Gate that sends on Began as each pass begins +// to wait for its shared hold. +type Waiting struct { + Gate *reactor.Gate + Began chan struct{} +} + +// Shared signals Began, then waits for a shared hold on Gate. +func (w Waiting) Shared(ctx context.Context) (func(), error) { + w.Began <- struct{}{} + return w.Gate.Shared(ctx) +} + +// Fixture is a sweeper with its scripted pool, the pool's recorder, and its +// captured logs. +type Fixture struct { + S *sweep.Sweeper + Pool *sql.DB + Rec *sqltest.Recorder + Logs *Logs +} + +// Reg registers r under name with interval and budget. +func Reg(name string, r sweep.Reclaimer, interval time.Duration, budget int) sweep.Registration { + return sweep.Registration{Name: name, Reclaimer: r, Policy: sweep.Policy{Interval: interval, Budget: budget}} +} + +// NewFixture builds a sweeper over regs with dialect on a scripted pool, +// logging to the fixture's [Logs]. +func NewFixture(t *testing.T, dialect sqlate.Dialect, regs []sweep.Registration, shutdown time.Duration, opts sweep.Options) Fixture { + t.Helper() + pool, rec := sqltest.Open(t) + l := &Logs{} + s, err := sweep.New(sqlate.Wrap(pool, dialect), regs, shutdown, l.Logger(), opts) + if err != nil { + t.Fatalf("New: %v", err) + } + return Fixture{S: s, Pool: pool, Rec: rec, Logs: l} +} + +func locks(rec *sqltest.Recorder) []string { + var out []string + for _, c := range rec.Calls() { + if len(c.Args) == 1 { + out = append(out, c.SQL+" "+c.Args[0].(string)) + } + } + return out +} + +// WantLocks checks that the lock calls rec recorded are want, each a [Try] +// or an [Unlock] and a lock's name, and that the script was consumed with +// no rows left open. +func WantLocks(t *testing.T, rec *sqltest.Recorder, want ...string) { + t.Helper() + if got := locks(rec); !slices.Equal(got, want) { + t.Errorf("lock calls = %q, want %q", got, want) + } + if rec.Pending() != 0 || rec.RowsLeaked() != 0 { + t.Errorf("pending = %d, leaked = %d; want 0, 0", rec.Pending(), rec.RowsLeaked()) + } +} + +// Await returns the next value from ch, failing the test after five +// seconds without one; what names the value in the failure. +func Await[T any](t *testing.T, ch <-chan T, what string) T { + t.Helper() + select { + case v := <-ch: + return v + case <-time.After(5 * time.Second): + t.Fatalf("timed out waiting for %s", what) + var zero T + return zero + } +} + +// Shutdown shuts s down within five seconds. +func Shutdown(s *sweep.Sweeper) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + return s.Shutdown(ctx) +} diff --git a/mise-tasks/acceptance b/mise-tasks/acceptance new file mode 100755 index 0000000..5232bdd --- /dev/null +++ b/mise-tasks/acceptance @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +#MISE description="The one-shot engine proof: db:up, integration, then db:down whatever the result, printing the stack's log on failure" +set -e +trap 'rc=$?; [ $rc -eq 0 ] || docker compose logs; mise run db:down; exit $rc' EXIT +mise run db:up +mise run integration diff --git a/mise-tasks/check b/mise-tasks/check new file mode 100755 index 0000000..1d18c27 --- /dev/null +++ b/mise-tasks/check @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +#MISE description="Build, vet, format, fix, tidy, test, and lint every module, vetting, fixing, and linting the integration tier with its tag but running only the unit tier, then run lint-context and lint-references, running the step scripts under scripts/check/; writes nothing" +# The check, as CI runs it: the Go step stops the check at its first failing gate; the lints step +# then runs both lints, and the check fails if either fails. +# See architecture/standards/go-elemental/principles/release-and-ci.md +set -eu +scripts/check/go.sh +scripts/check/lints.sh diff --git a/mise-tasks/integration b/mise-tasks/integration new file mode 100755 index 0000000..fd38ae7 --- /dev/null +++ b/mise-tasks/integration @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the integration tier of postgres/pgvector against the PostgreSQL named by GO_DATABASE_DSN" +set -e +cd postgres/pgvector +go test -race -tags integration -count=1 ./... diff --git a/mise-tasks/tidy b/mise-tasks/tidy new file mode 100755 index 0000000..3faba5c --- /dev/null +++ b/mise-tasks/tidy @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +#MISE description="Run go mod tidy across all modules" +set -e +for mod in $GO_MODULES; do + echo "==> tidy: $mod" + (cd "$mod" && go mod tidy) +done diff --git a/mise.agent.toml b/mise.agent.toml new file mode 100644 index 0000000..e174a16 --- /dev/null +++ b/mise.agent.toml @@ -0,0 +1,4 @@ +# The agent profile, read only where MISE_ENV=agent is set: it adds the agent tasks. +# See architecture/principles/agent-separation.md +[task_config] +includes = ["mise-tasks", ".agent/mise-tasks"] diff --git a/mise.toml b/mise.toml index 81a5e1b..05cf681 100644 --- a/mise.toml +++ b/mise.toml @@ -3,7 +3,7 @@ task.run_auto_install = false [tools] -"github:standards-lab/claude-plugins" = { version = "0.24.0", version_prefix = "marathon/v" } +"github:standards-lab/claude-plugins" = { version = "0.25.0", version_prefix = "marathon/v" } go = "1.27.4" golangci-lint = "2.15.0" jq = "1.8.2" @@ -15,36 +15,6 @@ GO_DATABASE_DSN = "postgres://app:app@127.0.0.1:{{ get_env(name='POSTGRES_PORT', HOLDS = ''' ''' -[tasks.check] -description = "Build, vet, format, fix, tidy, test, and lint every module, vetting, fixing, and linting the integration tier with its tag but running only the unit tier, then run lint-context and lint-references; writes nothing" -run = ''' -set -eu -export GOWORK=off -for mod in $GO_MODULES; do - echo "check: $mod" - cd "$MISE_PROJECT_ROOT/$mod" - go build ./... - go vet -tags integration ./... - unformatted=$(gofmt -l .) - if [ -n "$unformatted" ]; then echo "gofmt: unformatted files:"; echo "$unformatted"; exit 1; fi - go fix -diff -tags integration ./... - go mod tidy -diff - go test -race ./... - golangci-lint run --build-tags integration ./... -done -cd "$MISE_PROJECT_ROOT" -fail=0 -for lint in lint-context lint-references; do - if ! command -v "$lint" >/dev/null; then - echo "FAIL: $lint is not on PATH; run mise install" >&2 - fail=1 - elif ! "$lint"; then - fail=1 - fi -done -exit "$fail" -''' - [tasks.currency] description = "Report every mise tool, Go version, requirement, action pin, image tag, and Dockerfile source ARG behind its latest, a held one with its reason; writes nothing" run = "scripts/currency.sh report" @@ -53,76 +23,10 @@ run = "scripts/currency.sh report" description = "Bump the mise tools, then each module's go directive (to the current Go minor, with no toolchain line) and direct requirements, with a tidy, then the action pins, image tags, Dockerfile FROM tags, and Dockerfile source ARGs, to their latest, but a held one; rewrites mise.toml, go.mod, go.sum, the workflows, and the compose files" run = "scripts/currency.sh upgrade" -[tasks.build] -description = "Build every module in GO_MODULES standalone with GOWORK=off, resolving its pins as a consumer does" -run = ''' -set -e -for mod in $GO_MODULES; do - echo "==> build: $mod" - (cd "$mod" && GOWORK=off go build ./...) -done -''' - -[tasks.test] -description = "Run tests across all modules" -run = ''' -set -e -for mod in $GO_MODULES; do - echo "==> test: $mod" - (cd "$mod" && go test -race ./...) -done -''' - -[tasks.vet] -description = "Run go vet across all modules" -run = ''' -set -e -for mod in $GO_MODULES; do - echo "==> vet: $mod" - (cd "$mod" && go vet ./...) -done -''' - [tasks.fmt] description = "Format all Go source" run = "gofmt -w ." -[tasks.tidy] -description = "Run go mod tidy across all modules" -run = ''' -set -e -for mod in $GO_MODULES; do - echo "==> tidy: $mod" - (cd "$mod" && go mod tidy) -done -''' - -[tasks.lint] -description = "Run golangci-lint across all modules" -run = ''' -set -e -for mod in $GO_MODULES; do - echo "==> lint: $mod" - (cd "$mod" && golangci-lint run ./...) -done -''' - -[tasks.integration] -description = "Run the integration tier of postgres/pgvector against the PostgreSQL named by GO_DATABASE_DSN" -run = ''' -cd postgres/pgvector -go test -race -tags integration -count=1 ./... -''' - -[tasks.acceptance] -description = "The one-shot engine proof: db:up, integration, then db:down whatever the result, printing the stack's log on failure" -run = ''' -set -e -trap 'rc=$?; [ $rc -eq 0 ] || docker compose logs; mise run db:down; exit $rc' EXIT -mise run db:up -mise run integration -''' - [tasks."db:up"] description = "Build and start the compose PostgreSQL and wait until it is healthy" run = "docker compose up -d --wait --build" diff --git a/postgres/CHANGELOG.md b/postgres/CHANGELOG.md index f4bbd0a..b0b17bd 100644 --- a/postgres/CHANGELOG.md +++ b/postgres/CHANGELOG.md @@ -9,9 +9,14 @@ changelog covers this sub-module only; the base module keeps its own. ### Changed +- **Breaking:** The `go-core` requirement is v0.14.0. Its v0.13.0 changes `EventKind.Raise` to take + an `event.RaiseOptions`, so an importer that calls it changes with this upgrade. The provider's + own API is unchanged. - The `go-database` requirement is v0.13.0, which requires `sqlate` v0.8.0 and adds `admin.Status.Extensions`, readiness that follows each declared extension, and the `ErrConflict` mapping of the extension errors. The provider's own API is unchanged. +- The provider's tests sit in `postgres/test/` as an external test package. No exported API + changes. ## [v0.7.0] - 2026-11-11 diff --git a/postgres/go.mod b/postgres/go.mod index d62eff2..2a2f282 100644 --- a/postgres/go.mod +++ b/postgres/go.mod @@ -11,7 +11,7 @@ require ( github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect - github.com/standards-lab/go-core v0.12.0 // indirect + github.com/standards-lab/go-core v0.14.0 // indirect github.com/standards-lab/sqlate v0.8.0 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/text v0.41.0 // indirect diff --git a/postgres/go.sum b/postgres/go.sum index 0e01668..77d73e1 100644 --- a/postgres/go.sum +++ b/postgres/go.sum @@ -11,8 +11,8 @@ github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/standards-lab/go-core v0.12.0 h1:sqrzK6QSppEYpwvVAyiWgzNuOsjfK0Kwe86GPuZpHsU= -github.com/standards-lab/go-core v0.12.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= +github.com/standards-lab/go-core v0.14.0 h1:n8FRpoCqE0HErfo5V1iWASipo3ORx36V6ESQhgFZ27E= +github.com/standards-lab/go-core v0.14.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= github.com/standards-lab/go-database v0.13.0 h1:xBiN+gZE2Q0x+S/N0DgaDNqT9feHxcu43BrHXpFfLnI= github.com/standards-lab/go-database v0.13.0/go.mod h1:M4jca1wtAP4MUDAdLa+lgvBGAzyfc8A1EdpVaQssXfc= github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= diff --git a/postgres/pgvector/CHANGELOG.md b/postgres/pgvector/CHANGELOG.md index aa0afc4..c559c13 100644 --- a/postgres/pgvector/CHANGELOG.md +++ b/postgres/pgvector/CHANGELOG.md @@ -7,6 +7,15 @@ changelog covers this sub-module only; the base module and the `postgres` provid ## [Unreleased] +### Changed + +- **Breaking:** The `go-core` requirement is v0.14.0. Its v0.13.0 changes `EventKind.Raise` to take + an `event.RaiseOptions`, so an importer that calls it changes with this upgrade. The module's + own API is unchanged. +- The module's unit and integration tests sit in `postgres/pgvector/test/` as an external test + package, the integration ones still behind the `integration` build tag; `mise run acceptance` + runs them there. No exported API changes. + ## [v0.1.0] - 2026-11-24 ### Added diff --git a/postgres/pgvector/go.mod b/postgres/pgvector/go.mod index e3670b5..06cb340 100644 --- a/postgres/pgvector/go.mod +++ b/postgres/pgvector/go.mod @@ -15,7 +15,7 @@ require ( github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgx/v5 v5.13.0 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect - github.com/standards-lab/go-core v0.12.0 // indirect + github.com/standards-lab/go-core v0.14.0 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/text v0.41.0 // indirect ) diff --git a/postgres/pgvector/go.sum b/postgres/pgvector/go.sum index df1ec16..583fd54 100644 --- a/postgres/pgvector/go.sum +++ b/postgres/pgvector/go.sum @@ -15,8 +15,8 @@ github.com/pgvector/pgvector-go v0.4.1 h1:Oaj0mC0Ky8KaTweNHHpLwyFlN6a0nUFoo1vgSF github.com/pgvector/pgvector-go v0.4.1/go.mod h1:4fSXyjl1TYAIdByAql6JazKWRr2s7J0g4hcRY5cBFCk= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/standards-lab/go-core v0.12.0 h1:sqrzK6QSppEYpwvVAyiWgzNuOsjfK0Kwe86GPuZpHsU= -github.com/standards-lab/go-core v0.12.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= +github.com/standards-lab/go-core v0.14.0 h1:n8FRpoCqE0HErfo5V1iWASipo3ORx36V6ESQhgFZ27E= +github.com/standards-lab/go-core v0.14.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= github.com/standards-lab/go-database v0.13.0 h1:xBiN+gZE2Q0x+S/N0DgaDNqT9feHxcu43BrHXpFfLnI= github.com/standards-lab/go-database v0.13.0/go.mod h1:M4jca1wtAP4MUDAdLa+lgvBGAzyfc8A1EdpVaQssXfc= github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= diff --git a/postgres/pgvector/admin_live_test.go b/postgres/pgvector/test/admin_live_test.go similarity index 100% rename from postgres/pgvector/admin_live_test.go rename to postgres/pgvector/test/admin_live_test.go diff --git a/postgres/pgvector/metric_test.go b/postgres/pgvector/test/metric_test.go similarity index 100% rename from postgres/pgvector/metric_test.go rename to postgres/pgvector/test/metric_test.go diff --git a/postgres/pgvector/vector_live_test.go b/postgres/pgvector/test/vector_live_test.go similarity index 100% rename from postgres/pgvector/vector_live_test.go rename to postgres/pgvector/test/vector_live_test.go diff --git a/postgres/main_test.go b/postgres/test/main_test.go similarity index 100% rename from postgres/main_test.go rename to postgres/test/main_test.go diff --git a/postgres/postgres_test.go b/postgres/test/postgres_test.go similarity index 100% rename from postgres/postgres_test.go rename to postgres/test/postgres_test.go diff --git a/scripts/check/go.sh b/scripts/check/go.sh new file mode 100755 index 0000000..1e38894 --- /dev/null +++ b/scripts/check/go.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# The check's Go step: in each module of $GO_MODULES, with GOWORK=off, the gates in order (build, +# vet, gofmt, fix, tidy, test, lint), stopping at the first that fails. Vet, fix, and lint take the +# integration suites too; no gate writes. Gate names given as arguments run only those gates, in +# the order given. +# See architecture/standards/go-elemental/principles/release-and-ci.md +set -eu +root=$(cd "$(dirname "$0")/../.." && pwd) +export GOWORK=off +gates=${*:-build vet gofmt fix tidy test lint} +for mod in $GO_MODULES; do + echo "check: $mod" + cd "$root/$mod" + for gate in $gates; do + case $gate in + build) go build ./... ;; + vet) go vet -tags integration ./... ;; + gofmt) + unformatted=$(gofmt -l .) + if [ -n "$unformatted" ]; then echo "gofmt: unformatted files:"; echo "$unformatted"; exit 1; fi + ;; + fix) go fix -tags integration -diff ./... ;; + tidy) go mod tidy -diff ;; + test) go test -race ./... ;; + lint) golangci-lint run --build-tags integration ./... ;; + *) echo "FAIL: no Go gate named $gate" >&2; exit 2 ;; + esac + done +done diff --git a/scripts/check/lints.sh b/scripts/check/lints.sh new file mode 100755 index 0000000..df060c3 --- /dev/null +++ b/scripts/check/lints.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# The check's lints step: lint-context and lint-references at the repository root. Both lints run +# even when one fails, and the step fails if either fails. +# See architecture/standards/go-elemental/principles/release-and-ci.md +set -u +cd "$(dirname "$0")/../.." || exit +fail=0 +for lint in lint-context lint-references; do + if ! command -v "$lint" >/dev/null; then + echo "FAIL: $lint is not on PATH; run mise install" >&2 + fail=1 + continue + fi + "$lint" || fail=1 +done +exit "$fail" diff --git a/sweep/handle_test.go b/sweep/handle_test.go new file mode 100644 index 0000000..af92c41 --- /dev/null +++ b/sweep/handle_test.go @@ -0,0 +1,519 @@ +package sweep_test + +import ( + "context" + "errors" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/standards-lab/go-core/reactor" + "github.com/standards-lab/go-database/internal/sweeptest" + "github.com/standards-lab/go-database/sweep" + "github.com/standards-lab/sqlate/sqltest" +) + +var t0 = time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC) + +func TestHandle_TicksAtTheSmallestInterval(t *testing.T) { + var order []string + slow := &sweeptest.Reclaimer{Name: "slow", Log: &order} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("slow", slow, 5*time.Minute, 1), + sweeptest.Reg("fast", &sweeptest.Reclaimer{}, time.Minute, 1), + sweeptest.Reg("rare", &sweeptest.Reclaimer{}, time.Hour, 1), + }, time.Second, sweep.Options{Unlocked: true}) + handle := sweep.Handle(f.S) + + for _, at := range []time.Duration{0, 4*time.Minute + 29*time.Second, 4*time.Minute + 31*time.Second} { + if err := handle(context.Background(), t0.Add(at)); err != nil { + t.Fatalf("handle at %v: %v", at, err) + } + } + if want := []string{"pass slow", "pass slow"}; !slices.Equal(order, want) { + t.Errorf("slow's passes = %q, want %q: due at start and from 4m30s", order, want) + } +} + +func TestHandle_ClaimsTheLockAndPassesAtTheBudget(t *testing.T) { + var p sweeptest.Reports + r := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 7)}, time.Second, sweep.Options{OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if !slices.Equal(r.Budgets(), []int{7}) { + t.Errorf("budgets = %v, want [7]", r.Budgets()) + } + got := p.All() + if len(got) != 1 || got[0].Name != "files" || got[0].More || got[0].Err != nil || got[0].Duration < 0 { + t.Errorf("reports = %+v, want one finished pass of files", got) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") + if st := f.Pool.Stats(); st.OpenConnections != 1 || st.Idle != 1 { + t.Errorf("pool = %d open, %d idle; want the released connection pooled", st.OpenConnections, st.Idle) + } +} + +func TestHandle_ALockHeldElsewhereRunsNoPassAndReportsNothing(t *testing.T) { + var p sweeptest.Reports + r := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Flag(false)) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if r.Passes() != 0 || len(p.All()) != 0 { + t.Errorf("passes = %d, reports = %+v; want none", r.Passes(), p.All()) + } + if f.Logs.String() != "" { + t.Errorf("logged %q, want nothing", f.Logs.String()) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files") +} + +func TestHandle_PassesWhileMoreUnderOneClaim(t *testing.T) { + var p sweeptest.Reports + r := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: true}, {More: true}, {More: false}}} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 3)}, time.Second, sweep.Options{OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if r.Passes() != 3 { + t.Errorf("passes = %d, want 3", r.Passes()) + } + var more []bool + for _, got := range p.All() { + more = append(more, got.More) + } + if !slices.Equal(more, []bool{true, true, false}) { + t.Errorf("reported more = %v, want [true true false]", more) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *clock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +func endless(name string, log *[]string, c *clock, step time.Duration) *sweeptest.Reclaimer { + results := make([]sweeptest.Result, 100) + for i := range results { + results[i].More = true + } + return &sweeptest.Reclaimer{Name: name, Log: log, Results: results, Block: func(context.Context) error { + c.advance(step) + return nil + }} +} + +func TestHandle_ACycleYieldsAtItsIntervalAndStaysDue(t *testing.T) { + c := &clock{t: t0} + r := endless("files", nil, c, 20*time.Second) + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{}) + sweep.SetClock(f.S, c.now) + handle := sweep.Handle(f.S) + + f.Rec.Queue(sweeptest.Claimed()...) + if err := handle(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if r.Passes() != 3 { + t.Fatalf("passes = %d, want the cycle to end at its interval, after 3", r.Passes()) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") + + f.Rec.Queue(sweeptest.Claimed()...) + if err := handle(context.Background(), t0.Add(time.Second)); err != nil { + t.Fatalf("second handle: %v", err) + } + if r.Passes() != 6 { + t.Errorf("passes = %d, want the yielded reclaimer due again for 3 more", r.Passes()) + } + sweeptest.WantLocks(t, f.Rec, + sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files", sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +func TestHandle_AYieldingCycleLetsTheReclaimersAfterItRun(t *testing.T) { + var order []string + c := &clock{t: t0} + a := endless("a", &order, c, 30*time.Second) + b := &sweeptest.Reclaimer{Name: "b", Log: &order} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("a", a, time.Minute, 1), + sweeptest.Reg("b", b, time.Minute, 1), + }, time.Second, sweep.Options{}) + sweep.SetClock(f.S, c.now) + f.Rec.Queue(append(sweeptest.Claimed(), sweeptest.Claimed()...)...) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if want := []string{"pass a", "pass a", "pass b"}; !slices.Equal(order, want) { + t.Errorf("passes = %q, want %q: a yields at its interval and b runs after it", order, want) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.a", sweeptest.Unlock+"sweep.a", sweeptest.Try+"sweep.b", sweeptest.Unlock+"sweep.b") +} + +func TestHandle_ACycleWhoseLastPassReportsNoMoreIsNotLeftDue(t *testing.T) { + c := &clock{t: t0} + r := &sweeptest.Reclaimer{Block: func(context.Context) error { + c.advance(2 * time.Minute) + return nil + }} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{}) + sweep.SetClock(f.S, c.now) + handle := sweep.Handle(f.S) + + f.Rec.Queue(sweeptest.Claimed()...) + if err := handle(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if err := handle(context.Background(), t0.Add(time.Second)); err != nil { + t.Fatalf("second handle: %v", err) + } + if r.Passes() != 1 { + t.Errorf("passes = %d, want 1: a cycle that ran out of work is not left due", r.Passes()) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +func TestHandle_AFailedPassThatReportsMoreIsFollowedByAnother(t *testing.T) { + boom := errors.New("boom") + var p sweeptest.Reports + r := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: true, Err: boom}, {More: false}}} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle returned the pass's error: %v", err) + } + if r.Passes() != 2 { + t.Fatalf("passes = %d, want the failed pass's more to run a second", r.Passes()) + } + got := p.All() + if len(got) != 2 || !errors.Is(got[0].Err, boom) || !got[0].More || got[1].Err != nil || got[1].More { + t.Errorf("reports = %+v, want the failed pass with its more, then the finished one", got) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +func TestHandle_AFailedPassWithoutMoreEndsTheCycleAndTheNextIntervalRetries(t *testing.T) { + boom := errors.New("boom") + var p sweeptest.Reports + r := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: false, Err: boom}, {More: true}, {More: false}}} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + handle := sweep.Handle(f.S) + + if err := handle(context.Background(), t0); err != nil { + t.Fatalf("handle returned the pass's error: %v", err) + } + if r.Passes() != 1 { + t.Fatalf("passes = %d, want the cycle to end after a pass without more", r.Passes()) + } + if got := p.All(); len(got) != 1 || !errors.Is(got[0].Err, boom) || got[0].More { + t.Errorf("reports = %+v, want the failed pass", got) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") + + f.Rec.Queue(sweeptest.Claimed()...) + if err := handle(context.Background(), t0.Add(time.Minute)); err != nil { + t.Fatalf("second handle: %v", err) + } + if r.Passes() != 3 { + t.Errorf("passes = %d, want the next interval to run a cycle of two", r.Passes()) + } +} + +func TestHandle_TheDefaultHookLogsOnlyAFailedPass(t *testing.T) { + boom := errors.New("boom") + ok := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: false}}} + bad := &sweeptest.Reclaimer{Results: []sweeptest.Result{{Err: boom}}} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("ok", ok, time.Minute, 1), + sweeptest.Reg("bad", bad, time.Minute, 1), + }, time.Second, sweep.Options{}) + f.Rec.Queue(append(sweeptest.Claimed(), sweeptest.Claimed()...)...) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + out := f.Logs.String() + if strings.Count(out, "\n") != 1 || !strings.Contains(out, "level=WARN") || + !strings.Contains(out, `msg="sweep pass failed"`) || !strings.Contains(out, "reclaimer=bad") || + !strings.Contains(out, "error=boom") { + t.Errorf("log = %q, want one warn line for bad's pass", out) + } +} + +func TestHandle_NudgeRunsOnlyTheNamedReclaimer(t *testing.T) { + var order []string + a := &sweeptest.Reclaimer{Name: "a", Log: &order} + b := &sweeptest.Reclaimer{Name: "b", Log: &order} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("a", a, time.Minute, 1), + sweeptest.Reg("b", b, time.Minute, 1), + }, time.Second, sweep.Options{}) + handle := sweep.Handle(f.S) + f.Rec.Queue(append(sweeptest.Claimed(), sweeptest.Claimed()...)...) + if err := handle(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + + f.S.Nudge("b") + f.Rec.Queue(sweeptest.Claimed()...) + if err := handle(context.Background(), t0.Add(time.Second)); err != nil { + t.Fatalf("handle: %v", err) + } + if want := []string{"pass a", "pass b", "pass b"}; !slices.Equal(order, want) { + t.Errorf("passes = %q, want %q", order, want) + } + + if err := handle(context.Background(), t0.Add(2*time.Second)); err != nil { + t.Fatalf("handle: %v", err) + } + if len(order) != 3 { + t.Errorf("passes = %q, want no further pass", order) + } + sweeptest.WantLocks(t, f.Rec, + sweeptest.Try+"sweep.a", sweeptest.Unlock+"sweep.a", sweeptest.Try+"sweep.b", sweeptest.Unlock+"sweep.b", + sweeptest.Try+"sweep.b", sweeptest.Unlock+"sweep.b") +} + +func TestHandle_EachReclaimerRunsOnItsOwnInterval(t *testing.T) { + var order []string + fast := &sweeptest.Reclaimer{Name: "fast", Log: &order} + slow := &sweeptest.Reclaimer{Name: "slow", Log: &order} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("fast", fast, time.Minute, 1), + sweeptest.Reg("slow", slow, 3*time.Minute, 1), + }, time.Second, sweep.Options{Unlocked: true}) + handle := sweep.Handle(f.S) + + steps := []struct { + at time.Duration + want []string + }{ + {0, []string{"fast", "slow"}}, + {29 * time.Second, nil}, + {time.Minute - time.Second, []string{"fast"}}, + {2 * time.Minute, []string{"fast"}}, + {3*time.Minute - time.Second, []string{"fast", "slow"}}, + {3 * time.Minute, nil}, + } + for _, step := range steps { + order = order[:0] + if err := handle(context.Background(), t0.Add(step.at)); err != nil { + t.Fatalf("handle at %v: %v", step.at, err) + } + var want []string + for _, n := range step.want { + want = append(want, "pass "+n) + } + if !slices.Equal(order, want) { + t.Errorf("at +%v passes = %q, want %q", step.at, order, want) + } + } +} + +func TestHandle_UnlockedTakesNoLock(t *testing.T) { + r := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: true}, {More: false}}} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{Unlocked: true}) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if r.Passes() != 2 { + t.Errorf("passes = %d, want 2", r.Passes()) + } + if calls := f.Rec.Calls(); len(calls) != 0 { + t.Errorf("calls = %+v, want none", calls) + } +} + +func TestHandle_AFailedClaimIsLoggedAndRetriedNextInterval(t *testing.T) { + r := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{}) + f.Rec.Queue(sqltest.Response{Err: errors.New("lock table full")}) + handle := sweep.Handle(f.S) + + if err := handle(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if r.Passes() != 0 { + t.Errorf("passes = %d, want none without the claim", r.Passes()) + } + if out := f.Logs.String(); !strings.Contains(out, `msg="sweep claim failed"`) || !strings.Contains(out, "lock table full") { + t.Errorf("log = %q, want the claim failure", out) + } + + f.Rec.Queue(sweeptest.Claimed()...) + if err := handle(context.Background(), t0.Add(time.Minute)); err != nil { + t.Fatalf("handle: %v", err) + } + if r.Passes() != 1 { + t.Errorf("passes = %d, want the next interval to claim and pass", r.Passes()) + } +} + +func TestHandle_AFailedReleaseIsLogged(t *testing.T) { + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", &sweeptest.Reclaimer{}, time.Minute, 1)}, time.Second, sweep.Options{}) + f.Rec.Queue(sweeptest.Flag(true), sweeptest.Flag(false)) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if out := f.Logs.String(); !strings.Contains(out, `msg="sweep release failed"`) || !strings.Contains(out, "lock not held") { + t.Errorf("log = %q, want the release failure", out) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") + if st := f.Pool.Stats(); st.OpenConnections != 0 { + t.Errorf("pool = %d open; want the connection whose unlock failed discarded", st.OpenConnections) + } +} + +func TestHandle_AnEndedContextReturnsItsErrorAndReleasesTheClaim(t *testing.T) { + var p sweeptest.Reports + ctx, cancel := context.WithCancel(context.Background()) + r := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: true}}, Block: func(context.Context) error { + cancel() + return nil + }} + next := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("files", r, time.Minute, 1), + sweeptest.Reg("next", next, time.Minute, 1), + }, time.Second, sweep.Options{OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + + if err := sweep.Handle(f.S)(ctx, t0); !errors.Is(err, context.Canceled) { + t.Fatalf("handle = %v, want the context's error", err) + } + if r.Passes() != 1 || next.Passes() != 0 { + t.Errorf("passes = %d and %d, want 1 and none", r.Passes(), next.Passes()) + } + if got := p.All(); len(got) != 0 { + t.Errorf("reports = %+v, want none for a cancelled pass", got) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +type gateLog struct { + log *[]string + err error +} + +func (g gateLog) Shared(context.Context) (func(), error) { + if g.err != nil { + return nil, g.err + } + *g.log = append(*g.log, "hold") + return func() { *g.log = append(*g.log, "release") }, nil +} + +func TestHandle_EachPassHoldsTheGateShared(t *testing.T) { + var order []string + r := &sweeptest.Reclaimer{Name: "files", Log: &order, Results: []sweeptest.Result{{More: true}, {More: false}}} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, + sweep.Options{Gate: gateLog{log: &order}}) + f.Rec.Queue(sweeptest.Claimed()...) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if want := []string{"hold", "pass files", "release", "hold", "pass files", "release"}; !slices.Equal(order, want) { + t.Errorf("order = %q, want %q", order, want) + } +} + +func TestHandle_AGateFailureIsReportedAndRunsNoPass(t *testing.T) { + refused := errors.New("gate broken") + var p sweeptest.Reports + r := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, + sweep.Options{Gate: gateLog{err: refused}, OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + + if err := sweep.Handle(f.S)(context.Background(), t0); err != nil { + t.Fatalf("handle: %v", err) + } + if r.Passes() != 0 { + t.Errorf("passes = %d, want none", r.Passes()) + } + if got := p.All(); len(got) != 1 || !errors.Is(got[0].Err, refused) { + t.Errorf("reports = %+v, want the gate's failure", got) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +func TestHandle_AGateWaitItsContextEndsRunsNoPass(t *testing.T) { + var p sweeptest.Reports + g := &reactor.Gate{} + hold, err := g.Exclusive(context.Background()) + if err != nil { + t.Fatal(err) + } + defer hold() + w := sweeptest.Waiting{Gate: g, Began: make(chan struct{}, 1)} + r := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Minute, 1)}, time.Second, + sweep.Options{Gate: w, OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- sweep.Handle(f.S)(ctx, t0) }() + sweeptest.Await(t, w.Began, "the gate wait") + cancel() + if err := sweeptest.Await(t, done, "the handler"); !errors.Is(err, context.Canceled) { + t.Errorf("handle = %v, want the context's error", err) + } + if r.Passes() != 0 || len(p.All()) != 0 { + t.Errorf("passes = %d, reports = %+v; want none", r.Passes(), p.All()) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +func TestSweeper_AYieldingCycleNudgesTheReactor(t *testing.T) { + c := &clock{t: t0} + ran := make(chan struct{}, 2) + r := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: true}}, Block: func(context.Context) error { + c.advance(time.Hour) + ran <- struct{}{} + return nil + }} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Hour, 1)}, time.Second, sweep.Options{}) + sweep.SetClock(f.S, c.now) + f.Rec.Queue(append(sweeptest.Claimed(), sweeptest.Claimed()...)...) + if err := f.S.Start(context.Background()); err != nil { + t.Fatal(err) + } + sweeptest.Await(t, ran, "the first pass") + sweeptest.Await(t, ran, "the pass the yield's delivery runs") + if err := sweeptest.Shutdown(f.S); err != nil { + t.Errorf("Shutdown: %v", err) + } + sweeptest.WantLocks(t, f.Rec, + sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files", sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} diff --git a/sweep/sweep_test.go b/sweep/sweep_test.go deleted file mode 100644 index 9df7171..0000000 --- a/sweep/sweep_test.go +++ /dev/null @@ -1,880 +0,0 @@ -package sweep_test - -import ( - "bytes" - "context" - "database/sql" - "database/sql/driver" - "errors" - "log/slog" - "slices" - "strings" - "sync" - "testing" - "time" - - "github.com/standards-lab/go-core/reactor" - "github.com/standards-lab/go-database/sweep" - "github.com/standards-lab/sqlate" - "github.com/standards-lab/sqlate/sqltest" -) - -var t0 = time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC) - -func flag(b bool) sqltest.Response { - return sqltest.Response{Columns: []string{"ok"}, Rows: [][]driver.Value{{b}}} -} - -func claimed() []sqltest.Response { return []sqltest.Response{flag(true), flag(true)} } - -type result struct { - more bool - err error -} - -type reclaimer struct { - mu sync.Mutex - results []result - budgets []int - block func(ctx context.Context) error - log *[]string - name string -} - -func (r *reclaimer) Pass(ctx context.Context, budget int) (bool, error) { - r.mu.Lock() - r.budgets = append(r.budgets, budget) - if r.log != nil { - *r.log = append(*r.log, "pass "+r.name) - } - var res result - if len(r.results) > 0 { - res, r.results = r.results[0], r.results[1:] - } - block := r.block - r.mu.Unlock() - if block != nil { - if err := block(ctx); err != nil { - return false, err - } - } - return res.more, res.err -} - -func (r *reclaimer) passes() int { - r.mu.Lock() - defer r.mu.Unlock() - return len(r.budgets) -} - -type passes struct { - mu sync.Mutex - got []sweep.Pass -} - -func (p *passes) hook(_ context.Context, pass sweep.Pass) { - p.mu.Lock() - defer p.mu.Unlock() - p.got = append(p.got, pass) -} - -func (p *passes) all() []sweep.Pass { - p.mu.Lock() - defer p.mu.Unlock() - return slices.Clone(p.got) -} - -type logs struct { - mu sync.Mutex - buf bytes.Buffer -} - -func (l *logs) Write(p []byte) (int, error) { - l.mu.Lock() - defer l.mu.Unlock() - return l.buf.Write(p) -} - -func (l *logs) String() string { - l.mu.Lock() - defer l.mu.Unlock() - return l.buf.String() -} - -func (l *logs) logger() *slog.Logger { return slog.New(slog.NewTextHandler(l, nil)) } - -type fixture struct { - s *sweep.Sweeper - pool *sql.DB - rec *sqltest.Recorder - logs *logs -} - -func reg(name string, r sweep.Reclaimer, interval time.Duration, budget int) sweep.Registration { - return sweep.Registration{Name: name, Reclaimer: r, Policy: sweep.Policy{Interval: interval, Budget: budget}} -} - -func newFixture(t *testing.T, dialect sqlate.Dialect, regs []sweep.Registration, shutdown time.Duration, opts sweep.Options) fixture { - t.Helper() - pool, rec := sqltest.Open(t) - l := &logs{} - s, err := sweep.New(sqlate.Wrap(pool, dialect), regs, shutdown, l.logger(), opts) - if err != nil { - t.Fatalf("New: %v", err) - } - return fixture{s: s, pool: pool, rec: rec, logs: l} -} - -func locks(rec *sqltest.Recorder) []string { - var out []string - for _, c := range rec.Calls() { - if len(c.Args) == 1 { - out = append(out, c.SQL+" "+c.Args[0].(string)) - } - } - return out -} - -func wantLocks(t *testing.T, rec *sqltest.Recorder, want ...string) { - t.Helper() - if got := locks(rec); !slices.Equal(got, want) { - t.Errorf("lock calls = %q, want %q", got, want) - } - if rec.Pending() != 0 || rec.RowsLeaked() != 0 { - t.Errorf("pending = %d, leaked = %d; want 0, 0", rec.Pending(), rec.RowsLeaked()) - } -} - -func await[T any](t *testing.T, ch <-chan T, what string) T { - t.Helper() - select { - case v := <-ch: - return v - case <-time.After(5 * time.Second): - t.Fatalf("timed out waiting for %s", what) - var zero T - return zero - } -} - -func shutdown(s *sweep.Sweeper) error { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - return s.Shutdown(ctx) -} - -const ( - try = "SELECT try_lock($1) " - unlock = "SELECT unlock($1) " -) - -func TestNew_RefusesBeforeAnyIO(t *testing.T) { - r := &reclaimer{} - cases := []struct { - name string - dialect sqlate.Dialect - regs []sweep.Registration - shutdown time.Duration - opts sweep.Options - want string - is error - }{ - {name: "no reclaimers", want: "no reclaimers"}, - {name: "empty name", regs: []sweep.Registration{reg("", r, time.Minute, 1)}, want: "no name"}, - {name: "duplicate name", regs: []sweep.Registration{reg("a", r, time.Minute, 1), reg("a", r, time.Minute, 1)}, want: `"a" is registered twice`}, - {name: "nil reclaimer", regs: []sweep.Registration{reg("a", nil, time.Minute, 1)}, want: `"a" is nil`}, - {name: "zero interval", regs: []sweep.Registration{reg("a", r, 0, 1)}, want: "interval must be positive"}, - {name: "negative interval", regs: []sweep.Registration{reg("a", r, -time.Second, 1)}, want: "interval must be positive"}, - {name: "zero budget", regs: []sweep.Registration{reg("a", r, time.Minute, 0)}, want: "budget must be positive"}, - {name: "negative budget", regs: []sweep.Registration{reg("a", r, time.Minute, -1)}, want: "budget must be positive"}, - {name: "zero shutdown", regs: []sweep.Registration{reg("a", r, time.Minute, 1)}, shutdown: -1, want: "shutdown must be positive"}, - {name: "no try-lock", dialect: sqltest.Dialect{}, regs: []sweep.Registration{reg("a", r, time.Minute, 1)}, is: sweep.ErrNoTryLocker}, - {name: "no try-lock, gated", dialect: sqltest.Dialect{}, regs: []sweep.Registration{reg("a", r, time.Minute, 1)}, opts: sweep.Options{Gate: &reactor.Gate{}}, is: sweep.ErrNoTryLocker}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - pool, rec := sqltest.Open(t) - dialect := tc.dialect - if dialect == nil { - dialect = sqltest.LockingDialect{} - } - shutdown := tc.shutdown - if shutdown == 0 { - shutdown = time.Second - } else if shutdown < 0 { - shutdown = 0 - } - s, err := sweep.New(sqlate.Wrap(pool, dialect), tc.regs, shutdown, slog.New(slog.DiscardHandler), tc.opts) - if s != nil || err == nil { - t.Fatalf("New = %v, %v; want a refusal", s, err) - } - if tc.is != nil && !errors.Is(err, tc.is) { - t.Errorf("err = %v, want %v", err, tc.is) - } - if tc.want != "" && !strings.Contains(err.Error(), tc.want) { - t.Errorf("err = %v, want it to mention %q", err, tc.want) - } - if calls := rec.Calls(); len(calls) != 0 { - t.Errorf("calls = %+v, want none", calls) - } - }) - } -} - -func TestNew_UnlockedAcceptsADialectWithoutTryLock(t *testing.T) { - f := newFixture(t, sqltest.Dialect{}, []sweep.Registration{reg("a", &reclaimer{}, time.Minute, 1)}, time.Second, sweep.Options{Unlocked: true}) - if f.s == nil { - t.Fatal("New returned no sweeper") - } -} - -func TestNew_WiringDefectsPanic(t *testing.T) { - pool, _ := sqltest.Open(t) - db := sqlate.Wrap(pool, sqltest.LockingDialect{}) - regs := []sweep.Registration{reg("a", &reclaimer{}, time.Minute, 1)} - for name, call := range map[string]func(){ - "nil db": func() { _, _ = sweep.New(nil, regs, time.Second, slog.New(slog.DiscardHandler), sweep.Options{}) }, - "nil logger": func() { _, _ = sweep.New(db, regs, time.Second, nil, sweep.Options{}) }, - } { - t.Run(name, func(t *testing.T) { - defer func() { - if recover() == nil { - t.Error("no panic") - } - }() - call() - }) - } -} - -func TestHandle_TicksAtTheSmallestInterval(t *testing.T) { - var order []string - slow := &reclaimer{name: "slow", log: &order} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("slow", slow, 5*time.Minute, 1), - reg("fast", &reclaimer{}, time.Minute, 1), - reg("rare", &reclaimer{}, time.Hour, 1), - }, time.Second, sweep.Options{Unlocked: true}) - handle := sweep.Handle(f.s) - - for _, at := range []time.Duration{0, 4*time.Minute + 29*time.Second, 4*time.Minute + 31*time.Second} { - if err := handle(context.Background(), t0.Add(at)); err != nil { - t.Fatalf("handle at %v: %v", at, err) - } - } - if want := []string{"pass slow", "pass slow"}; !slices.Equal(order, want) { - t.Errorf("slow's passes = %q, want %q: due at start and from 4m30s", order, want) - } -} - -func TestHandle_ClaimsTheLockAndPassesAtTheBudget(t *testing.T) { - var p passes - r := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 7)}, time.Second, sweep.Options{OnPass: p.hook}) - f.rec.Queue(claimed()...) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if !slices.Equal(r.budgets, []int{7}) { - t.Errorf("budgets = %v, want [7]", r.budgets) - } - got := p.all() - if len(got) != 1 || got[0].Name != "files" || got[0].More || got[0].Err != nil || got[0].Duration < 0 { - t.Errorf("reports = %+v, want one finished pass of files", got) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") - if st := f.pool.Stats(); st.OpenConnections != 1 || st.Idle != 1 { - t.Errorf("pool = %d open, %d idle; want the released connection pooled", st.OpenConnections, st.Idle) - } -} - -func TestHandle_ALockHeldElsewhereRunsNoPassAndReportsNothing(t *testing.T) { - var p passes - r := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{OnPass: p.hook}) - f.rec.Queue(flag(false)) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if r.passes() != 0 || len(p.all()) != 0 { - t.Errorf("passes = %d, reports = %+v; want none", r.passes(), p.all()) - } - if f.logs.String() != "" { - t.Errorf("logged %q, want nothing", f.logs.String()) - } - wantLocks(t, f.rec, try+"sweep.files") -} - -func TestHandle_PassesWhileMoreUnderOneClaim(t *testing.T) { - var p passes - r := &reclaimer{results: []result{{more: true}, {more: true}, {more: false}}} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 3)}, time.Second, sweep.Options{OnPass: p.hook}) - f.rec.Queue(claimed()...) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if r.passes() != 3 { - t.Errorf("passes = %d, want 3", r.passes()) - } - var more []bool - for _, got := range p.all() { - more = append(more, got.More) - } - if !slices.Equal(more, []bool{true, true, false}) { - t.Errorf("reported more = %v, want [true true false]", more) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -type clock struct { - mu sync.Mutex - t time.Time -} - -func (c *clock) now() time.Time { - c.mu.Lock() - defer c.mu.Unlock() - return c.t -} - -func (c *clock) advance(d time.Duration) { - c.mu.Lock() - defer c.mu.Unlock() - c.t = c.t.Add(d) -} - -func endless(name string, log *[]string, c *clock, step time.Duration) *reclaimer { - results := make([]result, 100) - for i := range results { - results[i].more = true - } - return &reclaimer{name: name, log: log, results: results, block: func(context.Context) error { - c.advance(step) - return nil - }} -} - -func TestHandle_ACycleYieldsAtItsIntervalAndStaysDue(t *testing.T) { - c := &clock{t: t0} - r := endless("files", nil, c, 20*time.Second) - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{}) - sweep.SetClock(f.s, c.now) - handle := sweep.Handle(f.s) - - f.rec.Queue(claimed()...) - if err := handle(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if r.passes() != 3 { - t.Fatalf("passes = %d, want the cycle to end at its interval, after 3", r.passes()) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") - - f.rec.Queue(claimed()...) - if err := handle(context.Background(), t0.Add(time.Second)); err != nil { - t.Fatalf("second handle: %v", err) - } - if r.passes() != 6 { - t.Errorf("passes = %d, want the yielded reclaimer due again for 3 more", r.passes()) - } - wantLocks(t, f.rec, - try+"sweep.files", unlock+"sweep.files", try+"sweep.files", unlock+"sweep.files") -} - -func TestHandle_AYieldingCycleLetsTheReclaimersAfterItRun(t *testing.T) { - var order []string - c := &clock{t: t0} - a := endless("a", &order, c, 30*time.Second) - b := &reclaimer{name: "b", log: &order} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("a", a, time.Minute, 1), - reg("b", b, time.Minute, 1), - }, time.Second, sweep.Options{}) - sweep.SetClock(f.s, c.now) - f.rec.Queue(append(claimed(), claimed()...)...) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if want := []string{"pass a", "pass a", "pass b"}; !slices.Equal(order, want) { - t.Errorf("passes = %q, want %q: a yields at its interval and b runs after it", order, want) - } - wantLocks(t, f.rec, try+"sweep.a", unlock+"sweep.a", try+"sweep.b", unlock+"sweep.b") -} - -func TestHandle_ACycleWhoseLastPassReportsNoMoreIsNotLeftDue(t *testing.T) { - c := &clock{t: t0} - r := &reclaimer{block: func(context.Context) error { - c.advance(2 * time.Minute) - return nil - }} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{}) - sweep.SetClock(f.s, c.now) - handle := sweep.Handle(f.s) - - f.rec.Queue(claimed()...) - if err := handle(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if err := handle(context.Background(), t0.Add(time.Second)); err != nil { - t.Fatalf("second handle: %v", err) - } - if r.passes() != 1 { - t.Errorf("passes = %d, want 1: a cycle that ran out of work is not left due", r.passes()) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -func TestHandle_AFailedPassThatReportsMoreIsFollowedByAnother(t *testing.T) { - boom := errors.New("boom") - var p passes - r := &reclaimer{results: []result{{more: true, err: boom}, {more: false}}} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{OnPass: p.hook}) - f.rec.Queue(claimed()...) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle returned the pass's error: %v", err) - } - if r.passes() != 2 { - t.Fatalf("passes = %d, want the failed pass's more to run a second", r.passes()) - } - got := p.all() - if len(got) != 2 || !errors.Is(got[0].Err, boom) || !got[0].More || got[1].Err != nil || got[1].More { - t.Errorf("reports = %+v, want the failed pass with its more, then the finished one", got) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -func TestHandle_AFailedPassWithoutMoreEndsTheCycleAndTheNextIntervalRetries(t *testing.T) { - boom := errors.New("boom") - var p passes - r := &reclaimer{results: []result{{more: false, err: boom}, {more: true}, {more: false}}} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{OnPass: p.hook}) - f.rec.Queue(claimed()...) - handle := sweep.Handle(f.s) - - if err := handle(context.Background(), t0); err != nil { - t.Fatalf("handle returned the pass's error: %v", err) - } - if r.passes() != 1 { - t.Fatalf("passes = %d, want the cycle to end after a pass without more", r.passes()) - } - if got := p.all(); len(got) != 1 || !errors.Is(got[0].Err, boom) || got[0].More { - t.Errorf("reports = %+v, want the failed pass", got) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") - - f.rec.Queue(claimed()...) - if err := handle(context.Background(), t0.Add(time.Minute)); err != nil { - t.Fatalf("second handle: %v", err) - } - if r.passes() != 3 { - t.Errorf("passes = %d, want the next interval to run a cycle of two", r.passes()) - } -} - -func TestHandle_TheDefaultHookLogsOnlyAFailedPass(t *testing.T) { - boom := errors.New("boom") - ok := &reclaimer{results: []result{{more: false}}} - bad := &reclaimer{results: []result{{err: boom}}} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("ok", ok, time.Minute, 1), - reg("bad", bad, time.Minute, 1), - }, time.Second, sweep.Options{}) - f.rec.Queue(append(claimed(), claimed()...)...) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - out := f.logs.String() - if strings.Count(out, "\n") != 1 || !strings.Contains(out, "level=WARN") || - !strings.Contains(out, `msg="sweep pass failed"`) || !strings.Contains(out, "reclaimer=bad") || - !strings.Contains(out, "error=boom") { - t.Errorf("log = %q, want one warn line for bad's pass", out) - } -} - -func TestHandle_NudgeRunsOnlyTheNamedReclaimer(t *testing.T) { - var order []string - a := &reclaimer{name: "a", log: &order} - b := &reclaimer{name: "b", log: &order} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("a", a, time.Minute, 1), - reg("b", b, time.Minute, 1), - }, time.Second, sweep.Options{}) - handle := sweep.Handle(f.s) - f.rec.Queue(append(claimed(), claimed()...)...) - if err := handle(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - - f.s.Nudge("b") - f.rec.Queue(claimed()...) - if err := handle(context.Background(), t0.Add(time.Second)); err != nil { - t.Fatalf("handle: %v", err) - } - if want := []string{"pass a", "pass b", "pass b"}; !slices.Equal(order, want) { - t.Errorf("passes = %q, want %q", order, want) - } - - if err := handle(context.Background(), t0.Add(2*time.Second)); err != nil { - t.Fatalf("handle: %v", err) - } - if len(order) != 3 { - t.Errorf("passes = %q, want no further pass", order) - } - wantLocks(t, f.rec, - try+"sweep.a", unlock+"sweep.a", try+"sweep.b", unlock+"sweep.b", - try+"sweep.b", unlock+"sweep.b") -} - -func TestNudge_AnUnregisteredNamePanics(t *testing.T) { - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("a", &reclaimer{}, time.Minute, 1)}, time.Second, sweep.Options{}) - defer func() { - if recover() == nil { - t.Error("Nudge of an unregistered name did not panic") - } - }() - f.s.Nudge("b") -} - -func TestHandle_EachReclaimerRunsOnItsOwnInterval(t *testing.T) { - var order []string - fast := &reclaimer{name: "fast", log: &order} - slow := &reclaimer{name: "slow", log: &order} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("fast", fast, time.Minute, 1), - reg("slow", slow, 3*time.Minute, 1), - }, time.Second, sweep.Options{Unlocked: true}) - handle := sweep.Handle(f.s) - - steps := []struct { - at time.Duration - want []string - }{ - {0, []string{"fast", "slow"}}, - {29 * time.Second, nil}, - {time.Minute - time.Second, []string{"fast"}}, - {2 * time.Minute, []string{"fast"}}, - {3*time.Minute - time.Second, []string{"fast", "slow"}}, - {3 * time.Minute, nil}, - } - for _, step := range steps { - order = order[:0] - if err := handle(context.Background(), t0.Add(step.at)); err != nil { - t.Fatalf("handle at %v: %v", step.at, err) - } - var want []string - for _, n := range step.want { - want = append(want, "pass "+n) - } - if !slices.Equal(order, want) { - t.Errorf("at +%v passes = %q, want %q", step.at, order, want) - } - } -} - -func TestHandle_UnlockedTakesNoLock(t *testing.T) { - r := &reclaimer{results: []result{{more: true}, {more: false}}} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{Unlocked: true}) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if r.passes() != 2 { - t.Errorf("passes = %d, want 2", r.passes()) - } - if calls := f.rec.Calls(); len(calls) != 0 { - t.Errorf("calls = %+v, want none", calls) - } -} - -func TestHandle_AFailedClaimIsLoggedAndRetriedNextInterval(t *testing.T) { - r := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{}) - f.rec.Queue(sqltest.Response{Err: errors.New("lock table full")}) - handle := sweep.Handle(f.s) - - if err := handle(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if r.passes() != 0 { - t.Errorf("passes = %d, want none without the claim", r.passes()) - } - if out := f.logs.String(); !strings.Contains(out, `msg="sweep claim failed"`) || !strings.Contains(out, "lock table full") { - t.Errorf("log = %q, want the claim failure", out) - } - - f.rec.Queue(claimed()...) - if err := handle(context.Background(), t0.Add(time.Minute)); err != nil { - t.Fatalf("handle: %v", err) - } - if r.passes() != 1 { - t.Errorf("passes = %d, want the next interval to claim and pass", r.passes()) - } -} - -func TestHandle_AFailedReleaseIsLogged(t *testing.T) { - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", &reclaimer{}, time.Minute, 1)}, time.Second, sweep.Options{}) - f.rec.Queue(flag(true), flag(false)) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if out := f.logs.String(); !strings.Contains(out, `msg="sweep release failed"`) || !strings.Contains(out, "lock not held") { - t.Errorf("log = %q, want the release failure", out) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") - if st := f.pool.Stats(); st.OpenConnections != 0 { - t.Errorf("pool = %d open; want the connection whose unlock failed discarded", st.OpenConnections) - } -} - -func TestHandle_AnEndedContextReturnsItsErrorAndReleasesTheClaim(t *testing.T) { - var p passes - ctx, cancel := context.WithCancel(context.Background()) - r := &reclaimer{results: []result{{more: true}}, block: func(context.Context) error { - cancel() - return nil - }} - next := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("files", r, time.Minute, 1), - reg("next", next, time.Minute, 1), - }, time.Second, sweep.Options{OnPass: p.hook}) - f.rec.Queue(claimed()...) - - if err := sweep.Handle(f.s)(ctx, t0); !errors.Is(err, context.Canceled) { - t.Fatalf("handle = %v, want the context's error", err) - } - if r.passes() != 1 || next.passes() != 0 { - t.Errorf("passes = %d and %d, want 1 and none", r.passes(), next.passes()) - } - if got := p.all(); len(got) != 0 { - t.Errorf("reports = %+v, want none for a cancelled pass", got) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -type gateLog struct { - log *[]string - err error -} - -func (g gateLog) Shared(context.Context) (func(), error) { - if g.err != nil { - return nil, g.err - } - *g.log = append(*g.log, "hold") - return func() { *g.log = append(*g.log, "release") }, nil -} - -func TestHandle_EachPassHoldsTheGateShared(t *testing.T) { - var order []string - r := &reclaimer{name: "files", log: &order, results: []result{{more: true}, {more: false}}} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, - sweep.Options{Gate: gateLog{log: &order}}) - f.rec.Queue(claimed()...) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if want := []string{"hold", "pass files", "release", "hold", "pass files", "release"}; !slices.Equal(order, want) { - t.Errorf("order = %q, want %q", order, want) - } -} - -func TestHandle_AGateFailureIsReportedAndRunsNoPass(t *testing.T) { - refused := errors.New("gate broken") - var p passes - r := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, - sweep.Options{Gate: gateLog{err: refused}, OnPass: p.hook}) - f.rec.Queue(claimed()...) - - if err := sweep.Handle(f.s)(context.Background(), t0); err != nil { - t.Fatalf("handle: %v", err) - } - if r.passes() != 0 { - t.Errorf("passes = %d, want none", r.passes()) - } - if got := p.all(); len(got) != 1 || !errors.Is(got[0].Err, refused) { - t.Errorf("reports = %+v, want the gate's failure", got) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -type waiting struct { - g *reactor.Gate - began chan struct{} -} - -func (w waiting) Shared(ctx context.Context) (func(), error) { - w.began <- struct{}{} - return w.g.Shared(ctx) -} - -func TestHandle_AGateWaitItsContextEndsRunsNoPass(t *testing.T) { - var p passes - g := &reactor.Gate{} - hold, err := g.Exclusive(context.Background()) - if err != nil { - t.Fatal(err) - } - defer hold() - w := waiting{g: g, began: make(chan struct{}, 1)} - r := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, - sweep.Options{Gate: w, OnPass: p.hook}) - f.rec.Queue(claimed()...) - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan error, 1) - go func() { done <- sweep.Handle(f.s)(ctx, t0) }() - await(t, w.began, "the gate wait") - cancel() - if err := await(t, done, "the handler"); !errors.Is(err, context.Canceled) { - t.Errorf("handle = %v, want the context's error", err) - } - if r.passes() != 0 || len(p.all()) != 0 { - t.Errorf("passes = %d, reports = %+v; want none", r.passes(), p.all()) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -func TestSweeper_EveryReclaimerIsDueAtStart(t *testing.T) { - ran := make(chan string, 2) - mark := func(name string) *reclaimer { - return &reclaimer{block: func(context.Context) error { ran <- name; return nil }} - } - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("a", mark("a"), time.Hour, 1), - reg("b", mark("b"), time.Hour, 1), - }, time.Second, sweep.Options{Unlocked: true}) - if f.s.Ready() { - t.Error("Ready before Start") - } - if err := f.s.Start(context.Background()); err != nil { - t.Fatal(err) - } - got := []string{await(t, ran, "a pass"), await(t, ran, "a pass")} - if err := shutdown(f.s); err != nil { - t.Errorf("Shutdown: %v", err) - } - if !slices.Equal(got, []string{"a", "b"}) { - t.Errorf("ran = %q, want both at start, in order", got) - } - if f.s.Ready() { - t.Error("Ready after Shutdown") - } -} - -func TestSweeper_AYieldingCycleNudgesTheReactor(t *testing.T) { - c := &clock{t: t0} - ran := make(chan struct{}, 2) - r := &reclaimer{results: []result{{more: true}}, block: func(context.Context) error { - c.advance(time.Hour) - ran <- struct{}{} - return nil - }} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Hour, 1)}, time.Second, sweep.Options{}) - sweep.SetClock(f.s, c.now) - f.rec.Queue(append(claimed(), claimed()...)...) - if err := f.s.Start(context.Background()); err != nil { - t.Fatal(err) - } - await(t, ran, "the first pass") - await(t, ran, "the pass the yield's delivery runs") - if err := shutdown(f.s); err != nil { - t.Errorf("Shutdown: %v", err) - } - wantLocks(t, f.rec, - try+"sweep.files", unlock+"sweep.files", try+"sweep.files", unlock+"sweep.files") -} - -func TestSweeper_TheDrainStartsNoFurtherPassAndLetsTheOneInFlightFinish(t *testing.T) { - entered := make(chan struct{}) - var readyInPass bool - var s *sweep.Sweeper - r := &reclaimer{results: []result{{more: true}, {more: true}}, block: func(ctx context.Context) error { - readyInPass = s.Ready() - close(entered) - <-reactor.Draining(ctx) - return ctx.Err() - }} - next := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ - reg("files", r, time.Hour, 1), - reg("next", next, time.Hour, 1), - }, time.Hour, sweep.Options{}) - s = f.s - f.rec.Queue(claimed()...) - if err := f.s.Start(context.Background()); err != nil { - t.Fatal(err) - } - await(t, entered, "the pass") - if err := shutdown(f.s); err != nil { - t.Errorf("Shutdown: %v", err) - } - if !readyInPass { - t.Error("not Ready while a pass ran") - } - if r.passes() != 1 || next.passes() != 0 { - t.Errorf("passes = %d and %d, want 1 and none after the drain", r.passes(), next.passes()) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -func TestSweeper_TheDrainsCancellationIsTheReactorsError(t *testing.T) { - var p passes - entered := make(chan struct{}) - r := &reclaimer{block: func(ctx context.Context) error { - close(entered) - <-ctx.Done() - return ctx.Err() - }} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Hour, 1)}, 20*time.Millisecond, - sweep.Options{OnPass: p.hook}) - f.rec.Queue(claimed()...) - if err := f.s.Start(context.Background()); err != nil { - t.Fatal(err) - } - await(t, entered, "the pass") - err := shutdown(f.s) - if err == nil || !strings.Contains(err.Error(), "handlers cancelled") { - t.Errorf("Shutdown = %v, want the handlers' cancellation", err) - } - if got := p.all(); len(got) != 0 { - t.Errorf("reports = %+v, want none for the cancelled pass", got) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} - -func TestSweeper_TheDrainEndsAGateWaitWithNoPass(t *testing.T) { - var p passes - g := &reactor.Gate{} - hold, err := g.Exclusive(context.Background()) - if err != nil { - t.Fatal(err) - } - defer hold() - w := waiting{g: g, began: make(chan struct{}, 1)} - r := &reclaimer{} - f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Hour, 1)}, time.Hour, - sweep.Options{Gate: w, OnPass: p.hook}) - f.rec.Queue(claimed()...) - if err := f.s.Start(context.Background()); err != nil { - t.Fatal(err) - } - await(t, w.began, "the gate wait") - if err := shutdown(f.s); err != nil { - t.Errorf("Shutdown = %v, want nil: the drain, not a cancellation, ended the wait", err) - } - if r.passes() != 0 || len(p.all()) != 0 { - t.Errorf("passes = %d, reports = %+v; want none", r.passes(), p.all()) - } - wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") -} diff --git a/sweep/test/sweep_test.go b/sweep/test/sweep_test.go new file mode 100644 index 0000000..242df65 --- /dev/null +++ b/sweep/test/sweep_test.go @@ -0,0 +1,217 @@ +package sweep_test + +import ( + "context" + "errors" + "log/slog" + "slices" + "strings" + "testing" + "time" + + "github.com/standards-lab/go-core/reactor" + "github.com/standards-lab/go-database/internal/sweeptest" + "github.com/standards-lab/go-database/sweep" + "github.com/standards-lab/sqlate" + "github.com/standards-lab/sqlate/sqltest" +) + +func TestNew_RefusesBeforeAnyIO(t *testing.T) { + r := &sweeptest.Reclaimer{} + cases := []struct { + name string + dialect sqlate.Dialect + regs []sweep.Registration + shutdown time.Duration + opts sweep.Options + want string + is error + }{ + {name: "no reclaimers", want: "no reclaimers"}, + {name: "empty name", regs: []sweep.Registration{sweeptest.Reg("", r, time.Minute, 1)}, want: "no name"}, + {name: "duplicate name", regs: []sweep.Registration{sweeptest.Reg("a", r, time.Minute, 1), sweeptest.Reg("a", r, time.Minute, 1)}, want: `"a" is registered twice`}, + {name: "nil reclaimer", regs: []sweep.Registration{sweeptest.Reg("a", nil, time.Minute, 1)}, want: `"a" is nil`}, + {name: "zero interval", regs: []sweep.Registration{sweeptest.Reg("a", r, 0, 1)}, want: "interval must be positive"}, + {name: "negative interval", regs: []sweep.Registration{sweeptest.Reg("a", r, -time.Second, 1)}, want: "interval must be positive"}, + {name: "zero budget", regs: []sweep.Registration{sweeptest.Reg("a", r, time.Minute, 0)}, want: "budget must be positive"}, + {name: "negative budget", regs: []sweep.Registration{sweeptest.Reg("a", r, time.Minute, -1)}, want: "budget must be positive"}, + {name: "zero shutdown", regs: []sweep.Registration{sweeptest.Reg("a", r, time.Minute, 1)}, shutdown: -1, want: "shutdown must be positive"}, + {name: "no try-lock", dialect: sqltest.Dialect{}, regs: []sweep.Registration{sweeptest.Reg("a", r, time.Minute, 1)}, is: sweep.ErrNoTryLocker}, + {name: "no try-lock, gated", dialect: sqltest.Dialect{}, regs: []sweep.Registration{sweeptest.Reg("a", r, time.Minute, 1)}, opts: sweep.Options{Gate: &reactor.Gate{}}, is: sweep.ErrNoTryLocker}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + pool, rec := sqltest.Open(t) + dialect := tc.dialect + if dialect == nil { + dialect = sqltest.LockingDialect{} + } + shutdown := tc.shutdown + if shutdown == 0 { + shutdown = time.Second + } else if shutdown < 0 { + shutdown = 0 + } + s, err := sweep.New(sqlate.Wrap(pool, dialect), tc.regs, shutdown, slog.New(slog.DiscardHandler), tc.opts) + if s != nil || err == nil { + t.Fatalf("New = %v, %v; want a refusal", s, err) + } + if tc.is != nil && !errors.Is(err, tc.is) { + t.Errorf("err = %v, want %v", err, tc.is) + } + if tc.want != "" && !strings.Contains(err.Error(), tc.want) { + t.Errorf("err = %v, want it to mention %q", err, tc.want) + } + if calls := rec.Calls(); len(calls) != 0 { + t.Errorf("calls = %+v, want none", calls) + } + }) + } +} + +func TestNew_UnlockedAcceptsADialectWithoutTryLock(t *testing.T) { + f := sweeptest.NewFixture(t, sqltest.Dialect{}, []sweep.Registration{sweeptest.Reg("a", &sweeptest.Reclaimer{}, time.Minute, 1)}, time.Second, sweep.Options{Unlocked: true}) + if f.S == nil { + t.Fatal("New returned no sweeper") + } +} + +func TestNew_WiringDefectsPanic(t *testing.T) { + pool, _ := sqltest.Open(t) + db := sqlate.Wrap(pool, sqltest.LockingDialect{}) + regs := []sweep.Registration{sweeptest.Reg("a", &sweeptest.Reclaimer{}, time.Minute, 1)} + for name, call := range map[string]func(){ + "nil db": func() { _, _ = sweep.New(nil, regs, time.Second, slog.New(slog.DiscardHandler), sweep.Options{}) }, + "nil logger": func() { _, _ = sweep.New(db, regs, time.Second, nil, sweep.Options{}) }, + } { + t.Run(name, func(t *testing.T) { + defer func() { + if recover() == nil { + t.Error("no panic") + } + }() + call() + }) + } +} + +func TestNudge_AnUnregisteredNamePanics(t *testing.T) { + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("a", &sweeptest.Reclaimer{}, time.Minute, 1)}, time.Second, sweep.Options{}) + defer func() { + if recover() == nil { + t.Error("Nudge of an unregistered name did not panic") + } + }() + f.S.Nudge("b") +} + +func TestSweeper_EveryReclaimerIsDueAtStart(t *testing.T) { + ran := make(chan string, 2) + mark := func(name string) *sweeptest.Reclaimer { + return &sweeptest.Reclaimer{Block: func(context.Context) error { ran <- name; return nil }} + } + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("a", mark("a"), time.Hour, 1), + sweeptest.Reg("b", mark("b"), time.Hour, 1), + }, time.Second, sweep.Options{Unlocked: true}) + if f.S.Ready() { + t.Error("Ready before Start") + } + if err := f.S.Start(context.Background()); err != nil { + t.Fatal(err) + } + got := []string{sweeptest.Await(t, ran, "a pass"), sweeptest.Await(t, ran, "a pass")} + if err := sweeptest.Shutdown(f.S); err != nil { + t.Errorf("Shutdown: %v", err) + } + if !slices.Equal(got, []string{"a", "b"}) { + t.Errorf("ran = %q, want both at start, in order", got) + } + if f.S.Ready() { + t.Error("Ready after Shutdown") + } +} + +func TestSweeper_TheDrainStartsNoFurtherPassAndLetsTheOneInFlightFinish(t *testing.T) { + entered := make(chan struct{}) + var readyInPass bool + var s *sweep.Sweeper + r := &sweeptest.Reclaimer{Results: []sweeptest.Result{{More: true}, {More: true}}, Block: func(ctx context.Context) error { + readyInPass = s.Ready() + close(entered) + <-reactor.Draining(ctx) + return ctx.Err() + }} + next := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ + sweeptest.Reg("files", r, time.Hour, 1), + sweeptest.Reg("next", next, time.Hour, 1), + }, time.Hour, sweep.Options{}) + s = f.S + f.Rec.Queue(sweeptest.Claimed()...) + if err := f.S.Start(context.Background()); err != nil { + t.Fatal(err) + } + sweeptest.Await(t, entered, "the pass") + if err := sweeptest.Shutdown(f.S); err != nil { + t.Errorf("Shutdown: %v", err) + } + if !readyInPass { + t.Error("not Ready while a pass ran") + } + if r.Passes() != 1 || next.Passes() != 0 { + t.Errorf("passes = %d and %d, want 1 and none after the drain", r.Passes(), next.Passes()) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +func TestSweeper_TheDrainsCancellationIsTheReactorsError(t *testing.T) { + var p sweeptest.Reports + entered := make(chan struct{}) + r := &sweeptest.Reclaimer{Block: func(ctx context.Context) error { + close(entered) + <-ctx.Done() + return ctx.Err() + }} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Hour, 1)}, 20*time.Millisecond, + sweep.Options{OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + if err := f.S.Start(context.Background()); err != nil { + t.Fatal(err) + } + sweeptest.Await(t, entered, "the pass") + err := sweeptest.Shutdown(f.S) + if err == nil || !strings.Contains(err.Error(), "handlers cancelled") { + t.Errorf("Shutdown = %v, want the handlers' cancellation", err) + } + if got := p.All(); len(got) != 0 { + t.Errorf("reports = %+v, want none for the cancelled pass", got) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} + +func TestSweeper_TheDrainEndsAGateWaitWithNoPass(t *testing.T) { + var p sweeptest.Reports + g := &reactor.Gate{} + hold, err := g.Exclusive(context.Background()) + if err != nil { + t.Fatal(err) + } + defer hold() + w := sweeptest.Waiting{Gate: g, Began: make(chan struct{}, 1)} + r := &sweeptest.Reclaimer{} + f := sweeptest.NewFixture(t, sqltest.LockingDialect{}, []sweep.Registration{sweeptest.Reg("files", r, time.Hour, 1)}, time.Hour, + sweep.Options{Gate: w, OnPass: p.Hook}) + f.Rec.Queue(sweeptest.Claimed()...) + if err := f.S.Start(context.Background()); err != nil { + t.Fatal(err) + } + sweeptest.Await(t, w.Began, "the gate wait") + if err := sweeptest.Shutdown(f.S); err != nil { + t.Errorf("Shutdown = %v, want nil: the drain, not a cancellation, ended the wait", err) + } + if r.Passes() != 0 || len(p.All()) != 0 { + t.Errorf("passes = %d, reports = %+v; want none", r.Passes(), p.All()) + } + sweeptest.WantLocks(t, f.Rec, sweeptest.Try+"sweep.files", sweeptest.Unlock+"sweep.files") +} diff --git a/config_test.go b/test/config_test.go similarity index 100% rename from config_test.go rename to test/config_test.go diff --git a/database_test.go b/test/database_test.go similarity index 100% rename from database_test.go rename to test/database_test.go diff --git a/env_test.go b/test/env_test.go similarity index 100% rename from env_test.go rename to test/env_test.go diff --git a/errors_test.go b/test/errors_test.go similarity index 100% rename from errors_test.go rename to test/errors_test.go