From 8c5d576a7226da358c040ae9a268d1633e76835a Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 30 Jun 2026 12:29:02 -0500 Subject: [PATCH] =?UTF-8?q?feat(device):=20--json=20output,=20streaming=20?= =?UTF-8?q?chunker,=20pause=20--for,=20per-mount=20exclude,=20rescan=20kno?= =?UTF-8?q?b=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 `: 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. --- cmd/devbox/control.go | 13 ++++- cmd/devbox/main.go | 98 ++++++++++++++++++++++++++++---- cmd/devbox/main_test.go | 46 +++++++++++++++ internal/chunk/chunk.go | 20 +++++-- internal/chunk/chunk_test.go | 21 +++++++ internal/config/config.go | 10 +++- internal/control/control.go | 13 ++++- internal/control/control_test.go | 33 ++++++++++- internal/control/server.go | 12 +++- internal/daemon/daemon.go | 64 ++++++++++++++++----- internal/daemon/pause_test.go | 30 ++++++++++ internal/manifest/manifest.go | 5 +- internal/syncer/syncer.go | 19 +++++-- internal/syncer/syncer_test.go | 22 +++++++ 14 files changed, 361 insertions(+), 45 deletions(-) diff --git a/cmd/devbox/control.go b/cmd/devbox/control.go index 8245c9c..c94446c 100644 --- a/cmd/devbox/control.go +++ b/cmd/devbox/control.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "os" + "time" "github.com/spf13/cobra" @@ -12,7 +13,8 @@ import ( ) func pauseCmd() *cobra.Command { - return &cobra.Command{ + var forDur time.Duration + cmd := &cobra.Command{ Use: "pause", Short: "⏸️ pause syncing on the running daemon", RunE: func(cmd *cobra.Command, _ []string) error { @@ -20,6 +22,13 @@ func pauseCmd() *cobra.Command { if err != nil { 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 { return daemonHint(err) } @@ -27,6 +36,8 @@ func pauseCmd() *cobra.Command { 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 { diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index d2ba068..fa49172 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -4,7 +4,9 @@ package main import ( "cmp" "context" + "encoding/json" "fmt" + "io" "io/fs" "net/http" "os" @@ -189,6 +191,7 @@ func publishCmd() *cobra.Command { func mountCmd() *cobra.Command { var ro bool + var exclude []string cmd := &cobra.Command{ Use: "mount ", 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 { 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 { return err } c := transport.New(d.Hub) c.SetBearer(d.Bearer) - ig, err := syncer.LoadIgnore(local) + ig, err := syncer.LoadIgnoreWith(local, exclude) if err != nil { 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().StringArrayVar(&exclude, "exclude", nil, "device-local ignore pattern (gitignore syntax; repeatable) layered on .devignore") return cmd } @@ -285,8 +289,16 @@ func upsertMount(mounts []config.Mount, m config.Mount) []config.Mount { 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 { - return &cobra.Command{ + var asJSON bool + cmd := &cobra.Command{ Use: "log ", Short: "πŸ•“ show a share's snapshot history", Args: cobra.ExactArgs(1), @@ -310,6 +322,9 @@ func logCmd() *cobra.Command { return err } out := cmd.OutOrStdout() + if asJSON { + return writeJSON(out, snaps) + } for _, s := range snaps { 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 @@ -317,6 +332,8 @@ func logCmd() *cobra.Command { return nil }, } + cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON") + return cmd } func inviteCmd() *cobra.Command { @@ -446,7 +463,7 @@ func restoreCmd() *cobra.Command { c := transport.New(d.Hub) c.SetBearer(d.Bearer) - ig, err := syncer.LoadIgnore(m.Local) + ig, err := syncer.LoadIgnoreWith(m.Local, m.Exclude) if err != nil { return err } @@ -547,7 +564,8 @@ func ignoreCmd() *cobra.Command { } func conflictsCmd() *cobra.Command { - return &cobra.Command{ + var asJSON bool + cmd := &cobra.Command{ Use: "conflicts", Short: "πŸ’₯ list conflict copies across all mounts", RunE: func(cmd *cobra.Command, _ []string) error { @@ -560,7 +578,11 @@ func conflictsCmd() *cobra.Command { return err } out := cmd.OutOrStdout() - n := 0 + type conflict struct { + Share string `json:"share"` + Path string `json:"path"` + } + found := []conflict{} for _, m := range d.Mounts { _ = filepath.WalkDir(m.Local, func(p string, e fs.DirEntry, err error) error { if err != nil || e.IsDir() { @@ -568,20 +590,27 @@ func conflictsCmd() *cobra.Command { } if strings.Contains(e.Name(), ".conflict-") { rel, _ := filepath.Rel(m.Local, p) - fmt.Fprintf(out, " πŸ’₯ %s/%s\n", m.Share, filepath.ToSlash(rel)) - n++ + found = append(found, conflict{Share: m.Share, Path: filepath.ToSlash(rel)}) } 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") } 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 }, } + cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON") + return cmd } // findMount returns the first configured mount for share. @@ -623,7 +652,7 @@ func deployCmd() *cobra.Command { c := transport.New(d.Hub) c.SetBearer(d.Bearer) - ig, err := syncer.LoadIgnore(m.Local) + ig, err := syncer.LoadIgnoreWith(m.Local, m.Exclude) if err != nil { 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 { - return &cobra.Command{ + var asJSON bool + cmd := &cobra.Command{ Use: "status", Short: "πŸ“Š show device + sync status", RunE: func(cmd *cobra.Command, _ []string) error { @@ -727,6 +775,9 @@ func statusCmd() *cobra.Command { out := cmd.OutOrStdout() id, err := identity.Load(dir) if err != nil { + if asJSON { + return writeJSON(out, statusJSON{Joined: false}) + } fmt.Fprintln(out, "not joined yet β€” run: devbox join ") return nil } @@ -735,6 +786,27 @@ func statusCmd() *cobra.Command { 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: // 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 @@ -780,6 +852,8 @@ func statusCmd() *cobra.Command { return nil }, } + cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON (prefers live daemon state)") + return cmd } func orNone(s string) string { diff --git a/cmd/devbox/main_test.go b/cmd/devbox/main_test.go index 27a61df..223f0c6 100644 --- a/cmd/devbox/main_test.go +++ b/cmd/devbox/main_test.go @@ -1,12 +1,58 @@ package main import ( + "bytes" + "encoding/json" "os" "strconv" "strings" "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 // stale-pidfile recovery. func TestWritePidArbitration(t *testing.T) { diff --git a/internal/chunk/chunk.go b/internal/chunk/chunk.go index ad047bb..41bc799 100644 --- a/internal/chunk/chunk.go +++ b/internal/chunk/chunk.go @@ -46,17 +46,29 @@ type Chunk struct { // 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. // -// ponytail: Split is in-memory β€” it takes the whole []byte and the underlying -// chunker reads from a bytes.Reader over it. Streaming large inputs from an -// io.Reader without buffering the entire payload is the upgrade path. +// Split divides an in-memory buffer. It is a convenience wrapper over +// SplitReader for callers that already hold the whole []byte. func Split(data []byte) ([]Chunk, error) { if len(data) == 0 { 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() defer splitMu.Unlock() - chunker, err := fastcdc.NewChunker(bytes.NewReader(data), fastcdc.Options{ + chunker, err := fastcdc.NewChunker(r, fastcdc.Options{ MinSize: MinSize, AverageSize: AvgSize, MaxSize: MaxSize, diff --git a/internal/chunk/chunk_test.go b/internal/chunk/chunk_test.go index 7cac82b..332e77b 100644 --- a/internal/chunk/chunk_test.go +++ b/internal/chunk/chunk_test.go @@ -4,8 +4,29 @@ import ( "bytes" "math/rand" "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. func seededBlob(seed int64, n int) []byte { r := rand.New(rand.NewSource(seed)) diff --git a/internal/config/config.go b/internal/config/config.go index 325f8bc..8e89049 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -42,6 +42,10 @@ type Mount struct { // 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. 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 @@ -94,11 +98,15 @@ func SaveDaemon(dir string, d Daemon) error { // Settings is config.toml: per-machine tunables (separate from daemon.toml). type Settings 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"` Secrets struct { ExtraPatterns []string `toml:"extra_patterns"` } `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). diff --git a/internal/control/control.go b/internal/control/control.go index 48b7557..cfcf0d5 100644 --- a/internal/control/control.go +++ b/internal/control/control.go @@ -14,6 +14,7 @@ import ( "fmt" "net" "net/http" + "net/url" "path/filepath" "time" ) @@ -46,9 +47,10 @@ type MountState struct { // 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 - Resume() // clear pause + catch up all mounts + 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 @@ -99,6 +101,11 @@ func DialState(dir string) (State, error) { // 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") } diff --git a/internal/control/control_test.go b/internal/control/control_test.go index c8b1da5..0dff994 100644 --- a/internal/control/control_test.go +++ b/internal/control/control_test.go @@ -13,9 +13,10 @@ import ( // fakeDaemon is a minimal Daemon for exercising the control server in isolation. type fakeDaemon struct { - mu sync.Mutex - paused bool - resumes int + mu sync.Mutex + paused bool + resumes int + pauseFor time.Duration } 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() { f.mu.Lock() f.paused = true @@ -109,6 +117,25 @@ func TestRoundTripPauseStateResume(t *testing.T) { } } +// TestPauseForCarriesDuration proves POST /pause?for= 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 // ErrNotRunning when no daemon is listening, so callers can fall back. func TestNoDaemonReturnsNotRunning(t *testing.T) { diff --git a/internal/control/server.go b/internal/control/server.go index b5d5979..a1befe3 100644 --- a/internal/control/server.go +++ b/internal/control/server.go @@ -82,7 +82,17 @@ func (s *Server) handleState(w http.ResponseWriter, _ *http.Request) { _ = 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() w.WriteHeader(http.StatusOK) } diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index cdc4eae..38f0a59 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -22,13 +22,13 @@ import ( "github.com/shoemoney/devbox/pkg/proto" ) -// rescanInterval is the safety-net cadence for re-syncing a mount even when no -// trigger fired. It backstops a watcher that never started (e.g. inotify +// defaultRescanInterval is the safety-net cadence for re-syncing a mount even +// 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: // 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 -// periodic manifest rebuild measurably costly. -const rescanInterval = 60 * time.Second +// Overridable per machine via settings.sync.rescan_seconds (Daemon.rescanInterval) +// β€” a huge tree can lengthen it, a latency-sensitive one can shorten it. +const defaultRescanInterval = 60 * time.Second // Daemon syncs a device's mounts against their hub. type Daemon struct { @@ -37,14 +37,17 @@ type Daemon struct { host string guard *secret.Guard 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) 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) + 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) + 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). @@ -64,9 +67,15 @@ func New(dir string, cfg config.Daemon, host string, logf func(string, ...any)) if logf == nil { logf = log.Printf } + rescan := defaultRescanInterval + if settings.Sync.RescanSeconds > 0 { + rescan = time.Duration(settings.Sync.RescanSeconds) * time.Second + } return &Daemon{ dir: dir, cfg: cfg, host: host, guard: guard, maxBytesPerSec: settings.Transfer.MaxKbps * 1024, + compress: settings.Transfer.Compress, + rescanInterval: rescan, logf: logf, state: state, nudges: map[string]func(){}, 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 // 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 { - 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 { defer w.Close() go func() { @@ -189,9 +198,9 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) { select { case <-ctx.Done(): 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() for { select { @@ -243,14 +252,43 @@ func (d *Daemon) unregister(m config.Mount) { // are drained without effect while paused. func (d *Daemon) Pause() { d.paused.Store(true) + d.clearResumeTimer() // an explicit pause overrides any pending auto-resume 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 // catch-up sync, so edits made while paused converge right away. func (d *Daemon) Resume() { d.paused.Store(false) 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)) for _, n := range d.nudges { nudges = append(nudges, n) @@ -282,7 +320,7 @@ func (d *Daemon) StateSnapshot() control.State { } 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 { d.logf("ignore %s: %v", m.Local, err) return diff --git a/internal/daemon/pause_test.go b/internal/daemon/pause_test.go index 370c41a..066359d 100644 --- a/internal/daemon/pause_test.go +++ b/internal/daemon/pause_test.go @@ -28,6 +28,36 @@ func absent(path string, d time.Duration) bool { 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 // 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 diff --git a/internal/manifest/manifest.go b/internal/manifest/manifest.go index e3f1810..2f577c7 100644 --- a/internal/manifest/manifest.go +++ b/internal/manifest/manifest.go @@ -73,11 +73,12 @@ func Build(root string, ig *ignore.Matcher, guard *secret.Guard) (Manifest, []st if err != nil { return err } - data, err := os.ReadFile(p) // ponytail: whole-file read; stream huge files later + f, err := os.Open(p) if err != nil { 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 { return fmt.Errorf("chunk %s: %w", rel, err) } diff --git a/internal/syncer/syncer.go b/internal/syncer/syncer.go index 9a8c1d4..e25bea6 100644 --- a/internal/syncer/syncer.go +++ b/internal/syncer/syncer.go @@ -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). func LoadIgnore(root string) (*ignore.Matcher, error) { + return LoadIgnoreWith(root, 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 os.IsNotExist(err) { - return ignore.Compile(nil) - } - if err != nil { + if err != nil && !os.IsNotExist(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) } diff --git a/internal/syncer/syncer_test.go b/internal/syncer/syncer_test.go index 868dcf3..e512440 100644 --- a/internal/syncer/syncer_test.go +++ b/internal/syncer/syncer_test.go @@ -17,6 +17,28 @@ import ( "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. func joinDevice(t *testing.T, db *meta.DB, baseURL, name string) *transport.Client { t.Helper()