feat(M6): versioning — log, restore, hub gc 🕰️
- devbox log <share>: hub GET /v1/log (meta.SnapshotLog newest-first), client.Log - devbox restore <share> <snapshot> [path]: snapshot id == manifest blob hash, so syncer.Restore fetches the old manifest, rewrites the file(s) (+deletes extras for a whole-tree restore), and pushes -> itself a new reversible snapshot - devbox-hub gc [--keep N]: prune snapshots beyond the newest N (never the head), decrement chunk refcounts, sweep refcount<=0 chunks + manifest blobs from the store - meta: SnapshotLog, ShareNames, DeletableSnapshots (rowid tiebreaker), DeleteSnapshot (tx + refcount--), UnreferencedChunks, DeleteChunkRow - tests: log order/limit, deletable keeps head+newest, refcount decrement, whole-tree + single-path restore, gc end-to-end (old unique chunks freed, head intact)
This commit is contained in:
parent
c17a5da9c5
commit
6d0453d8e3
11 changed files with 909 additions and 0 deletions
183
cmd/devbox-hub/gc_test.go
Normal file
183
cmd/devbox-hub/gc_test.go
Normal file
|
|
@ -0,0 +1,183 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/rand"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
"git.shoemoney.ai/shoemoney/devbox/internal/syncer"
|
||||||
|
"git.shoemoney.ai/shoemoney/devbox/internal/transport"
|
||||||
|
)
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, root, rel, content string) {
|
||||||
|
t.Helper()
|
||||||
|
p := filepath.Join(root, filepath.FromSlash(rel))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestGCDropsOldUniqueChunks pushes two snapshots, gc's with keep=1, and asserts
|
||||||
|
// the pruned snapshot's UNIQUE chunk blob is gone while a chunk still referenced
|
||||||
|
// by the surviving head remains — and the head itself is untouched.
|
||||||
|
func TestGCDropsOldUniqueChunks(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()
|
||||||
|
|
||||||
|
// Enroll a device.
|
||||||
|
if err := db.CreateToken(hub.HashToken("tok"), time.Now().Unix()+3600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c := transport.New(srv.URL)
|
||||||
|
pub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := c.Join("tok", "dev", pub); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := c.Publish("proj"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
guard, _ := secret.New(nil)
|
||||||
|
root := t.TempDir()
|
||||||
|
ig, _ := syncer.LoadIgnore(root)
|
||||||
|
|
||||||
|
// v1: shared.txt (kept across versions) + only-v1.txt (unique to snap1).
|
||||||
|
writeFile(t, root, "shared.txt", "stable content\n")
|
||||||
|
writeFile(t, root, "only-v1.txt", "this file vanishes in v2\n")
|
||||||
|
v1, err := syncer.Push(c, root, "proj", "", ig, guard, "", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("push v1: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// v2: shared.txt unchanged, only-v1.txt deleted, only-v2.txt added.
|
||||||
|
if err := os.Remove(filepath.Join(root, "only-v1.txt")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeFile(t, root, "only-v2.txt", "fresh in v2\n")
|
||||||
|
v2, err := syncer.Push(c, root, "proj", "", ig, guard, v1.Head, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("push v2: %v", err)
|
||||||
|
}
|
||||||
|
if v2.Snapshot == v1.Snapshot {
|
||||||
|
t.Fatal("v2 must differ from v1")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture chunk hashes per snapshot before gc.
|
||||||
|
v1Chunks := manifestChunksOrFail(t, store, v1.Snapshot)
|
||||||
|
v2Chunks := manifestChunksOrFail(t, store, v2.Snapshot)
|
||||||
|
uniqueV1 := diff(v1Chunks, v2Chunks) // chunks only v1 referenced
|
||||||
|
shared := intersect(v1Chunks, v2Chunks)
|
||||||
|
if len(uniqueV1) == 0 {
|
||||||
|
t.Fatal("test setup: expected at least one v1-only chunk")
|
||||||
|
}
|
||||||
|
if len(shared) == 0 {
|
||||||
|
t.Fatal("test setup: expected at least one shared chunk")
|
||||||
|
}
|
||||||
|
|
||||||
|
// gc keeping only the newest snapshot (v2 == head): v1 is pruned.
|
||||||
|
snaps, chunks, err := runGC(db, store, 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("gc: %v", err)
|
||||||
|
}
|
||||||
|
if snaps != 1 {
|
||||||
|
t.Fatalf("gc removed %d snapshots, want 1", snaps)
|
||||||
|
}
|
||||||
|
if chunks != len(uniqueV1) {
|
||||||
|
t.Fatalf("gc freed %d chunks, want %d (v1-only)", chunks, len(uniqueV1))
|
||||||
|
}
|
||||||
|
|
||||||
|
// v1's unique chunk blobs are gone.
|
||||||
|
for _, h := range uniqueV1 {
|
||||||
|
if has, _ := store.Has(h); has {
|
||||||
|
t.Fatalf("unique v1 chunk %s should have been deleted", h)
|
||||||
|
}
|
||||||
|
if rc, _ := db.ChunkRefcount(h); rc != 0 {
|
||||||
|
t.Fatalf("unique v1 chunk %s refcount = %d, want 0/gone", h, rc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Shared chunks survive (still referenced by the head).
|
||||||
|
for _, h := range shared {
|
||||||
|
if has, _ := store.Has(h); !has {
|
||||||
|
t.Fatalf("shared chunk %s must survive gc", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// v1's manifest blob is gone; v2's (the head's) survives.
|
||||||
|
if has, _ := store.Has(v1.Snapshot); has {
|
||||||
|
t.Fatal("pruned v1 manifest blob should be deleted")
|
||||||
|
}
|
||||||
|
if has, _ := store.Has(v2.Snapshot); !has {
|
||||||
|
t.Fatal("head v2 manifest blob must survive")
|
||||||
|
}
|
||||||
|
// The head is intact.
|
||||||
|
if head, _, _ := db.ShareHead("proj"); head != v2.Snapshot {
|
||||||
|
t.Fatalf("head = %q after gc, want %q", head, v2.Snapshot)
|
||||||
|
}
|
||||||
|
// And v2's chunks are all still present.
|
||||||
|
for _, h := range v2Chunks {
|
||||||
|
if has, _ := store.Has(h); !has {
|
||||||
|
t.Fatalf("head chunk %s must survive gc", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func manifestChunksOrFail(t *testing.T, store blobstore.Store, id string) []string {
|
||||||
|
t.Helper()
|
||||||
|
hs, err := manifestChunks(store, id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("manifestChunks(%s): %v", id, err)
|
||||||
|
}
|
||||||
|
return hs
|
||||||
|
}
|
||||||
|
|
||||||
|
// diff returns elements of a not present in b.
|
||||||
|
func diff(a, b []string) []string {
|
||||||
|
set := map[string]bool{}
|
||||||
|
for _, x := range b {
|
||||||
|
set[x] = true
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, x := range a {
|
||||||
|
if !set[x] {
|
||||||
|
out = append(out, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// intersect returns elements present in both a and b.
|
||||||
|
func intersect(a, b []string) []string {
|
||||||
|
set := map[string]bool{}
|
||||||
|
for _, x := range b {
|
||||||
|
set[x] = true
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, x := range a {
|
||||||
|
if set[x] {
|
||||||
|
out = append(out, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
@ -15,6 +15,7 @@ import (
|
||||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub"
|
"git.shoemoney.ai/shoemoney/devbox/internal/hub"
|
||||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore"
|
"git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore"
|
||||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/meta"
|
"git.shoemoney.ai/shoemoney/devbox/internal/hub/meta"
|
||||||
|
"git.shoemoney.ai/shoemoney/devbox/internal/manifest"
|
||||||
)
|
)
|
||||||
|
|
||||||
var version = "0.0.0-dev"
|
var version = "0.0.0-dev"
|
||||||
|
|
@ -36,6 +37,7 @@ func main() {
|
||||||
tokenCmd(),
|
tokenCmd(),
|
||||||
readonlyCmd(),
|
readonlyCmd(),
|
||||||
revokeCmd(),
|
revokeCmd(),
|
||||||
|
gcCmd(),
|
||||||
)
|
)
|
||||||
if err := root.Execute(); err != nil {
|
if err := root.Execute(); err != nil {
|
||||||
fmt.Fprintln(os.Stderr, "error:", err)
|
fmt.Fprintln(os.Stderr, "error:", err)
|
||||||
|
|
@ -155,6 +157,103 @@ func revokeCmd() *cobra.Command {
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func gcCmd() *cobra.Command {
|
||||||
|
var data string
|
||||||
|
var keep int
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "gc",
|
||||||
|
Short: "🧹 prune old snapshots and unreferenced chunks",
|
||||||
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
|
db, err := openDB(data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
store, err := blobstore.NewDisk(filepath.Join(data, "blobs"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
snaps, chunks, err := runGC(db, store, keep)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Fprintf(cmd.OutOrStdout(), "🧹 gc: removed %d snapshots, %d chunks (freed)\n", snaps, chunks)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||||
|
cmd.Flags().IntVar(&keep, "keep", 10, "snapshots to keep per share (newest)")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// runGC prunes deletable snapshots (keeping the head + `keep` newest per share),
|
||||||
|
// then deletes any chunk that lost its last reference. It returns how many
|
||||||
|
// snapshots and chunks were removed. Deleting an already-absent blob is fine —
|
||||||
|
// the metadata is the source of truth.
|
||||||
|
func runGC(db *meta.DB, store blobstore.Store, keep int) (snaps, chunks int, err error) {
|
||||||
|
shares, err := db.ShareNames()
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
for _, share := range shares {
|
||||||
|
ids, err := db.DeletableSnapshots(share, keep)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
for _, id := range ids {
|
||||||
|
hashes, err := manifestChunks(store, id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
if err := db.DeleteSnapshot(id, hashes); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
if err := store.Delete(id); err != nil && err != blobstore.ErrNotFound {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
snaps++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unref, err := db.UnreferencedChunks()
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
for _, h := range unref {
|
||||||
|
if err := store.Delete(h); err != nil && err != blobstore.ErrNotFound {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
if err := db.DeleteChunkRow(h); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return snaps, len(unref), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// manifestChunks returns the distinct chunk hashes referenced by the snapshot
|
||||||
|
// whose id is its manifest blob key.
|
||||||
|
func manifestChunks(store blobstore.Store, snapshotID string) ([]string, error) {
|
||||||
|
b, err := store.Get(snapshotID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
m, err := manifest.Unmarshal(b)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var hashes []string
|
||||||
|
for _, e := range m.Entries {
|
||||||
|
for _, h := range e.Chunks {
|
||||||
|
if !seen[h] {
|
||||||
|
seen[h] = true
|
||||||
|
hashes = append(hashes, h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hashes, nil
|
||||||
|
}
|
||||||
|
|
||||||
func randHex(n int) (string, error) {
|
func randHex(n int) (string, error) {
|
||||||
b := make([]byte, n)
|
b := make([]byte, n)
|
||||||
if _, err := rand.Read(b); err != nil {
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,8 @@ func main() {
|
||||||
joinCmd(),
|
joinCmd(),
|
||||||
publishCmd(),
|
publishCmd(),
|
||||||
mountCmd(),
|
mountCmd(),
|
||||||
|
logCmd(),
|
||||||
|
restoreCmd(),
|
||||||
startCmd(),
|
startCmd(),
|
||||||
statusCmd(),
|
statusCmd(),
|
||||||
versionCmd(),
|
versionCmd(),
|
||||||
|
|
@ -251,6 +253,113 @@ func upsertMount(mounts []config.Mount, m config.Mount) []config.Mount {
|
||||||
return append(mounts, m)
|
return append(mounts, m)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func logCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "log <share>",
|
||||||
|
Short: "🕓 show a share's snapshot history",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
share := args[0]
|
||||||
|
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 <hub> <token>")
|
||||||
|
}
|
||||||
|
c := transport.New(d.Hub)
|
||||||
|
c.SetBearer(d.Bearer)
|
||||||
|
snaps, err := c.Log(share)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out := cmd.OutOrStdout()
|
||||||
|
for _, s := range snaps {
|
||||||
|
ts := time.Unix(s.CreatedAt, 0).Format("2006-01-02 15:04:05")
|
||||||
|
fmt.Fprintf(out, "%s %s %s\n", short(s.ID), ts, s.Device)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func restoreCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "restore <share> <snapshot> [path]",
|
||||||
|
Short: "↩️ restore a share (or one path) to an older snapshot",
|
||||||
|
Args: cobra.RangeArgs(2, 3),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
share, snapshot := args[0], args[1]
|
||||||
|
var onlyPath string
|
||||||
|
if len(args) == 3 {
|
||||||
|
onlyPath = args[2]
|
||||||
|
}
|
||||||
|
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 <hub> <token>")
|
||||||
|
}
|
||||||
|
m, ok := findMount(d.Mounts, share)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("no mount for share %q — mount it first", 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
|
||||||
|
}
|
||||||
|
host, _ := os.Hostname()
|
||||||
|
res, err := syncer.Restore(c, m.Local, share, m.Subpath, snapshot, onlyPath, host, time.Now().UnixNano(), ig, guard, nil)
|
||||||
|
if 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()
|
||||||
|
what := share
|
||||||
|
if onlyPath != "" {
|
||||||
|
what = share + "/" + onlyPath
|
||||||
|
}
|
||||||
|
fmt.Fprintf(out, "↩️ restored %s -> snapshot %s\n", what, short(res.Snapshot))
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// findMount returns the first configured mount for share.
|
||||||
|
func findMount(mounts []config.Mount, share string) (config.Mount, bool) {
|
||||||
|
for _, m := range mounts {
|
||||||
|
if m.Share == share {
|
||||||
|
return m, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return config.Mount{}, false
|
||||||
|
}
|
||||||
|
|
||||||
func startCmd() *cobra.Command {
|
func startCmd() *cobra.Command {
|
||||||
return &cobra.Command{
|
return &cobra.Command{
|
||||||
Use: "start",
|
Use: "start",
|
||||||
|
|
|
||||||
|
|
@ -283,6 +283,128 @@ func (d *DB) ChunkRefcount(hash string) (int, error) {
|
||||||
return rc, err
|
return rc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- history & gc -------------------------------------------------------- //
|
||||||
|
|
||||||
|
// SnapInfo is one entry in a share's snapshot history.
|
||||||
|
type SnapInfo struct {
|
||||||
|
ID string
|
||||||
|
Parent string
|
||||||
|
Device string
|
||||||
|
CreatedAt int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// SnapshotLog returns a share's snapshots newest-first, capped at limit.
|
||||||
|
func (d *DB) SnapshotLog(share string, limit int) ([]SnapInfo, error) {
|
||||||
|
rows, err := d.sql.Query(
|
||||||
|
`SELECT id, COALESCE(parent_id,''), device_id, created_at
|
||||||
|
FROM snapshots WHERE share=? ORDER BY created_at DESC, rowid DESC LIMIT ?`,
|
||||||
|
share, limit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []SnapInfo
|
||||||
|
for rows.Next() {
|
||||||
|
var s SnapInfo
|
||||||
|
if err := rows.Scan(&s.ID, &s.Parent, &s.Device, &s.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShareNames lists every share name.
|
||||||
|
func (d *DB) ShareNames() ([]string, error) {
|
||||||
|
rows, err := d.sql.Query(`SELECT name FROM shares`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []string
|
||||||
|
for rows.Next() {
|
||||||
|
var n string
|
||||||
|
if err := rows.Scan(&n); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, n)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeletableSnapshots returns the snapshot ids GC may prune for a share: every
|
||||||
|
// snapshot except the current head and the `keep` most recent (by created_at).
|
||||||
|
// The kept set and the head can overlap; either way they are never returned.
|
||||||
|
func (d *DB) DeletableSnapshots(share string, keep int) ([]string, error) {
|
||||||
|
head, _, err := d.ShareHead(share)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rows, err := d.sql.Query(
|
||||||
|
`SELECT id FROM snapshots WHERE share=? ORDER BY created_at DESC, rowid DESC`, share)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var del []string
|
||||||
|
for i := 0; rows.Next(); i++ {
|
||||||
|
var id string
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if i < keep || id == head {
|
||||||
|
continue // protected: within the keep window or the live head
|
||||||
|
}
|
||||||
|
del = append(del, id)
|
||||||
|
}
|
||||||
|
return del, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteSnapshot removes a snapshot row and decrements the refcount of each
|
||||||
|
// distinct chunk hash it referenced, all in one transaction. The caller derives
|
||||||
|
// chunkHashes from the snapshot's manifest (distinct, as AddSnapshot counted them).
|
||||||
|
func (d *DB) DeleteSnapshot(id string, chunkHashes []string) error {
|
||||||
|
tx, err := d.sql.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err := tx.Exec(`DELETE FROM snapshots WHERE id=?`, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, h := range chunkHashes {
|
||||||
|
if _, err := tx.Exec(`UPDATE chunks SET refcount=refcount-1 WHERE hash=?`, h); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnreferencedChunks lists chunk hashes whose refcount has dropped to zero (or
|
||||||
|
// below): their bytes are no longer reachable and the GC may delete them.
|
||||||
|
func (d *DB) UnreferencedChunks() ([]string, error) {
|
||||||
|
rows, err := d.sql.Query(`SELECT hash FROM chunks WHERE refcount<=0`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []string
|
||||||
|
for rows.Next() {
|
||||||
|
var h string
|
||||||
|
if err := rows.Scan(&h); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, h)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteChunkRow removes a chunk's metadata row (after its blob is gone).
|
||||||
|
func (d *DB) DeleteChunkRow(hash string) error {
|
||||||
|
_, err := d.sql.Exec(`DELETE FROM chunks WHERE hash=?`, hash)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
func nullable(v int64) any {
|
func nullable(v int64) any {
|
||||||
if v == 0 {
|
if v == 0 {
|
||||||
return nil
|
return nil
|
||||||
|
|
|
||||||
|
|
@ -122,3 +122,146 @@ func TestSharesSnapshotsRefcounts(t *testing.T) {
|
||||||
t.Fatalf("head = %q after re-add, want snap1 (revert)", head)
|
t.Fatalf("head = %q after re-add, want snap1 (revert)", head)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedSnaps creates a share and a chain of snapshots with ascending timestamps.
|
||||||
|
func seedSnaps(t *testing.T, db *DB) {
|
||||||
|
t.Helper()
|
||||||
|
if err := db.CreateShare("proj", "dev1", 1); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
snaps := []struct {
|
||||||
|
id, parent string
|
||||||
|
at int64
|
||||||
|
chunks []ChunkRef
|
||||||
|
}{
|
||||||
|
{"s1", "", 10, []ChunkRef{{"h1", 5}, {"h2", 6}}}, // h1, h2
|
||||||
|
{"s2", "s1", 20, []ChunkRef{{"h1", 5}, {"h3", 7}}}, // shares h1, adds h3
|
||||||
|
{"s3", "s2", 30, []ChunkRef{{"h1", 5}, {"h4", 8}}}, // shares h1, adds h4 (head)
|
||||||
|
}
|
||||||
|
for _, s := range snaps {
|
||||||
|
if err := db.AddSnapshot(Snapshot{ID: s.id, Share: "proj", ParentID: s.parent, DeviceID: "dev1", ManifestHash: s.id, CreatedAt: s.at}, s.chunks); err != nil {
|
||||||
|
t.Fatalf("AddSnapshot %s: %v", s.id, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSnapshotLogNewestFirst(t *testing.T) {
|
||||||
|
db := open(t)
|
||||||
|
seedSnaps(t, db)
|
||||||
|
|
||||||
|
log, err := db.SnapshotLog("proj", 100)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
wantIDs := []string{"s3", "s2", "s1"}
|
||||||
|
if len(log) != len(wantIDs) {
|
||||||
|
t.Fatalf("log len = %d, want %d", len(log), len(wantIDs))
|
||||||
|
}
|
||||||
|
for i, want := range wantIDs {
|
||||||
|
if log[i].ID != want {
|
||||||
|
t.Fatalf("log[%d].ID = %q, want %q (newest-first)", i, log[i].ID, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if log[0].Parent != "s2" || log[2].Parent != "" {
|
||||||
|
t.Fatalf("parents wrong: %q, %q", log[0].Parent, log[2].Parent)
|
||||||
|
}
|
||||||
|
if log[0].Device != "dev1" || log[0].CreatedAt != 30 {
|
||||||
|
t.Fatalf("head meta = %+v", log[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// limit caps the result.
|
||||||
|
if got, _ := db.SnapshotLog("proj", 2); len(got) != 2 || got[0].ID != "s3" {
|
||||||
|
t.Fatalf("limited log = %+v, want first 2 newest", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeletableSnapshotsKeepsHeadAndNewest(t *testing.T) {
|
||||||
|
db := open(t)
|
||||||
|
seedSnaps(t, db) // head = s3
|
||||||
|
|
||||||
|
// keep=1 protects the newest (s3) which is also the head; s1, s2 are deletable.
|
||||||
|
del, err := db.DeletableSnapshots("proj", 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(del) != 2 || del[0] != "s2" || del[1] != "s1" {
|
||||||
|
t.Fatalf("deletable(keep=1) = %v, want [s2 s1]", del)
|
||||||
|
}
|
||||||
|
|
||||||
|
// keep=2 protects s3 + s2; only s1 deletable.
|
||||||
|
if del, _ := db.DeletableSnapshots("proj", 2); len(del) != 1 || del[0] != "s1" {
|
||||||
|
t.Fatalf("deletable(keep=2) = %v, want [s1]", del)
|
||||||
|
}
|
||||||
|
|
||||||
|
// keep >= count: nothing deletable.
|
||||||
|
if del, _ := db.DeletableSnapshots("proj", 10); len(del) != 0 {
|
||||||
|
t.Fatalf("deletable(keep=10) = %v, want []", del)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Even keep=0 must never delete the head.
|
||||||
|
del0, _ := db.DeletableSnapshots("proj", 0)
|
||||||
|
for _, id := range del0 {
|
||||||
|
if id == "s3" {
|
||||||
|
t.Fatal("keep=0 must still protect the head (s3)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(del0) != 2 {
|
||||||
|
t.Fatalf("deletable(keep=0) = %v, want s1+s2 (head s3 protected)", del0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteSnapshotDecrementsRefcounts(t *testing.T) {
|
||||||
|
db := open(t)
|
||||||
|
seedSnaps(t, db)
|
||||||
|
|
||||||
|
// Before: h1 referenced by s1,s2,s3 (rc=3); h2 only by s1 (rc=1).
|
||||||
|
if rc, _ := db.ChunkRefcount("h1"); rc != 3 {
|
||||||
|
t.Fatalf("h1 rc = %d, want 3", rc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete s1, which referenced h1 and h2.
|
||||||
|
if err := db.DeleteSnapshot("s1", []string{"h1", "h2"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rc, _ := db.ChunkRefcount("h1"); rc != 2 {
|
||||||
|
t.Fatalf("h1 rc after delete = %d, want 2", rc)
|
||||||
|
}
|
||||||
|
if rc, _ := db.ChunkRefcount("h2"); rc != 0 {
|
||||||
|
t.Fatalf("h2 rc after delete = %d, want 0", rc)
|
||||||
|
}
|
||||||
|
// The snapshot row is gone.
|
||||||
|
if log, _ := db.SnapshotLog("proj", 100); len(log) != 2 {
|
||||||
|
t.Fatalf("after delete log len = %d, want 2", len(log))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnreferencedChunks(t *testing.T) {
|
||||||
|
db := open(t)
|
||||||
|
seedSnaps(t, db)
|
||||||
|
|
||||||
|
if got, _ := db.UnreferencedChunks(); len(got) != 0 {
|
||||||
|
t.Fatalf("nothing should be unreferenced yet, got %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drop s1: h2 falls to 0 and becomes collectable; h1 still has s2,s3.
|
||||||
|
if err := db.DeleteSnapshot("s1", []string{"h1", "h2"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
un, err := db.UnreferencedChunks()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(un) != 1 || un[0] != "h2" {
|
||||||
|
t.Fatalf("unreferenced = %v, want [h2]", un)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.DeleteChunkRow("h2"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rc, _ := db.ChunkRefcount("h2"); rc != 0 {
|
||||||
|
t.Fatalf("h2 should be gone, refcount lookup = %d", rc)
|
||||||
|
}
|
||||||
|
if got, _ := db.UnreferencedChunks(); len(got) != 0 {
|
||||||
|
t.Fatalf("after row delete, unreferenced = %v, want []", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -59,6 +59,7 @@ func (s *Server) Handler() http.Handler {
|
||||||
mux.HandleFunc("GET "+proto.PathBlob+"{hash}", s.auth(s.handleGetBlob))
|
mux.HandleFunc("GET "+proto.PathBlob+"{hash}", s.auth(s.handleGetBlob))
|
||||||
mux.HandleFunc("POST "+proto.PathPush, s.auth(s.handlePush))
|
mux.HandleFunc("POST "+proto.PathPush, s.auth(s.handlePush))
|
||||||
mux.HandleFunc("GET "+proto.PathHead, s.auth(s.handleHead))
|
mux.HandleFunc("GET "+proto.PathHead, s.auth(s.handleHead))
|
||||||
|
mux.HandleFunc("GET "+proto.PathLog, s.auth(s.handleLog))
|
||||||
mux.HandleFunc("GET "+proto.PathEvents, s.auth(s.handleEvents))
|
mux.HandleFunc("GET "+proto.PathEvents, s.auth(s.handleEvents))
|
||||||
mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics)
|
mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics)
|
||||||
return mux
|
return mux
|
||||||
|
|
@ -271,6 +272,19 @@ func (s *Server) handleHead(w http.ResponseWriter, r *http.Request, _ string) {
|
||||||
writeJSON(w, http.StatusOK, proto.HeadResponse{Head: head})
|
writeJSON(w, http.StatusOK, proto.HeadResponse{Head: head})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleLog(w http.ResponseWriter, r *http.Request, _ string) {
|
||||||
|
snaps, err := s.db.SnapshotLog(r.URL.Query().Get("share"), 100)
|
||||||
|
if err != nil {
|
||||||
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := make([]proto.SnapshotInfo, len(snaps))
|
||||||
|
for i, s := range snaps {
|
||||||
|
out[i] = proto.SnapshotInfo{ID: s.ID, Parent: s.Parent, Device: s.Device, CreatedAt: s.CreatedAt}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, proto.LogResponse{Snapshots: out})
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleMetrics(w http.ResponseWriter, _ *http.Request) {
|
func (s *Server) handleMetrics(w http.ResponseWriter, _ *http.Request) {
|
||||||
gauges := []struct {
|
gauges := []struct {
|
||||||
name, table, help string
|
name, table, help string
|
||||||
|
|
|
||||||
|
|
@ -179,6 +179,19 @@ func TestHubHappyPath(t *testing.T) {
|
||||||
t.Fatalf("head = %q, want %q", head.Head, manifestHash)
|
t.Fatalf("head = %q, want %q", head.Head, manifestHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GET log returns the share's snapshot history (one entry so far).
|
||||||
|
status, body = do(t, "GET", base+proto.PathLog+"?share="+share, bearer, nil)
|
||||||
|
if status != http.StatusOK {
|
||||||
|
t.Fatalf("log status = %d, body = %s", status, body)
|
||||||
|
}
|
||||||
|
var log proto.LogResponse
|
||||||
|
if err := json.Unmarshal(body, &log); err != nil {
|
||||||
|
t.Fatalf("decode log: %v", err)
|
||||||
|
}
|
||||||
|
if len(log.Snapshots) != 1 || log.Snapshots[0].ID != manifestHash {
|
||||||
|
t.Fatalf("log = %+v, want one snapshot %s", log.Snapshots, manifestHash)
|
||||||
|
}
|
||||||
|
|
||||||
// /metrics exposes the gauges.
|
// /metrics exposes the gauges.
|
||||||
status, body = do(t, "GET", base+proto.PathMetrics, "", nil)
|
status, body = do(t, "GET", base+proto.PathMetrics, "", nil)
|
||||||
if status != http.StatusOK {
|
if status != http.StatusOK {
|
||||||
|
|
|
||||||
|
|
@ -143,6 +143,57 @@ func Pull(c *transport.Client, root, share, subpath, base, host string, now int6
|
||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Restore rewrites the local tree to match an older snapshot, then pushes it as a
|
||||||
|
// new head — so a restore is itself a reversible snapshot, never a history rewrite.
|
||||||
|
//
|
||||||
|
// With onlyPath set, just that one file is brought back to its snapshot content
|
||||||
|
// (the rest of the tree is untouched). Otherwise the whole mounted subtree is made
|
||||||
|
// to match the snapshot: every snapshot entry is written and any local path the
|
||||||
|
// 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 != nil {
|
||||||
|
return Result{}, 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)
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
head, err := c.Head(share)
|
||||||
|
if err != nil {
|
||||||
|
return Result{}, err
|
||||||
|
}
|
||||||
|
return Push(c, root, share, subpath, ig, guard, head, hk)
|
||||||
|
}
|
||||||
|
|
||||||
// Sync brings a mount into agreement with the hub: pull+merge to head, then push
|
// Sync brings a mount into agreement with the hub: pull+merge to head, then push
|
||||||
// the merged local state; retries if the hub advanced underneath. Returns the new
|
// the merged local state; retries if the hub advanced underneath. Returns the new
|
||||||
// base snapshot and the pull result.
|
// base snapshot and the pull result.
|
||||||
|
|
|
||||||
151
internal/syncer/restore_test.go
Normal file
151
internal/syncer/restore_test.go
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
func readFile(t *testing.T, root, rel string) string {
|
||||||
|
t.Helper()
|
||||||
|
b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(rel)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRestoreWholeTree pushes v1, edits to v2, then restores v1: the file content
|
||||||
|
// reverts and a fresh head snapshot is created (a restore is a new commit).
|
||||||
|
func TestRestoreWholeTree(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, "alice")
|
||||||
|
if err := c.Publish("proj"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
root := t.TempDir()
|
||||||
|
|
||||||
|
// v1: two files.
|
||||||
|
writeFile(t, root, "main.go", "v1\n")
|
||||||
|
writeFile(t, root, "keep.txt", "constant\n")
|
||||||
|
snap1, err := Push(c, root, "proj", "", ig, guard, "", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("push v1: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// v2: edit main.go, add extra.txt.
|
||||||
|
writeFile(t, root, "main.go", "v2 changed\n")
|
||||||
|
writeFile(t, root, "extra.txt", "added later\n")
|
||||||
|
snap2, err := Push(c, root, "proj", "", ig, guard, snap1.Head, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("push v2: %v", err)
|
||||||
|
}
|
||||||
|
if snap2.Snapshot == snap1.Snapshot {
|
||||||
|
t.Fatal("v2 should be a different snapshot than v1")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore v1.
|
||||||
|
res, err := Restore(c, root, "proj", "", snap1.Snapshot, "", "host", 1, ig, guard, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("restore: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// main.go reverts; keep.txt unchanged; extra.txt (not in v1) is deleted.
|
||||||
|
if got := readFile(t, root, "main.go"); got != "v1\n" {
|
||||||
|
t.Fatalf("main.go after restore = %q, want v1", got)
|
||||||
|
}
|
||||||
|
if got := readFile(t, root, "keep.txt"); got != "constant\n" {
|
||||||
|
t.Fatalf("keep.txt = %q, want constant", got)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(root, "extra.txt")); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("extra.txt should be deleted by a whole-tree restore to v1")
|
||||||
|
}
|
||||||
|
|
||||||
|
// The restore created a NEW head whose content equals v1 (content-addressed
|
||||||
|
// snapshot id matches the original v1 snapshot).
|
||||||
|
if res.Snapshot != snap1.Snapshot {
|
||||||
|
t.Fatalf("restored head = %q, want v1 content id %q", res.Snapshot, snap1.Snapshot)
|
||||||
|
}
|
||||||
|
head, err := c.Head("proj")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if head != snap1.Snapshot {
|
||||||
|
t.Fatalf("hub head after restore = %q, want %q", head, snap1.Snapshot)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRestoreSinglePath brings back just one file to its snapshot content without
|
||||||
|
// touching the rest of the tree, and errors cleanly on a path not in the snapshot.
|
||||||
|
func TestRestoreSinglePath(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, "bob")
|
||||||
|
if err := c.Publish("proj"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
root := t.TempDir()
|
||||||
|
|
||||||
|
writeFile(t, root, "a.txt", "a-v1\n")
|
||||||
|
writeFile(t, root, "b.txt", "b-v1\n")
|
||||||
|
snap1, err := Push(c, root, "proj", "", ig, guard, "", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("push v1: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Edit both files.
|
||||||
|
writeFile(t, root, "a.txt", "a-v2\n")
|
||||||
|
writeFile(t, root, "b.txt", "b-v2\n")
|
||||||
|
if _, err := Push(c, root, "proj", "", ig, guard, snap1.Head, nil); err != nil {
|
||||||
|
t.Fatalf("push v2: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore only a.txt to v1; b.txt must keep its v2 content.
|
||||||
|
if _, err := Restore(c, root, "proj", "", snap1.Snapshot, "a.txt", "host", 1, ig, guard, nil); err != nil {
|
||||||
|
t.Fatalf("restore a.txt: %v", err)
|
||||||
|
}
|
||||||
|
if got := readFile(t, root, "a.txt"); got != "a-v1\n" {
|
||||||
|
t.Fatalf("a.txt = %q, want a-v1 (restored)", got)
|
||||||
|
}
|
||||||
|
if got := readFile(t, root, "b.txt"); got != "b-v2\n" {
|
||||||
|
t.Fatalf("b.txt = %q, want b-v2 (untouched)", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A path not in the snapshot is rejected without writing anything.
|
||||||
|
if _, err := Restore(c, root, "proj", "", snap1.Snapshot, "ghost.txt", "host", 1, ig, guard, nil); err == nil {
|
||||||
|
t.Fatal("restoring a path absent from the snapshot should error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -156,6 +156,16 @@ func (c *Client) Head(share string) (string, error) {
|
||||||
return resp.Head, nil
|
return resp.Head, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Log returns a share's snapshot history, newest first.
|
||||||
|
func (c *Client) Log(share string) ([]proto.SnapshotInfo, error) {
|
||||||
|
var resp proto.LogResponse
|
||||||
|
path := proto.PathLog + "?" + url.Values{"share": {share}}.Encode()
|
||||||
|
if err := c.do(http.MethodGet, path, true, nil, &resp); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return resp.Snapshots, nil
|
||||||
|
}
|
||||||
|
|
||||||
// do sends a JSON request (nil body for GET) and decodes a JSON response into
|
// do sends a JSON request (nil body for GET) and decodes a JSON response into
|
||||||
// out (nil out discards the body). It sets the bearer header when auth is true.
|
// out (nil out discards the body). It sets the bearer header when auth is true.
|
||||||
func (c *Client) do(method, path string, auth bool, body, out any) error {
|
func (c *Client) do(method, path string, auth bool, body, out any) error {
|
||||||
|
|
|
||||||
|
|
@ -11,10 +11,24 @@ const (
|
||||||
PathBlob = "/v1/blob/" // PUT /v1/blob/{hash}, auth: upload one blob's bytes
|
PathBlob = "/v1/blob/" // PUT /v1/blob/{hash}, auth: upload one blob's bytes
|
||||||
PathPush = "/v1/push" // POST, auth: commit a snapshot
|
PathPush = "/v1/push" // POST, auth: commit a snapshot
|
||||||
PathHead = "/v1/head" // GET ?share=, auth: current head snapshot id
|
PathHead = "/v1/head" // GET ?share=, auth: current head snapshot id
|
||||||
|
PathLog = "/v1/log" // GET ?share=, auth: snapshot history
|
||||||
PathEvents = "/v1/events" // GET ?share=, auth: SSE stream of change events
|
PathEvents = "/v1/events" // GET ?share=, auth: SSE stream of change events
|
||||||
PathMetrics = "/metrics" // GET, no auth: Prometheus text exposition
|
PathMetrics = "/metrics" // GET, no auth: Prometheus text exposition
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SnapshotInfo is one entry in a share's history.
|
||||||
|
type SnapshotInfo struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Parent string `json:"parent"`
|
||||||
|
Device string `json:"device"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LogResponse is a share's snapshot history, newest first.
|
||||||
|
type LogResponse struct {
|
||||||
|
Snapshots []SnapshotInfo `json:"snapshots"`
|
||||||
|
}
|
||||||
|
|
||||||
// Event is a hub change notification, delivered as one SSE "data:" line (JSON).
|
// Event is a hub change notification, delivered as one SSE "data:" line (JSON).
|
||||||
type Event struct {
|
type Event struct {
|
||||||
Share string `json:"share"`
|
Share string `json:"share"`
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue