fix(worktreerpc): bound handler contexts and drop the git binary from tests

Missed in f800e1d, which ported internal/worktree but stopped at "the
sibling package still compiles".

Both NATS handlers ran their work under context.Background(). The client
side has a Timeout and passes a context, but the server discarded it, so
a prepare or push ran unbounded. That was survivable when the work was a
git child process that could be killed; after f800e1d it is an in-process
go-git clone, so an unresponsive forge wedges the handler goroutine
permanently. Removing the per-repo object cache in that same commit made
clones longer, which widens the window further.

Server now has a Timeout (defaulting to 15 minutes, sized for a large
clone over a slow link) applied via handlerContext, with a table test
asserting both the explicit and default paths produce a bounded deadline.

The fixtures also still shelled out to git, so every test in the package
skipped when no git binary was present and the helpers tripped noctx.
Rebuilt on go-git to match internal/worktree's suite, including pinning
commit.gpgSign=false on the seed repo so fixtures do not inherit signing
from the host's global config.
This commit is contained in:
sam committed 2026-07-28 02:05:06 +10:00
1 parent f800e1de36
commit 6ee605a4fc
2 files changed
+118 -38

No files matched your search

+28 -2
View File
@@ -59,11 +59,33 @@ type PrepareResponse struct {
natsrpc.Envelope
}
// defaultHandlerTimeout bounds a single prepare or push when the Server
// has no explicit Timeout. A clone of a large repository over a slow link
// is the long pole, so this is generous rather than tight.
const defaultHandlerTimeout = 15 * time.Minute
// Server proxies push requests to a real worktree.Manager holding the
// forge push token.
type Server struct {
Trees *worktree.Manager
Log *slog.Logger
// Timeout bounds a single prepare or push. Zero uses
// defaultHandlerTimeout.
Timeout time.Duration
}
// handlerContext returns the context a single request runs under.
//
// NATS request/reply carries no deadline from the caller, and the work
// now runs in-process through go-git rather than as a killable child
// process, so the server has to impose its own bound. Without one an
// unresponsive forge holds this handler's goroutine forever.
func (s *Server) handlerContext() (context.Context, context.CancelFunc) {
timeout := s.Timeout
if timeout <= 0 {
timeout = defaultHandlerTimeout
}
return context.WithTimeout(context.Background(), timeout)
}
// Register subscribes the push and prepare handlers on nc. The returned
@@ -81,8 +103,10 @@ func (s *Server) handlePush(msg *nats.Msg) {
s.respond(msg, err)
return
}
ctx, cancel := s.handlerContext()
defer cancel()
dir := s.Trees.Dir(req.Owner, req.Repo, req.Issue)
s.respond(msg, s.Trees.Push(context.Background(), dir, req.Branch))
s.respond(msg, s.Trees.Push(ctx, dir, req.Branch))
}
func (s *Server) handlePrepare(msg *nats.Msg) {
@@ -91,7 +115,9 @@ func (s *Server) handlePrepare(msg *nats.Msg) {
s.respondPrepare(msg, "", "", err)
return
}
dir, branch, err := s.Trees.Prepare(context.Background(), req.Owner, req.Repo, req.Base, req.Issue, req.Title, req.Body, req.Labels)
ctx, cancel := s.handlerContext()
defer cancel()
dir, branch, err := s.Trees.Prepare(ctx, req.Owner, req.Repo, req.Base, req.Issue, req.Title, req.Body, req.Labels)
s.respondPrepare(msg, dir, branch, err)
}
+90 -36
View File
@@ -4,11 +4,14 @@ import (
"context"
"log/slog"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/go-git/go-git/v6"
gitconfig "github.com/go-git/go-git/v6/config"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/object"
"github.com/nats-io/nats-server/v2/server"
natssrv "github.com/nats-io/nats-server/v2/test"
"github.com/nats-io/nats.go"
@@ -33,58 +36,80 @@ func connect(t *testing.T, url string) *nats.Conn {
return nc
}
// newLocalRemote creates a bare repo with one commit on main, reachable
// via file://<host>/<owner>/<repo>.git -- mirrors worktree_test.go's helper.
// newLocalRemote creates a bare repo with one commit on main at
// <host>/<owner>/<repo>.git. Built with go-git, so this package's tests
// no longer require a git binary on the machine running them.
func newLocalRemote(t *testing.T, owner, repo string) string {
t.Helper()
host := t.TempDir()
bare := filepath.Join(host, owner, repo+".git")
mainRef := plumbing.NewBranchReferenceName("main")
if _, err := git.PlainInit(bare, true, git.WithDefaultBranch(mainRef)); err != nil {
t.Fatalf("init bare remote: %v", err)
}
seed := filepath.Join(t.TempDir(), "seed")
run := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
sr, err := git.PlainInit(seed, false, git.WithDefaultBranch(mainRef))
if err != nil {
t.Fatalf("init seed repo: %v", err)
}
// Fixtures must not inherit commit.gpgSign from the host's global
// git config: go-git cannot sign and would fail the commit.
cfg, err := sr.Config()
if err != nil {
t.Fatalf("read seed config: %v", err)
}
cfg.Raw.Section("commit").SetOption("gpgsign", "false")
if err := sr.SetConfig(cfg); err != nil {
t.Fatalf("write seed config: %v", err)
}
if err := os.MkdirAll(bare, 0o755); err != nil {
if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o600); err != nil {
t.Fatal(err)
}
run(host, "init", "--bare", "-b", "main", bare)
if err := os.MkdirAll(seed, 0o755); err != nil {
t.Fatal(err)
wt, err := sr.Worktree()
if err != nil {
t.Fatalf("seed worktree: %v", err)
}
run(seed, "init", "-b", "main")
run(seed, "config", "user.name", "seeder")
run(seed, "config", "user.email", "seed@example.com")
if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o644); err != nil {
t.Fatal(err)
if _, err := wt.Add("README.md"); err != nil {
t.Fatalf("seed add: %v", err)
}
sig := &object.Signature{
Name: "seeder",
Email: "seed@example.com",
When: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
}
if _, err := wt.Commit("seed", &git.CommitOptions{Author: sig, Committer: sig}); err != nil {
t.Fatalf("seed commit: %v", err)
}
if _, err := sr.CreateRemote(&gitconfig.RemoteConfig{
Name: git.DefaultRemoteName,
URLs: []string{bare},
}); err != nil {
t.Fatalf("seed remote: %v", err)
}
if err := sr.Push(&git.PushOptions{
RemoteName: git.DefaultRemoteName,
RefSpecs: []gitconfig.RefSpec{gitconfig.RefSpec(mainRef + ":" + mainRef)},
}); err != nil {
t.Fatalf("seed push: %v", err)
}
run(seed, "add", "-A")
run(seed, "commit", "-m", "seed")
run(seed, "push", "file://"+bare, "main")
return host
}
func remoteHasBranch(t *testing.T, host, owner, repo, branch string) bool {
t.Helper()
bare := filepath.Join(host, owner, repo+".git")
cmd := exec.Command("git", "ls-remote", "--heads", bare, branch)
out, err := cmd.CombinedOutput()
r, err := git.PlainOpen(bare)
if err != nil {
t.Fatalf("ls-remote: %v\n%s", err, out)
t.Fatalf("open bare remote: %v", err)
}
return len(out) > 0
_, err = r.Reference(plumbing.NewBranchReferenceName(branch), true)
return err == nil
}
func TestClientPreparePublishesViaServer(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not installed")
}
ctx := context.Background()
host := newLocalRemote(t, "acme", "widget")
@@ -93,7 +118,7 @@ func TestClientPreparePublishesViaServer(t *testing.T) {
Token: "unused-for-file-remotes",
BotUser: "archie-bot",
BotEmail: "archie-bot@example.com",
BaseURL: "file://" + host,
BaseURL: host,
}
srv := startEmbedded(t)
@@ -120,9 +145,6 @@ func TestClientPreparePublishesViaServer(t *testing.T) {
}
func TestClientPushPublishesViaServer(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not installed")
}
ctx := context.Background()
host := newLocalRemote(t, "acme", "widget")
@@ -131,7 +153,7 @@ func TestClientPushPublishesViaServer(t *testing.T) {
Token: "unused-for-file-remotes",
BotUser: "archie-bot",
BotEmail: "archie-bot@example.com",
BaseURL: "file://" + host,
BaseURL: host,
}
dir, branch, err := m.Prepare(ctx, "acme", "widget", "main", 1, "feat: test", "", "")
@@ -194,3 +216,35 @@ func TestClientPushTimesOutWithNoResponder(t *testing.T) {
t.Fatal("expected Push to time out with no server registered")
}
}
// A handler must impose its own deadline. NATS request/reply carries no
// deadline to the server, and a clone or push now runs in-process via
// go-git, so an unresponsive forge would otherwise wedge the handler
// goroutine forever.
func TestServerHandlerContextIsBounded(t *testing.T) {
tests := []struct {
name string
timeout time.Duration
wantMax time.Duration
}{
{name: "explicit timeout is honoured", timeout: 42 * time.Second, wantMax: 42 * time.Second},
{name: "zero falls back to the default", timeout: 0, wantMax: defaultHandlerTimeout},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
s := &Server{Timeout: tc.timeout}
ctx, cancel := s.handlerContext()
defer cancel()
deadline, ok := ctx.Deadline()
if !ok {
t.Fatal("handlerContext() returned a context with no deadline")
}
remaining := time.Until(deadline)
if remaining <= 0 || remaining > tc.wantMax {
t.Errorf("deadline in %v, want a positive value no greater than %v", remaining, tc.wantMax)
}
})
}
}