diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8dbb30c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: ci + +# Minimal CI for pgrun-cli: tests, cross-platform build, lint, vulnerability scan. +# Action SHAs and tool versions are pinned (as in pgrundev/pgbot) so a release upstream cannot +# change what CI enforces without a commit here. Go comes from go.mod (go + toolchain lines). +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + test: + name: vet + gofmt + unit tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - run: go vet ./... + - name: gofmt + run: | + unformatted=$(gofmt -l cmd internal) + if [ -n "$unformatted" ]; then echo "gofmt needed:"; echo "$unformatted"; exit 1; fi + - run: go test -race ./... + + build: + name: build ${{ matrix.goos }}/${{ matrix.goarch }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + goos: [linux, darwin, windows] + goarch: [amd64, arm64] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - name: build (same flags as the Makefile) + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + CGO_ENABLED: "0" + run: go build -trimpath -ldflags "-s -w" -o "bin/pgrun-$GOOS-$GOARCH" ./cmd/pgrun + + lint: + name: golangci-lint + govulncheck + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - name: "golangci-lint (config: .golangci.yml)" + run: | + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0 + "$(go env GOPATH)/bin/golangci-lint" run ./... + - name: govulncheck + run: | + go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 + "$(go env GOPATH)/bin/govulncheck" ./... diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..8d88de5 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,28 @@ +# Minimal lint baseline for pgrun-cli (golangci-lint v2, default linters: errcheck, govet, +# ineffassign, staticcheck, unused). The exclusions are the accepted patterns of a CLI, not bugs: +# - writes to the user's terminal (fmt/tabwriter/io to stdout/stderr) and best-effort cleanup +# (Close, Remove, RemoveAll, waiting on a launched browser) are intentionally unchecked; +# - tests: unchecked fixture writes, and staticcheck's quick-fix style hints. +version: "2" +linters: + settings: + errcheck: + exclude-functions: + - fmt.Fprint + - fmt.Fprintf + - fmt.Fprintln + - io.WriteString + - (io.Writer).Write + - (io.Closer).Close + - (*os.File).Close + - (*text/tabwriter.Writer).Flush + - (net/http.ResponseWriter).Write + - (*os/exec.Cmd).Wait + - os.Remove + - os.RemoveAll + exclusions: + rules: + - path: _test\.go + linters: [errcheck] + - linters: [staticcheck] + text: "QF1002" diff --git a/go.mod b/go.mod index a7e18ec..1892a76 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/pgrundev/pgrun-cli go 1.22 + +toolchain go1.27.4 diff --git a/internal/api/client.go b/internal/api/client.go index 49c24b5..418e344 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -31,6 +31,55 @@ type Client struct { Kind string httpClient *http.Client // nil uses the package default + + // CapacityWait bounds how long CreateBranch waits on 429 capacity_busy + // (server admission control, 2026-11-14) before returning the error. + // 0 uses DefaultCapacityWait; negative disables waiting. + CapacityWait time.Duration + // OnCapacityWait, when set, is told before each wait (the CLI prints a line). + OnCapacityWait func(d time.Duration) + sleep func(ctx context.Context, d time.Duration) error // tests replace it +} + +// DefaultCapacityWait is how long a create waits, in total, for a busy host. +const DefaultCapacityWait = 2 * time.Minute + +// capacityBusy reports the server's retry hint when raw is a 429 capacity_busy +// answer (admission control: the host is momentarily full and nothing was created). +func capacityBusy(err error, raw []byte) (time.Duration, bool) { + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusTooManyRequests { + return 0, false + } + var body struct { + Error string `json:"error"` + RetryAfterS float64 `json:"retry_after_s"` + } + if json.Unmarshal(raw, &body) != nil || body.Error != "capacity_busy" { + return 0, false + } + d := time.Duration(body.RetryAfterS * float64(time.Second)) + if d < 2*time.Second { + d = 2 * time.Second + } + if d > time.Minute { + d = time.Minute + } + return d, true +} + +func (c *Client) pause(ctx context.Context, d time.Duration) error { + if c.sleep != nil { + return c.sleep(ctx, d) + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } } // Version is the pgrun-cli version the headers carry; the cli package sets it @@ -191,7 +240,25 @@ func (c *Client) CreateBranch(ctx context.Context, project string, req CreateBra if err := validatePathSegment("project", project); err != nil { return nil, Branch{}, err } - raw, err = c.do(ctx, http.MethodPost, branchesPath(project), req, http.StatusCreated) + budget := c.CapacityWait + if budget == 0 { + budget = DefaultCapacityWait + } + var waited time.Duration + for { + raw, err = c.do(ctx, http.MethodPost, branchesPath(project), req, http.StatusCreated) + d, busy := capacityBusy(err, raw) + if !busy || budget < 0 || waited+d > budget { + break + } + if c.OnCapacityWait != nil { + c.OnCapacityWait(d) + } + if perr := c.pause(ctx, d); perr != nil { + return raw, Branch{}, err + } + waited += d + } if err != nil { return raw, Branch{}, err } diff --git a/internal/api/client_test.go b/internal/api/client_test.go index 4e304dc..6f0fc62 100644 --- a/internal/api/client_test.go +++ b/internal/api/client_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" ) // newTestServer returns a client wired to a fresh httptest server and the @@ -427,3 +428,59 @@ func TestRequestHeaders_IdentifyClient(t *testing.T) { } } } + +// Admission control (server 2026-11-14): 429 capacity_busy creates nothing, so the +// create is sent again after the server's hint, within CapacityWait. +func TestCreateBranch_WaitsOnCapacityBusyThenCreates(t *testing.T) { + posts := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + posts++ + if posts <= 2 { + w.Header().Set("Retry-After", "15") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":"capacity_busy","retry_after_s":15}`)) + return + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"name":"feat","status":"creating"}`)) + })) + defer srv.Close() + var slept []time.Duration + c := &Client{BaseURL: srv.URL, Token: "t", sleep: func(_ context.Context, d time.Duration) error { slept = append(slept, d); return nil }} + _, b, err := c.CreateBranch(context.Background(), "proj1", CreateBranchRequest{Name: "feat"}) + if err != nil || b.Name != "feat" || posts != 3 { + t.Fatalf("err=%v branch=%+v posts=%d", err, b, posts) + } + if len(slept) != 2 || slept[0] != 15*time.Second { + t.Fatalf("slept %v", slept) + } +} + +func TestCreateBranch_CapacityWaitBoundsAndOtherErrorsAreNotRetried(t *testing.T) { + posts := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + posts++ + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":"capacity_busy","retry_after_s":30}`)) + })) + defer srv.Close() + c := &Client{BaseURL: srv.URL, Token: "t", CapacityWait: 60 * time.Second, + sleep: func(context.Context, time.Duration) error { return nil }} + if _, _, err := c.CreateBranch(context.Background(), "proj1", CreateBranchRequest{Name: "feat"}); err == nil { + t.Fatal("still busy after the budget: the 429 is returned") + } + if posts != 3 { // 30 s + 30 s = budget, the third answer ends it + t.Fatalf("posts=%d", posts) + } + quota := 0 + srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + quota++ + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":"rate limited"}`)) + })) + defer srv2.Close() + c2 := &Client{BaseURL: srv2.URL, Token: "t", sleep: func(context.Context, time.Duration) error { return nil }} + if _, _, err := c2.CreateBranch(context.Background(), "proj1", CreateBranchRequest{Name: "feat"}); err == nil || quota != 1 { + t.Fatalf("a 429 that is not capacity_busy is not retried: posts=%d", quota) + } +} diff --git a/internal/cli/branch.go b/internal/cli/branch.go index 75d1069..1fb78f3 100644 --- a/internal/cli/branch.go +++ b/internal/cli/branch.go @@ -44,7 +44,7 @@ func branchCreate(args []string, stdout, stderr io.Writer) int { if len(pos) == 1 { explicit = pos[0] } - project, code, ok := resolveProject(explicit, stderr) + project, code, ok := resolveProject(explicit, rest, stderr) if !ok { return code } @@ -91,6 +91,9 @@ func branchCreate(args []string, stdout, stderr io.Writer) int { return code } client := api.New(cfg.URL, cfg.Token) + client.OnCapacityWait = func(d time.Duration) { + fmt.Fprintf(stderr, "pgrun: the host is busy, retrying in %ds\n", int(d.Seconds())) + } if tpl != "" && !ensureTemplateReady(client, project, tpl, define, templateWaitTimeout, stderr) { return exitFailure @@ -168,7 +171,7 @@ func branchList(args []string, stdout, stderr io.Writer) int { if len(pos) == 1 { explicit = pos[0] } - project, code, ok := resolveProject(explicit, stderr) + project, code, ok := resolveProject(explicit, rest, stderr) if !ok { return code } @@ -216,7 +219,7 @@ func branchGet(args []string, stdout, stderr io.Writer) int { } else { name = pos[0] } - project, code, ok := resolveProject(explicit, stderr) + project, code, ok := resolveProject(explicit, rest, stderr) if !ok { return code } @@ -264,7 +267,7 @@ func branchURL(args []string, stdout, stderr io.Writer) int { } else { name = pos[0] } - project, code, ok := resolveProject(explicit, stderr) + project, code, ok := resolveProject(explicit, rest, stderr) if !ok { return code } @@ -317,7 +320,7 @@ func branchDelete(args []string, stdout, stderr io.Writer) int { } else { name = pos[0] } - project, code, ok := resolveProject(explicit, stderr) + project, code, ok := resolveProject(explicit, rest, stderr) if !ok { return code } diff --git a/internal/cli/branch_env.go b/internal/cli/branch_env.go index f723e95..be5b749 100644 --- a/internal/cli/branch_env.go +++ b/internal/cli/branch_env.go @@ -31,7 +31,7 @@ func branchEnv(args []string, stdout, stderr io.Writer) int { } else { name = pos[0] } - project, code, ok := resolveProject(explicit, stderr) + project, code, ok := resolveProject(explicit, rest, stderr) if !ok { return code } diff --git a/internal/cli/branch_exec.go b/internal/cli/branch_exec.go index 55d842a..a96c55a 100644 --- a/internal/cli/branch_exec.go +++ b/internal/cli/branch_exec.go @@ -73,7 +73,7 @@ func branchExec(args []string, stdout, stderr io.Writer) int { } var code int var ok bool - project, code, ok = resolveProject(explicit, stderr) + project, code, ok = resolveProject(explicit, rest, stderr) if !ok { return code } @@ -83,7 +83,7 @@ func branchExec(args []string, stdout, stderr io.Writer) int { name = pos[0] var code int var ok bool - project, code, ok = resolveProject("", stderr) + project, code, ok = resolveProject("", rest, stderr) if !ok { return code } @@ -110,6 +110,9 @@ func branchExec(args []string, stdout, stderr io.Writer) int { return code } client := api.New(cfg.URL, cfg.Token) + client.OnCapacityWait = func(d time.Duration) { + fmt.Fprintf(stderr, "pgrun: the host is busy, retrying in %ds\n", int(d.Seconds())) + } // From here on a SIGINT/SIGTERM/SIGHUP (a CI runner cancelling the job, // a Ctrl-C) must not kill pgrun outright: that would skip --delete-after diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 93811b5..a4c6f58 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -700,3 +700,27 @@ func TestBranchDelete_409OnBase(t *testing.T) { t.Fatalf("stderr = %q", stderr) } } + +// TestBranchCreate_HelpNeedsNoProject: `pgrun branch create --help` from a +// directory with no .pgrun/project prints the flags and exits 0, instead of +// the "no project given" usage error the project lookup used to raise first. +func TestBranchCreate_HelpNeedsNoProject(t *testing.T) { + chdir(t, t.TempDir()) + for _, sub := range [][]string{{"branch", "create", "--help"}, {"branch", "list", "-h"}, {"template", "list", "--help"}} { + code, _, errOut := run(t, sub...) + if code != exitSuccess { + t.Fatalf("%v: code = %d, stderr = %q", sub, code, errOut) + } + if strings.Contains(errOut, "no project given") { + t.Fatalf("%v: help still demanded a project: %q", sub, errOut) + } + } + _, _, errOut := run(t, "branch", "create", "--help") + if !strings.Contains(errOut, "-engine") { + t.Fatalf("branch create --help should list -engine: %q", errOut) + } + // Without --help the lookup still runs and still refuses. + if code, _, errOut := run(t, "branch", "create", "--name", "x"); code != exitUsage || !strings.Contains(errOut, "no project given") { + t.Fatalf("no-help, no-project: code = %d, stderr = %q", code, errOut) + } +} diff --git a/internal/cli/resolve.go b/internal/cli/resolve.go index 682df2a..21e410a 100644 --- a/internal/cli/resolve.go +++ b/internal/cli/resolve.go @@ -44,10 +44,18 @@ func leadingPositionals(args []string) (positionals, rest []string) { // directory's .pgrun/project file (see config.FindProject, which walks up // like git finding .git). Neither present is a usage error, not an // operation failure — there's nothing to contact the API about yet. -func resolveProject(explicit string, stderr io.Writer) (slug string, code int, ok bool) { +// +// rest is the flag tail that follows the positionals. `--help`/`-h` in it +// means the caller is about to print the subcommand's usage, which needs no +// project: the lookup is skipped so help works from any directory instead +// of failing on "no project given" first. +func resolveProject(explicit string, rest []string, stderr io.Writer) (slug string, code int, ok bool) { if explicit != "" { return explicit, exitSuccess, true } + if wantsHelp(rest) { + return "", exitSuccess, true + } cwd, err := os.Getwd() if err != nil { fmt.Fprintf(stderr, "pgrun: %v\n", err) @@ -64,3 +72,17 @@ func resolveProject(explicit string, stderr io.Writer) (slug string, code int, o } return slug, exitSuccess, true } + +// wantsHelp reports whether a flag tail asks for usage (-h, --help, -help), +// looked at before the flag package parses it. +func wantsHelp(rest []string) bool { + for _, a := range rest { + switch a { + case "-h", "--help", "-help": + return true + case "--": + return false + } + } + return false +} diff --git a/internal/cli/source.go b/internal/cli/source.go index 02715d9..0a04119 100644 --- a/internal/cli/source.go +++ b/internal/cli/source.go @@ -113,7 +113,7 @@ func sourceNameArgs(cmd string, args []string, stderr io.Writer) (name string, r if looksLikeConnectionURL(explicit) { return "", nil, usageErrf(stderr, "source %s: that argument is the Production Database name, not a connection URL — usage: pgrun source %s [] %s", cmd, cmd, sourceUsageFlags(cmd)), false } - name, code, ok = resolveProject(explicit, stderr) + name, code, ok = resolveProject(explicit, rest, stderr) if !ok { return "", nil, code, false } diff --git a/internal/cli/template.go b/internal/cli/template.go index b1b292a..09fdd1c 100644 --- a/internal/cli/template.go +++ b/internal/cli/template.go @@ -60,7 +60,7 @@ func projectAndName(cmd string, args []string, stderr io.Writer) (project, name } else { name = pos[0] } - project, code, ok = resolveProject(explicit, stderr) + project, code, ok = resolveProject(explicit, rest, stderr) return project, name, rest, code, ok } @@ -175,7 +175,7 @@ func templateList(args []string, stdout, stderr io.Writer) int { if len(pos) == 1 { explicit = pos[0] } - project, code, ok := resolveProject(explicit, stderr) + project, code, ok := resolveProject(explicit, rest, stderr) if !ok { return code }