diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index cad8029..c1fec34 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -37,6 +37,7 @@ func main() { mountCmd(), logCmd(), restoreCmd(), + deployCmd(), startCmd(), statusCmd(), versionCmd(), @@ -360,6 +361,91 @@ func findMount(mounts []config.Mount, share string) (config.Mount, bool) { return config.Mount{}, false } +func deployCmd() *cobra.Command { + return &cobra.Command{ + Use: "deploy ", + Short: "🚀 pin a mount to a specific snapshot (apply without pushing — blue/green)", + Long: "deploy rewrites a mount's local directory to a specific snapshot WITHOUT pushing a\n" + + "new head — it pins the mount at that version (history untouched), so the daemon\n" + + "won't live-advance it. Ideal for blue/green deploys of /var/www boxes. Re-mount to\n" + + "resume live sync. Snapshot ids come from 'devbox log '.", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + share, snapshot := args[0], args[1] + dir, err := config.Dir() + if err != nil { + return err + } + d, err := config.LoadDaemon(dir) + if err != nil { + return err + } + if d.Hub == "" || d.Bearer == "" { + return fmt.Errorf("not joined — run: devbox join ") + } + m, ok := findDeployMount(d.Mounts, share) + if !ok { + return fmt.Errorf("no mount for share %q — mount it first: devbox mount %s --ro", share, share) + } + + c := transport.New(d.Hub) + c.SetBearer(d.Bearer) + ig, err := syncer.LoadIgnore(m.Local) + if err != nil { + return err + } + guard, err := secret.New(nil) + if err != nil { + return err + } + res, err := syncer.Deploy(c, m.Local, m.Subpath, snapshot, ig, guard) + if err != nil { + return err + } + + // Pin the mount so the daemon holds it at this snapshot (re-mount clears it). + m.Pinned = true + d.Mounts = upsertMount(d.Mounts, m) + if err := config.SaveDaemon(dir, d); err != nil { + return err + } + st, err := config.LoadState(dir) + if err != nil { + return err + } + st[share+"\x00"+m.Subpath+"\x00"+m.Local] = res.Snapshot + if err := config.SaveState(dir, st); err != nil { + return err + } + + out := cmd.OutOrStdout() + fmt.Fprintf(out, "🚀 deployed %s -> snapshot %s (%d files) at %s [pinned]\n", share, short(res.Snapshot), res.Written, m.Local) + if !m.ReadOnly { + fmt.Fprintln(out, "⚠️ this is a read-write mount; local edits here are now isolated until you re-mount") + } + return nil + }, + } +} + +// findDeployMount returns the read-only mount for share if one exists, else the +// first mount of any kind (deploy is intended for a --ro mount). +func findDeployMount(mounts []config.Mount, share string) (config.Mount, bool) { + first, ok := config.Mount{}, false + for _, m := range mounts { + if m.Share != share { + continue + } + if m.ReadOnly { + return m, true + } + if !ok { + first, ok = m, true + } + } + return first, ok +} + func startCmd() *cobra.Command { return &cobra.Command{ Use: "start", @@ -419,6 +505,9 @@ func statusCmd() *cobra.Command { if m.ReadOnly { mode = "ro" } + if m.Pinned { + mode += ",pinned" + } fmt.Fprintf(out, " - %s/%s -> %s [%s]\n", m.Share, m.Subpath, m.Local, mode) } return nil diff --git a/internal/config/config.go b/internal/config/config.go index 94124f2..325f8bc 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -39,6 +39,9 @@ type Mount struct { Local string `toml:"local"` Hub string `toml:"hub"` ReadOnly bool `toml:"readonly,omitempty"` + // 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"` } // Daemon is daemon.toml: which hub this device joined (with its bearer token and diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 5a9b69d..f706099 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -90,6 +90,12 @@ func (d *Daemon) setBase(m config.Mount, base string) { } func (d *Daemon) runMount(ctx context.Context, m config.Mount) { + if m.Pinned { + // Deployed to a fixed snapshot; never live-advance it. Held until re-mount. + d.logf("📌 %s pinned to %s — not live-syncing", m.Share, d.getBase(m)) + <-ctx.Done() + return + } c := transport.New(m.Hub) c.SetBearer(d.cfg.Bearer) if d.maxBytesPerSec > 0 { diff --git a/internal/syncer/deploy_test.go b/internal/syncer/deploy_test.go new file mode 100644 index 0000000..09204a8 --- /dev/null +++ b/internal/syncer/deploy_test.go @@ -0,0 +1,87 @@ +package syncer + +import ( + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "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/secret" +) + +// TestDeployPinsWithoutPushing pushes v1 then v2, then deploys v1 into a separate +// directory. Unlike Restore, Deploy must NOT advance the hub head: the deploy +// target ends up at v1's content while the share head stays at v2. +func TestDeployPinsWithoutPushing(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() + + guard, _ := secret.New(nil) + ig, _ := LoadIgnore(t.TempDir()) + + c := joinDevice(t, db, srv.URL, "deployer") + if err := c.Publish("app"); err != nil { + t.Fatal(err) + } + + // Author the share on one tree: v1, then v2. + src := t.TempDir() + writeFile(t, src, "index.html", "v1\n") + writeFile(t, src, "app.js", "console.log(1)\n") + snap1, err := Push(c, src, "app", "", ig, guard, "", nil) + if err != nil { + t.Fatalf("push v1: %v", err) + } + writeFile(t, src, "index.html", "v2\n") + writeFile(t, src, "new.css", "body{}\n") + snap2, err := Push(c, src, "app", "", ig, guard, snap1.Head, nil) + if err != nil { + t.Fatalf("push v2: %v", err) + } + + // Deploy v1 into a fresh /var/www-style target that already has a stray file. + target := t.TempDir() + writeFile(t, target, "stale.txt", "leftover\n") + res, err := Deploy(c, target, "", snap1.Snapshot, ig, guard) + if err != nil { + t.Fatalf("deploy: %v", err) + } + + // Target matches v1 exactly: v1 files present, v2-only and stray files gone. + if got := readFile(t, target, "index.html"); got != "v1\n" { + t.Fatalf("index.html = %q, want v1", got) + } + if got := readFile(t, target, "app.js"); got != "console.log(1)\n" { + t.Fatalf("app.js = %q, want v1", got) + } + if _, err := os.Stat(filepath.Join(target, "new.css")); !os.IsNotExist(err) { + t.Fatal("new.css (v2-only) should be absent in a v1 deploy") + } + if _, err := os.Stat(filepath.Join(target, "stale.txt")); !os.IsNotExist(err) { + t.Fatal("stray stale.txt should be deleted to match the snapshot") + } + if res.Snapshot != snap1.Snapshot { + t.Fatalf("deploy snapshot = %q, want v1 %q", res.Snapshot, snap1.Snapshot) + } + + // The crux: deploy never pushes — the hub head is still v2. + head, err := c.Head("app") + if err != nil { + t.Fatal(err) + } + if head != snap2.Snapshot { + t.Fatalf("hub head after deploy = %q, want unchanged v2 %q", head, snap2.Snapshot) + } +} diff --git a/internal/syncer/pull.go b/internal/syncer/pull.go index 7784d24..5aa4315 100644 --- a/internal/syncer/pull.go +++ b/internal/syncer/pull.go @@ -152,46 +152,77 @@ func Pull(c *transport.Client, root, share, subpath, base, host string, now int6 // snapshot doesn't contain is deleted. A bad onlyPath (not in the snapshot) errors // without touching the tree. func Restore(c *transport.Client, root, share, subpath, snapshot, onlyPath, host string, now int64, ig *ignore.Matcher, guard *secret.Guard, hk *hooks.Runner) (Result, error) { - full, err := fetchManifest(c, snapshot) + if _, err := applySnapshot(c, root, subpath, snapshot, onlyPath, ig, guard); err != nil { + return Result{}, err + } + head, err := c.Head(share) if err != nil { return Result{}, err } + return Push(c, root, share, subpath, ig, guard, head, hk) +} + +// DeployResult summarizes pinning a mount to a snapshot. +type DeployResult struct { + Snapshot string // the snapshot now applied (== its manifest blob hash) + Written int // files written from the snapshot +} + +// Deploy rewrites the mounted subtree to match a snapshot WITHOUT pushing — it +// pins a (typically read-only) mount to a specific version, e.g. blue/green +// deploys of /var/www. Unlike Restore it creates no new head: the snapshot stays +// exactly as-is on the hub and history is untouched. The caller pins the mount +// (config.Mount.Pinned) so the daemon won't live-advance it back to head. +func Deploy(c *transport.Client, root, subpath, snapshot string, ig *ignore.Matcher, guard *secret.Guard) (DeployResult, error) { + n, err := applySnapshot(c, root, subpath, snapshot, "", ig, guard) + if err != nil { + return DeployResult{}, err + } + return DeployResult{Snapshot: snapshot, Written: n}, nil +} + +// applySnapshot rewrites root to match a snapshot's manifest (filtered+stripped +// to subpath): writes every entry and, when onlyPath is empty, deletes any local +// path the snapshot doesn't contain. With onlyPath set, only that one entry is +// written (no deletes). Returns the number of entries written. A bad onlyPath +// (not in the snapshot) errors without touching the tree. +func applySnapshot(c *transport.Client, root, subpath, snapshot, onlyPath string, ig *ignore.Matcher, guard *secret.Guard) (int, error) { + full, err := fetchManifest(c, snapshot) + if err != nil { + return 0, err + } target := filterStrip(full, subpath) idx := indexEntries(target) if onlyPath != "" { e, ok := idx[onlyPath] if !ok { - return Result{}, fmt.Errorf("restore: path %q not in snapshot %s", onlyPath, snapshot) + return 0, fmt.Errorf("path %q not in snapshot %s", onlyPath, snapshot) } if _, err := writeEntry(c, root, e); err != nil { - return Result{}, err - } - } else { - for _, e := range target.Entries { - if _, err := writeEntry(c, root, e); err != nil { - return Result{}, err - } - } - // Delete anything present locally but absent from the snapshot. - local, _, err := manifest.Build(root, ig, guard) - if err != nil { - return Result{}, err - } - for _, e := range local.Entries { - if _, keep := idx[e.Path]; !keep { - if err := deleteFile(root, e.Path); err != nil { - return Result{}, err - } - } + return 0, err } + return 1, nil } - head, err := c.Head(share) - if err != nil { - return Result{}, err + for _, e := range target.Entries { + if _, err := writeEntry(c, root, e); err != nil { + return 0, err + } } - return Push(c, root, share, subpath, ig, guard, head, hk) + // Delete anything present locally but absent from the snapshot. + local, _, err := manifest.Build(root, ig, guard) + if err != nil { + return 0, err + } + for _, e := range local.Entries { + if _, keep := idx[e.Path]; !keep { + if err := deleteFile(root, e.Path); err != nil { + return 0, err + } + } + } + return len(target.Entries), nil } // Sync brings a mount into agreement with the hub: pull+merge to head, then push