devbox/internal/control/control.go
shoemoney 8c5d576a72 feat(device): --json output, streaming chunker, pause --for, per-mount exclude, rescan knob ✨
Five device-side wins from the feature review:

- 🤖 `--json` on status/log/conflicts: machine-readable output for fleet
  scripting/monitoring. status prefers live daemon state (paused +
  base-snapshot), falls back to disk; not-joined → {"joined":false}.
- 🌊 streaming chunker: chunk.SplitReader feeds FastCDC from an io.Reader so
  the manifest build no longer slurps whole files into RAM — a multi-GB file
  can't OOM the daemon. Identical boundaries/hashes (proven vs fragmented reads).
- ⏱️  `devbox pause --for 2h`: control socket carries a duration; the daemon
  schedules an auto-resume timer. Re-pause replaces it; plain pause/resume
  cancel it (no surprise resume).
- 🙈 per-mount `devbox mount --exclude <pat>`: device-local ignore layered on
  the shared .devignore (LoadIgnoreWith) — skip a local build dir without
  touching the shared file. Honored by daemon sync, restore, and deploy.
- 🎛️  rescan cadence is now settings.sync.rescan_seconds (was a hardcoded 60s
  const) — tune the watcher fallback per machine without a rebuild.

#6 (doctor non-zero exit) was already shipped — doctor returns an error on ❌.
Tests: SplitReader-vs-buffered, PauseFor auto-resume + cancel, wire duration,
LoadIgnoreWith layering, status/conflicts --json. go test ./... -race clean.
2026-06-30 12:29:02 -05:00

122 lines
4.1 KiB
Go

// 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"
"net/url"
"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"`
}
// Daemon is the slice of the running daemon the control server steers. The
// daemon package implements it; declared here (not in the build-tagged server
// files) so the real server and the Windows stub share one definition and can't
// drift. The server depends on this behaviour, not the daemon package — no cycle.
type Daemon interface {
StateSnapshot() State // live per-mount + paused view for GET /state
Pause() // stop syncing until resumed
PauseFor(dur time.Duration) // pause, then auto-resume after dur
Resume() // clear pause + catch up all mounts
}
// 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") }
// PauseFor asks the daemon to pause and auto-resume after dur.
func PauseFor(dir string, dur time.Duration) error {
return post(dir, "/pause?for="+url.QueryEscape(dur.String()))
}
// 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
}