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.
This commit is contained in:
shoemoney 2026-06-30 12:29:02 -05:00
parent 5440054a41
commit 8c5d576a72
14 changed files with 361 additions and 45 deletions

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"os" "os"
"time"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -12,7 +13,8 @@ import (
) )
func pauseCmd() *cobra.Command { func pauseCmd() *cobra.Command {
return &cobra.Command{ var forDur time.Duration
cmd := &cobra.Command{
Use: "pause", Use: "pause",
Short: "⏸️ pause syncing on the running daemon", Short: "⏸️ pause syncing on the running daemon",
RunE: func(cmd *cobra.Command, _ []string) error { RunE: func(cmd *cobra.Command, _ []string) error {
@ -20,6 +22,13 @@ func pauseCmd() *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
if forDur > 0 {
if err := control.PauseFor(dir, forDur); err != nil {
return daemonHint(err)
}
fmt.Fprintf(cmd.OutOrStdout(), "⏸️ paused — auto-resumes in %s (or run: devbox resume)\n", forDur)
return nil
}
if err := control.Pause(dir); err != nil { if err := control.Pause(dir); err != nil {
return daemonHint(err) return daemonHint(err)
} }
@ -27,6 +36,8 @@ func pauseCmd() *cobra.Command {
return nil return nil
}, },
} }
cmd.Flags().DurationVar(&forDur, "for", 0, "auto-resume after this duration (e.g. 2h, 30m); 0 = until 'devbox resume'")
return cmd
} }
func resumeCmd() *cobra.Command { func resumeCmd() *cobra.Command {

View file

@ -4,7 +4,9 @@ package main
import ( import (
"cmp" "cmp"
"context" "context"
"encoding/json"
"fmt" "fmt"
"io"
"io/fs" "io/fs"
"net/http" "net/http"
"os" "os"
@ -189,6 +191,7 @@ func publishCmd() *cobra.Command {
func mountCmd() *cobra.Command { func mountCmd() *cobra.Command {
var ro bool var ro bool
var exclude []string
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "mount <share[/subpath]> <localdir>", Use: "mount <share[/subpath]> <localdir>",
Short: "🔗 mount a hub share (or sub-path) into a local directory (clone + sync)", Short: "🔗 mount a hub share (or sub-path) into a local directory (clone + sync)",
@ -213,14 +216,14 @@ func mountCmd() *cobra.Command {
if err := os.MkdirAll(local, 0o755); err != nil { if err := os.MkdirAll(local, 0o755); err != nil {
return err return err
} }
d.Mounts = upsertMount(d.Mounts, config.Mount{Share: share, Subpath: subpath, Local: local, Hub: d.Hub, ReadOnly: ro}) d.Mounts = upsertMount(d.Mounts, config.Mount{Share: share, Subpath: subpath, Local: local, Hub: d.Hub, ReadOnly: ro, Exclude: exclude})
if err := config.SaveDaemon(dir, d); err != nil { if err := config.SaveDaemon(dir, d); err != nil {
return err return err
} }
c := transport.New(d.Hub) c := transport.New(d.Hub)
c.SetBearer(d.Bearer) c.SetBearer(d.Bearer)
ig, err := syncer.LoadIgnore(local) ig, err := syncer.LoadIgnoreWith(local, exclude)
if err != nil { if err != nil {
return err return err
} }
@ -263,6 +266,7 @@ func mountCmd() *cobra.Command {
}, },
} }
cmd.Flags().BoolVar(&ro, "ro", false, "mount read-only (pull only, never push)") cmd.Flags().BoolVar(&ro, "ro", false, "mount read-only (pull only, never push)")
cmd.Flags().StringArrayVar(&exclude, "exclude", nil, "device-local ignore pattern (gitignore syntax; repeatable) layered on .devignore")
return cmd return cmd
} }
@ -285,8 +289,16 @@ func upsertMount(mounts []config.Mount, m config.Mount) []config.Mount {
return append(mounts, m) return append(mounts, m)
} }
// writeJSON encodes v as indented JSON to w — the shared backend for --json flags.
func writeJSON(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(v)
}
func logCmd() *cobra.Command { func logCmd() *cobra.Command {
return &cobra.Command{ var asJSON bool
cmd := &cobra.Command{
Use: "log <share>", Use: "log <share>",
Short: "🕓 show a share's snapshot history", Short: "🕓 show a share's snapshot history",
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
@ -310,6 +322,9 @@ func logCmd() *cobra.Command {
return err return err
} }
out := cmd.OutOrStdout() out := cmd.OutOrStdout()
if asJSON {
return writeJSON(out, snaps)
}
for _, s := range snaps { for _, s := range snaps {
ts := time.Unix(s.CreatedAt, 0).Format("2006-01-02 15:04:05") ts := time.Unix(s.CreatedAt, 0).Format("2006-01-02 15:04:05")
fmt.Fprintf(out, "%s %s %s\n", s.ID, ts, s.Device) // full id so it round-trips to restore fmt.Fprintf(out, "%s %s %s\n", s.ID, ts, s.Device) // full id so it round-trips to restore
@ -317,6 +332,8 @@ func logCmd() *cobra.Command {
return nil return nil
}, },
} }
cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON")
return cmd
} }
func inviteCmd() *cobra.Command { func inviteCmd() *cobra.Command {
@ -446,7 +463,7 @@ func restoreCmd() *cobra.Command {
c := transport.New(d.Hub) c := transport.New(d.Hub)
c.SetBearer(d.Bearer) c.SetBearer(d.Bearer)
ig, err := syncer.LoadIgnore(m.Local) ig, err := syncer.LoadIgnoreWith(m.Local, m.Exclude)
if err != nil { if err != nil {
return err return err
} }
@ -547,7 +564,8 @@ func ignoreCmd() *cobra.Command {
} }
func conflictsCmd() *cobra.Command { func conflictsCmd() *cobra.Command {
return &cobra.Command{ var asJSON bool
cmd := &cobra.Command{
Use: "conflicts", Use: "conflicts",
Short: "💥 list conflict copies across all mounts", Short: "💥 list conflict copies across all mounts",
RunE: func(cmd *cobra.Command, _ []string) error { RunE: func(cmd *cobra.Command, _ []string) error {
@ -560,7 +578,11 @@ func conflictsCmd() *cobra.Command {
return err return err
} }
out := cmd.OutOrStdout() out := cmd.OutOrStdout()
n := 0 type conflict struct {
Share string `json:"share"`
Path string `json:"path"`
}
found := []conflict{}
for _, m := range d.Mounts { for _, m := range d.Mounts {
_ = filepath.WalkDir(m.Local, func(p string, e fs.DirEntry, err error) error { _ = filepath.WalkDir(m.Local, func(p string, e fs.DirEntry, err error) error {
if err != nil || e.IsDir() { if err != nil || e.IsDir() {
@ -568,20 +590,27 @@ func conflictsCmd() *cobra.Command {
} }
if strings.Contains(e.Name(), ".conflict-") { if strings.Contains(e.Name(), ".conflict-") {
rel, _ := filepath.Rel(m.Local, p) rel, _ := filepath.Rel(m.Local, p)
fmt.Fprintf(out, " 💥 %s/%s\n", m.Share, filepath.ToSlash(rel)) found = append(found, conflict{Share: m.Share, Path: filepath.ToSlash(rel)})
n++
} }
return nil return nil
}) })
} }
if n == 0 { if asJSON {
return writeJSON(out, found)
}
for _, cf := range found {
fmt.Fprintf(out, " 💥 %s/%s\n", cf.Share, cf.Path)
}
if len(found) == 0 {
fmt.Fprintln(out, "✅ no conflict copies") fmt.Fprintln(out, "✅ no conflict copies")
} else { } else {
fmt.Fprintf(out, "%d conflict copy(ies) — review, then delete the loser(s)\n", n) fmt.Fprintf(out, "%d conflict copy(ies) — review, then delete the loser(s)\n", len(found))
} }
return nil return nil
}, },
} }
cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON")
return cmd
} }
// findMount returns the first configured mount for share. // findMount returns the first configured mount for share.
@ -623,7 +652,7 @@ func deployCmd() *cobra.Command {
c := transport.New(d.Hub) c := transport.New(d.Hub)
c.SetBearer(d.Bearer) c.SetBearer(d.Bearer)
ig, err := syncer.LoadIgnore(m.Local) ig, err := syncer.LoadIgnoreWith(m.Local, m.Exclude)
if err != nil { if err != nil {
return err return err
} }
@ -715,8 +744,27 @@ func startCmd() *cobra.Command {
} }
} }
type statusMount struct {
Share string `json:"share"`
Subpath string `json:"subpath,omitempty"`
Local string `json:"local"`
ReadOnly bool `json:"readonly"`
Pinned bool `json:"pinned"`
BaseSnapshot string `json:"base_snapshot,omitempty"`
}
type statusJSON struct {
Joined bool `json:"joined"`
Device string `json:"device,omitempty"`
Hub string `json:"hub,omitempty"`
Live bool `json:"live"`
Paused bool `json:"paused"`
Mounts []statusMount `json:"mounts"`
}
func statusCmd() *cobra.Command { func statusCmd() *cobra.Command {
return &cobra.Command{ var asJSON bool
cmd := &cobra.Command{
Use: "status", Use: "status",
Short: "📊 show device + sync status", Short: "📊 show device + sync status",
RunE: func(cmd *cobra.Command, _ []string) error { RunE: func(cmd *cobra.Command, _ []string) error {
@ -727,6 +775,9 @@ func statusCmd() *cobra.Command {
out := cmd.OutOrStdout() out := cmd.OutOrStdout()
id, err := identity.Load(dir) id, err := identity.Load(dir)
if err != nil { if err != nil {
if asJSON {
return writeJSON(out, statusJSON{Joined: false})
}
fmt.Fprintln(out, "not joined yet — run: devbox join <hub> <token>") fmt.Fprintln(out, "not joined yet — run: devbox join <hub> <token>")
return nil return nil
} }
@ -735,6 +786,27 @@ func statusCmd() *cobra.Command {
return fmt.Errorf("reading config: %w", err) return fmt.Errorf("reading config: %w", err)
} }
if asJSON {
s := statusJSON{Joined: true, Device: id.Fingerprint(), Hub: d.Hub, Mounts: []statusMount{}}
if live, err := control.DialState(dir); err == nil {
s.Live, s.Paused = true, live.Paused
for _, m := range live.Mounts {
s.Mounts = append(s.Mounts, statusMount{
Share: m.Share, Subpath: m.Subpath, Local: m.Local,
ReadOnly: m.ReadOnly, Pinned: m.Pinned, BaseSnapshot: m.BaseSnapshot,
})
}
} else {
for _, m := range d.Mounts {
s.Mounts = append(s.Mounts, statusMount{
Share: m.Share, Subpath: m.Subpath, Local: m.Local,
ReadOnly: m.ReadOnly, Pinned: m.Pinned,
})
}
}
return writeJSON(out, s)
}
// Prefer the LIVE daemon when it's running AND stdout is a terminal: // 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 // 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 // can't. Piped/non-TTY output must stay byte-identical to v1 (scripts
@ -780,6 +852,8 @@ func statusCmd() *cobra.Command {
return nil return nil
}, },
} }
cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON (prefers live daemon state)")
return cmd
} }
func orNone(s string) string { func orNone(s string) string {

View file

@ -1,12 +1,58 @@
package main package main
import ( import (
"bytes"
"encoding/json"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
) )
// TestStatusJSON proves `status --json` emits valid JSON and reports not-joined
// on a fresh config dir (the scriptable path for fleet monitoring).
func TestStatusJSON(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // empty → unjoined device
var buf bytes.Buffer
cmd := statusCmd()
cmd.SetOut(&buf)
cmd.SetArgs([]string{"--json"})
if err := cmd.Execute(); err != nil {
t.Fatalf("status --json: %v", err)
}
var got statusJSON
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("status --json emitted invalid JSON: %v\n%s", err, buf.String())
}
if got.Joined {
t.Fatalf("fresh config dir should report joined=false, got %+v", got)
}
}
// TestConflictsJSON proves `conflicts --json` emits a JSON array (never null).
func TestConflictsJSON(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var buf bytes.Buffer
cmd := conflictsCmd()
cmd.SetOut(&buf)
cmd.SetArgs([]string{"--json"})
if err := cmd.Execute(); err != nil {
t.Fatalf("conflicts --json: %v", err)
}
var got []struct {
Share string `json:"share"`
Path string `json:"path"`
}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("conflicts --json emitted invalid JSON: %v\n%s", err, buf.String())
}
if len(got) != 0 {
t.Fatalf("no mounts should yield empty list, got %v", got)
}
}
// TestWritePidArbitration covers the O_EXCL claim, the live-daemon refusal, and // TestWritePidArbitration covers the O_EXCL claim, the live-daemon refusal, and
// stale-pidfile recovery. // stale-pidfile recovery.
func TestWritePidArbitration(t *testing.T) { func TestWritePidArbitration(t *testing.T) {

View file

@ -46,17 +46,29 @@ type Chunk struct {
// matters once Split streams from an io.Reader, where a mid-input error would // matters once Split streams from an io.Reader, where a mid-input error would
// otherwise produce a short, valid-looking chunk list with the wrong hash. // otherwise produce a short, valid-looking chunk list with the wrong hash.
// //
// ponytail: Split is in-memory — it takes the whole []byte and the underlying // Split divides an in-memory buffer. It is a convenience wrapper over
// chunker reads from a bytes.Reader over it. Streaming large inputs from an // SplitReader for callers that already hold the whole []byte.
// io.Reader without buffering the entire payload is the upgrade path.
func Split(data []byte) ([]Chunk, error) { func Split(data []byte) ([]Chunk, error) {
if len(data) == 0 { if len(data) == 0 {
return nil, nil return nil, nil
} }
return SplitReader(bytes.NewReader(data))
}
// SplitReader chunks an arbitrarily large input in bounded memory: FastCDC reads
// from r in windows of at most MaxSize, so a multi-GB file never has to be held
// whole in RAM (the OOM ceiling the old whole-[]byte path had). Same chunk
// boundaries and hashes as Split for identical content.
//
// ponytail: holds the process-wide splitMu (see above) for the whole read, so a
// slow reader serializes chunking longer than the in-memory path did. Acceptable
// while chunking is already globally serialized; the upgrade path is a per-chunker
// FastCDC table (then this lock disappears entirely).
func SplitReader(r io.Reader) ([]Chunk, error) {
splitMu.Lock() splitMu.Lock()
defer splitMu.Unlock() defer splitMu.Unlock()
chunker, err := fastcdc.NewChunker(bytes.NewReader(data), fastcdc.Options{ chunker, err := fastcdc.NewChunker(r, fastcdc.Options{
MinSize: MinSize, MinSize: MinSize,
AverageSize: AvgSize, AverageSize: AvgSize,
MaxSize: MaxSize, MaxSize: MaxSize,

View file

@ -4,8 +4,29 @@ import (
"bytes" "bytes"
"math/rand" "math/rand"
"testing" "testing"
"testing/iotest"
) )
// TestSplitReaderMatchesSplit proves streaming gives the same chunk boundaries
// and hashes as the whole-buffer path even when the reader hands back data one
// byte at a time (fragmented reads must not shift FastCDC's cut points).
func TestSplitReaderMatchesSplit(t *testing.T) {
data := seededBlob(7, 512*1024) // > MaxSize so it really chunks
want := mustSplit(t, data)
got, err := SplitReader(iotest.OneByteReader(bytes.NewReader(data)))
if err != nil {
t.Fatalf("SplitReader error: %v", err)
}
if len(got) != len(want) {
t.Fatalf("chunk count: streamed %d, buffered %d", len(got), len(want))
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("chunk %d differs: streamed %+v, buffered %+v", i, got[i], want[i])
}
}
}
// seededBlob returns a deterministic pseudo-random blob of n bytes. // seededBlob returns a deterministic pseudo-random blob of n bytes.
func seededBlob(seed int64, n int) []byte { func seededBlob(seed int64, n int) []byte {
r := rand.New(rand.NewSource(seed)) r := rand.New(rand.NewSource(seed))

View file

@ -42,6 +42,10 @@ type Mount struct {
// Pinned means this mount is held at a deployed snapshot (devbox deploy) and // Pinned means this mount is held at a deployed snapshot (devbox deploy) and
// the daemon must NOT live-advance it to head. Re-mounting clears it. // the daemon must NOT live-advance it to head. Re-mounting clears it.
Pinned bool `toml:"pinned,omitempty"` Pinned bool `toml:"pinned,omitempty"`
// Exclude are device-local ignore patterns (gitignore syntax) layered on top
// of the share-wide .devignore — for paths this machine shouldn't sync (e.g. a
// local build dir) without touching the shared ignore file.
Exclude []string `toml:"exclude,omitempty"`
} }
// Daemon is daemon.toml: which hub this device joined (with its bearer token and // Daemon is daemon.toml: which hub this device joined (with its bearer token and
@ -95,10 +99,14 @@ func SaveDaemon(dir string, d Daemon) error {
type Settings struct { type Settings struct {
Transfer struct { Transfer struct {
MaxKbps int `toml:"max_kbps"` // blob transfer cap; 0 = unlimited MaxKbps int `toml:"max_kbps"` // blob transfer cap; 0 = unlimited
Compress bool `toml:"compress"` // gzip blob uploads (helps over WAN; off by default)
} `toml:"transfer"` } `toml:"transfer"`
Secrets struct { Secrets struct {
ExtraPatterns []string `toml:"extra_patterns"` ExtraPatterns []string `toml:"extra_patterns"`
} `toml:"secrets"` } `toml:"secrets"`
Sync struct {
RescanSeconds int `toml:"rescan_seconds"` // periodic rescan cadence; 0 = default (60s)
} `toml:"sync"`
} }
// LoadSettings reads config.toml from dir (zero Settings if absent). // LoadSettings reads config.toml from dir (zero Settings if absent).

View file

@ -14,6 +14,7 @@ import (
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
"net/url"
"path/filepath" "path/filepath"
"time" "time"
) )
@ -48,6 +49,7 @@ type MountState struct {
type Daemon interface { type Daemon interface {
StateSnapshot() State // live per-mount + paused view for GET /state StateSnapshot() State // live per-mount + paused view for GET /state
Pause() // stop syncing until resumed Pause() // stop syncing until resumed
PauseFor(dur time.Duration) // pause, then auto-resume after dur
Resume() // clear pause + catch up all mounts Resume() // clear pause + catch up all mounts
} }
@ -99,6 +101,11 @@ func DialState(dir string) (State, error) {
// Pause asks the daemon to stop syncing until resumed. // Pause asks the daemon to stop syncing until resumed.
func Pause(dir string) error { return post(dir, "/pause") } 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. // Resume clears the pause and triggers an immediate catch-up on all mounts.
func Resume(dir string) error { return post(dir, "/resume") } func Resume(dir string) error { return post(dir, "/resume") }

View file

@ -16,6 +16,7 @@ type fakeDaemon struct {
mu sync.Mutex mu sync.Mutex
paused bool paused bool
resumes int resumes int
pauseFor time.Duration
} }
func (f *fakeDaemon) StateSnapshot() State { func (f *fakeDaemon) StateSnapshot() State {
@ -27,6 +28,13 @@ func (f *fakeDaemon) StateSnapshot() State {
} }
} }
func (f *fakeDaemon) PauseFor(dur time.Duration) {
f.mu.Lock()
f.paused = true
f.pauseFor = dur
f.mu.Unlock()
}
func (f *fakeDaemon) Pause() { func (f *fakeDaemon) Pause() {
f.mu.Lock() f.mu.Lock()
f.paused = true f.paused = true
@ -109,6 +117,25 @@ func TestRoundTripPauseStateResume(t *testing.T) {
} }
} }
// TestPauseForCarriesDuration proves POST /pause?for=<dur> reaches the daemon's
// PauseFor with the duration intact (the wire path for `devbox pause --for`).
func TestPauseForCarriesDuration(t *testing.T) {
dir, fd := serveTest(t)
if err := PauseFor(dir, 90*time.Minute); err != nil {
t.Fatalf("PauseFor: %v", err)
}
fd.mu.Lock()
got, paused := fd.pauseFor, fd.paused
fd.mu.Unlock()
if !paused {
t.Fatal("PauseFor should have paused the daemon")
}
if got != 90*time.Minute {
t.Fatalf("PauseFor duration = %s, want 90m", got)
}
}
// TestNoDaemonReturnsNotRunning proves the client returns the typed // TestNoDaemonReturnsNotRunning proves the client returns the typed
// ErrNotRunning when no daemon is listening, so callers can fall back. // ErrNotRunning when no daemon is listening, so callers can fall back.
func TestNoDaemonReturnsNotRunning(t *testing.T) { func TestNoDaemonReturnsNotRunning(t *testing.T) {

View file

@ -82,7 +82,17 @@ func (s *Server) handleState(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(s.d.StateSnapshot()) _ = json.NewEncoder(w).Encode(s.d.StateSnapshot())
} }
func (s *Server) handlePause(w http.ResponseWriter, _ *http.Request) { func (s *Server) handlePause(w http.ResponseWriter, r *http.Request) {
if v := r.URL.Query().Get("for"); v != "" {
dur, err := time.ParseDuration(v)
if err != nil || dur <= 0 {
http.Error(w, "bad for= duration", http.StatusBadRequest)
return
}
s.d.PauseFor(dur)
w.WriteHeader(http.StatusOK)
return
}
s.d.Pause() s.d.Pause()
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
} }

View file

@ -22,13 +22,13 @@ import (
"github.com/shoemoney/devbox/pkg/proto" "github.com/shoemoney/devbox/pkg/proto"
) )
// rescanInterval is the safety-net cadence for re-syncing a mount even when no // defaultRescanInterval is the safety-net cadence for re-syncing a mount even
// trigger fired. It backstops a watcher that never started (e.g. inotify // when no trigger fired. It backstops a watcher that never started (e.g. inotify
// max_user_watches exhausted on a big Pi tree) or an event that slipped through: // max_user_watches exhausted on a big Pi tree) or an event that slipped through:
// without it, such a mount would stop pushing local edits entirely. PRD risk #1. // without it, such a mount would stop pushing local edits entirely. PRD risk #1.
// ponytail: fixed 60s; promote to a Settings knob only if a huge tree makes the // Overridable per machine via settings.sync.rescan_seconds (Daemon.rescanInterval)
// periodic manifest rebuild measurably costly. // — a huge tree can lengthen it, a latency-sensitive one can shorten it.
const rescanInterval = 60 * time.Second const defaultRescanInterval = 60 * time.Second
// Daemon syncs a device's mounts against their hub. // Daemon syncs a device's mounts against their hub.
type Daemon struct { type Daemon struct {
@ -37,6 +37,8 @@ type Daemon struct {
host string host string
guard *secret.Guard guard *secret.Guard
maxBytesPerSec int maxBytesPerSec int
compress bool // gzip blob uploads (settings.transfer.compress)
rescanInterval time.Duration // periodic safety-net cadence (settings.sync.rescan_seconds)
logf func(string, ...any) logf func(string, ...any)
paused atomic.Bool // set via control /pause; gates the sync loop paused atomic.Bool // set via control /pause; gates the sync loop
@ -45,6 +47,7 @@ type Daemon struct {
state map[string]string // mountKey -> last-applied snapshot state map[string]string // mountKey -> last-applied snapshot
nudges map[string]func() // mountKey -> trigger a catch-up sync (for Resume) nudges map[string]func() // mountKey -> trigger a catch-up sync (for Resume)
mounts map[string]config.Mount // mountKey -> mount config (for StateSnapshot) mounts map[string]config.Mount // mountKey -> mount config (for StateSnapshot)
resumeTimer *time.Timer // pending auto-resume from PauseFor; nil if none
} }
// New builds a daemon from a loaded config. logf may be nil (defaults to log.Printf). // New builds a daemon from a loaded config. logf may be nil (defaults to log.Printf).
@ -64,9 +67,15 @@ func New(dir string, cfg config.Daemon, host string, logf func(string, ...any))
if logf == nil { if logf == nil {
logf = log.Printf logf = log.Printf
} }
rescan := defaultRescanInterval
if settings.Sync.RescanSeconds > 0 {
rescan = time.Duration(settings.Sync.RescanSeconds) * time.Second
}
return &Daemon{ return &Daemon{
dir: dir, cfg: cfg, host: host, guard: guard, dir: dir, cfg: cfg, host: host, guard: guard,
maxBytesPerSec: settings.Transfer.MaxKbps * 1024, maxBytesPerSec: settings.Transfer.MaxKbps * 1024,
compress: settings.Transfer.Compress,
rescanInterval: rescan,
logf: logf, state: state, logf: logf, state: state,
nudges: map[string]func(){}, nudges: map[string]func(){},
mounts: map[string]config.Mount{}, mounts: map[string]config.Mount{},
@ -141,7 +150,7 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) {
// Local filesystem changes -> sync. If the watcher can't start (e.g. inotify // 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. // limit), we don't bail: the periodic rescan below keeps the mount syncing.
if w, err := watch.New(m.Local, 300*time.Millisecond); err != nil { if w, err := watch.New(m.Local, 300*time.Millisecond); err != nil {
d.logf("watch %s: %v — falling back to %s rescans (run: devbox doctor)", m.Local, err, rescanInterval) d.logf("watch %s: %v — falling back to %s rescans (run: devbox doctor)", m.Local, err, d.rescanInterval)
} else { } else {
defer w.Close() defer w.Close()
go func() { go func() {
@ -189,9 +198,9 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) {
select { select {
case <-ctx.Done(): case <-ctx.Done():
return return
case <-time.After(time.Duration(rand.Int63n(int64(rescanInterval)))): case <-time.After(time.Duration(rand.Int63n(int64(d.rescanInterval)))):
} }
t := time.NewTicker(rescanInterval) t := time.NewTicker(d.rescanInterval)
defer t.Stop() defer t.Stop()
for { for {
select { select {
@ -243,14 +252,43 @@ func (d *Daemon) unregister(m config.Mount) {
// are drained without effect while paused. // are drained without effect while paused.
func (d *Daemon) Pause() { func (d *Daemon) Pause() {
d.paused.Store(true) d.paused.Store(true)
d.clearResumeTimer() // an explicit pause overrides any pending auto-resume
d.logf("⏸️ paused — syncing suspended (devbox resume to continue)") d.logf("⏸️ paused — syncing suspended (devbox resume to continue)")
} }
// PauseFor pauses syncing and auto-resumes after dur (devbox pause --for). A new
// pause replaces any pending auto-resume; an explicit Resume cancels it. A
// non-positive dur is an indefinite pause, identical to Pause.
func (d *Daemon) PauseFor(dur time.Duration) {
d.Pause() // clears any prior timer (fully unlocks before we re-lock below)
if dur <= 0 {
return
}
d.mu.Lock()
d.resumeTimer = time.AfterFunc(dur, d.Resume)
d.mu.Unlock()
d.logf("⏱️ auto-resume scheduled in %s", dur)
}
// clearResumeTimer stops and drops any pending PauseFor auto-resume.
func (d *Daemon) clearResumeTimer() {
d.mu.Lock()
if d.resumeTimer != nil {
d.resumeTimer.Stop()
d.resumeTimer = nil
}
d.mu.Unlock()
}
// Resume clears the pause and nudges every registered mount into an immediate // Resume clears the pause and nudges every registered mount into an immediate
// catch-up sync, so edits made while paused converge right away. // catch-up sync, so edits made while paused converge right away.
func (d *Daemon) Resume() { func (d *Daemon) Resume() {
d.paused.Store(false) d.paused.Store(false)
d.mu.Lock() d.mu.Lock()
if d.resumeTimer != nil { // cancel any pending auto-resume from PauseFor
d.resumeTimer.Stop()
d.resumeTimer = nil
}
nudges := make([]func(), 0, len(d.nudges)) nudges := make([]func(), 0, len(d.nudges))
for _, n := range d.nudges { for _, n := range d.nudges {
nudges = append(nudges, n) nudges = append(nudges, n)
@ -282,7 +320,7 @@ func (d *Daemon) StateSnapshot() control.State {
} }
func (d *Daemon) syncMount(c *transport.Client, m config.Mount) { func (d *Daemon) syncMount(c *transport.Client, m config.Mount) {
ig, err := syncer.LoadIgnore(m.Local) ig, err := syncer.LoadIgnoreWith(m.Local, m.Exclude)
if err != nil { if err != nil {
d.logf("ignore %s: %v", m.Local, err) d.logf("ignore %s: %v", m.Local, err)
return return

View file

@ -28,6 +28,36 @@ func absent(path string, d time.Duration) bool {
return true return true
} }
// TestPauseForAutoResumes proves PauseFor pauses immediately and clears the
// pause on its own after the duration, and that a plain Pause cancels a pending
// auto-resume (an explicit indefinite pause must override a scheduled resume).
func TestPauseForAutoResumes(t *testing.T) {
d, err := New(t.TempDir(), config.Daemon{}, "h", t.Logf)
if err != nil {
t.Fatal(err)
}
d.PauseFor(40 * time.Millisecond)
if !d.StateSnapshot().Paused {
t.Fatal("PauseFor should pause immediately")
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) && d.StateSnapshot().Paused {
time.Sleep(10 * time.Millisecond)
}
if d.StateSnapshot().Paused {
t.Fatal("PauseFor did not auto-resume after its duration")
}
// A plain Pause after scheduling an auto-resume must stay paused indefinitely.
d.PauseFor(40 * time.Millisecond)
d.Pause() // cancels the pending 40ms auto-resume
time.Sleep(200 * time.Millisecond)
if !d.StateSnapshot().Paused {
t.Fatal("plain Pause did not cancel the pending auto-resume")
}
}
// TestPauseGatesSyncing is the load-bearing pause test: while paused, a local // 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 // 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 // runMount still synced through the trigger, the "absent while paused" assertion

View file

@ -73,11 +73,12 @@ func Build(root string, ig *ignore.Matcher, guard *secret.Guard) (Manifest, []st
if err != nil { if err != nil {
return err return err
} }
data, err := os.ReadFile(p) // ponytail: whole-file read; stream huge files later f, err := os.Open(p)
if err != nil { if err != nil {
return err return err
} }
cs, err := chunk.Split(data) cs, err := chunk.SplitReader(f) // streams in bounded memory — no whole-file read
f.Close() // explicit (not defer): WalkDir calls this closure per file
if err != nil { if err != nil {
return fmt.Errorf("chunk %s: %w", rel, err) return fmt.Errorf("chunk %s: %w", rel, err)
} }

View file

@ -163,12 +163,21 @@ func splice(c *transport.Client, localM manifest.Manifest, subpath, parent strin
// LoadIgnore compiles root/.devignore (an empty matcher if the file is absent). // LoadIgnore compiles root/.devignore (an empty matcher if the file is absent).
func LoadIgnore(root string) (*ignore.Matcher, error) { func LoadIgnore(root string) (*ignore.Matcher, error) {
b, err := os.ReadFile(filepath.Join(root, ".devignore")) return LoadIgnoreWith(root, nil)
if os.IsNotExist(err) {
return ignore.Compile(nil)
} }
if err != nil {
// LoadIgnoreWith compiles root/.devignore plus extra device-local patterns
// (gitignore syntax) appended after it — so a per-mount --exclude layers on top
// of the shared ignore file with last-match-wins precedence.
func LoadIgnoreWith(root string, extra []string) (*ignore.Matcher, error) {
var lines []string
b, err := os.ReadFile(filepath.Join(root, ".devignore"))
if err != nil && !os.IsNotExist(err) {
return nil, err return nil, err
} }
return ignore.Compile(strings.Split(string(b), "\n")) if err == nil {
lines = strings.Split(string(b), "\n")
}
lines = append(lines, extra...)
return ignore.Compile(lines)
} }

View file

@ -17,6 +17,28 @@ import (
"github.com/shoemoney/devbox/internal/transport" "github.com/shoemoney/devbox/internal/transport"
) )
// TestLoadIgnoreWithLayersExtra proves device-local excludes layer on top of the
// shared .devignore without dropping its rules.
func TestLoadIgnoreWithLayersExtra(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, ".devignore"), []byte("*.log\n"), 0o644); err != nil {
t.Fatal(err)
}
ig, err := LoadIgnoreWith(root, []string{"build/"})
if err != nil {
t.Fatal(err)
}
if !ig.Match("app.log", false) {
t.Error("shared .devignore pattern (*.log) was lost")
}
if !ig.Match("build", true) {
t.Error("device-local exclude (build/) was not applied")
}
if ig.Match("main.go", false) {
t.Error("unrelated path wrongly ignored")
}
}
// joinDevice enrolls a fresh device against srv with a freshly-minted token. // joinDevice enrolls a fresh device against srv with a freshly-minted token.
func joinDevice(t *testing.T, db *meta.DB, baseURL, name string) *transport.Client { func joinDevice(t *testing.T, db *meta.DB, baseURL, name string) *transport.Client {
t.Helper() t.Helper()