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
19 changes: 18 additions & 1 deletion pkgs/mcpx/internal/cli/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,18 +325,31 @@ func (c *Client) Ping(ctx context.Context) bool {
// waits for it to become reachable. This is what makes every command work with
// no setup step.
func (c *Client) EnsureDaemon(ctx context.Context) error {
// A cancelled caller wants nothing started and nothing waited for:
// without this check a failed Ping (which a cancelled context always
// produces) is read as "no daemon", so a daemon gets spawned and the
// poll below waits out the whole connect timeout (#284).
if err := ctx.Err(); err != nil {
return err
}
if c.Remote() {
// Starting a local daemon because a remote one is unreachable would
// silently answer from the wrong machine, which is worse than
// failing.
if c.Ping(ctx) {
return nil
}
if err := ctx.Err(); err != nil {
return err
}
return fmt.Errorf("no mcpx daemon at %s; it is not started from here", c.endpoint)
}
if c.Ping(ctx) {
return nil
}
if err := ctx.Err(); err != nil {
return err
}
if !c.set.Bool("daemon.autostart") {
return fmt.Errorf("%w and daemon.autostart is off, so mcpx will not start one",
ErrNoDaemon)
Expand Down Expand Up @@ -383,7 +396,11 @@ func (c *Client) EnsureDaemon(ctx context.Context) error {
if c.Ping(ctx) {
return nil
}
time.Sleep(c.set.Duration("autostart.pollInterval"))
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(c.set.Duration("autostart.pollInterval")):
}
}
tail, _ := os.ReadFile(logPath)
if max := c.set.Bytes("autostart.logTail"); int64(len(tail)) > max {
Expand Down
94 changes: 94 additions & 0 deletions pkgs/mcpx/internal/cli/ensuredaemon_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package cli

import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/dezren39/mcpx/internal/daemon"
)

// ensureTestClient builds a client whose autostart "daemon" is a fake
// binary that only records that it was spawned, so tests can observe
// whether EnsureDaemon started anything without a real daemon.
func ensureTestClient(t *testing.T, connectTimeout string) (*Client, string) {
t.Helper()
dir := t.TempDir()
marker := filepath.Join(dir, "spawned")
bin := filepath.Join(dir, "fakebin.sh")
script := "#!/bin/sh\ntouch \"" + marker + "\"\n"
if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
c := NewClient(daemon.PathsAt(filepath.Join(dir, "state"), filepath.Join(dir, "cache")), "")
for path, raw := range map[string]string{
"autostart.connectTimeout": connectTimeout,
"autostart.pollInterval": "50ms",
"autostart.bin": bin,
} {
if err := c.set.SetRuntime(path, raw); err != nil {
t.Fatal(err)
}
}
return c, marker
}

// Regression for #284: an already-cancelled context was read as "no
// daemon", so EnsureDaemon spawned a daemon and waited out the whole
// connect timeout before failing with the wrong error.
func TestEnsureDaemonAlreadyCancelledContext(t *testing.T) {
c, marker := ensureTestClient(t, "3s")
ctx, cancel := context.WithCancel(context.Background())
cancel()
start := time.Now()
err := c.EnsureDaemon(ctx)
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want context.Canceled", err)
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("took %v with a cancelled context, want a prompt return", elapsed)
}
if _, statErr := os.Stat(marker); statErr == nil {
t.Fatal("spawned a daemon for a cancelled caller")
}
}

// Regression for #284: cancelling while EnsureDaemon waits for the
// started daemon must end the wait promptly, not at the deadline.
func TestEnsureDaemonCancelledWhileWaiting(t *testing.T) {
c, _ := ensureTestClient(t, "30s")
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(200 * time.Millisecond)
cancel()
}()
start := time.Now()
err := c.EnsureDaemon(ctx)
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want context.Canceled", err)
}
if elapsed := time.Since(start); elapsed > 5*time.Second {
t.Fatalf("took %v after cancellation, want a prompt return", elapsed)
}
}

// The uncancelled path is unchanged: a daemon that never becomes ready
// still fails with "did not become ready" after the connect timeout.
func TestEnsureDaemonNeverReadyStillTimesOut(t *testing.T) {
c, marker := ensureTestClient(t, "1s")
start := time.Now()
err := c.EnsureDaemon(context.Background())
if err == nil || !strings.Contains(err.Error(), "daemon did not become ready") {
t.Fatalf("err = %v, want the did-not-become-ready timeout error", err)
}
if elapsed := time.Since(start); elapsed < 900*time.Millisecond {
t.Fatalf("gave up after %v, before the 1s connect timeout", elapsed)
}
if _, statErr := os.Stat(marker); statErr != nil {
t.Fatal("the fake daemon was never spawned")
}
}
Loading