From 20579b0aae19d2e276b72b8ad24d781362e07e28 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 23 Jun 2026 10:38:22 -0500 Subject: [PATCH] =?UTF-8?q?feat(M8):=20daemon=20control=20socket=20+=20pau?= =?UTF-8?q?se/resume=20=F0=9F=8E=9B=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add internal/control: an HTTP/1.1 control plane the daemon hosts on a 0600 Unix socket (control.sock) in the config dir — GET /state, GET /events (SSE), POST /pause|/resume — plus a stdlib net/http client (DialState/Pause/Resume) that returns a typed ErrNotRunning when the daemon is down so callers can fall back. Wire into the daemon: paused atomic.Bool gates runMount's trigger loop (drains while paused, no-ops the initial nudge), a per-mount nudge registry lets Resume catch every mount up, and StateSnapshot feeds /state. The control server starts in Run and is non-fatal — sync never depends on it. Windows gets a build-tagged stub (named-pipe upgrade path noted). CLI: devbox pause/resume call the client (friendly 'daemon not running' when absent); status prefers the live socket but ONLY on a TTY, so piped output stays byte-identical to v1 for scripts. --- cmd/devbox/control.go | 68 ++++++++++ cmd/devbox/main.go | 33 +++++ go.mod | 2 +- internal/control/control.go | 105 ++++++++++++++++ internal/control/control_test.go | 175 ++++++++++++++++++++++++++ internal/control/server.go | 191 +++++++++++++++++++++++++++++ internal/control/server_windows.go | 33 +++++ internal/daemon/daemon.go | 105 +++++++++++++++- internal/daemon/pause_test.go | 90 ++++++++++++++ 9 files changed, 798 insertions(+), 4 deletions(-) create mode 100644 cmd/devbox/control.go create mode 100644 internal/control/control.go create mode 100644 internal/control/control_test.go create mode 100644 internal/control/server.go create mode 100644 internal/control/server_windows.go create mode 100644 internal/daemon/pause_test.go diff --git a/cmd/devbox/control.go b/cmd/devbox/control.go new file mode 100644 index 0000000..23b42dc --- /dev/null +++ b/cmd/devbox/control.go @@ -0,0 +1,68 @@ +package main + +import ( + "errors" + "fmt" + + "github.com/mattn/go-isatty" + "github.com/spf13/cobra" + + "git.shoemoney.ai/shoemoney/devbox/internal/config" + "git.shoemoney.ai/shoemoney/devbox/internal/control" +) + +func pauseCmd() *cobra.Command { + return &cobra.Command{ + Use: "pause", + Short: "⏸️ pause syncing on the running daemon", + RunE: func(cmd *cobra.Command, _ []string) error { + dir, err := config.Dir() + if err != nil { + return err + } + if err := control.Pause(dir); err != nil { + return daemonHint(err) + } + fmt.Fprintln(cmd.OutOrStdout(), "⏸️ paused — run: devbox resume to continue") + return nil + }, + } +} + +func resumeCmd() *cobra.Command { + return &cobra.Command{ + Use: "resume", + Short: "▶️ resume syncing on the running daemon", + RunE: func(cmd *cobra.Command, _ []string) error { + dir, err := config.Dir() + if err != nil { + return err + } + if err := control.Resume(dir); err != nil { + return daemonHint(err) + } + fmt.Fprintln(cmd.OutOrStdout(), "▶️ resumed — catching up all mounts") + return nil + }, + } +} + +// daemonHint turns the "no control socket" error into a user-facing message, +// passing other errors through unchanged. +func daemonHint(err error) error { + if errors.Is(err, control.ErrNotRunning) { + return fmt.Errorf("daemon not running — run: devbox start") + } + return err +} + +// isTTY reports whether the command's stdout is an interactive terminal. Used to +// decide whether status may show the human-only "(live)" enrichment — piped +// output stays byte-identical to v1 so scripts are unaffected. +func isTTY(cmd *cobra.Command) bool { + f, ok := cmd.OutOrStdout().(interface{ Fd() uintptr }) + if !ok { + return false + } + return isatty.IsTerminal(f.Fd()) || isatty.IsCygwinTerminal(f.Fd()) +} diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index a3ba12f..c2c9ffb 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -19,6 +19,7 @@ import ( "github.com/spf13/cobra" "git.shoemoney.ai/shoemoney/devbox/internal/config" + "git.shoemoney.ai/shoemoney/devbox/internal/control" "git.shoemoney.ai/shoemoney/devbox/internal/daemon" "git.shoemoney.ai/shoemoney/devbox/internal/hooks" "git.shoemoney.ai/shoemoney/devbox/internal/identity" @@ -52,6 +53,8 @@ func main() { conflictsCmd(), startCmd(), stopCmd(), + pauseCmd(), + resumeCmd(), statusCmd(), doctorCmd(), versionCmd(), @@ -618,6 +621,36 @@ func statusCmd() *cobra.Command { if err != nil { return fmt.Errorf("reading config: %w", err) } + + // Prefer the LIVE daemon when it's running AND stdout is a terminal: + // the socket can show paused state and the applied snapshot, which disk + // can't. Piped/non-TTY output must stay byte-identical to v1 (scripts + // parse it), so the enrichment is gated behind isTTY — the disk path is + // the unchanged v1 output. + if isTTY(cmd) { + if live, err := control.DialState(dir); err == nil { + fmt.Fprintf(out, "device: %s\n", id.Fingerprint()) + fmt.Fprintf(out, "hub: %s\n", orNone(d.Hub)) + paused := "" + if live.Paused { + paused = " ⏸️ PAUSED" + } + fmt.Fprintf(out, "mounts: %d (live)%s\n", len(live.Mounts), paused) + for _, m := range live.Mounts { + mode := "rw" + if m.ReadOnly { + mode = "ro" + } + if m.Pinned { + mode += ",pinned" + } + fmt.Fprintf(out, " - %s/%s -> %s [%s] @%s\n", + m.Share, m.Subpath, m.Local, mode, short(orNone(m.BaseSnapshot))) + } + return nil + } + } + fmt.Fprintf(out, "device: %s\n", id.Fingerprint()) fmt.Fprintf(out, "hub: %s\n", orNone(d.Hub)) fmt.Fprintf(out, "mounts: %d\n", len(d.Mounts)) diff --git a/go.mod b/go.mod index 60081a9..6a3ead3 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/BurntSushi/toml v1.6.0 github.com/fsnotify/fsnotify v1.10.1 github.com/jotfs/fastcdc-go v0.2.0 + github.com/mattn/go-isatty v0.0.20 github.com/spf13/cobra v1.10.2 github.com/zeebo/blake3 v0.2.4 golang.org/x/time v0.15.0 @@ -17,7 +18,6 @@ require ( github.com/google/uuid v1.6.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/klauspost/cpuid/v2 v2.0.12 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/spf13/pflag v1.0.9 // indirect diff --git a/internal/control/control.go b/internal/control/control.go new file mode 100644 index 0000000..7d58878 --- /dev/null +++ b/internal/control/control.go @@ -0,0 +1,105 @@ +// Package control is the daemon's local control plane: an HTTP/1.1 server the +// running daemon hosts on a Unix domain socket (Docker's pattern — routing and +// JSON for free), plus a thin client the CLI uses to introspect and steer it. +// +// It is what finally lets `devbox status` see the LIVE daemon (not just disk) +// and wires `devbox pause`/`resume` through to the sync loop. Everything is +// loopback-only and mode-0600: no auth, the filesystem is the boundary. +package control + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "path/filepath" + "time" +) + +// SockName is the control socket's filename inside the devbox config dir. +const SockName = "control.sock" + +// SockPath returns the control socket path for a config dir. +func SockPath(dir string) string { return filepath.Join(dir, SockName) } + +// State is the running daemon's live snapshot returned by GET /state. +type State struct { + Paused bool `json:"paused"` + Mounts []MountState `json:"mounts"` +} + +// MountState is one mount's live view: its config plus the snapshot the daemon +// has actually applied (base_snapshot), which disk-only status can't know. +type MountState struct { + Share string `json:"share"` + Subpath string `json:"subpath"` + Local string `json:"local"` + ReadOnly bool `json:"readonly"` + Pinned bool `json:"pinned"` + BaseSnapshot string `json:"base_snapshot"` +} + +// ErrNotRunning is returned by the client helpers when the control socket is +// absent or unreachable — i.e. the daemon isn't running — so callers can fall +// back to disk-based behaviour instead of treating it as a hard error. +var ErrNotRunning = errors.New("devbox daemon not running (no control socket)") + +// httpClient builds an http.Client that dials the Unix socket at dir. The host +// in request URLs is ignored by the dialer, so we use a placeholder. +func httpClient(dir string) *http.Client { + sock := SockPath(dir) + return &http.Client{ + Timeout: 5 * time.Second, + Transport: &http.Transport{ + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", sock) + }, + }, + } +} + +// notRunning maps a dial failure (socket missing / nobody listening) to +// ErrNotRunning, leaving genuine protocol errors as-is. +func notRunning(err error) error { + var oe *net.OpError + if errors.As(err, &oe) { + return ErrNotRunning + } + return err +} + +// DialState fetches the live daemon state. Returns ErrNotRunning if no daemon +// is listening on the socket. +func DialState(dir string) (State, error) { + var st State + resp, err := httpClient(dir).Get("http://unix/state") + if err != nil { + return st, notRunning(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return st, fmt.Errorf("control /state: %s", resp.Status) + } + return st, json.NewDecoder(resp.Body).Decode(&st) +} + +// Pause asks the daemon to stop syncing until resumed. +func Pause(dir string) error { return post(dir, "/pause") } + +// Resume clears the pause and triggers an immediate catch-up on all mounts. +func Resume(dir string) error { return post(dir, "/resume") } + +func post(dir, path string) error { + resp, err := httpClient(dir).Post("http://unix"+path, "", nil) + if err != nil { + return notRunning(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("control %s: %s", path, resp.Status) + } + return nil +} diff --git a/internal/control/control_test.go b/internal/control/control_test.go new file mode 100644 index 0000000..c8b1da5 --- /dev/null +++ b/internal/control/control_test.go @@ -0,0 +1,175 @@ +//go:build !windows + +package control + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" +) + +// fakeDaemon is a minimal Daemon for exercising the control server in isolation. +type fakeDaemon struct { + mu sync.Mutex + paused bool + resumes int +} + +func (f *fakeDaemon) StateSnapshot() State { + f.mu.Lock() + defer f.mu.Unlock() + return State{ + Paused: f.paused, + Mounts: []MountState{{Share: "s", Subpath: "p", Local: "/tmp/x", ReadOnly: true, BaseSnapshot: "snap123"}}, + } +} + +func (f *fakeDaemon) Pause() { + f.mu.Lock() + f.paused = true + f.mu.Unlock() +} + +func (f *fakeDaemon) Resume() { + f.mu.Lock() + f.paused = false + f.resumes++ + f.mu.Unlock() +} + +// shortTempDir returns a short-pathed temp dir. macOS caps a Unix socket path +// (sun_path) at ~104 bytes, and t.TempDir()'s deep paths blow past that — +// so the socket lives under /tmp where the real config dir (~/.config/devbox) +// also stays comfortably short. +func shortTempDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "dbxctl-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + return dir +} + +func serveTest(t *testing.T) (string, *fakeDaemon) { + t.Helper() + dir := shortTempDir(t) + fd := &fakeDaemon{} + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + if _, err := Serve(ctx, dir, fd, t.Logf); err != nil { + t.Fatalf("Serve: %v", err) + } + return dir, fd +} + +// TestRoundTripPauseStateResume proves the full control loop: a fresh daemon +// reports not-paused, POST /pause flips it (visible via GET /state), and +// POST /resume clears it and triggers a catch-up. +func TestRoundTripPauseStateResume(t *testing.T) { + dir, fd := serveTest(t) + + st, err := DialState(dir) + if err != nil { + t.Fatalf("DialState: %v", err) + } + if st.Paused { + t.Fatal("fresh daemon should not be paused") + } + if len(st.Mounts) != 1 || st.Mounts[0].BaseSnapshot != "snap123" { + t.Fatalf("state did not round-trip mounts: %+v", st.Mounts) + } + + if err := Pause(dir); err != nil { + t.Fatalf("Pause: %v", err) + } + st, err = DialState(dir) + if err != nil { + t.Fatalf("DialState after pause: %v", err) + } + if !st.Paused { + t.Fatal("state should show paused after POST /pause") + } + + if err := Resume(dir); err != nil { + t.Fatalf("Resume: %v", err) + } + st, err = DialState(dir) + if err != nil { + t.Fatalf("DialState after resume: %v", err) + } + if st.Paused { + t.Fatal("state should clear paused after POST /resume") + } + if fd.resumes != 1 { + t.Fatalf("Resume should have been invoked once, got %d", fd.resumes) + } +} + +// TestNoDaemonReturnsNotRunning proves the client returns the typed +// ErrNotRunning when no daemon is listening, so callers can fall back. +func TestNoDaemonReturnsNotRunning(t *testing.T) { + dir := t.TempDir() // no Serve here — socket absent + + if _, err := DialState(dir); !errors.Is(err, ErrNotRunning) { + t.Fatalf("DialState: want ErrNotRunning, got %v", err) + } + if err := Pause(dir); !errors.Is(err, ErrNotRunning) { + t.Fatalf("Pause: want ErrNotRunning, got %v", err) + } + if err := Resume(dir); !errors.Is(err, ErrNotRunning) { + t.Fatalf("Resume: want ErrNotRunning, got %v", err) + } +} + +// TestSocketMode0600 proves the control socket is owner-only. +func TestSocketMode0600(t *testing.T) { + dir, _ := serveTest(t) + info, err := os.Stat(SockPath(dir)) + if err != nil { + t.Fatalf("stat socket: %v", err) + } + if perm := info.Mode().Perm(); perm != 0o600 { + t.Fatalf("socket mode = %o, want 600", perm) + } +} + +// TestStaleSocketRemoved proves Serve recovers from a leftover socket file from +// a crashed daemon (else net.Listen("unix") fails with "address in use"). +func TestStaleSocketRemoved(t *testing.T) { + dir := shortTempDir(t) + // Plant a stale socket file. + if err := os.WriteFile(SockPath(dir), []byte("stale"), 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if _, err := Serve(ctx, dir, &fakeDaemon{}, t.Logf); err != nil { + t.Fatalf("Serve over stale socket: %v", err) + } + if _, err := DialState(dir); err != nil { + t.Fatalf("DialState after stale recovery: %v", err) + } +} + +// TestShutdownRemovesSocket proves ctx cancel cleans up the socket file. +func TestShutdownRemovesSocket(t *testing.T) { + dir := shortTempDir(t) + ctx, cancel := context.WithCancel(context.Background()) + if _, err := Serve(ctx, dir, &fakeDaemon{}, t.Logf); err != nil { + t.Fatalf("Serve: %v", err) + } + cancel() + // Shutdown is async; poll briefly for the socket to disappear. + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if _, err := os.Stat(SockPath(dir)); os.IsNotExist(err) { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("socket file not removed after ctx cancel") +} diff --git a/internal/control/server.go b/internal/control/server.go new file mode 100644 index 0000000..be14bc2 --- /dev/null +++ b/internal/control/server.go @@ -0,0 +1,191 @@ +//go:build !windows + +package control + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "os" + "sync" + "time" +) + +// Daemon is the slice of the running daemon the control server steers. The +// daemon package implements it; kept here so the server depends on a behaviour, +// not on the daemon package (no import cycle). +type Daemon interface { + StateSnapshot() State // live per-mount + paused view for GET /state + Pause() // stop syncing until resumed + Resume() // clear pause + catch up all mounts +} + +// Server hosts the control API on a Unix socket. The zero value is unusable; +// build one with Serve. +type Server struct { + d Daemon + broker *broker + ln net.Listener + srv *http.Server + sock string +} + +// Serve binds the control socket under dir (mode 0600, stale socket removed +// first) and serves the control API until ctx is cancelled, then cleans up. It +// returns once the listener is bound; the serving runs in the background. A bind +// failure is returned so the caller can warn-and-continue — sync must not depend +// on the control plane. +func Serve(ctx context.Context, dir string, d Daemon, logf func(string, ...any)) (*Server, error) { + sock := SockPath(dir) + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + // A stale socket from a crashed daemon would make Listen fail with + // "address already in use"; remove it first (it's ours by location). + if err := os.Remove(sock); err != nil && !os.IsNotExist(err) { + return nil, err + } + ln, err := net.Listen("unix", sock) + if err != nil { + return nil, err + } + // Tighten to owner-only: the socket is the daemon's authority boundary. + if err := os.Chmod(sock, 0o600); err != nil { + ln.Close() + os.Remove(sock) + return nil, err + } + + s := &Server{d: d, broker: newBroker(), ln: ln, sock: sock} + mux := http.NewServeMux() + mux.HandleFunc("GET /state", s.handleState) + mux.HandleFunc("GET /events", s.handleEvents) + mux.HandleFunc("POST /pause", s.handlePause) + mux.HandleFunc("POST /resume", s.handleResume) + s.srv = &http.Server{Handler: mux} + + go func() { + if err := s.srv.Serve(ln); err != nil && err != http.ErrServerClosed && logf != nil { + logf("control server: %v", err) + } + }() + go func() { + <-ctx.Done() + s.close() + }() + return s, nil +} + +// Publish reports that a mount finished a sync; the server fans it out to any +// GET /events subscribers. Safe to call from the sync goroutines. +func (s *Server) Publish(share, detail string) { + if s == nil { + return + } + s.broker.publish(activity{Share: share, Detail: detail, At: time.Now().Unix()}) +} + +func (s *Server) close() { + shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = s.srv.Shutdown(shutCtx) + _ = os.Remove(s.sock) +} + +func (s *Server) handleState(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(s.d.StateSnapshot()) +} + +func (s *Server) handlePause(w http.ResponseWriter, _ *http.Request) { + s.d.Pause() + w.WriteHeader(http.StatusOK) +} + +func (s *Server) handleResume(w http.ResponseWriter, _ *http.Request) { + s.d.Resume() + w.WriteHeader(http.StatusOK) +} + +// handleEvents streams sync activity as Server-Sent Events, mirroring the hub's +// SSE wire style (`data: \n\n`, periodic `: ping` comments to keep idle +// proxies open). ponytail: copied, not imported — internal/hub is off-limits. +func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) { + flusher, ok := w.(http.Flusher) + if !ok { + http.Error(w, "streaming unsupported", http.StatusInternalServerError) + return + } + ch := s.broker.sub() + defer s.broker.unsub(ch) + + h := w.Header() + h.Set("Content-Type", "text/event-stream") + h.Set("Cache-Control", "no-cache") + h.Set("Connection", "keep-alive") + w.WriteHeader(http.StatusOK) + flusher.Flush() + + ping := time.NewTicker(25 * time.Second) + defer ping.Stop() + for { + select { + case <-r.Context().Done(): + return + case <-ping.C: + fmt.Fprint(w, ": ping\n\n") + flusher.Flush() + case ev := <-ch: + b, _ := json.Marshal(ev) + fmt.Fprintf(w, "data: %s\n\n", b) + flusher.Flush() + } + } +} + +// activity is one line of sync activity emitted on GET /events. +type activity struct { + Share string `json:"share"` + Detail string `json:"detail"` + At int64 `json:"at"` // unix seconds +} + +// broker fans sync activity out to connected SSE subscribers. A slow subscriber +// is dropped rather than blocking the sync path — same trade-off as the hub's +// broker. ponytail: pattern copied from internal/hub/events.go. +type broker struct { + mu sync.Mutex + subs map[chan activity]struct{} +} + +func newBroker() *broker { return &broker{subs: map[chan activity]struct{}{}} } + +func (b *broker) sub() chan activity { + ch := make(chan activity, 16) + b.mu.Lock() + b.subs[ch] = struct{}{} + b.mu.Unlock() + return ch +} + +func (b *broker) unsub(ch chan activity) { + b.mu.Lock() + if _, ok := b.subs[ch]; ok { + delete(b.subs, ch) + close(ch) + } + b.mu.Unlock() +} + +func (b *broker) publish(ev activity) { + b.mu.Lock() + defer b.mu.Unlock() + for ch := range b.subs { + select { + case ch <- ev: + default: // slow subscriber; drop + } + } +} diff --git a/internal/control/server_windows.go b/internal/control/server_windows.go new file mode 100644 index 0000000..ba15b3a --- /dev/null +++ b/internal/control/server_windows.go @@ -0,0 +1,33 @@ +//go:build windows + +package control + +import ( + "context" + "errors" +) + +// ponytail: Windows gets a stub, not a real control plane. The fleet runs +// darwin/linux; a Windows port should serve the same HTTP/1.1 API over a named +// pipe (`\\.\pipe\devbox-control`) via Microsoft's go-winio — swap the +// net.Listen("unix", …) in server.go for winio.ListenPipe and the client's +// net.Dial for winio.DialPipe. Until a Windows user exists, we don't build it. + +// Daemon is the slice of the running daemon the control server would steer. +type Daemon interface { + StateSnapshot() State + Pause() + Resume() +} + +// Server is a no-op on Windows. +type Server struct{} + +// Serve reports that the control socket isn't supported on Windows yet. The +// daemon warns and continues; sync is unaffected. +func Serve(_ context.Context, _ string, _ Daemon, _ func(string, ...any)) (*Server, error) { + return nil, errors.New("control socket not supported on windows yet") +} + +// Publish is a no-op on Windows. +func (s *Server) Publish(_, _ string) {} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 5ebdd51..c765b32 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -6,12 +6,15 @@ package daemon import ( "context" + "fmt" "log" "math/rand" "sync" + "sync/atomic" "time" "git.shoemoney.ai/shoemoney/devbox/internal/config" + "git.shoemoney.ai/shoemoney/devbox/internal/control" "git.shoemoney.ai/shoemoney/devbox/internal/hooks" "git.shoemoney.ai/shoemoney/devbox/internal/secret" "git.shoemoney.ai/shoemoney/devbox/internal/syncer" @@ -37,8 +40,13 @@ type Daemon struct { maxBytesPerSec int logf func(string, ...any) - mu sync.Mutex - state map[string]string // mountKey -> last-applied snapshot + paused atomic.Bool // set via control /pause; gates the sync loop + + mu sync.Mutex + state map[string]string // mountKey -> last-applied snapshot + nudges map[string]func() // mountKey -> trigger a catch-up sync (for Resume) + mounts map[string]config.Mount // mountKey -> mount config (for StateSnapshot) + ctrl *control.Server // nil until Run starts it (and on Windows) } // New builds a daemon from a loaded config. logf may be nil (defaults to log.Printf). @@ -62,11 +70,22 @@ func New(dir string, cfg config.Daemon, host string, logf func(string, ...any)) dir: dir, cfg: cfg, host: host, guard: guard, maxBytesPerSec: settings.Transfer.MaxKbps * 1024, logf: logf, state: state, + nudges: map[string]func(){}, + mounts: map[string]config.Mount{}, }, nil } // Run syncs every mount until ctx is cancelled. func (d *Daemon) Run(ctx context.Context) error { + // Start the control plane before mounts so `devbox status`/`pause` can reach + // the daemon immediately. A bind failure is non-fatal: sync must not depend on + // the control socket. Serve stops itself on ctx cancel. + if srv, err := control.Serve(ctx, d.dir, d, d.logf); err != nil { + d.logf("control socket unavailable (introspection/pause disabled): %v", err) + } else { + d.ctrl = srv + } + var wg sync.WaitGroup for _, m := range d.cfg.Mounts { wg.Add(1) @@ -118,6 +137,10 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) { default: // a sync is already queued; coalesce } } + // Register this mount so the control plane can read its live state and so + // Resume can kick it into a catch-up sync. Unregister on exit. + d.register(m, nudge) + defer d.unregister(m) // Local filesystem changes -> sync. If the watcher can't start (e.g. inotify // limit), we don't bail: the periodic rescan below keeps the mount syncing. @@ -184,17 +207,84 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) { } }() - nudge() // initial sync + if !d.paused.Load() { + nudge() // initial sync (skipped while paused) + } for { select { case <-ctx.Done(): return case <-trigger: + // While paused we drain the trigger but don't sync; Resume re-nudges + // every mount so nothing buffered while paused is lost. + if d.paused.Load() { + continue + } d.syncMount(c, m) } } } +// register records a mount's nudge and config so Resume can catch it up and the +// control plane can report its live state. +func (d *Daemon) register(m config.Mount, nudge func()) { + k := mountKey(m) + d.mu.Lock() + d.nudges[k] = nudge + d.mounts[k] = m + d.mu.Unlock() +} + +func (d *Daemon) unregister(m config.Mount) { + k := mountKey(m) + d.mu.Lock() + delete(d.nudges, k) + delete(d.mounts, k) + d.mu.Unlock() +} + +// Pause stops syncing until Resume. In-flight syncs finish; queued/new triggers +// are drained without effect while paused. +func (d *Daemon) Pause() { + d.paused.Store(true) + d.logf("⏸️ paused — syncing suspended (devbox resume to continue)") +} + +// Resume clears the pause and nudges every registered mount into an immediate +// catch-up sync, so edits made while paused converge right away. +func (d *Daemon) Resume() { + d.paused.Store(false) + d.mu.Lock() + nudges := make([]func(), 0, len(d.nudges)) + for _, n := range d.nudges { + nudges = append(nudges, n) + } + d.mu.Unlock() + for _, n := range nudges { + n() + } + d.logf("▶️ resumed — catching up %d mount(s)", len(nudges)) +} + +// StateSnapshot returns the running daemon's live per-mount + paused view for +// the control plane's GET /state. +func (d *Daemon) StateSnapshot() control.State { + d.mu.Lock() + defer d.mu.Unlock() + st := control.State{Paused: d.paused.Load()} + for k, m := range d.mounts { + st.Mounts = append(st.Mounts, control.MountState{ + Share: m.Share, + Subpath: m.Subpath, + Local: m.Local, + ReadOnly: m.ReadOnly, + Pinned: m.Pinned, + BaseSnapshot: d.state[k], + }) + } + return st +} + func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { ig, err := syncer.LoadIgnore(m.Local) if err != nil { @@ -213,6 +303,7 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { } d.setBase(m, pr.Base) d.report(m, pr) + d.publishActivity(m, pr) return } @@ -223,6 +314,14 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { } d.setBase(m, newBase) d.report(m, pr) + d.publishActivity(m, pr) +} + +// publishActivity feeds a one-line sync summary to the control plane's +// GET /events stream (no-op when the control server didn't start). +func (d *Daemon) publishActivity(m config.Mount, pr syncer.PullResult) { + d.ctrl.Publish(m.Share, fmt.Sprintf("synced: %d written, %d deleted, %d conflicts, %d skipped", + len(pr.Written), len(pr.Deleted), len(pr.Conflicts), len(pr.Skipped))) } func (d *Daemon) report(m config.Mount, pr syncer.PullResult) { diff --git a/internal/daemon/pause_test.go b/internal/daemon/pause_test.go new file mode 100644 index 0000000..82b535a --- /dev/null +++ b/internal/daemon/pause_test.go @@ -0,0 +1,90 @@ +package daemon + +import ( + "context" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "git.shoemoney.ai/shoemoney/devbox/internal/config" + "git.shoemoney.ai/shoemoney/devbox/internal/hub" + "git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore" + "git.shoemoney.ai/shoemoney/devbox/internal/hub/meta" + "git.shoemoney.ai/shoemoney/devbox/internal/transport" +) + +// absent reports whether path stays absent for the whole window. It's the +// inverse of waitFor: it proves a change did NOT propagate. +func absent(path string, d time.Duration) bool { + deadline := time.Now().Add(d) + for time.Now().Before(deadline) { + if _, err := os.Stat(path); err == nil { + return false + } + time.Sleep(50 * time.Millisecond) + } + return true +} + +// TestPauseGatesSyncing is the load-bearing pause test: while paused, a local +// edit must NOT reach the peer; after resume it must. If Pause() were wired but +// runMount still synced through the trigger, the "absent while paused" assertion +// would fail — so this test fails loudly if pause doesn't gate syncing. +func TestPauseGatesSyncing(t *testing.T) { + db, err := meta.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + store, err := blobstore.NewDisk(t.TempDir()) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(hub.NewServer(db, store).Handler()) + defer srv.Close() + + bearerA := join(t, db, srv.URL, "alice") + bearerB := join(t, db, srv.URL, "bob") + + ca := transport.New(srv.URL) + ca.SetBearer(bearerA) + if err := ca.Publish("s"); err != nil { + t.Fatal(err) + } + + rootA, rootB := t.TempDir(), t.TempDir() + dirA := t.TempDir() + dirB := t.TempDir() + cfgA := config.Daemon{Hub: srv.URL, Bearer: bearerA, Mounts: []config.Mount{{Share: "s", Local: rootA, Hub: srv.URL}}} + cfgB := config.Daemon{Hub: srv.URL, Bearer: bearerB, Mounts: []config.Mount{{Share: "s", Local: rootB, Hub: srv.URL}}} + + dA, err := New(dirA, cfgA, "alice", t.Logf) + if err != nil { + t.Fatal(err) + } + dB, err := New(dirB, cfgB, "bob", t.Logf) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go dA.Run(ctx) + go dB.Run(ctx) + time.Sleep(300 * time.Millisecond) // let both subscribe + do initial sync + + // Pause Alice, then make a local edit. It must NOT reach Bob while paused. + dA.Pause() + writeF(t, rootA, "while-paused.txt", "should not propagate yet\n") + peerPath := filepath.Join(rootB, "while-paused.txt") + if !absent(peerPath, 2*time.Second) { + t.Fatal("edit propagated while paused — Pause() did not gate syncing") + } + + // Resume Alice: the buffered edit must now converge to Bob. + dA.Resume() + if !waitFor(peerPath, "should not propagate yet\n", 10*time.Second) { + t.Fatal("edit did not propagate after resume — Resume() did not catch up") + } +}