diff --git a/go.mod b/go.mod index 77d890e..e7277ac 100644 --- a/go.mod +++ b/go.mod @@ -8,11 +8,20 @@ require ( github.com/jotfs/fastcdc-go v0.2.0 github.com/spf13/cobra v1.10.2 github.com/zeebo/blake3 v0.2.4 + modernc.org/sqlite v1.53.0 ) require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/klauspost/cpuid/v2 v2.0.12 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/spf13/pflag v1.0.9 // indirect - golang.org/x/sys v0.13.0 // indirect + golang.org/x/sys v0.44.0 // indirect + modernc.org/libc v1.73.4 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect ) diff --git a/go.sum b/go.sum index bbb77a9..f658c21 100644 --- a/go.sum +++ b/go.sum @@ -1,14 +1,28 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jotfs/fastcdc-go v0.2.0 h1:WHYIGk3k9NumGWfp4YMsemEcx/s4JKpGAa6tpCpHJOo= github.com/jotfs/fastcdc-go v0.2.0/go.mod h1:PGFBIloiASFbiKnkCd/hmHXxngxYDYtisyurJ/zyDNM= github.com/klauspost/cpuid/v2 v2.0.12 h1:p9dKCg8i4gmOxtv35DvrYoWqYzQrvEVdjQ762Y0OqZE= github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= @@ -21,6 +35,41 @@ github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCR github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= -golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= +golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ= +golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= +golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c= +modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws= +modernc.org/ccgo/v4 v4.34.4/go.mod h1:qdKqE8FNIYyysougB1RX9MxCzp5oJOcQXSobANJ4TuE= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc= +modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA= +modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M= +modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go new file mode 100644 index 0000000..f39635d --- /dev/null +++ b/internal/hub/meta/meta.go @@ -0,0 +1,253 @@ +// Package meta is the hub's SQLite metadata store: devices, join tokens, shares, +// per-(device,share) write access, snapshots, and chunk refcounts. Blob bytes +// live in the blobstore; this tracks who/what/which-version and drives GC. +// +// Pure-Go driver (modernc.org/sqlite) so the hub cross-compiles without CGO. +package meta + +import ( + "database/sql" + "errors" + + _ "modernc.org/sqlite" +) + +const schema = ` +PRAGMA journal_mode=WAL; +PRAGMA foreign_keys=ON; +CREATE TABLE IF NOT EXISTS devices ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + pubkey BLOB NOT NULL, + last_seen INTEGER, + revoked INTEGER NOT NULL DEFAULT 0 +); +CREATE TABLE IF NOT EXISTS tokens ( + hash TEXT PRIMARY KEY, + expires_at INTEGER, + used INTEGER NOT NULL DEFAULT 0 +); +CREATE TABLE IF NOT EXISTS shares ( + name TEXT PRIMARY KEY, + head_snapshot TEXT, + created_by TEXT NOT NULL, + created_at INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS access ( + device_id TEXT NOT NULL, + share TEXT NOT NULL, + writable INTEGER NOT NULL DEFAULT 1, + PRIMARY KEY (device_id, share) +); +CREATE TABLE IF NOT EXISTS snapshots ( + id TEXT PRIMARY KEY, + share TEXT NOT NULL, + parent_id TEXT, + device_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + manifest_hash TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS chunks ( + hash TEXT PRIMARY KEY, + size INTEGER NOT NULL, + refcount INTEGER NOT NULL DEFAULT 0 +); +` + +// DB is the hub metadata store. +type DB struct{ sql *sql.DB } + +// Open opens (and migrates) the SQLite database at path. Use ":memory:" in tests. +func Open(path string) (*DB, error) { + db, err := sql.Open("sqlite", path) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(1) // ponytail: single-writer; SQLite serializes anyway + if _, err := db.Exec(schema); err != nil { + db.Close() + return nil, err + } + return &DB{sql: db}, nil +} + +// Close closes the database. +func (d *DB) Close() error { return d.sql.Close() } + +// --- devices ------------------------------------------------------------- + +// AddDevice registers (or updates) a device by id. +func (d *DB) AddDevice(id, name string, pubkey []byte, lastSeen int64) error { + _, err := d.sql.Exec( + `INSERT INTO devices (id, name, pubkey, last_seen) VALUES (?,?,?,?) + ON CONFLICT(id) DO UPDATE SET name=excluded.name, last_seen=excluded.last_seen`, + id, name, pubkey, lastSeen) + return err +} + +// Revoked reports whether a device is unknown or revoked (i.e. not allowed). +func (d *DB) Revoked(id string) (bool, error) { + var revoked int + err := d.sql.QueryRow(`SELECT revoked FROM devices WHERE id=?`, id).Scan(&revoked) + if errors.Is(err, sql.ErrNoRows) { + return true, nil + } + if err != nil { + return true, err + } + return revoked != 0, nil +} + +// Revoke marks a device revoked; its access ends immediately. +func (d *DB) Revoke(id string) error { + _, err := d.sql.Exec(`UPDATE devices SET revoked=1 WHERE id=?`, id) + return err +} + +// --- tokens -------------------------------------------------------------- + +// CreateToken stores a join token hash with an optional expiry (0 = none). +func (d *DB) CreateToken(hash string, expiresAt int64) error { + _, err := d.sql.Exec(`INSERT INTO tokens (hash, expires_at) VALUES (?,?)`, hash, nullable(expiresAt)) + return err +} + +// RedeemToken atomically consumes a token: valid only if present, unused, and +// unexpired at now. Returns true on success. +func (d *DB) RedeemToken(hash string, now int64) (bool, error) { + res, err := d.sql.Exec( + `UPDATE tokens SET used=1 WHERE hash=? AND used=0 AND (expires_at IS NULL OR expires_at > ?)`, + hash, now) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n == 1, err +} + +// --- shares & access ----------------------------------------------------- + +// CreateShare creates a share (no-op if it already exists). +func (d *DB) CreateShare(name, createdBy string, createdAt int64) error { + _, err := d.sql.Exec( + `INSERT INTO shares (name, created_by, created_at) VALUES (?,?,?) + ON CONFLICT(name) DO NOTHING`, name, createdBy, createdAt) + return err +} + +// ShareHead returns the current head snapshot id of a share (ok=false if the +// share is missing or has no snapshots yet). +func (d *DB) ShareHead(name string) (head string, ok bool, err error) { + var h sql.NullString + err = d.sql.QueryRow(`SELECT head_snapshot FROM shares WHERE name=?`, name).Scan(&h) + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil + } + if err != nil { + return "", false, err + } + return h.String, h.Valid && h.String != "", nil +} + +// Writable reports whether a device may push to a share. Default is true; an +// access row with writable=0 makes the device read-only on that share. +func (d *DB) Writable(deviceID, share string) (bool, error) { + var w int + err := d.sql.QueryRow(`SELECT writable FROM access WHERE device_id=? AND share=?`, deviceID, share).Scan(&w) + if errors.Is(err, sql.ErrNoRows) { + return true, nil + } + if err != nil { + return false, err + } + return w != 0, nil +} + +// SetWritable sets a device's write access on a share (the only access knob). +func (d *DB) SetWritable(deviceID, share string, writable bool) error { + w := 0 + if writable { + w = 1 + } + _, err := d.sql.Exec( + `INSERT INTO access (device_id, share, writable) VALUES (?,?,?) + ON CONFLICT(device_id, share) DO UPDATE SET writable=excluded.writable`, + deviceID, share, w) + return err +} + +// --- snapshots & chunks -------------------------------------------------- + +// Snapshot is one accepted change set on a share. +type Snapshot struct { + ID string + Share string + ParentID string // "" for the first snapshot + DeviceID string + ManifestHash string + CreatedAt int64 +} + +// ChunkRef is a chunk a snapshot references. +type ChunkRef struct { + Hash string + Size int64 +} + +// AddSnapshot records a snapshot, bumps the refcount of each distinct chunk it +// references, and advances the share's head — all in one transaction. +func (d *DB) AddSnapshot(s Snapshot, chunks []ChunkRef) error { + tx, err := d.sql.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + if _, err := tx.Exec( + `INSERT INTO snapshots (id, share, parent_id, device_id, created_at, manifest_hash) + VALUES (?,?,?,?,?,?)`, + s.ID, s.Share, nullableStr(s.ParentID), s.DeviceID, s.CreatedAt, s.ManifestHash); err != nil { + return err + } + seen := make(map[string]bool, len(chunks)) + for _, c := range chunks { + if seen[c.Hash] { // count each chunk once per snapshot + continue + } + seen[c.Hash] = true + if _, err := tx.Exec( + `INSERT INTO chunks (hash, size, refcount) VALUES (?,?,1) + ON CONFLICT(hash) DO UPDATE SET refcount=refcount+1`, + c.Hash, c.Size); err != nil { + return err + } + } + if _, err := tx.Exec(`UPDATE shares SET head_snapshot=? WHERE name=?`, s.ID, s.Share); err != nil { + return err + } + return tx.Commit() +} + +// ChunkRefcount returns a chunk's refcount (0 if unknown). Used by tests and GC. +func (d *DB) ChunkRefcount(hash string) (int, error) { + var rc int + err := d.sql.QueryRow(`SELECT refcount FROM chunks WHERE hash=?`, hash).Scan(&rc) + if errors.Is(err, sql.ErrNoRows) { + return 0, nil + } + return rc, err +} + +func nullable(v int64) any { + if v == 0 { + return nil + } + return v +} + +func nullableStr(s string) any { + if s == "" { + return nil + } + return s +} diff --git a/internal/hub/meta/meta_test.go b/internal/hub/meta/meta_test.go new file mode 100644 index 0000000..0805d22 --- /dev/null +++ b/internal/hub/meta/meta_test.go @@ -0,0 +1,112 @@ +package meta + +import "testing" + +func open(t *testing.T) *DB { + t.Helper() + db, err := Open(":memory:") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + return db +} + +func TestDeviceLifecycle(t *testing.T) { + db := open(t) + if rev, _ := db.Revoked("dev1"); !rev { + t.Fatal("unknown device should be treated as revoked") + } + if err := db.AddDevice("dev1", "laptop", []byte("pub"), 100); err != nil { + t.Fatal(err) + } + if rev, _ := db.Revoked("dev1"); rev { + t.Fatal("registered device should not be revoked") + } + if err := db.Revoke("dev1"); err != nil { + t.Fatal(err) + } + if rev, _ := db.Revoked("dev1"); !rev { + t.Fatal("revoked device should be revoked") + } +} + +func TestTokenRedeemOnce(t *testing.T) { + db := open(t) + if err := db.CreateToken("tok", 1000); err != nil { + t.Fatal(err) + } + if ok, _ := db.RedeemToken("tok", 500); !ok { + t.Fatal("valid unexpired token should redeem") + } + if ok, _ := db.RedeemToken("tok", 500); ok { + t.Fatal("token must not redeem twice") + } + + if err := db.CreateToken("old", 100); err != nil { + t.Fatal(err) + } + if ok, _ := db.RedeemToken("old", 200); ok { + t.Fatal("expired token must not redeem") + } + if ok, _ := db.RedeemToken("ghost", 1); ok { + t.Fatal("unknown token must not redeem") + } +} + +func TestWritableDefaultAndOverride(t *testing.T) { + db := open(t) + if w, _ := db.Writable("dev1", "projects"); !w { + t.Fatal("default writable should be true") + } + if err := db.SetWritable("dev1", "projects", false); err != nil { + t.Fatal(err) + } + if w, _ := db.Writable("dev1", "projects"); w { + t.Fatal("should be read-only after SetWritable(false)") + } + if err := db.SetWritable("dev1", "projects", true); err != nil { + t.Fatal(err) + } + if w, _ := db.Writable("dev1", "projects"); !w { + t.Fatal("should be writable again after SetWritable(true)") + } +} + +func TestSharesSnapshotsRefcounts(t *testing.T) { + db := open(t) + if err := db.CreateShare("projects", "dev1", 1); err != nil { + t.Fatal(err) + } + if _, ok, _ := db.ShareHead("projects"); ok { + t.Fatal("a new share should have no head yet") + } + + // snap1 references h1 twice (must count once) and h2. + s1 := Snapshot{ID: "snap1", Share: "projects", DeviceID: "dev1", ManifestHash: "m1", CreatedAt: 10} + if err := db.AddSnapshot(s1, []ChunkRef{{"h1", 5}, {"h2", 6}, {"h1", 5}}); err != nil { + t.Fatal(err) + } + head, ok, _ := db.ShareHead("projects") + if !ok || head != "snap1" { + t.Fatalf("head = %q ok=%v, want snap1", head, ok) + } + if rc, _ := db.ChunkRefcount("h1"); rc != 1 { + t.Fatalf("h1 refcount = %d, want 1 (deduped within a snapshot)", rc) + } + + // snap2 re-uses h1 and adds h3. + s2 := Snapshot{ID: "snap2", Share: "projects", ParentID: "snap1", DeviceID: "dev1", ManifestHash: "m2", CreatedAt: 20} + if err := db.AddSnapshot(s2, []ChunkRef{{"h1", 5}, {"h3", 7}}); err != nil { + t.Fatal(err) + } + if rc, _ := db.ChunkRefcount("h1"); rc != 2 { + t.Fatalf("h1 refcount = %d, want 2 (two snapshots reference it)", rc) + } + if rc, _ := db.ChunkRefcount("h3"); rc != 1 { + t.Fatalf("h3 refcount = %d, want 1", rc) + } + if head, _, _ := db.ShareHead("projects"); head != "snap2" { + t.Fatalf("head = %q, want snap2", head) + } +}