Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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" ./...
28 changes: 28 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -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"
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/pgrundev/pgrun-cli

go 1.22

toolchain go1.27.4
69 changes: 68 additions & 1 deletion internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
57 changes: 57 additions & 0 deletions internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"
)

// newTestServer returns a client wired to a fresh httptest server and the
Expand Down Expand Up @@ -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)
}
}
13 changes: 8 additions & 5 deletions internal/cli/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/branch_env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
7 changes: 5 additions & 2 deletions internal/cli/branch_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
Expand Down
24 changes: 24 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Loading
Loading