diff --git a/README.md b/README.md index 43bbd09..d0bf45f 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Squirrel works the same at any size: one machine backing up to one destination, ## Under the hood -Squirrel indexes a local file tree by BLAKE3 content hash and syncs it to one or more remote destinations (NAS, S3, B2, GCS, SFTP, …) via rclone. Peer syncs are BLAKE3-verified end-to-end; every other destination is checked by the strongest comparison it supports, and the index records which one ran. Destinations are append-only: an overwrite at the destination moves the prior bytes into `.squirrel-history/run-/`, never deletes them. +Squirrel indexes a local file tree by BLAKE3 content hash and syncs it to one or more destinations (a local disk, a NAS, SFTP, S3, B2, GCS, …): it writes local disks and plain SFTP servers itself, and reaches buckets and encrypted destinations through rclone. Peer syncs are BLAKE3-verified end-to-end; every other destination is checked by the strongest comparison it supports, and the index records which one ran. Destinations are append-only: an overwrite at the destination moves the prior bytes into `.squirrel-history/run-/`, never deletes them. ## Principle @@ -49,7 +49,7 @@ go install github.com/mbertschler/squirrel/cmd/squirrel@latest A source build reports its version as `0.0.0-dev` — the version is only stamped into the released binaries at build time. -You will also need [rclone](https://rclone.org) ≥ 1.71 on `PATH` to sync or restore against a **bucket destination** (1.71 added the sftp `hashes` option that [`hash_algo`](#offsite-verification-squirrel-verify) sets). Syncing to a **peer node** does not use it — those bytes stream over the peer's own sync API — so a machine whose only targets are peers needs no rclone at all: +You will also need [rclone](https://rclone.org) ≥ 1.71 on `PATH` to sync or restore against a **bucket destination** (`s3`, `b2`, `gcs`) or an **encrypted** one (1.71 added the sftp `hashes` option that [`hash_algo`](#offsite-verification-squirrel-verify) sets there). A `local` disk and a plain `sftp` server need no rclone — squirrel writes them itself — and neither does a **peer node**, whose bytes stream over the peer's own sync API, so a machine whose only targets are those needs no rclone at all: ``` brew install rclone # macOS @@ -88,11 +88,11 @@ bucket = "squirrel-backup" root = "/squirrel" ``` -Supported destination types: `local`, `sftp`, `s3`, `b2`, `gcs` (rclone-backed), and `kopia` (see [kopia destinations](#kopia-destinations)). Secrets accept either a literal string or an inline `{ env = "VAR_NAME" }` table that is resolved at load time. Unknown fields, missing required fields, and unset env vars are rejected immediately — squirrel will not invoke rclone with a misconfigured destination. +Supported destination types: `local`, `sftp`, `s3`, `b2`, `gcs`, and `kopia` (see [kopia destinations](#kopia-destinations)). squirrel writes `local` and `sftp` destinations itself, and rclone writes `s3`, `b2`, `gcs` and every encrypted destination. Secrets accept either a literal string or an inline `{ env = "VAR_NAME" }` table that is resolved at load time. Unknown fields, missing required fields, and unset env vars are rejected immediately — squirrel will not start a transfer to a misconfigured destination. Some optional params are specific to one backend type and rejected on the others (as an unknown field): -- **`sftp` host-key validation** — `known_hosts_file` points rclone at a known_hosts file so it validates the server's host key before transferring; `host_key_algorithms` is rclone's space-separated list pinning the accepted host-key algorithms. Both map to the rclone sftp options of the same name. **Without `known_hosts_file`, rclone does not validate the server's host key** and will connect to whatever host answers — set it (recommended) so a redirected or impersonated server is rejected. +- **`sftp` host-key validation** — `known_hosts_file` names a known_hosts file holding the server's host key; `host_key_algorithms` is a space-separated list pinning the accepted host-key algorithms. squirrel checks the key of every sftp destination it writes — every one without `crypt` — against `known_hosts_file`, or `~/.ssh/known_hosts` when unset, and refuses a server the file does not hold. On an encrypted sftp destination both map to the rclone sftp options of the same name, and **without `known_hosts_file`, rclone does not validate the server's host key** and will connect to whatever host answers — set it so a redirected or impersonated server is rejected. ```toml [destinations.nas] @@ -114,7 +114,7 @@ Some optional params are specific to one backend type and rejected on the others storage_class = "" # archive tiers cost less to store, more to read ``` -Squirrel writes its own `rclone.conf` next to the config (`~/.squirrel/rclone.conf`, mode 0600) on every sync invocation. You do not run `rclone config` and you should not edit `rclone.conf` by hand. +For the destinations rclone writes, squirrel writes its own `rclone.conf` next to the config (`~/.squirrel/rclone.conf`, mode 0600) on every sync invocation. You do not run `rclone config` and you should not edit `rclone.conf` by hand. ### Encrypted destinations @@ -158,7 +158,7 @@ Properties that differ from rclone destinations: ### Content-addressed destinations -By default a destination mirrors the volume's tree (see [Destination layout](#destination-layout)). Any rclone-remote destination — with or without a `crypt` block — can instead opt into an **append-only, content-addressed** layout, built for cold archive storage where objects should never be rewritten or moved: +By default a destination mirrors the volume's tree (see [Destination layout](#destination-layout)). Any destination but kopia — with or without a `crypt` block — can instead opt into an **append-only, content-addressed** layout, built for cold archive storage where objects should never be rewritten or moved. squirrel writes it itself on a `local` disk and on `sftp` without `crypt`: each object is staged, confirmed (read back through BLAKE3 locally, hashed by the server's `hash_algo` command on sftp) and only then renamed onto its name, never over a file already there. rclone writes the others: ```toml [destinations.archive] @@ -182,7 +182,7 @@ Properties that differ from mirrored destinations: - **Verification is presence+size**, recorded as such: each object is re-hashed with BLAKE3 before upload and confirmed present at the expected size after it, but its stored bytes are not compared at transfer time (and `crypt` remotes expose no hashes at all), so the runs row is recorded shallow and the push never claims content verification. On top of that, each upload's provider-side ciphertext fingerprint is recorded in the index and re-checked by [`squirrel verify`](#offsite-verification-squirrel-verify). - **Pick the layout when the destination is first used.** Switching an existing mirrored destination to `content-addressed` (or back) is not supported — point the new layout at a fresh destination or root. The push detects a mirrored history (a recorded successful sync without its manifest segment) and refuses. -- **`squirrel restore` restores the layout**: it resolves each present path to its content hash from the local index, fetches the per-hash object through the same rclone (`crypt`) read path the push uses, and re-hashes every fetched object before writing. When the *local index itself* is lost, the format is deliberately simple enough to recover without squirrel — see below. +- **`squirrel restore` restores the layout**: it resolves each present path to its content hash from the local index, fetches the per-hash object through the same read path the push uses (squirrel's own on a `local` disk and plain `sftp`, rclone and its `crypt` overlay otherwise), and re-hashes every fetched object before writing. When the *local index itself* is lost, the format is deliberately simple enough to recover without squirrel — see below. - `--dry-run` is not supported yet on the push (it previews restore). #### Offsite verification (`squirrel verify`) @@ -192,7 +192,8 @@ Cold archive storage is exactly the copy you can't cheaply re-download and re-ha What gets recorded depends on the backend type: - **`s3`** — the object **ETag**, recorded as `etag-md5` for a single-part upload's whole-object MD5, or `etag-md5-composite` for a multipart object's `-` value, stored verbatim either way. The ETag is read straight from the S3 API with a paginated `ListObjectsV2` over the `objects/` prefix, *not* through rclone: rclone funnels every hash read through `Object.Hash(MD5)`, which returns an empty string for a composite ETag, so a multipart (or client-encrypted, always-streamed) object would otherwise never expose a fingerprint at all. Listing is archive-tier-safe (no per-object `HEAD`, no restore), and the composite ETag is fixed at upload time and unaffected by later storage-class transitions or server-side encryption, so the recorded value stays stable for the life of the object. This read is the counterpart to the (deferred) write-side use of S3 additional checksums; capturing the ETag needs no upload-side change. For S3-compatible providers whose endpoint the client addresses wrongly, set `force_path_style = true` (see below). -- **`sftp`** — the checksum computed server-side by the remote's hash command. Content-addressed sftp destinations default to **SHA-256** (`hash_algo = "sha256"`, rendered as rclone's sftp `hashes` option so the selection is explicit rather than rclone's md5/sha1 preference); set `hash_algo` if your server only offers another type. +- **`local`** — the BLAKE3 of the stored bytes, read back by squirrel itself as each object lands and again on every verify pass; it must equal the object's name. +- **`sftp`** — the checksum computed server-side by the remote's hash command. Content-addressed sftp destinations default to **SHA-256** (`hash_algo = "sha256"`); set `hash_algo` if your server only offers another type. Without `crypt` squirrel runs the command itself (`md5sum`, `sha1sum`, `sha256sum` or `b3sum`) and checks its answer against the bytes it sent; behind `crypt` rclone runs it, through its sftp `hashes` option. - **other backends** — whatever hash `rclone lsjson --hash` exposes, recorded under its rclone hash name (e.g. `sha1` on b2). A backend exposing no checksum leaves the fingerprint pending, with a warning in the sync output. Re-verify a destination (or all content-addressed destinations) at any time: @@ -384,7 +385,7 @@ squirrel sync pictures --to nas # just one squirrel sync # every (volume, destination) pair in config ``` -Sync compares every file with its copy on a mirror destination by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on local disks and S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is not marked success. The run records the `checksum` method, which the offload gate does not accept: a mirror can never be named in `offload_requires`. Use `--shallow` to fall back to rclone's default size+mtime comparison if you want speed over integrity for a big initial push. Encrypted (`crypt`) destinations always use the size+mtime comparison (see [Encrypted destinations](#encrypted-destinations)). +A mirror on a `local` disk is written by squirrel itself: it hashes every file with BLAKE3 as it streams out, reads each copy back through BLAKE3 before committing it, and records the run as `fingerprint-verified` once every file has such a copy, so it can be named in `offload_requires`; `--shallow` is refused there, since there is no comparison to skip. A native sftp mirror (no crypt) is written the same way, without the read-back. Sync compares every file with its copy on a mirror rclone writes (encrypted, or on s3, b2 or gcs) by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is not marked success, and the run records the `checksum` method, which the offload gate refuses: such a mirror can never be named in `offload_requires`, and neither can a native sftp mirror, which reads nothing back. Use `--shallow` to fall back to rclone's default size+mtime comparison on an rclone mirror if you want speed over integrity for a big initial push. Encrypted (`crypt`) destinations always use the size+mtime comparison (see [Encrypted destinations](#encrypted-destinations)). ### First use and the `.squirrel-volume` marker @@ -470,13 +471,15 @@ Each mirrored destination (`layout = "mirror"`, the default) is a tree shaped li pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg + .squirrel-index/run-12 # receipt for run 12 (local disks) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) + .squirrel-staging/ # in-flight writes (local disks) docs/ invoice.pdf .squirrel-history/run-9/invoice.pdf ``` -`.squirrel-history/run-/` is rclone's `--backup-dir` target for that sync run. It is filtered out of all subsequent comparisons so it does not grow rclone's listing time or get uploaded back. A directory literally called `.squirrel-history` in your source volume is also filtered (with a warning), to keep the reserved name out of the destination tree by accident. +`.squirrel-history/run-/` holds the prior bytes of every file that sync run replaced, moved there first and never deleted. On a local disk squirrel writes the mirror itself: each file is staged under `.squirrel-staging/`, whatever its path held moves into history, and the staged copy is renamed into place; each run leaves a receipt of its changes at `.squirrel-index/run-`, and a local mirror starts on a fresh or emptied root. Remote mirrors are written by rclone, with history as its `--backup-dir`. History is filtered out of all subsequent comparisons so it does not grow listing time or get uploaded back. A directory literally called `.squirrel-history` in your source volume is also filtered (with a warning), to keep the reserved name out of the destination tree by accident. `.squirrel-index/` holds the index snapshots ridden along after each successful sync (see [Index snapshots](#index-snapshots)). Like `.squirrel-history`, it is filtered out of all sync and restore transfers and from peer-sync, so a snapshot is never mistaken for user content. diff --git a/SAFETY-AUDIT.md b/SAFETY-AUDIT.md index 15340f0..51576cb 100644 --- a/SAFETY-AUDIT.md +++ b/SAFETY-AUDIT.md @@ -958,7 +958,12 @@ extended enforcement to remote rclone destinations (`sftp`, `s3`, `b2`, the mirror, content-addressed, and packed layouts, with the marker filtered out of every transfer, comparison, and restore. A read that fails for any reason other than a definite "not found" refuses without writing, so a -reachability blip cannot be mistaken for a fresh root. +reachability blip cannot be mistaken for a fresh root. Since +[#217](https://github.com/mbertschler/squirrel/pull/217), a `local` +destination and an `sftp` one without crypt read and write the marker +through squirrel's own transport, staged and renamed onto its name, in every +layout; a volume that synced there before is refused as a disk that is most +likely not mounted rather than steered toward `--init`. **Issue:** [#64 — sync: require .squirrel-volume markers on destination and source to gate against misconfiguration](https://github.com/mbertschler/squirrel/issues/64); [#150 — sync: enforce .squirrel-volume markers on remote rclone destinations](https://github.com/mbertschler/squirrel/issues/150) @@ -1019,7 +1024,12 @@ local and s3 — and runs were recorded as `blake3` all the same. records such a run as `checksum`, relabels the components already stored, and stops the offload gate from accepting it, so a mirror can no longer be named in `offload_requires`. The shallow warning now says "skipping the -checksum comparison". +checksum comparison". The native mirror +([#217](https://github.com/mbertschler/squirrel/pull/217)) earns the evidence +back on a `local` disk: it refuses `--shallow`, hashes every file as it +streams, reads each copy back through BLAKE3 before committing it, and +`squirrel verify` re-checks its copies, so a local mirror may gate offload +again. rclone mirrors and native sftp mirrors still may not. **Issue:** `sync: surface --shallow trade-off in logs and persist it on the runs row` → tracked in [#79](https://github.com/mbertschler/squirrel/issues/79), @@ -1620,7 +1630,13 @@ proves — `presence+size` is explicitly **not** content-verified, and `store.ContentVerifiedMethod`). So the *consequence* the finding worried about — a presence-only advance gating an offload — is gone. -The narrow original gap remains: nothing downloads an object back through +Since [#217](https://github.com/mbertschler/squirrel/pull/217), a +destination without crypt that squirrel writes itself closes the gap: each +artifact is staged, read back through BLAKE3 on a local disk or hashed by +the server's command on sftp, and only then renamed onto its name. The gap +stays for crypt destinations, which rclone writes. + +The narrow original gap remains there: nothing downloads an object back through the crypt overlay and BLAKE3s the plaintext, so a wrong-at-upload object that happens to preserve decrypted size is still theoretically undetected. No `--verify` mode exists. This stays a deliberate non-decision rather than diff --git a/agent/scheduler.go b/agent/scheduler.go index 1a0420f..62fbcb1 100644 --- a/agent/scheduler.go +++ b/agent/scheduler.go @@ -113,15 +113,15 @@ func (s *scheduler) refresh() { s.pullEvery = resolvePullCadences(cur.Nodes) } -// resolveVerifyCadences maps each verifiable (content-addressed or packed) -// destination to its effective verify cadence: the destination's own +// resolveVerifyCadences maps each verifiable destination (content-addressed, +// packed, or a native mirror) to its effective verify cadence: the destination's own // verify_every when set, otherwise the [agent] verify_every default. Only // destinations with a positive resulting cadence are included, so a config // with neither knob set yields an empty map and no verify activity. func resolveVerifyCadences(dests map[string]*config.Destination, def time.Duration) map[string]time.Duration { out := make(map[string]time.Duration) for name, d := range dests { - if d.Layout != config.LayoutContentAddressed && d.Layout != config.LayoutPacked { + if !d.Verifiable() { continue } eff := d.VerifyEvery @@ -252,10 +252,12 @@ func (s *scheduler) tick(ctx context.Context) { } // The verify and durability-pull cadences key on destinations and peer // nodes rather than volumes, so they run after the per-volume loop as - // their own phases. Both are read-only / metadata-only and take no - // volume lock: verify touches only the remote-object bookkeeping, and a - // durability pull only merges peer-supplied vectors — neither races the - // per-volume index/sync/audit work the loop above coordinates. + // their own phases. Both only read the destination and take no volume + // lock: verify updates only squirrel's records of what the destination + // holds, a mirror copy's only while its row is still where the pass + // read it, and a durability pull only merges peer-supplied vectors — so + // neither is confused by the per-volume index/sync/audit work the loop + // above coordinates. s.evaluateVerify(ctx) s.evaluateDurabilityPulls(ctx) } diff --git a/agent/sync.go b/agent/sync.go index 7bf96e0..7de3f5d 100644 --- a/agent/sync.go +++ b/agent/sync.go @@ -38,18 +38,19 @@ const HistoryDirName = ".squirrel-history" // (conflicts) without parsing run-id semantics. const ConflictsDirName = ".squirrel-conflicts" -// RestoreHistoryDirName and IndexDirName mirror sync.RestoreHistoryDirName -// and sync.IndexDirName at the agent side (lowercase-duplicated for the -// same reason as HistoryDirName). The receiver never writes into either -// itself, but a peer's wire path can name them; the path validators -// reject them so the initiator-side reserved filter -// (sync.isReservedSyncPath / isReservedFolderPath) and the receiver -// allow-list cover the same four names. A wire path under +// RestoreHistoryDirName, IndexDirName and StagingDirName mirror their sync +// package namesakes at the agent side (duplicated for the same reason as +// HistoryDirName). The receiver never writes into any of them itself, but +// a peer's wire path can name them; the path validators reject them so the +// initiator-side reserved filter (sync.isReservedSyncPath / +// isReservedFolderPath) and the receiver allow-list cover the same five +// names. A wire path under // .squirrel-restore-history could otherwise overwrite the receiver's // only pre-restore backup. const ( RestoreHistoryDirName = ".squirrel-restore-history" IndexDirName = ".squirrel-index" + StagingDirName = ".squirrel-staging" ) // maxPlanBodyBytes caps a decoded request body. decodeJSON applies it to @@ -807,14 +808,14 @@ func validateRelPath(p string) error { } // isReservedSyncDir reports whether a cleaned, slash-separated path is -// one of the four reserved sync directories or lives under one. The +// one of the five reserved sync directories or lives under one. The // allow-list matches the initiator-side filter // (sync.isReservedSyncPath / isReservedFolderPath) so the receiver // can't be made to write where the initiator would never publish — // including .squirrel-restore-history, whose contents are the // receiver's only pre-restore backup. func isReservedSyncDir(cleaned string) bool { - for _, dir := range []string{HistoryDirName, ConflictsDirName, RestoreHistoryDirName, IndexDirName} { + for _, dir := range []string{HistoryDirName, ConflictsDirName, RestoreHistoryDirName, IndexDirName, StagingDirName} { if cleaned == dir || strings.HasPrefix(cleaned, dir+"/") { return true } diff --git a/agent/sync_test.go b/agent/sync_test.go index 393fcb7..508dcaa 100644 --- a/agent/sync_test.go +++ b/agent/sync_test.go @@ -584,7 +584,7 @@ func TestPreStageTransferPreservesOutOfBandFile(t *testing.T) { } // TestValidateRelPathRejectsAllReservedDirs (#106b): the receiver's wire -// path allow-list must reject all four reserved sync directories, matching +// path allow-list must reject all five reserved sync directories, matching // the initiator-side filter. A path under .squirrel-restore-history or // .squirrel-index could otherwise let a peer overwrite the receiver's only // pre-restore backup or its index ride-along. @@ -594,8 +594,10 @@ func TestValidateRelPathRejectsAllReservedDirs(t *testing.T) { ConflictsDirName + "/run-1/x", RestoreHistoryDirName + "/run-1/x", IndexDirName + "/index.db", + StagingDirName + "/run-1/x", RestoreHistoryDirName, IndexDirName, + StagingDirName, } for _, p := range reserved { t.Run(p, func(t *testing.T) { diff --git a/cmd/squirrel/agent_scheduler.go b/cmd/squirrel/agent_scheduler.go index d7d7e3b..883737b 100644 --- a/cmd/squirrel/agent_scheduler.go +++ b/cmd/squirrel/agent_scheduler.go @@ -61,7 +61,7 @@ func (t *schedulerTools) rclone() *sync.Rclone { return t.rcl.Load() } // destinations the kick was planned against. func (t *schedulerTools) rebuild(ctx context.Context, cfg *config.Config) error { needsSync := anyVolumeNeedsScheduledSync(cfg) - needsVerify := anyDestinationNeedsScheduledVerify(cfg) + needsVerify := anyScheduledVerifyNeedsRclone(cfg) if !needsSync && !needsVerify { return nil } @@ -82,9 +82,9 @@ func (t *schedulerTools) rebuild(ctx context.Context, cfg *config.Config) error // anyVolumeNeedsScheduledSync reports whether a scheduled sync will // invoke rclone. Only rclone-backed destinations count: a peer node -// streams its bytes over the sync API and a kopia destination drives its -// own binary, so a cadence naming only those runs its whole schedule on a -// host with no rclone installed. +// streams its bytes over the sync API, a kopia destination drives its own +// binary, and squirrel writes a native destination itself, so a cadence naming +// only those runs its whole schedule on a host with no rclone installed. func anyVolumeNeedsScheduledSync(cfg *config.Config) bool { for _, v := range cfg.Volumes { if v.SyncEvery <= 0 { @@ -108,21 +108,22 @@ func targetNeedsRclone(cfg *config.Config, target string) bool { if _, isNode := cfg.Nodes[target]; isNode { return false } - if dest, ok := cfg.Destinations[target]; ok && dest.Type == "kopia" { - return false + if dest, ok := cfg.Destinations[target]; ok { + return sync.Pair{Destination: dest}.DrivesRclone() } return true } -// anyDestinationNeedsScheduledVerify reports whether any verifiable -// destination has an effective verify cadence — its own verify_every, or the -// [agent] verify_every default. Mirrors the scheduler's own resolution so -// the rclone/runner wiring lines up with what the scheduler will actually -// fire. -func anyDestinationNeedsScheduledVerify(cfg *config.Config) bool { +// anyScheduledVerifyNeedsRclone reports whether any verifiable destination +// squirrel reaches through rclone has an effective verify cadence — its own +// verify_every, or the [agent] verify_every default. Mirrors the scheduler's +// own resolution so the rclone wiring lines up with what the scheduler will +// actually fire; a native destination is verified through squirrel's own +// transport. +func anyScheduledVerifyNeedsRclone(cfg *config.Config) bool { agentDefault := cfg.AgentVerifyEvery() > 0 for _, d := range cfg.Destinations { - if d.Layout != config.LayoutContentAddressed && d.Layout != config.LayoutPacked { + if !d.Verifiable() || !(sync.Pair{Destination: d}).DrivesRclone() { continue } if d.VerifyEvery > 0 || agentDefault { @@ -159,7 +160,7 @@ func buildSchedulerSyncRunner(live *config.Live, s *store.Store, tools *schedule return agent.SyncRunReport{Err: err} } rcl := tools.rclone() - if rcl == nil && !pair.IsNode() { + if rcl == nil && pair.DrivesRclone() { return agent.SyncRunReport{Err: errors.New("scheduled sync needs rclone, which the configuration in force did not call for")} } // Per-kick because the kopia lookup belongs to the kicks that @@ -174,7 +175,7 @@ func buildSchedulerSyncRunner(live *config.Live, s *store.Store, tools *schedule // a single pair, so a fresh Snapshotter per kick is the right unit. opts := sync.Options{} if cfg.Backups.Enabled { - opts.Snapshot = sync.NewSnapshotter(s, rcl, snapshotConfig(cfg, s.Path())) + opts.Snapshot = sync.NewSnapshotter(s, snapshotConfig(cfg, s.Path())) } rep, runErr := sync.RunPair(ctx, s, syncTools, pair, opts) return agent.SyncRunReport{ @@ -205,14 +206,14 @@ func schedulerPairFor(cfg *config.Config, vol *config.Volume, destName string) ( // never reaches it. func buildSchedulerVerifyRunner(live *config.Live, s *store.Store, tools *schedulerTools) agent.VerifyRunner { return func(ctx context.Context, destName string) agent.VerifyRunReport { - rcl := tools.rclone() - if rcl == nil { - return agent.VerifyRunReport{Status: store.RunStatusFailed, Err: errors.New("scheduled verify needs rclone, which the configuration in force did not call for")} - } dest, ok := live.Get().Destinations[destName] if !ok { return agent.VerifyRunReport{Status: store.RunStatusFailed, Err: fmt.Errorf("destination %q is not declared in config", destName)} } + rcl := tools.rclone() + if rcl == nil && (sync.Pair{Destination: dest}).DrivesRclone() { + return agent.VerifyRunReport{Status: store.RunStatusFailed, Err: errors.New("scheduled verify needs rclone, which the configuration in force did not call for")} + } rep, err := sync.VerifyRemote(ctx, s, rcl, dest) return agent.VerifyRunReport{RunID: rep.RunID, Status: verifyRunStatus(rep, err), Err: err} } diff --git a/cmd/squirrel/agent_scheduler_test.go b/cmd/squirrel/agent_scheduler_test.go index 4dd271a..eacc868 100644 --- a/cmd/squirrel/agent_scheduler_test.go +++ b/cmd/squirrel/agent_scheduler_test.go @@ -61,20 +61,26 @@ func TestAnyDestinationNeedsScheduledVerify(t *testing.T) { cfg := base() cfg.Destinations["m"] = &config.Destination{Layout: config.LayoutMirror, VerifyEvery: time.Hour} - if anyDestinationNeedsScheduledVerify(cfg) { + if anyScheduledVerifyNeedsRclone(cfg) { t.Fatalf("mirror layout must never need scheduled verify") } + cfg = base() + cfg.Destinations["usb"] = &config.Destination{Type: "local", Layout: config.LayoutMirror, VerifyEvery: time.Hour} + if anyScheduledVerifyNeedsRclone(cfg) { + t.Fatalf("a native mirror's scheduled verify must not need rclone") + } + cfg = base() cfg.Destinations["p"] = &config.Destination{Layout: config.LayoutPacked, VerifyEvery: time.Hour} - if !anyDestinationNeedsScheduledVerify(cfg) { + if !anyScheduledVerifyNeedsRclone(cfg) { t.Fatalf("packed destination with own cadence should need verify") } cfg = base() cfg.Agent.VerifyEvery = time.Hour cfg.Destinations["c"] = &config.Destination{Layout: config.LayoutContentAddressed} - if !anyDestinationNeedsScheduledVerify(cfg) { + if !anyScheduledVerifyNeedsRclone(cfg) { t.Fatalf("agent default should cover a verifiable destination with no own cadence") } } @@ -109,3 +115,23 @@ func TestSchedulerToolsRebuildKeepsRclone(t *testing.T) { t.Fatalf("rclone() = %p after a reload that needs none, want the located wrapper %p", got, located) } } + +// TestScheduledSyncToANativeMirrorNeedsNoRclone: squirrel writes a local +// mirror and a plain sftp mirror itself, so a cadence naming only those +// runs on a host without rclone; an encrypted sftp mirror still needs it. +func TestScheduledSyncToANativeMirrorNeedsNoRclone(t *testing.T) { + cfg := &config.Config{ + Volumes: map[string]*config.Volume{"pics": {Name: "pics", SyncEvery: time.Hour, SyncTo: []string{"usb", "box"}}}, + Destinations: map[string]*config.Destination{ + "usb": {Name: "usb", Type: "local", Layout: config.LayoutMirror}, + "box": {Name: "box", Type: "sftp", Layout: config.LayoutMirror}, + }, + } + if anyVolumeNeedsScheduledSync(cfg) { + t.Fatal("a cadence onto native mirrors only must not need rclone") + } + cfg.Destinations["box"].Crypt = &config.Crypt{Password: "pw"} + if !anyVolumeNeedsScheduledSync(cfg) { + t.Fatal("an encrypted sftp mirror is written by rclone") + } +} diff --git a/cmd/squirrel/content_native_test.go b/cmd/squirrel/content_native_test.go new file mode 100644 index 0000000..77b6134 --- /dev/null +++ b/cmd/squirrel/content_native_test.go @@ -0,0 +1,43 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestCLIContentLayoutsOnLocalWithoutRclone: a content-addressed and a +// packed destination on a local disk sync, verify and restore with no +// rclone on PATH, and the sync fingerprints what it landed. +func TestCLIContentLayoutsOnLocalWithoutRclone(t *testing.T) { + for _, layout := range []string{"content-addressed", "packed"} { + t.Run(layout, func(t *testing.T) { + withoutRclone(t) + f := writeSyncFixture(t) + cfg, err := os.ReadFile(f.configPath) + if err != nil { + t.Fatal(err) + } + cfg = []byte(strings.Replace(string(cfg), "type = \"local\"\n", "type = \"local\"\nlayout = \""+layout+"\"\n", 1)) + if err := os.WriteFile(f.configPath, cfg, 0o600); err != nil { + t.Fatal(err) + } + writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") + runCLI(t, "--config", f.configPath, "index", f.volumeName) + + out := runCLI(t, "--config", f.configPath, "sync", "pics") + if !strings.Contains(out, "status=success") || !strings.Contains(out, "fingerprints=1") || strings.Contains(out, "rclone") { + t.Fatalf("sync output = %q, want a fingerprinted success with no rclone preamble", out) + } + if out := runCLI(t, "--config", f.configPath, "verify", "scratch"); !strings.Contains(out, "mismatched=0 missing=0") { + t.Fatalf("verify output = %q, want a clean pass", out) + } + to := t.TempDir() + runCLI(t, "--config", f.configPath, "restore", "pics", "--from", "scratch", "--to", to) + if got, err := os.ReadFile(filepath.Join(to, "a.txt")); err != nil || string(got) != "alpha" { + t.Fatalf("restored a.txt = %q, %v", got, err) + } + }) + } +} diff --git a/cmd/squirrel/destination_reset.go b/cmd/squirrel/destination_reset.go index 88e649b..9b469c0 100644 --- a/cmd/squirrel/destination_reset.go +++ b/cmd/squirrel/destination_reset.go @@ -107,11 +107,11 @@ func printResetPreview(out io.Writer, name string, c store.DestinationResetCount func printResetResult(out io.Writer, name string, c store.DestinationResetCounts, runID int64) { fmt.Fprintf(out, "reset destination %q (run %d):\n", name, runID) printResetCounts(out, c) - fmt.Fprintf(out, "next: the next sync re-uploads to %q; for a content-addressed or packed layout, wipe or repoint the remote root so the layout guard sees a fresh start\n", name) + fmt.Fprintf(out, "next: the next sync re-uploads to %q; for a content-addressed, packed or native mirror layout, wipe or repoint the remote root so the layout guard sees a fresh start\n", name) } func printResetCounts(out io.Writer, c store.DestinationResetCounts) { - fmt.Fprintf(out, " upload records: %d objects, %d packs\n", c.RemoteObjects, c.RemotePacks) + fmt.Fprintf(out, " upload records: %d objects, %d packs, %d mirror paths\n", c.RemoteObjects, c.RemotePacks, c.RemotePaths) fmt.Fprintf(out, " durability vector: %d component(s)\n", c.VectorComponents) fmt.Fprintf(out, " push freshness: %d row(s)\n", c.FreshnessRows) } diff --git a/cmd/squirrel/main_test.go b/cmd/squirrel/main_test.go index 58a40b9..db472b5 100644 --- a/cmd/squirrel/main_test.go +++ b/cmd/squirrel/main_test.go @@ -24,6 +24,13 @@ func requireRcloneCLI(t *testing.T) { } } +// withoutRclone hides rclone from the test: PATH names only an empty +// directory, so a command that reached for rclone would fail to find it. +func withoutRclone(t *testing.T) { + t.Helper() + t.Setenv("PATH", t.TempDir()) +} + // syncFixturePaths bundles the paths writeSyncFixture lays down so callers // can pass them straight to the CLI via --config / --db. type syncFixturePaths struct { diff --git a/cmd/squirrel/recover.go b/cmd/squirrel/recover.go index c740bb8..15c532e 100644 --- a/cmd/squirrel/recover.go +++ b/cmd/squirrel/recover.go @@ -70,6 +70,7 @@ type recoverOptions struct { // before agreeing to its first step. type recoverPlan struct { dest *config.Destination + rcl *sync.Rclone // nil for a native destination, which squirrel reads itself volumes []string snapshots []sync.IndexSnapshot chosen sync.IndexSnapshot @@ -123,14 +124,11 @@ func discoverRecovery(cmd *cobra.Command, cfg *config.Config, opts recoverOption cfg.Path, opts.From) } - rcl, err := sync.Find(cmd.Context()) - if err != nil { - return recoverPlan{}, err - } - if err := writeRcloneConfigLogged(cmd.OutOrStdout(), rcl, cfg); err != nil { + var err error + if plan.rcl, err = rcloneFor(cmd, cfg, dest); err != nil { return recoverPlan{}, err } - plan.snapshots, err = sync.DiscoverIndexSnapshots(cmd.Context(), rcl, dest, plan.volumes) + plan.snapshots, err = sync.DiscoverIndexSnapshots(cmd.Context(), plan.rcl, dest, plan.volumes) if err != nil { return recoverPlan{}, err } @@ -242,10 +240,6 @@ func recoverIndexPhase(cmd *cobra.Command, plan recoverPlan, opts recoverOptions return false, nil } - rcl, err := sync.Find(cmd.Context()) - if err != nil { - return false, err - } dir, err := os.MkdirTemp("", "squirrel-recover-") if err != nil { return false, fmt.Errorf("create staging directory: %w", err) @@ -254,7 +248,7 @@ func recoverIndexPhase(cmd *cobra.Command, plan recoverPlan, opts recoverOptions staged := filepath.Join(dir, plan.chosen.Name) fmt.Fprintf(out, "fetching %s …\n", plan.chosen.Name) - if err := sync.FetchIndexSnapshot(cmd.Context(), rcl, plan.dest, plan.chosen, staged); err != nil { + if err := sync.FetchIndexSnapshot(cmd.Context(), plan.rcl, plan.dest, plan.chosen, staged); err != nil { return false, err } // runDBRestore preflights the schema version, refuses to clobber a live diff --git a/cmd/squirrel/recover_test.go b/cmd/squirrel/recover_test.go index dcd9cb7..ef250ba 100644 --- a/cmd/squirrel/recover_test.go +++ b/cmd/squirrel/recover_test.go @@ -76,7 +76,7 @@ func TestRecoverRejectsPeerNode(t *testing.T) { // catalog is a real state, and the message has to say what is still // possible rather than only what failed. func TestRecoverWithoutSnapshotsExplains(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, _ := recoverConfig(t) out, err := runCLIExpectErr(t, "--config", cfgPath, "recover", "--from", "scratch") joined := out + err.Error() @@ -93,7 +93,7 @@ func TestRecoverWithoutSnapshotsExplains(t *testing.T) { // runs `squirrel recover --from X` to find out what is there must not // discover they have started a recovery. func TestRecoverDryRunTouchesNothing(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, destRoot := recoverConfig(t) newest := "index-20260807T120000.000Z-run-42.db" seedSnapshots(t, destRoot, "photos", "index-20260101T090000.000Z-run-7.db", newest) @@ -119,7 +119,7 @@ func TestRecoverDryRunTouchesNothing(t *testing.T) { // TestRecoverRejectsUnknownSnapshot: naming a snapshot that is not there // stops before any fetch, and says how to see the real list. func TestRecoverRejectsUnknownSnapshot(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, destRoot := recoverConfig(t) seedSnapshots(t, destRoot, "photos", "index-20260807T120000.000Z-run-42.db") @@ -171,7 +171,7 @@ func TestSnapshotAgeUnknownIsSaid(t *testing.T) { // which is itself the property worth pinning: absence of an answer is not // consent. func TestRecoverDeclinedPhaseStopsTheSequence(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, destRoot := recoverConfig(t) seedSnapshots(t, destRoot, "photos", "index-20260807T120000.000Z-run-42.db") diff --git a/cmd/squirrel/restore.go b/cmd/squirrel/restore.go index b5b1b71..e43e653 100644 --- a/cmd/squirrel/restore.go +++ b/cmd/squirrel/restore.go @@ -32,7 +32,7 @@ func newRestoreCmd() *cobra.Command { ) cmd := &cobra.Command{ Use: "restore ", - Short: "Pull a volume back from one of its rclone destinations", + Short: "Pull a volume back from one of its destinations", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return runRestore(cmd, args[0], from, sync.RestoreOptions{ @@ -45,8 +45,8 @@ func newRestoreCmd() *cobra.Command { } cmd.Flags().StringVar(&from, "from", "", "destination name to pull from, or peer node name to filter by content origin (overloaded; names are unique across both kinds)") cmd.Flags().StringVar(&to, "to", "", "local target path (default: the volume's declared path)") - cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on the way down") - cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview rclone actions without transferring") + cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on the way down from an rclone mirror (every other destination's bytes are always re-hashed)") + cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview what the restore would fetch without transferring") cmd.Flags().BoolVar(&inPlace, "in-place", false, "permit restore against a non-empty live vol.Path; overwritten files are moved to .squirrel-restore-history/run-/") return cmd } @@ -84,17 +84,14 @@ func runRestore(cmd *cobra.Command, volumeName, fromName string, opts sync.Resto opts.IncludeFromFile = includeFile } - rcl, err := sync.Find(cmd.Context()) + rcl, err := rcloneFor(cmd, cfg, dest) if err != nil { return err } out := cmd.OutOrStdout() - if opts.Shallow { + if opts.Shallow && rcl != nil { fmt.Fprintln(out, shallowSyncWarning) } - if err := writeRcloneConfigLogged(out, rcl, cfg); err != nil { - return err - } rep, runErr := sync.Restore(cmd.Context(), s, rcl, vol, dest, opts) // Restore pulls destination → local, so flip the arrow: the sync-shaped diff --git a/cmd/squirrel/restore_test.go b/cmd/squirrel/restore_test.go index 5d6d25a..5f53b8f 100644 --- a/cmd/squirrel/restore_test.go +++ b/cmd/squirrel/restore_test.go @@ -17,7 +17,7 @@ import ( // remove the local copy, restore from the destination, and verify the // contents match. func TestCLIRestoreRoundTrip(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") writeTestFile(t, filepath.Join(f.volumeDir, "b.txt"), "beta") @@ -63,7 +63,7 @@ func TestCLIRestoreRoundTrip(t *testing.T) { // TestCLIRestoreToPathOverridesVolumePath confirms --to writes to the // override directory rather than the volume's declared path. func TestCLIRestoreToPathOverridesVolumePath(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") @@ -92,7 +92,7 @@ func TestCLIRestoreToPathOverridesVolumePath(t *testing.T) { // TestCLIRestoreRecordsRunsRowWithKindRestore verifies that the restore // command produces a runs row distinguishable from sync runs. func TestCLIRestoreRecordsRunsRowWithKindRestore(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") runCLI(t, "--config", f.configPath, "index", f.volumeName) @@ -110,7 +110,7 @@ func TestCLIRestoreRecordsRunsRowWithKindRestore(t *testing.T) { // candidate is picked automatically. This is the common case and the // counterpart to TestCLIRestoreNeedsExplicitFromWhenAmbiguous. func TestCLIRestoreInfersDestinationWhenUnambiguous(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") @@ -137,7 +137,7 @@ func TestCLIRestoreInfersDestinationWhenUnambiguous(t *testing.T) { // introduction), and syncs the tree. Restoring with --from peer-a // should land only the from-a path in the target tree. func TestCLIRestoreFromNodeFiltersByAttribution(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "local.txt"), "local") diff --git a/cmd/squirrel/status_test.go b/cmd/squirrel/status_test.go index fbc9b1d..08301cd 100644 --- a/cmd/squirrel/status_test.go +++ b/cmd/squirrel/status_test.go @@ -77,7 +77,7 @@ func TestCLIStatusNeverSyncedIsAmber(t *testing.T) { // TestCLIStatusAfterSyncIsGreen: once a fresh sync lands, the pair is // caught up within cadence and the command exits 0. func TestCLIStatusAfterSyncIsGreen(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) cfg := writeStatusConfig(t) runCLI(t, "--config", cfg, "index", "pics") runCLI(t, "--config", cfg, "sync", "pics", "--init") diff --git a/cmd/squirrel/sync.go b/cmd/squirrel/sync.go index 9099c98..e2bc842 100644 --- a/cmd/squirrel/sync.go +++ b/cmd/squirrel/sync.go @@ -26,7 +26,7 @@ func newSyncCmd() *cobra.Command { ) cmd := &cobra.Command{ Use: "sync []", - Short: "Push configured volumes to their rclone destinations", + Short: "Push configured volumes to their destinations", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { volumeName := "" @@ -41,8 +41,8 @@ func newSyncCmd() *cobra.Command { }, } cmd.Flags().StringVar(&to, "to", "", "limit to this destination name (default: every destination declared on the volume)") - cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison; trust rclone's default size+mtime comparison") - cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview rclone actions without transferring; no runs row is written") + cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on an rclone mirror; trust rclone's default size+mtime comparison (refused on a native mirror: local, or sftp without crypt)") + cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview what a push would transfer without transferring; no runs row is written") cmd.Flags().BoolVar(&initDst, "init", false, "authorise first-use destination bootstrap: write a .squirrel-volume marker, or create a kopia repository when connect finds none (refused without --init so a typo or outage can't mint a fresh empty target)") cmd.Flags().BoolVarP(&progress, "progress", "P", false, "show live transfer progress (auto-enabled on a terminal; use --progress=false to force off)") return cmd @@ -91,7 +91,7 @@ func runSync(cmd *cobra.Command, volumeName, destinationName string, progress bo // for dry-run (no run rows to snapshot against) and when [backups] is // turned off. if !opts.DryRun && cfg.Backups.Enabled { - opts.Snapshot = sync.NewSnapshotter(s, rcl, snapshotConfig(cfg, s.Path())) + opts.Snapshot = sync.NewSnapshotter(s, snapshotConfig(cfg, s.Path())) } // Progress renders to stderr (leaving stdout for the summary lines). A @@ -152,6 +152,23 @@ func rcloneConfigPathFor(cfg *config.Config) string { return filepath.Join(filepath.Dir(cfg.Path), "rclone.conf") } +// rcloneFor locates rclone and renders its config for reading dest. A +// native destination is read through squirrel's own transport, so it gets +// a nil wrapper and no rclone preamble. +func rcloneFor(cmd *cobra.Command, cfg *config.Config, dest *config.Destination) (*sync.Rclone, error) { + if dest.Native() { + return nil, nil + } + rcl, err := sync.Find(cmd.Context()) + if err != nil { + return nil, err + } + if err := writeRcloneConfigLogged(cmd.OutOrStdout(), rcl, cfg); err != nil { + return nil, err + } + return rcl, nil +} + // writeRcloneConfigLogged renders the rclone.conf and logs a single line // when the file actually changed. An unexpected rewrite is worth // surfacing: the config is derived deterministically from squirrel's @@ -264,8 +281,8 @@ func printSyncReport(w io.Writer, rep sync.Report, runErr error, reverse bool) { // an empty one — transferred=0 alone is ambiguous (friction F7). func printSyncSummaryLine(w io.Writer, rep sync.Report, src, dst string) { r := rep.RcloneResult - switch rep.Verification.Method { - case sync.VerifyMethodKopia: + switch { + case rep.Verification.Method == sync.VerifyMethodKopia: // Kopia pushes have no rclone counters; render the snapshot's // own numbers instead. fmt.Fprintf(w, "%s → %s status=%s files=%d bytes=%d snapshot=%s verified=%t run=%d\n", @@ -273,7 +290,7 @@ func printSyncSummaryLine(w io.Writer, rep sync.Report, src, dst string) { rep.Verification.Files, rep.Verification.Bytes, rep.Verification.SnapshotID, rep.Verification.Verified(), rep.RunID, ) - case sync.VerifyMethodPresenceSize: + case rep.Layout == config.LayoutContentAddressed || rep.Layout == config.LayoutPacked: // Content-addressed pushes count objects, with skipped = hashes // the destination already recorded, entries = manifest segment // lines, and fingerprints = provider checksums captured for the diff --git a/cmd/squirrel/sync_test.go b/cmd/squirrel/sync_test.go index dcedf01..cbf4101 100644 --- a/cmd/squirrel/sync_test.go +++ b/cmd/squirrel/sync_test.go @@ -9,7 +9,7 @@ import ( ) func TestCLISyncErrorsWhenVolumeNotIndexed(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") @@ -21,7 +21,7 @@ func TestCLISyncErrorsWhenVolumeNotIndexed(t *testing.T) { } func TestCLISyncHappyPath(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") writeTestFile(t, filepath.Join(f.volumeDir, "b.txt"), "beta") @@ -46,7 +46,7 @@ func TestCLISyncHappyPath(t *testing.T) { // volume reports already_correct so an in-sync no-op is distinguishable // from an empty one (transferred=0 alone is ambiguous). func TestCLISyncAlreadyCorrect(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") writeTestFile(t, filepath.Join(f.volumeDir, "b.txt"), "beta") @@ -143,7 +143,7 @@ func TestCLISyncRequiresConfig(t *testing.T) { // sync/. We verify (a) the command succeeds and prints a report, (b) // nothing lands at the destination, and (c) no new runs row is recorded. func TestCLISyncDryRun(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") runCLI(t, "--config", f.configPath, "index", f.volumeName) @@ -175,7 +175,7 @@ func TestCLISyncMissingExplicitConfigErrors(t *testing.T) { } func TestCLISyncRunsRowVisibleViaRunsCommand(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") diff --git a/cmd/squirrel/verify.go b/cmd/squirrel/verify.go index e160a72..1d6aa4c 100644 --- a/cmd/squirrel/verify.go +++ b/cmd/squirrel/verify.go @@ -3,6 +3,7 @@ package main import ( "fmt" "io" + "slices" "sort" "github.com/spf13/cobra" @@ -53,12 +54,9 @@ func runVerify(cmd *cobra.Command, destName string) error { } defer s.Close() - rcl, err := sync.Find(cmd.Context()) - if err != nil { - return err - } out := cmd.OutOrStdout() - if err := writeRcloneConfigLogged(out, rcl, cfg); err != nil { + rcl, err := verifyRclone(cmd, cfg, names) + if err != nil { return err } @@ -76,58 +74,77 @@ func runVerify(cmd *cobra.Command, destName string) error { return nil } +// verifyRclone locates rclone and renders its config when a target is +// reached through it; a native destination is verified without it. +func verifyRclone(cmd *cobra.Command, cfg *config.Config, names []string) (*sync.Rclone, error) { + if !slices.ContainsFunc(names, func(name string) bool { + return sync.Pair{Destination: cfg.Destinations[name]}.DrivesRclone() + }) { + return nil, nil + } + rcl, err := sync.Find(cmd.Context()) + if err != nil { + return nil, err + } + if err := writeRcloneConfigLogged(cmd.OutOrStdout(), rcl, cfg); err != nil { + return nil, err + } + return rcl, nil +} + // verifyTargetNames resolves the verification subjects in deterministic -// order: an explicit destination (validated to exist and be -// content-addressed or packed), or every such destination in config. +// order: an explicit destination (validated to exist and be verifiable), +// or every verifiable destination in config. func verifyTargetNames(cfg *config.Config, destName string) ([]string, error) { if destName != "" { d, ok := cfg.Destinations[destName] if !ok { return nil, fmt.Errorf("unknown destination %q (declare it in %s)", destName, cfg.Path) } - if !verifiableLayout(d.Layout) { - return nil, fmt.Errorf("destination %q has layout %q — verify covers the recorded objects and packs of content-addressed and packed destinations", destName, d.Layout) + if !d.Verifiable() { + return nil, fmt.Errorf("destination %q is an rclone mirror — verify covers the recorded objects and packs of content-addressed and packed destinations, and the recorded copies of a mirror squirrel writes itself (local, or sftp without crypt)", destName) } return []string{destName}, nil } var names []string for name, d := range cfg.Destinations { - if verifiableLayout(d.Layout) { + if d.Verifiable() { names = append(names, name) } } if len(names) == 0 { - return nil, fmt.Errorf("no content-addressed or packed destinations declared in %s", cfg.Path) + return nil, fmt.Errorf("no verifiable destinations declared in %s: verify covers content-addressed and packed destinations and native mirrors", cfg.Path) } sort.Strings(names) return names, nil } -// verifiableLayout reports whether a destination's layout keeps per-object -// or per-pack fingerprints that `squirrel verify` re-checks. -func verifiableLayout(layout string) bool { - return layout == config.LayoutContentAddressed || layout == config.LayoutPacked -} - // printVerifyReport renders one destination's pass: a loud stderr line // per missing or mismatched object or pack, then the summary counters, // then the standing-alarm transition this pass caused (#157, F30). func printVerifyReport(out, errOut io.Writer, rep sync.RemoteVerifyReport, runErr error) { printVerifyFailures(errOut, "object", rep.Destination, rep.Missing, rep.Mismatched) printVerifyFailures(errOut, "pack", rep.Destination, rep.PacksMissing, rep.PackMismatched) + printMirrorFailures(errOut, rep) if runErr != nil { fmt.Fprintf(errOut, "verify %s: %v\n", rep.Destination, runErr) return } + if rep.Paths > 0 { + fmt.Fprintf(out, "verify %s: run=%d copies=%d reread=%d changed=%d missing=%d\n", + rep.Destination, rep.RunID, rep.Paths, rep.PathsReread, len(rep.PathsChanged), len(rep.PathsMissing)) + printVerifyAlarmTransition(out, errOut, rep) + return + } if rep.Objects == 0 && rep.Packs == 0 { - fmt.Fprintf(out, "verify %s: no recorded objects or packs\n", rep.Destination) + fmt.Fprintf(out, "verify %s: nothing recorded to verify\n", rep.Destination) return } - fmt.Fprintf(out, "verify %s: run=%d objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d\n", + fmt.Fprintf(out, "verify %s: run=%d objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d unchecked=%d\n", rep.Destination, rep.RunID, rep.Objects, rep.Verified, rep.Populated, rep.Pending, len(rep.Mismatched), len(rep.Missing), rep.Unrecorded, rep.Packs, rep.PacksVerified, rep.PacksPopulated, rep.PacksPending, - len(rep.PackMismatched), len(rep.PacksMissing)) + len(rep.PackMismatched), len(rep.PacksMissing), rep.Unchecked) printVerifyAlarmTransition(out, errOut, rep) } @@ -144,6 +161,18 @@ func printVerifyAlarmTransition(out, errOut io.Writer, rep sync.RemoteVerifyRepo } } +// printMirrorFailures writes one stderr line per mirror copy the pass found +// gone or changed; the next push writes each one again that the index still +// holds. +func printMirrorFailures(errOut io.Writer, rep sync.RemoteVerifyReport) { + for _, name := range rep.PathsMissing { + fmt.Fprintf(errOut, "error: copy %s on %q: recorded as stored but absent\n", name, rep.Destination) + } + for _, name := range rep.PathsChanged { + fmt.Fprintf(errOut, "error: copy %s on %q: its size, mtime or BLAKE3 no longer matches what squirrel stored — possible corruption or tampering\n", name, rep.Destination) + } +} + // printVerifyFailures writes one stderr line per missing or mismatched // artifact (an object or a pack), naming the kind so a mixed destination's // failures stay distinguishable. diff --git a/cmd/squirrel/verify_test.go b/cmd/squirrel/verify_test.go index cdf702d..f45aca2 100644 --- a/cmd/squirrel/verify_test.go +++ b/cmd/squirrel/verify_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/mbertschler/squirrel/config" "github.com/mbertschler/squirrel/sync" ) @@ -16,18 +17,28 @@ func TestVerifyUnknownDestination(t *testing.T) { } } -func TestVerifyRefusesMirrorDestination(t *testing.T) { +// TestVerifyNativeMirrorNeedsNoRclone: a local mirror is verifiable, and a +// pass over one with nothing recorded yet runs without rclone. +func TestVerifyNativeMirrorNeedsNoRclone(t *testing.T) { fx := writeSyncFixture(t) - _, err := runCLIExpectErr(t, "verify", "scratch", "--config", fx.configPath) - if !strings.Contains(err.Error(), "content-addressed") { - t.Fatalf("err = %v, want content-addressed refusal", err) + t.Setenv("PATH", t.TempDir()) + out := runCLI(t, "verify", "scratch", "--config", fx.configPath) + if !strings.Contains(out, "verify scratch: nothing recorded to verify") { + t.Fatalf("output = %q, want the empty summary", out) } } -func TestVerifyNoContentAddressedDestinations(t *testing.T) { - fx := writeSyncFixture(t) - _, err := runCLIExpectErr(t, "verify", "--config", fx.configPath) - if !strings.Contains(err.Error(), "no content-addressed or packed destinations") { +// TestVerifyTargetNamesRefusesRcloneMirrors: an rclone mirror records +// nothing to re-check, so naming one is refused, and a config holding only +// such mirrors has no verify targets. +func TestVerifyTargetNamesRefusesRcloneMirrors(t *testing.T) { + cfg := &config.Config{Path: "squirrel.toml", Destinations: map[string]*config.Destination{ + "cloudbox": {Name: "cloudbox", Type: "sftp", Layout: config.LayoutMirror, Crypt: &config.Crypt{Password: "x"}}, + }} + if _, err := verifyTargetNames(cfg, "cloudbox"); err == nil || !strings.Contains(err.Error(), "rclone mirror") { + t.Fatalf("err = %v, want an rclone-mirror refusal", err) + } + if _, err := verifyTargetNames(cfg, ""); err == nil || !strings.Contains(err.Error(), "no verifiable destinations") { t.Fatalf("err = %v, want no-destinations refusal", err) } } @@ -38,7 +49,7 @@ func TestVerifyNoContentAddressedDestinations(t *testing.T) { func TestPrintVerifyReportErrorSuppressesSummary(t *testing.T) { var out, errOut strings.Builder printVerifyReport(&out, &errOut, sync.RemoteVerifyReport{Destination: "offsite"}, errors.New("rclone exploded")) - if strings.Contains(out.String(), "no recorded objects") || out.Len() != 0 { + if out.Len() != 0 { t.Fatalf("stdout = %q, want empty on an error run", out.String()) } if !strings.Contains(errOut.String(), "rclone exploded") { @@ -51,7 +62,7 @@ func TestPrintVerifyReportErrorSuppressesSummary(t *testing.T) { func TestPrintVerifyReportCleanEmptyShowsSummary(t *testing.T) { var out, errOut strings.Builder printVerifyReport(&out, &errOut, sync.RemoteVerifyReport{Destination: "offsite"}, nil) - if !strings.Contains(out.String(), "no recorded objects") { + if !strings.Contains(out.String(), "nothing recorded to verify") { t.Fatalf("stdout = %q, want the no-objects summary on a clean run", out.String()) } } diff --git a/config/config.go b/config/config.go index 2aedbb7..1a7ee48 100644 --- a/config/config.go +++ b/config/config.go @@ -186,6 +186,10 @@ type Destination struct { // invocations against this destination, for providers that cap // simultaneous connections. Zero leaves rclone's default in force. Checkers int + // Concurrency is how many files a push writes at once: squirrel's own + // paths in flight on a local or plain sftp destination, rclone's + // --transfers on one rclone writes. Zero leaves the default in force. + Concurrency int // PathStyle forces path-style bucket addressing (bucket in the URL // path, not the host) for the direct S3 client that reads scan-back // ETags. Settable on s3 destinations only, for S3-compatible providers @@ -531,7 +535,7 @@ func rejectUnsatisfiableOffloadRequires(names []string, dests map[string]*Destin continue } if capable, reason := d.CanEverGateOffload(); !capable { - return fmt.Errorf("offload_requires names %q, which can never satisfy the durability gate (%s); require a content-addressed or packed destination, a kopia repository, or a peer node instead", n, reason) + return fmt.Errorf("offload_requires names %q, which can never satisfy the durability gate (%s); require a local mirror, a content-addressed or packed destination, a kopia repository, or a peer node instead", n, reason) } } return nil diff --git a/config/config_test.go b/config/config_test.go index 8e5ae61..7dd6938 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -323,24 +323,50 @@ offload_requires = ["cloudbox"] } } -// TestLoadRejectsPlainMirrorOffloadRequires: a plain mirror's sync is -// compared by rclone's checksum under a hash rclone picks, never the -// index's BLAKE3, so it can no more gate offload than a crypt mirror can -// (#211). Naming one fails at load. -func TestLoadRejectsPlainMirrorOffloadRequires(t *testing.T) { +// TestLoadRejectsSFTPMirrorOffloadRequires: a native sftp mirror reads +// nothing back and never hashes a mirror path on the server, so it can no +// more gate offload than a crypt mirror can. Naming one fails at load, and +// the reason says why. +func TestLoadRejectsSFTPMirrorOffloadRequires(t *testing.T) { + p := writeConfig(t, ` +[destinations.box] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" + +[volumes.docs] +path = "/tmp/docs" +sync_to = ["box"] +offload_requires = ["box"] +`) + _, err := Load(p) + if err == nil || !strings.Contains(err.Error(), "can never satisfy the durability gate") || !strings.Contains(err.Error(), "reads nothing back") { + t.Fatalf("expected sftp-mirror offload_requires rejection naming the reason, got %v", err) + } +} + +// TestLoadAcceptsLocalMirrorOffloadRequires: a native local mirror reads +// every copy back through BLAKE3, so it may gate offload, with a verify +// cadence re-reading its copies. +func TestLoadAcceptsLocalMirrorOffloadRequires(t *testing.T) { p := writeConfig(t, ` [destinations.usb] -type = "local" -root = "/media/usb" +type = "local" +root = "/media/usb" +verify_every = "168h" [volumes.docs] path = "/tmp/docs" sync_to = ["usb"] offload_requires = ["usb"] `) - _, err := Load(p) - if err == nil || !strings.Contains(err.Error(), "can never satisfy the durability gate") { - t.Fatalf("expected plain-mirror offload_requires rejection, got %v", err) + cfg, err := Load(p) + if err != nil { + t.Fatalf("Load: %v", err) + } + if !cfg.VerifyCadencedTargets([]string{"usb"})["usb"] { + t.Fatal("the local mirror's verify cadence does not count for the gate") } } @@ -1596,14 +1622,20 @@ secret_access_key = { env = "K" } } } -// TestLoadRejectsVerifyEveryOnMirror rejects verify_every on a layout that -// keeps no per-object fingerprints — verify has nothing to re-check there. +// TestLoadRejectsVerifyEveryOnMirror rejects verify_every on an rclone +// mirror, which keeps no records of what it stored — verify has nothing to +// re-check there. func TestLoadRejectsVerifyEveryOnMirror(t *testing.T) { p := writeConfig(t, ` -[destinations.usb] -type = "local" -root = "/media/usb" +[destinations.cloudbox] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" verify_every = "168h" + +[destinations.cloudbox.crypt] +password = "obscured-pw" `) _, err := Load(p) if err == nil || !strings.Contains(err.Error(), "verify_every requires") { diff --git a/config/destinations.go b/config/destinations.go index 24f24b2..d20e3af 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -146,11 +146,12 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } - hashAlgo, err := resolveHashAlgo(raw, typ, layout) + native := isNative(typ, crypt != nil) + hashAlgo, err := resolveHashAlgo(raw, typ, layout, native) if err != nil { return nil, err } - checkers, err := resolveCheckers(raw, typ) + checkers, concurrency, err := resolveParallelism(raw, typ, native) if err != nil { return nil, err } @@ -162,7 +163,7 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } - verifyEvery, err := resolveVerifyEvery(raw, layout) + verifyEvery, err := resolveVerifyEvery(raw, verifiable(layout, native && isMirrorLayout(layout))) if err != nil { return nil, err } @@ -172,7 +173,7 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { } return &Destination{ Name: name, Type: typ, Root: root, Layout: layout, Params: params, - Crypt: crypt, HashAlgo: hashAlgo, Checkers: checkers, PathStyle: pathStyle, + Crypt: crypt, HashAlgo: hashAlgo, Checkers: checkers, Concurrency: concurrency, PathStyle: pathStyle, PackThreshold: pack.threshold, PackSize: pack.size, ZstdLevel: pack.zstdLevel, VerifyEvery: verifyEvery, }, nil @@ -232,13 +233,13 @@ func resolveCryptAndLayout(raw map[string]any, typ string) (*Crypt, string, erro // resolveVerifyEvery validates the optional per-destination `verify_every` // cadence that drives the agent's scheduled re-check of this destination's -// recorded objects and packs (the same pass as `squirrel verify`). It is -// meaningful only on the content-addressed and packed layouts that keep -// per-artifact fingerprints, so a present key on any other layout is -// rejected rather than silently ignored — a mirror destination has nothing -// for verify to re-check. Empty stays zero: no per-destination cadence, an -// [agent] verify_every default may still apply. -func resolveVerifyEvery(raw map[string]any, layout string) (time.Duration, error) { +// records (the same pass as `squirrel verify`). It is meaningful only where +// squirrel records what it stored — the content-addressed and packed +// layouts' objects and packs, a native mirror's copies — so a present key +// on an rclone mirror is rejected rather than silently ignored. Empty stays +// zero: no per-destination cadence, an [agent] verify_every default may +// still apply. +func resolveVerifyEvery(raw map[string]any, verifiable bool) (time.Duration, error) { v, err := optionalString(raw, "verify_every") if err != nil { return 0, err @@ -246,54 +247,70 @@ func resolveVerifyEvery(raw map[string]any, layout string) (time.Duration, error if v == "" { return 0, nil } - if layout != LayoutContentAddressed && layout != LayoutPacked { - return 0, fmt.Errorf("verify_every requires the %q or %q layout; layout %q keeps no per-object fingerprints to re-check", LayoutContentAddressed, LayoutPacked, layout) + if !verifiable { + return 0, fmt.Errorf("verify_every requires the %q or %q layout, or a mirror squirrel writes itself (local, or sftp without crypt): an rclone mirror keeps no records of what it stored to re-check", LayoutContentAddressed, LayoutPacked) } return parseVolumeCadence("verify_every", v) } // sftpHashAlgos are the checksum types rclone's sftp backend can read -// via a server-side sum command, the valid values for `hash_algo`. +// via a server-side sum command, the valid values for `hash_algo` on an +// sftp destination rclone writes. var sftpHashAlgos = map[string]bool{ "md5": true, "sha1": true, "sha256": true, "crc32": true, "blake3": true, "xxh3": true, "xxh128": true, } -// resolveHashAlgo validates the optional `hash_algo` key. sftp is the -// one backend where rclone must be told which server-side hash command -// to run; every other type exposes a fixed checksum, so the key is -// rejected there. Content-addressed sftp destinations default to -// "sha256" so scan-back fingerprints get a strong checksum without -// relying on rclone's md5/sha1 preference. -func resolveHashAlgo(raw map[string]any, typ, layout string) (string, error) { +// nativeHashAlgos are the valid values for `hash_algo` on a content- +// addressed or packed sftp destination squirrel writes itself: the hashes +// whose server command (md5sum, sha1sum, sha256sum, b3sum) squirrel runs, +// and which it computes itself to check the server's answer. +var nativeHashAlgos = map[string]bool{"md5": true, "sha1": true, "sha256": true, "blake3": true} + +// resolveHashAlgo validates the optional `hash_algo` key: which hash +// command the sftp server runs to fingerprint what squirrel stored. Every +// other type exposes a fixed checksum, so the key is rejected there, and +// so is it on a native sftp mirror, which runs no command on the server. +// Content-addressed sftp destinations, and packed ones squirrel writes +// itself, default to "sha256" so fingerprints get a strong checksum. +func resolveHashAlgo(raw map[string]any, typ, layout string, native bool) (string, error) { v, err := optionalString(raw, "hash_algo") if err != nil { return "", err } if v == "" { - if typ == "sftp" && layout == LayoutContentAddressed { + if typ == "sftp" && (layout == LayoutContentAddressed || (native && layout == LayoutPacked)) { return "sha256", nil } return "", nil } - if typ != "sftp" { + allowed := sftpHashAlgos + switch { + case typ != "sftp": return "", fmt.Errorf(`hash_algo is only supported on type "sftp" destinations; type %q exposes a fixed checksum`, typ) + case native && isMirrorLayout(layout): + return "", errors.New("hash_algo names the hash command run on the sftp server, and a mirror without crypt runs none: squirrel writes it itself and hashes every file as it sends it") + case native: + allowed = nativeHashAlgos } - if !sftpHashAlgos[v] { - return "", fmt.Errorf("unknown hash_algo %q (supported: %v)", v, sortedKeys(sftpHashAlgos)) + if !allowed[v] { + return "", fmt.Errorf("unknown hash_algo %q (supported: %v)", v, sortedKeys(allowed)) } return v, nil } // resolveCheckers validates the optional `checkers` key: a positive -// integer cap on rclone's concurrent checkers for this destination. -func resolveCheckers(raw map[string]any, typ string) (int, error) { +// integer cap on rclone's concurrent checkers for this destination. A +// native destination runs no rclone, so the key is rejected there. +func resolveCheckers(raw map[string]any, typ string, native bool) (int, error) { v, ok := raw["checkers"] if !ok { return 0, nil } - switch typ { - case "local", "kopia": + switch { + case native: + return 0, fmt.Errorf("checkers caps rclone's checkers, and a type %q destination without crypt is written by squirrel itself, without rclone", typ) + case typ == "kopia": return 0, fmt.Errorf("checkers requires an rclone-remote destination type, not %q", typ) } n, isInt := v.(int64) @@ -303,6 +320,34 @@ func resolveCheckers(raw map[string]any, typ string) (int, error) { return int(n), nil } +// resolveParallelism validates the keys that cap how much a push does at +// once: `checkers` and `concurrency`. +func resolveParallelism(raw map[string]any, typ string, native bool) (checkers, concurrency int, err error) { + if checkers, err = resolveCheckers(raw, typ, native); err != nil { + return 0, 0, err + } + concurrency, err = resolveConcurrency(raw, typ) + return checkers, concurrency, err +} + +// resolveConcurrency validates the optional `concurrency` key: a positive +// integer, how many files a push writes at once. Kopia drives its own +// parallelism, so the key is rejected there. +func resolveConcurrency(raw map[string]any, typ string) (int, error) { + v, ok := raw["concurrency"] + if !ok { + return 0, nil + } + if typ == "kopia" { + return 0, errors.New("concurrency sets how many files squirrel or rclone writes at once, and a kopia destination is written by kopia") + } + n, isInt := v.(int64) + if !isInt || n <= 0 { + return 0, errors.New("concurrency must be a positive integer") + } + return int(n), nil +} + // resolvePathStyle validates the optional `force_path_style` key: a // boolean confined to s3 destinations, consumed by the direct S3 ETag // client (not rendered into rclone.conf — it governs only squirrel's own @@ -333,9 +378,8 @@ func sortedKeys(m map[string]bool) []string { // resolveLayout validates the optional `layout` key of a destination. An // absent key resolves to LayoutMirror. LayoutContentAddressed and -// LayoutPacked drive squirrel's own rclone transfers, so both require an -// rclone-remote type: type "local" is addressed by filesystem path, and -// "kopia" repositories already use kopia's own content-addressed format. +// LayoutPacked are squirrel's own formats, on any type but "kopia", whose +// repositories already use kopia's own content-addressed format. func resolveLayout(raw map[string]any, typ string) (string, error) { v, err := optionalString(raw, "layout") if err != nil { @@ -345,8 +389,8 @@ func resolveLayout(raw map[string]any, typ string) (string, error) { case "", LayoutMirror: return LayoutMirror, nil case LayoutContentAddressed, LayoutPacked: - if err := requireRcloneRemote(v, typ); err != nil { - return "", err + if typ == "kopia" { + return "", fmt.Errorf(`layout %q does not apply to type "kopia": kopia repositories are content-addressed by kopia itself`, v) } return v, nil default: @@ -354,21 +398,6 @@ func resolveLayout(raw map[string]any, typ string) (string, error) { } } -// requireRcloneRemote rejects the two rclone-remote-only layouts on the -// destination types that can't drive per-object squirrel transfers: type -// "local" is a filesystem path, and "kopia" runs its own content-addressed -// binary. Shared by the LayoutContentAddressed and LayoutPacked branches so -// both give the same guardrail message. -func requireRcloneRemote(layout, typ string) error { - switch typ { - case "local": - return fmt.Errorf(`layout %q requires an rclone-remote destination; type "local" is addressed by filesystem path`, layout) - case "kopia": - return fmt.Errorf(`layout %q requires an rclone-remote destination; type "kopia" repositories are content-addressed by kopia itself`, layout) - } - return nil -} - // Pack-layout knob defaults, applied when a LayoutPacked destination omits // the corresponding key. Sizes are in bytes. const ( @@ -602,7 +631,7 @@ func validateCryptRemoteNames(dests map[string]*Destination) error { // unknown-field check that consumes them. var universalDestKeys = []string{ "type", "root", "crypt", "layout", - "hash_algo", "checkers", "force_path_style", + "hash_algo", "checkers", "concurrency", "force_path_style", "pack_threshold", "pack_size", "zstd_level", "verify_every", } @@ -825,6 +854,37 @@ func sortedSubset(in []string) []string { return out } +// Native reports whether squirrel writes this destination itself, through +// its own transport, in any layout: a local disk, or an sftp server without +// crypt. rclone writes every other destination but kopia. +func (d *Destination) Native() bool { + return isNative(d.Type, d.Crypt != nil) +} + +func isNative(typ string, crypt bool) bool { + return !crypt && (typ == "local" || typ == "sftp") +} + +// NativeMirror reports whether this is a mirror squirrel writes itself. +func (d *Destination) NativeMirror() bool { + return d.Native() && isMirrorLayout(d.Layout) +} + +func isMirrorLayout(layout string) bool { + return layout != LayoutContentAddressed && layout != LayoutPacked +} + +// Verifiable reports whether `squirrel verify` re-checks this destination: +// squirrel records what it stored there, as the content-addressed and +// packed layouts' objects and packs, or as a native mirror's copies. +func (d *Destination) Verifiable() bool { + return verifiable(d.Layout, d.NativeMirror()) +} + +func verifiable(layout string, nativeMirror bool) bool { + return layout == LayoutContentAddressed || layout == LayoutPacked || nativeMirror +} + // HidesArtifactNames reports whether this destination names its content // objects, packs, and per-volume directories by a keyed BLAKE3 hash derived // from its crypt passwords, so the remote discloses neither a path nor a @@ -842,35 +902,38 @@ func layoutHidesArtifactNames(layout string) bool { // CanEverGateOffload reports whether a durability push to this destination // can ever advance its vector with a component the offload gate will accept -// — one that is content-verified, either natively or after a scan-back -// fingerprint upgrades a presence+size component. When it returns false, -// reason names the structural gap for the caller's message; it is empty -// when capable. +// — one that is content-verified, either natively or after a fingerprint +// upgrades a presence+size component. When it returns false, reason names +// the structural gap for the caller's message; it is empty when capable. // -// The structurally-incapable shape is an rclone mirror, plain or crypt. Its -// sync compares source against destination by rclone's --checksum — under -// a hash rclone picks, unrelated to the index's BLAKE3 — or, behind a crypt -// overlay, by size+mtime alone (sync.EffectiveShallow); and the mirror -// layout records no scan-back fingerprint that a later `squirrel verify` -// could upgrade (#211). The content-addressed and packed layouts, by -// contrast, advance with presence+size but stay upgradable — their -// fingerprint is read back over the stored ciphertext, so a crypt overlay -// does not block it — and kopia's own repository verification is capable -// outright. +// The content-addressed and packed layouts advance with presence+size but +// stay upgradable — their fingerprint is read back over the stored +// ciphertext, so a crypt overlay does not block it — and kopia's own +// repository verification is capable outright. So is a native local mirror: +// every copy it writes is read back through BLAKE3 before it is committed, +// and `squirrel verify` re-reads them. The incapable shapes are the other +// mirrors. A native sftp mirror reads nothing back, and its paths — the +// volume's own file names — never go on a server command line, so its +// evidence stays presence+size. An rclone mirror compares source against +// destination by rclone's --checksum — under a hash rclone picks, unrelated +// to the index's BLAKE3 — or, behind a crypt overlay, by size+mtime alone +// (sync.EffectiveShallow), and records nothing a later `squirrel verify` +// could upgrade (#211). func (d *Destination) CanEverGateOffload() (bool, string) { - if d.Type == "kopia" { + switch { + case d.Type == "kopia", d.Layout == LayoutContentAddressed || d.Layout == LayoutPacked: return true, "" - } - switch d.Layout { - case LayoutContentAddressed, LayoutPacked: + case d.NativeMirror() && d.Type == "local": return true, "" + case d.NativeMirror(): + return false, "sftp mirror destination: a push reads nothing back, and its paths are the volume's own file names, which squirrel never puts on a server command line, so no copy is fingerprinted and its evidence stays presence+size, which is not content-verified; a local mirror, or a content-addressed or packed sftp destination, can gate" } - return false, "mirror destination: a sync compares it with the source by rclone's checksum or by size+mtime, never against the index's BLAKE3, and the mirror layout records no scan-back fingerprint to upgrade" + return false, "mirror destination: a sync compares it with the source by rclone's checksum or by size+mtime, never against the index's BLAKE3, and records nothing a later verify could upgrade" } // VerifyCadencedTargets marks the required targets that carry an effective // local verify cadence — a per-destination verify_every, or the [agent] -// verify_every default applied to a content-addressed/packed destination. +// verify_every default applied to a verifiable destination. // The offload gate accepts a locally-advanced fingerprint-verified // component as content-verified only for a target in this set, so the // provider-fingerprint evidence keeps being re-confirmed for as long as @@ -890,10 +953,7 @@ func (c *Config) VerifyCadencedTargets(require []string) map[string]bool { out := make(map[string]bool, len(require)) for _, name := range require { d, ok := c.Destinations[name] - if !ok { - continue - } - if d.Layout != LayoutContentAddressed && d.Layout != LayoutPacked { + if !ok || !d.Verifiable() { continue } eff := d.VerifyEvery diff --git a/config/fingerprint_knobs_test.go b/config/fingerprint_knobs_test.go index 65576e4..bbea6c7 100644 --- a/config/fingerprint_knobs_test.go +++ b/config/fingerprint_knobs_test.go @@ -44,7 +44,7 @@ root = "/data" } // TestLoadHashAlgoExplicit: an explicit hash_algo overrides the default -// and renders on mirrored sftp destinations too. +// and renders on an encrypted sftp mirror, which rclone still writes. func TestLoadHashAlgoExplicit(t *testing.T) { cfg, err := Load(writeConfig(t, ` [destinations.archive] @@ -61,6 +61,9 @@ host = "host.example" user = "u" root = "/data" hash_algo = "sha256" + +[destinations.mirror.crypt] +password = "pw" `)) if err != nil { t.Fatalf("Load: %v", err) @@ -76,6 +79,53 @@ hash_algo = "sha256" } } +// TestNativeContentLayoutsTakeTheirOwnHashes: a content-addressed or packed +// sftp destination squirrel writes itself defaults to sha256, accepts the +// hashes whose command squirrel runs and checks, refuses the ones only +// rclone reads, and refuses checkers; one behind crypt keeps rclone's. +func TestNativeContentLayoutsTakeTheirOwnHashes(t *testing.T) { + dest := func(extra string) string { + return "[destinations.archive]\ntype = \"sftp\"\nhost = \"h\"\nuser = \"u\"\nroot = \"/data\"\nlayout = \"packed\"\n" + extra + } + cfg, err := Load(writeConfig(t, dest(""))) + if err != nil { + t.Fatalf("Load: %v", err) + } + if got := cfg.Destinations["archive"].HashAlgo; got != "sha256" { + t.Fatalf("HashAlgo = %q, want the sha256 default on a native packed destination", got) + } + if _, err := Load(writeConfig(t, dest(`hash_algo = "blake3"`+"\n"))); err != nil { + t.Fatalf("blake3 on a native packed destination: %v", err) + } + for _, key := range []string{`hash_algo = "xxh3"`, "checkers = 4"} { + name, _, _ := strings.Cut(key, " ") + if _, err := Load(writeConfig(t, dest(key+"\n"))); err == nil || !strings.Contains(err.Error(), name) { + t.Fatalf("%s on a native packed destination: err = %v, want a rejection naming it", key, err) + } + } + if _, err := Load(writeConfig(t, dest(`hash_algo = "xxh3"`+"\n\n[destinations.archive.crypt]\npassword = \"pw\"\n"))); err != nil { + t.Fatalf("xxh3 behind crypt, which rclone writes: %v", err) + } +} + +// TestLoadRejectsRcloneKeysOnNativeMirrors: squirrel writes a plain sftp +// mirror itself, so the keys that only tune rclone are refused there. +func TestLoadRejectsRcloneKeysOnNativeMirrors(t *testing.T) { + for _, key := range []string{`hash_algo = "sha256"`, "checkers = 4"} { + _, err := Load(writeConfig(t, ` +[destinations.mirror] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" +`+key+"\n")) + name, _, _ := strings.Cut(key, " ") + if err == nil || !strings.Contains(err.Error(), name) || !strings.Contains(err.Error(), "squirrel") { + t.Fatalf("%s on a plain sftp mirror: err = %v, want a rejection naming the key", name, err) + } + } +} + func TestLoadRejectsHashAlgoOnNonSFTP(t *testing.T) { _, err := Load(writeConfig(t, ` [destinations.bucket] @@ -111,7 +161,11 @@ type = "sftp" host = "host.example" user = "u" root = "/data" +layout = "content-addressed" checkers = 4 + +[destinations.archive.crypt] +password = "pw" `)) if err != nil { t.Fatalf("Load: %v", err) @@ -135,10 +189,11 @@ func TestLoadRejectsBadCheckers(t *testing.T) { t.Run(c.name, func(t *testing.T) { _, err := Load(writeConfig(t, ` [destinations.archive] -type = "sftp" -host = "host.example" -user = "u" -root = "/data" +type = "sftp" +host = "host.example" +user = "u" +root = "/data" +layout = "content-addressed" `+c.body+"\n")) if err == nil || !strings.Contains(err.Error(), "checkers") { t.Fatalf("err = %v, want checkers rejection", err) @@ -147,6 +202,58 @@ root = "/data" } } +// TestLoadConcurrency: every destination but kopia accepts a positive +// concurrency, native and rclone-written alike, and it stays out of +// rclone.conf. +func TestLoadConcurrency(t *testing.T) { + cfg, err := Load(writeConfig(t, ` +[destinations.usb] +type = "local" +root = "/mnt/usb" +concurrency = 2 + +[destinations.archive] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" +concurrency = 16 + +[destinations.archive.crypt] +password = "pw" +`)) + if err != nil { + t.Fatalf("Load: %v", err) + } + if got := cfg.Destinations["usb"].Concurrency; got != 2 { + t.Fatalf("usb Concurrency = %d, want 2", got) + } + archive := cfg.Destinations["archive"] + if archive.Concurrency != 16 { + t.Fatalf("archive Concurrency = %d, want 16", archive.Concurrency) + } + if strings.Contains(archive.RcloneSection(), "concurrency") { + t.Fatalf("concurrency leaked into rclone.conf (it is an invocation flag):\n%s", archive.RcloneSection()) + } +} + +func TestLoadRejectsBadConcurrency(t *testing.T) { + cases := []struct{ name, body string }{ + {"zero", "type = \"local\"\nroot = \"/mnt/usb\"\nconcurrency = 0"}, + {"negative", "type = \"local\"\nroot = \"/mnt/usb\"\nconcurrency = -1"}, + {"string", "type = \"local\"\nroot = \"/mnt/usb\"\nconcurrency = \"4\""}, + {"kopia", "type = \"kopia\"\nroot = \"/repo\"\npassword = \"pw\"\nconcurrency = 4"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, err := Load(writeConfig(t, "[destinations.d]\n"+c.body+"\n")) + if err == nil || !strings.Contains(err.Error(), "concurrency") { + t.Fatalf("err = %v, want concurrency rejection", err) + } + }) + } +} + func TestLoadForcePathStyle(t *testing.T) { cfg, err := Load(writeConfig(t, ` [destinations.bucket] diff --git a/config/layout_test.go b/config/layout_test.go index 8f43aa2..0f37190 100644 --- a/config/layout_test.go +++ b/config/layout_test.go @@ -63,16 +63,20 @@ layout = "mirror" } } -func TestLoadRejectsContentAddressedOnLocal(t *testing.T) { - p := writeConfig(t, ` +// TestLoadContentAddressedOnLocal: squirrel writes a content-addressed +// destination on a local disk itself, so the layout is valid there. +func TestLoadContentAddressedOnLocal(t *testing.T) { + cfg, err := Load(writeConfig(t, ` [destinations.scratch] type = "local" root = "/tmp/dst" layout = "content-addressed" -`) - _, err := Load(p) - if err == nil || !strings.Contains(err.Error(), "rclone-remote") { - t.Fatalf("expected rclone-remote requirement error, got %v", err) +`)) + if err != nil { + t.Fatalf("Load: %v", err) + } + if d := cfg.Destinations["scratch"]; d.Layout != LayoutContentAddressed || !d.Native() { + t.Fatalf("destination = %+v, want a native content-addressed one", d) } } diff --git a/config/offload_capability_test.go b/config/offload_capability_test.go index 18cb823..ef4eba7 100644 --- a/config/offload_capability_test.go +++ b/config/offload_capability_test.go @@ -6,9 +6,10 @@ import ( ) // TestCanEverGateOffload pins the structural capability predicate the -// offload fail-fast reads: the incapable shape is an rclone mirror, plain or -// crypt (checksum or size+mtime, no fingerprint to upgrade it); every other -// shape can eventually contribute a content-verified component. +// offload fail-fast reads: the incapable shapes are an rclone mirror (a +// crypt one: checksum or size+mtime, no fingerprint to upgrade it) and a +// native sftp mirror (nothing read back); every other shape, a native local +// mirror included, can eventually contribute a content-verified component. func TestCanEverGateOffload(t *testing.T) { crypt := &Crypt{Password: "obscured"} cases := []struct { @@ -16,13 +17,15 @@ func TestCanEverGateOffload(t *testing.T) { dest Destination wantCapable bool }{ - {"mirror plain", Destination{Type: "sftp", Layout: LayoutMirror}, false}, + {"sftp mirror", Destination{Type: "sftp", Layout: LayoutMirror}, false}, {"mirror crypt", Destination{Type: "sftp", Layout: LayoutMirror, Crypt: crypt}, false}, + {"local mirror crypt", Destination{Type: "local", Layout: LayoutMirror, Crypt: crypt}, false}, + {"b2 mirror", Destination{Type: "b2", Layout: LayoutMirror}, false}, {"content-addressed plain", Destination{Type: "sftp", Layout: LayoutContentAddressed}, true}, {"content-addressed crypt", Destination{Type: "s3", Layout: LayoutContentAddressed, Crypt: crypt}, true}, {"packed plain", Destination{Type: "s3", Layout: LayoutPacked}, true}, {"packed crypt", Destination{Type: "s3", Layout: LayoutPacked, Crypt: crypt}, true}, - {"local mirror", Destination{Type: "local", Layout: LayoutMirror}, false}, + {"local mirror", Destination{Type: "local", Layout: LayoutMirror}, true}, {"kopia mirror", Destination{Type: "kopia", Layout: LayoutMirror}, true}, } for _, c := range cases { diff --git a/config/pack_test.go b/config/pack_test.go index 11d646b..ac6ab27 100644 --- a/config/pack_test.go +++ b/config/pack_test.go @@ -83,15 +83,20 @@ root = "p" } } -func TestLoadRejectsPackedOnLocal(t *testing.T) { - _, err := Load(writeConfig(t, ` +// TestLoadPackedOnLocal: squirrel writes a packed destination on a local +// disk itself, so the layout is valid there. +func TestLoadPackedOnLocal(t *testing.T) { + cfg, err := Load(writeConfig(t, ` [destinations.scratch] type = "local" root = "/tmp/dst" layout = "packed" `)) - if err == nil || !strings.Contains(err.Error(), "rclone-remote") { - t.Fatalf("expected rclone-remote requirement error, got %v", err) + if err != nil { + t.Fatalf("Load: %v", err) + } + if d := cfg.Destinations["scratch"]; d.Layout != LayoutPacked || !d.Native() { + t.Fatalf("destination = %+v, want a native packed one", d) } } diff --git a/design/README.md b/design/README.md index fa12273..d3840c7 100644 --- a/design/README.md +++ b/design/README.md @@ -14,6 +14,9 @@ each time. every supported destination type in play. - [`testbed.md`](testbed.md) — how the reference setup is simulated on one development machine with real commands and no containers. +- [`native-mirror.md`](native-mirror.md) — *implemented in #217*: one + planner shared by every layout, a small transport, and every `local` and + plain `sftp` destination written without rclone. ## How to use this folder diff --git a/design/friction-log.md b/design/friction-log.md index 39c5e7b..cb15507 100644 --- a/design/friction-log.md +++ b/design/friction-log.md @@ -296,6 +296,14 @@ advance the vector, now as `checksum`, but the gate refuses that method and config load rejects every mirror in `offload_requires`, plain or crypt. The fail-fast half stands and now covers both. +*Revised again in the native mirror PR (#217).* A mirror squirrel writes on a +`local` disk reads every copy back through BLAKE3 before committing it, records +that as the copy's fingerprint, and advances the vector as +`fingerprint-verified`; `squirrel verify` re-checks its copies. Such a mirror +may be named in `offload_requires` again. Every other mirror is still rejected +at load: an rclone mirror (crypt, or on s3, b2, gcs) compares by checksum or +size+mtime, and a native sftp mirror reads nothing back. + ## Checkpoints 4–5 — trip return + offload day **F22 · S2 — ~~gate refusals are per-file walls of jargon that can't @@ -560,6 +568,60 @@ must configure `[agent] listen` + auth token anyway, because the scheduler lives inside the agent. A listener that exists to be unused is config noise and attack surface. +## Native mirror walk (2026-09-24, #217) + +A second, shorter walk: the native mirror's lifecycle on `homepc`'s seat — +bootstrap, steady state, changes, verify, an unplugged disk, restore with +and without the index, recover, the offload gate — against an exFAT disk +image on macOS and a plain sftp destination on `rclone serve sftp`, plus a +benchmark against `main`'s rclone mirrors +([native-mirror.md](native-mirror.md), section 8). The bootstrap refusals, +the host-key refusal (it prints the known_hosts line to add), repairs of a +copy verify found gone, and a rename that changed only case all behaved. + +**F36 · S1 — ~~a fresh index took over a tree it never wrote.~~ (fixed in +#217)** With no sync of the volume in the index, a push to a native mirror +started from nothing over whatever the volume's directory held: pointed at +a tree rclone wrote, it moved all 4690 files into history and wrote them +again, doubling what the disk holds, where the design refuses existing +trees. A volume's first push now refuses a directory that holds files +squirrel has no record of writing, and points at `squirrel recover --from` +for a native mirror whose index is gone. + +**F37 · S2 — ~~macOS's `._` files read as foreign.~~ (fixed in #217)** On +exFAT, macOS keeps every file's extended attributes in a `._` +companion. Every push warned about the last run's `._run-` in staging, +and an index-less restore brought back 619 `._` files as unchecked, +including those of `.squirrel-history` and the marker. A `._X` beside `X` +is now `X`'s. + +**F38 · S2 — ~~an unplugged disk was told to re-run with `--init`.~~ (fixed +in #217)** The refusal for a missing root or marker led with `--init` even +for a disk the volume had synced to, where `--init` would bootstrap an empty +destination on the bare mountpoint. It now says the disk is most likely not +mounted; `squirrel verify` on a missing root says the same instead of a raw +open error. + +**F39 · S4 — ~~the unsatisfiable-gate refusal forgot the local mirror.~~ +(fixed in #217)** Rejecting an sftp mirror in `offload_requires` listed every +target that can gate but the local mirror, which the same message's reason +names. + +**F40 · S1 — ~~native pushes that write are several times slower than +rclone.~~ (fixed in #217)** A first push took 116 s against rclone's 13 s on +the exFAT image, and 432 s against 45 s over sftp at a 20 ms round trip; +unchanged pushes are faster. The cost was three full flushes per file on a +local disk and 27 sequential requests per path over sftp. Decision 8 in +native-mirror.md flushes once per batch and writes several paths at once +(`concurrency`), and a scan that made a first push quadratic in its file +count is gone. Rerun, a first push to the exFAT image takes 15–29 s against +rclone's 19–25 s, and 50 s against 47 s at a 20 ms round trip. + +Observed, by design: a copy corrupted in place on the local mirror, size and +mtime kept, passed two verify passes because each re-reads only a tenth of +the bytes; the restore's BLAKE3 refused it. Until its turn in the rotation, +the offload gate would count it. + ## Summary and priority *The verdict below is the walk's own, kept as written that night; the diff --git a/design/native-mirror.md b/design/native-mirror.md new file mode 100644 index 0000000..fb141e8 --- /dev/null +++ b/design/native-mirror.md @@ -0,0 +1,1106 @@ +# Native mirror layout: one planner, three layouts, a small transport + +*Implemented in #217.* This is step 2 of replacing rclone with squirrel's own +transports. Peer sync dropped rclone in #210. #211 made the mirror's evidence +honest. Step 3 is S3 for the packed and content-addressed layouts. + +## Summary + +Today a mirror push hands the whole job to `rclone copy`. Rclone lists both +sides, compares them, transfers what differs, and moves overwritten files into +`--backup-dir`. This design replaces that for `local` mirrors and plain `sftp` +mirrors. The replacement has three layers: + +1. **Planner**, shared by every layout: the index changes since the + destination's last confirmed run. +2. **Layout**: turns those changes into operations. Content-addressed uploads + an object per hash. Packed adds small content to a pack. Mirror writes the + path and first moves the previous version into history. +3. **Transport**: byte-level access to one destination root (stat, list, get, + put, rename). There is a `local` implementation and an `sftp` one. + +The planner lands first. It is a refactor of the content-addressed and packed +handlers, which already share this logic in duplicated form. It changes no +behaviour except a bug fix it exposes (see "Watermark rule"). The mirror then +plugs in as a third layout. + +## Scope + +**In scope:** + +- the planner refactor; +- the transport, with its local and sftp implementations; +- the mirror layout on `local`, and on `sftp` without `crypt`; +- marker, snapshot ride-along, recover and restore for those destinations. + +**Out of scope, and still on rclone:** + +- **Crypt mirrors, including cloudbox.** They wait for the crypt + byte-compatibility decision (open question 1). In this design, crypt is a + wrapper around a transport. So that decision changes neither the planner nor + the layout. +- **Mirrors on s3, b2 and gcs.** A mirror needs rename, and object stores have + none (see "Transport"). +- **Peer sync.** It keeps its negotiated plan, where the receiver decides. +- **Kopia.** + +In the [reference setup](reference-setup.md), `usb` moves with this work. +`cloudbox` is an encrypted sftp mirror, so it moves when crypt does. + +## What changes for the operator + +- **A push plans from the index.** It sends what the index recorded, not what + a live walk finds. This already holds for the content-addressed and packed + layouts. A file created after the last index run reaches the mirror on the + first push after it gets indexed. +- **A push checks only the paths it plans to write.** Each one gets a single + `Lstat`. Anything found at such a path is moved into `.squirrel-history/` + before the new version lands, whatever it holds. So a remote change can cost + an extra copy in history, never an overwrite. Changes elsewhere on the + destination are found by the verify pass (`verify_every`, extended to + mirrors in the evidence step). +- **Each push leaves a receipt** at `/.squirrel-index/run-`. It is + the same manifest segment the content-addressed and packed layouts write + (see [formats](../docs/src/content/docs/reference/formats.md)). The mirror + stays browsable. The receipts make it verifiable without the index. +- **New reserved directory** `/.squirrel-staging/` holds in-flight + writes. +- **sftp host keys are always verified** (see "Configuration"). +- **`--shallow` is refused for a native mirror.** A push decides from + squirrel's records, confirms each planned path's size and mtime, and moves + whatever is there aside before writing. Its safety comes from that move, not + from a content comparison. Content is checked by hashing the source as it + streams, by the read-back on local disks, and by the verify pass (both from the + evidence step). + None of those is optional, so the flag has nothing to switch off. + +## 1. The planner + +`contentAddressedHandler.Push` and `packedHandler.Push` each carry the same +sequence: + +1. indexed-volume check; +2. markers; +3. run allocation; +4. watermark; +5. advance snapshot; +6. delta; +7. finish; +8. ride-along. + +They differ only in their landing evidence (segment or placement map) and in +what they transfer. The planner is that shared sequence, extracted once: + +```go +// pushPlan is what one push must land: the volume's index changes since the +// destination's last confirmed run, and the durability snapshot the push +// advances to once they land. +type pushPlan struct { + volumeID int64 + watermark int64 // last confirmed run; 0 for a fresh destination + delta []store.PathDelta // ListPathDeltaSince(volumeID, watermark) + advance []store.OriginComponent // captured before any transfer +} + +// layout is one destination layout's part of a push. O is the layout's +// own operations type; a dry run reports its preview. +type layout[O operations] interface { + // markers gates the push on the destination's markers (writes them + // under --init; a dry run only checks). + markers(ctx context.Context, rep *Report, volumeID int64, opts Options) error + // landed reports whether runID left this layout's landing evidence. + landed(ctx context.Context, runID int64) (bool, error) + // rootEmpty and foreignHistory complete the watermark rule below. + rootEmpty(ctx context.Context) (bool, error) + foreignHistory(runID int64) error + // reconcile settles what an earlier push left in flight (mirror only). + reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error + // translate turns the plan into this layout's operations. It reads + // squirrel's records and writes nothing: a dry run is translate alone. + translate(ctx context.Context, p pushPlan) (O, error) + // execute performs the operations and records each confirmed one. + execute(ctx context.Context, rep *Report, runID int64, ops O) error + // seal writes the run's landing evidence once every operation is confirmed. + seal(ctx context.Context, rep *Report, runID int64, p pushPlan, ops O) error + // advanceMethod names the evidence the confirmed landing earns; an + // empty method holds the vector (packed, while a fingerprint is pending). + advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) + // shelf is /.squirrel-index/ for the ride-along: reached + // through rclone for the content layouts, through the transport for a + // mirror. + shelf(runID int64) snapshotShelf +} +``` + +One driver runs every layout: + + requireIndexedVolume → markers → begin run → reconcile → plan → translate → execute → seal → advance → finish → ride-along + +A dry run stops after translate and reports the operations' preview. The +separate `previewDryRun` each handler carried became that preview +(`sync/push.go`). + +The driver promotes a run to success only after the vector advanced, for +every layout. Before the refactor a packed run whose advance failed still +closed as success; it now closes as failed, like content-addressed. + +### Watermark rule + +This rule is shared by all three layouts: + +1. If there is no successful sync of this (volume, destination), the + watermark is 0, once the layout's first-push gate passes. The content + layouts pass it always: an artifact already at its name is confirmed and + adopted. A mirror refuses when squirrel holds no `remote_paths` row of the + volume there and the volume's directory holds files outside + `.squirrel-staging/` beyond its marker (`mirrorHandler.firstPush`): a + tree rclone wrote, or a native mirror whose index is gone, which + `squirrel recover --from` restores. Without the gate, a fresh index moved + the whole existing tree into history and wrote it again, doubling what + the disk holds. A first push that crashed left rows, so its retry passes, + and the check covers the volume's directory only, so a second volume + starts fresh beside the first. +2. If the last success left its landing evidence at the destination, the + watermark is that run's id. +3. The watermark is also 0 (a fresh start) when all three of these hold: + - the landing evidence is absent; + - the destination root is empty apart from its markers; + - squirrel holds **no upload records** for the destination. +4. In every other case, refuse with `ErrRefused`. The message points at a + fresh root or `squirrel destination reset`. + +A probe that fails, for the evidence or for the root's emptiness, fails the run +with its error instead: it can't tell either way, so it neither refuses nor +starts fresh. + +Each layout's landing evidence lives at a different place: + +| Layout | Landing evidence | +|---|---| +| content-addressed | `/index/run-` | +| packed | `packs/map-` | +| mirror | `/.squirrel-index/run-` | + +No two layouts share a location, so a destination switched from one layout to +another is refused. + +**The last condition in rule 3 is new, and it fixes a live bug.** Before the +planner, `freshStartOnEmptyRoot` checked only that the remote root was empty. +Consider a content-addressed destination whose root was wiped without a +`destination reset`, then re-marked with `--init`: + +1. The next push takes the fresh-start branch. +2. `uploadObjects` skips every content that `remote_objects` still records. +3. It writes a segment mapping paths to objects that no longer exist. +4. The run closes as `success` and advances the durability vector. If the old + fingerprints were verified, it advances as `fingerprint-verified`. + +`TestPushRefusesWipedRootWithUploadRecords` pins it. It runs one push, wipes +the fake remote, re-seeds the markers and runs a second push. Before the fix +that push reported `success` with `transferred=0 checked=1`, and the object +was absent; only a later verify pass would have noticed. The planner now fails +closed here (`DestinationHasUploadRecords`), because the mirror's records would +repeat the same mistake. + +### Repairs: the mirror's second input + +This input arrives with the evidence step. A verify pass that finds a +recorded copy missing or changed marks that record `lost`. The next push +then plans the record's content again, even though the index didn't change: + + work = delta since watermark ∪ records marked lost + +The mirror's translate reads them (`ListRemotePathRepairs`): present paths +where a `lost` row holds the current content and no live row does. A +withdrawn commit is one too, but its path is still in the delta. A push +that writes repairs counts them as changed, so the runs fold shows it. + +The content layouts keep only raising the alarm. Their records have no +`lost` state, and a changed object can't be healed in place: nothing +replaces an existing name, so repairing one needs a displacement the +content layouts don't have. + +## 2. Layouts translate changes into operations + +| Layout | Operations from one delta | +|---|---| +| content-addressed | one object upload per present content with no upload record on the destination | +| packed | object uploads for content at or above `pack_threshold`; pack members for the rest | +| mirror | one path write per present path whose live record doesn't hold that content | + +Rows that are `missing`, `offloaded` or `superseded` produce no transfer in any +layout. A destination keeps content the source no longer has. + +Translate reads only squirrel's own records. That makes each layout's +decisions table-testable without a transport. For the mirror, those decisions +include the destructive one: which existing entry gets moved into history. + +## 3. Transport + +```go +// transport is byte-level access to one destination root. Names are +// slash-separated and relative to the root; symlinks are never followed. +type transport interface { + Stat(ctx context.Context, name string) (entry, error) // fs.ErrNotExist when absent + List(ctx context.Context, dir string) ([]entry, error) + Get(ctx context.Context, name string) (io.ReadCloser, error) + // Put creates name exclusively (fs.ErrExist if present), streams r into + // it and sets its mtime. Its bytes are durable once a later Flush returns. + Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error + // Rename moves from to to, creating to's parents; fs.ErrExist if to exists. + // The move is durable once a later Flush returns. + Rename(ctx context.Context, from, to string) error + Remove(ctx context.Context, name string) error + // Flush returns once every Put and Rename that returned before it, and + // the entries of dirs, are on stable storage. dirs names directories an + // earlier process may have changed, which the caller is about to rely on. + Flush(ctx context.Context, dirs ...string) error + Close() error +} +``` + +### Contract + +- **Nothing replaces an existing name.** `Put` creates exclusively and + `Rename` never replaces its target. So no transport call can overwrite + bytes. +- **Only a name guard decides what may move or disappear.** Layouts never + hold the raw transport. They get a wrapper whose one small function, with + its own table test, allows: + - `Remove` only on squirrel's own staging names from runs that have + finished (`.squirrel-staging/run-/`), and on ride-along snapshots + (`.squirrel-index/index-*.db`, which rotation already deletes today). + Anything else found in staging, a run directory of a run the index + doesn't know included, is reported and left alone; + - `Rename` only from this run's staging to a snapshot name (the + ride-along) or to what the layout commits — a live name for a mirror; for + a content layout `objects/`, `packs/`, `packs/map-` + or `/index/run-` — or, for a mirror only, from a live + name to `.squirrel-history/run-/` (displacement); + - under `--init`, before the push holds a run, the marker's own staging: + it is written to `.squirrel-staging/volume-marker` and renamed onto + `.squirrel-volume`, and a stale staged copy may be removed; + - for a mirror push holding a run, `Remove` of the name probe, + `.squirrel-staging/fold-probe-é` (see "Names the destination folds"). + + So the marker and the ride-along snapshot land whole or not at all, like + every path: a write that fails halfway leaves its partial copy in staging, + never at a name recovery or the marker gate reads. + + That function is the whole audit surface for destroying or moving bytes on + a destination. +- **Durability comes from `Flush`, once per batch.** `Put` and `Rename` + return once their effect is visible; one `Flush` then makes everything + before it durable. A layout records a location as holding bytes (a `live` + or `displaced` row, an upload record, a receipt that seals a run) only + after a `Flush` that follows the call that put the bytes there. It also + flushes staged bytes before renaming them into place, because reconcile + trusts size and mtime at a name. A flush per batch of files instead of + several per file is what makes a push that writes affordable on a local + disk (section 8). +- **Object stores implement everything except `Rename`.** S3 can create + exclusively with a conditional put. That is enough for the + content-addressed and packed layouts in step 3. A mirror needs `Rename`, + which is why mirrors on s3, b2 and gcs are out of scope. + +### Local implementation + +- Built on `os.Root` (Go 1.25+). It resolves every name inside the root and + refuses to follow symlinks out of it. `os.Root` does follow symlinks that + stay inside the root, so every call also checks its name's parent chain with + `Lstat` and refuses a symlink anywhere along it (`sync/transport_local.go`). +- `Put` opens with `O_CREATE|O_EXCL`, copies, and sets the times. The file + stays open until the next `Flush`, and every directory whose entries a call + changed is remembered: a new file's, both sides of a rename, and the parent + of every directory a call created. +- `Rename` avoids replacing its target in one of two ways: + - **Preferred:** the platform's no-replace rename (`renameat2` with + `RENAME_NOREPLACE` on Linux, `renamex_np` with `RENAME_EXCL` on macOS), + called on the parent directories' handles. + - **Fallback:** where the filesystem supports neither (exFAT, common on + USB disks), and on every other platform, squirrel checks with `Lstat` and + then renames. A concurrent + writer from outside squirrel could still slip in between the check and + the rename. Squirrel can't collide with itself here, because the run guard + and the volume marker already exclude a second squirrel writer. +- `Flush` makes the remembered files and directories durable in one go: + - **macOS:** each file is `fsync`ed as its `Put` ends and each directory at + the flush, then one `F_FULLFSYNC` flushes the drive's cache. The `fcntl` + manual page guarantees that this also persists everything `fsync`ed on + the device before it. That is one full flush per batch instead of three + per file. + - **Linux:** `fsync` itself flushes the drive, so the flush `fsync`s every + remembered file and directory together, and the filesystem's journal + commits them at once. + - **Elsewhere:** each file is flushed as its `Put` ends, and directories + are flushed where the platform can. +- **Every call is bounded by progress.** A call that makes none for + `DefaultStallTimeout` (a `Put` progresses with every chunk it reads) fails the + push. A `Flush` is also allowed the time the bytes put since the last one + take at 1 MiB/s. A local call blocked in the kernel can't be interrupted and may still + finish a move later, so a push refuses while a call an earlier push gave up + on is still outstanding (`sync/transport_stall.go`). + +### sftp implementation + +- Built on `golang.org/x/crypto/ssh`, already a dependency, and + `github.com/pkg/sftp`, which is new (`sync/transport_sftp.go`). +- `Put` opens with `SSH_FXF_CREAT|SSH_FXF_EXCL` and uses concurrent writes, so + high latency doesn't cap throughput. It flushes its file through + `fsync@openssh.com` when the server offers it. The protocol can't flush a + directory, so `Flush` has nothing left to do. +- **Paths in flight share one connection.** Every file a push writes at once + (`concurrency`, section 7) goes over the same SSH connection and sftp + session, which interleaves their requests. A server's cap on concurrent + connections is never the limit; one that serves a session's requests one + at a time, as OpenSSH's does, still hides the network's round trips. +- **mtime is whole seconds.** Protocol version 3 carries only seconds, so the + records store the mtime the server reports. +- **`Put` and `Rename` check first.** The protocol's rename fails when the + target exists, but servers don't all honour that: `pkg/sftp`'s own server and + `rclone serve sftp` both replace it (`TestSFTPServersRenameOverAnExistingName`). Version 3 also has no + "already exists" status, so an exclusive create that fails can't say why. So + both calls run `Lstat` on their target first and fail with `fs.ErrExist`, + and every call checks its name's parent chain for symlinks, as the local + transport does. The contract suite passes against an in-process `pkg/sftp` + server and against `rclone serve sftp`, the testbed's server. That server + hides symlinks, so the symlink cases skip there. +- **Host keys follow known_hosts.** The handshake asks the server for the key + types known_hosts pins for it (or `host_key_algorithms` when set), so a + server that also offers another key type is still checked against the + pinned one (`sync/transport_sftp_hostkey.go`). +- **One optional server-side command: a hash.** Content-addressed and packed + artifacts get their fingerprint confirmed, and re-confirmed, by a hash + command run on the server (`ServerHash`, `sync/transport_sftp_hash.go`). + That is `sha256sum` by default, chosen by `hash_algo`: `md5sum`, + `sha1sum`, `sha256sum` or `b3sum`, the hashes squirrel can also compute + itself to compare against. + - The command line is built only from the configured root and a name + whose last element is a lowercase hex artifact name: an object or pack, + or its staged copy `/.squirrel-staging/run-/` (volume + names hold only letters, digits, `_` and `-`). A root holding anything + beyond letters, digits, `.`, `_`, `-` and `/` is never hashed on the + server, and a relative one is passed as `./` so it never reads as + an option. + - The transport probes for the command once per session, and a push opens + one session: it hashes a known input on the server and compares. The leaf + must be a regular file, so the command never follows a symlink. On a + server that runs no programs, like the cloudbox shape, or whose command + computes something else, fingerprints stay pending, as today. + - Mirror paths are user filenames, so they never go on a command line. + +## 4. The mirror layout + +### On disk + +The tree keeps the shape it has today and gains two reserved entries: + +``` +// + 2024/cat.jpg + .squirrel-volume + .squirrel-history/run-7/2024/cat.jpg # prior version, moved aside by run 7 + .squirrel-index/run-7 # receipt: run 7's manifest segment + .squirrel-index/index-…-run-7.db # ride-along index snapshot + .squirrel-staging/ # in-flight writes, squirrel-owned + .squirrel-staging/fold-probe-é # name probe, removed within the push +``` + +`.squirrel-staging` joins the reserved names in `reservedSubtreeFilter`, +`isReservedSyncPath` and the walker's warning. + +### Destination records + +The mirror's counterpart of `remote_objects` is one row per version squirrel +wrote at a path. The row is keyed on the `files` row it came from: + +```sql +CREATE TABLE remote_paths ( + id INTEGER PRIMARY KEY, + destination TEXT NOT NULL, + folder_id INTEGER NOT NULL, + name TEXT NOT NULL, + content_id INTEGER NOT NULL, + written_run_id INTEGER NOT NULL REFERENCES runs(id), + state TEXT NOT NULL + CHECK (state IN ('committing', 'live', 'displacing', 'displaced', 'lost')), + displaced_run_id INTEGER REFERENCES runs(id), + mtime_ns INTEGER NOT NULL, + checksum_algo TEXT, + checksum TEXT, + verified_at_ns INTEGER, + FOREIGN KEY (folder_id, name, content_id) REFERENCES files (folder_id, name, content_id), + CHECK (state NOT IN ('committing', 'live') OR displaced_run_id IS NULL), + CHECK (state NOT IN ('displacing', 'displaced') OR displaced_run_id IS NOT NULL), + CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) +) STRICT; +CREATE UNIQUE INDEX uniq_remote_paths_live ON remote_paths (destination, folder_id, name) + WHERE state IN ('committing', 'live'); +CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) + WHERE state IN ('committing', 'displacing'); +``` + +- **A displaced version has a derived location.** It sits at + `.squirrel-history/run-/`. +- **Directory moves keep that rule true.** When a directory is displaced + because a file replaced it, every live row under the directory moves with it + and gets the same `displaced_run_id`. +- **Rows are never deleted.** The one exception is `squirrel destination + reset`, which clears `remote_paths` the same way it clears + `remote_objects`. +- **Foreign files are preserved but not recorded.** Bytes squirrel didn't + write have no content id. When squirrel displaces them, they are kept in + history, reported as a run warning, and listed in a runs_audit note. +- **A row is `lost` when its bytes are no longer where it says.** A push or a + verify pass found other bytes there, or nothing. The row keeps its history + but stops vouching for its content. +- **The upload-once check leaves mirror copies out.** The plan was for + `ContentPresentOnDestination` to gain `remote_paths` rows in the `live` and + `displaced` states as a third source. Its only callers are the content + layouts' upload-once checks, and a mirror copy isn't at `objects/`: a + destination whose mirror records outlived a switch to a content layout would + skip those objects and still seal. So the check stays with objects and packs, + and the mirror decides from its own records. `DestinationHasUploadRecords` + does count every `remote_paths` row. + +### Translation rules + +| Delta row | Live record for the path | Operation | +|---|---|---| +| present, content C | holds C | none (counted as already correct) | +| present, content C | holds other content | write C, displacing the recorded version | +| present, content C | none | write C, displacing any unrecorded entry found at the path | +| missing, offloaded, superseded | any | none | +| repair: a live record the verify pass marked `lost` | | write C, displacing whatever is there | + +Execute confirms each planned path with a single `Lstat`, never a listing. If +an "already correct" path's size or mtime disagrees with its record, the path +is treated as changed behind squirrel's back: its row becomes `lost` and the path is written again, with a warning. + +### Writing one path + +Execute writes the planned paths in batches of at most 64 paths or 256 MB, +several paths at a time: `concurrency` of them (section 7). Each step below +runs for the whole batch before the next begins. A path whose step fails drops +out of the batch, and the others go on. + +1. **Reconcile** (once, at push start). Squirrel settles every `committing` + and `displacing` row for this destination by checking both locations + (next table). Staging left by finished runs is removed. +2. **Stage.** The source is streamed into + `.squirrel-staging/run-/`, and BLAKE3 is computed over the same + bytes. The path key is the lowercase hex BLAKE3 of the volume-relative path: + the row doesn't exist yet (step 5 inserts it), and hex stays unique on a + destination that folds case. If the hash doesn't match the indexed hash, the + path fails and the run fails before its seal, so the watermark stays put. The + staged file stays until the next push's reconcile removes it with the + finished run's staging: the name guard removes no running run's staging. That is the `errContentDrift` contract. Here the + hash covers exactly the bytes sent, which closes the re-hash-then-read gap + noted on the rclone artifact store's `put`. The batch's staged files are + then flushed. +3. **Read back**, on a local disk: every staged file is read in full, past + the cache, through BLAKE3 (section 5). A mismatch fails the path before it + touches the live tree. +4. **Displace.** First any parent of a path that isn't a directory (a + file↔directory swap, a symlink) is displaced the same way, once per + directory, in path order. Then, for each path, if `Lstat` finds an entry + there: + - **The entry's size and mtime match the live row:** + 1. mark the row `displacing` with this run; + 2. rename the entry to `.squirrel-history/run-/`; + 3. after the batch's flush, mark the row `displaced`. + - **They don't match** (the file changed behind squirrel's back): + 1. mark the row `lost`; + 2. displace the entry as unrecorded bytes, which a warning and a + runs_audit note report. + + A record never claims history holds bytes it doesn't. + - **It is a directory** a file replaced: every live row under it becomes + `displacing`, the directory moves, and they become `displaced` after the + flush; a row whose bytes changed becomes `lost` first. + - **It is not a directory, or nothing**, while live rows sit under the + path (a recorded directory replaced by a file or a symlink on the + destination, or removed): those rows become `lost`, since their bytes + can't be at their paths, and turn into repairs while the index holds + their content. +5. **Commit:** + 1. insert the new row as `committing`; + 2. rename the staged file to the path; + 3. after the batch's flush, mark the row `live`. + +Each move is recorded before it happens. Reconcile then finishes the record or +withdraws it, based on where the bytes actually are. The destination never +lacks a copy of something it held. Displaced bytes reach history before the +new version is committed, and the new version stays in staging until then. +Between steps 4 and 5 the live path is briefly empty, for up to a batch. That +costs availability until the next push, never content. + +Each path still passes through the same states as a push that wrote one path +at a time: all of a batch's displacements are marked `displaced` before any of +its commits begins, so a path never holds a `displacing` and a `committing` row +at once. Only the step that confirms a move waits for the flush. + +**Paths in flight.** Within a step the batch's paths run `concurrency` at a +time. They can't collide: each stages under its own key, a path's displacement +moves only what sits at its own name, and both a parent in the way and a +version recorded under another spelling of the name (next section) are +displaced in the sequential pass that opens step 4. The writer's own +bookkeeping, the live records it keeps current and the report, is shared +behind one lock. + +### Names the destination folds + +APFS and HFS+ resolve names that differ only by case, or only by Unicode +normalization (composed `é` against `e` plus a combining accent), to the same +entry; exFAT and NTFS fold case. A source on a Linux disk can hold both +spellings as two files, and a case-only rename at any source shows up in the +index as one path gone and another new. Squirrel's records key on the exact +spelling, so on such a destination the records alone would let a write of +`A.jpg` move `a.jpg`'s bytes to history as unrecorded while `a.jpg`'s row +stayed `live` over the other spelling's bytes, breaking invariant 1. + +- **Probe.** Before its first write, each push writes + `.squirrel-staging/fold-probe-é`, looks it up by an upper-case and by a + decomposed spelling, and removes it again (`sync/mirror_fold.go`). A lookup + that finds the file means the destination folds that way. The probe runs on + every push that writes, so a disk reformatted between pushes is probed + again; one a crashed push left behind is removed by the next probe. +- **Collisions** (decision 6). On a destination that folds, execute groups + every planned path and every `live` row by the folded form of each name + along the path. Two present paths clash when one's name folds onto the + other's under another spelling where at least one is a file: two files, or + a file where the other's parent directory is. The spelling the destination + already holds (a `live` row of a present path) wins, then the first by byte + order; every other planned path claiming that name is refused. A refused + path is never staged and displaces nothing. It fails the run before its + seal, as drift does, with a warning naming both spellings, so the watermark + holds until one of them is renamed at the source. Two directory spellings + never clash: the destination merges them. +- **Case-only renames.** A `live` row under another spelling whose path is no + longer present at the source is displaced as its record before the planned + path lands: `a.jpg` moves to `.squirrel-history/run-/a.jpg` and becomes + `displaced`, then `A.jpg` is committed. A file in the way of a planned + path's directory moves the same way, and a directory displaced because a + file replaced it takes every live row under any spelling of it along + (`nameFolding.under`). +- **What stays behind.** A directory keeps the spelling it was created with: + after `Photos/` is renamed to `photos/` at the source, the files land under + the existing `Photos/` directory. Every lookup by the recorded name finds + them, but a restore without an index, which walks the tree, restores them + under `Photos/`, as files no receipt names. +- A dry run doesn't probe, so its preview doesn't show collisions. + +### AppleDouble companions + +On a filesystem without extended attributes (exFAT, FAT, some SMB shares), +macOS keeps a file's attributes in a companion `._` beside it, and +moves and removes the companion with the file. Every file squirrel writes +from a Mac gets one, since the system tags new files with an attribute. The +testbed walk found them reported as foreign staging on every push, restored +as unchecked files by an index-less restore, and counted as content by the +emptiness checks. A `._X` whose `X` is in the same listing is now X's +(`sync/appledouble.go`): skipped by the staging report and the emptiness +checks, and left out of an index-less restore, counted in one warning, +unless a receipt names it. A companion the system left behind is reported +like any other foreign entry. + +### Crash points + +| Crash after | Destination | Reconcile at the next push | +|---|---|---| +| staging write | partial file in staging | removed with the finished run's staging | +| `displacing` recorded | old version still at the path | size matches the record, so the row goes back to `live` | +| displace rename | old version in history | history entry present, so the row becomes `displaced` | +| `committing` recorded | new version in staging, path empty | the intent is withdrawn (the row becomes `lost`: its version never reached the path), the staging file removed, and the path planned again (no seal, so it's still in the delta) | +| commit rename | new version at the path | staging gone and path present, so the row becomes `live` | +| every write, before the seal | tree complete, no receipt | the watermark holds, and the next push translates every path to "already correct" | + +A power cut can also undo whatever the last flush didn't cover. Every row +still finds its bytes at one of the two places the table checks: no row +leaves `displacing` or `committing` before the flush that covers its move, +and a staged file is flushed before it's renamed onto a path. The receipt is +flushed before the run is sealed. A push that stopped before its flush — +cancelled, stalled, killed — leaves moves the disk may still take back, so +reconcile flushes every directory along both places of each unsettled row +before it records any settlement. + +`TestMirrorCrashTable` runs each row above; `TestMirrorTranslationRules` and +`TestMirrorWriteDisplacesWhatThePathHolds` run the translation table. + +A native push reports as `already_correct` every path whose live row holds its +present content, planned or not, so an unchanged push still reads as in sync +(friction F7). + +### What the tests must cover + +A native mirror loses the independence rclone's own walk gave it (see "What we +give up"). So its tests for destroying and moving bytes carry more weight than +usual: + +- **Crash injection at every transport call** of a push, using a + fault-injecting transport wrapper, then a clean push. The invariants below + must hold afterwards. It writes one path at a time, so the calls come in + the same order on every run; `Flush` is a call like any other. +- **Power cuts.** The same wrapper can, at the crash, also take back what no + `Flush` covered: every `Put` and `Rename` since the last one undone (a put + file vanishes, a rename is reversed), or every name kept but none of those + files' bytes. The invariants must hold after the next clean push. A first + push, which displaces nothing, runs it too: there only the flush after + staging stands between a staged file's bytes and its commit. +- **A model-based test.** It generates random index histories: add, modify, + delete, re-add, file↔directory swaps, names that collide by case. It then + pushes with several paths in flight and random crash points, some of them + power cuts, and compares the results against a reference model. +- **File↔directory swaps**, in both directions and nested. +- **Unexpected entries at a target:** + - an unrecorded file (a foreign write, or a tree rclone wrote); + - a recorded file changed behind squirrel's back: it is displaced as + unrecorded bytes, and its row becomes `lost`, never `displaced`; + - a file placed in `.squirrel-staging/` from outside squirrel: it is + reported and never removed; + - a symlink anywhere along a target's parent chain, which must not be + followed. +- **Case-insensitive destinations** (APFS or exFAT USB disks): + - When `a.jpg` and `A.jpg` both exist at the source, the second write is + refused for that path, and nothing is displaced. + - Destinations that ignore Unicode normalization get the same treatment, + for names that differ only in composed versus decomposed form. + - Each push that writes probes the destination's case and normalization + behaviour inside staging. +- **Failures:** + - the disk fills up or the quota runs out mid-write; + - the history directory can't be written; + - the source drifts while streaming. +- **Rename onto an existing target** must fail on both implementations and on + the testbed's sftp server. + +**Invariants:** + +1. Every `live` row's bytes are at its path. Every `displaced` row's bytes are + at its history path. In both cases their BLAKE3 matches. +2. Outside `.squirrel-staging/`, the set of files on the destination only + grows. +3. After a clean push, every path present in the index has a `live` row + holding its current content. + +The suite runs against the local transport. It runs against the sftp +transport through an in-process `pkg/sftp` server. And it runs against both +wrapped in the fault injector. + +Where each case lives: + +| Case | Tests | +|---|---| +| Crash at every call, then a clean push | `TestMirrorCrashAtEveryTransportCall`, `TestNativeContentCrashAtEveryTransportCall` (`sync/crash_every_call_test.go`) | +| Power cuts at every call | `TestMirrorPowerCutAtEveryTransportCall`, `TestNativeContentPowerCutAtEveryTransportCall` (`sync/crash_every_call_test.go`), `TestMirrorFirstPushSurvivesAPowerCutAtEveryCall` | +| Random histories against a model | `TestMirrorModel` (`sync/mirror_model_test.go`) | +| File↔directory swaps | `TestMirrorFileDirectorySwap`, `TestMirrorNestedFileDirectorySwaps` | +| Unrecorded and changed entries at a target | `TestMirrorWriteDisplacesWhatThePathHolds`, `TestMirrorRecordChangedBehindSquirrelsBack` | +| A tree squirrel has no record of | `TestMirrorWatermarkRule`, `TestMirrorRefusesATreeItHasNoRecordOf` | +| Foreign entries in staging | `TestMirrorForeignStagingIsLeftAlone`, `TestMirrorLeavesForeignStagingAlone` | +| Symlinks at a target, along its parents, in place of a reserved directory, at an artifact's name | `TestMirrorNeverFollowsASymlinkAtATarget`, `TestMirrorNeverFollowsASymlinkedReservedDirectory`, `TestNativeContentNeverFollowsASymlinkAtAnArtifactName` | +| Names a destination folds | `TestMirrorProbesHowTheDestinationComparesNames`, `TestMirrorRefusesNamesTheDestinationCannotTellApart`, `TestMirrorRefusesTheSecondOfTwoNewNames`, `TestMirrorFollowsARenameThatChangesOnlyCase`, `TestMirrorFoldingMovesAFileOutOfADirectorysWay` (`sync/mirror_fold_test.go`, with a transport that folds names on any disk) | +| Disk full, unwritable history, drift while streaming | `TestMirrorDiskFullMidWrite`, `TestMirrorHistoryUnwritable`, `TestMirrorSourceDriftWhileStreaming`, `TestNativeContentSourceDriftWhileStreaming` (`sync/mirror_hostile_test.go`) | +| Rename onto an existing target | `RenameNeverReplaces` in the contract suite, and `TestSFTPServersRenameOverAnExistingName` | + +`checkInvariants` (`sync/mirror_test.go`) asserts the three invariants; +invariant 1 alone (`checkRecordsVouch`) also runs right after every +injected crash, since it holds at every point of a push. + +## 5. Evidence and verification (reverses #216) + +Until this step, a native mirror push advances its vector as `presence+size`. +Every fingerprint stays pending, so the mirror still can't gate offload. +That's the same as today, only the method name changes. This step changes it +for local mirrors. + +- **Read-back at write time, on local disks.** Once a batch's staged files + are flushed to stable storage, squirrel re-reads each one in full and + hashes it with BLAKE3 before committing it (`sync/readback.go`). So every + fingerprint comes from reading bytes the disk has already reported + persisted; a copy never read back that way never counts for offload. The read bypasses the cache: on Linux the + synced pages are dropped (`POSIX_FADV_DONTNEED`) before the read, and on + macOS both the write and the read run with `F_NOCACHE`, because a read + there is still served from pages the write left cached. It is best + effort: a USB bridge's own cache is out of reach. A mismatch fails the + path before its commit, and the staged copy goes with the run's staging. + + A match records `checksum_algo = blake3` and `verified_at_ns` on the row. + `CountVolumeContentsPendingFingerprint` and `ContentFingerprintVerified` + consult `remote_paths` rows in the `live` and `displaced` states. So a push + advances as `fingerprint-verified` once no present content is pending, as + the content layouts do; the gate accepts that component through the + existing path, which requires a verify cadence or a per-content + fingerprint. Migration v33 indexes `remote_paths` by content for those + per-content reads. +- **sftp mirrors stay non-gating.** An sftp push skips read-back, and mirror + paths never go on a server command line, so their fingerprints stay + pending. +- **Cost.** Read-back is a safety property, so it's always on for local + disks. Every written byte is read once more: about 2 ms for a 230 KB file + on the testbed's exFAT image, a tenth of what a push per file cost before + flushes were batched (section 8). +- **Verify pass for mirrors.** `verify_every` becomes valid on native mirrors. + Each pass does two things: + - It checks the size and mtime of every `live` and `displaced` row with + `Lstat`. Both states count as stored content, so both are checked. This is + cheap and catches deletion, truncation and replacement. + - On local mirrors, it re-hashes a slice of rows, oldest `verified_at_ns` + first (never-verified first of all), until the slice covers a tenth of the + bytes the destination holds (`mirrorRereadShare`, `sync/verify_mirror.go`), + and always at least one row. So every byte is re-read within about ten + passes. Kopia's `verify_files_percent` is the precedent for sampled + read-back. + + A pass first reads every volume's `.squirrel-volume` through the transport + and fails, marking nothing, when one is missing or names another volume: an + unmounted disk or an emptied share must not read as every copy gone. + + Findings latch the existing destination alarm, also when the pass aborts + after recording them, and mark the affected rows `lost` — only while the row + is still in the state the pass read it in, since a push may be moving it. A + finding also demotes the volume's locally advanced `fingerprint-verified` + components to `presence+size` (`DemoteFingerprintVerifiedVector`), at the + runs they cover. Without that, a gate with a verify cadence would still take + the component's word for a lost copy, and a peer pulling the vector would + too; demoted, the gate checks each content's own fingerprint, and the next + push that leaves nothing pending upgrades the component again. `lost` rows whose content is still the index's + current content become the mirror's repairs. A clean pass re-attempts the + `fingerprint-verified` upgrade, as it does for the content layouts. + `squirrel verify` reaches the mirror through its transport, without rclone. +- **Documents amended in the same PR:** + - `CanEverGateOffload` becomes true for native local mirrors, and + `offload_requires` accepts them. sftp mirrors keep refusing, and the + refusal names the reason; + - reference-setup.md's "Offload gate" paragraph; + - guides/offloading.md and layouts/mirror.md; + - the F21 entry in friction-log.md; + - SAFETY-AUDIT.md. + +### The content layouts on the transport + +Content-addressed and packed destinations on `local`, and on `sftp` without +`crypt`, are written through the transport too (`sync/artifacts_transport.go`). +The layouts land every object, pack, placement map and manifest segment +through one small interface, `artifactStore` (`sync/artifacts.go`), whose +other implementation is rclone's, for crypt destinations and for s3, b2 and +gcs. Objects land in batches, like a mirror's paths: at most 64 or 256 MB, +`concurrency` at a time. Each step runs for the whole batch before the next: + +1. every artifact is streamed into `/.squirrel-staging/run-/` + while BLAKE3 hashes the bytes sent — the drift check, over exactly those + bytes — and, on sftp, the hash the server's command computes; then the + batch is flushed; +2. each is confirmed before it gets its name: read back through BLAKE3 on a + local disk, hashed by the server's command on sftp. A match is the + artifact's fingerprint; a mismatch fails the artifact. A server without + the command confirms nothing, and the fingerprint stays pending, as it + does under rclone for such a server; +3. each is renamed onto its name. If the name already holds a file — a crash + between landing and recording, or a failed run's orphan — that file is + confirmed instead (downloaded and hashed when the server runs no command), + or the artifact fails. Squirrel never replaces it; +4. the batch is flushed, and only then is each landed artifact's upload row + recorded, with its fingerprint. An artifact a stall or cancellation kept + from that flush fails, and the push stops after a batch that stalled. + +A pack, the placement map and the manifest segment land alone, through the +same steps. + +`squirrel verify` reads these destinations through the transport too +(`sync/verify_native.go`): once the marker of every volume that synced there +is in place, it lists `objects/` and `packs/` and re-reads every recorded +artifact — through BLAKE3, and through any other hash its row recorded, on a +local disk; through the server's hash command on sftp. An artifact the +server cannot hash this pass (no command, or a row recorded under another +`hash_algo`) is counted unchecked: neither re-confirmed nor a finding. On a +plain destination a BLAKE3 that differs from what the name says (an object's +content hash, a pack's key) is a mismatch, whichever backend reported it. + +The probe runs once per session once the server has answered it; a session +that could not start the command asks again next time. + +The staged copy of a failed artifact goes with the run's staging at the next +push's reconcile. The content layouts' guard commits only onto artifact names +and displaces nothing (section 3). Both native content layouts are gated on +the volume marker like a native mirror, `--init` creating a missing local +root; a missing root is otherwise refused like a missing marker. Before this, +config refused the content layouts on `local` outright, because rclone +addressed local destinations by path; that restriction is gone. + +## 6. Restore, ride-along, recover + +- **Mirror restore with an index** uses the archive restore pipeline + (`sync/restore_mirror.go`): + 1. resolve the present paths; + 2. `Get` each one by path; + 3. BLAKE3 while streaming; + 4. place it. + + Placing goes through a temporary file in the target directory, a sync and a + rename (`sync/restore_place.go`). Archive restore wrote with `O_TRUNC` in + place; both now place the same way. Bytes that fail their hash never reach + the path. A path that already holds its indexed bytes is left alone and + counted as already correct, so an in-place restore moves into + `.squirrel-restore-history/` only what it actually replaces. +- **Mirror restore without an index** (a fresh machine) walks the mirror with + `List` and skips the reserved directories. "Without an index" means the index + holds no present file for the volume: a fresh database, or one whose rows for + the volume are all missing after a rescan of an emptied disk. The receipts, + folded oldest run first, give each path the content its newest present entry + recorded. A file with such an entry is checked against it and refused when it + differs; a file no receipt names can't be checked, so it is restored and + counted in a warning. A receipt that doesn't parse is reported and skipped. +- **`--shallow` changes nothing** on a native mirror restore, as on an archive + restore: every byte is hashed anyway. +- **The marker gate, the snapshot ride-along and its rotation, and `recover + --from` discovery** become transport calls. That removes the rclone-specific + helpers `statRemoteExists`, `catRemote`, `copyTo`, `listSnapshots`, + `deleteFile` and `remoteRootEmpty` for these destinations. + +## 7. Configuration and dispatch + +- **Dispatch.** `HandlerFor` sends every destination on `local`, and on + `sftp` without `crypt`, through squirrel's own transport + (`Destination.Native`): mirrors to the native mirror handler, the content + layouts to their handlers with the transport's artifact store. Crypt + destinations and s3, b2 and gcs keep rclone. +- **sftp settings.** `host`, `port`, `user`, `password`, `key_file`, + `known_hosts_file` and `host_key_algorithms` map onto `ssh.ClientConfig`. + When there is neither password nor key file, squirrel uses ssh-agent, as + rclone does. +- **Host key verification is always on.** Without `known_hosts_file`, + squirrel reads `~/.ssh/known_hosts`. An unknown host is refused, and the + message gives the presented fingerprint and how to trust it. + - **Migration cost:** a config that relied on rclone accepting any host key + stops connecting until the key is pinned. +- **Rclone-only keys are rejected** on native destinations: `checkers` + everywhere, and `hash_algo` on sftp mirrors. On content-addressed and packed + sftp destinations, `hash_algo` still chooses the hash, which now names the + command the transport runs on the server: `md5`, `sha1`, `sha256` (the + default, now for packed as well) or `blake3`, the hashes squirrel also + computes to check the server's answer. rclone's other hashes (`crc32`, + `xxh3`, `xxh128`) stay valid behind crypt only. +- **`concurrency`** is how many files a push writes at once, on every + destination type but kopia: 4 by default on a local disk, 8 on sftp. A storage + server that limits concurrent connections, or a slow disk or USB bridge, + may want it lower. On a destination squirrel writes itself, the files share + one SSH connection (section 3), and each file on sftp also goes out as up + to 64 concurrent write requests (`pkg/sftp`'s default). On a destination + rclone writes, it becomes rclone's `--transfers`; together with + `checkers` it caps the connections rclone opens. + +## 8. What we give up + +- **Implementation independence.** Today rclone walks the source itself. A + file the indexer misses still reaches cloudbox and usb. Once native, every + mirror inherits indexer bugs, and kopia remains the only independent leg. + - reference-setup.md already claims that every copy comes from the same + walker. With a native mirror that becomes literally true. The + kopia-leg section gets amended in the mirror PR to say what the mirrors + no longer cover. + - Decision 7 keeps a cheap mitigation as a candidate. +- **Rclone's tuning and backend know-how.** Rclone brings parallel transfers, + multi-threaded streams, and years of workarounds for sftp servers. The + switch waited for a benchmark on the testbed against rclone: it ran on + 2026-09-24 (below). Native pushes that wrote were several times slower, + and the fix is decided (open question 2, now decision 8). + +### The benchmark + +One macOS laptop (arm64), `main`'s binary (rclone mirrors) against this +branch's (native mirrors), each on a fresh index and a fresh destination: + +- `usb`: an exFAT disk image, so rclone can't clone files on APFS; +- `box`: `rclone serve sftp` on loopback; +- `wan`: the same server behind a proxy that delays every chunk 10 ms each + way (20 ms round trip). + +`pics` is 4540 files, 724 MB (photo years and small documents, from +`test/testbed/gendata`); `trip` is 608 files, 114 MB. "Changed" rewrites 150 +files and adds 150 (30 and 30 on `trip`). Wall time in seconds: + +| Push | usb (pics) rclone | native | box (pics) rclone | native | wan (trip) rclone | native | +|---|---|---|---|---|---|---| +| first | 12.6 | 115.8 | 3.7 | 13.7 | 45.4 | 431.9 | +| unchanged | 0.63 | 0.13 | 2.11 | 0.09 | 7.72 | 1.80 | +| changed | 1.51 | 9.96 | 2.41 | 1.46 | 8.85 | 51.06 | + +A native first push to APFS on the internal disk took 86.4 s. + +That build wrote one path at a time: + +- **Local disks paid for durability.** Every written file was synced to + stable storage — on macOS a full flush of the drive's cache — read back + past the cache, and after its rename both parent directories were synced; + rclone syncs nothing. That was about 18 ms per file on the internal SSD, + and 25 ms on the exFAT image. +- **sftp paid in round trips.** A written path cost about 30 sequential + requests: `Put` checks its target and each parent with `Lstat`, then + creates, writes, closes and sets the mtime; the staged copy, the path's + parents and the path are each looked up again, and the rename checks both + parent chains. At a 20 ms round trip that was about 0.7 s per path, against + rclone's four transfers in flight. +- **Unchanged pushes are faster natively** everywhere: they read squirrel's + records instead of listing both trees. + +**Where the time went.** A push instrumented call by call, 1000 files of +231 MB shaped like the photo tree, on the same laptop: + +| per file | internal APFS disk | exFAT image | +|---|---|---| +| whole push | 19.0 ms | 26.2 ms | +| the three full flushes: the file, then both directories after the commit rename | about 13 ms | 11.5 ms, and they slow the calls after them | +| read-back | 2.0 ms | 1.7 ms | +| each call's parent-chain check for symlinks | 0.5 ms | 0.3 ms | +| the same push with a plain `fsync` in place of each full flush | 2.2 ms | 6.3–8.7 ms | + +So the cost was the number of full flushes, not reading back. +Several paths in flight, each still flushing on its own, took a stripped-down +reproduction only from 22 to 16 ms per file on the exFAT image (15.5 to 9.4 on +APFS); sharing each flush among the paths in flight reached 11 and 3.0; one +flush per step for a batch of 64 reached 3–6 and 0.7. On the exFAT image the +rest is that filesystem's slow file calls (create 0.8, set mtime 1.1, rename +1.7 ms) and the evidence itself: writing past the cache and reading back take +about 3 ms per file, which rclone doesn't spend. + +Over sftp a new path at depth two cost 27 requests, each waiting for the one +before: 20 `Lstat`s (14 re-checking parent chains, 6 the target), 2 lookups +while creating parents, open, write, set mtime, close and rename. At a 20 ms +round trip that measured 632 ms per path, 73% of it in `Lstat`. Several paths +in flight over the one connection scale linearly, with every check kept: 608, +152, 76 and 39 ms per path at 1, 4, 8 and 16 in flight. At 8 that is rclone's +time for the 608-file tree (45 s); rclone itself checks no parent chain and +writes through a symlinked directory (rclone 1.74.1 against the in-process +server). + +**After decision 8** (2026-09-25, same laptop). Three binaries this time — +`main`'s (rclone), this branch just before the change, and this branch with +it — on the same trees regenerated by `gendata` (`pics` 4540 files, 716 MB; +`trip` 608 files, 123 MB), each on a fresh index and destination. The exFAT +image fills as runs pile up and its timings drift with it, so every `usb` run +got a freshly created image, and ran twice (ranges below). Wall time in +seconds: + +| Push | usb (pics) rclone | before | after | box (pics) rclone | before | after | wan (trip) rclone | before | after | +|---|---|---|---|---|---|---|---|---|---| +| first | 19.0–24.2 | 116.1–127.4 | 41.4–43.6 | 3.1 | 16.6 | 5.7 | 46.9 | 409.4 | 49.7 | +| unchanged | 2.7–3.5 | 0.14–0.20 | 0.11 | 1.84 | 0.10 | 0.09 | 7.22 | 1.89 | 1.88 | +| changed | 1.8–2.8 | 9.1–10.1 | 2.9–3.9 | 1.99 | 1.30 | 0.78 | 8.38 | 45.66 | 8.05 | + +- **sftp at a 20 ms round trip is at rclone's speed**, with the default of 8 + paths in flight: 49.7 s against 46.9 s, from 409 s. The instrumented push + measured 91.5 ms per path at 8, 56.5 at 16 and 37.4 at 32, so a + destination on a slow link can go past rclone by raising `concurrency`. +- **A local disk is several times faster than before.** The instrumented + push went from 27.6 to 5.3 ms per file on the exFAT image (19 to 1.2 on + the internal disk). More paths in flight don't help that disk: 9.2 ms per + file at 1, 5.3 at 4, 5.7 at 8, which is why a local disk defaults to 4. + The `usb` "after" column overstates native's time: each of those runs + followed the old build's, and the host disk was still working off their + flushes (below). +- **Unchanged pushes stay faster than rclone everywhere, and so do changed + ones** except on the exFAT image, where a changed push took about 1.4 + times rclone's time in those runs. + +**exFAT, settled** (2026-09-25 afternoon). A timed build broke the first +push to a fresh image into its steps, with the host disk left 30 s to settle +before each run. Staging writes swing between runs (7–25 s) with the host +disk, and so does rclone; the other steps hold still: + +| First push, `pics` to a fresh exFAT image | seconds | +|---|---| +| rclone (`main`) | 18.9–24.9 | +| native, as benchmarked above | 18.5–31.8 | +| native, without the read-back | 19.9–29.9 | +| native, with the live-record fix | 15.4–29.1 (15.4 twice, against rclone's 22.4–22.6) | + +- **The read-back costs about 2 s** of the push (1.7–2.1 s for 716 MB), a + tenth; the per-call symlink checks cost nothing measurable, and renaming + staged copies onto their paths about 5 s. +- **A quadratic scan cost 2.3 s.** For every path with nothing at it, the + writer looked through every live record for records below it, under the + lock the paths in flight share. The writer now counts the live records + below every directory (`sync/mirror_live.go`), so that question is one + lookup: at 30,000 files the displace step fell from 62 s to 0.6 s, and the + whole first push from 81 s to 17 s. + +- **A new dependency:** `github.com/pkg/sftp`. + +## 9. Order of work + +Items 1 to 6 land together on one branch, in this order. The pull request's +checklist splits them into sections for separate sessions: + +1. **Planner.** Extract `pushPlan` and the layout driver from the + content-addressed and packed handlers, and fix the wiped-root rule. Nothing + else changes. The existing tests pass untouched, and a new wiped-root test + is added. +2. **Local.** + - The transport, the name guard and the local implementation. + - The fault-injecting wrapper and the contract suite. + - The native mirror layout with `remote_paths`, and the `usb` push. + - Amend reference-setup.md (the kopia leg, and the `usb` topology arrow) + and layouts/mirror.md. +3. **sftp.** The sftp implementation, host key handling, and plain sftp + mirrors. +4. **Restore, ride-along and recover** on the transport. Once this lands, + `local` and plain `sftp` mirrors are free of rclone. +5. **Evidence.** Read-back fingerprints on local mirrors, the mirror verify pass, and repairs + in the planner. This reverses #216 and amends the design and docs listed in + section 5. +6. **Content-addressed and packed on `local` and `sftp`** move to the + transport. +7. **S3 transport**: step 3 of the plan, on its own branch afterwards. + +The crypt decision is independent of this order. Once made, it becomes a +crypt transport wrapper, and then cloudbox moves. + +## 10. Decisions and open questions + +Decided on 2026-09-23: + +1. **Offload gating on sftp.** Content-addressed and packed sftp destinations + gate through the optional server hash command (section 3), as they do + through rclone today. sftp mirrors stay non-gating, and so does any server + that runs no programs. +2. **Host keys.** They are always verified against `known_hosts_file`, or + against `~/.ssh/known_hosts` when that's unset. Unknown hosts are refused. + Configs that relied on rclone accepting any key must pin it first. +3. **Read-back** runs on local disks only (section 5). +4. **Existing mirror trees aren't adopted.** The watermark rule refuses an + rclone-era mirror: the tree isn't empty, and its runs left no receipts. + An index that never synced there is refused too, by the first-push gate + (rule 1). A native mirror needs a fresh or emptied root. Adoption gets + built only if the testbed shows that hurts. +5. **Receipts** for mirrors live in `.squirrel-index/`. The content layouts + keep their segments where they are. +6. **Case-folding and normalization collisions** refuse only the colliding + path. +7. **No source-completeness audit in this branch.** It stays a candidate. A + periodic check would compare a plain directory walk with the index's + present set, which would restore some independence for every layout. + +Decided on 2026-09-24: + +8. **Throughput of pushes that write** (section 8). Three changes, on this + branch before the switch: + - **One flush per batch.** `Put` and `Rename` stop flushing, and + `Transport.Flush` makes a batch durable (section 3). A mirror and a + content-addressed push write batches of at most 64 files or 256 MB, and + every record waits for the flush that covers its bytes (section 4). The + full read-back runs after the batch's staged files are flushed + (section 5). + - **Several paths in flight**, set per destination by `concurrency` + (section 7), on both transports. + - **Every per-call check stays.** Checking each parent chain once per push + would have cut the sftp round trips by half, but it trusts a directory + for the rest of the push; paths in flight reach rclone's speed without + it. + +Open: + +1. **Crypt byte-compatibility with rclone.** This blocks cloudbox only, and is + to be discussed separately. +2. ~~**Throughput of pushes that write.**~~ Decided on 2026-09-24: + decision 8. diff --git a/design/reference-setup.md b/design/reference-setup.md index 0bf5e7c..d38dc18 100644 --- a/design/reference-setup.md +++ b/design/reference-setup.md @@ -53,9 +53,13 @@ run programs, so it is a dumb **destination**; the NAS can, so it is a ▲ │ └──── durability evidence flows back out to the edges ────┘ - homepc ──rclone──▶ usb (local destination, .squirrel-volume marker) + homepc ──native──▶ usb (local mirror, .squirrel-volume marker) ``` +`native` is squirrel's own transport ([native-mirror.md](native-mirror.md)): +every `local` destination and every `sftp` one without crypt, in any layout. +`rclone` carries the encrypted destinations and the buckets. + Initiation direction follows availability: the intermittently-awake machines (laptop, homepc) initiate toward the always-on nas; the nas initiates toward the always-on htpc. A sleeping laptop can't be dialed, @@ -70,21 +74,22 @@ so nothing ever tries. | **media** | nas (master), htpc | nas → htpc; nas → cloudbox + s3archive | htpc offloads watched items once s3archive holds them | Offload gates may name only targets that *produce durability evidence*. -Three shapes do: content-addressed and packed destinations (presence+size, -upgraded to content-verified by the scan-back fingerprint), peer nodes the -offloading machine itself pushes to (`peer-blake3`), and kopia repositories -(`kopia-verify`). A **mirror** — cloudbox, usb — never yields evidence the -gate accepts. A plain mirror's sync is rclone's `--checksum` compare, which -runs under the first hash both backends support (MD5 on local and s3), never -against the index's BLAKE3; it advances the vector with the `checksum` method -so `status` can show how current the copy is, but the gate refuses it (#211; -#156 had accepted it believing the compare was BLAKE3). A crypt mirror is -weaker still: the overlay hides the content hash, so rclone falls back to -size+mtime (friction log F21). Neither layout keeps a fingerprint a verify -pass could upgrade. Naming a locally-configured mirror in `offload_requires` -is therefore rejected at config load as an unsatisfiable policy — -fail-early, not the wait-forever gate the walk hit with the laptop gating on -the crypt-mirror cloudbox. +Four shapes do: content-addressed and packed destinations (presence+size, +upgraded to content-verified by the scan-back fingerprint), a mirror squirrel +writes itself on a local disk — usb — which reads every copy back through +BLAKE3 before committing it and advances as `fingerprint-verified`, peer nodes +the offloading machine itself pushes to (`peer-blake3`), and kopia +repositories (`kopia-verify`). Every other **mirror** never yields evidence +the gate accepts. The crypt mirror cloudbox is written by rclone: the overlay +hides the content hash, so rclone compares by size+mtime (friction log F21), +and a plain rclone mirror's `--checksum` compare runs under the first hash +both backends support, never against the index's BLAKE3 (#211). A native sftp +mirror reads nothing back, and squirrel never puts its paths — the volume's +own file names — on a server command line. None of those keeps a fingerprint a +verify pass could upgrade. Naming one in `offload_requires` is therefore +rejected at config load as an unsatisfiable policy — fail-early, not the +wait-forever gate the walk hit with the laptop gating on the crypt-mirror +cloudbox. A receive-only node (htpc) cannot credit its *upstream* peer, so its gate rests on the offsites the hub pushes to, reached via the durability pull. @@ -113,6 +118,16 @@ the same disk, with its own end-to-end verification (`snapshot verify`) on every sync, recorded in squirrel's runs table like any other destination. +For usb the shared walker is literal: a native mirror plans from the +index, as the content layouts always did, so a file the indexer misses +never reaches it. An rclone mirror walked the source itself, which let a missed file +still reach it; of the household's copies only cloudbox keeps that until +crypt moves to the native transport, and then none does. What an +independent walk covered is kopia-mirror's job alone, and it covers only +photos and docs. A periodic check comparing a plain directory walk with +the index is the candidate that would give every layout some of that +back (native-mirror.md, decision 7). + Because its purpose is *implementation* redundancy, not geo redundancy (cloudbox and s3archive cover that twice), living on the nas's second disk group is fine: independent, cheap, fast to restore from. It is diff --git a/design/testbed.md b/design/testbed.md index 65acc8e..d252835 100644 --- a/design/testbed.md +++ b/design/testbed.md @@ -15,7 +15,53 @@ machines are five processes on loopback ports. | cloudbox (pure SFTP, no programs) | `rclone serve sftp --user u123456 --pass …` on `127.0.0.1:2222`, serving an empty dir | Exactly the product shape: an SFTP endpoint you cannot run code on. Presents a real host key, so the `known_hosts_file` UX is exercised too | | s3archive | SeaweedFS `weed server -s3` on `127.0.0.1:8333` (same creds/config as `test/integration/s3config.json`) | Already the reference S3 endpoint for the integration tests; proven to produce the composite multipart ETags the fingerprint path depends on | | kopia-mirror | `kopia` binary + a repo directory | Same as production: squirrel drives the CLI | -| usb disk | a plain directory; "unplugging" = renaming it | `local` destination + marker semantics don't care about hardware | +| usb disk | a plain directory; "unplugging" = renaming it. On macOS, an exFAT disk image (`hdiutil create -fs ExFAT -type SPARSE`, attached with `-mountpoint`) is closer: it folds case, gets macOS's `._` companion files, and keeps rclone from cloning files on APFS; "unplugging" = `hdiutil detach` | `local` destination + marker semantics don't care about hardware | + +### The sftp server and native mirrors + +`rclone serve sftp` is also the server the sftp transport's contract suite runs +against: `go test ./sync` starts one per case whenever rclone is on PATH +(`TestSFTPTransportContractAgainstRcloneServe`). It differs from an OpenSSH +server in three ways the suite accounts for: + +- its rename replaces an existing target (`TestSFTPServersRenameOverAnExistingName`), + which is why the transport checks every target first; +- it hides symlinks, so the symlink cases skip there; +- it offers no `fsync@openssh.com`, so a push to it skips the flush. + +cloudbox is an encrypted mirror, so rclone still writes it. To walk a native +sftp mirror, declare a second, plain sftp destination against the same server: + +```toml +[destinations.cloudbox-plain] +type = "sftp" +host = "127.0.0.1" +port = "2222" +user = "u123456" +password = { env = "CLOUDBOX_PASS" } +root = "/plain" +known_hosts_file = ".testbed/cloudbox/known_hosts" +``` + +squirrel refuses the server until its host key is pinned; the first push's +refusal prints the known_hosts line to add. Serve with `--key ` to keep +the key stable across restarts (without it, rclone reuses keys it generated in +its cache directory). + +### Benchmarking native against rclone + +The 2026-09-24 numbers ([native-mirror.md](native-mirror.md), section 8) +came from `main`'s binary and the branch's, each installed with +`GOBIN= go install ./cmd/squirrel` from its own tree, pushing +`gendata` trees on fresh indexes to the exFAT image and to `rclone serve +sftp`. Loopback hides what a real link costs per round trip, so a third +destination reached the same server through a TCP proxy that delays every +chunk by a fixed time each way, kept outside the repo. Restart `rclone serve +sftp` after removing files under its root behind its back: its directory +cache otherwise keeps answering for them. The 2026-09-25 rerun after +decision 8 added the branch's binary from before the change as a third +column, and gave every exFAT run a freshly created image: a sparse image's +timings drift as it fills. Deliberately not simulated: Synology/QNAP packaging (below squirrel), b2/gcs (same shape as s3), real network partitions — a dead machine or diff --git a/docs/src/content/docs/configuration/destinations.md b/docs/src/content/docs/configuration/destinations.md index d624c02..dd405ae 100644 --- a/docs/src/content/docs/configuration/destinations.md +++ b/docs/src/content/docs/configuration/destinations.md @@ -1,6 +1,6 @@ --- title: Destinations & secrets -description: Declare rclone-backed and kopia destinations, resolve secrets from environment variables, and let squirrel own rclone.conf. +description: Declare local, sftp, bucket and kopia destinations, resolve secrets from environment variables, and let squirrel own rclone.conf. --- A **destination** is a named remote (or local directory) that volumes sync to. @@ -27,10 +27,10 @@ root = "/squirrel" ## Supported types -| Type | Backing | Notes | +| Type | Written by | Notes | |---|---|---| -| `local` | rclone | A local directory; requires a `.squirrel-volume` marker (see [first use](/squirrel/guides/syncing/)). | -| `sftp` | rclone | Add `known_hosts_file` to validate the server host key. | +| `local` | squirrel | A local directory; requires a `.squirrel-volume` marker (see [first use](/squirrel/guides/syncing/)). | +| `sftp` | squirrel; rclone with `crypt` | The server's host key must be in `known_hosts_file` or `~/.ssh/known_hosts`. | | `s3` | rclone | Set `provider`, `region`, `bucket`; optional `storage_class`. | | `b2` | rclone | Backblaze B2. | | `gcs` | rclone | Google Cloud Storage. | @@ -46,12 +46,13 @@ password = { env = "NAS_PASSWORD" } ``` An unset environment variable is a hard error at config load — squirrel will not -invoke rclone with a misconfigured destination. +start a transfer to a misconfigured destination. :::caution[Never hand-edit rclone.conf] -Squirrel writes its own `rclone.conf` next to the config file -(`~/.squirrel/rclone.conf`, mode `0600`) on every sync invocation. You do not -run `rclone config` and you should not edit `rclone.conf` by hand. +For the destinations rclone writes, squirrel writes its own `rclone.conf` next +to the config file (`~/.squirrel/rclone.conf`, mode `0600`) on every sync +invocation. You do not run `rclone config` and you should not edit `rclone.conf` +by hand. ::: ## Backend-specific parameters @@ -61,9 +62,13 @@ field) on the others. ### SFTP host-key validation -Without `known_hosts_file`, **rclone does not validate the server's host key** -and will connect to whatever host answers. Set it so a redirected or -impersonated server is rejected. +squirrel checks the host key of every sftp destination it writes — every one +without `crypt` — against `known_hosts_file`, or `~/.ssh/known_hosts` when that +is unset, and refuses a server the file does not hold; the refusal prints the +line that trusts it. On an encrypted sftp destination rclone checks it, and +**without `known_hosts_file` rclone does not validate the server's host key**: +it connects to whatever host answers. Set it so a redirected or impersonated +server is rejected. ```toml [destinations.nas] @@ -76,7 +81,8 @@ known_hosts_file = "~/.ssh/known_hosts" # validate the server host key ( host_key_algorithms = "ssh-ed25519 ssh-rsa" # optional: pin accepted host-key algorithms ``` -Both map to the rclone sftp options of the same name. +On an encrypted destination both map to the rclone sftp options of the same +name. ### S3 storage class @@ -94,10 +100,11 @@ storage_class = "" # archive tiers cost less to store, ## Choosing a layout -By default a destination **mirrors** the volume's tree. Any rclone-remote -destination can instead opt into an append-only, content-addressed or packed -layout, and any non-`local` destination can encrypt contents with a `crypt` -block. See: +By default a destination **mirrors** the volume's tree. Any destination but +kopia can instead opt into an append-only, content-addressed or packed layout, +and any non-`local` destination can encrypt contents with a `crypt` block. +squirrel writes a `local` destination, and an `sftp` one without `crypt`, itself +in every layout; rclone writes the others. See: - [Mirror (default)](/squirrel/layouts/mirror/) - [Encrypted (crypt)](/squirrel/layouts/encrypted/) diff --git a/docs/src/content/docs/guides/agent.md b/docs/src/content/docs/guides/agent.md index af4e7c9..cd72d7b 100644 --- a/docs/src/content/docs/guides/agent.md +++ b/docs/src/content/docs/guides/agent.md @@ -21,10 +21,11 @@ The agent requires an `[agent]` block in config. - **Scheduled audits** — runs [`audit`](/squirrel/guides/auditing/) passes on a schedule. - **Scheduled verify** — re-checks each content-addressed/packed destination's - recorded objects and packs against their upload fingerprints on its - `verify_every` cadence (per-destination, or an `[agent]` default) — the same - pass as [`squirrel verify`](/squirrel/guides/verification/), recorded as an - `audit` run. Offsite bitrot detection stops depending on anyone typing it. + recorded objects and packs against their upload fingerprints, and each native + mirror's recorded copies, on its `verify_every` cadence (per-destination, or + an `[agent]` default) — the same pass as + [`squirrel verify`](/squirrel/guides/verification/), recorded as an `audit` + run. Offsite bitrot detection stops depending on anyone typing it. - **Scheduled durability pull** — refreshes a peer's relayed durability evidence on its `pull_durability_every` cadence, independent of any sync. A receive-only node keeps its [offload](/squirrel/guides/offloading/) gate @@ -44,8 +45,9 @@ Syncs are dispatched **per destination**, so a cloud target that has gone dark does not hold up local NAS→HTPC replication behind it. Two bounds keep a sick destination from occupying its own worker forever: -- every automatic rclone transfer runs with connect and I/O timeouts, so a dead - endpoint fails rather than hanging; +- every automatic transfer has a connect bound — rclone's connect and I/O + timeouts, or a one-minute connect and handshake limit on an sftp destination + squirrel writes itself — so a dead endpoint fails rather than hanging; - a **stall timeout** (10 minutes without progress by default) covers the case those miss — an endpoint that is live but stuck, accepting the connection and then never moving bytes. diff --git a/docs/src/content/docs/guides/offloading.md b/docs/src/content/docs/guides/offloading.md index 39c912c..9e55ac8 100644 --- a/docs/src/content/docs/guides/offloading.md +++ b/docs/src/content/docs/guides/offloading.md @@ -36,13 +36,21 @@ destination/node namespace that `sync_to` uses; they may also name targets only has not arrived yet simply keeps the gate closed. :::caution[An unsatisfiable requirement is a config error, not a closed gate] -A target whose layout can *never* produce evidence the gate accepts — any -[mirror](/squirrel/layouts/mirror/) destination, plain or encrypted — is rejected -when the config loads, rather than leaving a gate that silently never opens. A -mirror sync compares each copy by checksum or by size+mtime, never against the -BLAKE3 in the index, and keeps no fingerprint a verify pass could upgrade. The check covers targets only a peer pushes to as well, -using the capabilities that peer reports. This distinction is the whole point: -a refusal you see always means **not yet**, never **never**. +A target that can *never* produce evidence the gate accepts is rejected when the +config loads, rather than leaving a gate that silently never opens. That is every +[mirror](/squirrel/layouts/mirror/) except one squirrel writes itself on a +`local` disk: + +- a mirror rclone writes (an encrypted one, or one on `s3`, `b2` or `gcs`) + compares each copy by checksum or by size+mtime, never against the BLAKE3 in + the index, and records nothing a verify pass could upgrade; +- a mirror on `sftp` reads nothing back, and never hashes your file names on + the server, so its copies are never fingerprinted. + +A mirror on a `local` disk reads every copy back through BLAKE3 and can gate. +The check covers targets only a peer pushes to as well, using the capabilities +that peer reports. This distinction is the whole point: a refusal you see always +means **not yet**, never **never**. ::: ## The durability gate @@ -66,16 +74,26 @@ Files failing the gate are skipped and reported per target — see ### How a component becomes content-verified -Content-addressed and packed uploads are recorded as `presence+size` at write -time — a crypt remote exposes no hash to compare, and a pack's members are not -individually addressable at the destination. They are **upgraded** when a +A content-addressed or packed push advances its component as +`fingerprint-verified` when every object and pack it holds got a fingerprint as +it landed: always on a local disk, on sftp when the server runs its hash +command, from the provider's checksum on a bucket. Otherwise the component +stays `presence+size` — a server that runs no programs, a crypt remote that +exposes no hash to compare — and is **upgraded** when a [`squirrel verify`](/squirrel/guides/verification/) pass finds every underlying object and pack fingerprint-verified: the component is re-stamped as content-verified and relays to peers that way, so a hub's certified archive can open an edge machine's gate. -The practical consequence: on a cold-archive target, offload becomes possible -after verification has run, not merely after the sync succeeded. Give +A mirror on a `local` disk earns the same upgrade at push time: every copy is +flushed to the disk, then read back through BLAKE3 before it is committed, so +once every file of the volume has such a copy, the push itself advances the +component as `fingerprint-verified`. A copy a verify pass later finds gone or changed stops +counting for its file until the next push writes it again. + +The practical consequence: on a cold-archive target whose fingerprints stay +pending, offload becomes possible after verification has run, not merely after +the sync succeeded. Give `verify` [its own agent cadence](/squirrel/guides/agent/) and this happens unattended; run it by hand and offload waits on you. @@ -137,7 +155,7 @@ The causes, in the order the gate applies them: | **evidence is behind** | The target's coverage of that origin stops at an earlier run than this file's. | | **evidence is too old** | Coverage is sound but was last re-verified outside [`offload_max_evidence_age`](#evidence-staleness-opt-in). | | **not pushed since this file appeared** | No completed whole-volume sync covers the run in which the path became present (re-acquisition). | -| **stored but not content-verified** | The component rests on presence or on a mirror's checksum comparison, not on proof of the bytes; a verify pass upgrades a `presence+size` component. | +| **stored but not content-verified** | The component rests on presence or on an rclone mirror's checksum comparison, not on proof of the bytes; a verify pass upgrades a `presence+size` component, and a local mirror's next push rewrites a copy verify found gone or changed. | ## Evidence staleness (opt-in) diff --git a/docs/src/content/docs/guides/recovery.md b/docs/src/content/docs/guides/recovery.md index 534783a..c421142 100644 --- a/docs/src/content/docs/guides/recovery.md +++ b/docs/src/content/docs/guides/recovery.md @@ -11,17 +11,19 @@ an opt-in operator command. This page collects the recovery paths. ## Resetting a wrecked destination `squirrel destination reset ` forgets everything the index records about -a destination's remote state — its per-content and per-pack upload ledgers, its -live durability vector, and its push-freshness maxima — so the next sync treats -the destination as fresh and re-uploads. +a destination's remote state — its per-content, per-pack and per-mirror-path +upload ledgers, its live durability vector, and its push-freshness maxima — so +the next sync treats the destination as fresh and re-uploads. Use it when a destination's recorded state no longer matches reality and a sync refuses to proceed. The classic case: after wiping a remote, or pointing an -existing destination name at a fresh `root`, the -[content-addressed](/squirrel/layouts/content-addressed/) or -[packed](/squirrel/layouts/packed/) layout guard refuses — its recorded history -under that destination name expects a manifest segment or placement map that is -no longer there. Before this verb, the only escape was hand-editing SQLite or +existing destination name at a fresh `root`, the layout guard refuses — its +recorded history under that destination name expects a +[content-addressed](/squirrel/layouts/content-addressed/) manifest segment, a +[packed](/squirrel/layouts/packed/) placement map, or a native +[mirror](/squirrel/layouts/mirror/)'s receipt that is no longer there. An emptied root is refused too while its upload records remain: +a push would otherwise skip everything those records claim is still there. +Before this verb, the only escape was hand-editing SQLite or renaming the destination across every machine's config. ```sh @@ -36,7 +38,7 @@ clear, and refuses without `--yes` (or a `--dry-run` preview). Cleared (derived state only): -- `remote_objects` and `remote_packs` — the upload ledgers. +- `remote_objects`, `remote_packs` and `remote_paths` — the upload ledgers. - the destination's durability vector and push-freshness rows. Preserved (the audit trail): @@ -64,7 +66,7 @@ recovery legible. When an edge machine dies (the most likely disaster), rebuild it from the hub with a **reverse peer push** — the same peer-sync mechanism the hub uses to feed a receive-only node every day. There is no separate restore verb for -this: `squirrel restore` pulls from bucket destinations, not from peer nodes, +this: `squirrel restore` pulls from destinations, not from peer nodes, and the machinery to push a volume to a node already exists. The story, using the [reference setup](/squirrel/reference/configuration/) @@ -160,14 +162,15 @@ destination carries bytes but no catalog to recover the index from. For a [mirror](/squirrel/layouts/mirror/) destination (including an encrypted one), [`squirrel restore`](/squirrel/guides/restore/) pulls the volume back -byte-for-byte, decrypting on the way down and comparing checksums where the -destination exposes hashes. +byte-for-byte. A native mirror checks every file against the index's BLAKE3, or +against its receipts without an index; an rclone mirror decrypts on the way down +and compares checksums where the backend exposes them. ### Recovering the index too squirrel rides an [index snapshot](/squirrel/configuration/index-snapshots/) -along to destination buckets under `.squirrel-index/`. When the hub itself dies, -a restore-from-cloud yields the data *and* the index that explains it — fetch +along to its destinations under `.squirrel-index/`. When the hub itself dies, +a restore from a destination yields the data *and* the index that explains it — fetch the ride-along snapshot and swap it in as the live index with [`squirrel db restore`](/squirrel/reference/cli/#squirrel-db). `runs` and `query` answer immediately against the recovered catalog. diff --git a/docs/src/content/docs/guides/restore.md b/docs/src/content/docs/guides/restore.md index 277e36b..5130b99 100644 --- a/docs/src/content/docs/guides/restore.md +++ b/docs/src/content/docs/guides/restore.md @@ -1,9 +1,9 @@ --- title: Restoring -description: Pull a volume back from one of its rclone destinations, with content verification on the way down (BLAKE3 for archive layouts, a checksum comparison for mirrors). +description: Pull a volume back from one of its destinations, with content verification on the way down (BLAKE3 for native mirrors and archive layouts, a checksum comparison for rclone mirrors). --- -`squirrel restore` pulls a volume back from one of its rclone destinations. +`squirrel restore` pulls a volume back from one of its destinations. ```sh squirrel restore pictures --from nas @@ -18,22 +18,29 @@ It takes exactly one positional argument — the **volume name**. |---|---|---| | `--from ` | — | Destination name to pull from, **or** peer node name to filter by content origin (names are unique across both kinds). | | `--to ` | volume's declared path | Local target path. | -| `--shallow` | off | Skip the checksum comparison on the way down (mirror destinations). | -| `--dry-run` | off | Preview rclone actions without transferring. | +| `--shallow` | off | Skip the checksum comparison on the way down from an rclone mirror. Every other destination's bytes are re-hashed regardless. | +| `--dry-run` | off | Preview what the restore would fetch without transferring. | | `--in-place` | off | Permit restore against a non-empty live `vol.Path`; overwritten files are moved to `.squirrel-restore-history/run-/`. | ## Verification on the way down -By default, a mirror restore compares each file with its copy by checksum as it -arrives, the same comparison [`sync`](/squirrel/guides/syncing/) uses on the way -up. Pass `--shallow` to skip it. Content-addressed and packed restores re-hash -everything they extract to BLAKE3 regardless (see below). +A [native mirror](#native-mirrors) restore and a content-addressed or packed +restore hash every byte to BLAKE3 as it arrives and refuse what does not match +(see below). A restore from an rclone mirror compares each file with its copy by +checksum as it arrives, the same comparison [`sync`](/squirrel/guides/syncing/) +uses on the way up; pass `--shallow` to skip it. -:::note[Encrypted destinations are always size+mtime] -[Encrypted (`crypt`)](/squirrel/layouts/encrypted/) destinations cannot expose +Every restored file lands through a temporary file beside its path, which is +flushed and then renamed over it, so a restore that stops halfway never leaves a +truncated file behind. + +:::note[Encrypted mirrors are always size+mtime] +An [encrypted (`crypt`)](/squirrel/layouts/encrypted/) mirror cannot expose content hashes through rclone, so restore from one falls back to a size+mtime comparison — recorded as shallow — **even without** `--shallow`, exactly as sync -does. Passing `--shallow` changes nothing for these destinations. +does. Passing `--shallow` changes nothing there. An encrypted content-addressed +or packed destination is different: its restore re-hashes every file to BLAKE3, +with or without crypt. ::: ## Restoring in place @@ -44,6 +51,27 @@ overwrite is first moved to `.squirrel-restore-history/run-/`, mirroring the append-only [`.squirrel-history`](/squirrel/layouts/mirror/) behavior on the sync side. Nothing is destroyed. +## Native mirrors + +A [native mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written) — `local`, +or `sftp` without crypt — is read through squirrel's own transport; no rclone is +involved. + +- **With an index** that holds present files for the volume, each present path + is fetched by its path and its bytes are checked against the index's BLAKE3 + as they stream; a file whose bytes differ is refused, not written. A path that + already holds its indexed bytes is left alone and counted as already correct. +- **Without one** — a fresh machine, before or instead of + [`squirrel recover`](/squirrel/guides/recovery/) — restore walks the mirrored + tree, leaving out `.squirrel-history/`, `.squirrel-index/`, + `.squirrel-staging/` and the marker. The mirror's + [receipts](/squirrel/layouts/mirror/#how-a-mirror-is-written) name the content + each path last held, so every file a receipt names is checked against it and + refused if it differs. A file no receipt names (one squirrel did not write) is + restored unchecked, and the run's warnings count them. The `._` files macOS + keeps beside each file on an exFAT or FAT disk hold that file's extended + attributes; restore leaves them out and counts them in one warning. + ## Content-addressed and packed destinations `squirrel restore` handles the @@ -55,9 +83,11 @@ copy, so restore works from the **local index** instead: 2. The bytes are located per content: a per-hash object under `objects/`, or a member of a `tar.zst` pack under `packs/` (`pack_members` carries its offset and length). -3. Objects and packs are fetched through the same rclone (`crypt`) read path the - push uses. **Packs are fetched once** — one download serves every requested - member of that pack, never one fetch per file. +3. Objects and packs are fetched through the same read path the push uses: + squirrel's own transport on a `local` disk and on `sftp` without crypt, with + no rclone involved, and rclone (and its `crypt` overlay) elsewhere. **Packs + are fetched once** — one download serves every requested member of that + pack, never one fetch per file. 4. Every fetched object and extracted pack member is **re-hashed to BLAKE3 and compared** before it is written, so a misplaced or corrupted byte is refused rather than restored. (Because of this, `--shallow` does not weaken an @@ -90,7 +120,7 @@ restore goes through the kopia CLI (`kopia snapshot restore`) instead. ## Restoring the index too For a full disaster-recovery scenario, remember that squirrel rides an -[index snapshot](/squirrel/configuration/index-snapshots/) along to destination -buckets under `.squirrel-index/`. A restore-from-cloud yields the data *and* the -index that explains it — use [`squirrel db restore`](/squirrel/reference/cli/#squirrel-db) +[index snapshot](/squirrel/configuration/index-snapshots/) along to its +destinations under `.squirrel-index/`. A restore from a destination yields the +data *and* the index that explains it — use [`squirrel db restore`](/squirrel/reference/cli/#squirrel-db) to swap that snapshot in as the live index. diff --git a/docs/src/content/docs/guides/syncing.md b/docs/src/content/docs/guides/syncing.md index c3a2f1c..5e4712c 100644 --- a/docs/src/content/docs/guides/syncing.md +++ b/docs/src/content/docs/guides/syncing.md @@ -3,8 +3,7 @@ title: Syncing & first use description: Push configured volumes to their destinations with checksum verification, and bootstrap first-use destinations safely with --init. --- -`squirrel sync` pushes configured volumes to their rclone (or kopia) -destinations. +`squirrel sync` pushes configured volumes to their destinations. ```sh squirrel sync pictures # all destinations declared on pictures @@ -18,30 +17,39 @@ squirrel sync # every (volume, destination) pair in config ## Verification -Sync compares every file with its copy on a mirror destination by checksum -(rclone's `--checksum`), under the first hash both ends support — MD5 on local -disks and S3, independent of the BLAKE3 in the index. A copy that fails the check -after transfer is an error, so the runs row is **not** marked success. The run is -recorded with the `checksum` method, which the offload gate does not accept, so a -mirror cannot back an offload. Peer syncs are different: both ends hash every -byte with BLAKE3 (see [Peer sync](/squirrel/guides/peer-sync/)). - -Use `--shallow` to fall back to rclone's default size+mtime comparison if you -want speed over integrity for a big initial push. Encrypted +A mirror on a `local` disk is written by squirrel itself: it hashes every file +with BLAKE3 as it streams out, reads each copy back through BLAKE3 before +committing it, and records the run as `fingerprint-verified` once every file +has such a copy (see [Mirror](/squirrel/layouts/mirror/#verification)). That +mirror can back an offload. A native mirror on `sftp` reads nothing back, so +its runs stay `presence+size` and cannot. + +Sync compares every file with its copy on an rclone mirror destination by +checksum (rclone's `--checksum`), under the first hash both ends support — MD5 +on S3, independent of the BLAKE3 in the index. A copy that fails the check after +transfer is an error, so the runs row is **not** marked success. The run is +recorded with the `checksum` method, which the offload gate refuses. + +Peer syncs are different: both ends hash every byte with BLAKE3 (see +[Peer sync](/squirrel/guides/peer-sync/)). + +Use `--shallow` to fall back to rclone's default size+mtime comparison on an +rclone mirror if you want speed over integrity for a big initial push. A +[native mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written) (`local`, or +`sftp` without crypt) refuses it: there is no comparison to switch off. Encrypted ([`crypt`](/squirrel/layouts/encrypted/)) destinations always use the size+mtime comparison, and content-addressed/packed destinations use presence+size plus the [scan-back fingerprint](/squirrel/guides/verification/). -Sync runs do **not** pass `--delete-*` to rclone. Files removed locally remain at -the destination. +Sync never deletes at a destination: files removed locally remain there. ## Flags | Flag | Default | Meaning | |---|---|---| | `--to ` | all | Limit to this destination name. | -| `--shallow` | off | Skip the checksum comparison; trust rclone's size+mtime comparison. | -| `--dry-run` | off | Preview rclone actions without transferring; no runs row is written. | +| `--shallow` | off | Skip the checksum comparison on an rclone mirror; trust rclone's size+mtime comparison. Refused on a native mirror (`local`, or `sftp` without crypt). | +| `--dry-run` | off | Preview what a push would transfer without transferring; no runs row is written. | | `--init` | off | Authorise first-use destination bootstrap (see below). | | `--progress`, `-P` | auto on a TTY | Show a live transfer progress line (files, bytes, rate, ETA). | @@ -57,13 +65,18 @@ squirrel sync pictures --to mirror # every time after `--init` authorises the one-time first-use setup, by destination type: -- **`local` and remote rclone** (`sftp`, `s3`, `b2`, `gcs`) — write a - `.squirrel-volume` marker under the destination's volume directory (on the - filesystem for local, over rclone through the same overlay the transfer uses - for remotes). Every later sync **requires** that marker and refuses if it is +- **`local`, `sftp`, `s3`, `b2`, `gcs`** — write a `.squirrel-volume` marker + under the destination's volume directory, through the same path the transfer + takes: squirrel's own transport on a destination it writes itself (`local`, + or `sftp` without crypt, in any layout), rclone and its overlay everywhere + else. On a `local` destination whose root does not exist yet, + `--init` also creates the root. Every later sync **requires** that marker and refuses if it is missing (a missing marker after the fact almost always means the root is wrong — an unmounted disk, a typo, or an unreachable remote). A marker that names a - *different* volume is always refused, with or without `--init`. This holds + *different* volume is always refused, with or without `--init`. A native + mirror also refuses a volume's first push, `--init` or not, onto a volume + directory that already holds files squirrel has no record of writing (see + [mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written)). This holds across the mirror, content-addressed, and packed layouts: the marker sits at the volume root regardless of layout, and is filtered out of every transfer, comparison, and restore. diff --git a/docs/src/content/docs/guides/verification.md b/docs/src/content/docs/guides/verification.md index 2e3e7e1..cf5a5ab 100644 --- a/docs/src/content/docs/guides/verification.md +++ b/docs/src/content/docs/guides/verification.md @@ -1,12 +1,14 @@ --- title: Offsite verification -description: Content-addressed and packed destinations get a metadata-only integrity check — the scan-back fingerprint — that re-checks stored objects without downloading a byte. +description: squirrel verify re-checks what squirrel stored — content-addressed and packed objects by their fingerprint, a native mirror's copies by size and mtime, and on a local disk by BLAKE3. --- Cold archive storage is exactly the copy you can't cheaply re-download and re-hash. [Content-addressed](/squirrel/layouts/content-addressed/) and -[packed](/squirrel/layouts/packed/) destinations therefore get a metadata-only -integrity check: the **scan-back fingerprint**. +[packed](/squirrel/layouts/packed/) destinations on a bucket therefore get a +metadata-only integrity check: the **scan-back fingerprint**. A destination +squirrel writes itself — `local`, or `sftp` without crypt — is re-hashed in +full instead (below). ## How the scan-back fingerprint works @@ -17,10 +19,11 @@ from the remote and records it in the index next to the upload. Verification then re-fetches the same metadata later and compares **provider value then vs provider value now** — squirrel never recomputes a provider checksum, so provider-specific composite forms are handled as opaque strings, and -**no object body is ever transferred**. +on a bucket **no object body is ever transferred**. -The read is done via a direct S3 `ListObjectsV2` for `s3`, or `rclone lsjson ---hash` for every other backend. +The read is done via a direct S3 `ListObjectsV2` for `s3`, `rclone lsjson +--hash` for every other backend rclone writes, and squirrel's own transport for +a destination it writes itself (below). ## What gets recorded, by backend @@ -36,17 +39,26 @@ The read is done via a direct S3 `ListObjectsV2` for `s3`, or `rclone lsjson storage-class transitions or server-side encryption. For S3-compatible providers whose endpoint the client addresses wrongly, set `force_path_style = true`. +- **`local`** — the BLAKE3 of the stored bytes, which squirrel reads back itself, + past the page cache where the system allows: as each object or pack lands, + before it gets its name, and on every verify pass. Here the fingerprint is a + content check too: an object's BLAKE3 must equal its name, a pack's its key. - **`sftp`** — the checksum computed server-side by the remote's hash command. - Content-addressed sftp destinations default to **SHA-256** (`hash_algo = - "sha256"`); set `hash_algo` if your server only offers another type. + Content-addressed sftp destinations, and packed ones without crypt, default + to **SHA-256** (`hash_algo = "sha256"`); set `hash_algo` if your server only + offers another type. Without `crypt` squirrel runs the command itself — `md5sum`, `sha1sum`, + `sha256sum` or `b3sum`, probed once per session — on the staged copy before it + gets its name, and checks the answer against the bytes it sent. A server that + runs no programs leaves every fingerprint pending, with a warning. The command + line carries only the destination root and the artifact's hex name, and only + when both hold nothing but letters, digits, `.`, `_`, `-` and `/`. - **other backends** — whatever hash `rclone lsjson --hash` exposes, recorded under its rclone hash name (e.g. `sha1` on b2). A backend exposing no checksum leaves the fingerprint pending, with a warning in the sync output. ## Running verify -Re-verify a destination (or all content-addressed and packed destinations) at any -time: +Re-verify a destination (or every destination verify covers) at any time: ```sh squirrel verify archive @@ -54,15 +66,21 @@ squirrel verify ``` With no argument, `verify` covers every content-addressed or packed destination -in config. An explicit destination must have one of those layouts, else it -errors. +and every [native mirror](#native-mirrors) in config. An explicit destination +must be one of those, else it errors: a mirror rclone writes records nothing to +re-check. -The pass lists the destination's `objects/` directory once (batched, -metadata-only), then per recorded object: +The pass lists the destination's `objects/` directory once (batched, and +metadata-only on a bucket; on a `local` destination squirrel re-reads every +recorded artifact, on plain sftp the server re-hashes each one), then per +recorded object: - a **match** stamps the object verified in the index; - an object **without a fingerprint yet** (uploaded before this feature, or whose capture failed) gets one recorded and is counted separately; +- an object an sftp server **cannot hash this pass** — its hash command is + gone, or the object was fingerprinted under another `hash_algo` — is counted + as `unchecked`: neither re-confirmed nor a finding; - a **mismatch or missing object** prints one loud line per object and exits non-zero — that is potential offsite corruption or tampering, and squirrel deliberately leaves both the destination and the recorded fingerprint untouched @@ -81,8 +99,12 @@ gate refuses that method. When a pass leaves every object and pack of a durability vector to a content-verified method** and re-attempts any advance that was held back, relaying the upgraded method to peers. -So on a cold archive the sequence is sync → verify → offloadable, not sync → -offloadable. Giving verify [its own agent cadence](/squirrel/guides/agent/) +A push whose objects all got their fingerprint as they landed advances the +vector content-verified by itself: squirrel reads each one back on a local disk, +hashes it with the server's command on sftp, and scans it back right after the +upload elsewhere. Where a fingerprint stays pending — a server that runs no +programs, a backend that exposes none at upload — the sequence is sync → verify +→ offloadable, not sync → offloadable. Giving verify [its own agent cadence](/squirrel/guides/agent/) (`verify_every`) keeps that unattended. ## A mismatch latches an alarm @@ -116,13 +138,39 @@ locally from the crypt passwords. Verification is otherwise identical, so keying the names costs no depth of checking and no offload eligibility. ::: +## Native mirrors + +A [mirror](/squirrel/layouts/mirror/) squirrel writes itself — on a `local` +disk, or on `sftp` without crypt — records every copy it stored, so verify +re-checks those instead of objects. It reaches the mirror through squirrel's own +transport, without rclone. Each pass: + +- checks every copy squirrel stored, the live ones and those in + `.squirrel-history`, by size and mtime — one `lstat` each; +- on a `local` disk, also re-reads the least recently checked copies through + BLAKE3, until it has read a tenth of the stored bytes, so every byte is read + again within about ten passes. + +A pass first reads every volume's `.squirrel-volume` marker and stops, checking +nothing, when one is missing: an unmounted disk must not read as every copy +gone. A copy found gone or changed prints one loud line, latches the +[alarm](#a-mismatch-latches-an-alarm), and stops counting as evidence for its +file: the volume's evidence drops to `presence+size`, so offload checks each +file's own copy until the next push writes the lost one again. The next push writes it again as long as the index still holds that file +there, with a warning; the copy that was found keeps its place in history if the +push has to move it aside. + +A local mirror earns its fingerprints at push time: every copy is flushed to the +disk, then read back through BLAKE3 before it is committed. An sftp mirror is checked by size and +mtime alone, and never gates offload. + ## Related knobs ```toml [destinations.archive] # ... hash_algo = "sha256" # sftp only: which server-side hash the fingerprint uses -checkers = 4 # cap rclone's concurrent checkers +checkers = 4 # rclone destinations only: cap rclone's concurrent checkers force_path_style = true # s3 only: path-style bucket addressing for the ETag reader ``` diff --git a/docs/src/content/docs/layouts/content-addressed.md b/docs/src/content/docs/layouts/content-addressed.md index 04df7fe..44f8a02 100644 --- a/docs/src/content/docs/layouts/content-addressed.md +++ b/docs/src/content/docs/layouts/content-addressed.md @@ -4,9 +4,10 @@ description: An append-only, content-addressed layout for cold archive storage w --- By default a destination [mirrors](/squirrel/layouts/mirror/) the volume's tree. -Any rclone-remote destination — with or without a [`crypt`](/squirrel/layouts/encrypted/) -block — can instead opt into an **append-only, content-addressed** layout, built -for cold archive storage where objects should never be rewritten or moved. +Any destination but kopia — a `local` disk, or an `sftp` server, `s3`, `b2` or +`gcs` with or without a [`crypt`](/squirrel/layouts/encrypted/) block — can +instead opt into an **append-only, content-addressed** layout, built for cold +archive storage where objects should never be rewritten or moved. ```toml [destinations.archive] @@ -40,12 +41,40 @@ Deduplication is unaffected — identical content still derives one name and uploads once. ::: +## How it is written + +On a `local` disk, and on an `sftp` server without `crypt`, squirrel writes the +destination itself, without rclone. Objects land in batches of up to 64, +several at once ([`concurrency`](/squirrel/reference/configuration/#common-keys)); +a manifest segment lands alone. Each: + +1. streams into `/.squirrel-staging/run-/` while BLAKE3 hashes the + bytes sent, and is refused if they no longer match the index; the batch is + then flushed to stable storage; +2. is confirmed before it gets its name: read back through BLAKE3 on a local + disk, hashed by the server's `hash_algo` command (`sha256sum` by default) on + sftp. A match becomes the object's fingerprint; +3. is renamed onto its name. A file already at that name is never replaced: + squirrel checks that it holds the right bytes, or fails the object; +4. is recorded, with its fingerprint, once a second flush has made the batch's + renames durable. + +A server that runs no programs takes every object all the same, but +fingerprints nothing: those objects stay pending, with a warning, and the +destination cannot gate offload for them. Both kinds of destination carry the +`.squirrel-volume` marker, written under `--init`, which also creates a missing +local root. + +Encrypted destinations, and those on `s3`, `b2` and `gcs`, are written by +rclone. + ## Transactional durability Durability is **transactional per run**: the run only counts as successful — and only then feeds the durability evidence squirrel records per destination — once *both* all its content objects *and* its manifest segment are confirmed on the -remote (each transfer's success plus a follow-up presence/size listing). +remote: squirrel confirms each artifact it writes itself as it lands, and +rclone's transfers are followed by a presence/size listing. A failed run may leave objects without a segment; they are harmless (nothing maps them) and the next run skips re-uploading anything already recorded, pushing only @@ -53,30 +82,33 @@ what's missing. ## Properties that differ from mirrored destinations -- **Verification is presence+size**, recorded as such: each object is - re-hashed with BLAKE3 before upload and confirmed present at the expected size - after it, but its stored bytes are not compared at transfer time (and `crypt` - remotes expose no hashes at all), so the runs row is recorded shallow and the push never claims content - verification. On top of that, each upload's provider-side ciphertext - fingerprint is recorded and re-checked by - [`squirrel verify`](/squirrel/guides/verification/). +- **Verification is presence+size**, recorded as such: each object is hashed + with BLAKE3 on its way out and confirmed present at the expected size after + it, and the runs row is recorded shallow. On top of that, each object's + fingerprint is recorded — confirmed at landing where squirrel writes the + destination itself, read back from the provider after the upload elsewhere + (the ciphertext's, behind `crypt`) — and re-checked by + [`squirrel verify`](/squirrel/guides/verification/). A push whose volume is + fingerprinted throughout advances as `fingerprint-verified`. - **Pick the layout when the destination is first used.** Switching an existing mirrored destination to `content-addressed` (or back) is not supported — point the new layout at a fresh destination or root. The push detects a mirrored history and refuses. - **[`squirrel restore`](/squirrel/guides/restore/) restores the layout**: it resolves each present path to its content hash from the local index, fetches - the per-hash object through the same rclone (`crypt`) read path the push uses, - and re-hashes it before writing. When the local index itself is lost, the + the per-hash object through the same read path the push uses — squirrel's + own, or rclone and its `crypt` overlay — and re-hashes it before writing. When the local index itself is lost, the format is deliberately simple enough to [recover without squirrel](/squirrel/reference/formats/#disaster-recovery-without-squirrel). -- **`--dry-run` is not supported yet on the push** (it previews restore). +- **`--dry-run` previews the push**: the objects it would upload and their + bytes, written nowhere. ## Offsite verification Cold archive storage is exactly the copy you can't cheaply re-download and -re-hash. Content-addressed destinations therefore get a metadata-only integrity -check — the **scan-back fingerprint** — that never transfers an object body. See +re-hash. Content-addressed destinations on a bucket therefore get a +metadata-only integrity check — the **scan-back fingerprint** — that never +transfers an object body; one squirrel writes itself is re-hashed in full. See [Offsite verification](/squirrel/guides/verification/) for how it works per backend and how to run `squirrel verify`. @@ -86,7 +118,7 @@ backend and how to run `squirrel verify`. [destinations.archive] # ... hash_algo = "sha256" # sftp only: which server-side hash the fingerprint uses -checkers = 4 # cap rclone's concurrent checkers (providers that limit connections) +checkers = 4 # rclone destinations only: cap rclone's concurrent checkers force_path_style = true # s3 only: path-style bucket addressing for the ETag reader ``` diff --git a/docs/src/content/docs/layouts/encrypted.md b/docs/src/content/docs/layouts/encrypted.md index 749c501..5ed0041 100644 --- a/docs/src/content/docs/layouts/encrypted.md +++ b/docs/src/content/docs/layouts/encrypted.md @@ -1,11 +1,14 @@ --- title: Encrypted (crypt) -description: Any non-local destination can encrypt file contents client-side before upload via rclone's crypt overlay. On the append-only layouts the stored names are keyed too; verification falls back to size+mtime. +description: An sftp, s3, b2 or gcs destination can encrypt file contents client-side before upload via rclone's crypt overlay. On the append-only layouts the stored names are keyed too; an encrypted mirror compares by size+mtime. --- -Any non-`local` destination can add a `crypt` block to encrypt file contents -client-side before upload, via rclone's [crypt](https://rclone.org/crypt/) -overlay. +An `sftp`, `s3`, `b2` or `gcs` destination can add a `crypt` block to encrypt +file contents client-side before upload, via rclone's +[crypt](https://rclone.org/crypt/) overlay. rclone writes every encrypted +destination, so on sftp the crypt block also moves the server's host key check +to rclone, which accepts whatever key the server presents unless +`known_hosts_file` is set (see [sftp keys](/squirrel/reference/configuration/#sftp)). ```toml [destinations.offsite.crypt] @@ -115,11 +118,11 @@ Losing the passwords costs you the ability to *locate* an artifact as well as to decrypt it. ::: -### Verification falls back to size+mtime +### An encrypted mirror compares by size+mtime rclone crypt remotes cannot expose content hashes, so the checksum comparison (`--checksum`) cannot pass through the overlay. Transfers to and -from an encrypted destination compare by **size+mtime** instead — the same +from an encrypted mirror compare by **size+mtime** instead — the same comparison `--shallow` uses — and say so in the run output; the runs row records the transfer as shallow. diff --git a/docs/src/content/docs/layouts/mirror.md b/docs/src/content/docs/layouts/mirror.md index 765368c..8b038f2 100644 --- a/docs/src/content/docs/layouts/mirror.md +++ b/docs/src/content/docs/layouts/mirror.md @@ -12,44 +12,132 @@ destination without a `layout` key. pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg + .squirrel-index/run-12 # receipt: what run 12 changed (native mirrors) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) + .squirrel-staging/ # in-flight writes (native mirrors) docs/ invoice.pdf .squirrel-history/run-9/invoice.pdf ``` +## How a mirror is written + +On a `local` destination, and on an `sftp` destination without +[crypt](/squirrel/layouts/encrypted/), squirrel writes the mirror itself: a +*native* mirror. A push plans from +the index: it sends the changes recorded since the destination's last confirmed +run, not what a fresh walk of the disk finds. It writes the changed paths in +batches of up to 64 files, several at once +([`concurrency`](/squirrel/reference/configuration/#common-keys)). For each +batch it: + +1. streams every file into `.squirrel-staging/run-/`, hashing the bytes as + they go, and refuses a path if they no longer match the index; then it + flushes the batch to stable storage; +2. on a `local` disk, reads every staged copy back through BLAKE3, past the + page cache where the system allows, and refuses a path if the disk returns + other bytes; +3. moves whatever each path holds into `.squirrel-history/run-/`; +4. renames each staged copy onto its path. The rename never replaces a file. + +squirrel records each move before making it, and confirms it only once a flush +has made it durable, so the next push finishes or withdraws whatever a crashed +or unplugged push, or a power cut, left half done. Every successful +push leaves a **receipt** at `.squirrel-index/run-`: the run's changes in the +[manifest segment format](/squirrel/reference/formats/), so the mirror can be +checked without the index. A push that finds no receipt for the last success it +recorded refuses, unless the root is empty and squirrel holds no records for it. +A volume's first push refuses too when its directory already holds files +squirrel has no record of writing. So a native mirror starts on a fresh or +emptied root: squirrel does not adopt a tree some other tool wrote, rclone +included. If the tree is a native mirror whose index you lost, recover the +index from it with [`squirrel recover --from`](/squirrel/guides/recovery/) +instead: the index snapshots and receipts on the mirror let the next push carry +on where the last one stopped. + +### Names a disk can't tell apart + +Disks formatted APFS or HFS+ (macOS), exFAT or NTFS treat `a.jpg` and `A.jpg` +as one name, and APFS and HFS+ also treat a composed `é` and an `e` followed by +a combining accent as one. Before its first write, each push checks how the +destination compares names with one small file in `.squirrel-staging/`. + +- When two of your files have names the destination can't tell apart, or one + file's name matches the other's directory, only one of them is written: the + one already on the destination, otherwise the first by name. The other is + left out and nothing moves for it, every other file still lands, and the run + fails with a warning naming both spellings. Rename one of them, index, and + sync again. +- A file you renamed only in case moves from its old spelling into + `.squirrel-history/` and lands under the new one. +- A directory keeps the spelling it was created with: after you rename + `Photos/` to `photos/`, the files land inside the existing `Photos/`. + +On sftp, squirrel checks the server's host key against `known_hosts` and refuses +a server it does not know (see [sftp keys](/squirrel/reference/configuration/#sftp)). + +Encrypted mirrors, and mirrors on `s3`, `b2` and `gcs`, are written by rclone, +which compares both trees and moves overwritten files into its `--backup-dir`. + ## Append-only history -`.squirrel-history/run-/` is rclone's `--backup-dir` target for that -sync run. When a file at the destination is about to be overwritten, its prior -bytes are moved here first — never deleted. +`.squirrel-history/run-/` holds the prior bytes of every file a sync run +replaced. They are moved there first, never deleted. +- On a native mirror, anything found at a path squirrel is about to write moves + there, including bytes squirrel did not write. The run names each one in a + warning and in its audit trail. - It is **filtered out** of all subsequent comparisons, so it does not grow - rclone's listing time or get uploaded back. + listing time or get uploaded back. - A directory literally called `.squirrel-history` in your source volume is also filtered (with a warning), to keep the reserved name out of the destination tree by accident. -Sync runs do **not** pass `--delete-*` to rclone. Files removed locally remain -at the destination. +Files removed locally remain at the destination. ## Verification -Sync compares every file with its copy by checksum (rclone's `--checksum`), -under the first hash both ends support — MD5 on local disks and S3, independent +A native mirror push hashes every file with BLAKE3 as it streams out and +confirms each written path's size and mtime. What else backs it depends on +where the mirror lives: + +- **On a `local` disk**, every copy is flushed to the disk, then read back in + full through BLAKE3 before it is committed, and the match is recorded as the + copy's fingerprint. Once every + file of the volume has such a copy, the run advances the destination's + durability evidence as `fingerprint-verified`. A local mirror can therefore be + named in [`offload_requires`](/squirrel/guides/offloading/). +- **On sftp**, nothing is read back: a mirror's paths are your own file names, + and squirrel never puts them on a server command line to hash them there. The + run advances as `presence+size`, and an sftp mirror cannot gate offload. Use a + [content-addressed](/squirrel/layouts/content-addressed/) or + [packed](/squirrel/layouts/packed/) sftp destination for that. + +[`squirrel verify`](/squirrel/guides/verification/) re-checks a native mirror, +on demand or on the agent's `verify_every` cadence. Each pass checks every copy +squirrel stored — the live ones and those in `.squirrel-history` — by size and +mtime. On a local disk it also re-reads the least recently checked copies, a +tenth of the stored bytes per pass, so every byte is read again within about ten +passes. A copy found gone or changed stops counting as evidence, raises the +destination's alarm, and is written again by the next push while the index still +holds that file. + +`--shallow` is refused on a native mirror: there is no comparison to switch off. + +An rclone mirror compares every file with its copy by checksum (rclone's +`--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an -error, so the run is not marked success. The run advances the destination's -durability evidence under the `checksum` method, which -[`squirrel status`](/squirrel/reference/cli/) shows but the offload gate does not -accept: a mirror cannot be named in -[`offload_requires`](/squirrel/guides/offloading/). See -[Syncing & first use](/squirrel/guides/syncing/). +error, so the run is not marked success, and the run advances the evidence under +the `checksum` method. [`squirrel status`](/squirrel/reference/cli/) shows it, +but the offload gate refuses it, and an rclone mirror cannot be named in +`offload_requires`. See [Syncing & first use](/squirrel/guides/syncing/). ## Index snapshots `.squirrel-index/` holds the [index snapshots](/squirrel/configuration/index-snapshots/) -ridden along after each successful sync. Like `.squirrel-history`, it is filtered -out of all sync and restore transfers and from peer-sync. +ridden along after each successful sync, and a native mirror's receipts. Like +`.squirrel-history`, it is filtered out of all sync and restore transfers and +from peer-sync. ## When to use another layout diff --git a/docs/src/content/docs/layouts/packed.md b/docs/src/content/docs/layouts/packed.md index c9539fd..e5a4b48 100644 --- a/docs/src/content/docs/layouts/packed.md +++ b/docs/src/content/docs/layouts/packed.md @@ -60,11 +60,15 @@ destination's durability evidence only once *all three* of its artifacts — eve pack, the run's `packs/map-`, and its `index/run-` segment — are confirmed on the remote **and** every pack has a verified scan-back fingerprint. -A pack's fingerprint is read straight back from the provider after upload (one -check per ~512 MB pack vouches for every file it holds — the packed analogue of -the per-object scan-back). If that read is unavailable, the pack is left -**pending** with a warning and the vector is *not* advanced, so unverified packed -content is never counted durable. +A pack's fingerprint is confirmed as it lands where squirrel writes the +destination itself — read back through BLAKE3 on a `local` disk, hashed by the +server's command on `sftp` (see +[how it is written](/squirrel/layouts/content-addressed/#how-it-is-written)) — +and read straight back from the provider after upload elsewhere. One check per +~512 MB pack vouches for every file it holds, the packed analogue of the +per-object fingerprint. If none is available, the pack is left **pending** with +a warning and the vector is *not* advanced, so unverified packed content is +never counted durable. [`squirrel verify`](/squirrel/guides/verification/) fills any pending pack fingerprint and re-confirms the rest, per pack. @@ -72,10 +76,14 @@ fingerprint and re-confirms the rest, per pack. Properties match the content-addressed layout: +- It is written by squirrel itself on a `local` disk and on `sftp` without + `crypt`, and by rclone elsewhere, in the + [same way](/squirrel/layouts/content-addressed/#how-it-is-written). - Verification is presence+size (recorded shallow). - The layout is chosen at first use and refuses to run against a differently-shaped history. -- `--dry-run` is not supported yet on the push. +- `--dry-run` previews the push: the objects and pack members it would upload, + written nowhere. - [`squirrel restore`](/squirrel/guides/restore/) **restores the layout**: it resolves each present path to its content in the local index, fetches each pack once to serve all its members, and re-hashes every extracted member diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index b7199a0..af65a9a 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -95,7 +95,7 @@ Indexing by raw path is not supported. See [Indexing](/squirrel/guides/indexing/ ## squirrel sync -**Push configured volumes to their rclone destinations.** +**Push configured volumes to their destinations.** ``` squirrel sync [] @@ -108,8 +108,8 @@ Optional single positional. No arg = every `(volume, destination)` pair; one arg | Flag | Default | Meaning | |---|---|---| | `--to` | all | Limit to this destination name. | -| `--shallow` | `false` | Skip the checksum comparison on mirror destinations; trust rclone's size+mtime comparison. A peer sync hashes every byte on both ends regardless. | -| `--dry-run` | `false` | Preview rclone actions without transferring; no runs row is written. | +| `--shallow` | `false` | Skip the checksum comparison on rclone mirror destinations; trust rclone's size+mtime comparison. Refused on a native mirror (`local`, or `sftp` without crypt), which has no comparison to skip. A peer sync hashes every byte on both ends regardless. | +| `--dry-run` | `false` | Preview what a push would transfer without transferring; no runs row is written. | | `--init` | `false` | Authorise first-use destination bootstrap. | | `--progress`, `-P` | auto on a TTY | Show live transfer progress (files, bytes, rate, ETA). | @@ -214,22 +214,24 @@ renders the same facts from the same query layer — see ## squirrel verify -**Re-check recorded offsite objects and packs against their upload fingerprints.** +**Re-check what squirrel recorded storing on a destination: objects and packs against their upload fingerprints, a native mirror's copies by size and mtime, and on a local disk a rotating tenth of them by BLAKE3.** ``` squirrel verify [] ``` Optional single positional. If omitted, verifies every content-addressed or -packed destination in config (sorted). An explicit destination must have layout -`content-addressed` or `packed`, else it errors. No flags. See +packed destination and every native mirror in config (sorted). An explicit +destination must be one of those, else it errors: a mirror rclone writes records +nothing to re-check. No flags. See [Offsite verification](/squirrel/guides/verification/). A clean pass does two things beyond reporting: it fills any pending fingerprints and then **upgrades the destination's durability vector to a content-verified method**, which is what lets [`offload`](#squirrel-offload) accept it. A mismatch **latches a standing alarm** on the destination that survives the run and shows -on every surface until acknowledged. +on every surface until acknowledged. On a native mirror, a copy found gone or +changed is also marked lost, and the next push writes it again. ### squirrel verify ack @@ -313,7 +315,7 @@ Takes no arguments. Lists every kind of run — `index`, `sync`, `restore`, Under routine cadences most rows are no-ops (a pair checked, nothing to do). `--changes` keys on the count of files a run actually changed, so it folds away -bucket pushes and index runs too, not just peer-sync no-ops. Runs recorded +destination pushes and index runs too, not just peer-sync no-ops. Runs recorded before that count existed are shown rather than silently folded — their change count is genuinely unknown. @@ -402,7 +404,7 @@ winner live. Adopting the preserved version instead is a deliberate ## squirrel restore -**Pull a volume back from one of its rclone destinations.** +**Pull a volume back from one of its destinations.** ``` squirrel restore @@ -414,13 +416,18 @@ Exactly one positional — the volume name. See [Restoring](/squirrel/guides/res |---|---|---| | `--from` | — | Destination name to pull from, or peer node name to filter by content origin. | | `--to` | volume's declared path | Local target path. | -| `--shallow` | `false` | Skip the checksum comparison on the way down (mirror destinations). | -| `--dry-run` | `false` | Preview rclone actions without transferring. | +| `--shallow` | `false` | Skip the checksum comparison on the way down from an rclone mirror. Native mirrors and the content-addressed and packed layouts are always re-hashed to BLAKE3. | +| `--dry-run` | `false` | Preview what the restore would fetch without transferring. | | `--in-place` | `false` | Permit restore against a non-empty live path; overwritten files move to `.squirrel-restore-history/run-/`. | -Restore from an [encrypted (`crypt`)](/squirrel/layouts/encrypted/) destination -is always a size+mtime comparison (recorded shallow) even without `--shallow`, -because rclone crypt remotes don't expose content hashes. +A [native mirror](/squirrel/guides/restore/#native-mirrors) restore needs no rclone: +with an index it checks each path against it, and without one it walks the mirror +and checks each file against the mirror's receipts. + +Restore from an [encrypted (`crypt`)](/squirrel/layouts/encrypted/) mirror is +always a size+mtime comparison (recorded shallow) even without `--shallow`, +because rclone crypt remotes don't expose content hashes. An encrypted +content-addressed or packed restore re-hashes every file to BLAKE3. --- @@ -477,8 +484,8 @@ On its own it prints help. See [Recovery & disaster runbooks](/squirrel/guides/r squirrel destination reset ``` -One positional — the destination name. Clears the `remote_objects`/`remote_packs` -upload ledgers, the durability vector, and the push-freshness rows for the +One positional — the destination name. Clears the +`remote_objects`/`remote_packs`/`remote_paths` upload ledgers, the durability vector, and the push-freshness rows for the destination, so the next sync treats it as fresh and re-uploads. The runs table and the append-only durability advance log are preserved, and the reset is recorded as an audit run; the remote bytes are untouched. diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index 7070445..f73d594 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -25,7 +25,7 @@ table resolved at load time. | `sync_to` | no | List of destination names to push to. | | `sync_every` | no | Duration; the [agent](/squirrel/guides/agent/) syncs this volume to every target in `sync_to` on this cadence. Absent = no scheduled sync. | | `index_every` | no | Duration; cadence for *standalone* index passes between syncs (a sync indexes first anyway). Absent = no extra indexing. | -| `offload_requires` | no | List of targets whose durability must cover a file before its local bytes may be [offloaded](/squirrel/guides/offloading/). A volume without this key refuses to offload. Naming a mirror destination is a config error: a mirror can never produce evidence the gate accepts. | +| `offload_requires` | no | List of targets whose durability must cover a file before its local bytes may be [offloaded](/squirrel/guides/offloading/). A volume without this key refuses to offload. Naming a mirror destination is a config error, except a native mirror on a `local` disk: every other mirror can never produce evidence the gate accepts. | | `offload_max_evidence_age` | no | Duration; a target whose durability evidence was last re-verified longer ago than this refuses the offload. Default disabled. | ### `[volumes..hook]` @@ -46,7 +46,8 @@ See [Hooks](/squirrel/guides/hooks/). |---|---|---| | `type` | all | `local`, `sftp`, `s3`, `b2`, `gcs`, or `kopia`. | | `root` | all | Base path (or bucket sub-path) at the destination. | -| `layout` | rclone remotes | `mirror` (default), `content-addressed`, or `packed`. | +| `layout` | every type but kopia | `mirror` (default), `content-addressed`, or `packed`. | +| `concurrency` | every type but kopia | How many files a push writes at once (optional; a positive integer). On a destination squirrel writes itself the default is `4` on `local` and `8` on `sftp`, where every file in flight shares one SSH connection; lower it for a slow disk or USB bridge, or a server that answers one request at a time. On a destination rclone writes (crypt, `s3`, `b2`, `gcs`) it caps rclone's concurrent transfers (`--transfers`), whose default applies otherwise. | ### `local` @@ -59,14 +60,31 @@ See [Hooks](/squirrel/guides/hooks/). | Key | Meaning | |---|---| | `host` | Server hostname. | -| `port` | SSH port (optional; rclone's default when omitted). | +| `port` | SSH port (optional; `22` when omitted). | | `user` | SSH user. | | `password` | Secret (literal or `{ env }`). | -| `key_file` | Path to a private key file, as an alternative to `password` (optional). | +| `key_file` | Path to a private key file, as an alternative to `password` (optional; a leading `~/` is expanded). A passphrase-protected key goes through ssh-agent instead. | | `root` | Base path on the server. | -| `known_hosts_file` | Path to a known_hosts file; **validates the server host key** (recommended). Without it, rclone connects to whatever host answers. | +| `known_hosts_file` | Path to a known_hosts file holding the server's host key (a leading `~/` is expanded). | | `host_key_algorithms` | Space-separated list pinning accepted host-key algorithms (optional). | +With neither `password` nor `key_file` set, squirrel logs in with the keys of the +running ssh-agent (`SSH_AUTH_SOCK`). + +An sftp destination without [crypt](/squirrel/layouts/encrypted/), in any +layout, is written by squirrel itself: it connects to the server, and **always +checks its host key**, against `known_hosts_file` or `~/.ssh/known_hosts` when +that is unset. A server whose key the file does not hold is refused; the message +gives the key's fingerprint and the known_hosts line that trusts it, to add once +you have confirmed it. A key that differs from the pinned one is refused too. +Unless `host_key_algorithms` is set, squirrel asks the server for the key types +the file holds for it. `checkers` tunes rclone, so these destinations reject it, +and a mirror rejects `hash_algo`, since it runs no command on the server. + +An encrypted sftp destination is written by rclone, which checks the host key +against `known_hosts_file` and accepts whatever key the server presents when it +is unset. + ### `s3` | Key | Meaning | @@ -134,13 +152,13 @@ For `layout = "content-addressed"` or `layout = "packed"` destinations. See | Key | Applies to | Default | Meaning | |---|---|---|---| -| `hash_algo` | sftp | `sha256` | Which server-side hash the [scan-back fingerprint](/squirrel/guides/verification/) uses. | -| `checkers` | rclone remotes | rclone default | Cap rclone's concurrent checkers (`--checkers`). | +| `hash_algo` | sftp, except a mirror without crypt | `sha256` | Which server-side hash the [fingerprint](/squirrel/guides/verification/) uses. On a content-addressed or packed destination without crypt it names the command squirrel runs on the server — `md5` (`md5sum`), `sha1` (`sha1sum`), `sha256` (`sha256sum`) or `blake3` (`b3sum`) — and squirrel checks its answer against the bytes it sent. Behind crypt rclone runs it, and `crc32`, `xxh3` and `xxh128` are valid too; there the default applies to content-addressed only. A plain sftp mirror runs no command on the server, so the key is rejected there. | +| `checkers` | rclone remotes | rclone default | Cap rclone's concurrent checkers (`--checkers`). Rejected on every `local` destination and every `sftp` one without crypt: squirrel writes those itself, without rclone. | | `force_path_style` | s3 | `false` | Path-style bucket addressing for squirrel's own ETag reader (not the rclone transport). | | `pack_threshold` | packed | — | Files smaller than this are packed; at/above land as objects (e.g. `1MiB`). | | `pack_size` | packed | — | Target size of one pack before it is closed (e.g. `512MiB`). | | `zstd_level` | packed | — | zstd compression level, `1` fastest … `4` best. | -| `verify_every` | content-addressed / packed | off | Cadence for the agent to re-check this destination's recorded objects and packs against their upload fingerprints — the same pass as [`squirrel verify`](/squirrel/guides/verification/), recorded as an `audit` run. Falls back to `[agent] verify_every`. Read-only; the agent never writes to the destination. | +| `verify_every` | content-addressed / packed, native mirror | off | Cadence for the agent to re-check what squirrel recorded storing on this destination — objects and packs against their upload fingerprints, a native mirror's copies by size, mtime and (on a local disk) BLAKE3 — the same pass as [`squirrel verify`](/squirrel/guides/verification/), recorded as an `audit` run. Falls back to `[agent] verify_every`. Read-only; the agent never writes to the destination. Rejected on a mirror rclone writes. | ## `[backups]` @@ -178,7 +196,7 @@ optional. See [The agent](/squirrel/guides/agent/#listener-less-cadence-only-mac | `auth.peers..bearer` | no | Per-peer bearer token this agent accepts from node ``. Must equal that node's `[nodes.].auth.bearer`; [`squirrel node pair`](/squirrel/guides/peer-sync/) emits both halves so they match by construction. | | `scan_interval` | no | Drift-scan cadence over every hosted volume. Off when absent. | | `scan_strategy` | no | `shallow` (default) or `deep` (re-hash everything — bit-rot detection). | -| `verify_every` | no | Fleet-wide default verify cadence applied to every content-addressed/packed destination that declares no `verify_every` of its own. Off when absent. | +| `verify_every` | no | Fleet-wide default verify cadence applied to every content-addressed, packed or native mirror destination that declares no `verify_every` of its own. Off when absent. | ## `[nodes.]` diff --git a/docs/src/content/docs/reference/formats.md b/docs/src/content/docs/reference/formats.md index e215e3f..1aec702 100644 --- a/docs/src/content/docs/reference/formats.md +++ b/docs/src/content/docs/reference/formats.md @@ -25,6 +25,10 @@ sorted by `(path, status)`: | `size_bytes` | File size as indexed. | | `mtime_ns` | Modification time (nanoseconds) as indexed. | +A native [mirror](/squirrel/layouts/mirror/) (`local`, or `sftp` without crypt) +writes the same format as its receipt, at `/.squirrel-index/run-`; there the bytes of a +`present` path are at the path itself. + ### Replaying segments Process segments in **ascending run id**; each line with status `present`, diff --git a/docs/src/content/docs/reference/on-disk-layout.md b/docs/src/content/docs/reference/on-disk-layout.md index 7f4d074..b4f93de 100644 --- a/docs/src/content/docs/reference/on-disk-layout.md +++ b/docs/src/content/docs/reference/on-disk-layout.md @@ -16,6 +16,7 @@ A tree shaped like the local volumes: pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg + .squirrel-index/run-12 # receipt for run 12 (native mirrors) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) docs/ invoice.pdf @@ -80,15 +81,16 @@ names](/squirrel/reference/formats/#deriving-the-stored-names-on-an-encrypted-de ## Reserved directories -Three directory names are reserved and **filtered out** of all sync and restore +Four directory names are reserved and **filtered out** of all sync and restore transfers (and from peer-sync), so squirrel's own bookkeeping is never mistaken for user content: | Directory | Purpose | |---|---| -| `.squirrel-history/run-/` | rclone's `--backup-dir` target — prior bytes of overwritten files ([mirror](/squirrel/layouts/mirror/)). | -| `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/). | +| `.squirrel-history/run-/` | Prior bytes of the files a sync run replaced on a [mirror](/squirrel/layouts/mirror/). | +| `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/), and a native mirror's receipts. | | `.squirrel-restore-history/run-/` | Files displaced by an [`--in-place` restore](/squirrel/guides/restore/). | +| `.squirrel-staging/run-/` | In-flight writes on a destination squirrel writes itself, in any layout, renamed onto their names once confirmed. | One reserved **file** sits at the destination root rather than in a volume tree: `.squirrel-naming`, which records the artifact-naming scheme of an @@ -96,8 +98,8 @@ One reserved **file** sits at the destination root rather than in a volume tree: the gate that stops two naming schemes from being mixed into one root, and it never carries key material. -A directory literally called `.squirrel-history` in your **source** volume is -also filtered (with a warning) to keep the reserved name out of the destination +A directory literally called `.squirrel-history` or `.squirrel-staging` in your +**source** volume is also filtered (with a warning) to keep the reserved name out of the destination tree by accident. ## Related formats diff --git a/go.mod b/go.mod index dcd6e08..53c9f87 100644 --- a/go.mod +++ b/go.mod @@ -12,11 +12,14 @@ require ( github.com/mattn/go-isatty v0.0.22 github.com/minio/minio-go/v7 v7.2.1 github.com/pelletier/go-toml/v2 v2.3.1 + github.com/pkg/sftp v1.13.11 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/wailsapp/wails/v3 v3.0.0-alpha.95 github.com/zeebo/blake3 v0.2.4 - golang.org/x/crypto v0.51.0 + golang.org/x/crypto v0.54.0 + golang.org/x/sys v0.47.0 + golang.org/x/text v0.40.0 modernc.org/sqlite v1.50.1 ) @@ -53,6 +56,7 @@ require ( github.com/kevinburke/ssh_config v1.4.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/crc32 v1.3.0 // indirect + github.com/kr/fs v0.1.0 // indirect github.com/leaanthony/go-ansi-parser v1.6.1 // indirect github.com/leaanthony/u v1.1.1 // indirect github.com/lmittmann/tint v1.1.2 // indirect @@ -81,9 +85,7 @@ require ( github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/zeebo/xxh3 v1.1.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/net v0.53.0 // indirect - golang.org/x/sys v0.44.0 // indirect - golang.org/x/text v0.37.0 // indirect + golang.org/x/net v0.56.0 // indirect gopkg.in/ini.v1 v1.67.2 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect modernc.org/libc v1.72.3 // indirect diff --git a/go.sum b/go.sum index 5a85c44..e15354e 100644 --- a/go.sum +++ b/go.sum @@ -102,6 +102,8 @@ github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzh github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -154,6 +156,8 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE= +github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= @@ -210,17 +214,17 @@ github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= -golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= -golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= -golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= -golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= -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/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -230,17 +234,17 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.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/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4= -golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= -golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= -golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= diff --git a/offload/native_mirror_test.go b/offload/native_mirror_test.go new file mode 100644 index 0000000..b388a0e --- /dev/null +++ b/offload/native_mirror_test.go @@ -0,0 +1,90 @@ +package offload + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/sync" + "github.com/mbertschler/squirrel/volmark" +) + +// pushNativeMirror pushes the indexed volume at root to a native mirror +// on a local disk at dst, as `squirrel sync` does, and returns the +// destination. +func pushNativeMirror(t *testing.T, s *store.Store, root, dst string) *config.Destination { + t.Helper() + if err := os.MkdirAll(filepath.Join(dst, volName), 0o755); err != nil { + t.Fatal(err) + } + if err := volmark.Write(filepath.Join(dst, volName), volmark.Marker{Volume: volName}); err != nil { + t.Fatalf("seed destination marker: %v", err) + } + dest := &config.Destination{Name: "usb", Type: "local", Root: dst, Layout: config.LayoutMirror} + pair := sync.Pair{Volume: &config.Volume{Name: volName, Path: root}, Destination: dest} + rep, err := sync.RunPair(context.Background(), s, sync.Tools{}, pair, sync.Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return dest +} + +// TestOffloadGatesOnNativeLocalMirror: a native local mirror reads every +// copy back through BLAKE3, so its push alone lets offload delete the local +// bytes, with or without a verify cadence. Once a verify pass finds a copy +// gone, that copy stops vouching and its file stays. +func TestOffloadGatesOnNativeLocalMirror(t *testing.T) { + for _, cadenced := range []bool{false, true} { + t.Run(map[bool]string{false: "no cadence", true: "verify cadence"}[cadenced], func(t *testing.T) { + root, dst := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(root, "a.txt"), "alpha") + writeFile(t, filepath.Join(root, "b.txt"), "bravo") + s := setupStore(t) + ctx := context.Background() + indexVolume(t, s, root) + dest := pushNativeMirror(t, s, root, dst) + + if err := os.Remove(filepath.Join(dst, volName, "b.txt")); err != nil { + t.Fatal(err) + } + if rep, err := sync.VerifyRemote(ctx, s, nil, dest); err != nil || len(rep.PathsMissing) != 1 { + t.Fatalf("verify = %+v, %v; want b.txt found missing", rep, err) + } + + rep, err := Offload(ctx, s, root, Options{ + Name: volName, Paths: []string{"."}, Require: []string{"usb"}, + RequireDests: map[string]*config.Destination{"usb": dest}, + VerifyCadenced: map[string]bool{"usb": cadenced}, + }) + if err != nil { + t.Fatalf("Offload: %v", err) + } + oneResult(t, rep, "a.txt", OutcomeOffloaded) + mustBeGone(t, filepath.Join(root, "a.txt")) + oneFailure(t, oneResult(t, rep, "b.txt", OutcomeNotDurable), "usb", FailureNotVerified) + mustExist(t, filepath.Join(root, "b.txt")) + }) + } +} + +// TestOffloadRefusesNativeSFTPMirrorUpFront: a native sftp mirror reads +// nothing back, so naming one aborts the offload before any file is +// walked, and the reason says so. +func TestOffloadRefusesNativeSFTPMirrorUpFront(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "a.txt"), "alpha") + s := setupStore(t) + indexVolume(t, s, root) + dests := map[string]*config.Destination{"box": {Name: "box", Type: "sftp", Layout: config.LayoutMirror}} + _, err := Offload(context.Background(), s, root, Options{ + Name: volName, Paths: []string{"."}, Require: []string{"box"}, RequireDests: dests, + }) + if err == nil || !strings.Contains(err.Error(), "reads nothing back") { + t.Fatalf("err = %v, want an up-front refusal naming the reason", err) + } + mustExist(t, filepath.Join(root, "a.txt")) +} diff --git a/store/content_presence.go b/store/content_presence.go index e4e7035..fec3f6b 100644 --- a/store/content_presence.go +++ b/store/content_presence.go @@ -14,6 +14,8 @@ import ( // already offsite in either form. Both branches are per-destination: a pack // this content sits in counts only when that pack was uploaded to *this* // destination, so a pack landed elsewhere never suppresses a needed upload. +// A mirror copy is at its path rather than where these layouts read their +// bytes, so remote_paths is left to the mirror's own records. func (s *Store) ContentPresentOnDestination(ctx context.Context, contentID int64, destination string) (bool, error) { var present int err := s.db.QueryRowContext(ctx, ` @@ -35,11 +37,11 @@ func (s *Store) ContentPresentOnDestination(ctx context.Context, contentID int64 // contents of the volume that do NOT yet carry a verified provider // fingerprint on the destination — the whole-state "pending artifact" // tally the fingerprint-verified upgrade gates on. A content counts as -// pending unless it has either a remote_objects row or a member pack's -// remote_packs row on this destination with a non-NULL checksum and -// verified_at_ns, so content not yet uploaded, uploaded but not yet -// fingerprinted, or fingerprinted but not yet re-confirmed all keep the -// tally above zero. Zero means every present content is fingerprint- +// pending unless a remote_objects row, a member pack's remote_packs row, or +// a live or displaced mirror copy's remote_paths row on this destination +// carries a non-NULL checksum and verified_at_ns, so content not yet +// uploaded, uploaded but not yet fingerprinted, or fingerprinted but not +// yet re-confirmed all keep the tally above zero. Zero means every present content is fingerprint- // verified on the destination, so the vector may advance to // VerifyMethodFingerprint over the whole present set. The reserved sync // subtrees are excluded, matching PresentOriginMaxima — they never travel @@ -65,24 +67,32 @@ func (s *Store) CountVolumeContentsPendingFingerprint(ctx context.Context, volum WHERE pm.content_id = f.content_id AND rp.destination = ? AND rp.checksum IS NOT NULL AND rp.verified_at_ns IS NOT NULL ) + OR EXISTS ( + SELECT 1 FROM remote_paths rpa + WHERE rpa.content_id = f.content_id AND rpa.destination = ? + AND rpa.state IN ('live', 'displaced') + AND rpa.checksum IS NOT NULL AND rpa.verified_at_ns IS NOT NULL + ) ) ) - `, volumeID, destination, destination).Scan(&pending) + `, volumeID, destination, destination, destination).Scan(&pending) if err != nil { return 0, fmt.Errorf("count pending fingerprints for volume %d on %q: %w", volumeID, destination, err) } return pending, nil } -// ContentFingerprintVerified reports whether a verified provider -// fingerprint backs the content on the destination via either layout: a -// remote_objects row carrying a checksum and a verified_at_ns, or a -// remote_packs row (for a pack this content belongs to) likewise -// re-confirmed. The offload gate uses it to certify a presence+size -// component — a coarse vector that only claims bytes-present — so packed -// content gates exactly when its pack has a re-confirmed fingerprint, the -// packed analogue of the per-object scan-back the content-addressed layout -// requires. One verified pack vouches for every member. +// ContentFingerprintVerified reports whether a verified fingerprint backs +// the content on the destination in any layout: a remote_objects row +// carrying a checksum and a verified_at_ns, a remote_packs row (for a pack +// this content belongs to) likewise re-confirmed, or a live or displaced +// mirror copy whose remote_paths row records the BLAKE3 a read of the +// stored bytes confirmed. The offload gate uses it to certify a +// presence+size component — a coarse vector that only claims bytes-present +// — so packed content gates exactly when its pack has a re-confirmed +// fingerprint, the packed analogue of the per-object scan-back the +// content-addressed layout requires. One verified pack vouches for every +// member. func (s *Store) ContentFingerprintVerified(ctx context.Context, contentID int64, destination string) (bool, error) { var verified int err := s.db.QueryRowContext(ctx, ` @@ -98,9 +108,34 @@ func (s *Store) ContentFingerprintVerified(ctx context.Context, contentID int64, WHERE pm.content_id = ? AND rp.destination = ? AND rp.checksum IS NOT NULL AND rp.verified_at_ns IS NOT NULL ) - `, contentID, destination, contentID, destination).Scan(&verified) + OR EXISTS ( + SELECT 1 FROM remote_paths + WHERE content_id = ? AND destination = ? AND state IN ('live', 'displaced') + AND checksum IS NOT NULL AND verified_at_ns IS NOT NULL + ) + `, contentID, destination, contentID, destination, contentID, destination).Scan(&verified) if err != nil { return false, fmt.Errorf("lookup content fingerprint on %q: %w", destination, err) } return verified != 0, nil } + +// DestinationHasUploadRecords reports whether the index records any upload +// to the destination, in any volume: a per-hash object, a pack, or a +// mirror path in any state. The push +// watermark rule reads an empty root as a fresh start only when this is +// false; otherwise the root was wiped behind squirrel's back, and a push +// would skip content these records still claim is there. +func (s *Store) DestinationHasUploadRecords(ctx context.Context, destination string) (bool, error) { + var has int + err := s.db.QueryRowContext(ctx, ` + SELECT + EXISTS (SELECT 1 FROM remote_objects WHERE destination = ?) + OR EXISTS (SELECT 1 FROM remote_packs WHERE destination = ?) + OR EXISTS (SELECT 1 FROM remote_paths WHERE destination = ?) + `, destination, destination, destination).Scan(&has) + if err != nil { + return false, fmt.Errorf("lookup upload records on %q: %w", destination, err) + } + return has != 0, nil +} diff --git a/store/destination_reset.go b/store/destination_reset.go index 198f731..19eb59a 100644 --- a/store/destination_reset.go +++ b/store/destination_reset.go @@ -7,22 +7,23 @@ import ( ) // DestinationResetCounts reports how many recorded-state rows a destination -// reset cleared (or, on a dry run, would clear). The four categories are the -// full derived record squirrel keeps about a destination: the per-content -// and per-pack upload ledgers, the live durability vector, and the -// push-freshness maxima. They span every volume — a destination's recorded +// reset cleared (or, on a dry run, would clear). The five categories are the +// full derived record squirrel keeps about a destination: the per-content, +// per-pack and per-mirror-path upload ledgers, the live durability vector, +// and the push-freshness maxima. They span every volume — a destination's recorded // state is not volume-scoped — so the counts are totals across the index. type DestinationResetCounts struct { RemoteObjects int64 RemotePacks int64 + RemotePaths int64 VectorComponents int64 FreshnessRows int64 } -// Total is the sum of all four categories, used as the reset run's +// Total is the sum of all five categories, used as the reset run's // file_count so the audit trail carries the magnitude at a glance. func (c DestinationResetCounts) Total() int64 { - return c.RemoteObjects + c.RemotePacks + c.VectorComponents + c.FreshnessRows + return c.RemoteObjects + c.RemotePacks + c.RemotePaths + c.VectorComponents + c.FreshnessRows } // Empty reports whether the destination has no recorded state at all — the @@ -56,6 +57,7 @@ func countDestinationRecordedState(ctx context.Context, q rowQuerier, destinatio }{ {&c.RemoteObjects, `SELECT COUNT(*) FROM remote_objects WHERE destination = ?`}, {&c.RemotePacks, `SELECT COUNT(*) FROM remote_packs WHERE destination = ?`}, + {&c.RemotePaths, `SELECT COUNT(*) FROM remote_paths WHERE destination = ?`}, {&c.VectorComponents, `SELECT COUNT(*) FROM destination_run_ids WHERE destination = ?`}, {&c.FreshnessRows, `SELECT COUNT(*) FROM destination_push_freshness WHERE destination = ?`}, } @@ -68,8 +70,8 @@ func countDestinationRecordedState(ctx context.Context, q rowQuerier, destinatio } // ResetDestination forgets everything the index records about a destination's -// remote state — its per-content and per-pack upload ledgers, its live -// durability vector, and its push-freshness maxima — so the next sync treats +// remote state — its per-content, per-pack and per-mirror-path upload +// ledgers, its live durability vector, and its push-freshness maxima — so the next sync treats // the destination as fresh and re-uploads. It is the supported recovery for a // wrecked or repointed destination (friction log F20): before it, a fresh // `root` still refused because the layout guard keyed on run history by @@ -110,8 +112,8 @@ func (s *Store) ResetDestination(ctx context.Context, destination string) (int64 if err := deleteDestinationRecordedStateTx(ctx, tx, destination); err != nil { return 0, DestinationResetCounts{}, err } - note := fmt.Sprintf("destination=%q objects=%d packs=%d vector=%d freshness=%d", - destination, counts.RemoteObjects, counts.RemotePacks, counts.VectorComponents, counts.FreshnessRows) + note := fmt.Sprintf("destination=%q objects=%d packs=%d paths=%d vector=%d freshness=%d", + destination, counts.RemoteObjects, counts.RemotePacks, counts.RemotePaths, counts.VectorComponents, counts.FreshnessRows) if err := appendRunAuditTx(ctx, tx, RunAuditEntry{RunID: runID, Transition: TransitionResetDestination, Note: note}, atNs); err != nil { return 0, DestinationResetCounts{}, err @@ -144,13 +146,14 @@ func insertResetRunTx(ctx context.Context, tx *sql.Tx, atNs int64) (int64, error return id, nil } -// deleteDestinationRecordedStateTx clears the four derived-state tables for +// deleteDestinationRecordedStateTx clears the five derived-state tables for // destination. The append-only destination_run_ids_history and the runs // table are deliberately absent — the reset preserves the audit trail. func deleteDestinationRecordedStateTx(ctx context.Context, tx *sql.Tx, destination string) error { stmts := []string{ `DELETE FROM remote_objects WHERE destination = ?`, `DELETE FROM remote_packs WHERE destination = ?`, + `DELETE FROM remote_paths WHERE destination = ?`, `DELETE FROM destination_run_ids WHERE destination = ?`, `DELETE FROM destination_push_freshness WHERE destination = ?`, } diff --git a/store/destination_run_ids.go b/store/destination_run_ids.go index fe35c8a..5df57a9 100644 --- a/store/destination_run_ids.go +++ b/store/destination_run_ids.go @@ -294,6 +294,31 @@ func (s *Store) UpgradeDestinationVectorToFingerprintVerified(ctx context.Contex return true, nil } +// DemoteFingerprintVerifiedVector re-stamps every locally advanced +// fingerprint-verified component of the (volume, destination) vector as +// presence+size, at the run and verification instant it already records: +// a verify pass found content the destination held gone or changed, so its +// vector no longer vouches for the volume as a whole. The offload gate then +// checks each content's own fingerprint, and a peer pulling the vector sees +// presence+size. The next push that leaves nothing pending upgrades it +// again. Each demotion is logged in destination_run_ids_history. +func (s *Store) DemoteFingerprintVerifiedVector(ctx context.Context, volumeID int64, destination string) error { + components, err := s.ListDestinationRunIDs(ctx, volumeID, destination) + if err != nil { + return err + } + for _, c := range components { + if c.VerifyMethod != VerifyMethodFingerprint || c.SourceNodeID.Valid { + continue + } + verifiedAt := c.VerifiedAtNs + if err := s.upsertDestinationRunID(ctx, volumeID, destination, c.OriginNodeID, c.OriginRunID, VerifyMethodPresenceSize, sql.NullInt64{}, &verifiedAt, false); err != nil { + return fmt.Errorf("demote vector of %q: %w", destination, err) + } + } + return nil +} + // recordPushFreshness overwrites the destination's push-freshness maxima // to exactly the supplied snapshot — the per-origin-node maxima of the // present set this push enumerated. Distinct from the monotonic vector diff --git a/store/migrate_v27_test.go b/store/migrate_v27_test.go index 628411c..f5ce2a5 100644 --- a/store/migrate_v27_test.go +++ b/store/migrate_v27_test.go @@ -138,7 +138,10 @@ func TestMigrateV26ToV27PreservesEveryRow(t *testing.T) { // by later migrations are legitimately present after the rebuild and // absent from the v26 fixture. Naming them keeps the count assertion // exact — a table the rebuild itself invented would still fail here. - addedAfterV27 := []string{"config_drift"} // v29 (#191) + addedAfterV27 := []string{ + "config_drift", // v29 (#191) + "remote_paths", // v32 + } if got, want := len(countsAfter), len(countsBefore)+len(addedAfterV27); got != want { t.Errorf("table count = %d after migration, want %d", got, want) } @@ -147,8 +150,11 @@ func TestMigrateV26ToV27PreservesEveryRow(t *testing.T) { t.Errorf("table %s missing after migration to v%d", table, SchemaVersion) } } - if after := schemaObjectNames(t, s.db); !equalStrings(after, objectsBefore) { - t.Errorf("indexes/triggers after migration = %v, want %v", after, objectsBefore) + indexesAddedAfterV27 := []string{"idx_remote_paths_unsettled", "uniq_remote_paths_live", "idx_remote_paths_content", "idx_remote_paths_lost"} // v32, v33 + wantObjects := append(append([]string{}, objectsBefore...), indexesAddedAfterV27...) + sort.Strings(wantObjects) + if after := schemaObjectNames(t, s.db); !equalStrings(after, wantObjects) { + t.Errorf("indexes/triggers after migration = %v, want %v", after, wantObjects) } assertContentRowIntact(t, s) diff --git a/store/migrations.go b/store/migrations.go index e7353c0..3e467ca 100644 --- a/store/migrations.go +++ b/store/migrations.go @@ -10,7 +10,7 @@ import ( ) // SchemaVersion is the schema version this binary writes and reads. -const SchemaVersion = 31 +const SchemaVersion = 33 // freshSchemaBaseline is the version applied to a brand-new database. The // chain in `migrations` continues from here. v1 is no longer reachable from @@ -74,6 +74,8 @@ func buildMigrations(mctx migrationCtx) []migration { {version: 29, up: migrateV28ToV29}, {version: 30, up: migrateV29ToV30}, {version: 31, up: migrateV30ToV31}, + {version: 32, up: migrateV31ToV32}, + {version: 33, up: migrateV32ToV33}, } } @@ -2449,3 +2451,85 @@ func relabelBlake3ComponentsV31(ctx context.Context, tx *sql.Tx) error { } return nil } + +// --- v31 → v32 --- + +// migrateV31ToV32 adds remote_paths, the native mirror's destination +// record and its counterpart of remote_objects: one row per version +// squirrel wrote at a mirror path, keyed on the files row it came from. +// The state column records each move before it happens (committing → +// live, live → displacing → displaced, anything → lost), so a push that +// crashed mid-move is settled by the next one from where the bytes are. +// A displaced version's location is derived: +// .squirrel-history/run-/. +// +// At most one committing-or-live row per (destination, path), enforced by +// a partial unique index; the unsettled index serves the reconcile at push +// start, which reads only committing and displacing rows. STRICT per the +// new-table convention; additive, so no existing table is rebuilt. +func migrateV31ToV32(ctx context.Context, db *sql.DB) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + stmts := []string{ + `CREATE TABLE remote_paths ( + id INTEGER PRIMARY KEY, + destination TEXT NOT NULL, + folder_id INTEGER NOT NULL, + name TEXT NOT NULL, + content_id INTEGER NOT NULL, + written_run_id INTEGER NOT NULL REFERENCES runs(id), + state TEXT NOT NULL + CHECK (state IN ('committing', 'live', 'displacing', 'displaced', 'lost')), + displaced_run_id INTEGER REFERENCES runs(id), + mtime_ns INTEGER NOT NULL, + checksum_algo TEXT, + checksum TEXT, + verified_at_ns INTEGER, + FOREIGN KEY (folder_id, name, content_id) REFERENCES files (folder_id, name, content_id), + CHECK (state NOT IN ('committing', 'live') OR displaced_run_id IS NULL), + CHECK (state NOT IN ('displacing', 'displaced') OR displaced_run_id IS NOT NULL), + CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) + ) STRICT`, + `CREATE UNIQUE INDEX uniq_remote_paths_live ON remote_paths (destination, folder_id, name) + WHERE state IN ('committing', 'live')`, + `CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) + WHERE state IN ('committing', 'displacing')`, + `INSERT INTO schema_version (version) VALUES (32)`, + } + for _, stmt := range stmts { + if _, err := tx.ExecContext(ctx, stmt); err != nil { + return fmt.Errorf("migrate to schema v32: %w", err) + } + } + return tx.Commit() +} + +// --- v32 → v33 --- + +// migrateV32ToV33 indexes remote_paths for the reads the mirror's evidence +// adds: by content, for the offload gate's per-content fingerprint check +// and the pending-fingerprint tally, and the lost rows of a destination, +// which a push plans again as repairs. Additive. +func migrateV32ToV33(ctx context.Context, db *sql.DB) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + stmts := []string{ + `CREATE INDEX idx_remote_paths_content ON remote_paths (content_id)`, + `CREATE INDEX idx_remote_paths_lost ON remote_paths (destination) WHERE state = 'lost'`, + `INSERT INTO schema_version (version) VALUES (33)`, + } + for _, stmt := range stmts { + if _, err := tx.ExecContext(ctx, stmt); err != nil { + return fmt.Errorf("migrate to schema v33: %w", err) + } + } + return tx.Commit() +} diff --git a/store/path_delta.go b/store/path_delta.go index 075246c..1b2cc71 100644 --- a/store/path_delta.go +++ b/store/path_delta.go @@ -13,6 +13,7 @@ import ( // bytes gone — unexpectedly or intentionally). type PathDelta struct { Path string + FolderID int64 // with the path's last component, the files row key ContentID int64 Blake3 []byte // raw 32-byte BLAKE3-256 digest SizeBytes int64 @@ -27,7 +28,8 @@ type PathDelta struct { const reservedSubtreeFilter = `fo.path != '.squirrel-history' AND fo.path NOT LIKE '.squirrel-history/%' AND fo.path != '.squirrel-conflicts' AND fo.path NOT LIKE '.squirrel-conflicts/%' AND fo.path != '.squirrel-restore-history' AND fo.path NOT LIKE '.squirrel-restore-history/%' - AND fo.path != '.squirrel-index' AND fo.path NOT LIKE '.squirrel-index/%'` + AND fo.path != '.squirrel-index' AND fo.path NOT LIKE '.squirrel-index/%' + AND fo.path != '.squirrel-staging' AND fo.path NOT LIKE '.squirrel-staging/%'` // ListPathDeltaSince returns every row in the volume whose status last // changed after sinceRunID, ordered by (path, status) so the export is @@ -39,7 +41,7 @@ const reservedSubtreeFilter = `fo.path != '.squirrel-history' AND fo.pat // coordinate). func (s *Store) ListPathDeltaSince(ctx context.Context, volumeID, sinceRunID int64) ([]PathDelta, error) { return queryRows(ctx, s.db, ` - SELECT `+pathFromFolderAndName+`, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status + SELECT `+pathFromFolderAndName+`, f.folder_id, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status FROM `+fileFromJoin+` WHERE fo.volume_id = ? AND COALESCE(f.status_changed_run_id, f.first_seen_run_id) > ? @@ -57,7 +59,7 @@ func (s *Store) ListPathDeltaSince(ctx context.Context, volumeID, sinceRunID int // content hash it must fetch from objects/ or a pack. func (s *Store) ListPresentContent(ctx context.Context, volumeID int64) ([]PathDelta, error) { return queryRows(ctx, s.db, ` - SELECT `+pathFromFolderAndName+`, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status + SELECT `+pathFromFolderAndName+`, f.folder_id, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status FROM `+fileFromJoin+` WHERE fo.volume_id = ? AND f.status = 'present' @@ -68,6 +70,6 @@ func (s *Store) ListPresentContent(ctx context.Context, volumeID int64) ([]PathD func scanPathDelta(s rowScanner) (PathDelta, error) { var d PathDelta - err := s.Scan(&d.Path, &d.ContentID, &d.Blake3, &d.SizeBytes, &d.MtimeNs, &d.Status) + err := s.Scan(&d.Path, &d.FolderID, &d.ContentID, &d.Blake3, &d.SizeBytes, &d.MtimeNs, &d.Status) return d, err } diff --git a/store/path_delta_test.go b/store/path_delta_test.go index 97f3948..63f03c0 100644 --- a/store/path_delta_test.go +++ b/store/path_delta_test.go @@ -106,6 +106,7 @@ func TestListPathDeltaSinceExcludesReservedSubtrees(t *testing.T) { ".squirrel-conflicts/run-2/x.txt", ".squirrel-restore-history/run-3/y.txt", ".squirrel-index/index-snapshot.db", + ".squirrel-staging/run-4/z", } for i, p := range reserved { if err := s.Upsert(ctx, FileRow{ diff --git a/store/remote_paths.go b/store/remote_paths.go new file mode 100644 index 0000000..eb6e360 --- /dev/null +++ b/store/remote_paths.go @@ -0,0 +1,239 @@ +package store + +import ( + "context" + "database/sql" + "fmt" +) + +// The states of a remote_paths row. Each move on the destination is +// recorded before it happens, so a crash leaves the row naming the move in +// flight and the next push settles it from where the bytes actually are. +const ( + // RemotePathCommitting: the version is staged and about to be renamed + // onto its path. + RemotePathCommitting = "committing" + // RemotePathLive: the version is at its path. + RemotePathLive = "live" + // RemotePathDisplacing: the version is about to move into history. + RemotePathDisplacing = "displacing" + // RemotePathDisplaced: the version sits at + // .squirrel-history/run-/. + RemotePathDisplaced = "displaced" + // RemotePathLost: the bytes are no longer where the row says. The row + // keeps its history but stops vouching for its content. + RemotePathLost = "lost" +) + +// RemotePath is one version squirrel wrote at a mirror path on a +// destination, keyed on the files row it came from. Path, SizeBytes and +// Blake3 are read through that row's folder and content. MtimeNs is the +// mtime the destination reported for the written version. Checksum is +// the BLAKE3 a read of the stored bytes confirmed, NULL while none did. +type RemotePath struct { + ID int64 + ContentID int64 + WrittenRunID int64 + State string + DisplacedRunID sql.NullInt64 + MtimeNs int64 + Checksum sql.NullString + + Path string + SizeBytes int64 + Blake3 []byte +} + +// RemotePathWrite is the intent to commit one version at a mirror path. +// Checksum is the lowercase hex BLAKE3 a read-back of the staged version +// confirmed at VerifiedAtNs, or empty when the destination offered none. +type RemotePathWrite struct { + Destination string + FolderID int64 + Name string + ContentID int64 + RunID int64 + MtimeNs int64 + Checksum string + VerifiedAtNs int64 +} + +// ChecksumAlgoBlake3 is the checksum_algo of a fingerprint squirrel +// computed itself, by reading the stored bytes back through BLAKE3. +const ChecksumAlgoBlake3 = "blake3" + +// BeginRemotePathCommit records the intent to rename a staged version onto +// its path, as a committing row. The path's previous live row must already +// be displacing, displaced or lost: at most one committing-or-live row per +// (destination, path) exists, and the insert fails on that unique index +// otherwise. +func (s *Store) BeginRemotePathCommit(ctx context.Context, w RemotePathWrite) (int64, error) { + if w.Destination == "" { + return 0, fmt.Errorf("BeginRemotePathCommit: destination must be non-empty") + } + var algo, checksum sql.NullString + var verified sql.NullInt64 + if w.Checksum != "" { + algo = sql.NullString{String: ChecksumAlgoBlake3, Valid: true} + checksum = sql.NullString{String: w.Checksum, Valid: true} + verified = sql.NullInt64{Int64: w.VerifiedAtNs, Valid: true} + } + res, err := s.db.ExecContext(ctx, ` + INSERT INTO remote_paths (destination, folder_id, name, content_id, written_run_id, state, mtime_ns, + checksum_algo, checksum, verified_at_ns) + VALUES (?, ?, ?, ?, ?, 'committing', ?, ?, ?, ?) + `, w.Destination, w.FolderID, w.Name, w.ContentID, w.RunID, w.MtimeNs, algo, checksum, verified) + if err != nil { + return 0, fmt.Errorf("record commit of %q on %q: %w", w.Name, w.Destination, err) + } + return res.LastInsertId() +} + +// ConfirmRemotePathsLive moves committing rows to live once their versions +// are at their paths. +func (s *Store) ConfirmRemotePathsLive(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathLive, ` + UPDATE remote_paths SET state = 'live' WHERE id = ? AND state = 'committing'`) +} + +// BeginRemotePathsDisplace records that live rows are about to move into +// .squirrel-history/run-/. A directory displaced because a file +// replaced it moves every live row under it, all in one call. +func (s *Store) BeginRemotePathsDisplace(ctx context.Context, runID int64, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathDisplacing, ` + UPDATE remote_paths SET state = 'displacing', displaced_run_id = ? + WHERE id = ? AND state = 'live'`, runID) +} + +// ConfirmRemotePathsDisplaced moves displacing rows to displaced once their +// versions are in history. +func (s *Store) ConfirmRemotePathsDisplaced(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathDisplaced, ` + UPDATE remote_paths SET state = 'displaced' WHERE id = ? AND state = 'displacing'`) +} + +// RevertRemotePathsLive withdraws a displacement that never happened: the +// version is still at its path, so the row goes back to live. +func (s *Store) RevertRemotePathsLive(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathLive, ` + UPDATE remote_paths SET state = 'live', displaced_run_id = NULL + WHERE id = ? AND state = 'displacing'`) +} + +// MarkRemotePathsLost records that the rows' bytes are no longer where the +// rows say: other bytes are there, or nothing. A withdrawn commit ends +// here too, because its version never reached its path. +func (s *Store) MarkRemotePathsLost(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathLost, ` + UPDATE remote_paths SET state = 'lost' WHERE id = ? AND state != 'lost'`) +} + +// transitionRemotePaths applies one state transition to every id in one +// transaction. update takes the prefix args followed by the row id. Each +// row must be in the transition's source state or the whole batch fails, +// so a record moves only through the moves it witnessed. +func (s *Store) transitionRemotePaths(ctx context.Context, ids []int64, to, update string, prefix ...any) error { + if len(ids) == 0 { + return nil + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin remote path transition to %s: %w", to, err) + } + defer func() { _ = tx.Rollback() }() + for _, id := range ids { + res, err := tx.ExecContext(ctx, update, append(append([]any{}, prefix...), id)...) + if err != nil { + return fmt.Errorf("move remote path %d to %s: %w", id, to, err) + } + n, err := res.RowsAffected() + if err != nil { + return fmt.Errorf("move remote path %d to %s: %w", id, to, err) + } + if n != 1 { + return fmt.Errorf("move remote path %d to %s: the row is not in the state this move starts from", id, to) + } + } + return tx.Commit() +} + +// remotePathSelect reads remote_paths rows with their volume-relative path +// and content size and hash (table aliases rp, fo, c). +const remotePathSelect = ` + SELECT rp.id, rp.content_id, rp.written_run_id, + rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, + CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, + c.size_bytes, c.blake3 + FROM remote_paths rp + JOIN folders fo ON fo.id = rp.folder_id + JOIN contents c ON c.id = rp.content_id` + +func scanRemotePath(s rowScanner) (RemotePath, error) { + var r RemotePath + err := s.Scan(&r.ID, &r.ContentID, &r.WrittenRunID, + &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, + &r.Path, &r.SizeBytes, &r.Blake3) + return r, err +} + +// ListLiveRemotePaths returns the volume's live rows on the destination, +// ordered by path: what the destination's mirror tree holds by squirrel's +// records. +func (s *Store) ListLiveRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { + return queryRows(ctx, s.db, remotePathSelect+` + WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state = 'live' + ORDER BY 9 + `, scanRemotePath, destination, volumeID) +} + +// ListUnsettledRemotePaths returns the volume's committing and displacing +// rows on the destination: the moves a crashed push left in flight. +func (s *Store) ListUnsettledRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { + return queryRows(ctx, s.db, remotePathSelect+` + WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state IN ('committing', 'displacing') + ORDER BY rp.id + `, scanRemotePath, destination, volumeID) +} + +// ListRemotePaths returns every row of the volume on the destination, in +// insertion order. +func (s *Store) ListRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { + return queryRows(ctx, s.db, remotePathSelect+` + WHERE rp.destination = ? AND fo.volume_id = ? + ORDER BY rp.id + `, scanRemotePath, destination, volumeID) +} + +// VolumeHasRemotePaths reports whether squirrel holds any row of the +// volume on the destination, in any state. +func (s *Store) VolumeHasRemotePaths(ctx context.Context, destination string, volumeID int64) (bool, error) { + var has int + err := s.db.QueryRowContext(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM remote_paths rp JOIN folders fo ON fo.id = rp.folder_id + WHERE rp.destination = ? AND fo.volume_id = ?) + `, destination, volumeID).Scan(&has) + if err != nil { + return false, fmt.Errorf("lookup mirror records of volume %d on %q: %w", volumeID, destination, err) + } + return has != 0, nil +} + +// CountInSyncRemotePaths counts the volume's live rows on the destination +// whose files row is still present: paths the destination holds with +// their current content by squirrel's records, the mirror's "already +// correct". +func (s *Store) CountInSyncRemotePaths(ctx context.Context, destination string, volumeID int64) (int64, error) { + var n int64 + err := s.db.QueryRowContext(ctx, ` + SELECT COUNT(*) + FROM remote_paths rp + JOIN folders fo ON fo.id = rp.folder_id + JOIN files f ON f.folder_id = rp.folder_id AND f.name = rp.name AND f.content_id = rp.content_id + WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state = 'live' AND f.status = 'present' + `, destination, volumeID).Scan(&n) + if err != nil { + return 0, fmt.Errorf("count in-sync mirror paths on %q: %w", destination, err) + } + return n, nil +} diff --git a/store/remote_paths_evidence.go b/store/remote_paths_evidence.go new file mode 100644 index 0000000..6af051d --- /dev/null +++ b/store/remote_paths_evidence.go @@ -0,0 +1,102 @@ +package store + +import ( + "context" + "fmt" +) + +// StoredRemotePath is a live or displaced remote_paths row with the volume +// it belongs to: a version a mirror holds by squirrel's records, at +// / or in that volume's history. +type StoredRemotePath struct { + RemotePath + VolumeID int64 + Volume string +} + +// ListStoredRemotePaths returns every live and displaced row on the +// destination, in every volume: what a verify pass checks. They come least +// recently verified first, never-verified ones before all others, so a pass +// that re-reads only a slice of them rotates through the whole set. +func (s *Store) ListStoredRemotePaths(ctx context.Context, destination string) ([]StoredRemotePath, error) { + return queryRows(ctx, s.db, ` + SELECT rp.id, rp.content_id, rp.written_run_id, + rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, + CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, + c.size_bytes, c.blake3, v.id, v.name + FROM remote_paths rp + JOIN folders fo ON fo.id = rp.folder_id + JOIN volumes v ON v.id = fo.volume_id + JOIN contents c ON c.id = rp.content_id + WHERE rp.destination = ? AND rp.state IN ('live', 'displaced') + ORDER BY rp.verified_at_ns IS NOT NULL, rp.verified_at_ns, rp.id + `, func(sc rowScanner) (StoredRemotePath, error) { + var r StoredRemotePath + err := sc.Scan(&r.ID, &r.ContentID, &r.WrittenRunID, + &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, + &r.Path, &r.SizeBytes, &r.Blake3, &r.VolumeID, &r.Volume) + return r, err + }, destination) +} + +// RecordRemotePathVerified records that a read of a live or displaced +// row's stored bytes just hashed to checksum, its content's BLAKE3 in +// lowercase hex, at atNs, and reports whether it did. A row that already +// records a checksum must record this one — a read never replaces the +// fingerprint it re-confirms — and a row a push moved since is left alone. +func (s *Store) RecordRemotePathVerified(ctx context.Context, id int64, checksum string, atNs int64) (bool, error) { + res, err := s.db.ExecContext(ctx, ` + UPDATE remote_paths SET checksum_algo = ?, checksum = ?, verified_at_ns = ? + WHERE id = ? AND state IN ('live', 'displaced') AND (checksum IS NULL OR checksum = ?) + `, ChecksumAlgoBlake3, checksum, atNs, id, checksum) + if err != nil { + return false, fmt.Errorf("record verification of remote path %d: %w", id, err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("record verification of remote path %d: %w", id, err) + } + return n == 1, nil +} + +// LoseStoredRemotePath marks a row lost that a verify pass found missing or +// changed, provided it is still in state, the state the pass read it in. +// It reports whether the row moved: a push may have moved it since, and +// then the pass's finding describes a version that is no longer there. +func (s *Store) LoseStoredRemotePath(ctx context.Context, id int64, state string) (bool, error) { + res, err := s.db.ExecContext(ctx, ` + UPDATE remote_paths SET state = 'lost' WHERE id = ? AND state = ? AND state IN ('live', 'displaced') + `, id, state) + if err != nil { + return false, fmt.Errorf("mark remote path %d lost: %w", id, err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("mark remote path %d lost: %w", id, err) + } + return n == 1, nil +} + +// ListRemotePathRepairs returns the volume's present paths the destination +// lost: a lost row holds the path's current content, and no committing or +// live row does. A push writes them again although the index did not change +// — the planner's repairs. Ordered by path, like the delta. +func (s *Store) ListRemotePathRepairs(ctx context.Context, destination string, volumeID int64) ([]PathDelta, error) { + return queryRows(ctx, s.db, ` + SELECT DISTINCT `+pathFromFolderAndName+`, f.folder_id, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status + FROM remote_paths rp + JOIN files f ON f.folder_id = rp.folder_id AND f.name = rp.name AND f.content_id = rp.content_id + JOIN folders fo ON fo.id = f.folder_id + JOIN contents c ON c.id = f.content_id + WHERE rp.destination = ? AND rp.state = 'lost' + AND fo.volume_id = ? AND f.status = 'present' + AND `+reservedSubtreeFilter+` + AND NOT EXISTS ( + SELECT 1 FROM remote_paths held + WHERE held.destination = rp.destination AND held.folder_id = rp.folder_id + AND held.name = rp.name AND held.content_id = rp.content_id + AND held.state IN ('committing', 'live') + ) + ORDER BY 1 + `, scanPathDelta, destination, volumeID) +} diff --git a/store/remote_paths_test.go b/store/remote_paths_test.go new file mode 100644 index 0000000..eae6187 --- /dev/null +++ b/store/remote_paths_test.go @@ -0,0 +1,425 @@ +package store + +import ( + "context" + "testing" +) + +// remotePathFixture indexes one path, "2024/cat.jpg", and returns its +// PathDelta (which carries the files row key) and the observing run. +func remotePathFixture(t *testing.T, s *Store) (PathDelta, int64, int64) { + t.Helper() + ctx := context.Background() + vID := makeVolume(t, s, "/v") + runID := makeRun(t, s, vID) + if err := s.Upsert(ctx, FileRow{ + VolumeID: vID, Path: "2024/cat.jpg", Blake3: digest(0xaa), SizeBytes: 3, MtimeNs: 1, + Status: StatusPresent, FirstSeenRunID: runID, LastSeenRunID: runID, IndexedAtNs: 1, + }, nil); err != nil { + t.Fatalf("Upsert: %v", err) + } + delta, err := s.ListPathDeltaSince(ctx, vID, 0) + if err != nil || len(delta) != 1 { + t.Fatalf("ListPathDeltaSince = %v, %v; want one row", delta, err) + } + return delta[0], vID, runID +} + +func commitWrite(d PathDelta, runID int64) RemotePathWrite { + return RemotePathWrite{Destination: "usb", FolderID: d.FolderID, Name: "cat.jpg", ContentID: d.ContentID, RunID: runID, MtimeNs: 42} +} + +// TestRemotePathLifecycle walks one version through every recorded move — +// committing, live, displacing, displaced — and checks that each read sees +// it where the move left it, with its path and size resolved. +func TestRemotePathLifecycle(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + unsettled, err := s.ListUnsettledRemotePaths(ctx, "usb", vID) + if err != nil || len(unsettled) != 1 || unsettled[0].State != RemotePathCommitting { + t.Fatalf("unsettled after commit intent = %+v, %v", unsettled, err) + } + if got := unsettled[0]; got.Path != "2024/cat.jpg" || got.SizeBytes != 3 || got.MtimeNs != 42 { + t.Fatalf("row = %+v, want path 2024/cat.jpg size 3 mtime 42", got) + } + + if err := s.ConfirmRemotePathsLive(ctx, id); err != nil { + t.Fatalf("ConfirmRemotePathsLive: %v", err) + } + live, err := s.ListLiveRemotePaths(ctx, "usb", vID) + if err != nil || len(live) != 1 || live[0].ID != id { + t.Fatalf("live = %+v, %v", live, err) + } + + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { + t.Fatalf("BeginRemotePathsDisplace: %v", err) + } + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { + t.Fatalf("ConfirmRemotePathsDisplaced: %v", err) + } + rows, err := s.ListRemotePaths(ctx, "usb", vID) + if err != nil || len(rows) != 1 { + t.Fatalf("ListRemotePaths = %+v, %v", rows, err) + } + if rows[0].State != RemotePathDisplaced || rows[0].DisplacedRunID.Int64 != runID { + t.Fatalf("row = %+v, want displaced by run %d", rows[0], runID) + } + if live, _ := s.ListLiveRemotePaths(ctx, "usb", vID); len(live) != 0 { + t.Fatalf("a displaced row still reads as live: %+v", live) + } +} + +// TestVolumeHasRemotePaths: a volume has mirror records on a destination +// once any row of it is there, in any state, and only on that destination. +func TestVolumeHasRemotePaths(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + if has, err := s.VolumeHasRemotePaths(ctx, "usb", vID); err != nil || has { + t.Fatalf("before any write = %v, %v; want none", has, err) + } + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatal(err) + } + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatal(err) + } + if has, err := s.VolumeHasRemotePaths(ctx, "usb", vID); err != nil || !has { + t.Fatalf("with a lost row = %v, %v; want records", has, err) + } + if has, err := s.VolumeHasRemotePaths(ctx, "other", vID); err != nil || has { + t.Fatalf("on another destination = %v, %v; want none", has, err) + } +} + +// TestRemotePathTransitionsNeedTheirSourceState: a move applies only to a +// row in the state it starts from, and a batch with one wrong row changes +// nothing, so a record never claims a move it did not witness. +func TestRemotePathTransitionsNeedTheirSourceState(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err == nil { + t.Fatal("a committing row was confirmed displaced") + } + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err == nil { + t.Fatal("a committing row began a displacement") + } + if err := s.RevertRemotePathsLive(ctx, id); err == nil { + t.Fatal("a committing row was reverted to live") + } + if err := s.ConfirmRemotePathsLive(ctx, id, id+1); err == nil { + t.Fatal("a batch naming a missing row succeeded") + } + rows, _ := s.ListRemotePaths(ctx, "usb", vID) + if len(rows) != 1 || rows[0].State != RemotePathCommitting { + t.Fatalf("a failed batch changed the row: %+v", rows) + } + + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatalf("MarkRemotePathsLost: %v", err) + } + if err := s.MarkRemotePathsLost(ctx, id); err == nil { + t.Fatal("a lost row was marked lost twice") + } +} + +// TestRemotePathOneLiveVersionPerPath: while a version is live, no second +// commit may start at its path; once the live one is displacing, it may. +// A displacement that never happened reverts to live. +func TestRemotePathOneLiveVersionPerPath(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + first, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if err := s.ConfirmRemotePathsLive(ctx, first); err != nil { + t.Fatalf("ConfirmRemotePathsLive: %v", err) + } + if _, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)); err == nil { + t.Fatal("a second commit started at a path with a live version") + } + // Another destination is independent. + other := commitWrite(d, runID) + other.Destination = "nas" + if _, err := s.BeginRemotePathCommit(ctx, other); err != nil { + t.Fatalf("commit on another destination: %v", err) + } + + if err := s.BeginRemotePathsDisplace(ctx, runID, first); err != nil { + t.Fatalf("BeginRemotePathsDisplace: %v", err) + } + if err := s.RevertRemotePathsLive(ctx, first); err != nil { + t.Fatalf("RevertRemotePathsLive: %v", err) + } + rows, _ := s.ListLiveRemotePaths(ctx, "usb", vID) + if len(rows) != 1 || rows[0].DisplacedRunID.Valid { + t.Fatalf("reverted row = %+v, want live with no displacing run", rows) + } +} + +// TestContentPresentOnDestinationCountsContentLayoutsOnly: the content +// layouts' upload-once check counts only bytes where they read them. A +// live mirror copy sits at its path, so a destination whose mirror records +// outlived a switch to a content layout still uploads the object. +func TestContentPresentOnDestinationCountsContentLayoutsOnly(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, _, runID := remotePathFixture(t, s) + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if err := s.ConfirmRemotePathsLive(ctx, id); err != nil { + t.Fatal(err) + } + if ok, err := s.ContentPresentOnDestination(ctx, d.ContentID, "usb"); err != nil || ok { + t.Fatalf("ContentPresentOnDestination with only a mirror copy = %t, %v; want false", ok, err) + } + if err := s.InsertRemoteObject(ctx, RemoteObject{ContentID: d.ContentID, Destination: "usb", UploadedRunID: runID}); err != nil { + t.Fatal(err) + } + if ok, err := s.ContentPresentOnDestination(ctx, d.ContentID, "usb"); err != nil || !ok { + t.Fatalf("ContentPresentOnDestination with an object = %t, %v; want true", ok, err) + } +} + +// TestResetDestinationClearsRemotePaths: a reset clears the mirror ledger +// with the others, counts it, and leaves the destination without upload +// records. +func TestResetDestinationClearsRemotePaths(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + if _, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)); err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if has, err := s.DestinationHasUploadRecords(ctx, "usb"); err != nil || !has { + t.Fatalf("DestinationHasUploadRecords = %t, %v; want true", has, err) + } + + _, counts, err := s.ResetDestination(ctx, "usb") + if err != nil { + t.Fatalf("ResetDestination: %v", err) + } + if counts.RemotePaths != 1 { + t.Fatalf("counts = %+v, want one remote path", counts) + } + if rows, _ := s.ListRemotePaths(ctx, "usb", vID); len(rows) != 0 { + t.Fatalf("rows after reset = %+v", rows) + } + if has, err := s.DestinationHasUploadRecords(ctx, "usb"); err != nil || has { + t.Fatalf("DestinationHasUploadRecords after reset = %t, %v; want false", has, err) + } +} + +// liveRemotePath commits d at runID on "usb" with checksum (empty for +// none) and confirms it live. +func liveRemotePath(t *testing.T, s *Store, d PathDelta, runID int64, checksum string) int64 { + t.Helper() + ctx := context.Background() + w := commitWrite(d, runID) + w.Checksum, w.VerifiedAtNs = checksum, 7 + id, err := s.BeginRemotePathCommit(ctx, w) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if err := s.ConfirmRemotePathsLive(ctx, id); err != nil { + t.Fatalf("ConfirmRemotePathsLive: %v", err) + } + return id +} + +// TestMirrorFingerprintsGateOnlyWhileStored: a live or displaced mirror copy +// whose read-back recorded its BLAKE3 counts as fingerprint-verified; one +// without a checksum, or a lost one, does not. +func TestMirrorFingerprintsGateOnlyWhileStored(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + verified := func() bool { + t.Helper() + ok, err := s.ContentFingerprintVerified(ctx, d.ContentID, "usb") + if err != nil { + t.Fatal(err) + } + pending, err := s.CountVolumeContentsPendingFingerprint(ctx, vID, "usb") + if err != nil { + t.Fatal(err) + } + if ok != (pending == 0) { + t.Fatalf("ContentFingerprintVerified = %t but %d content(s) pending", ok, pending) + } + return ok + } + + unhashed := liveRemotePath(t, s, d, runID, "") + if verified() { + t.Fatal("a mirror copy without a checksum counts as verified") + } + if err := s.MarkRemotePathsLost(ctx, unhashed); err != nil { + t.Fatal(err) + } + id := liveRemotePath(t, s, d, runID, "abc") + if !verified() { + t.Fatal("a live mirror copy with a read-back checksum does not count as verified") + } + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { + t.Fatal(err) + } + if verified() { + t.Fatal("a copy on its way into history counts as verified") + } + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { + t.Fatal(err) + } + if !verified() { + t.Fatal("a displaced copy with a read-back checksum does not count as verified") + } + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatal(err) + } + if verified() { + t.Fatal("a lost copy counts as verified") + } +} + +// TestListStoredRemotePathsRotatesByVerification: the verify listing holds +// every live and displaced row, never-verified first, then oldest verified, +// and a re-read moves a row to the back. +func TestListStoredRemotePathsRotatesByVerification(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, _, runID := remotePathFixture(t, s) + first := liveRemotePath(t, s, d, runID, "abc") + if err := s.BeginRemotePathsDisplace(ctx, runID, first); err != nil { + t.Fatal(err) + } + if err := s.ConfirmRemotePathsDisplaced(ctx, first); err != nil { + t.Fatal(err) + } + second := liveRemotePath(t, s, d, runID, "") + ids := func() []int64 { + t.Helper() + rows, err := s.ListStoredRemotePaths(ctx, "usb") + if err != nil { + t.Fatal(err) + } + var out []int64 + for _, r := range rows { + if r.Volume != "v" || r.Path != "2024/cat.jpg" { + t.Fatalf("row = %+v, want volume v at 2024/cat.jpg", r) + } + out = append(out, r.ID) + } + return out + } + if got := ids(); len(got) != 2 || got[0] != second || got[1] != first { + t.Fatalf("order = %v, want the never-verified %d before %d", got, second, first) + } + if stamped, err := s.RecordRemotePathVerified(ctx, second, "abc", 9); err != nil || !stamped { + t.Fatalf("RecordRemotePathVerified = %t, %v", stamped, err) + } + if got := ids(); got[0] != first || got[1] != second { + t.Fatalf("order after re-reading %d = %v", second, got) + } + if stamped, err := s.RecordRemotePathVerified(ctx, second, "def", 10); err != nil || stamped { + t.Fatalf("a read replaced the checksum it should re-confirm: %t, %v", stamped, err) + } +} + +// TestListRemotePathRepairs: a present path whose current content the +// destination lost is a repair until a new live row holds it again. +func TestListRemotePathRepairs(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + repairs := func() []PathDelta { + t.Helper() + out, err := s.ListRemotePathRepairs(ctx, "usb", vID) + if err != nil { + t.Fatal(err) + } + return out + } + id := liveRemotePath(t, s, d, runID, "") + if got := repairs(); len(got) != 0 { + t.Fatalf("repairs with a live copy = %+v", got) + } + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatal(err) + } + got := repairs() + if len(got) != 1 || got[0].Path != d.Path || got[0].ContentID != d.ContentID || got[0].Status != StatusPresent { + t.Fatalf("repairs after the copy was lost = %+v, want %s", got, d.Path) + } + liveRemotePath(t, s, d, runID, "") + if got := repairs(); len(got) != 0 { + t.Fatalf("repairs once a new copy is live = %+v", got) + } +} + +// TestLoseStoredRemotePathOnlyFromTheStateRead: a verify finding marks a +// row lost only while it is still in the state the pass read, so a push +// that moved the row in between keeps its record. +func TestLoseStoredRemotePathOnlyFromTheStateRead(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, _, runID := remotePathFixture(t, s) + id := liveRemotePath(t, s, d, runID, "") + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { + t.Fatal(err) + } + if moved, err := s.LoseStoredRemotePath(ctx, id, RemotePathLive); err != nil || moved { + t.Fatalf("lose a row read live that is now displacing = %t, %v; want untouched", moved, err) + } + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { + t.Fatal(err) + } + if moved, err := s.LoseStoredRemotePath(ctx, id, RemotePathDisplaced); err != nil || !moved { + t.Fatalf("lose a displaced row = %t, %v; want moved", moved, err) + } +} + +// TestDemoteFingerprintVerifiedVector: a demotion re-stamps only the +// locally advanced fingerprint-verified components, keeping their runs, and +// a later advance upgrades them again. +func TestDemoteFingerprintVerifiedVector(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + _, vID, runID := remotePathFixture(t, s) + self, err := s.GetSelfNode(ctx) + if err != nil { + t.Fatal(err) + } + if err := s.UpsertDestinationRunIDVerified(ctx, vID, "usb", self.ID, runID, VerifyMethodFingerprint, false); err != nil { + t.Fatal(err) + } + if err := s.DemoteFingerprintVerifiedVector(ctx, vID, "usb"); err != nil { + t.Fatalf("DemoteFingerprintVerifiedVector: %v", err) + } + comps, err := s.ListDestinationRunIDs(ctx, vID, "usb") + if err != nil || len(comps) != 1 || comps[0].VerifyMethod != VerifyMethodPresenceSize || comps[0].OriginRunID != runID { + t.Fatalf("vector = %+v, %v; want one presence+size component at run %d", comps, err, runID) + } + if err := s.UpsertDestinationRunIDVerified(ctx, vID, "usb", self.ID, runID, VerifyMethodFingerprint, false); err != nil { + t.Fatal(err) + } + if comps, _ := s.ListDestinationRunIDs(ctx, vID, "usb"); comps[0].VerifyMethod != VerifyMethodFingerprint { + t.Fatalf("vector after a later advance = %+v, want fingerprint-verified again", comps) + } +} diff --git a/store/runs_audit.go b/store/runs_audit.go index 43212e4..23edb77 100644 --- a/store/runs_audit.go +++ b/store/runs_audit.go @@ -97,6 +97,13 @@ const ( // recovered, and the volume restores that follow would appear in the // history with no explanation of where the catalog came from. TransitionRecoverIndex = "recover-index" + // TransitionDisplaceUnrecorded records bytes a native mirror push found + // at a path it was about to write and moved into history although + // squirrel had not written them there: a foreign write, a tree another + // tool wrote, or a recorded version changed behind squirrel's back. The + // note carries the path and where the bytes now are, so the trail lists + // what squirrel preserved without vouching for it. + TransitionDisplaceUnrecorded = "displace-unrecorded" ) // RunAudit is one row of the insert-only runs_audit log: a single diff --git a/store/schema.sql b/store/schema.sql index bfff9aa..612e82f 100644 --- a/store/schema.sql +++ b/store/schema.sql @@ -1,6 +1,6 @@ -- Generated by `go test ./store -update-schema` — DO NOT EDIT. -- --- Flattened snapshot of the squirrel index schema at version 31, for humans +-- Flattened snapshot of the squirrel index schema at version 33, for humans -- and agents who want the current shape without replaying the migration -- chain in migrations.go. It is NOT used to create or migrate databases — -- a fresh DB is built by applyV5 plus the migration registry. The golden @@ -211,6 +211,36 @@ CREATE TABLE "remote_packs" ( CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) ) STRICT; +CREATE TABLE remote_paths ( + id INTEGER PRIMARY KEY, + destination TEXT NOT NULL, + folder_id INTEGER NOT NULL, + name TEXT NOT NULL, + content_id INTEGER NOT NULL, + written_run_id INTEGER NOT NULL REFERENCES runs(id), + state TEXT NOT NULL + CHECK (state IN ('committing', 'live', 'displacing', 'displaced', 'lost')), + displaced_run_id INTEGER REFERENCES runs(id), + mtime_ns INTEGER NOT NULL, + checksum_algo TEXT, + checksum TEXT, + verified_at_ns INTEGER, + FOREIGN KEY (folder_id, name, content_id) REFERENCES files (folder_id, name, content_id), + CHECK (state NOT IN ('committing', 'live') OR displaced_run_id IS NULL), + CHECK (state NOT IN ('displacing', 'displaced') OR displaced_run_id IS NOT NULL), + CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) + ) STRICT; + +CREATE INDEX idx_remote_paths_content ON remote_paths (content_id); + +CREATE INDEX idx_remote_paths_lost ON remote_paths (destination) WHERE state = 'lost'; + +CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) + WHERE state IN ('committing', 'displacing'); + +CREATE UNIQUE INDEX uniq_remote_paths_live ON remote_paths (destination, folder_id, name) + WHERE state IN ('committing', 'live'); + CREATE TABLE "runs" ( id INTEGER PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('index','sync','restore','audit','offload')), diff --git a/sync/appledouble.go b/sync/appledouble.go new file mode 100644 index 0000000..b752195 --- /dev/null +++ b/sync/appledouble.go @@ -0,0 +1,21 @@ +package sync + +import "strings" + +// appleDouble reports whether name is the AppleDouble companion of an +// entry beside it: "._X" next to "X", where macOS keeps X's extended +// attributes on a filesystem that has none (exFAT, FAT, some SMB shares). +// The system moves and removes the companion together with X. +func appleDouble(name string, siblings map[string]bool) bool { + x, ok := strings.CutPrefix(name, "._") + return ok && x != "" && siblings[x] +} + +// entryNames is the set of the entries' names. +func entryNames(entries []entry) map[string]bool { + names := make(map[string]bool, len(entries)) + for _, e := range entries { + names[e.name] = true + } + return names +} diff --git a/sync/artifacts.go b/sync/artifacts.go new file mode 100644 index 0000000..b74859c --- /dev/null +++ b/sync/artifacts.go @@ -0,0 +1,87 @@ +package sync + +import ( + "context" + "fmt" + "os" + + "github.com/zeebo/blake3" +) + +// artifactStore is where a content-addressed or packed push lands its +// artifacts: an rclone remote, or a native destination root reached +// through squirrel's own transport. Names are slash-separated and relative +// to the destination root, as namer and the layout constants build them. +type artifactStore interface { + // markers gates the push on the destination's markers, writing missing + // ones under opts.Init; a dry run only checks. + markers(ctx context.Context, opts Options) error + // exists reports whether the artifact at name is present. + exists(ctx context.Context, name string) (bool, error) + // rootEmpty reports whether the root holds nothing beyond squirrel's + // markers. + rootEmpty(ctx context.Context) (bool, error) + // reconcile clears what finished pushes left in flight, once at push + // start. + reconcile(ctx context.Context, rep *Report, runID int64) error + // putAll lands every artifact whole, confirms each landed — its size, + // and bytes whose BLAKE3 is its sum: errContentDrift when its source + // no longer hashes to it — and returns once each has landed durably or + // failed, so the caller may record what landed. Each result carries + // the fingerprint the landing already confirmed, or nil when capture + // must read one later; results follow items. + putAll(ctx context.Context, runID int64, items []artifactPut) []artifactResult + // capture fills the fingerprints put left pending for this run's + // artifacts under dir (ObjectsDirName or PacksDirName). + capture(ctx context.Context, rep *Report, dir string, targets []captureTarget) + // shelf is the volume's .squirrel-index/ directory, where runID's + // ride-along index snapshot lands. + shelf(runID int64) snapshotShelf + // where names an artifact for a message. + where(name string) string + // close releases the destination once the push returns. + close() +} + +// artifactPut is one artifact to land: the local file src at name, size +// bytes whose BLAKE3 is sum. +type artifactPut struct { + name, src string + size int64 + sum []byte +} + +// artifactResult is how one artifact landed: the fingerprint the landing +// confirmed, if any, or why it failed. +type artifactResult struct { + fingerprint *remoteChecksum + err error +} + +// putArtifact lands one artifact through art. +func putArtifact(ctx context.Context, art artifactStore, runID int64, item artifactPut) (*remoteChecksum, error) { + r := art.putAll(ctx, runID, []artifactPut{item})[0] + return r.fingerprint, r.err +} + +// putBytes lands body at name through art, staged in a temporary file. +// what names the artifact in error messages. +func putBytes(ctx context.Context, art artifactStore, runID int64, name string, body []byte, what string) error { + tmp, err := os.CreateTemp("", "squirrel-meta-*") + if err != nil { + return fmt.Errorf("stage %s: %w", what, err) + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err := tmp.Write(body); err != nil { + _ = tmp.Close() + return fmt.Errorf("write %s: %w", what, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("close %s: %w", what, err) + } + sum := blake3.Sum256(body) + if _, err := putArtifact(ctx, art, runID, artifactPut{name: name, src: tmp.Name(), size: int64(len(body)), sum: sum[:]}); err != nil { + return fmt.Errorf("upload %s to %s: %w", what, art.where(name), err) + } + return nil +} diff --git a/sync/artifacts_rclone.go b/sync/artifacts_rclone.go new file mode 100644 index 0000000..732ecdf --- /dev/null +++ b/sync/artifacts_rclone.go @@ -0,0 +1,113 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "fmt" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// rcloneArtifacts is an artifact store rclone reaches, through the crypt +// overlay when the destination has one. +type rcloneArtifacts struct { + store *store.Store + rcl *Rclone + vol *config.Volume + dest *config.Destination +} + +// names is how the destination names its artifacts. +func (a *rcloneArtifacts) names() namer { return namerFor(a.dest) } + +// markers gates the push on the root's naming scheme, then on the +// destination's per-volume .squirrel-volume marker, exactly as the mirror +// layout does (the marker sits at the volume root regardless of layout). A +// dry run checks the naming scheme read-only and writes nothing. +func (a *rcloneArtifacts) markers(ctx context.Context, opts Options) error { + if opts.DryRun { + _, err := a.checkNamingScheme(ctx) + return err + } + if err := a.ensureNamingScheme(ctx, opts.Init); err != nil { + return err + } + return ensureRemoteDestinationMarker(ctx, a.store, a.rcl, a.dest, a.vol.Name, opts.Init) +} + +func (a *rcloneArtifacts) exists(ctx context.Context, name string) (bool, error) { + return a.rcl.statRemoteExists(ctx, a.where(name), concurrencyArgs(a.dest)...) +} + +// rootEmpty reports whether the destination root holds no files beyond +// squirrel's markers — a wiped or repointed destination, or one whose +// recorded state was cleared by `squirrel destination reset`. +func (a *rcloneArtifacts) rootEmpty(ctx context.Context) (bool, error) { + return a.rcl.remoteRootEmpty(ctx, remoteSubpathURI(a.dest, ""), rootMarkerNames(a.dest), concurrencyArgs(a.dest)...) +} + +// reconcile returns at once: rclone lands every artifact under its own +// name, and squirrel records it only after it landed. +func (a *rcloneArtifacts) reconcile(context.Context, *Report, int64) error { return nil } + +// putAll copies the artifacts one after another. +func (a *rcloneArtifacts) putAll(ctx context.Context, _ int64, items []artifactPut) []artifactResult { + out := make([]artifactResult, len(items)) + for i, it := range items { + out[i].err = a.put(ctx, it.name, it.src, it.size, it.sum) + } + return out +} + +// put re-hashes src immediately before the transfer and refuses +// (errContentDrift) when the digest no longer matches sum, catching a +// size+mtime-preserving in-place edit that a metadata stat would pass. The +// post-transfer stat confirms presence and size; the fingerprint is read +// back afterwards (capture). +// +// Residual: rclone reads the file in a separate child process after the +// re-hash, so a writer that edits the file in the window between the hash +// and rclone's read could still upload drifted bytes. The window is the +// fork/exec of one rclone invocation rather than the whole walk-to-push +// span, and the scan-back fingerprint pass (#109) re-reads the landed +// object to upgrade the durability vector, catching any byte that slipped +// through before the object is treated as content-verified. +func (a *rcloneArtifacts) put(ctx context.Context, name, src string, size int64, sum []byte) error { + digest, err := hashLocalFile(src) + if err != nil { + return fmt.Errorf("re-hash %s before upload: %w", src, err) + } + if !bytes.Equal(digest, sum) { + return fmt.Errorf("%w: %s now hashes to %s, indexed as %s", errContentDrift, src, hex.EncodeToString(digest), hex.EncodeToString(sum)) + } + uri := a.where(name) + if err := a.rcl.copyTo(ctx, src, uri, concurrencyArgs(a.dest)...); err != nil { + return err + } + landed, err := a.rcl.statRemote(ctx, uri, concurrencyArgs(a.dest)...) + if err != nil { + return fmt.Errorf("confirm %s after upload: %w", uri, err) + } + if landed != size { + return fmt.Errorf("%s landed with size %d, want %d", uri, landed, size) + } + return nil +} + +func (a *rcloneArtifacts) capture(ctx context.Context, rep *Report, dir string, targets []captureTarget) { + a.captureScanBackFingerprints(ctx, rep, dir, targets) +} + +// shelf is the destination's .squirrel-index/ directory, reached through +// rclone like the rest of the push. +func (a *rcloneArtifacts) shelf(int64) snapshotShelf { + return rcloneShelf{rcl: a.rcl, dir: indexDirURI(a.dest, a.vol.Name)} +} + +// where is the artifact's rclone URI, through the crypt overlay when the +// destination has one. +func (a *rcloneArtifacts) where(name string) string { return remoteSubpathURI(a.dest, name) } + +func (a *rcloneArtifacts) close() {} diff --git a/sync/artifacts_transport.go b/sync/artifacts_transport.go new file mode 100644 index 0000000..c98c2d8 --- /dev/null +++ b/sync/artifacts_transport.go @@ -0,0 +1,298 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "io/fs" + "os" + gosync "sync" + "sync/atomic" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/store" +) + +// transportArtifacts is an artifact store squirrel writes itself: a +// content-addressed or packed destination on a local disk, or on an sftp +// server without crypt. Each artifact is staged in the volume's +// .squirrel-staging/run-/ while BLAKE3 hashes the bytes sent, flushed, +// read back — through BLAKE3 on a local disk, through the server's hash +// command on sftp — and renamed onto its name, so it lands whole or not at +// all. Artifacts land a batch at a time, several in flight. +type transportArtifacts struct { + *destinationRoot + + mu gosync.Mutex + // noServerHash is why the sftp server fingerprinted nothing this push, + // once a landing found out. + noServerHash error +} + +// root is the destination root as the push may hold it: guarded, so only +// runID's own commits pass (none when runID is 0), and bounded by progress. +func (a *transportArtifacts) root(ctx context.Context, runID int64) (transport, error) { + return a.guarded(ctx, nameGuard{volumeDir: a.volumeDir, runID: runID, content: true, finished: a.runFinished}) +} + +// markers gates a push that writes on the volume marker, as a native +// mirror does: written under --init, which also creates a missing local +// root, and refused otherwise. +func (a *transportArtifacts) markers(ctx context.Context, opts Options) error { + if opts.DryRun { + return nil + } + return a.ensureMarker(ctx, opts.Init) +} + +func (a *transportArtifacts) exists(ctx context.Context, name string) (bool, error) { + tr, err := a.root(ctx, 0) + if err != nil { + return false, err + } + return present(ctx, tr, name) +} + +func (a *transportArtifacts) rootEmpty(ctx context.Context) (bool, error) { + tr, err := a.root(ctx, 0) + if err != nil { + return false, err + } + return treeEmpty(ctx, tr, ".") +} + +// reconcile removes what finished runs left staged: a partial artifact +// from a crash, a drifted source's copy, or one whose name another run's +// landing already held. +func (a *transportArtifacts) reconcile(ctx context.Context, rep *Report, runID int64) error { + tr, err := a.root(ctx, runID) + if err != nil { + return err + } + return a.clearFinishedStaging(ctx, rep, tr) +} + +// artifactLanding is one artifact on its way through putAll. +type artifactLanding struct { + artifactPut + staged string + // sent is the server-side hash of the bytes sent, "" without one. + sent string + res *artifactResult +} + +// putAll takes the artifacts through the steps of a landing, each for all +// of them before the next: stage, flush, confirm, rename, flush. An +// artifact whose step fails drops out; one a stall or cancellation kept +// from the final flush fails too, since only that flush lands it. +func (a *transportArtifacts) putAll(ctx context.Context, runID int64, items []artifactPut) []artifactResult { + out := make([]artifactResult, len(items)) + tr, err := a.root(ctx, runID) + if err != nil { + for i := range out { + out[i].err = err + } + return out + } + ls := make([]*artifactLanding, len(items)) + for i, it := range items { + ls[i] = &artifactLanding{artifactPut: it, staged: stagingName(a.volumeDir, runID, stagingKey(it.name)), res: &out[i]} + } + b := artifactBatch{a: a, tr: tr, n: pushConcurrency(a.dest)} + b.each(ctx, ls, b.stage) + if b.flush(ctx, ls, "flush the staged artifacts") { + b.each(ctx, ls, b.confirmStaged) + b.each(ctx, ls, b.rename) + if b.flush(ctx, ls, "flush the landed artifacts") { + return out + } + } + b.abandon(ctx, ls) + return out +} + +// artifactBatch runs the steps of putAll over one batch. +type artifactBatch struct { + a *transportArtifacts + tr transport + n int + stalled atomic.Bool +} + +// each runs step for every artifact still on its way, n in flight; an +// artifact whose step fails drops out, and a stall starts no more. +func (b *artifactBatch) each(ctx context.Context, ls []*artifactLanding, step func(context.Context, *artifactLanding) error) { + inFlight(ctx, b.n, pendingArtifacts(ls), b.stalled.Load, func(l *artifactLanding) { + if err := step(ctx, l); err != nil { + l.res.err = err + if errors.Is(err, errTransportStalled) { + b.stalled.Store(true) + } + } + }) +} + +// flush makes the batch's last step durable and reports whether it did. +// A flush that fails fails every artifact still on its way; a stalled or +// cancelled batch goes no further. +func (b *artifactBatch) flush(ctx context.Context, ls []*artifactLanding, what string) bool { + pending := pendingArtifacts(ls) + if len(pending) == 0 || b.stalled.Load() || ctx.Err() != nil { + return false + } + if err := b.tr.Flush(ctx); err != nil { + for _, l := range pending { + l.res.err = fmt.Errorf("%s: %w", what, err) + } + return false + } + return true +} + +// abandon fails every artifact the batch stopped short of landing. +func (b *artifactBatch) abandon(ctx context.Context, ls []*artifactLanding) { + why := ctx.Err() + if why == nil { + why = fmt.Errorf("%w: the batch stopped before the artifact landed", errTransportStalled) + } + for _, l := range pendingArtifacts(ls) { + l.res.err = why + } +} + +func pendingArtifacts(ls []*artifactLanding) []*artifactLanding { + var out []*artifactLanding + for _, l := range ls { + if l.res.err == nil { + out = append(out, l) + } + } + return out +} + +func (b *artifactBatch) stage(ctx context.Context, l *artifactLanding) error { + sent, err := b.a.stage(ctx, b.tr, l.staged, l.src, l.size, l.sum) + l.sent = sent + return err +} + +func (b *artifactBatch) confirmStaged(ctx context.Context, l *artifactLanding) error { + fingerprint, err := b.a.confirm(ctx, b.tr, l.staged, l.sum, l.sent, true) + l.res.fingerprint = fingerprint + return err +} + +// rename moves the staged artifact onto its name. A name that already +// holds a file is confirmed instead, and never replaced. +func (b *artifactBatch) rename(ctx context.Context, l *artifactLanding) error { + err := b.tr.Rename(ctx, l.staged, l.name) + if !errors.Is(err, fs.ErrExist) { + return err + } + fingerprint, err := b.a.confirm(ctx, b.tr, l.name, l.sum, l.sent, false) + l.res.fingerprint = fingerprint + return err +} + +// stage streams src into staged, hashing the bytes sent with BLAKE3 and, +// on sftp, with the hash the server's command computes. It returns that +// server-side hash's value for what was sent, or "" when there is none. +func (a *transportArtifacts) stage(ctx context.Context, tr transport, staged, src string, size int64, sum []byte) (string, error) { + f, err := os.Open(src) + if err != nil { + return "", fmt.Errorf("open %s: %w", src, err) + } + defer f.Close() + b3 := blake3.New() + counted := &countWriter{w: b3} + sink := io.Writer(counted) + server := newArtifactHash(a.dest.HashAlgo) + if server != nil { + sink = io.MultiWriter(counted, server) + } + if err := tr.Put(ctx, staged, io.TeeReader(f, sink), time.Now()); err != nil { + return "", fmt.Errorf("stage %s: %w", staged, err) + } + if counted.n != size || !bytes.Equal(b3.Sum(nil), sum) { + return "", fmt.Errorf("%w: %s sent %d bytes hashing to %s, want %d bytes %s", errContentDrift, src, counted.n, hex.EncodeToString(b3.Sum(nil)), size, hex.EncodeToString(sum)) + } + e, err := tr.Stat(ctx, staged) + if err != nil { + return "", fmt.Errorf("confirm %s: %w", staged, err) + } + if e.size != size { + return "", fmt.Errorf("%s landed with size %d, want %d", staged, e.size, size) + } + return hexSum(server), nil +} + +// confirm checks that name holds the bytes sent — read back through +// BLAKE3 against sum on a local disk, hashed by the server's command +// against sent on sftp — and returns the fingerprint that earns. An sftp +// server without the command confirms nothing and fingerprints nothing: +// a staged artifact is committed with its fingerprint pending; one already +// at its name — a crash between its landing and its record, or an earlier +// failed run's orphan — is downloaded and hashed instead, because squirrel +// never replaces it. +func (a *transportArtifacts) confirm(ctx context.Context, tr transport, name string, sum []byte, sent string, staged bool) (*remoteChecksum, error) { + if !readsBack(a.dest) { + cs, err := tr.ServerHash(ctx, name) + switch { + case err == nil && cs.Value == sent: + return &cs, nil + case err == nil: + return nil, fmt.Errorf("%w: %s hashes to %s %s on the server, sent %s", errReadBackMismatch, name, cs.Algo, cs.Value, sent) + case !errors.Is(err, errNoServerHash): + return nil, fmt.Errorf("hash %s on the server: %w", name, err) + } + a.mu.Lock() + a.noServerHash = err + a.mu.Unlock() + if staged { + return nil, nil + } + } + got, err := readBack(ctx, tr, name) + if err != nil { + return nil, fmt.Errorf("read back %s: %w", name, err) + } + if !bytes.Equal(got, sum) { + return nil, fmt.Errorf("%w: %s hashes to %s, sent %s — squirrel never replaces it; inspect it", errReadBackMismatch, name, hex.EncodeToString(got), hex.EncodeToString(sum)) + } + if !readsBack(a.dest) { + return nil, nil + } + return &remoteChecksum{Algo: store.ChecksumAlgoBlake3, Value: hex.EncodeToString(got)}, nil +} + +// capture warns about the artifacts that landed without a fingerprint: an +// sftp server that runs no hash command squirrel trusts. +func (a *transportArtifacts) capture(_ context.Context, rep *Report, dir string, targets []captureTarget) { + if len(targets) == 0 { + return + } + rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %d artifact(s) under %s/ landed without a fingerprint (%v); they stay pending, so the destination cannot gate offload for them", a.dest.Name, len(targets), dir, a.noServerHash)) +} + +// shelf is the volume's .squirrel-index/, reached through runID's guarded +// transport. +func (a *transportArtifacts) shelf(runID int64) snapshotShelf { + return transportShelf{ + open: func(ctx context.Context) (transport, error) { return a.root(ctx, runID) }, + volume: a.volumeDir, + runID: runID, + } +} + +func hexSum(h hash.Hash) string { + if h == nil { + return "" + } + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/sync/batch.go b/sync/batch.go new file mode 100644 index 0000000..5c9ac52 --- /dev/null +++ b/sync/batch.go @@ -0,0 +1,79 @@ +package sync + +import ( + "context" + gosync "sync" + + "github.com/mbertschler/squirrel/config" +) + +// A native push writes in batches: every file of a batch is staged before +// one Flush makes the batch durable, and every record waits for the flush +// that covers its bytes. A batch holds at most batchMaxFiles files and +// batchMaxBytes bytes; a larger file goes alone. +const ( + batchMaxFiles = 64 + batchMaxBytes = 256 << 20 +) + +// Default paths in flight when a destination sets no concurrency: a local +// disk gains nothing past a few, a remote link hides its round trips +// behind more. +const ( + defaultLocalConcurrency = 4 + defaultSFTPConcurrency = 8 +) + +// pushConcurrency is how many files a push writes to dest at once. +func pushConcurrency(dest *config.Destination) int { + switch { + case dest.Concurrency > 0: + return dest.Concurrency + case dest.Type == "sftp": + return defaultSFTPConcurrency + default: + return defaultLocalConcurrency + } +} + +// batches splits items, in order, into runs of at most batchMaxFiles items +// and batchMaxBytes bytes by size. +func batches[T any](items []T, size func(T) int64) [][]T { + var out [][]T + var cur []T + var bytes int64 + for _, it := range items { + n := size(it) + if len(cur) > 0 && (len(cur) == batchMaxFiles || bytes+n > batchMaxBytes) { + out = append(out, cur) + cur, bytes = nil, 0 + } + cur = append(cur, it) + bytes += n + } + if len(cur) > 0 { + out = append(out, cur) + } + return out +} + +// inFlight calls fn for each item, at most n at a time and in order of +// starting, and returns once every call has returned. It starts no call +// once ctx is done or stop reports true. With n of 1 the calls run one +// after another, in order. +func inFlight[T any](ctx context.Context, n int, items []T, stop func() bool, fn func(T)) { + slots := make(chan struct{}, max(n, 1)) + var wg gosync.WaitGroup + for _, it := range items { + slots <- struct{}{} + if ctx.Err() != nil || stop() { + <-slots + break + } + wg.Go(func() { + defer func() { <-slots }() + fn(it) + }) + } + wg.Wait() +} diff --git a/sync/batch_test.go b/sync/batch_test.go new file mode 100644 index 0000000..4b447cd --- /dev/null +++ b/sync/batch_test.go @@ -0,0 +1,65 @@ +package sync + +import ( + "context" + "sync/atomic" + "testing" + "time" +) + +// TestBatches: a batch closes at batchMaxFiles items or before the item +// that would take it past batchMaxBytes; an item larger than that goes +// alone. +func TestBatches(t *testing.T) { + size := func(n int64) int64 { return n } + cases := []struct { + name string + items []int64 + want []int + }{ + {"none", nil, nil}, + {"by count", make([]int64, batchMaxFiles+1), []int{batchMaxFiles, 1}}, + {"by bytes", []int64{batchMaxBytes / 2, batchMaxBytes / 2, 1}, []int{2, 1}}, + {"too large alone", []int64{1, batchMaxBytes + 1, 1}, []int{1, 1, 1}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var got []int + for _, b := range batches(c.items, size) { + got = append(got, len(b)) + } + if len(got) != len(c.want) { + t.Fatalf("batch sizes = %v, want %v", got, c.want) + } + for i := range got { + if got[i] != c.want[i] { + t.Fatalf("batch sizes = %v, want %v", got, c.want) + } + } + }) + } +} + +// TestInFlightBoundsTheCallsAtOnce: inFlight never runs more than n calls +// at once, runs every call, and starts none once stop reports true. +func TestInFlightBoundsTheCallsAtOnce(t *testing.T) { + var running, peak, calls atomic.Int64 + inFlight(context.Background(), 3, make([]int, 20), func() bool { return false }, func(int) { + now := running.Add(1) + for p := peak.Load(); now > p && !peak.CompareAndSwap(p, now); p = peak.Load() { + } + time.Sleep(time.Millisecond) + running.Add(-1) + calls.Add(1) + }) + if calls.Load() != 20 || peak.Load() > 3 { + t.Fatalf("calls = %d, peak = %d; want 20 calls, at most 3 at once", calls.Load(), peak.Load()) + } + var started atomic.Int64 + inFlight(context.Background(), 1, make([]int, 5), func() bool { return started.Load() == 2 }, func(int) { + started.Add(1) + }) + if started.Load() != 2 { + t.Fatalf("started %d calls, want 2 before stop", started.Load()) + } +} diff --git a/sync/content_addressed.go b/sync/content_addressed.go index a06fa05..b321de0 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -1,8 +1,8 @@ package sync import ( - "bytes" "context" + "database/sql" "encoding/hex" "encoding/json" "errors" @@ -11,6 +11,7 @@ import ( "os" "path" "path/filepath" + "slices" "strconv" "github.com/zeebo/blake3" @@ -97,43 +98,46 @@ func encodeManifestSegment(delta []store.PathDelta) ([]byte, error) { // per-run manifest segment under /index/run-, and fingerprint // freshly landed objects the same way. The content-addressed layout uses // this base directly; the packed layout embeds it and adds pack assembly -// for content below its threshold. +// for content below its threshold. art is where the artifacts land. type contentPusher struct { store *store.Store - rcl *Rclone vol *config.Volume dest *config.Destination + art artifactStore } // names is how this push names the artifacts it writes. func (h *contentPusher) names() namer { return namerFor(h.dest) } -// ensureMarkers gates a remote content-layout push on the root's naming -// scheme, then on the destination's per-volume .squirrel-volume marker, -// exactly as the mirror layout does (the marker sits at the volume root -// regardless of layout). Local content-addressed and packed destinations -// are intentionally left ungated here: they carry no such gate today, so -// extending it to them is a separate parity concern — this closes only the -// remote gap (#150). -func (h *contentPusher) ensureMarkers(ctx context.Context, init bool) error { - if h.dest.Type == "local" { - return nil - } - if err := h.ensureNamingScheme(ctx, init); err != nil { - return err - } - return ensureRemoteDestinationMarker(ctx, h.store, h.rcl, h.dest, h.vol.Name, init) +func (h *contentPusher) shelf(runID int64) snapshotShelf { return h.art.shelf(runID) } + +func (h *contentPusher) markers(ctx context.Context, _ *Report, _ int64, opts Options) error { + return h.art.markers(ctx, opts) } -// contentAddressedHandler pushes a volume to a content-addressed rclone -// destination: per-hash `rclone copyto` for each content object the -// destination lacks, then the run's manifest segment. The landing is +func (h *contentPusher) rootEmpty(ctx context.Context) (bool, error) { return h.art.rootEmpty(ctx) } + +// firstPush lets a content layout start over whatever the destination +// holds: an artifact already at its name is confirmed and adopted, never +// replaced. +func (h *contentPusher) firstPush(context.Context, int64) error { return nil } + +func (h *contentPusher) reconcile(ctx context.Context, rep *Report, _, runID int64) error { + return h.art.reconcile(ctx, rep, runID) +} + +func (h *contentPusher) target() pushTarget { + return pushTarget{store: h.store, vol: h.vol, dest: h.dest} +} + +// contentAddressedHandler pushes a volume to a content-addressed +// destination: one object for each content the destination lacks, then the +// run's manifest segment, through the artifact store. The landing is // transactional from the durability gate's point of view — the runs row // reaches success and the destination vector advances only once both // the objects and the segment are confirmed present at the expected // size; any earlier failure leaves orphaned objects that are recorded -// (or re-uploaded idempotently) and harmless without a segment mapping -// them. +// (or landed again) and harmless without a segment mapping them. type contentAddressedHandler struct { contentPusher } @@ -141,136 +145,45 @@ type contentAddressedHandler struct { func (h *contentAddressedHandler) TargetName() string { return h.dest.Name } func (h *contentAddressedHandler) Push(ctx context.Context, opts Options) (Report, error) { - rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} - // Stamped up front so output renderers key content-addressed - // formatting off the method even when the push fails early. - rep.Verification.Method = VerifyMethodPresenceSize + defer h.art.close() if h.vol.Name == ObjectsDirName { + rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} + rep.Verification.Method = VerifyMethodPresenceSize return rep, fmt.Errorf("volume %q: the name collides with the destination-root %s/ directory of content-addressed destination %q — rename the volume or use a mirrored destination", h.vol.Name, ObjectsDirName, h.dest.Name) } - volID, err := requireIndexedVolume(ctx, h.store, h.vol) - if err != nil { - return rep, err - } - if opts.DryRun { - if _, err := h.checkNamingScheme(ctx); err != nil { - return rep, err - } - return rep, h.previewDryRun(ctx, &rep, volID) - } - if err := h.ensureMarkers(ctx, opts.Init); err != nil { - return rep, err - } - // shallow=true on the runs row: the per-object transfers carry no - // BLAKE3 end-to-end check (crypt remotes expose no hashes), and the - // audit trail stays honest about that. - runID, err := beginSyncRunGuarded(ctx, h.store, false, store.SyncRunSpec{ - VolumeID: volID, - Destination: h.dest.Name, - Shallow: true, - }, h.vol.Name) - if err != nil { - return rep, err - } - rep.RunID = runID - if opts.OnRunID != nil { - opts.OnRunID(runID) - } - - err = h.push(ctx, &rep, volID, runID) - finishHandlerRun(ctx, h.store, &rep, err) - opts.Snapshot.afterSync(ctx, &rep, h.vol, h.dest) - return rep, err + return pushThrough(ctx, h.target(), h, opts) } func (h *contentAddressedHandler) sealed() {} -// previewDryRun reports what a real push would upload without transferring -// anything or writing a runs row: rep.RunID stays 0, no objects land, and -// no remote_objects or manifest-segment rows are written. It computes the -// same delta and new-content selection the real push does (watermark → -// delta → plannedUploads), so the preview matches what the next real run -// would land. The watermark check still reads the destination, so a -// layout-flip is refused here too — a dry-run is an honest rehearsal. -func (h *contentAddressedHandler) previewDryRun(ctx context.Context, rep *Report, volID int64) error { - watermark, err := h.watermark(ctx, volID) - if err != nil { - return err - } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) - } - rep.Verification.Files = int64(len(delta)) - if err := h.previewObjectUploads(ctx, rep, plannedUploads(delta)); err != nil { - return err - } - rep.Status = store.RunStatusSuccess - return nil +// translate selects the delta's present content, one source path per hash, +// and splits it by whether the destination already records it. +func (h *contentAddressedHandler) translate(ctx context.Context, p pushPlan) (objectUploads, error) { + return h.splitRecorded(ctx, plannedUploads(p.delta)) } -// push runs the transactional landing: delta → objects → segment → -// vector. rep.Status starts failed and is promoted to success only at -// the end, after the destination vector advanced — a confirmed landing -// whose evidence failed to record must not present as success, or the -// next run's watermark would skip past it. -func (h *contentAddressedHandler) push(ctx context.Context, rep *Report, volID, runID int64) error { - rep.Status = store.RunStatusFailed - watermark, err := h.watermark(ctx, volID) - if err != nil { - return err - } - advance, err := captureDurabilityAdvance(ctx, h.store, volID) - if err != nil { - return err - } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) - } - rep.Verification.Files = int64(len(delta)) - // The delta is exactly what this push changes at the destination: the - // paths whose content the manifest segment newly maps. An empty delta - // is a genuine no-op, which is what the runs fold keys on (#182). - rep.Changed = knownChanged(int64(len(delta))) - if err := h.uploadObjects(ctx, rep, runID, plannedUploads(delta)); err != nil { - return err - } - if err := h.uploadSegment(ctx, delta, runID); err != nil { - return err - } - // presence+size is not a content-verified method (crypt remotes expose - // no hashes): the component advances so the offload gate's per-object - // scan-back can back it locally. When this run's capture leaves the - // whole (volume, destination) pair with a verified fingerprint behind - // every present content, the advance is instead stamped - // fingerprint-verified — the content-verified method that also relays - // over the durability pull (see the durability-vector upgrade in - // store). A single still-pending object holds it at presence+size. - method, err := h.advanceMethod(ctx, volID, len(advance)) - if err != nil { - return err - } - if err := h.store.AdvanceDestinationVectorTo(ctx, volID, h.dest.Name, method, advance); err != nil { - return fmt.Errorf("advance destination vector for %s: %w", h.dest.Name, err) - } - rep.Status = store.RunStatusSuccess - rep.Verification.Bytes = rep.RcloneResult.Bytes - return nil +// execute lands every object the destination has no record of. +func (h *contentAddressedHandler) execute(ctx context.Context, rep *Report, runID int64, ops objectUploads) error { + return h.uploadObjects(ctx, rep, runID, ops) +} + +// seal writes the run's manifest segment, the layout's landing evidence. +func (h *contentAddressedHandler) seal(ctx context.Context, _ *Report, runID int64, p pushPlan, _ objectUploads) error { + return h.uploadSegment(ctx, p.delta, runID) } -// advanceMethod chooses the method the content-addressed push advances its -// durability vector with: fingerprint-verified when every present content -// of the volume already carries a verified provider fingerprint on this +// advanceMethod chooses fingerprint-verified when every present content of +// the volume already carries a verified provider fingerprint on this // destination (the whole-state check, not just this run's uploads), and -// presence+size otherwise. advanceLen is the size of the advance snapshot; -// an empty snapshot advances nothing, so the method is immaterial and the -// pending query is skipped. -func (h *contentPusher) advanceMethod(ctx context.Context, volID int64, advanceLen int) (string, error) { - if advanceLen == 0 { +// presence+size otherwise: presence+size is not content-verified (crypt +// remotes expose no hashes), so the offload gate's per-object scan-back +// backs it locally, and a single still-pending object holds the upgrade. +// An empty advance advances nothing, so the pending query is skipped. +func (h *contentAddressedHandler) advanceMethod(ctx context.Context, _ *Report, p pushPlan) (string, error) { + if len(p.advance) == 0 { return store.VerifyMethodPresenceSize, nil } - pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, volID, h.dest.Name) + pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, p.volumeID, h.dest.Name) if err != nil { return "", err } @@ -280,64 +193,65 @@ func (h *contentPusher) advanceMethod(ctx context.Context, volID int64, advanceL return store.VerifyMethodPresenceSize, nil } -// watermark resolves the run id the delta starts after: the last -// successful sync of this (volume, destination), or 0 for a fresh -// destination. The last success must still have its manifest segment at -// the destination — every successful content-addressed run uploads one, -// so its absence means the recorded history belongs to a different -// layout (a destination flipped from mirror) and a delta computed -// against it would silently skip everything the mirror era covered. -func (h *contentAddressedHandler) watermark(ctx context.Context, volID int64) (int64, error) { - last, err := h.store.LatestSuccessfulSyncRun(ctx, volID, h.dest.Name) - if store.IsNotFound(err) { - return 0, nil - } - if err != nil { - return 0, fmt.Errorf("lookup last successful sync of %s: %w", h.dest.Name, err) - } - segURI := h.segmentURI(last.ID) - if _, err := h.rcl.statRemote(ctx, segURI, checkersArgs(h.dest)...); err != nil { - if freshStartOnEmptyRoot(ctx, h.rcl, h.dest) { - return 0, nil - } - return 0, fmt.Errorf("destination %q: the last successful sync (run %d) left no manifest segment at %s — its history does not look content-addressed; point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w: %w", h.dest.Name, last.ID, segURI, h.dest.Name, err, ErrRefused) +// landed reports whether runID's manifest segment is at the destination. +// Every successful content-addressed run uploads one, so its absence means +// the recorded history belongs to a different layout or a wiped root. +func (h *contentAddressedHandler) landed(ctx context.Context, runID int64) (bool, error) { + return h.art.exists(ctx, h.segmentName(runID)) +} + +func (h *contentAddressedHandler) foreignHistory(runID int64) error { + return fmt.Errorf("destination %q: the last successful sync (run %d) left no manifest segment at %s — its history does not look content-addressed; point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.art.where(h.segmentName(runID)), h.dest.Name, ErrRefused) +} + +// objectUploads is the object side of a content push: the planned content +// the destination has no upload record for, and how many planned contents +// it already records (as a per-hash object or a pack member). +type objectUploads struct { + needed []store.PathDelta + recorded int64 +} + +// preview counts the split uploadObjects would record: needed content as +// Transferred + Bytes, recorded content as Checked. +func (o objectUploads) preview(rep *Report) { + rep.RcloneResult.Checked += o.recorded + for _, d := range o.needed { + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += d.SizeBytes } - return last.ID, nil } -// previewObjectUploads counts, without uploading, the split uploadObjects -// would record: planned content the destination has no record of lands on -// rep.RcloneResult as Transferred + Bytes, content already offsite (as a -// per-hash object or a pack member) as Checked. It writes nothing and -// touches no object. Both layouts' dry-run preview use it — the packed -// layout passes only its object-routed (large) content. -func (h *contentPusher) previewObjectUploads(ctx context.Context, rep *Report, planned []store.PathDelta) error { +// splitRecorded splits planned content by whether the destination already +// records it offsite, as a per-hash object or a pack member, so a threshold +// change that reclassifies content never re-uploads bytes the destination +// already holds in the other form. Both content layouts translate their +// object side through it. +func (h *contentPusher) splitRecorded(ctx context.Context, planned []store.PathDelta) (objectUploads, error) { + var out objectUploads for _, d := range planned { recorded, err := h.store.ContentPresentOnDestination(ctx, d.ContentID, h.dest.Name) if err != nil { - return fmt.Errorf("lookup upload record for %s: %w", d.Path, err) + return objectUploads{}, fmt.Errorf("lookup upload record for %s: %w", d.Path, err) } if recorded { - rep.RcloneResult.Checked++ + out.recorded++ continue } - rep.RcloneResult.Transferred++ - rep.RcloneResult.Bytes += d.SizeBytes + out.needed = append(out.needed, d) } - return nil + return out, nil } -// uploadObjects lands every planned content object that the destination -// has no upload record for. planned is the deduplicated, present-only -// upload set (plannedUploads) — the content-addressed layout passes its -// whole delta's uploads, the packed layout passes only the files at or -// above its pack threshold. Counters land on -// rep.RcloneResult so the run report reads like the other rclone -// flows: Transferred = objects uploaded, Checked = objects skipped as -// already recorded, Errors/FailedFiles = per-object failures. Per-object -// failures don't stop the loop — every object that lands now is recorded -// and saves work on the retry — but any failure fails the run before -// the segment is written. +// uploadObjects lands every planned content object the destination has +// no upload record for. The content-addressed layout passes its whole +// delta's uploads, the packed layout only the files at or above its pack +// threshold. Counters land on rep.RcloneResult so the run report reads +// like the other rclone flows: Transferred = objects uploaded, Checked = +// objects skipped as already recorded, Errors/FailedFiles = per-object +// failures. Per-object failures don't stop the loop — every object that +// lands now is recorded and saves work on the retry — but any failure +// fails the run before the segment is written. // // A source whose bytes drifted from the indexed hash is refused without a // remote_objects row (errContentDrift): it is surfaced as a warning and @@ -345,40 +259,42 @@ func (h *contentPusher) previewObjectUploads(ctx context.Context, rep *Report, p // advance. The next run recomputes the same delta and re-offers the // object, letting the honest bytes land once they are restored — without // the drifted bytes ever being recorded under the hash. -func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID int64, planned []store.PathDelta) error { - var confirmed []store.PathDelta +func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID int64, ops objectUploads) error { + rep.RcloneResult.Checked += ops.recorded + var pending []store.PathDelta var drifted int - for _, d := range planned { - // Two-source presence: skip content already offsite as a per-hash - // object or bundled in a pack already uploaded to this destination, - // so a threshold change that reclassifies content never re-uploads - // bytes the destination already holds in the other form. - recorded, err := h.store.ContentPresentOnDestination(ctx, d.ContentID, h.dest.Name) - if err != nil { - return fmt.Errorf("lookup upload record for %s: %w", d.Path, err) + for _, batch := range batches(ops.needed, func(d store.PathDelta) int64 { return d.SizeBytes }) { + if err := ctx.Err(); err != nil { + return err } - if recorded { - rep.RcloneResult.Checked++ - continue - } - if err := h.uploadOneObject(ctx, runID, d); err != nil { - if errors.Is(err, errContentDrift) { + results := h.uploadBatch(ctx, runID, batch) + for i, res := range results { + d := batch[i] + switch { + case errors.Is(res.err, errContentDrift): drifted++ - rep.Warnings = append(rep.Warnings, err.Error()) + rep.Warnings = append(rep.Warnings, res.err.Error()) continue + case res.err != nil: + rep.RcloneResult.Errors++ + if int64(len(rep.RcloneResult.FailedFiles)) < maxFailedFiles { + rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, + FailedFile{Object: d.Path, Message: res.err.Error()}) + } + continue + case res.fingerprint != nil: + rep.Fingerprints++ + default: + pending = append(pending, d) } - rep.RcloneResult.Errors++ - if int64(len(rep.RcloneResult.FailedFiles)) < maxFailedFiles { - rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, - FailedFile{Object: d.Path, Message: err.Error()}) - } - continue + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += d.SizeBytes + } + if slices.ContainsFunc(results, func(r artifactResult) bool { return errors.Is(r.err, errTransportStalled) }) { + break } - confirmed = append(confirmed, d) - rep.RcloneResult.Transferred++ - rep.RcloneResult.Bytes += d.SizeBytes } - h.captureFingerprints(ctx, rep, confirmed) + h.captureFingerprints(ctx, rep, pending) if rep.RcloneResult.Errors > 0 { return fmt.Errorf("%d object(s) failed to land on %q; the manifest segment for run %d was not written and the durability vector did not advance", rep.RcloneResult.Errors, h.dest.Name, runID) } @@ -389,15 +305,17 @@ func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID in } // captureFingerprints fills the pending checksum pair of every object -// confirmed during this run with the provider checksum read back from the -// underlying remote's objects/ directory, over the shared scan-back capture -// surface. That read-back is the first verification, so each object records -// and stamps verified_at_ns in one write (SetRemoteObjectFingerprint) — -// matching the packed layout; the later `squirrel verify` re-read re-stamps -// it on each re-confirmation. -func (h *contentPusher) captureFingerprints(ctx context.Context, rep *Report, confirmed []store.PathDelta) { - targets := make([]captureTarget, 0, len(confirmed)) - for _, d := range confirmed { +// confirmed during this run without one, read back from the destination's +// objects/ directory (the scan-back capture over rclone). That read-back is +// the first verification, so each object records and stamps verified_at_ns +// in one write (SetRemoteObjectFingerprint) — matching the packed layout; +// the later `squirrel verify` re-read re-stamps it on each re-confirmation. +func (h *contentPusher) captureFingerprints(ctx context.Context, rep *Report, pending []store.PathDelta) { + if len(pending) == 0 { + return + } + targets := make([]captureTarget, 0, len(pending)) + for _, d := range pending { d := d targets = append(targets, captureTarget{ name: h.names().object(d.Blake3), @@ -407,7 +325,7 @@ func (h *contentPusher) captureFingerprints(ctx context.Context, rep *Report, co }, }) } - h.captureScanBackFingerprints(ctx, rep, ObjectsDirName, targets) + h.art.capture(ctx, rep, ObjectsDirName, targets) } // plannedUploads selects the delta rows that need a content object — @@ -433,52 +351,44 @@ func plannedUploads(delta []store.PathDelta) []store.PathDelta { // the run so the watermark holds and the object is re-offered next run. var errContentDrift = errors.New("source content drifted from its indexed hash") -// uploadOneObject lands one content object and records the upload. It -// guards the content-addressed invariant — the bytes stored under a hash -// must be the bytes that produced it — by re-hashing the source file -// immediately before the transfer and refusing (errContentDrift) when the -// digest no longer matches the indexed hash, catching a -// size+mtime-preserving in-place edit that a metadata stat would pass. -// The post-transfer stat confirms presence and size on the remote, and the -// upload record is written only after that confirmation, so a recorded -// hash is always a confirmed one; a crash in between re-uploads the same -// bytes idempotently on the next run. -// -// Residual: rclone reads the file in a separate child process after the -// re-hash, so a writer that edits the file in the window between the hash -// and rclone's read could still upload drifted bytes. The window is the -// fork/exec of one rclone invocation rather than the whole walk-to-push -// span, and the scan-back fingerprint pass (#109) re-reads the landed -// object to upgrade the durability vector, catching any byte that slipped -// through before the object is treated as content-verified. -func (h *contentPusher) uploadOneObject(ctx context.Context, runID int64, d store.PathDelta) error { - src := filepath.Join(h.vol.Path, filepath.FromSlash(d.Path)) - digest, err := hashLocalFile(src) - if err != nil { - return fmt.Errorf("re-hash %s before upload: %w", src, err) - } - if !bytes.Equal(digest, d.Blake3) { - return fmt.Errorf("%w: %s now hashes to %s, indexed as %s — run `squirrel index %s` and sync again", - errContentDrift, d.Path, hex.EncodeToString(digest), hex.EncodeToString(d.Blake3), h.vol.Name) - } - hash := hex.EncodeToString(d.Blake3) - uri := h.objectURI(d.Blake3) - if err := h.rcl.copyTo(ctx, src, uri, checkersArgs(h.dest)...); err != nil { - return err - } - size, err := h.rcl.statRemote(ctx, uri, checkersArgs(h.dest)...) - if err != nil { - return fmt.Errorf("confirm object %s after upload: %w", hash, err) - } - if size != d.SizeBytes { - return fmt.Errorf("object %s landed with size %d, want %d", hash, size, d.SizeBytes) +// uploadBatch lands one batch of content objects and records each upload +// that landed, with its fingerprint when the landing already confirmed +// one. It guards the content-addressed invariant — the bytes stored under +// a hash must be the bytes that produced it: the artifact store refuses a +// source that no longer hashes to the indexed hash (errContentDrift), +// catching a size+mtime-preserving in-place edit that a metadata stat +// would pass. An upload is recorded only once the store returned its +// landing confirmed and durable, so a recorded hash is always a confirmed +// one; a crash in between lands the same bytes again on the next run. +func (h *contentPusher) uploadBatch(ctx context.Context, runID int64, batch []store.PathDelta) []artifactResult { + items := make([]artifactPut, len(batch)) + for i, d := range batch { + items[i] = artifactPut{name: h.objectName(d.Blake3), src: filepath.Join(h.vol.Path, filepath.FromSlash(d.Path)), size: d.SizeBytes, sum: d.Blake3} + } + results := h.art.putAll(ctx, runID, items) + for i, d := range batch { + res := &results[i] + if errors.Is(res.err, errContentDrift) { + res.err = fmt.Errorf("%s: %w — run `squirrel index %s` and sync again", d.Path, res.err, h.vol.Name) + } + if res.err == nil { + res.err = h.recordObject(ctx, runID, d, res.fingerprint) + } } - if err := h.store.InsertRemoteObject(ctx, store.RemoteObject{ - ContentID: d.ContentID, - Destination: h.dest.Name, - UploadedRunID: runID, - }); err != nil { - return fmt.Errorf("record upload of %s: %w", hash, err) + return results +} + +// recordObject records the upload of d's content, with the fingerprint +// its landing confirmed, if any. +func (h *contentPusher) recordObject(ctx context.Context, runID int64, d store.PathDelta, cs *remoteChecksum) error { + obj := store.RemoteObject{ContentID: d.ContentID, Destination: h.dest.Name, UploadedRunID: runID} + if cs != nil { + obj.ChecksumAlgo = sql.NullString{String: cs.Algo, Valid: true} + obj.Checksum = sql.NullString{String: cs.Value, Valid: true} + obj.VerifiedAtNs = sql.NullInt64{Int64: store.NowNs(), Valid: true} + } + if err := h.store.InsertRemoteObject(ctx, obj); err != nil { + return fmt.Errorf("record upload of %s: %w", hex.EncodeToString(d.Blake3), err) } return nil } @@ -507,20 +417,19 @@ func (h *contentPusher) uploadSegment(ctx context.Context, delta []store.PathDel if err != nil { return err } - return h.uploadBytes(ctx, body, h.segmentURI(runID), "manifest segment") + return putBytes(ctx, h.art, runID, h.segmentName(runID), body, "manifest segment") } -// objectURI addresses one content object under the destination-root -// objects/ directory, through the crypt overlay when the destination -// has one. The basename is namer.object's. -func (h *contentPusher) objectURI(contentHash []byte) string { - return remoteSubpathURI(h.dest, path.Join(ObjectsDirName, h.names().object(contentHash))) +// objectName is one content object under the destination-root objects/ +// directory. The basename is namer.object's. +func (h *contentPusher) objectName(contentHash []byte) string { + return path.Join(ObjectsDirName, h.names().object(contentHash)) } -// segmentURI addresses one run's manifest segment under the -// destination's per-volume index/ directory. The run id stays in clear: -// replaying the segments in run order is what recovers a volume without -// squirrel, and that ordering has to survive without the naming key. -func (h *contentPusher) segmentURI(runID int64) string { - return remoteSubpathURI(h.dest, path.Join(h.names().volumeDir(h.vol.Name), ManifestDirName, "run-"+strconv.FormatInt(runID, 10))) +// segmentName is one run's manifest segment under the destination's +// per-volume index/ directory. The run id stays in clear: replaying the +// segments in run order is what recovers a volume without squirrel, and +// that ordering has to survive without the naming key. +func (h *contentPusher) segmentName(runID int64) string { + return path.Join(h.names().volumeDir(h.vol.Name), ManifestDirName, "run-"+strconv.FormatInt(runID, 10)) } diff --git a/sync/content_addressed_test.go b/sync/content_addressed_test.go index e8a107f..9a9f327 100644 --- a/sync/content_addressed_test.go +++ b/sync/content_addressed_test.go @@ -228,19 +228,6 @@ password = "obscured-pw" return f } -// setupPlainContentAddressedFixture is setupContentAddressedFixture -// without the crypt block. -func setupPlainContentAddressedFixture(t *testing.T) *caFixture { - t.Helper() - return setupCAFixture(t, `[destinations.offsite] -type = "sftp" -host = "remote.invalid" -user = "u" -root = "/data" -layout = "content-addressed" -`, "/data") -} - // setupCAFixture is the destination-configurable body of // setupContentAddressedFixture. destBlock declares the `offsite` // destination; strip is the destination root the shim removes from @@ -340,7 +327,7 @@ func (f *caFixture) seedMarker(t *testing.T, volumes ...string) { // push established. func (f *caFixture) seedNamingMarker(t *testing.T) { t.Helper() - h := &contentPusher{store: f.store, rcl: f.rcl, dest: f.cfg.Destinations["offsite"]} + h := &rcloneArtifacts{store: f.store, rcl: f.rcl, dest: f.cfg.Destinations["offsite"]} if err := h.writeNamingMarker(context.Background()); err != nil { t.Fatalf("seed %s: %v", namingMarkerName, err) } diff --git a/sync/content_native_test.go b/sync/content_native_test.go new file mode 100644 index 0000000..ae3edc6 --- /dev/null +++ b/sync/content_native_test.go @@ -0,0 +1,627 @@ +package sync + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/index" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// nativeContentFixture is one volume, "pics", pushed to a content-addressed +// or packed destination squirrel writes itself, "vault": a directory on +// this machine, or one an in-process sftp server serves. dst is where the +// destination's bytes land on this machine either way. +type nativeContentFixture struct { + store *store.Store + pair Pair + src string + dst string +} + +// contentBackend is where a native content fixture's destination lives. +type contentBackend struct { + name string + settings func(t *testing.T, dst string) string +} + +var ( + localContent = contentBackend{"local", func(_ *testing.T, dst string) string { + return fmt.Sprintf("type = \"local\"\nroot = %q\n", dst) + }} + // sftpContent runs sha256sum, as an OpenSSH host does. + sftpContent = contentBackend{"sftp", func(t *testing.T, dst string) string { + return sftpSettings(t, dst, map[string]string{"sha256sum": "sha256"}) + }} + // sftpContentNoPrograms runs no programs, the cloudbox shape. + sftpContentNoPrograms = contentBackend{"sftp without programs", func(t *testing.T, dst string) string { + return sftpSettings(t, dst, nil) + }} + contentBackends = []contentBackend{localContent, sftpContent} + contentLayouts = []string{config.LayoutContentAddressed, config.LayoutPacked} +) + +// setupNativeContentFixture declares vault on b with layout; a packed one +// packs content under 8 bytes. The destination root exists, and on sftp it +// carries the volume marker. +func setupNativeContentFixture(t *testing.T, b contentBackend, layout string) *nativeContentFixture { + t.Helper() + root := t.TempDir() + f := &nativeContentFixture{src: filepath.Join(root, "src"), dst: filepath.Join(root, "vault")} + for _, d := range []string{f.src, filepath.Join(f.dst, "pics")} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + if err := volmark.Write(filepath.Join(f.dst, "pics"), volmark.Marker{Volume: "pics"}); err != nil { + t.Fatalf("seed marker: %v", err) + } + s, err := store.Open(filepath.Join(root, "test.db")) + if err != nil { + t.Fatalf("store.Open: %v", err) + } + t.Cleanup(func() { s.Close() }) + f.store = s + body := "[destinations.vault]\n" + b.settings(t, f.dst) + fmt.Sprintf("layout = %q\n", layout) + if layout == config.LayoutPacked { + body += "pack_threshold = \"8B\"\n" + } + body += "\n[volumes.pics]\npath = \"" + f.src + "\"\nsync_to = [\"vault\"]\n" + cfgPath := filepath.Join(root, "config.toml") + if err := os.WriteFile(cfgPath, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(cfgPath) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + f.pair = Pair{Volume: cfg.Volumes["pics"], Destination: cfg.Destinations["vault"]} + return f +} + +func (f *nativeContentFixture) write(t *testing.T, rel, body string) { + t.Helper() + p := filepath.Join(f.src, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func (f *nativeContentFixture) index(t *testing.T) { + t.Helper() + if _, err := index.Index(context.Background(), f.store, f.src, index.Options{Name: "pics"}); err != nil { + t.Fatalf("index: %v", err) + } +} + +// push runs one push with no rclone wrapper at all. +func (f *nativeContentFixture) push(t *testing.T, opts Options) (Report, error) { + t.Helper() + return RunPair(context.Background(), f.store, Tools{}, f.pair, opts) +} + +func (f *nativeContentFixture) mustPush(t *testing.T) Report { + t.Helper() + rep, err := f.push(t, Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return rep +} + +// pushCrashing runs one push whose transport crashes, as mode says, at the +// first call crashAt selects. +func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool, mode crashMode) (Report, error) { + t.Helper() + return f.pushVia(t, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode} + }) +} + +// pushCuttingPower runs one push that loses power at the first call +// crashAt selects, before or after it as mode says, keeping the oldest +// keep(n) of the n calls no Flush covered. +func (f *nativeContentFixture) pushCuttingPower(t *testing.T, crashAt func(transportCall) bool, mode crashMode, keep func(int) int) (Report, error) { + t.Helper() + return f.pushVia(t, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode, powerCut: true, keep: keep} + }) +} + +// oneAtATime makes the fixture's pushes land one artifact at a time, so +// their transport calls come in the same order on every push. +func (f *nativeContentFixture) oneAtATime() { f.pair.Destination.Concurrency = 1 } + +// pushVia runs one push through wrap's transport. +func (f *nativeContentFixture) pushVia(t *testing.T, wrap func(transport) transport) (Report, error) { + t.Helper() + h, err := HandlerFor(f.store, Tools{}, f.pair) + if err != nil { + t.Fatalf("HandlerFor: %v", err) + } + var art artifactStore + switch h := h.(type) { + case *contentAddressedHandler: + art = h.art + case *packedHandler: + art = h.art + } + root := art.(*transportArtifacts).destinationRoot + root.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + if err != nil { + return nil, err + } + return wrap(raw), nil + } + return h.Push(context.Background(), Options{}) +} + +func (f *nativeContentFixture) objectPath(body string) string { + return filepath.Join(f.dst, ObjectsDirName, blake3Hex(body)) +} + +func (f *nativeContentFixture) remoteObject(t *testing.T, body string) (store.RemoteObject, bool) { + t.Helper() + ctx := context.Background() + v, err := f.store.GetVolumeByName(ctx, "pics") + if err != nil { + t.Fatal(err) + } + present, err := f.store.ListPresentContent(ctx, v.ID) + if err != nil { + t.Fatal(err) + } + for _, d := range present { + if hex.EncodeToString(d.Blake3) == blake3Hex(body) { + obj, err := f.store.GetRemoteObject(ctx, d.ContentID, "vault") + return obj, err == nil + } + } + t.Fatalf("no present content holds %q", body) + return store.RemoteObject{}, false +} + +// wantFingerprint is what a native push records for body's bytes on b: the +// BLAKE3 a local read-back confirmed, or the server's sha256. +func wantFingerprint(b contentBackend, body string) (string, string) { + if b.name == localContent.name { + return store.ChecksumAlgoBlake3, blake3Hex(body) + } + sum := sha256.Sum256([]byte(body)) + return "sha256", hex.EncodeToString(sum[:]) +} + +// TestNativeContentPushWithoutRclone: both content layouts push to a local +// disk and to an sftp server with no rclone wrapper. Every artifact lands +// at its name with its bytes, records the fingerprint its landing confirmed +// — a read-back BLAKE3 locally, the server's sha256 over sftp — and the +// vector advances as fingerprint-verified. The next push clears the first +// run's staging. +func TestNativeContentPushWithoutRclone(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + f := setupNativeContentFixture(t, b, layout) + f.write(t, "a.txt", "alpha") + f.write(t, "big.txt", "a larger file") + f.index(t) + first := f.mustPush(t) + + if got, err := os.ReadFile(f.objectPath("a larger file")); err != nil || string(got) != "a larger file" { + t.Fatalf("object = %q, %v", got, err) + } + obj, ok := f.remoteObject(t, "a larger file") + algo, value := wantFingerprint(b, "a larger file") + if !ok || obj.ChecksumAlgo.String != algo || obj.Checksum.String != value || !obj.VerifiedAtNs.Valid { + t.Fatalf("remote object = %+v, want %s %s recorded at landing", obj, algo, value) + } + segment := filepath.Join(f.dst, "pics", ManifestDirName, fmt.Sprintf("run-%d", first.RunID)) + if _, err := os.Stat(segment); err != nil { + t.Fatalf("manifest segment: %v", err) + } + if layout == config.LayoutPacked { + if _, err := os.Stat(filepath.Join(f.dst, PacksDirName, fmt.Sprintf("map-%d", first.RunID))); err != nil { + t.Fatalf("placement map: %v", err) + } + if _, err := os.Stat(f.objectPath("alpha")); err == nil { + t.Fatal("content under the threshold landed as an object") + } + } + if comps := volumeComponents(t, f.store, "pics", "vault"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodFingerprint { + t.Fatalf("vector = %+v, want one fingerprint-verified component", comps) + } + + f.mustPush(t) + if _, err := os.Stat(filepath.Join(f.dst, stagingName("pics", first.RunID, ""))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the next push left the first run's staging: %v", err) + } + }) + } + } +} + +// TestNativeContentWithoutServerHash: an sftp server that runs no programs +// still takes every artifact, whole, but fingerprints nothing: the objects +// stay pending with a warning and the vector stays presence+size. +// stallingPuts holds the nth Put into staging, and every one after it, +// until release is closed. +type stallingPuts struct { + transport + n int32 + seen *atomic.Int32 + release chan struct{} +} + +func (s stallingPuts) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if strings.Contains(name, "/"+StagingDirName+"/run-") && s.seen.Add(1) >= s.n { + <-s.release + } + return s.transport.Put(ctx, name, r, mtime) +} + +// TestNativeContentStallRecordsOnlyWhatLanded: a content-addressed push +// whose transport stalls halfway through a batch records no object it did +// not land and flush, so the push after the stall clears lands the rest. +func TestNativeContentStallRecordsOnlyWhatLanded(t *testing.T) { + f := setupNativeContentFixture(t, contentBackends[0], config.LayoutContentAddressed) + f.oneAtATime() + bodies := []string{"one", "two", "three", "four", "five"} + for _, b := range bodies { + f.write(t, b+".txt", b) + } + f.index(t) + h, err := HandlerFor(f.store, Tools{}, f.pair) + if err != nil { + t.Fatal(err) + } + root := h.(*contentAddressedHandler).art.(*transportArtifacts).destinationRoot + release := make(chan struct{}) + root.stallTimeout = 50 * time.Millisecond + root.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return stallingPuts{transport: raw, n: 3, seen: new(atomic.Int32), release: release}, err + } + rep, err := h.Push(context.Background(), Options{}) + if err == nil || len(rep.RcloneResult.FailedFiles) == 0 || !strings.Contains(rep.RcloneResult.FailedFiles[0].Message, errTransportStalled.Error()) { + t.Fatalf("stalled push = %v, failures %+v; want it failed on the stall", err, rep.RcloneResult.FailedFiles) + } + for _, b := range bodies { + if _, recorded := f.remoteObject(t, b); recorded { + if _, err := os.Stat(f.objectPath(b)); err != nil { + t.Errorf("object %q is recorded but not at its name: %v", b, err) + } + } + } + close(release) + deadline := time.Now().Add(5 * time.Second) + for stalledCounter("vault").Load() > 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + f.mustPush(t) + f.checkArtifactsVouch(t) + for _, b := range bodies { + if _, recorded := f.remoteObject(t, b); !recorded { + t.Errorf("object %q not recorded after the push that followed the stall", b) + } + } +} + +func TestNativeContentWithoutServerHash(t *testing.T) { + f := setupNativeContentFixture(t, sftpContentNoPrograms, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + rep := f.mustPush(t) + if obj, ok := f.remoteObject(t, "alpha"); !ok || obj.Checksum.Valid { + t.Fatalf("remote object = %+v, want recorded with a pending fingerprint", obj) + } + if !strings.Contains(strings.Join(rep.Warnings, "\n"), "without a fingerprint") { + t.Fatalf("warnings = %v, want the pending fingerprints named", rep.Warnings) + } + if comps := volumeComponents(t, f.store, "pics", "vault"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { + t.Fatalf("vector = %+v, want one presence+size component", comps) + } +} + +// TestNativeContentAdoptsAnArtifactItAlreadyLanded: a push that crashed +// between landing an object and recording it leaves the object at its +// name. The next push finds it there, confirms its bytes, and records it +// instead of replacing it. +func TestNativeContentAdoptsAnArtifactItAlreadyLanded(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + if _, err := f.pushCrashing(t, func(c transportCall) bool { + return c.op == "rename" && strings.HasPrefix(c.to, ObjectsDirName+"/") + }, crashAfter); err == nil { + t.Fatal("the crashing push succeeded") + } + if _, err := os.Stat(f.objectPath("alpha")); err != nil { + t.Fatalf("the crash left no object: %v", err) + } + if _, ok := f.remoteObject(t, "alpha"); ok { + t.Fatal("the crashed push recorded the object") + } + + f.mustPush(t) + obj, ok := f.remoteObject(t, "alpha") + algo, value := wantFingerprint(b, "alpha") + if !ok || obj.ChecksumAlgo.String != algo || obj.Checksum.String != value { + t.Fatalf("remote object = %+v, want the landed object adopted with %s %s", obj, algo, value) + } + }) + } +} + +// TestNativeContentRefusesOtherBytesAtAnArtifactName: bytes squirrel did +// not record sitting at an object's name are never replaced: the object +// fails, the push fails before its segment, and the bytes stay. +func TestNativeContentRefusesOtherBytesAtAnArtifactName(t *testing.T) { + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + if err := os.MkdirAll(filepath.Join(f.dst, ObjectsDirName), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.objectPath("alpha"), []byte("other"), 0o644); err != nil { + t.Fatal(err) + } + rep, err := f.push(t, Options{}) + if err == nil || len(rep.RcloneResult.FailedFiles) != 1 || !strings.Contains(rep.RcloneResult.FailedFiles[0].Message, errReadBackMismatch.Error()) { + t.Fatalf("push: err=%v failed=%+v, want the object refused as other bytes", err, rep.RcloneResult.FailedFiles) + } + if got, _ := os.ReadFile(f.objectPath("alpha")); string(got) != "other" { + t.Fatalf("object = %q, want the bytes that were there left alone", got) + } + if _, ok := f.remoteObject(t, "alpha"); ok { + t.Fatal("the refused object was recorded") + } +} + +// TestNativeContentMarkerGate: a native content destination is gated on +// its volume marker, as a native mirror is, and --init writes it through +// the transport. On a local disk --init also creates a missing root. +func TestNativeContentMarkerGate(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutPacked) + bare := filepath.Join(f.dst, "pics") + if b.name == localContent.name { + bare = f.dst + } + if err := os.RemoveAll(bare); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + if _, err := f.push(t, Options{}); !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "--init") { + t.Fatalf("push without a marker = %v, want a refusal naming --init", err) + } + if rep, err := f.push(t, Options{Init: true}); err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("--init push: status=%q err=%v", rep.Status, err) + } + if err := volmark.Validate(filepath.Join(f.dst, "pics"), "pics"); err != nil { + t.Fatalf("marker after --init: %v", err) + } + }) + } +} + +// TestNativeContentDriftLeavesNothingAtTheName: a source whose bytes +// drifted from their indexed hash is refused after staging; nothing lands +// at the object's name, and the next push clears the staged copy and lands +// the honest bytes. +func TestNativeContentDriftLeavesNothingAtTheName(t *testing.T) { + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + src := filepath.Join(f.src, "a.txt") + fi, err := os.Stat(src) + if err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "ALPHA") + if err := os.Chtimes(src, fi.ModTime(), fi.ModTime()); err != nil { + t.Fatal(err) + } + rep, err := f.push(t, Options{}) + if err == nil || !strings.Contains(err.Error(), "drifting") { + t.Fatalf("push = %v, want a drift refusal", err) + } + if _, err := os.Stat(f.objectPath("alpha")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("drifted bytes reached the object name: %v", err) + } + f.write(t, "a.txt", "alpha") + if err := os.Chtimes(src, fi.ModTime(), fi.ModTime()); err != nil { + t.Fatal(err) + } + f.mustPush(t) + if got, _ := os.ReadFile(f.objectPath("alpha")); string(got) != "alpha" { + t.Fatalf("object = %q, want the honest bytes", got) + } + if _, err := os.Stat(filepath.Join(f.dst, stagingName("pics", rep.RunID, ""))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the drifted run's staging is still there: %v", err) + } +} + +// TestNativeContentRestoreWithoutRclone: both content layouts restore from +// a local disk and from an sftp server with no rclone wrapper, every byte +// re-hashed on the way down. +func TestNativeContentRestoreWithoutRclone(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + f := setupNativeContentFixture(t, b, layout) + f.write(t, "a.txt", "alpha") + f.write(t, "2024/big.txt", "a larger file") + f.index(t) + f.mustPush(t) + to := t.TempDir() + rep, err := Restore(context.Background(), f.store, nil, f.pair.Volume, f.pair.Destination, RestoreOptions{ToPath: to}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("restore: status=%q err=%v", rep.Status, err) + } + for rel, want := range map[string]string{"a.txt": "alpha", "2024/big.txt": "a larger file"} { + if got, err := os.ReadFile(filepath.Join(to, filepath.FromSlash(rel))); err != nil || string(got) != want { + t.Fatalf("%s = %q, %v; want %q", rel, got, err, want) + } + } + }) + } + } +} + +// TestNativeContentRideAlongAndRecover: a native content push rides the +// index snapshot along through the transport, and recover's discovery lists +// and fetches it without rclone. +func TestNativeContentRideAlongAndRecover(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push: err=%v snapshot=%v", err, rep.SnapshotErr) + } + ctx := context.Background() + snaps, err := DiscoverIndexSnapshots(ctx, nil, f.pair.Destination, []string{"pics"}) + if err != nil || len(snaps) != 1 || snaps[0].RunID != rep.RunID { + t.Fatalf("snapshots = %+v, %v; want run %d's", snaps, err, rep.RunID) + } + local := filepath.Join(t.TempDir(), "index.db") + if err := FetchIndexSnapshot(ctx, nil, f.pair.Destination, snaps[0], local); err != nil { + t.Fatalf("FetchIndexSnapshot: %v", err) + } + }) + } +} + +func (f *nativeContentFixture) verify(t *testing.T) RemoteVerifyReport { + t.Helper() + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil { + t.Fatalf("VerifyRemote: %v", err) + } + return rep +} + +// TestNativeContentVerifyWithoutRclone: verify re-reads a native content +// destination through the transport — BLAKE3 against the content hash or +// pack key on a local disk, the server's hash command over sftp — and +// finds an artifact changed in place or gone. +func TestNativeContentVerifyWithoutRclone(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + f := setupNativeContentFixture(t, b, layout) + f.write(t, "a.txt", "alpha") + f.write(t, "big.txt", "a larger file") + f.write(t, "gone.txt", "gone, soon") + f.index(t) + f.mustPush(t) + rep := f.verify(t) + objects, packs := 3, 0 + if layout == config.LayoutPacked { + objects, packs = 2, 1 + } + if !rep.Clean() || rep.Verified != objects || rep.PacksVerified != packs { + t.Fatalf("rep = %+v, want a clean pass re-confirming every artifact", rep) + } + + if err := os.WriteFile(f.objectPath("a larger file"), []byte("A LARGER FILE"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Remove(f.objectPath("gone, soon")); err != nil { + t.Fatal(err) + } + if layout == config.LayoutPacked { + f.flipPack(t) + } + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil || len(rep.Mismatched) != 1 || len(rep.Missing) != 1 || len(rep.PackMismatched) != packs || !rep.AlarmRaised { + t.Fatalf("rep = %+v, %v; want one object changed, one gone, every pack changed, and the alarm raised", rep, err) + } + }) + } + } +} + +// flipPack changes the first byte of every pack in place. +func (f *nativeContentFixture) flipPack(t *testing.T) { + t.Helper() + entries, err := os.ReadDir(filepath.Join(f.dst, PacksDirName)) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if strings.HasPrefix(e.Name(), packMapPrefix) { + continue + } + p := filepath.Join(f.dst, PacksDirName, e.Name()) + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + b[0] ^= 0xff + if err := os.WriteFile(p, b, 0o644); err != nil { + t.Fatal(err) + } + } +} + +// TestNativeContentVerifyWithoutAServerHash: over sftp, an artifact the +// server cannot hash this pass — it lost its command, or the row records +// another hash_algo — is neither re-confirmed nor a finding. +func TestNativeContentVerifyWithoutAServerHash(t *testing.T) { + f := setupNativeContentFixture(t, sftpContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + f.pair.Destination.HashAlgo = "sha1" + rep := f.verify(t) + if !rep.Clean() || rep.Unchecked != 1 || rep.Verified != 0 || rep.AlarmRaised { + t.Fatalf("rep = %+v, want the object left unchecked and no alarm", rep) + } +} + +// TestNativeContentVerifyRefusesAnUnmountedRoot: a native content root +// without its volume markers fails the pass instead of reporting every +// object missing. +func TestNativeContentVerifyRefusesAnUnmountedRoot(t *testing.T) { + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + entries, err := os.ReadDir(f.dst) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if err := os.RemoveAll(filepath.Join(f.dst, e.Name())); err != nil { + t.Fatal(err) + } + } + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err == nil || !strings.Contains(err.Error(), "nothing was checked") || rep.AlarmRaised { + t.Fatalf("VerifyRemote = %+v, %v; want the pass refused without an alarm", rep, err) + } +} diff --git a/sync/crash_every_call_test.go b/sync/crash_every_call_test.go new file mode 100644 index 0000000..1c55019 --- /dev/null +++ b/sync/crash_every_call_test.go @@ -0,0 +1,317 @@ +package sync + +import ( + "context" + "fmt" + "os" + "path" + "path/filepath" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +// crashModesFor is every way a call can die that leaves a different +// destination behind: a read fails the same way before or after it runs, +// a write can also land, and a Put can land part of its body. +func crashModesFor(c transportCall) []crashMode { + switch c.op { + case "stat", "list": + return []crashMode{crashBefore} + case "put": + return []crashMode{crashBefore, crashMidway, crashAfter} + default: + return []crashMode{crashBefore, crashAfter} + } +} + +var crashModeNames = map[crashMode]string{crashBefore: "before", crashAfter: "after", crashMidway: "midway"} + +// crashAtCall selects the i-th call a push makes. +func crashAtCall(i int) func(transportCall) bool { + n := -1 + return func(transportCall) bool { + n++ + return n == i + } +} + +// mirrorCrashScenario lands a first tree with one clean push, then changes +// the source and the destination so the next push takes every kind of +// step: a confirm, a write displacing its recorded version, a write +// displacing bytes squirrel never wrote, a record changed behind +// squirrel's back, a file becoming a directory and a directory becoming a +// file, a rename that changes only case, and a path deleted at the source. +func mirrorCrashScenario(t *testing.T, f *mirrorFixture) { + t.Helper() + for rel, body := range map[string]string{ + "keep.txt": "keep", "change.txt": "v1", "tampered.txt": "t1", + "swap": "file swap", "dir/x": "in dir", "gone.txt": "gone", "Case.txt": "case", + } { + f.write(t, rel, body) + } + f.index(t) + f.mustPush(t) + for _, rel := range []string{"swap", "dir", "gone.txt"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "change.txt", "v2 is longer") + f.write(t, "tampered.txt", "t2 at the source") + f.write(t, "swap/inner", "swap is a directory now") + f.write(t, "dir", "dir is a file now") + f.write(t, "new.txt", "new") + f.rename(t, "Case.txt", "case.txt") + f.index(t) + for rel, body := range map[string]string{"tampered.txt": "tampered on the destination", "new.txt": "foreign"} { + if err := os.WriteFile(f.dest(rel), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } +} + +// recordMirrorCalls runs the scenario's push once without a crash and returns +// every transport call it made. +func recordMirrorCalls(t *testing.T, b mirrorBackend, fold nameFolding) []transportCall { + t.Helper() + f := setupMirrorFixtureOn(t, b) + f.fold = fold + f.oneAtATime() + mirrorCrashScenario(t, f) + var rec *faultTransport + rep, err := f.pushVia(t, Options{}, func(tr transport) transport { + rec = &faultTransport{transport: tr} + return rec + }) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("recording push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return rec.calls +} + +// TestMirrorCrashAtEveryTransportCall: a push that dies at any one of its +// transport calls, in any way that call can die, leaves every record +// vouching for its bytes and every byte where it was; the next clean push +// then settles what the crash left and satisfies all three invariants. +// Both transports run it, on a destination that tells names apart and on +// one that folds them. +func TestMirrorCrashAtEveryTransportCall(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + t.Run(fmt.Sprintf("%s/folds=%v", b.name, fold.folds()), func(t *testing.T) { + calls := recordMirrorCalls(t, b, fold) + for i, c := range calls { + for _, mode := range crashModesFor(c) { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), crashModeNames[mode]), func(t *testing.T) { + t.Parallel() + runMirrorCrashAt(t, b, fold, func(f *mirrorFixture) (Report, error) { + return f.pushCrashing(t, crashAtCall(i), mode) + }) + }) + } + } + }) + } + } +} + +// powerCutModes are the two moments a power cut can strike around a call: +// before it, after every record written since the call before, and after +// it. +var powerCutModes = []crashMode{crashBefore, crashAfter} + +// powerCut is one way a power cut can leave the disk: every call no Flush +// covered taken back, or every name kept but none of those calls' bytes. +type powerCut struct { + name string + mode crashMode + keep func(n int) int +} + +var powerCuts = []powerCut{ + {"before", crashBefore, nil}, + {"after", crashAfter, nil}, + {"names-kept", crashBefore, func(n int) int { return n }}, +} + +// TestMirrorPowerCutAtEveryTransportCall: a push that loses power around +// any one of its transport calls, taking back every call no Flush covered +// or keeping their names without their bytes, still leaves every record +// vouching for its bytes, because no record claims bytes before the flush +// that covers them and no staged file is renamed before its bytes are +// flushed; the next clean push settles the rest. +func TestMirrorPowerCutAtEveryTransportCall(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + t.Run(fmt.Sprintf("%s/folds=%v", b.name, fold.folds()), func(t *testing.T) { + for i, c := range recordMirrorCalls(t, b, fold) { + for _, cut := range powerCuts { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), cut.name), func(t *testing.T) { + t.Parallel() + runMirrorCrashAt(t, b, fold, func(f *mirrorFixture) (Report, error) { + return f.pushCuttingPower(t, crashAtCall(i), cut.mode, cut.keep) + }) + }) + } + } + }) + } + } +} + +func runMirrorCrashAt(t *testing.T, b mirrorBackend, fold nameFolding, crash func(*mirrorFixture) (Report, error)) { + f := setupMirrorFixtureOn(t, b) + f.fold = fold + f.oneAtATime() + mirrorCrashScenario(t, f) + before := f.contentHashes(t) + if rep, err := crash(f); !crashedOn(rep, err) { + t.Fatalf("crashing push: status=%q err=%v failures=%+v, want the injected crash", rep.Status, err, rep.RcloneResult.FailedFiles) + } + f.checkRecordsVouch(t, "tampered.txt") + f.checkOnlyGrew(t, before) + + clean := f.mustPush(t) + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) + for rel, want := range map[string]string{ + "keep.txt": "keep", "change.txt": "v2 is longer", "tampered.txt": "t2 at the source", + "swap/inner": "swap is a directory now", "dir": "dir is a file now", "new.txt": "new", + "case.txt": "case", "gone.txt": "gone", + } { + if got := f.readDest(t, rel); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } +} + +// contentCrashScenario lands a first tree on a content destination with +// one clean push, then adds, changes and deletes files so the next push +// uploads objects and, on a packed destination, a pack and its map. +func contentCrashScenario(t *testing.T, f *nativeContentFixture) { + t.Helper() + f.write(t, "a.txt", "alpha") + f.write(t, "big.txt", "a larger file") + f.write(t, "gone.txt", "gone, soon") + f.index(t) + f.mustPush(t) + if err := os.Remove(filepath.Join(f.src, "gone.txt")); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "ALPHA") + f.write(t, "b.txt", "beta") + f.write(t, "2024/big.txt", "another larger file") + f.index(t) +} + +func recordContentCalls(t *testing.T, b contentBackend, layout string) []transportCall { + t.Helper() + f := setupNativeContentFixture(t, b, layout) + f.oneAtATime() + contentCrashScenario(t, f) + var calls []transportCall + rep, err := f.pushCrashing(t, func(c transportCall) bool { + calls = append(calls, c) + return false + }, crashBefore) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("recording push: status=%q err=%v", rep.Status, err) + } + return calls +} + +// TestNativeContentCrashAtEveryTransportCall: a content-addressed or +// packed push that dies at any one of its transport calls leaves every +// recorded artifact at its name with its bytes and every byte where it +// was. The next clean push lands the rest, a verify pass re-confirms every +// artifact, and a restore returns the volume. +func TestNativeContentCrashAtEveryTransportCall(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + for i, c := range recordContentCalls(t, b, layout) { + for _, mode := range crashModesFor(c) { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), crashModeNames[mode]), func(t *testing.T) { + t.Parallel() + runContentCrashAt(t, b, layout, func(f *nativeContentFixture) (Report, error) { + return f.pushCrashing(t, crashAtCall(i), mode) + }) + }) + } + } + }) + } + } +} + +// TestNativeContentPowerCutAtEveryTransportCall: a content push that loses +// power around any one of its transport calls, taking back every call no +// Flush covered or keeping their names without their bytes, records no +// artifact the destination does not hold; the next clean push lands the +// rest. +func TestNativeContentPowerCutAtEveryTransportCall(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + for i, c := range recordContentCalls(t, b, layout) { + for _, cut := range powerCuts { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), cut.name), func(t *testing.T) { + t.Parallel() + runContentCrashAt(t, b, layout, func(f *nativeContentFixture) (Report, error) { + return f.pushCuttingPower(t, crashAtCall(i), cut.mode, cut.keep) + }) + }) + } + } + }) + } + } +} + +func runContentCrashAt(t *testing.T, b contentBackend, layout string, crash func(*nativeContentFixture) (Report, error)) { + f := setupNativeContentFixture(t, b, layout) + f.oneAtATime() + contentCrashScenario(t, f) + before := hashesOutsideStaging(t, f.dst) + if rep, err := crash(f); !crashedOn(rep, err) { + t.Fatalf("crashing push: status=%q err=%v failures=%+v, want the injected crash", rep.Status, err, rep.RcloneResult.FailedFiles) + } + f.checkArtifactsVouch(t) + checkStillHeld(t, before, hashesOutsideStaging(t, f.dst)) + + f.mustPush(t) + f.checkArtifactsVouch(t) + checkStillHeld(t, before, hashesOutsideStaging(t, f.dst)) + to := t.TempDir() + rep, err := Restore(context.Background(), f.store, nil, f.pair.Volume, f.pair.Destination, RestoreOptions{ToPath: to}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("restore: status=%q err=%v", rep.Status, err) + } + for rel, want := range map[string]string{"a.txt": "ALPHA", "b.txt": "beta", "big.txt": "a larger file", "2024/big.txt": "another larger file"} { + if got, err := os.ReadFile(filepath.Join(to, filepath.FromSlash(rel))); err != nil || string(got) != want { + t.Errorf("restored %s = %q, %v; want %q", rel, got, err, want) + } + } +} + +// checkArtifactsVouch asserts that every artifact squirrel recorded on the +// destination is at its name with the bytes recorded: a verify pass +// re-confirms each one and finds nothing gone or changed. +func (f *nativeContentFixture) checkArtifactsVouch(t *testing.T) { + t.Helper() + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil || !rep.Clean() || rep.Unchecked != 0 { + t.Fatalf("verify = %+v, %v; want every recorded artifact re-confirmed", rep, err) + } +} + +// checkStillHeld asserts that every content in before is still in after. +func checkStillHeld(t *testing.T, before, after map[string]bool) { + t.Helper() + for h := range before { + if !after[h] { + t.Errorf("content %s left the destination", h) + } + } +} diff --git a/sync/destination_marker.go b/sync/destination_marker.go new file mode 100644 index 0000000..228d870 --- /dev/null +++ b/sync/destination_marker.go @@ -0,0 +1,162 @@ +package sync + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "time" + + "github.com/mbertschler/squirrel/volmark" +) + +// maxMarkerBytes bounds how much of a destination's marker squirrel reads. +const maxMarkerBytes = 64 << 10 + +// ensureMarker is a native destination's gate against a wrong or unmounted +// root: the destination's /.squirrel-volume must name this volume. +// A missing marker is written only under init, and a marker naming another +// volume, or one that does not parse, is always refused and never +// overwritten. A local root that does not exist yet is created under init, +// so a first push can land on an empty disk, and refused like a missing +// marker otherwise. +func (h *destinationRoot) ensureMarker(ctx context.Context, init bool) error { + if err := h.ensureLocalRoot(ctx, init); err != nil { + return err + } + tr, err := h.guarded(ctx, nameGuard{volumeDir: h.volumeDir, bootstrap: init}) + if err != nil { + return err + } + name := path.Join(h.volumeDir, volmark.MarkerName) + data, err := readSmallFile(ctx, tr, name, maxMarkerBytes) + switch { + case err == nil: + return h.checkMarker(name, data) + case !errors.Is(err, fs.ErrNotExist): + return fmt.Errorf("destination %q: read %s: %w", h.dest.Name, name, err) + case !init: + return fmt.Errorf("destination %q has no %s at %s — %s: %w", h.dest.Name, volmark.MarkerName, h.where(name), h.bootstrapHint(ctx), ErrRefused) + } + return h.writeMarker(ctx, tr, name) +} + +func (h *destinationRoot) ensureLocalRoot(ctx context.Context, init bool) error { + if h.dest.Type != "local" { + return nil + } + _, err := os.Stat(h.dest.Root) + switch { + case !errors.Is(err, fs.ErrNotExist): + return nil + case init: + if err := os.MkdirAll(h.dest.Root, 0o755); err != nil { + return fmt.Errorf("destination %q: create root %s: %w", h.dest.Name, h.dest.Root, err) + } + return nil + } + return fmt.Errorf("destination %q has no root at %s — %s: %w", h.dest.Name, h.dest.Root, h.bootstrapHint(ctx), ErrRefused) +} + +// bootstrapHint is what a refusal over a missing root or marker asks for. +// A volume that synced to the destination before points at an unmounted +// disk or a moved root, not at --init, which would bootstrap a new, empty +// destination in its place. +func (h *destinationRoot) bootstrapHint(ctx context.Context) string { + if h.volumeSyncedBefore(ctx) { + return fmt.Sprintf("volume %q has synced to it before, so the disk is most likely not mounted or the root moved; mount it and sync again (--init is only for a new, empty destination)", h.volumeDir) + } + return "re-run with --init to bootstrap (refusing in case the root is a typo or the disk is not mounted)" +} + +func (h *destinationRoot) volumeSyncedBefore(ctx context.Context) bool { + v, err := h.store.GetVolumeByName(ctx, h.volumeDir) + if err != nil { + return false + } + _, err = h.store.LatestSuccessfulSyncRun(ctx, v.ID, h.dest.Name) + return err == nil +} + +func (h *destinationRoot) checkMarker(name string, data []byte) error { + m, err := volmark.Parse(data) + if err != nil { + return fmt.Errorf("destination %q: %w at %s: %w", h.dest.Name, err, h.where(name), ErrRefused) + } + if m.Volume != h.volumeDir { + return fmt.Errorf("destination %q: %s at %s names volume %q, want %q (refusing to sync over a different volume's tree): %w", + h.dest.Name, volmark.MarkerName, h.where(name), m.Volume, h.volumeDir, ErrRefused) + } + return nil +} + +// writeMarker stages the marker, then renames it onto name, so a write +// that fails halfway never leaves a marker that does not parse; its bytes +// are flushed before the rename and the rename before it returns. A copy +// an earlier --init left staged is cleared first. +func (h *destinationRoot) writeMarker(ctx context.Context, tr transport, name string) error { + m, err := selfMarker(ctx, h.store, h.volumeDir) + if err != nil { + return fmt.Errorf("destination %q: %w", h.dest.Name, err) + } + data, err := volmark.Marshal(m) + if err != nil { + return fmt.Errorf("destination %q: %w", h.dest.Name, err) + } + staged := markerStagingName(h.volumeDir) + if err := tr.Remove(ctx, staged); err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("destination %q: clear the staged marker %s: %w", h.dest.Name, h.where(staged), err) + } + if err := tr.Put(ctx, staged, bytes.NewReader(data), time.Now()); err != nil { + return fmt.Errorf("destination %q: write %s: %w", h.dest.Name, h.where(staged), err) + } + if err := landStaged(ctx, tr, staged, name); err != nil { + return fmt.Errorf("destination %q: write %s: %w", h.dest.Name, h.where(name), err) + } + return nil +} + +// landStaged renames a staged file onto name, flushing its bytes before +// the rename and the rename after it, so neither a crash nor a power cut +// leaves name holding anything but the whole file. +func landStaged(ctx context.Context, tr transport, staged, name string) error { + if err := tr.Flush(ctx); err != nil { + return err + } + if err := tr.Rename(ctx, staged, name); err != nil { + return err + } + return tr.Flush(ctx) +} + +// where names a destination-relative name for a message: the path on a +// local disk, host:path on an sftp server. +func (h *destinationRoot) where(name string) string { + full := path.Join(h.dest.Root, name) + if h.dest.Type == "sftp" { + return h.dest.Params["host"] + ":" + full + } + return full +} + +// readSmallFile reads the whole regular file at name, refusing one larger +// than limit. +func readSmallFile(ctx context.Context, tr transport, name string, limit int64) ([]byte, error) { + rc, err := tr.Get(ctx, name) + if err != nil { + return nil, err + } + defer func() { _ = rc.Close() }() + data, err := io.ReadAll(io.LimitReader(ctxReader{ctx: ctx, r: rc}, limit+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, fmt.Errorf("%s is larger than %d bytes", name, limit) + } + return data, nil +} diff --git a/sync/destination_root.go b/sync/destination_root.go new file mode 100644 index 0000000..e0aa2d0 --- /dev/null +++ b/sync/destination_root.go @@ -0,0 +1,172 @@ +package sync + +import ( + "context" + "database/sql" + "errors" + "fmt" + "io/fs" + "path" + "strconv" + "strings" + "sync/atomic" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// destinationRoot is a native destination's root for one push: opened on +// first use, closed when the push returns, and handed to a layout only +// behind a name guard and bounded by progress. +type destinationRoot struct { + store *store.Store + dest *config.Destination + volumeDir string // the volume's directory under the root + // openTransport opens the destination root; tests wrap it to inject + // faults. + openTransport func(context.Context, *config.Destination) (transport, error) + // stallTimeout bounds every transport call by progress. + stallTimeout time.Duration + // unflushed counts the bytes put since the last Flush, which the + // Flush is allowed the time to write. + unflushed atomic.Int64 + + raw transport // opened on first use, closed by close +} + +func newDestinationRoot(s *store.Store, dest *config.Destination, volumeDir string) *destinationRoot { + return &destinationRoot{store: s, dest: dest, volumeDir: volumeDir, openTransport: openDestinationTransport, stallTimeout: DefaultStallTimeout} +} + +// guarded is the destination root behind guard, bounded by progress. +func (h *destinationRoot) guarded(ctx context.Context, guard nameGuard) (transport, error) { + if h.raw == nil { + raw, err := h.openTransport(ctx, h.dest) + if err != nil { + return nil, err + } + h.raw = raw + } + return stallTransport{ + transport: guardedTransport{transport: h.raw, guard: guard}, + timeout: h.stallTimeout, + stalled: stalledCounter(h.dest.Name), + unflushed: &h.unflushed, + }, nil +} + +func (h *destinationRoot) close() { + if h.raw != nil { + _ = h.raw.Close() + h.raw = nil + } +} + +// runFinished reports whether runID has ended, so its staging may be +// removed. A run squirrel cannot look up is left alone. +func (h *destinationRoot) runFinished(runID int64) bool { + r, err := h.store.GetRun(context.Background(), runID) + return err == nil && r.Status != store.RunStatusRunning +} + +// clearFinishedStaging removes what finished runs left in staging: +// partial files from a crash, and a drifted source's staged copy. +// Anything in staging squirrel did not name, a run directory of a run the +// index does not know included, is reported and left alone. +func (h *destinationRoot) clearFinishedStaging(ctx context.Context, rep *Report, tr transport) error { + dir := path.Join(h.volumeDir, StagingDirName) + runs, err := tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("list %s: %w", dir, err) + } + names := entryNames(runs) + for _, e := range runs { + if e.name == markerStagingBase || isFoldProbe(e.name) || appleDouble(e.name, names) { + continue + } + runID, ok := stagingRunID(e) + if !ok { + h.warnForeignStaging(rep, path.Join(dir, e.name)) + continue + } + r, err := h.store.GetRun(ctx, runID) + if errors.Is(err, sql.ErrNoRows) { + h.warnForeignStaging(rep, path.Join(dir, e.name)) + continue + } + if err != nil { + return fmt.Errorf("look up the run of %s: %w", path.Join(dir, e.name), err) + } + if r.Status == store.RunStatusRunning { + continue + } + if err := h.clearStagingRun(ctx, rep, tr, path.Join(dir, e.name)); err != nil { + return err + } + } + return nil +} + +// clearStagingRun removes a finished run's staged copies, then the run's +// staging directory once nothing else is left in it. An AppleDouble +// companion goes with its staged copy; one the system left behind is +// reported like anything else squirrel did not write. +func (h *destinationRoot) clearStagingRun(ctx context.Context, rep *Report, tr transport, runDir string) error { + entries, err := tr.List(ctx, runDir) + if err != nil { + return fmt.Errorf("list %s: %w", runDir, err) + } + foreign := false + names := entryNames(entries) + for _, e := range entries { + name := path.Join(runDir, e.name) + switch { + case appleDouble(e.name, names): + case e.kind != kindFile || !isStagingKey(e.name): + foreign = true + h.warnForeignStaging(rep, name) + default: + if err := tr.Remove(ctx, name); err != nil { + return fmt.Errorf("remove finished staging %s: %w", name, err) + } + } + } + if foreign { + return nil + } + left, err := tr.List(ctx, runDir) + if err != nil { + return fmt.Errorf("list %s: %w", runDir, err) + } + for _, e := range left { + h.warnForeignStaging(rep, path.Join(runDir, e.name)) + } + if len(left) > 0 { + return nil + } + if err := tr.Remove(ctx, runDir); err != nil { + return fmt.Errorf("remove finished staging %s: %w", runDir, err) + } + return nil +} + +// stagingRunID reads the run id of a staging run directory, run-. +func stagingRunID(e entry) (int64, bool) { + idText, ok := strings.CutPrefix(e.name, "run-") + if !ok || e.kind != kindDir { + return 0, false + } + id, err := strconv.ParseInt(idText, 10, 64) + if err != nil || id <= 0 || strconv.FormatInt(id, 10) != idText { + return 0, false + } + return id, true +} + +func (h *destinationRoot) warnForeignStaging(rep *Report, name string) { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %s is in squirrel's staging but squirrel did not write it; it is left alone", h.dest.Name, name)) +} diff --git a/sync/fingerprint.go b/sync/fingerprint.go index 838fdb3..0638f68 100644 --- a/sync/fingerprint.go +++ b/sync/fingerprint.go @@ -105,13 +105,17 @@ func algoHashType(algo string) string { return algo } -// checkersArgs renders dest's optional concurrent-checkers cap as rclone -// argv. -func checkersArgs(dest *config.Destination) []string { - if dest.Checkers <= 0 { - return nil +// concurrencyArgs renders dest's optional caps on rclone's concurrent +// checkers and transfers as rclone argv. +func concurrencyArgs(dest *config.Destination) []string { + var args []string + if dest.Checkers > 0 { + args = append(args, "--checkers", strconv.Itoa(dest.Checkers)) } - return []string{"--checkers", strconv.Itoa(dest.Checkers)} + if dest.Concurrency > 0 { + args = append(args, "--transfers", strconv.Itoa(dest.Concurrency)) + } + return args } // underlyingDirURI addresses a destination-root directory (objects/ or diff --git a/sync/fingerprint_test.go b/sync/fingerprint_test.go index d44c1bd..3fef160 100644 --- a/sync/fingerprint_test.go +++ b/sync/fingerprint_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "os" + "slices" "strings" "testing" @@ -394,3 +395,23 @@ func TestListedNameCryptSuffix(t *testing.T) { t.Errorf("plain remote name = %q, want abc (untouched)", got) } } + +// TestConcurrencyArgs: a destination rclone writes passes checkers and +// concurrency to rclone as --checkers and --transfers, and neither when +// unset, leaving rclone's defaults. +func TestConcurrencyArgs(t *testing.T) { + cases := []struct { + dest config.Destination + want []string + }{ + {config.Destination{}, nil}, + {config.Destination{Checkers: 2}, []string{"--checkers", "2"}}, + {config.Destination{Concurrency: 6}, []string{"--transfers", "6"}}, + {config.Destination{Checkers: 2, Concurrency: 6}, []string{"--checkers", "2", "--transfers", "6"}}, + } + for _, c := range cases { + if got := concurrencyArgs(&c.dest); !slices.Equal(got, c.want) { + t.Errorf("concurrencyArgs(%+v) = %v, want %v", c.dest, got, c.want) + } + } +} diff --git a/sync/handler.go b/sync/handler.go index 803d61b..62ce018 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io/fs" "path/filepath" "github.com/mbertschler/squirrel/config" @@ -125,15 +126,19 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } return &kopiaHandler{store: s, kopia: tools.Kopia, vol: p.Volume, dest: p.Destination}, nil case p.Destination.Layout == config.LayoutPacked: - if tools.Rclone == nil { - return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) + pusher, err := contentPusherFor(s, tools, p) + if err != nil { + return nil, err } - return &packedHandler{contentPusher{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination}}, nil + return &packedHandler{pusher}, nil case p.Destination.Layout == config.LayoutContentAddressed: - if tools.Rclone == nil { - return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) + pusher, err := contentPusherFor(s, tools, p) + if err != nil { + return nil, err } - return &contentAddressedHandler{contentPusher{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination}}, nil + return &contentAddressedHandler{pusher}, nil + case p.Destination.NativeMirror(): + return &mirrorHandler{destinationRoot: newDestinationRoot(s, p.Destination, p.Volume.Name), vol: p.Volume}, nil default: if tools.Rclone == nil { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) @@ -142,6 +147,48 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } } +// contentPusherFor is a content layout's push: through squirrel's own +// transport onto a native destination, through rclone onto any other. +func contentPusherFor(s *store.Store, tools Tools, p Pair) (contentPusher, error) { + pusher := contentPusher{store: s, vol: p.Volume, dest: p.Destination} + switch { + case p.Destination.Native(): + pusher.art = &transportArtifacts{destinationRoot: newDestinationRoot(s, p.Destination, p.Volume.Name)} + case tools.Rclone == nil: + return contentPusher{}, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) + default: + pusher.art = &rcloneArtifacts{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination} + } + return pusher, nil +} + +// openDestinationTransport opens a native destination's root: a directory +// on this machine, or on an sftp server. +func openDestinationTransport(ctx context.Context, dest *config.Destination) (transport, error) { + if dest.Type == "sftp" { + return dialSFTP(ctx, dest) + } + return openLocalTransport(dest.Root) +} + +// openReadOnly opens a native destination's root for reading alone: the name +// guard, held by no run, refuses every move and removal, and every call is +// bounded by progress. +func openReadOnly(ctx context.Context, dest *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, dest) + if dest.Type == "local" && errors.Is(err, fs.ErrNotExist) { + return nil, fmt.Errorf("destination %q has no root at %s — the disk may not be mounted, or the root is wrong: %w", dest.Name, dest.Root, err) + } + if err != nil { + return nil, err + } + return stallTransport{ + transport: guardedTransport{transport: raw}, + timeout: DefaultStallTimeout, + stalled: stalledCounter(dest.Name), + }, nil +} + // rcloneHandler pushes to an rclone-backed bucket destination via Sync. type rcloneHandler struct { store *store.Store diff --git a/sync/handler_test.go b/sync/handler_test.go index 02c4af8..1befa02 100644 --- a/sync/handler_test.go +++ b/sync/handler_test.go @@ -9,7 +9,10 @@ import ( func TestHandlerForDispatch(t *testing.T) { vol := &config.Volume{Name: "pics", Path: "/tmp/pics"} - bucket := &config.Destination{Name: "scratch", Type: "local", Root: "/tmp/dst"} + bucket := &config.Destination{Name: "offsite", Type: "s3", Root: "/data"} + usb := &config.Destination{Name: "usb", Type: "local", Root: "/tmp/dst"} + box := &config.Destination{Name: "box", Type: "sftp", Root: "/data"} + cryptBox := &config.Destination{Name: "box", Type: "sftp", Root: "/data", Crypt: &config.Crypt{Password: "pw"}} node := &config.Node{Name: "nas"} tools := Tools{Rclone: &Rclone{Binary: "rclone"}} @@ -17,8 +20,33 @@ func TestHandlerForDispatch(t *testing.T) { if err != nil { t.Fatalf("bucket pair: %v", err) } - if _, ok := h.(*rcloneHandler); !ok || h.TargetName() != "scratch" { - t.Fatalf("bucket pair resolved to %T (%q), want *rcloneHandler scratch", h, h.TargetName()) + if _, ok := h.(*rcloneHandler); !ok || h.TargetName() != "offsite" { + t.Fatalf("bucket pair resolved to %T (%q), want *rcloneHandler offsite", h, h.TargetName()) + } + + // A local mirror is native, and needs no rclone wrapper. + h, err = HandlerFor(nil, Tools{}, Pair{Volume: vol, Destination: usb}) + if err != nil { + t.Fatalf("local mirror pair: %v", err) + } + if _, ok := h.(*mirrorHandler); !ok || h.TargetName() != "usb" { + t.Fatalf("local mirror pair resolved to %T (%q), want *mirrorHandler usb", h, h.TargetName()) + } + + // So is a plain sftp mirror; an encrypted one stays on rclone. + h, err = HandlerFor(nil, Tools{}, Pair{Volume: vol, Destination: box}) + if err != nil { + t.Fatalf("sftp mirror pair: %v", err) + } + if _, ok := h.(*mirrorHandler); !ok { + t.Fatalf("sftp mirror pair resolved to %T, want *mirrorHandler", h) + } + h, err = HandlerFor(nil, tools, Pair{Volume: vol, Destination: cryptBox}) + if err != nil { + t.Fatalf("crypt sftp mirror pair: %v", err) + } + if _, ok := h.(*rcloneHandler); !ok { + t.Fatalf("crypt sftp mirror pair resolved to %T, want *rcloneHandler", h) } h, err = HandlerFor(nil, tools, Pair{Volume: vol, Node: node}) diff --git a/sync/kopia.go b/sync/kopia.go index 15d4d64..4853a4b 100644 --- a/sync/kopia.go +++ b/sync/kopia.go @@ -221,9 +221,9 @@ func (h *kopiaHandler) Push(ctx context.Context, opts Options) (Report, error) { err = h.snapshotAndVerify(ctx, &rep, opts.Init) finishHandlerRun(ctx, h.store, &rep, err) // Local index snapshot only: the repository is kopia's own format, - // so the rclone ride-along stays out of it (dest=nil, mirroring the - // peer flow). - opts.Snapshot.afterSync(ctx, &rep, h.vol, nil) + // so the ride-along stays out of it (no shelf, mirroring the peer + // flow). + opts.Snapshot.afterSync(ctx, &rep, nil) return rep, err } diff --git a/sync/mirror.go b/sync/mirror.go new file mode 100644 index 0000000..56379b5 --- /dev/null +++ b/sync/mirror.go @@ -0,0 +1,228 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "path" + "slices" + "strconv" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/runevents" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// mirrorHandler pushes a volume to a native mirror: the volume's tree at +// //, written through a transport instead of rclone. +// It plans from the index like the content layouts, writes each changed +// path through .squirrel-staging/, moves whatever the path held into +// .squirrel-history/run-/ first, and records every version it wrote +// in remote_paths. Each run leaves a receipt, the same manifest segment the +// content layouts write, at /.squirrel-index/run-. +type mirrorHandler struct { + *destinationRoot + vol *config.Volume + progress func(runevents.Progress) // this push's Options.Progress +} + +func (h *mirrorHandler) TargetName() string { return h.dest.Name } + +func (h *mirrorHandler) sealed() {} + +func (h *mirrorHandler) Push(ctx context.Context, opts Options) (Report, error) { + rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} + rep.Verification.Method = VerifyMethodPresenceSize + if opts.Shallow { + return rep, fmt.Errorf("destination %q is a native mirror: a push already decides from squirrel's records, confirms each planned path's size and mtime, and moves whatever is there aside before writing, so --shallow has nothing to switch off", h.dest.Name) + } + if n := stalledCounter(h.dest.Name).Load(); n > 0 { + return rep, fmt.Errorf("destination %q: %d transport call(s) an earlier push gave up on have not returned — the disk or server may be hung; wait, or restart squirrel once it is reachable again", h.dest.Name, n) + } + h.progress = opts.Progress + defer h.close() + return pushThrough(ctx, pushTarget{store: h.store, vol: h.vol, dest: h.dest}, h, opts) +} + +// root is the destination root as a layout may hold it: guarded, so only +// runID's own moves pass (none when runID is 0), and bounded by progress. +func (h *mirrorHandler) root(ctx context.Context, runID int64) (transport, error) { + return h.guarded(ctx, nameGuard{volumeDir: h.vol.Name, runID: runID, finished: h.runFinished}) +} + +// markers gates the push on the per-volume .squirrel-volume marker, the +// guard against pushing to an unmounted disk or a mistyped root. A refusal +// is recorded as its own refused run, so a disk that stays unplugged shows +// up in `squirrel runs` and the TUI. A dry run skips the gate: it writes +// nothing. +func (h *mirrorHandler) markers(ctx context.Context, rep *Report, volumeID int64, opts Options) error { + if opts.DryRun { + return nil + } + merr := h.ensureMarker(ctx, opts.Init) + if merr == nil { + return nil + } + _, err := recordSyncRefusal(ctx, h.store, volumeID, h.dest.Name, rep, merr) + return err +} + +// landed reports whether runID left its receipt at the destination. +func (h *mirrorHandler) landed(ctx context.Context, runID int64) (bool, error) { + tr, err := h.root(ctx, 0) + if err != nil { + return false, err + } + e, err := tr.Stat(ctx, h.receiptName(runID)) + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir) { + return false, nil + } + if err != nil { + return false, err + } + return e.kind == kindFile, nil +} + +// rootEmpty reports whether the destination root holds no file beyond +// the volume markers. +func (h *mirrorHandler) rootEmpty(ctx context.Context) (bool, error) { + tr, err := h.root(ctx, 0) + if err != nil { + return false, err + } + return treeEmpty(ctx, tr, ".") +} + +// treeEmpty reports whether dir holds no file beyond volume markers, +// walking it until the first one. The directories in skip are not walked. +func treeEmpty(ctx context.Context, tr transport, dir string, skip ...string) (bool, error) { + entries, err := tr.List(ctx, dir) + if err != nil { + return false, err + } + names := entryNames(entries) + for _, e := range entries { + switch { + case appleDouble(e.name, names): + case e.kind == kindDir && slices.Contains(skip, path.Join(dir, e.name)): + case e.kind == kindDir: + empty, err := treeEmpty(ctx, tr, path.Join(dir, e.name), skip...) + if err != nil || !empty { + return false, err + } + case e.kind == kindFile && e.name == volmark.MarkerName: + default: + return false, nil + } + } + return true, nil +} + +// firstPush refuses to start a volume's mirror over a volume directory +// that already holds files squirrel has no record of writing — a tree +// rclone wrote, another layout's, or a native mirror whose index is gone: +// a native mirror adopts no tree. A first push that crashed left records, +// so its retry passes. +func (h *mirrorHandler) firstPush(ctx context.Context, volumeID int64) error { + recorded, err := h.store.VolumeHasRemotePaths(ctx, h.dest.Name, volumeID) + if err != nil || recorded { + return err + } + tr, err := h.root(ctx, 0) + if err != nil { + return err + } + empty, err := treeEmpty(ctx, tr, h.vol.Name, path.Join(h.vol.Name, StagingDirName)) + if errors.Is(err, fs.ErrNotExist) || empty { + return nil + } + if err != nil { + return fmt.Errorf("destination %q: check whether %s/ is empty: %w", h.dest.Name, h.vol.Name, err) + } + return fmt.Errorf("destination %q: %s/ already holds files, but squirrel has no record of syncing volume %q there; a native mirror does not adopt a tree it did not record writing: if squirrel wrote it, recover this index from it with `squirrel recover --from %s`; otherwise point the destination at a fresh root, or empty %s/ apart from its %s: %w", + h.dest.Name, h.vol.Name, h.vol.Name, h.dest.Name, h.vol.Name, volmark.MarkerName, ErrRefused) +} + +func (h *mirrorHandler) foreignHistory(runID int64) error { + return fmt.Errorf("destination %q: the last successful sync (run %d) left no receipt at %s, so the root holds a tree this mirror did not write (by rclone, or another layout) or was emptied while squirrel still records uploads to it; a native mirror does not adopt an existing tree: point the destination at a fresh or emptied root, and after emptying it run `squirrel destination reset %s`: %w", h.dest.Name, runID, h.receiptName(runID), h.dest.Name, ErrRefused) +} + +// seal writes the run's receipt, the manifest segment of its delta, +// confirms it landed at its size, and flushes it: the run succeeds only on +// a receipt a power cut cannot take back. +func (h *mirrorHandler) seal(ctx context.Context, _ *Report, runID int64, p pushPlan, _ *mirrorOps) error { + body, err := encodeManifestSegment(p.delta) + if err != nil { + return err + } + tr, err := h.root(ctx, runID) + if err != nil { + return err + } + name := h.receiptName(runID) + if err := tr.Put(ctx, name, bytes.NewReader(body), time.Now()); err != nil { + return fmt.Errorf("write receipt %s: %w", name, err) + } + e, err := tr.Stat(ctx, name) + if err != nil { + return fmt.Errorf("confirm receipt %s: %w", name, err) + } + if e.size != int64(len(body)) { + return fmt.Errorf("receipt %s landed with size %d, want %d", name, e.size, len(body)) + } + if err := tr.Flush(ctx); err != nil { + return fmt.Errorf("flush receipt %s: %w", name, err) + } + return nil +} + +// advanceMethod is fingerprint-verified once every present content of the +// volume has a copy on the destination whose read-back confirmed its +// BLAKE3 (a local disk), and presence+size otherwise: the push hashed +// every path's bytes as they streamed out and confirmed each landed at its +// size, and an sftp mirror stays there. +func (h *mirrorHandler) advanceMethod(ctx context.Context, _ *Report, p pushPlan) (string, error) { + if len(p.advance) == 0 { + return store.VerifyMethodPresenceSize, nil + } + pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, p.volumeID, h.dest.Name) + if err != nil { + return "", err + } + if pending == 0 { + return store.VerifyMethodFingerprint, nil + } + return store.VerifyMethodPresenceSize, nil +} + +// shelf is the mirror's /.squirrel-index/, reached through runID's +// guarded transport. +func (h *mirrorHandler) shelf(runID int64) snapshotShelf { + return transportShelf{ + open: func(ctx context.Context) (transport, error) { return h.root(ctx, runID) }, + volume: h.vol.Name, + runID: runID, + } +} + +func (h *mirrorHandler) receiptName(runID int64) string { + return path.Join(h.vol.Name, IndexDirName, "run-"+strconv.FormatInt(runID, 10)) +} + +// liveName is where a volume-relative path lives on the destination. +func (h *mirrorHandler) liveName(rel string) string { return path.Join(h.vol.Name, rel) } + +// stagingKey names a path's staging file: the lowercase hex BLAKE3 of the +// volume-relative path, unique per path and unchanged by a destination +// that folds case. +func stagingKey(rel string) string { + sum := blake3.Sum256([]byte(rel)) + return hex.EncodeToString(sum[:]) +} diff --git a/sync/mirror_first_push_test.go b/sync/mirror_first_push_test.go new file mode 100644 index 0000000..edd7e95 --- /dev/null +++ b/sync/mirror_first_push_test.go @@ -0,0 +1,225 @@ +package sync + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// TestMirrorRefusesATreeItHasNoRecordOf: a volume's first push to a native +// mirror refuses a volume directory that already holds files squirrel has +// no record of writing — a tree rclone wrote, or a native mirror whose +// index is gone — and a dry run refuses the same. Nothing moves. Another +// volume on the same root still starts fresh, and so does one whose +// directory holds only its marker and staging. +func TestMirrorRefusesATreeItHasNoRecordOf(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.index(t) + if err := os.WriteFile(f.dest("a.txt"), []byte("written by another tool"), 0o644); err != nil { + t.Fatal(err) + } + for _, dryRun := range []bool{true, false} { + _, err := f.push(t, Options{DryRun: dryRun}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "squirrel recover --from usb") { + t.Fatalf("push (dry run %v) = %v, want a refusal pointing at recover", dryRun, err) + } + } + if f.readDest(t, "a.txt") != "written by another tool" { + t.Fatal("the refused push moved the tree it found") + } + if _, err := os.Stat(f.dest(HistoryDirName)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the refused push displaced something: %v", err) + } + + if err := os.Remove(f.dest("a.txt")); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(f.dest(StagingDirName+"/run-99"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest(StagingDirName+"/run-99/"+stagingKey("a.txt")), []byte("partial"), 0o644); err != nil { + t.Fatal(err) + } + f.mustPush(t) + f.checkInvariants(t, nil) + }) + } +} + +// TestMirrorSecondVolumeStartsFreshBesideAnother: a volume's first push to +// a root that already holds another volume's mirror is no adoption: it +// starts fresh in its own directory. +func TestMirrorSecondVolumeStartsFreshBesideAnother(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + if err := os.MkdirAll(filepath.Join(f.dst, "docs", "2024"), 0o755); err != nil { + t.Fatal(err) + } + if err := volmark.Write(filepath.Join(f.dst, "docs"), volmark.Marker{Volume: "docs"}); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(f.dst, "docs", "2024", "invoice.pdf"), []byte("another volume's"), 0o644); err != nil { + t.Fatal(err) + } + f.mustPush(t) + f.checkInvariants(t, nil) +} + +// TestMirrorRetriesAFirstPushThatCrashed: a first push that died after +// committing some paths left records, so its retry is no adoption: it +// settles what the crash left and lands the rest. +func TestMirrorRetriesAFirstPushThatCrashed(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + commits := 0 + if rep, err := f.pushCrashing(t, func(c transportCall) bool { + if c.op == "rename" && strings.Contains(c.name, StagingDirName+"/run-") { + commits++ + } + return commits == 2 + }, crashAfter); !crashedOn(rep, err) { + t.Fatalf("crashing first push = %v, want the injected crash", err) + } + f.mustPush(t) + f.checkInvariants(t, nil) + }) + } +} + +// TestMirrorFirstPushSurvivesAPowerCutAtEveryCall: a first push displaces +// nothing, so only the flush after staging stands between a staged file's +// bytes and the rename that commits it. A power cut around any call, even +// one that keeps every name but loses the bytes no Flush covered, leaves +// every record vouching for its bytes, and the retry lands the rest. +func TestMirrorFirstPushSurvivesAPowerCutAtEveryCall(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + var rec *faultTransport + if _, err := firstPushFixture(t, b).pushVia(t, Options{}, func(tr transport) transport { + rec = &faultTransport{transport: tr} + return rec + }); err != nil { + t.Fatal(err) + } + for i := range rec.calls { + for _, cut := range powerCuts { + t.Run(fmt.Sprintf("%03d-%s", i, cut.name), func(t *testing.T) { + t.Parallel() + f := firstPushFixture(t, b) + if rep, err := f.pushCuttingPower(t, crashAtCall(i), cut.mode, cut.keep); !crashedOn(rep, err) { + t.Fatalf("push cut short = %v, want the injected crash", err) + } + f.checkRecordsVouch(t) + f.mustPush(t) + f.checkInvariants(t, nil) + }) + } + } + }) + } +} + +// firstPushFixture is a fixture about to push three files for the first +// time, one path at a time. +func firstPushFixture(t *testing.T, b mirrorBackend) *mirrorFixture { + t.Helper() + f := setupMirrorFixtureOn(t, b) + f.oneAtATime() + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.write(t, "d/c.txt", "gamma") + f.index(t) + return f +} + +// TestMirrorLeavesAppleDoubleCompanionsToTheSystem: the "._X" files macOS +// keeps beside X on a disk without extended attributes are X's, not +// foreign: one beside the marker leaves a root empty, one beside a +// finished run's staging is not reported, and an index-less restore leaves +// them out, counted once, while an orphan with no X beside it is restored +// like any file no receipt names. +func TestMirrorLeavesAppleDoubleCompanionsToTheSystem(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + if err := os.WriteFile(f.dest("._"+volmark.MarkerName), []byte("attributes"), 0o644); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + first := f.mustPush(t) + run := "run-" + strconv.FormatInt(first.RunID, 10) + for _, rel := range []string{StagingDirName + "/._" + run, "._a.txt", "._" + HistoryDirName, "._orphan.txt"} { + if err := os.WriteFile(f.dest(rel), []byte("attributes"), 0o644); err != nil { + t.Fatal(err) + } + } + if err := os.MkdirAll(f.dest(HistoryDirName), 0o755); err != nil { + t.Fatal(err) + } + f.write(t, "b.txt", "beta") + f.index(t) + if rep := f.mustPush(t); warned(rep, "._"+run) { + t.Fatalf("warnings = %v, want the companion of finished staging left alone", rep.Warnings) + } + + to := t.TempDir() + fresh, err := store.Open(filepath.Join(t.TempDir(), "fresh.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + rep, err := Restore(t.Context(), fresh, nil, f.pair.Volume, f.pair.Destination, RestoreOptions{ToPath: to}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("restore: status=%q err=%v", rep.Status, err) + } + if !warned(rep, "3 AppleDouble file(s)") || !warned(rep, "1 file(s) on \"usb\" are named in no receipt") { + t.Fatalf("warnings = %v, want three companions left out and the orphan restored unchecked", rep.Warnings) + } + for rel, want := range map[string]bool{"a.txt": true, "b.txt": true, "._orphan.txt": true, "._a.txt": false, "._" + HistoryDirName: false, "._" + volmark.MarkerName: false} { + if _, err := os.Stat(filepath.Join(to, rel)); (err == nil) != want { + t.Errorf("%s restored = %v, want %v", rel, err == nil, want) + } + } + }) + } +} + +// TestMarkerRefusalOfADestinationSyncedBefore: a destination the volume +// synced to before that has lost its root or its marker is refused as a +// disk that is most likely not mounted; the refusal does not steer toward +// --init, which would bootstrap an empty destination in its place. +func TestMarkerRefusalOfADestinationSyncedBefore(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + for _, gone := range []string{f.dest(volmark.MarkerName), f.dst} { + if err := os.RemoveAll(gone); err != nil { + t.Fatal(err) + } + _, err := f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "most likely not mounted") || strings.Contains(err.Error(), "re-run with --init") { + t.Fatalf("push with %s gone = %v, want a refusal naming an unmounted disk", gone, err) + } + } + if _, err := VerifyRemote(t.Context(), f.store, nil, f.pair.Destination); err == nil || !strings.Contains(err.Error(), "may not be mounted") { + t.Fatalf("verify with the root gone = %v, want it named as a disk that may not be mounted", err) + } +} diff --git a/sync/mirror_fold.go b/sync/mirror_fold.go new file mode 100644 index 0000000..d88b731 --- /dev/null +++ b/sync/mirror_fold.go @@ -0,0 +1,374 @@ +package sync + +import ( + "context" + "database/sql" + "errors" + "fmt" + "path" + "sort" + "strings" + "time" + "unicode" + + "golang.org/x/text/unicode/norm" + + "github.com/mbertschler/squirrel/store" +) + +// foldProbeBase is the file a mirror push writes into staging to learn how +// the destination compares names. foldProbeCase is the same name with its +// ASCII letters in upper case, foldProbeNorm the same name decomposed. +const ( + foldProbeBase = "fold-probe-\u00e9" + foldProbeCase = "FOLD-PROBE-\u00e9" + foldProbeNorm = "fold-probe-e\u0301" +) + +// foldProbeName is where a push probes the destination's names: +// /.squirrel-staging/fold-probe-é. +func foldProbeName(volumeDir string) string { + return path.Join(volumeDir, StagingDirName, foldProbeBase) +} + +// isFoldProbe reports whether a staging entry is the name probe, as a +// destination that stores names decomposed lists it. +func isFoldProbe(name string) bool { + return norm.NFC.String(name) == foldProbeBase +} + +// nameFolding is how a destination compares names: whether it resolves +// names that differ only by case, or only by Unicode normalization, to the +// same entry (APFS does both, exFAT folds case). +type nameFolding struct { + caseless, normless bool +} + +func (f nameFolding) folds() bool { return f.caseless || f.normless } + +// key is the one spelling of s the destination resolves every equivalent +// spelling to. +func (f nameFolding) key(s string) string { + if f.normless { + s = norm.NFC.String(s) + } + if f.caseless { + s = strings.Map(foldRune, s) + } + return s +} + +// under reports whether rel lies below dir, as the destination resolves +// both. +func (f nameFolding) under(rel, dir string) bool { + return strings.HasPrefix(f.key(rel), f.key(dir)+"/") +} + +// foldRune maps r to the smallest rune of its simple case folding orbit, +// so every case variant of a rune maps to the same one. +func foldRune(r rune) rune { + least := r + for f := unicode.SimpleFold(r); f != r; f = unicode.SimpleFold(f) { + least = min(least, f) + } + return least +} + +// probeFolding writes the name probe and looks it up by its upper-case and +// its decomposed spelling: whichever the destination finds, it folds. The +// probe is removed again; one a crashed push left behind is removed first. +func (w *mirrorWriter) probeFolding(ctx context.Context) (nameFolding, error) { + dir := path.Join(w.h.vol.Name, StagingDirName) + name := foldProbeName(w.h.vol.Name) + if err := w.removeProbe(ctx, name); err != nil { + return nameFolding{}, err + } + if err := w.tr.Put(ctx, name, strings.NewReader(""), time.Now()); err != nil { + return nameFolding{}, fmt.Errorf("write the name probe %s: %w", name, err) + } + var f nameFolding + var err error + if f.caseless, err = present(ctx, w.tr, path.Join(dir, foldProbeCase)); err != nil { + return nameFolding{}, fmt.Errorf("probe case folding: %w", err) + } + if f.normless, err = present(ctx, w.tr, path.Join(dir, foldProbeNorm)); err != nil { + return nameFolding{}, fmt.Errorf("probe normalization folding: %w", err) + } + return f, w.removeProbe(ctx, name) +} + +func (w *mirrorWriter) removeProbe(ctx context.Context, name string) error { + left, err := present(ctx, w.tr, name) + if err != nil || !left { + return err + } + if err := w.tr.Remove(ctx, name); err != nil { + return fmt.Errorf("remove the name probe %s: %w", name, err) + } + return nil +} + +// foldPlan is how a push writes to a destination that folds names: the +// planned paths it refuses, each with the spelling it collides with, and +// for each path it writes, the versions recorded under another spelling of +// its name or a parent's, which move aside before it lands. +type foldPlan struct { + refused map[string]string + displace map[string][]string +} + +// foldMember is one path's claim on a folded name: a file at it, or a +// directory the path lies under. +type foldMember struct { + path string + spelling string // how the path spells the name + dir bool + planned bool // the push plans the path: it is present at the source + live bool // a live record holds the path +} + +// foldEntity is one thing the destination can hold at a folded name: a +// file under one spelling, or a directory under any. +type foldEntity struct { + name string + members []foldMember + present bool // a present path claims it + onDest bool // a live record of a present path claims it +} + +// planFolding decides how every planned path lands on a folding +// destination. Two present paths whose names, or whose parents' names, +// fold together where one is a file cannot both land: the one the +// destination already holds wins, then the first by spelling, and every +// other is refused, displacing nothing. A version recorded under another +// spelling whose path is no longer present — a rename that changed only +// case — moves aside as its record before the planned path lands. +func (w *mirrorWriter) planFolding(ctx context.Context, ops *mirrorOps) (foldPlan, error) { + plan := foldPlan{refused: map[string]string{}, displace: map[string][]string{}} + groups := w.foldGroups(ops) + isPresent := w.presentAtSource(ctx) + var candidates []string + for key, members := range groups { + if collides(members) { + candidates = append(candidates, key) + } + } + sort.Strings(candidates) + for _, key := range candidates { + entities, err := foldEntities(groups[key], isPresent) + if err != nil { + return foldPlan{}, err + } + plan.refuse(entities) + } + for _, key := range candidates { + if err := plan.displaceOthers(groups[key], isPresent); err != nil { + return foldPlan{}, err + } + } + return plan, nil +} + +// foldGroups gathers, for every folded name along a planned path, the +// claims of every planned path and live record on it. +func (w *mirrorWriter) foldGroups(ops *mirrorOps) map[string][]foldMember { + interest := map[string]bool{} + claims := map[string]*foldMember{} + for _, p := range ops.paths { + rel := p.delta.Path + claims[rel] = &foldMember{path: rel, planned: true} + key := w.fold.key(rel) + for i := range key { + if key[i] == '/' { + interest[key[:i]] = true + } + } + interest[key] = true + } + for rel := range w.live.byPath { + if c, ok := claims[rel]; ok { + c.live = true + continue + } + claims[rel] = &foldMember{path: rel, live: true} + } + groups := map[string][]foldMember{} + for rel, c := range claims { + key := w.fold.key(rel) + for i := range len(key) + 1 { + if i < len(key) && key[i] != '/' { + continue + } + if !interest[key[:i]] { + continue + } + m := *c + m.spelling, m.dir = spellingAt(rel, strings.Count(key[:i], "/")), i < len(key) + groups[key[:i]] = append(groups[key[:i]], m) + } + } + return groups +} + +// spellingAt is rel cut after its first depth+1 elements. +func spellingAt(rel string, depth int) string { + parts := strings.SplitN(rel, "/", depth+2) + return strings.Join(parts[:depth+1], "/") +} + +// collides reports whether the claims on one folded name can clash: two +// files under different spellings, or a file where a directory is. +func collides(members []foldMember) bool { + files := map[string]bool{} + dirs := false + for _, m := range members { + if m.dir { + dirs = true + } else { + files[m.spelling] = true + } + } + return len(files) > 1 || (len(files) == 1 && dirs) +} + +// foldEntities groups one folded name's claims into what the destination +// can hold there: a file per spelling, and one directory for every +// directory spelling, which the destination merges. +func foldEntities(members []foldMember, isPresent func(string) (bool, error)) ([]foldEntity, error) { + byName := map[string]*foldEntity{} + var dir *foldEntity + for _, m := range members { + e := byName[m.spelling] + if m.dir { + if dir == nil { + dir = &foldEntity{name: m.spelling} + } + dir.name = min(dir.name, m.spelling) + e = dir + } else if e == nil { + e = &foldEntity{name: m.spelling} + byName[m.spelling] = e + } + e.members = append(e.members, m) + } + var out []foldEntity + if dir != nil { + out = append(out, *dir) + } + for _, e := range byName { + out = append(out, *e) + } + for i := range out { + if err := out[i].weigh(isPresent); err != nil { + return nil, err + } + } + return out, nil +} + +func (e *foldEntity) weigh(isPresent func(string) (bool, error)) error { + for _, m := range e.members { + if e.onDest { + return nil + } + p := m.planned + if !p { + var err error + if p, err = isPresent(m.path); err != nil { + return err + } + } + e.present = e.present || p + e.onDest = e.onDest || (p && m.live) + } + return nil +} + +// refuse picks the winner among the present entities at one folded name, +// the one the destination holds first, then the first by spelling, and +// refuses every planned path that claims another. +func (p foldPlan) refuse(entities []foldEntity) { + var present []foldEntity + for _, e := range entities { + if e.present { + present = append(present, e) + } + } + if len(present) < 2 { + return + } + sort.Slice(present, func(i, j int) bool { + if present[i].onDest != present[j].onDest { + return present[i].onDest + } + return present[i].name < present[j].name + }) + for _, e := range present[1:] { + for _, m := range e.members { + if m.planned { + if _, done := p.refused[m.path]; !done { + p.refused[m.path] = present[0].name + } + } + } + } +} + +// displaceOthers plans, for every planned path that still lands at or +// under one folded name, the move of each version recorded as a file there +// under another spelling whose path is no longer present. +func (p foldPlan) displaceOthers(members []foldMember, isPresent func(string) (bool, error)) error { + for _, stale := range members { + if stale.dir || stale.planned || !stale.live { + continue + } + present, err := isPresent(stale.path) + if err != nil { + return err + } + if present { + continue + } + for _, m := range members { + if _, refused := p.refused[m.path]; m.planned && !refused && m.path != stale.path { + p.displace[m.path] = append(p.displace[m.path], stale.path) + } + } + } + return nil +} + +// presentAtSource reports whether a path is present in the volume's +// index, remembering each answer. +func (w *mirrorWriter) presentAtSource(ctx context.Context) func(string) (bool, error) { + seen := map[string]bool{} + return func(rel string) (bool, error) { + if p, ok := seen[rel]; ok { + return p, nil + } + r, err := w.h.store.GetByPath(ctx, w.volumeID, rel) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return false, fmt.Errorf("look up %s: %w", rel, err) + } + seen[rel] = err == nil && r.Status == store.StatusPresent + return seen[rel], nil + } +} + +// displaceSpelling moves aside the version recorded at rel, another +// spelling of a planned path's name, unless an earlier path of this push +// already did. +func (w *mirrorWriter) displaceSpelling(ctx context.Context, rel string) error { + if _, ok := w.liveAt(rel); !ok { + return nil + } + return w.displace(ctx, rel) +} + +func (w *mirrorWriter) refuseCollision(rel, other string) { + w.mu.Lock() + defer w.mu.Unlock() + w.collided++ + w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s is not written: the destination cannot tell its name apart from %s (it ignores case or Unicode normalization); rename one of them at the source", + w.h.dest.Name, rel, other)) +} diff --git a/sync/mirror_fold_test.go b/sync/mirror_fold_test.go new file mode 100644 index 0000000..0b16c18 --- /dev/null +++ b/sync/mirror_fold_test.go @@ -0,0 +1,362 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/store" +) + +// foldingTransport stands in for a destination that folds names, as APFS +// and exFAT do: each name resolves, element by element, to the entry +// already on disk whose name folds to the same key. disk is where the +// destination root is on this machine. +type foldingTransport struct { + transport + disk string + fold nameFolding +} + +func (f foldingTransport) resolve(name string) string { + parts := strings.Split(name, "/") + dir := f.disk + for i, p := range parts { + entries, err := os.ReadDir(dir) + if err != nil { + break + } + for _, e := range entries { + if f.fold.key(e.Name()) == f.fold.key(p) { + parts[i] = e.Name() + break + } + } + dir = filepath.Join(dir, parts[i]) + } + return strings.Join(parts, "/") +} + +func (f foldingTransport) Stat(ctx context.Context, name string) (entry, error) { + return f.transport.Stat(ctx, f.resolve(name)) +} + +func (f foldingTransport) List(ctx context.Context, dir string) ([]entry, error) { + return f.transport.List(ctx, f.resolve(dir)) +} + +func (f foldingTransport) Get(ctx context.Context, name string) (io.ReadCloser, error) { + return f.transport.Get(ctx, f.resolve(name)) +} + +func (f foldingTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + return f.transport.Put(ctx, f.resolve(name), r, mtime) +} + +func (f foldingTransport) Rename(ctx context.Context, from, to string) error { + return f.transport.Rename(ctx, f.resolve(from), f.resolve(to)) +} + +func (f foldingTransport) Remove(ctx context.Context, name string) error { + return f.transport.Remove(ctx, f.resolve(name)) +} + +func (f foldingTransport) ServerHash(ctx context.Context, name string) (remoteChecksum, error) { + return f.transport.ServerHash(ctx, f.resolve(name)) +} + +var ( + caseAndNormFolding = nameFolding{caseless: true, normless: true} + composed = "caf\u00e9.txt" + decomposed = "cafe\u0301.txt" +) + +func TestNameFoldingKey(t *testing.T) { + cases := []struct { + fold nameFolding + a, b string + same bool + }{ + {nameFolding{}, "a.jpg", "A.jpg", false}, + {nameFolding{caseless: true}, "a.jpg", "A.jpg", true}, + {nameFolding{caseless: true}, "Straße/Ä", "STRASSE/ä", false}, + {nameFolding{caseless: true}, "ärger/Σ", "Ärger/ς", true}, + {nameFolding{caseless: true}, composed, decomposed, false}, + {nameFolding{normless: true}, composed, decomposed, true}, + {nameFolding{normless: true}, "a.jpg", "A.jpg", false}, + {caseAndNormFolding, "Caf\u00e9/X", "cafe\u0301/x", true}, + } + for _, c := range cases { + if got := c.fold.key(c.a) == c.fold.key(c.b); got != c.same { + t.Errorf("%+v: %q and %q fold together = %v, want %v", c.fold, c.a, c.b, got, c.same) + } + } +} + +// TestMirrorProbesHowTheDestinationComparesNames: a push learns from one +// file in staging whether the destination folds case, normalization, +// both or neither, and leaves no probe behind. +func TestMirrorProbesHowTheDestinationComparesNames(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, {caseless: true}, {normless: true}, caseAndNormFolding} { + t.Run(fmt.Sprintf("%s/%+v", b.name, fold), func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.fold = fold + f.write(t, "a.txt", "alpha") + f.index(t) + var got nameFolding + _, err := f.pushVia(t, Options{}, func(tr transport) transport { + return probeRecorder{transport: tr, got: &got} + }) + if err != nil { + t.Fatal(err) + } + disk := diskFolding(t, f.dst) + want := nameFolding{caseless: fold.caseless || disk.caseless, normless: fold.normless || disk.normless} + if got != want { + t.Fatalf("probe = %+v, want %+v", got, want) + } + if _, err := os.Stat(f.dest(StagingDirName + "/" + foldProbeBase)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the probe stayed in staging: %v", err) + } + }) + } + } +} + +// probeRecorder records what the name probe's two lookups found. +type probeRecorder struct { + transport + got *nameFolding +} + +func (p probeRecorder) Stat(ctx context.Context, name string) (entry, error) { + e, err := p.transport.Stat(ctx, name) + switch { + case strings.HasSuffix(name, "/"+foldProbeCase): + p.got.caseless = err == nil + case strings.HasSuffix(name, "/"+foldProbeNorm): + p.got.normless = err == nil + } + return e, err +} + +// setupFoldingMirror is a mirror fixture on b whose destination folds case +// and normalization. +func setupFoldingMirror(t *testing.T, b mirrorBackend) *mirrorFixture { + t.Helper() + f := setupMirrorFixtureOn(t, b) + f.fold = caseAndNormFolding + return f +} + +// observe records body as present at rel in a run of its own, as an index +// run over a source that holds rel would; it writes no source file, so a +// push that tried to send rel would fail to read it. +func (f *mirrorFixture) observe(t *testing.T, rel, body string) { + t.Helper() + ctx := context.Background() + volID := f.volumeID(t) + runID, err := f.store.BeginIndexRun(ctx, store.RunKindIndex, volID, false) + if err != nil { + t.Fatal(err) + } + sum := blake3.Sum256([]byte(body)) + now := time.Now().UnixNano() + row := store.FileRow{VolumeID: volID, Path: rel, Blake3: sum[:], SizeBytes: int64(len(body)), MtimeNs: now, + Status: store.StatusPresent, FirstSeenRunID: runID, LastSeenRunID: runID, IndexedAtNs: now} + if err := f.store.Upsert(ctx, row, nil); err != nil { + t.Fatalf("Upsert %s: %v", rel, err) + } + if err := f.store.FinishRun(ctx, runID, store.RunStatusSuccess, "", 1); err != nil { + t.Fatal(err) + } +} + +// TestMirrorRefusesNamesTheDestinationCannotTellApart: on a destination +// that folds case and normalization, a present path whose name — or a +// parent's — folds onto another present path's is refused, and only that +// path: nothing is displaced, the path already there keeps its bytes and +// its record, every other path lands, and the run fails before its +// receipt, so the watermark holds until one of them is renamed. +func TestMirrorRefusesNamesTheDestinationCannotTellApart(t *testing.T) { + cases := []struct { + name string + first, colliding string + }{ + {"case", "a.jpg", "A.jpg"}, + {"normalization", composed, decomposed}, + {"a file where a directory is", "d/x.txt", "D"}, + {"a directory where a file is", "f", "F/y.txt"}, + } + for _, b := range mirrorBackends { + for _, c := range cases { + t.Run(b.name+"/"+c.name, func(t *testing.T) { + f := setupFoldingMirror(t, b) + f.write(t, c.first, "first") + f.index(t) + f.mustPush(t) + f.write(t, "other.txt", "other") + f.index(t) + f.observe(t, c.colliding, "colliding") + before := f.contentHashes(t) + + rep, err := f.push(t, Options{}) + if err == nil || rep.Status != store.RunStatusFailed || !strings.Contains(err.Error(), "cannot tell their names apart") { + t.Fatalf("push: status=%q err=%v, want a failed run naming the collision", rep.Status, err) + } + if !warned(rep, c.colliding+" is not written") { + t.Fatalf("warnings = %v, want %s refused", rep.Warnings, c.colliding) + } + if f.readDest(t, c.first) != "first" || f.readDest(t, "other.txt") != "other" { + t.Fatal("the path already there changed, or the other path did not land") + } + if got := f.rowsAt(t, c.first); !slicesEqual(got, []string{store.RemotePathLive}) { + t.Fatalf("%s rows = %v, want its one live row untouched", c.first, got) + } + if got := f.rowsAt(t, c.colliding); len(got) != 0 { + t.Fatalf("%s rows = %v, want none", c.colliding, got) + } + if _, err := os.Stat(f.dest(HistoryDirName)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("a refused path displaced something: %v", err) + } + if after := f.contentHashes(t); len(after) != len(before)+1 { + t.Fatalf("destination holds %d files, want the %d before plus other.txt", len(after), len(before)) + } + if _, err := os.Stat(f.dest(".squirrel-index/run-" + strconv.FormatInt(rep.RunID, 10))); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the failed run left a receipt: %v", err) + } + }) + } + } +} + +// TestMirrorRefusesTheSecondOfTwoNewNames: two new present paths that fold +// together land as one: the first by spelling, the second refused. +func TestMirrorRefusesTheSecondOfTwoNewNames(t *testing.T) { + f := setupFoldingMirror(t, localBackend) + f.write(t, "keep.txt", "keep") + f.index(t) + f.observe(t, "X.jpg", "upper") + f.observe(t, "x.jpg", "lower") + f.write(t, "X.jpg", "upper") + rep, err := f.push(t, Options{}) + if err == nil || !warned(rep, "x.jpg is not written") { + t.Fatalf("push: err=%v warnings=%v, want x.jpg refused", err, rep.Warnings) + } + if f.readDest(t, "X.jpg") != "upper" { + t.Fatal("the first spelling did not land") + } +} + +// TestMirrorFollowsARenameThatChangesOnlyCase: a file or a directory +// renamed at the source in case alone moves the recorded versions under the +// old spelling into history as their records, then lands under the new +// one, on a destination that cannot hold both. Every record keeps +// vouching for the bytes it names, on the folding the fixture emulates and +// on this machine's own disk when that folds. +func TestMirrorFollowsARenameThatChangesOnlyCase(t *testing.T) { + for _, b := range mirrorBackends { + for _, emulate := range []bool{true, false} { + t.Run(b.name+"/emulated="+strconv.FormatBool(emulate), func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + if emulate { + f.fold = caseAndNormFolding + } else if !diskFolding(t, f.dst).caseless { + t.Skip("this machine's disk tells names apart by case") + } + f.write(t, "a.jpg", "file") + f.write(t, "Photos/x.jpg", "in a directory") + f.index(t) + f.mustPush(t) + f.rename(t, "a.jpg", "A.jpg") + f.rename(t, "Photos", "photos") + f.index(t) + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := strconv.FormatInt(rep.RunID, 10) + if f.readDest(t, "A.jpg") != "file" || f.readDest(t, "photos/x.jpg") != "in a directory" { + t.Fatal("the renamed paths did not land") + } + for _, rel := range []string{"a.jpg", "Photos/x.jpg"} { + if got := f.rowsAt(t, rel); !slicesEqual(got, []string{store.RemotePathDisplaced}) { + t.Fatalf("%s rows = %v, want displaced", rel, got) + } + } + if f.readDest(t, HistoryDirName+"/run-"+run+"/a.jpg") != "file" { + t.Fatal("the old spelling's version is not in history") + } + f.checkInvariants(t, before) + }) + } + } +} + +func (f *mirrorFixture) rename(t *testing.T, from, to string) { + t.Helper() + if err := os.Rename(filepath.Join(f.src, from), filepath.Join(f.src, to)); err != nil { + t.Fatal(err) + } +} + +// diskFolding is how the disk under dir compares names. +func diskFolding(t *testing.T, dir string) nameFolding { + t.Helper() + found := func(name, lookup string) bool { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, nil, 0o644); err != nil { + t.Fatal(err) + } + defer func() { _ = os.Remove(p) }() + _, err := os.Stat(filepath.Join(dir, lookup)) + return err == nil + } + return nameFolding{caseless: found("case-probe", "CASE-PROBE"), normless: found(composed, decomposed)} +} + +// TestMirrorFoldingMovesAFileOutOfADirectorysWay: a recorded file whose +// path is gone at the source moves aside as its record when a new path's +// directory folds onto its name, and a recorded directory moves with every +// version in it when a new file's name folds onto it. +func TestMirrorFoldingMovesAFileOutOfADirectorysWay(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupFoldingMirror(t, b) + f.write(t, "a", "file a") + f.write(t, "D/x", "inside D") + f.index(t) + f.mustPush(t) + for _, rel := range []string{"a", "D"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "A/b", "under A") + f.write(t, "d", "file d") + f.index(t) + before := f.contentHashes(t) + + f.mustPush(t) + if f.readDest(t, "A/b") != "under A" || f.readDest(t, "d") != "file d" { + t.Fatal("the new paths did not land") + } + for _, rel := range []string{"a", "D/x"} { + if got := f.rowsAt(t, rel); !slicesEqual(got, []string{store.RemotePathDisplaced}) { + t.Fatalf("%s rows = %v, want displaced as its record", rel, got) + } + } + f.checkInvariants(t, before) + }) + } +} diff --git a/sync/mirror_hostile_test.go b/sync/mirror_hostile_test.go new file mode 100644 index 0000000..e66dd22 --- /dev/null +++ b/sync/mirror_hostile_test.go @@ -0,0 +1,538 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// plantSymlink replaces what the destination holds at rel with a symlink +// to target. +func (f *mirrorFixture) plantSymlink(t *testing.T, rel, target string) { + t.Helper() + if err := os.RemoveAll(f.dest(rel)); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(f.dest(rel)), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, f.dest(rel)); err != nil { + t.Fatal(err) + } +} + +// outsideDir is a directory beside the destination that a symlink can +// point squirrel at; checkUntouched asserts nothing was written there. +func outsideDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "precious.txt"), []byte("outside"), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func checkUntouched(t *testing.T, dir string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "precious.txt" { + t.Fatalf("outside directory holds %v, want only precious.txt", entries) + } + if b, _ := os.ReadFile(filepath.Join(dir, "precious.txt")); string(b) != "outside" { + t.Fatalf("precious.txt = %q, want it unchanged", b) + } +} + +// TestMirrorNeverFollowsASymlinkAtATarget: a symlink the destination holds +// where a path, or a directory along it, should be is never followed. It +// moves into history as bytes squirrel did not write, a record it replaced +// becomes lost, and the path lands in a real directory; nothing is written +// where the symlink points. +func TestMirrorNeverFollowsASymlinkAtATarget(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "dir/old.txt", "old") + f.write(t, "a.txt", "a1") + f.index(t) + f.mustPush(t) + outside := outsideDir(t) + f.plantSymlink(t, "dir", outside) + f.plantSymlink(t, "a.txt", filepath.Join(outside, "precious.txt")) + f.write(t, "dir/new.txt", "new") + f.write(t, "a.txt", "a2") + f.index(t) + + rep := f.mustPush(t) + checkUntouched(t, outside) + if f.readDest(t, "dir/new.txt") != "new" || f.readDest(t, "a.txt") != "a2" { + t.Fatal("the paths did not land in real entries") + } + run := strconv.FormatInt(rep.RunID, 10) + for _, rel := range []string{"dir", "a.txt"} { + if fi, err := os.Lstat(f.dest(HistoryDirName + "/run-" + run + "/" + rel)); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatalf("history/%s = %v, %v; want the symlink itself preserved", rel, fi, err) + } + } + for _, rel := range []string{"dir/old.txt", "a.txt"} { + if got := f.rowsAt(t, rel); len(got) == 0 || got[0] != store.RemotePathLost { + t.Fatalf("%s rows = %v, want its first row lost", rel, got) + } + } + f.checkRecordsVouch(t) + + f.mustPush(t) + if f.readDest(t, "dir/old.txt") != "old" { + t.Fatal("the next push did not repair the path the symlink took away") + } + f.checkInvariants(t, nil) + }) + } +} + +// TestMirrorNeverFollowsASymlinkedReservedDirectory: a symlink in place of +// the volume directory, or of its history, staging or index directory, +// fails the push instead of being followed, and nothing is written where +// it points. Once the symlink is gone, a clean push settles everything. +func TestMirrorNeverFollowsASymlinkedReservedDirectory(t *testing.T) { + for _, b := range mirrorBackends { + for _, rel := range []string{HistoryDirName, StagingDirName, IndexDirName, "."} { + t.Run(b.name+"/"+rel, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2, longer") + f.index(t) + outside := outsideDir(t) + real := f.dest(rel) + ".real" + if err := os.Rename(f.dest(rel), real); err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + if err := os.Symlink(outside, f.dest(rel)); err != nil { + t.Fatal(err) + } + if rel == "." { + if err := volmark.Write(outside, volmark.Marker{Volume: "pics"}); err != nil { + t.Fatal(err) + } + } + + if rep, err := f.push(t, Options{}); err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push through a symlinked %s: status=%q err=%v, want it failed", rel, rep.Status, err) + } + if rel == "." { + _ = os.Remove(filepath.Join(outside, volmark.MarkerName)) + } + checkUntouched(t, outside) + if err := os.Remove(f.dest(rel)); err != nil { + t.Fatal(err) + } + if err := os.Rename(real, f.dest(rel)); err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + f.checkRecordsVouch(t) + f.mustPush(t) + if f.readDest(t, "a.txt") != "v2, longer" { + t.Fatal("the push after the symlink went did not land the change") + } + f.checkInvariants(t, nil) + }) + } + } +} + +// TestMirrorNestedFileDirectorySwaps: a file deep in the tree that became a +// directory holding a deeper file, and a directory tree that became a +// file, each move aside as their records — a replaced directory with every +// version recorded under it, a version changed behind squirrel's back +// losing its record, and bytes squirrel never wrote kept beside them. +func TestMirrorNestedFileDirectorySwaps(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a/b/c", "file c") + f.write(t, "x/y/z", "file z") + f.write(t, "x/y/w", "file w") + f.write(t, "x/v", "file v") + f.index(t) + f.mustPush(t) + for _, rel := range []string{"a/b/c", "x"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "a/b/c/d/e", "deep under c") + f.write(t, "x", "x is a file") + f.index(t) + if err := os.WriteFile(f.dest("x/y/w"), []byte("changed on the destination"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("x/y/foreign"), []byte("not squirrel's"), 0o644); err != nil { + t.Fatal(err) + } + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := HistoryDirName + "/run-" + strconv.FormatInt(rep.RunID, 10) + "/" + if f.readDest(t, "a/b/c/d/e") != "deep under c" || f.readDest(t, "x") != "x is a file" { + t.Fatal("the swapped paths did not land") + } + for rel, want := range map[string]string{"a/b/c": "file c", "x/y/z": "file z", "x/v": "file v", "x/y/foreign": "not squirrel's", "x/y/w": "changed on the destination"} { + if got := f.readDest(t, run+rel); got != want { + t.Errorf("history %s = %q, want %q", rel, got, want) + } + } + for rel, want := range map[string]string{"a/b/c": store.RemotePathDisplaced, "x/y/z": store.RemotePathDisplaced, "x/v": store.RemotePathDisplaced, "x/y/w": store.RemotePathLost} { + if got := f.rowsAt(t, rel); !slicesEqual(got, []string{want}) { + t.Errorf("%s rows = %v, want %s", rel, got, want) + } + } + f.checkInvariants(t, before) + }) + } +} + +// TestMirrorLeavesForeignStagingAlone: whatever squirrel did not name in +// staging — a file or directory at its top, a run directory of a run the +// index does not know, a symlink or directory in a finished run's staging +// — is reported and never removed, while the finished run's own staging +// beside it goes. +func TestMirrorLeavesForeignStagingAlone(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.index(t) + first := f.mustPush(t) + finished := StagingDirName + "/run-" + strconv.FormatInt(first.RunID, 10) + "/" + key := stagingKey("a.txt") + foreign := []string{StagingDirName + "/notes.txt", StagingDirName + "/mine/x", StagingDirName + "/run-999999/" + key, finished + key + "0/x"} + for _, rel := range foreign { + if err := os.MkdirAll(filepath.Dir(f.dest(rel)), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest(rel), []byte("foreign"), 0o644); err != nil { + t.Fatal(err) + } + } + if err := os.Symlink(outsideDir(t), f.dest(finished+"link")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest(finished+key), []byte("a crashed run's partial copy"), 0o644); err != nil { + t.Fatal(err) + } + + f.write(t, "a.txt", "alpha, changed") + f.index(t) + rep := f.mustPush(t) + for _, name := range []string{"notes.txt", "mine", "run-999999", key + "0", "link"} { + if !warned(rep, name+" is in squirrel's staging") { + t.Errorf("warnings = %v, want %s reported", rep.Warnings, name) + } + } + for _, rel := range append(foreign, finished+"link") { + if _, err := os.Lstat(f.dest(rel)); err != nil { + t.Errorf("%s was removed: %v", rel, err) + } + } + if _, err := os.Stat(f.dest(finished + key)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the finished run's own staged copy is still there: %v", err) + } + }) + } +} + +// fullTransport fails a Put that full selects once it has taken limit +// bytes, as a disk that fills up, or a quota that runs out, mid-write. +type fullTransport struct { + transport + full func(name string) bool + limit int64 + errno syscall.Errno +} + +func (f fullTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if !f.full(name) { + return f.transport.Put(ctx, name, r, mtime) + } + return f.transport.Put(ctx, name, &fillingReader{r: r, left: f.limit, errno: f.errno}, mtime) +} + +type fillingReader struct { + r io.Reader + left int64 + errno syscall.Errno +} + +func (f *fillingReader) Read(p []byte) (int, error) { + if f.left <= 0 { + return 0, &fs.PathError{Op: "write", Path: "staged", Err: f.errno} + } + if int64(len(p)) > f.left { + p = p[:f.left] + } + n, err := f.r.Read(p) + f.left -= int64(n) + return n, err +} + +// TestMirrorDiskFullMidWrite: a destination that fills up, or runs out of +// quota, part way through a path's staged copy, the name probe or the +// receipt fails the push with the disk's error. Nothing reaches a path, +// every version already there stays, and once there is room again a clean +// push lands everything and clears the partial copy. +func TestMirrorDiskFullMidWrite(t *testing.T) { + staged := func(n string) bool { return strings.Contains(n, StagingDirName+"/run-") } + cases := []struct { + name string + full func(string) bool + limit int64 + errno syscall.Errno + }{ + {"staged copy, disk full", staged, 100, syscall.ENOSPC}, + {"staged copy, quota", staged, 100, syscall.EDQUOT}, + {"name probe", func(n string) bool { return strings.HasSuffix(n, foldProbeBase) }, 0, syscall.ENOSPC}, + {"receipt", func(n string) bool { return strings.Contains(n, IndexDirName+"/run-") }, 100, syscall.ENOSPC}, + } + for _, b := range mirrorBackends { + for _, c := range cases { + t.Run(b.name+"/"+c.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", strings.Repeat("v2 ", 1000)) + f.write(t, "b.txt", strings.Repeat("new ", 1000)) + f.index(t) + before := f.contentHashes(t) + rep, err := f.pushVia(t, Options{}, func(tr transport) transport { + return fullTransport{transport: tr, full: c.full, limit: c.limit, errno: c.errno} + }) + if err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push onto a full disk: status=%q err=%v, want it failed", rep.Status, err) + } + if msg := err.Error() + fmt.Sprint(rep.RcloneResult.FailedFiles); !strings.Contains(msg, c.errno.Error()) { + t.Fatalf("failure %q, want the disk's error %q named", msg, c.errno.Error()) + } + if c.name != "receipt" && f.readDest(t, "a.txt") != "v1" { + t.Fatal("a path changed although its new version never fully landed") + } + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + + clean := f.mustPush(t) + if f.readDest(t, "a.txt") != strings.Repeat("v2 ", 1000) || f.readDest(t, "b.txt") != strings.Repeat("new ", 1000) { + t.Fatal("the push with room again did not land everything") + } + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) + }) + } + } +} + +// TestMirrorHistoryUnwritable: when the history directory can't be +// written, a path whose recorded version must move there fails and keeps +// that version in place; nothing else is displaced for it. Once history is +// writable again, the next push settles the interrupted move and lands the +// change. +func TestMirrorHistoryUnwritable(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permissions do not bind root") + } + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + f.mustPush(t) + history := f.dest(HistoryDirName) + if err := os.Chmod(history, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(history, 0o755) }) + f.write(t, "a.txt", "v3, longer") + f.index(t) + before := f.contentHashes(t) + + rep, err := f.push(t, Options{}) + if err == nil || len(rep.RcloneResult.FailedFiles) != 1 { + t.Fatalf("push: err=%v failures=%+v, want a.txt failed", err, rep.RcloneResult.FailedFiles) + } + if f.readDest(t, "a.txt") != "v2" { + t.Fatal("the recorded version left its path although history could not take it") + } + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + + if err := os.Chmod(history, 0o755); err != nil { + t.Fatal(err) + } + f.mustPush(t) + if f.readDest(t, "a.txt") != "v3, longer" { + t.Fatal("the push with history writable did not land the change") + } + f.checkInvariants(t, before) + }) + } +} + +// driftingTransport changes the source file of the path staged at a +// staging key once its Put has taken the first chunk: the source drifts +// while it streams. +type driftingTransport struct { + transport + src string // the source file that drifts +} + +func (d driftingTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if !strings.Contains(name, StagingDirName+"/run-") { + return d.transport.Put(ctx, name, r, mtime) + } + return d.transport.Put(ctx, name, &driftingReader{r: r, src: d.src}, mtime) +} + +type driftingReader struct { + r io.Reader + src string + drifted bool +} + +func (d *driftingReader) Read(p []byte) (int, error) { + n, err := d.r.Read(p) + if !d.drifted && n > 0 { + d.drifted = true + b, rerr := os.ReadFile(d.src) + if rerr != nil { + return n, rerr + } + for i := range b { + b[i] ^= 0xff + } + if werr := os.WriteFile(d.src, b, 0o644); werr != nil { + return n, werr + } + } + return n, err +} + +// TestMirrorSourceDriftWhileStreaming: a source file that changes while +// its bytes stream to the destination is refused — the hash covers exactly +// the bytes sent — and its path keeps the version it had. The run fails +// before its receipt; after an index run the next push lands the new +// bytes and clears the refused copy. +func TestMirrorSourceDriftWhileStreaming(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "big.bin", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "big.bin", strings.Repeat("0123456789abcdef", 256<<10)) + f.index(t) + before := f.contentHashes(t) + rep, err := f.pushVia(t, Options{}, func(tr transport) transport { + return driftingTransport{transport: tr, src: filepath.Join(f.src, "big.bin")} + }) + if err == nil || !strings.Contains(err.Error(), "drifting") || !warned(rep, "big.bin sent") { + t.Fatalf("push: err=%v warnings=%v, want big.bin refused for drifting", err, rep.Warnings) + } + if f.readDest(t, "big.bin") != "v1" { + t.Fatal("the path changed although its source drifted") + } + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + + f.index(t) + clean := f.mustPush(t) + want, _ := os.ReadFile(filepath.Join(f.src, "big.bin")) + if f.readDest(t, "big.bin") != string(want) { + t.Fatal("the push after the index did not land the drifted bytes") + } + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) + }) + } +} + +// TestNativeContentNeverFollowsASymlinkAtAnArtifactName: a symlink where +// an object, or the objects directory, should be is never followed or +// replaced: the artifact fails, nothing is recorded for it, and nothing is +// written where the symlink points. +func TestNativeContentNeverFollowsASymlinkAtAnArtifactName(t *testing.T) { + for _, b := range contentBackends { + for _, at := range []string{"object", "objects directory"} { + t.Run(b.name+"/"+at, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + outside := outsideDir(t) + link, target := f.objectPath("alpha"), filepath.Join(outside, "precious.txt") + if at == "objects directory" { + link, target = filepath.Dir(link), outside + } else if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + if rep, err := f.push(t, Options{}); err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v, want the object refused", rep.Status, err) + } + checkUntouched(t, outside) + if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatalf("the symlink was replaced: %v, %v", fi, err) + } + if _, ok := f.remoteObject(t, "alpha"); ok { + t.Fatal("the refused object was recorded") + } + }) + } + } +} + +// TestNativeContentSourceDriftWhileStreaming: a content layout refuses an +// object whose source changed while it streamed; nothing lands at the +// object's name. +func TestNativeContentSourceDriftWhileStreaming(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + body := strings.Repeat("0123456789abcdef", 256<<10) + f.write(t, "big.bin", body) + f.index(t) + rep, err := f.pushVia(t, func(tr transport) transport { + return driftingTransport{transport: tr, src: filepath.Join(f.src, "big.bin")} + }) + if err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v, want the drifted object refused", rep.Status, err) + } + if _, err := os.Stat(f.objectPath(body)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("drifted bytes reached the object's name: %v", err) + } + if _, ok := f.remoteObject(t, body); ok { + t.Fatal("the drifted object was recorded") + } + }) + } +} diff --git a/sync/mirror_live.go b/sync/mirror_live.go new file mode 100644 index 0000000..5435160 --- /dev/null +++ b/sync/mirror_live.go @@ -0,0 +1,71 @@ +package sync + +import ( + "github.com/mbertschler/squirrel/store" +) + +// liveRecords is the live records a push keeps current, by path, with a +// count of the records below every directory as the destination resolves +// names. Asking what lies below a path that holds nothing — every new +// path of a push asks — costs one lookup, so a push stays linear in the +// paths it writes. The writer's lock guards it. +type liveRecords struct { + fold nameFolding + byPath map[string]store.RemotePath + below map[string]int +} + +func newLiveRecords(fold nameFolding, rows map[string]store.RemotePath) *liveRecords { + l := &liveRecords{fold: fold, byPath: make(map[string]store.RemotePath, len(rows)), below: map[string]int{}} + for _, r := range rows { + l.set(r) + } + return l +} + +func (l *liveRecords) at(rel string) (store.RemotePath, bool) { + r, ok := l.byPath[rel] + return r, ok +} + +// set records r as the live record at its path. +func (l *liveRecords) set(r store.RemotePath) { + l.remove(r.Path) + l.byPath[r.Path] = r + l.countAncestors(r.Path, 1) +} + +func (l *liveRecords) remove(rel string) { + if _, ok := l.byPath[rel]; !ok { + return + } + delete(l.byPath, rel) + l.countAncestors(rel, -1) +} + +// under is every live record below dir. +func (l *liveRecords) under(dir string) []store.RemotePath { + if l.below[l.fold.key(dir)] == 0 { + return nil + } + var out []store.RemotePath + for rel, r := range l.byPath { + if l.fold.under(rel, dir) { + out = append(out, r) + } + } + return out +} + +// countAncestors adds by to the count of every directory above rel. +func (l *liveRecords) countAncestors(rel string, by int) { + key := l.fold.key(rel) + for i := range len(key) { + if key[i] != '/' { + continue + } + if l.below[key[:i]] += by; l.below[key[:i]] == 0 { + delete(l.below, key[:i]) + } + } +} diff --git a/sync/mirror_live_test.go b/sync/mirror_live_test.go new file mode 100644 index 0000000..c0c5ad1 --- /dev/null +++ b/sync/mirror_live_test.go @@ -0,0 +1,76 @@ +package sync + +import ( + "maps" + "math/rand/v2" + "slices" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +// TestLiveRecordsMatchAScan: through random sets and removes, on a +// destination that folds names and one that doesn't, under always returns +// what a scan of every record returns, and the counts that let it answer +// in one lookup always match a recount. +func TestLiveRecordsMatchAScan(t *testing.T) { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + rng := rand.New(rand.NewPCG(7, 7)) + randomPath := func() string { + elems := make([]string, 1+rng.IntN(3)) + for i := range elems { + elems[i] = []string{"a", "A", "b", "é", "é"}[rng.IntN(5)] + } + return strings.Join(elems, "/") + } + l := newLiveRecords(fold, map[string]store.RemotePath{"a/b": {Path: "a/b"}, "b": {Path: "b"}}) + for step := range 2000 { + if p := randomPath(); rng.IntN(3) == 0 { + l.remove(p) + } else { + l.set(store.RemotePath{Path: p, ID: int64(step)}) + } + dir := randomPath() + if got, want := sortedPaths(l.under(dir)), scanUnder(l, dir); !slices.Equal(got, want) { + t.Fatalf("folds=%v step %d: under(%q) = %v, want %v", fold.folds(), step, dir, got, want) + } + } + if want := recountBelow(l); !maps.Equal(l.below, want) { + t.Fatalf("folds=%v: counts = %v, want %v", fold.folds(), l.below, want) + } + } +} + +func sortedPaths(rs []store.RemotePath) []string { + out := make([]string, 0, len(rs)) + for _, r := range rs { + out = append(out, r.Path) + } + slices.Sort(out) + return out +} + +func scanUnder(l *liveRecords, dir string) []string { + out := []string{} + for rel := range l.byPath { + if l.fold.under(rel, dir) { + out = append(out, rel) + } + } + slices.Sort(out) + return out +} + +func recountBelow(l *liveRecords) map[string]int { + out := map[string]int{} + for rel := range l.byPath { + key := l.fold.key(rel) + for i := range len(key) { + if key[i] == '/' { + out[key[:i]]++ + } + } + } + return out +} diff --git a/sync/mirror_model_test.go b/sync/mirror_model_test.go new file mode 100644 index 0000000..c509e32 --- /dev/null +++ b/sync/mirror_model_test.go @@ -0,0 +1,389 @@ +package sync + +import ( + "encoding/hex" + "fmt" + "io/fs" + "math/rand/v2" + "os" + "path" + "path/filepath" + "slices" + "strings" + "testing" + "time" + "unicode" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/store" +) + +// mirrorModel is the reference a native mirror is checked against: the +// source's present files, and the live tree a clean push leaves on the +// destination. A destination keeps what the source deleted, until a +// present path needs its name. +type mirrorModel struct { + fold nameFolding + present map[string]string // source path → body + dest map[string]string // destination path → body +} + +// push applies one push to the model: every present path, except the +// refused ones, lands, and every other entry whose name it needs — the same +// name under another spelling, a file where its directory goes, or a +// directory where it goes — moves into history. +func (m *mirrorModel) push(refused map[string]bool) { + for _, p := range sortedKeys(m.present) { + if refused[p] { + continue + } + for q := range m.dest { + if q != p && m.conflicts(p, q) { + delete(m.dest, q) + } + } + m.dest[p] = m.present[p] + } +} + +func (m *mirrorModel) conflicts(p, q string) bool { + kp, kq := m.fold.key(p), m.fold.key(q) + return kp == kq || strings.HasPrefix(kp, kq+"/") || strings.HasPrefix(kq, kp+"/") +} + +func sortedKeys(m map[string]string) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + slices.Sort(keys) + return keys +} + +// modelRun drives one random history against a mirror fixture and its +// model. +type modelRun struct { + t *testing.T + f *mirrorFixture + m *mirrorModel + rng *rand.Rand + step int + clock time.Time +} + +// sourceFolding is how the generator keeps the source free of spellings +// any destination would fold together, whatever this machine's disk does. +var sourceFolding = caseAndNormFolding + +// TestMirrorModel runs random histories — adds, changes, deletes, re-adds, +// file↔directory swaps, nested, renames that change only case, and on a +// folding destination names that collide — through a native mirror +// writing several paths at once, each push preceded now and then by one +// that crashes or loses power at a random transport call. After every +// clean push the destination's live records and its tree match the +// reference model, and the three invariants hold. +func TestMirrorModel(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + for seed := uint64(1); seed <= 3; seed++ { + t.Run(fmt.Sprintf("%s/folds=%v/seed=%d", b.name, fold.folds(), seed), func(t *testing.T) { + t.Parallel() + f := setupMirrorFixtureOn(t, b) + f.fold = fold + disk := diskFolding(t, f.dst) + r := &modelRun{t: t, f: f, rng: rand.New(rand.NewPCG(seed, seed)), clock: time.Unix(1_700_000_000, 0), + m: &mirrorModel{ + fold: nameFolding{caseless: fold.caseless || disk.caseless, normless: fold.normless || disk.normless}, + present: map[string]string{}, dest: map[string]string{}, + }} + for r.step = 0; r.step < 25; r.step++ { + r.changeSource() + r.push() + } + }) + } + } + } +} + +// changeSource applies one to three random changes to the source. +func (r *modelRun) changeSource() { + for range 1 + r.rng.IntN(3) { + switch r.rng.IntN(10) { + case 0, 1, 2, 3: + r.write(r.randomPath()) + case 4, 5: + if p, ok := r.pickPresent(); ok { + r.write(p) + } + case 6, 7: + if p, ok := r.pickPresent(); ok { + r.remove(p) + } + case 8: + if p, ok := r.pickGone(); ok { + r.write(p) + } + case 9: + r.renameCase() + } + } +} + +func (r *modelRun) randomPath() string { + elems := make([]string, 1+r.rng.IntN(3)) + for i := range elems { + elems[i] = string(rune('a' + r.rng.IntN(3))) + } + return strings.Join(elems, "/") +} + +func (r *modelRun) pickPresent() (string, bool) { + keys := sortedKeys(r.m.present) + if len(keys) == 0 { + return "", false + } + return keys[r.rng.IntN(len(keys))], true +} + +// pickGone picks a path the destination still holds that the source no +// longer has. +func (r *modelRun) pickGone() (string, bool) { + var gone []string + for _, p := range sortedKeys(r.m.dest) { + if _, ok := r.m.present[p]; !ok { + gone = append(gone, p) + } + } + if len(gone) == 0 { + return "", false + } + return gone[r.rng.IntN(len(gone))], true +} + +// write puts a new body at p, spelled as the source already spells its +// existing parts, first removing a file where p's directory goes and a +// directory where p goes: the file↔directory swaps. +func (r *modelRun) write(p string) { + p = foldingTransport{disk: r.f.src, fold: sourceFolding}.resolve(p) + for q := range r.m.present { + if strings.HasPrefix(p, q+"/") || strings.HasPrefix(q, p+"/") { + delete(r.m.present, q) + } + } + parts := strings.Split(p, "/") + for i := 1; i <= len(parts); i++ { + at := filepath.Join(r.f.src, filepath.FromSlash(strings.Join(parts[:i], "/"))) + if fi, err := os.Lstat(at); err == nil && (i < len(parts)) != fi.IsDir() { + if err := os.RemoveAll(at); err != nil { + r.t.Fatal(err) + } + } + } + body := fmt.Sprintf("%s at step %d %s", p, r.step, strings.Repeat("x", r.rng.IntN(40))) + r.f.write(r.t, p, body) + r.touch(p) + r.m.present[p] = body +} + +// touch gives p an mtime of its own, so the index sees every change. +func (r *modelRun) touch(p string) { + r.clock = r.clock.Add(time.Second) + if err := os.Chtimes(filepath.Join(r.f.src, filepath.FromSlash(p)), r.clock, r.clock); err != nil { + r.t.Fatal(err) + } +} + +func (r *modelRun) remove(p string) { + if err := os.Remove(filepath.Join(r.f.src, filepath.FromSlash(p))); err != nil { + r.t.Fatal(err) + } + delete(r.m.present, p) +} + +// renameCase renames one element of a present path — the file, or a +// directory above it — to its other case, when no other present path +// would fold onto the new spelling. +func (r *modelRun) renameCase() { + p, ok := r.pickPresent() + if !ok { + return + } + parts := strings.Split(p, "/") + i := r.rng.IntN(len(parts)) + from := strings.Join(parts[:i+1], "/") + parts[i] = otherCase(parts[i]) + to := strings.Join(parts[:i+1], "/") + moved := map[string]string{} + for q, body := range r.m.present { + switch { + case q == from || strings.HasPrefix(q, from+"/"): + moved[to+strings.TrimPrefix(q, from)] = body + case sourceFolding.key(q) == sourceFolding.key(to) || sourceFolding.under(q, to): + return + } + } + if err := os.Rename(filepath.Join(r.f.src, filepath.FromSlash(from)), filepath.Join(r.f.src, filepath.FromSlash(to))); err != nil { + r.t.Fatal(err) + } + for q := range r.m.present { + if q == from || strings.HasPrefix(q, from+"/") { + delete(r.m.present, q) + } + } + for q, body := range moved { + r.m.present[q] = body + } +} + +func otherCase(s string) string { + rs := []rune(s) + if unicode.IsUpper(rs[0]) { + rs[0] = unicode.ToLower(rs[0]) + } else { + rs[0] = unicode.ToUpper(rs[0]) + } + return string(rs) +} + +// push indexes the source, sometimes pushes once with a crash at a random +// transport call, then pushes cleanly and checks the destination against +// the model. On a folding destination it sometimes records, after the +// index, a second spelling of a file the destination holds: that push +// refuses the second spelling and fails, and the next index drops it, +// since no source file holds it. +func (r *modelRun) push() { + t, f := r.t, r.f + f.index(t) + before := f.contentHashes(t) + if r.m.fold.folds() && r.rng.IntN(6) == 0 { + if r.collide() { + return + } + } + if r.rng.IntN(3) == 0 { + r.crashingPush() + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + } + rep, err := f.push(t, Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("step %d: push: status=%q err=%v warnings=%v", r.step, rep.Status, err, rep.Warnings) + } + r.m.push(nil) + f.checkInvariants(t, before) + r.checkAgainstModel() +} + +// crashingPush pushes once with a crash at a random transport call: the +// process dies, or half the time the power goes, keeping a random oldest +// part of what no Flush covered. +func (r *modelRun) crashingPush() { + at := crashAtCall(r.rng.IntN(60)) + if r.rng.IntN(2) == 0 { + mode := []crashMode{crashBefore, crashAfter, crashMidway}[r.rng.IntN(3)] + _, _ = r.f.pushCrashing(r.t, at, mode) + return + } + seed := r.rng.Uint64() + keep := func(n int) int { return rand.New(rand.NewPCG(seed, seed)).IntN(n + 1) } + _, _ = r.f.pushCuttingPower(r.t, at, powerCutModes[r.rng.IntN(2)], keep) +} + +// collide records another spelling of a file the destination holds as +// present and pushes: the push refuses that spelling alone and fails. +func (r *modelRun) collide() bool { + var held []string + for _, p := range sortedKeys(r.m.present) { + if r.m.dest[p] == r.m.present[p] { + held = append(held, p) + } + } + if len(held) == 0 { + return false + } + p := held[r.rng.IntN(len(held))] + variant := path.Join(path.Dir(p), otherCase(path.Base(p))) + r.f.observe(r.t, variant, "a spelling the destination cannot hold") + before := r.f.contentHashes(r.t) + rep, err := r.f.push(r.t, Options{}) + if err == nil || !warned(rep, variant+" is not written") { + r.t.Fatalf("step %d: push with %s beside %s: err=%v warnings=%v, want %s refused", r.step, variant, p, err, rep.Warnings, variant) + } + r.m.push(map[string]bool{variant: true}) + r.f.checkRecordsVouch(r.t) + r.f.checkOnlyGrew(r.t, before) + return true +} + +// checkAgainstModel compares the live records and the destination's tree +// with the model, name by name as the destination resolves names. +func (r *modelRun) checkAgainstModel() { + t, f := r.t, r.f + want := map[string]string{} + for p, body := range r.m.dest { + want[r.m.fold.key(p)] = p + " " + bodyHash(body) + } + live := map[string]string{} + volID := f.volumeID(t) + for _, row := range f.rows(t) { + if row.State == store.RemotePathLive { + live[r.m.fold.key(row.Path)] = row.Path + " " + f.contentHashOf(t, volID, row) + } + } + if !mapsEqual(live, want) { + t.Fatalf("step %d: live records = %v, want %v", r.step, live, want) + } + tree := r.destTree() + for k, v := range want { + if got := tree[k]; got != strings.SplitN(v, " ", 2)[1] { + t.Errorf("step %d: destination holds %q at %s, want %s", r.step, got, v, bodyHash(r.m.dest[strings.SplitN(v, " ", 2)[0]])) + } + } + if len(tree) != len(want) { + t.Fatalf("step %d: destination tree = %v, want %v", r.step, tree, want) + } +} + +// destTree is the hash of every file in the volume's mirrored tree, keyed +// by folded name, outside the reserved directories and the marker. +func (r *modelRun) destTree() map[string]string { + root := filepath.Join(r.f.dst, "pics") + out := map[string]string{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + rel = filepath.ToSlash(rel) + if d.IsDir() && isReservedFolderPath(rel) { + return filepath.SkipDir + } + if d.Type().IsRegular() && rel != ".squirrel-volume" { + out[r.m.fold.key(rel)] = hashOnDisk(p) + } + return nil + }) + if err != nil { + r.t.Fatal(err) + } + return out +} + +func bodyHash(body string) string { + sum := blake3.Sum256([]byte(body)) + return hex.EncodeToString(sum[:]) +} + +func mapsEqual(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if b[k] != v { + return false + } + } + return true +} diff --git a/sync/mirror_reconcile.go b/sync/mirror_reconcile.go new file mode 100644 index 0000000..422bf75 --- /dev/null +++ b/sync/mirror_reconcile.go @@ -0,0 +1,161 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io/fs" + "path" + + "github.com/mbertschler/squirrel/store" +) + +// reconcile settles, once at push start, every move an earlier push +// recorded but may not have finished, deciding each from where the bytes +// actually are, then removes the staging finished runs left behind. The +// earlier push may have stopped before flushing its moves, so the +// directories they touched are flushed before any settlement is recorded. +func (h *mirrorHandler) reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error { + tr, err := h.root(ctx, runID) + if err != nil { + return err + } + rows, err := h.store.ListUnsettledRemotePaths(ctx, h.dest.Name, volumeID) + if err != nil { + return fmt.Errorf("list unsettled mirror paths on %q: %w", h.dest.Name, err) + } + settlements := make([]settlement, len(rows)) + var dirs []string + for i, r := range rows { + if settlements[i], err = h.settle(ctx, tr, r); err != nil { + return fmt.Errorf("reconcile %s on %q: %w", r.Path, h.dest.Name, err) + } + dirs = append(dirs, h.movedThrough(r)...) + } + if len(rows) > 0 { + if err := tr.Flush(ctx, dirs...); err != nil { + return fmt.Errorf("flush the moves an earlier push left in flight on %q: %w", h.dest.Name, err) + } + } + for i, r := range rows { + if err := h.recordSettlement(ctx, r, settlements[i]); err != nil { + return fmt.Errorf("reconcile %s on %q: %w", r.Path, h.dest.Name, err) + } + } + return h.clearFinishedStaging(ctx, rep, tr) +} + +// movedThrough is every directory along the two places an unsettled +// row's version can be: the rename that moved it may have moved a +// directory above it. +func (h *mirrorHandler) movedThrough(r store.RemotePath) []string { + other := stagingName(h.vol.Name, r.WrittenRunID, stagingKey(r.Path)) + if r.State == store.RemotePathDisplacing { + other = historyName(h.vol.Name, r.DisplacedRunID.Int64, r.Path) + } + return append(ancestors(h.liveName(r.Path)), ancestors(other)...) +} + +// ancestors is every directory above name, below the root. +func ancestors(name string) []string { + var out []string + for d := path.Dir(name); d != "."; d = path.Dir(d) { + out = append(out, d) + } + return out +} + +// settlement is how reconcile resolves one unsettled row. +type settlement int + +const ( + settleLive settlement = iota + settleDisplaced + settleLost + settleNothing +) + +// settle looks at both places an unsettled row's version can be and +// decides where it is. +func (h *mirrorHandler) settle(ctx context.Context, tr transport, r store.RemotePath) (settlement, error) { + at, err := statMatch(ctx, tr, h.liveName(r.Path), r) + if err != nil { + return settleNothing, err + } + switch r.State { + case store.RemotePathCommitting: + staged, err := present(ctx, tr, stagingName(h.vol.Name, r.WrittenRunID, stagingKey(r.Path))) + if err != nil { + return settleNothing, err + } + return settleCommitting(staged, at), nil + case store.RemotePathDisplacing: + inHistory, err := statMatch(ctx, tr, historyName(h.vol.Name, r.DisplacedRunID.Int64, r.Path), r) + if err != nil { + return settleNothing, err + } + return settleDisplacing(inHistory, at), nil + default: + return settleNothing, nil + } +} + +// settleCommitting decides a committing row: its version is live once the +// staged file is gone and the path holds the recorded version. Otherwise +// the commit never happened, so the intent is withdrawn — the path stays +// in the delta, since no receipt sealed the run, and is planned again. +func settleCommitting(staged, atPath bool) settlement { + if !staged && atPath { + return settleLive + } + return settleLost +} + +// settleDisplacing decides a displacing row: displaced once history holds +// the version, back to live while the path still holds it, lost when +// neither does. +func settleDisplacing(inHistory, atPath bool) settlement { + switch { + case inHistory: + return settleDisplaced + case atPath: + return settleLive + default: + return settleLost + } +} + +func (h *mirrorHandler) recordSettlement(ctx context.Context, r store.RemotePath, s settlement) error { + switch { + case s == settleNothing: + return nil + case s == settleLost: + return h.store.MarkRemotePathsLost(ctx, r.ID) + case r.State == store.RemotePathCommitting: + return h.store.ConfirmRemotePathsLive(ctx, r.ID) + case s == settleDisplaced: + return h.store.ConfirmRemotePathsDisplaced(ctx, r.ID) + default: + return h.store.RevertRemotePathsLive(ctx, r.ID) + } +} + +// statMatch reports whether name holds the version r records. +func statMatch(ctx context.Context, tr transport, name string, r store.RemotePath) (bool, error) { + e, err := tr.Stat(ctx, name) + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir) { + return false, nil + } + if err != nil { + return false, err + } + return matchesRecord(e, r), nil +} + +func present(ctx context.Context, tr transport, name string) (bool, error) { + _, err := tr.Stat(ctx, name) + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir) { + return false, nil + } + return err == nil, err +} diff --git a/sync/mirror_sftp_test.go b/sync/mirror_sftp_test.go new file mode 100644 index 0000000..723c515 --- /dev/null +++ b/sync/mirror_sftp_test.go @@ -0,0 +1,88 @@ +package sync + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// TestMirrorPushOverSFTP: a plain sftp mirror pushes natively with no +// rclone wrapper. --init writes the marker through the transport, a +// changed path moves its prior version into history, and every run +// leaves its receipt. Nothing is read back, so no row records a +// fingerprint and the vector stays presence+size. +func TestMirrorPushOverSFTP(t *testing.T) { + f := setupMirrorFixtureOn(t, sftpBackend) + if err := os.Remove(filepath.Join(f.dst, "pics", volmark.MarkerName)); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "v1") + f.write(t, "2024/cat.jpg", "meow") + f.index(t) + + if _, err := f.push(t, Options{}); !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "--init") { + t.Fatalf("push onto a root with no marker = %v, want a refusal naming --init", err) + } + first, err := f.push(t, Options{Init: true}) + if err != nil || first.Status != store.RunStatusSuccess { + t.Fatalf("--init push: status=%q err=%v", first.Status, err) + } + if err := volmark.Validate(filepath.Join(f.dst, "pics"), "pics"); err != nil { + t.Fatalf("marker after --init: %v", err) + } + f.write(t, "a.txt", "v2") + f.index(t) + second := f.mustPush(t) + + if f.readDest(t, "a.txt") != "v2" || f.readDest(t, "2024/cat.jpg") != "meow" { + t.Fatal("destination bytes differ from the source") + } + if got := f.readDest(t, historyName("", second.RunID, "a.txt")); got != "v1" { + t.Fatalf("history holds %q, want the displaced v1", got) + } + for _, rep := range []Report{first, second} { + if _, err := os.Stat(f.dest(IndexDirName + "/run-" + strconv.FormatInt(rep.RunID, 10))); err != nil { + t.Fatalf("receipt of run %d: %v", rep.RunID, err) + } + } + f.checkInvariants(t, nil) + for _, r := range f.rows(t) { + if r.Checksum.Valid { + t.Fatalf("%s row = %+v, want no fingerprint over sftp", r.Path, r) + } + } + if comps := volumeComponents(t, f.store, "pics", "usb"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { + t.Fatalf("vector = %+v, want one presence+size component", comps) + } +} + +// TestMirrorOverSFTPRefusesAnUnknownHost: a server whose host key +// known_hosts does not pin never receives a byte, and the refusal is +// recorded as its own run. +func TestMirrorOverSFTPRefusesAnUnknownHost(t *testing.T) { + f := setupMirrorFixtureOn(t, sftpBackend) + empty := filepath.Join(t.TempDir(), "known_hosts") + if err := os.WriteFile(empty, nil, 0o600); err != nil { + t.Fatal(err) + } + f.pair.Destination.Params["known_hosts_file"] = empty + f.write(t, "a.txt", "alpha") + f.index(t) + + rep, err := f.push(t, Options{Init: true}) + if !errors.Is(err, errUnknownHostKey) || rep.Status != store.RunStatusRefused { + t.Fatalf("push to an unknown host: status=%q err=%v, want a refused run", rep.Status, err) + } + if _, err := os.Stat(f.dest("a.txt")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a.txt reached the unknown host: %v", err) + } + if runs := mustListSyncRuns(t, f.store); len(runs) != 1 || runs[0].Status != store.RunStatusRefused { + t.Fatalf("runs = %+v, want the one refused run", runs) + } +} diff --git a/sync/mirror_snapshot_test.go b/sync/mirror_snapshot_test.go new file mode 100644 index 0000000..63b34b1 --- /dev/null +++ b/sync/mirror_snapshot_test.go @@ -0,0 +1,171 @@ +package sync + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// TestMirrorRideAlongThroughTheTransport: a native mirror's ride-along +// index snapshot lands in /.squirrel-index/ through the transport, +// on both backends, and rotation removes only the oldest snapshots, +// leaving every receipt in place. +func TestMirrorRideAlongThroughTheTransport(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + var runs []int64 + for i := range 3 { + f.write(t, "a.txt", strings.Repeat("v", i+1)) + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 2}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push %d: err=%v snapshot=%v", i, err, rep.SnapshotErr) + } + runs = append(runs, rep.RunID) + } + entries, err := os.ReadDir(f.dest(IndexDirName)) + if err != nil { + t.Fatal(err) + } + var snaps, receipts []string + for _, e := range entries { + if isSnapshotName(e.Name()) { + snaps = append(snaps, e.Name()) + } else { + receipts = append(receipts, e.Name()) + } + } + if len(snaps) != 2 || !strings.HasSuffix(snaps[1], "-run-"+strconv.FormatInt(runs[2], 10)+".db") { + t.Fatalf("snapshots = %v, want the newest two", snaps) + } + if len(receipts) != 3 { + t.Fatalf("receipts = %v, want one per run", receipts) + } + }) + } +} + +// TestRecoverFindsAMirrorsSnapshots: recover's discovery lists a native +// mirror's ride-along snapshots and fetches one through the transport, +// with no rclone wrapper, on both backends. +func TestRecoverFindsAMirrorsSnapshots(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push: err=%v snapshot=%v", err, rep.SnapshotErr) + } + ctx := context.Background() + snaps, err := DiscoverIndexSnapshots(ctx, nil, f.pair.Destination, []string{"pics", "never-synced"}) + if err != nil || len(snaps) != 1 || snaps[0].RunID != rep.RunID { + t.Fatalf("discovery = %+v, %v; want run %d's snapshot", snaps, err, rep.RunID) + } + local := filepath.Join(t.TempDir(), snaps[0].Name) + if err := FetchIndexSnapshot(ctx, nil, f.pair.Destination, snaps[0], local); err != nil { + t.Fatalf("fetch: %v", err) + } + if fileHash(t, local) != fileHash(t, f.dest(IndexDirName+"/"+snaps[0].Name)) { + t.Fatal("the fetched snapshot differs from the one on the destination") + } + }) + } +} + +// partialPuts lands one byte of every Put whose name matches, then fails +// it, while every other call works on. +type partialPuts struct { + transport + match func(name string) bool +} + +func (p partialPuts) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if !p.match(name) { + return p.transport.Put(ctx, name, r, mtime) + } + if err := p.transport.Put(ctx, name, io.LimitReader(r, 1), mtime); err != nil { + return err + } + return errors.New("the link dropped") +} + +// withPartialPuts makes the fixture's handler land only one byte of every +// Put whose name match selects. +func (f *mirrorFixture) withPartialPuts(t *testing.T, match func(name string) bool) *mirrorHandler { + t.Helper() + h := f.handler(t) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return partialPuts{transport: raw, match: match}, err + } + return h +} + +// TestMirrorRideAlongLeavesNoPartialSnapshot: a snapshot upload that fails +// halfway leaves nothing in .squirrel-index/, so recovery never offers a +// truncated snapshot as the newest — even when the link is gone and +// nothing could be cleaned up. The push itself still succeeds, and the +// partial copy goes with its run's staging at the next push. +func TestMirrorRideAlongLeavesNoPartialSnapshot(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + h := f.withPartialPuts(t, func(name string) bool { return strings.Contains(name, StagingDirName+"/") }) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + rep, err := h.Push(context.Background(), Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr == nil { + t.Fatalf("push: err=%v snapshot=%v, want a successful push reporting the failed ride-along", err, rep.SnapshotErr) + } + entries, err := os.ReadDir(f.dest(IndexDirName)) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if isSnapshotName(e.Name()) { + t.Fatalf("the partial snapshot %s reached .squirrel-index", e.Name()) + } + } + clean := f.mustPush(t) + f.checkStagingEmpty(t, clean.RunID) +} + +// TestMirrorMarkerWriteIsAllOrNothing: an --init whose marker write fails +// halfway leaves no marker that does not parse, so the next --init +// succeeds. +func TestMirrorMarkerWriteIsAllOrNothing(t *testing.T) { + f := setupMirrorFixture(t) + if err := os.Remove(f.dest(volmark.MarkerName)); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + h := f.withPartialPuts(t, func(name string) bool { return name == markerStagingName("pics") }) + if _, err := h.Push(context.Background(), Options{Init: true}); err == nil { + t.Fatal("an --init whose marker write failed succeeded") + } + if _, err := os.Stat(f.dest(volmark.MarkerName)); !os.IsNotExist(err) { + t.Fatalf("a failed marker write left a marker behind: %v", err) + } + if rep, err := f.push(t, Options{Init: true}); err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("the next --init: status=%q err=%v", rep.Status, err) + } + if err := volmark.Validate(f.dest(""), "pics"); err != nil { + t.Fatalf("marker after the retried --init: %v", err) + } +} diff --git a/sync/mirror_test.go b/sync/mirror_test.go new file mode 100644 index 0000000..0399f17 --- /dev/null +++ b/sync/mirror_test.go @@ -0,0 +1,1087 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "net" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/index" + "github.com/mbertschler/squirrel/runevents" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// mirrorFixture is one volume, "pics", mirrored to a native destination, +// "usb", with the destination's volume marker in place. The destination +// is a local directory unless the fixture is set up on another backend. +type mirrorFixture struct { + store *store.Store + pair Pair + src string // the volume's source directory + dst string // the destination root + // fold, when it folds, makes the destination resolve names as a disk + // that folds them does, whatever this machine's disk does. + fold nameFolding +} + +// mirrorBackend is where a mirror fixture's destination lives: its name, +// and the settings of a destination rooted at dst on it. +type mirrorBackend struct { + name string + settings func(t *testing.T, dst string) string +} + +var ( + localBackend = mirrorBackend{"local", func(_ *testing.T, dst string) string { + return fmt.Sprintf("type = \"local\"\nroot = %q\n", dst) + }} + // sftpBackend serves the destination root from an in-process sftp + // server, so the fixture reads what landed straight off the disk. + sftpBackend = mirrorBackend{"sftp", func(t *testing.T, dst string) string { + return sftpSettings(t, dst, nil) + }} + mirrorBackends = []mirrorBackend{localBackend, sftpBackend} +) + +// sftpSettings are the settings of a destination rooted at dst on a fresh +// in-process sftp server that runs the given hash commands. +func sftpSettings(t *testing.T, dst string, commands map[string]string) string { + t.Helper() + srv := startSFTPServer(t) + srv.runsHashCommands(commands) + host, port, _ := net.SplitHostPort(srv.addr) + return fmt.Sprintf("type = \"sftp\"\nroot = %q\nhost = %q\nport = %q\nuser = \"u\"\npassword = \"p\"\nknown_hosts_file = %q\n", + dst, host, port, srv.knownHosts(t, srv.hostKeys[0].PublicKey())) +} + +func setupMirrorFixture(t *testing.T) *mirrorFixture { + t.Helper() + return setupMirrorFixtureOn(t, localBackend) +} + +func setupMirrorFixtureOn(t *testing.T, b mirrorBackend) *mirrorFixture { + t.Helper() + root := t.TempDir() + f := &mirrorFixture{src: filepath.Join(root, "src"), dst: filepath.Join(root, "usb")} + for _, d := range []string{f.src, filepath.Join(f.dst, "pics")} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + if err := volmark.Write(filepath.Join(f.dst, "pics"), volmark.Marker{Volume: "pics"}); err != nil { + t.Fatalf("seed marker: %v", err) + } + s, err := store.Open(filepath.Join(root, "test.db")) + if err != nil { + t.Fatalf("store.Open: %v", err) + } + t.Cleanup(func() { s.Close() }) + f.store = s + cfgPath := filepath.Join(root, "config.toml") + body := "[destinations.usb]\n" + b.settings(t, f.dst) + "\n" + + "[volumes.pics]\npath = \"" + f.src + "\"\nsync_to = [\"usb\"]\n" + if err := os.WriteFile(cfgPath, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(cfgPath) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + f.pair = Pair{Volume: cfg.Volumes["pics"], Destination: cfg.Destinations["usb"]} + return f +} + +func (f *mirrorFixture) write(t *testing.T, rel, body string) { + t.Helper() + p := filepath.Join(f.src, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func (f *mirrorFixture) index(t *testing.T) { + t.Helper() + if _, err := index.Index(context.Background(), f.store, f.src, index.Options{Name: "pics"}); err != nil { + t.Fatalf("index: %v", err) + } +} + +// push runs one push with no rclone wrapper at all. +func (f *mirrorFixture) push(t *testing.T, opts Options) (Report, error) { + t.Helper() + if !f.fold.folds() { + return RunPair(context.Background(), f.store, Tools{}, f.pair, opts) + } + return f.pushVia(t, opts, func(tr transport) transport { return tr }) +} + +// pushVia runs one push through wrap's transport, on top of the folding +// the fixture sets. +func (f *mirrorFixture) pushVia(t *testing.T, opts Options, wrap func(transport) transport) (Report, error) { + t.Helper() + h := f.handler(t) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + if err != nil { + return nil, err + } + if f.fold.folds() { + raw = foldingTransport{transport: raw, disk: f.dst, fold: f.fold} + } + return wrap(raw), nil + } + return h.Push(context.Background(), opts) +} + +func (f *mirrorFixture) mustPush(t *testing.T) Report { + t.Helper() + rep, err := f.push(t, Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return rep +} + +// pushCrashing runs one push whose transport crashes at the first call +// crashAt selects. +func (f *mirrorFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool, mode crashMode) (Report, error) { + t.Helper() + return f.pushVia(t, Options{}, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode} + }) +} + +// pushCuttingPower runs one push that loses power at the first call +// crashAt selects, before or after it as mode says, keeping the oldest +// keep(n) of the n calls no Flush covered. +func (f *mirrorFixture) pushCuttingPower(t *testing.T, crashAt func(transportCall) bool, mode crashMode, keep func(int) int) (Report, error) { + t.Helper() + return f.pushVia(t, Options{}, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode, powerCut: true, keep: keep} + }) +} + +// oneAtATime makes the fixture's pushes write one path at a time, so +// their transport calls come in the same order on every push. +func (f *mirrorFixture) oneAtATime() { f.pair.Destination.Concurrency = 1 } + +func (f *mirrorFixture) handler(t *testing.T) *mirrorHandler { + t.Helper() + h, err := HandlerFor(f.store, Tools{}, f.pair) + if err != nil { + t.Fatalf("HandlerFor: %v", err) + } + return h.(*mirrorHandler) +} + +func (f *mirrorFixture) volumeID(t *testing.T) int64 { + t.Helper() + v, err := f.store.GetVolumeByName(context.Background(), "pics") + if err != nil { + t.Fatalf("GetVolumeByName: %v", err) + } + return v.ID +} + +// dest is the path of rel under the destination's volume directory, as +// the destination resolves it. +func (f *mirrorFixture) dest(rel string) string { + return f.onDisk(path.Join("pics", rel)) +} + +// onDisk is where the destination keeps name, relative to its root. +func (f *mirrorFixture) onDisk(name string) string { + if f.fold.folds() { + name = foldingTransport{disk: f.dst, fold: f.fold}.resolve(name) + } + return filepath.Join(f.dst, filepath.FromSlash(name)) +} + +func (f *mirrorFixture) readDest(t *testing.T, rel string) string { + t.Helper() + b, err := os.ReadFile(f.dest(rel)) + if err != nil { + t.Fatalf("read destination %s: %v", rel, err) + } + return string(b) +} + +func (f *mirrorFixture) rows(t *testing.T) []store.RemotePath { + t.Helper() + rows, err := f.store.ListRemotePaths(context.Background(), "usb", f.volumeID(t)) + if err != nil { + t.Fatalf("ListRemotePaths: %v", err) + } + return rows +} + +// rowsAt returns the states of rel's rows, oldest first. +func (f *mirrorFixture) rowsAt(t *testing.T, rel string) []string { + t.Helper() + var states []string + for _, r := range f.rows(t) { + if r.Path == rel { + states = append(states, r.State) + } + } + return states +} + +// contentHashes collects the BLAKE3 of every file under the destination +// root outside staging: what invariant 2 says only grows. +func (f *mirrorFixture) contentHashes(t *testing.T) map[string]bool { + t.Helper() + return hashesOutsideStaging(t, f.dst) +} + +// hashesOutsideStaging collects the BLAKE3 of every file under root that +// is not in a .squirrel-staging directory. +func hashesOutsideStaging(t *testing.T, root string) map[string]bool { + t.Helper() + out := map[string]bool{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() && d.Name() == StagingDirName { + return filepath.SkipDir + } + if d.Type().IsRegular() { + out[fileHash(t, p)] = true + } + return nil + }) + if err != nil { + t.Fatalf("walk destination: %v", err) + } + return out +} + +func fileHash(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatalf("read %s: %v", p, err) + } + sum := blake3.Sum256(b) + return hex.EncodeToString(sum[:]) +} + +// checkInvariants asserts the design's three invariants after a clean +// push, given the content the destination held before it. +func (f *mirrorFixture) checkInvariants(t *testing.T, before map[string]bool) { + t.Helper() + liveContent := map[string]int64{} + for _, r := range f.checkRecordsVouch(t) { + switch r.State { + case store.RemotePathLive: + liveContent[r.Path] = r.ContentID + case store.RemotePathCommitting, store.RemotePathDisplacing: + t.Errorf("%s row %d is still %s after a clean push", r.Path, r.ID, r.State) + } + } + f.checkOnlyGrew(t, before) + present, err := f.store.ListPresentContent(context.Background(), f.volumeID(t)) + if err != nil { + t.Fatalf("ListPresentContent: %v", err) + } + for _, d := range present { + if liveContent[d.Path] != d.ContentID { + t.Errorf("present %s has no live row holding content %d", d.Path, d.ContentID) + } + } +} + +// checkRecordsVouch asserts invariant 1, which holds at every point of a +// push, a crashed one too: every live row's bytes are at its path, every +// displaced row's at its history path, and no two live rows name the one +// entry a folding destination holds. It returns the rows it checked. +// Rows at a path in changed, which the test itself changed behind +// squirrel's back, are left unchecked. +func (f *mirrorFixture) checkRecordsVouch(t *testing.T, changed ...string) []store.RemotePath { + t.Helper() + volID := f.volumeID(t) + disk := diskFolding(t, f.dst) + fold := nameFolding{caseless: f.fold.caseless || disk.caseless, normless: f.fold.normless || disk.normless} + liveAt := map[string]string{} + rows := f.rows(t) + for _, r := range rows { + if slices.Contains(changed, r.Path) { + continue + } + var at string + switch r.State { + case store.RemotePathLive: + if other, ok := liveAt[fold.key(r.Path)]; ok { + t.Errorf("live %s and %s name the one entry the destination holds there", r.Path, other) + } + liveAt[fold.key(r.Path)] = r.Path + at = f.dest(r.Path) + case store.RemotePathDisplaced: + at = f.onDisk(historyName("pics", r.DisplacedRunID.Int64, r.Path)) + default: + continue + } + if got, want := hashOnDisk(at), f.contentHashOf(t, volID, r); got != want { + t.Errorf("%s row for %s: %s holds %q, want %s", r.State, r.Path, at, got, want) + } + } + return rows +} + +// checkOnlyGrew asserts invariant 2: every content the destination held +// outside staging before is still there. +func (f *mirrorFixture) checkOnlyGrew(t *testing.T, before map[string]bool) { + t.Helper() + after := f.contentHashes(t) + for h := range before { + if !after[h] { + t.Errorf("content %s left the destination", h) + } + } +} + +// hashOnDisk is the hex BLAKE3 of the file at p, or why it has none. +func hashOnDisk(p string) string { + fi, err := os.Lstat(p) + if err != nil { + return err.Error() + } + if !fi.Mode().IsRegular() { + return "not a file: " + fi.Mode().String() + } + b, err := os.ReadFile(p) + if err != nil { + return err.Error() + } + sum := blake3.Sum256(b) + return hex.EncodeToString(sum[:]) +} + +func (f *mirrorFixture) contentHashOf(t *testing.T, volID int64, r store.RemotePath) string { + t.Helper() + hist, err := f.store.ListHistoryByPath(context.Background(), volID, r.Path) + if err != nil { + t.Fatalf("ListHistoryByPath %s: %v", r.Path, err) + } + for _, h := range hist { + if h.ContentID == r.ContentID { + return hex.EncodeToString(h.Blake3) + } + } + t.Fatalf("no files row holds content %d at %s", r.ContentID, r.Path) + return "" +} + +// TestMirrorPushWithoutRclone: a local mirror pushes through the native +// handler with no rclone wrapper, lands every present path with its bytes +// and mtime, records each one live with the BLAKE3 its read-back +// confirmed, writes the run's receipt, and advances the vector as +// fingerprint-verified. An unchanged second push writes nothing and still +// leaves a receipt. +func TestMirrorPushWithoutRclone(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.write(t, "2024/cat.jpg", "meow") + f.index(t) + + rep := f.mustPush(t) + if rep.RcloneResult.Transferred != 2 || rep.RcloneResult.Bytes != int64(len("alpha")+len("meow")) { + t.Fatalf("counters = %+v, want 2 paths, 9 bytes", rep.RcloneResult) + } + if f.readDest(t, "a.txt") != "alpha" || f.readDest(t, "2024/cat.jpg") != "meow" { + t.Fatal("destination bytes differ from the source") + } + srcInfo, _ := os.Stat(filepath.Join(f.src, "a.txt")) + dstInfo, _ := os.Stat(f.dest("a.txt")) + if !dstInfo.ModTime().Equal(srcInfo.ModTime()) { + t.Fatalf("mtime = %v, want the source's %v", dstInfo.ModTime(), srcInfo.ModTime()) + } + for _, rel := range []string{"a.txt", "2024/cat.jpg"} { + if got := f.rowsAt(t, rel); len(got) != 1 || got[0] != store.RemotePathLive { + t.Fatalf("%s rows = %v, want one live", rel, got) + } + } + for _, r := range f.rows(t) { + if r.Checksum.String != hex.EncodeToString(r.Blake3) { + t.Fatalf("%s row = %+v, want the read-back BLAKE3 recorded", r.Path, r) + } + } + if rep.Fingerprints != 2 { + t.Fatalf("fingerprints = %d, want one read-back per path", rep.Fingerprints) + } + delta, err := f.store.ListPathDeltaSince(context.Background(), f.volumeID(t), 0) + if err != nil { + t.Fatal(err) + } + want, _ := encodeManifestSegment(delta) + if got := f.readDest(t, ".squirrel-index/run-"+strconv.FormatInt(rep.RunID, 10)); got != string(want) { + t.Fatalf("receipt = %q, want the delta's manifest segment %q", got, want) + } + comps := volumeComponents(t, f.store, "pics", "usb") + if len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodFingerprint { + t.Fatalf("vector = %+v, want one fingerprint-verified component", comps) + } + run, err := f.store.GetRun(context.Background(), rep.RunID) + if err != nil || !run.Shallow.Valid || !run.Shallow.Bool { + t.Fatalf("run = %+v, %v; want recorded shallow", run, err) + } + + if rep.AlreadyCorrect != 0 { + t.Fatalf("first push already_correct = %d, want 0", rep.AlreadyCorrect) + } + again := f.mustPush(t) + if again.RcloneResult.Transferred != 0 || !again.Changed.Valid || again.Changed.Int64 != 0 || again.AlreadyCorrect != 2 { + t.Fatalf("unchanged push: counters=%+v changed=%+v already_correct=%d, want nothing written and both paths correct", again.RcloneResult, again.Changed, again.AlreadyCorrect) + } + if got := f.readDest(t, ".squirrel-index/run-"+strconv.FormatInt(again.RunID, 10)); got != "" { + t.Fatalf("unchanged push's receipt = %q, want empty", got) + } + f.checkInvariants(t, nil) +} + +// TestMirrorTranslationRules is the design's translation table, decided +// from squirrel's records alone. After one push, a changed path, an added +// one, a missing one and an offloaded one are re-planned against the full +// delta: only present paths produce an operation, and a path whose live +// record already holds its content is only confirmed. +func TestMirrorTranslationRules(t *testing.T) { + f := setupMirrorFixture(t) + for _, rel := range []string{"same.txt", "changed.txt", "gone.txt", "offloaded.txt", "lost.txt"} { + f.write(t, rel, "v1 "+rel) + } + f.index(t) + f.mustPush(t) + for _, r := range f.rows(t) { + if r.Path == "lost.txt" { + if err := f.store.MarkRemotePathsLost(context.Background(), r.ID); err != nil { + t.Fatal(err) + } + } + } + f.write(t, "changed.txt", "v2 changed") + f.write(t, "new.txt", "new") + if err := os.Remove(filepath.Join(f.src, "gone.txt")); err != nil { + t.Fatal(err) + } + f.index(t) + ctx := context.Background() + volID := f.volumeID(t) + off, err := f.store.GetByPath(ctx, volID, "offloaded.txt") + if err != nil { + t.Fatal(err) + } + if err := f.store.MarkOffloaded(ctx, volID, "offloaded.txt", off.ContentID, off.LastSeenRunID); err != nil { + t.Fatalf("MarkOffloaded: %v", err) + } + full, err := f.store.ListPathDeltaSince(ctx, volID, 0) + if err != nil { + t.Fatal(err) + } + var delta []store.PathDelta + for _, d := range full { + if d.Path != "lost.txt" { + delta = append(delta, d) + } + } + + ops, err := f.handler(t).translate(ctx, pushPlan{volumeID: volID, delta: delta}) + if err != nil { + t.Fatalf("translate: %v", err) + } + got := map[string]string{} + for _, p := range ops.paths { + got[p.delta.Path] = map[bool]string{true: "confirm", false: "write"}[p.current] + } + want := map[string]string{ + "same.txt": "confirm", // present, live record holds C + "changed.txt": "write", // present, live record holds other content + "new.txt": "write", // present, no live record + "lost.txt": "write", // repair: outside the delta, its record lost + // gone.txt (missing), offloaded.txt (offloaded) and changed.txt's + // superseded row produce nothing. + } + if len(got) != len(want) { + t.Fatalf("operations = %v, want %v", got, want) + } + for rel, op := range want { + if got[rel] != op { + t.Errorf("%s: %s, want %s", rel, got[rel], op) + } + } +} + +// TestMirrorWriteDisplacesWhatThePathHolds carries the translation table's +// destructive decisions to the disk: a recorded version moves into the +// run's history as its record, an entry squirrel never wrote moves there as +// unrecorded bytes with a warning and an audit note, and a path deleted at +// the source stays on the destination. +func TestMirrorWriteDisplacesWhatThePathHolds(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "changed.txt", "v1") + f.write(t, "gone.txt", "kept") + f.index(t) + f.mustPush(t) + f.write(t, "changed.txt", "v2") + f.write(t, "new.txt", "ours") + if err := os.Remove(filepath.Join(f.src, "gone.txt")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("new.txt"), []byte("foreign"), 0o644); err != nil { + t.Fatal(err) + } + f.index(t) + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := strconv.FormatInt(rep.RunID, 10) + if f.readDest(t, "changed.txt") != "v2" || f.readDest(t, ".squirrel-history/run-"+run+"/changed.txt") != "v1" { + t.Fatal("the recorded version did not move into this run's history") + } + if got := f.rowsAt(t, "changed.txt"); len(got) != 2 || got[0] != store.RemotePathDisplaced || got[1] != store.RemotePathLive { + t.Fatalf("changed.txt rows = %v, want displaced then live", got) + } + if f.readDest(t, "new.txt") != "ours" || f.readDest(t, ".squirrel-history/run-"+run+"/new.txt") != "foreign" { + t.Fatal("the foreign entry was not preserved in history") + } + if !warned(rep, "new.txt held bytes squirrel did not write") { + t.Fatalf("warnings = %v, want one about the foreign new.txt", rep.Warnings) + } + audit, err := f.store.ListRunAudit(context.Background(), rep.RunID) + if err != nil { + t.Fatal(err) + } + if !auditHas(audit, store.TransitionDisplaceUnrecorded, "new.txt") { + t.Fatalf("audit = %+v, want a displace-unrecorded note for new.txt", audit) + } + if f.readDest(t, "gone.txt") != "kept" { + t.Fatal("a path deleted at the source left the destination") + } + f.checkInvariants(t, before) +} + +// TestMirrorRecordChangedBehindSquirrelsBack: an already-correct path +// whose bytes changed on the destination loses its record, is displaced as +// unrecorded bytes, and is written again. The first push crashes before its +// receipt, so the next one re-plans every path. +func TestMirrorRecordChangedBehindSquirrelsBack(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "ours") + f.index(t) + if rep, err := f.pushCrashing(t, isReceiptPut, crashBefore); !crashedOn(rep, err) { + t.Fatalf("crashing push = %v, want the injected crash", err) + } + if err := os.WriteFile(f.dest("a.txt"), []byte("tampered"), 0o644); err != nil { + t.Fatal(err) + } + before := f.contentHashes(t) + + rep := f.mustPush(t) + if f.readDest(t, "a.txt") != "ours" { + t.Fatal("the tampered path was not written again") + } + if got := f.rowsAt(t, "a.txt"); len(got) != 2 || got[0] != store.RemotePathLost || got[1] != store.RemotePathLive { + t.Fatalf("a.txt rows = %v, want lost then live — never displaced", got) + } + if !warned(rep, "behind squirrel's back") { + t.Fatalf("warnings = %v, want one about the changed path", rep.Warnings) + } + f.checkInvariants(t, before) +} + +func warned(rep Report, substr string) bool { + for _, w := range rep.Warnings { + if strings.Contains(w, substr) { + return true + } + } + return false +} + +func auditHas(audit []store.RunAudit, transition, substr string) bool { + for _, a := range audit { + if a.Transition == transition && strings.Contains(a.Note.String, substr) { + return true + } + } + return false +} + +func isReceiptPut(c transportCall) bool { + return c.op == "put" && strings.Contains(c.name, IndexDirName+"/run-") +} + +// mirrorCrashCase is one row of the crash table: where the push dies, and +// what it leaves recorded. +type mirrorCrashCase struct { + name string + crashAt func(transportCall) bool + mode crashMode + // crashed is the changed path's rows after the crash, oldest first. + crashed []string + check func(t *testing.T, f *mirrorFixture, clean Report) +} + +// TestMirrorCrashTable is the design's crash table: a push that dies at +// each point of writing one changed path, then a clean push, on both +// transports. Each row pins what the crash leaves recorded and how +// reconcile settles it; afterwards the three invariants hold. +func TestMirrorCrashTable(t *testing.T) { + staged := func(c transportCall) bool { return strings.Contains(c.name, StagingDirName+"/run-") } + intoHistory := func(c transportCall) bool { return c.op == "rename" && strings.Contains(c.to, HistoryDirName+"/") } + commitRename := func(c transportCall) bool { return c.op == "rename" && staged(c) } + cases := []mirrorCrashCase{ + {"staging write", func(c transportCall) bool { return c.op == "put" && staged(c) }, crashMidway, + []string{store.RemotePathLive}, nil}, + {"displacing recorded", intoHistory, crashBefore, + []string{store.RemotePathDisplacing}, nil}, + {"displace rename", intoHistory, crashAfter, + []string{store.RemotePathDisplacing}, nil}, + {"committing recorded", commitRename, crashBefore, + []string{store.RemotePathDisplaced, store.RemotePathCommitting}, nil}, + {"commit rename", commitRename, crashAfter, + []string{store.RemotePathDisplaced, store.RemotePathCommitting}, nil}, + {"every write, before the seal", isReceiptPut, crashBefore, + []string{store.RemotePathDisplaced, store.RemotePathLive}, + func(t *testing.T, _ *mirrorFixture, clean Report) { + if clean.RcloneResult.Transferred != 0 || clean.RcloneResult.Checked != 1 || clean.AlreadyCorrect != 2 { + t.Fatalf("clean push counters = %+v already_correct=%d, want the planned path confirmed and both paths correct", clean.RcloneResult, clean.AlreadyCorrect) + } + }}, + } + for _, b := range mirrorBackends { + for _, c := range cases { + t.Run(b.name+"/"+c.name, func(t *testing.T) { + runCrashCase(t, setupMirrorFixtureOn(t, b), c) + }) + } + } +} + +func runCrashCase(t *testing.T, f *mirrorFixture, c mirrorCrashCase) { + f.write(t, "keep.txt", "untouched") + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2 is longer") + f.index(t) + before := f.contentHashes(t) + + if rep, err := f.pushCrashing(t, c.crashAt, c.mode); !crashedOn(rep, err) { + t.Fatalf("crashing push = %v (failures %+v), want the injected crash", err, rep.RcloneResult.FailedFiles) + } + if got := f.rowsAt(t, "a.txt"); !slicesEqual(got, c.crashed) { + t.Fatalf("rows after the crash = %v, want %v", got, c.crashed) + } + clean := f.mustPush(t) + if f.readDest(t, "a.txt") != "v2 is longer" { + t.Fatal("the clean push did not land the new version") + } + if c.check != nil { + c.check(t, f, clean) + } + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) +} + +// crashedOn reports whether a push failed on the injected crash, directly +// or on one of its paths. +func crashedOn(rep Report, err error) bool { + if errors.Is(err, errInjectedCrash) { + return true + } + for _, ff := range rep.RcloneResult.FailedFiles { + if strings.Contains(ff.Message, errInjectedCrash.Error()) { + return err != nil + } + } + return false +} + +func slicesEqual(a, b []string) bool { + return strings.Join(a, ",") == strings.Join(b, ",") +} + +// checkStagingEmpty asserts that only the latest run's staging directory +// is left, and that it holds nothing: every earlier run's staging was +// removed by reconcile. +func (f *mirrorFixture) checkStagingEmpty(t *testing.T, latest int64) { + t.Helper() + dir := f.dest(StagingDirName) + entries, err := os.ReadDir(dir) + if errors.Is(err, fs.ErrNotExist) { + return + } + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if e.Name() != "run-"+strconv.FormatInt(latest, 10) { + t.Errorf("staging still holds %s", e.Name()) + continue + } + if left, _ := os.ReadDir(filepath.Join(dir, e.Name())); len(left) != 0 { + t.Errorf("the latest run's staging holds %d entries", len(left)) + } + } +} + +// TestMirrorRefusesShallow: --shallow has nothing to switch off on a +// native mirror, so it is refused before any run starts. +func TestMirrorRefusesShallow(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + _, err := f.push(t, Options{Shallow: true}) + if err == nil || !strings.Contains(err.Error(), "--shallow") { + t.Fatalf("shallow push = %v, want a refusal naming --shallow", err) + } + if runs := mustListSyncRuns(t, f.store); len(runs) != 0 { + t.Fatalf("a refused shallow push wrote runs: %+v", runs) + } +} + +func mustListSyncRuns(t *testing.T, s *store.Store) []store.Run { + t.Helper() + runs, err := s.ListRuns(context.Background(), store.ListRunsOpts{}) + if err != nil { + t.Fatal(err) + } + var out []store.Run + for _, r := range runs { + if r.Kind == store.RunKindSync { + out = append(out, r) + } + } + return out +} + +// TestMirrorDryRunWritesNothing: a dry run previews what a push would +// write and changes nothing — no runs row, no files, no records. +func TestMirrorDryRunWritesNothing(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "alpha two") + f.write(t, "b.txt", "beta") + f.index(t) + before := len(f.rows(t)) + + rep, err := f.push(t, Options{DryRun: true}) + if err != nil || rep.RunID != 0 { + t.Fatalf("dry run: run=%d err=%v", rep.RunID, err) + } + if rep.RcloneResult.Transferred != 2 || rep.RcloneResult.Bytes != int64(len("alpha two")+len("beta")) { + t.Fatalf("preview = %+v, want 2 paths", rep.RcloneResult) + } + if _, err := os.Stat(f.dest("b.txt")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the dry run wrote b.txt: %v", err) + } + if len(f.rows(t)) != before || len(mustListSyncRuns(t, f.store)) != 1 { + t.Fatal("the dry run recorded something") + } +} + +// TestMirrorMarkerRefusalIsRecorded: without the volume marker — an +// unplugged disk, a mistyped root — the push refuses and records the +// refusal as its own run. +func TestMirrorMarkerRefusalIsRecorded(t *testing.T) { + f := setupMirrorFixture(t) + if err := os.Remove(filepath.Join(f.dst, "pics", volmark.MarkerName)); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + rep, err := f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || rep.Status != store.RunStatusRefused { + t.Fatalf("push without a marker: status=%q err=%v, want a recorded refusal", rep.Status, err) + } + if runs := mustListSyncRuns(t, f.store); len(runs) != 1 || runs[0].Status != store.RunStatusRefused { + t.Fatalf("sync runs = %+v, want one refused", runs) + } +} + +// TestMirrorWatermarkRule: a native mirror adopts no existing tree. An +// rclone-era success with its tree still there is refused; once the root +// is emptied it is a fresh start; and a root emptied behind squirrel's back +// while its records remain is refused again. +func TestMirrorWatermarkRule(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + ctx := context.Background() + rcloneRun, err := f.store.BeginRun(ctx, store.RunKindSync, f.volumeID(t), "usb", false) + if err != nil { + t.Fatal(err) + } + if err := f.store.FinishRun(ctx, rcloneRun, store.RunStatusSuccess, "", 1); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("a.txt"), []byte("alpha"), 0o644); err != nil { + t.Fatal(err) + } + + _, err = f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "does not adopt") { + t.Fatalf("push over an rclone-era tree = %v, want a refusal", err) + } + + if err := os.Remove(f.dest("a.txt")); err != nil { + t.Fatal(err) + } + f.mustPush(t) + if f.readDest(t, "a.txt") != "alpha" { + t.Fatal("the fresh start did not write the tree") + } + + if err := os.RemoveAll(filepath.Join(f.dst, "pics")); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(f.dst, "pics"), 0o755); err != nil { + t.Fatal(err) + } + if err := volmark.Write(filepath.Join(f.dst, "pics"), volmark.Marker{Volume: "pics"}); err != nil { + t.Fatal(err) + } + _, err = f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "destination reset") { + t.Fatalf("push to a wiped root with records = %v, want a refusal", err) + } +} + +// TestMirrorForeignStagingIsLeftAlone: something in staging squirrel did +// not name is reported and never removed. +func TestMirrorForeignStagingIsLeftAlone(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + first := f.mustPush(t) + foreign := f.dest(filepath.Join(StagingDirName, "run-"+strconv.FormatInt(first.RunID, 10), "notes.txt")) + if err := os.WriteFile(foreign, []byte("mine"), 0o644); err != nil { + t.Fatal(err) + } + rep := f.mustPush(t) + if !warned(rep, "notes.txt is in squirrel's staging") { + t.Fatalf("warnings = %v, want the foreign file reported", rep.Warnings) + } + if _, err := os.Stat(foreign); err != nil { + t.Fatalf("the foreign file was removed: %v", err) + } +} + +// TestMirrorFileDirectorySwap: a file that became a directory, and a +// directory that became a file, each move the old entry into history — +// the directory with every version recorded in it — before the new one +// lands. +func TestMirrorFileDirectorySwap(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a", "file a") + f.write(t, "d/x", "inside d") + f.index(t) + f.mustPush(t) + for _, rel := range []string{"a", "d"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "a/b", "under a") + f.write(t, "d", "file d") + f.index(t) + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := strconv.FormatInt(rep.RunID, 10) + if f.readDest(t, "a/b") != "under a" || f.readDest(t, "d") != "file d" { + t.Fatal("the swapped paths did not land") + } + if f.readDest(t, ".squirrel-history/run-"+run+"/a") != "file a" || f.readDest(t, ".squirrel-history/run-"+run+"/d/x") != "inside d" { + t.Fatal("the replaced entries are not in history") + } + if got := f.rowsAt(t, "d/x"); len(got) != 1 || got[0] != store.RemotePathDisplaced { + t.Fatalf("d/x rows = %v, want displaced with its directory", got) + } + f.checkInvariants(t, before) +} + +// TestMirrorProgressEvents: a push reports one progress event per planned +// path. +func TestMirrorProgressEvents(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + var events []runevents.Progress + _, err := f.push(t, Options{Progress: func(p runevents.Progress) { events = append(events, p) }}) + if err != nil { + t.Fatal(err) + } + if len(events) != 2 || events[1].Done != 2 || events[1].Total != 2 || events[1].BytesDone != 9 { + t.Fatalf("events = %+v, want two ending at 2/2 paths and 9 bytes", events) + } +} + +// flushRecorder notes the directories each Flush was asked to cover. +type flushRecorder struct { + transport + flushes *[][]string +} + +func (r flushRecorder) Flush(ctx context.Context, dirs ...string) error { + *r.flushes = append(*r.flushes, dirs) + return r.transport.Flush(ctx, dirs...) +} + +// TestMirrorReconcileFlushesWhatItSettles: a push that died after renaming +// a staged file onto its path, before the flush that makes the rename +// durable, leaves its row committing; the next push flushes the path's +// directories and the staging directory before it records the row live. +func TestMirrorReconcileFlushesWhatItSettles(t *testing.T) { + f := setupMirrorFixture(t) + f.oneAtATime() + f.write(t, "d/a.txt", "alpha") + f.index(t) + crash, err := f.pushCrashing(t, func(c transportCall) bool { + return c.op == "rename" && path.Base(c.to) == "a.txt" + }, crashAfter) + if !crashedOn(crash, err) { + t.Fatalf("crashing push = %v, want the injected crash", err) + } + if got := f.rowsAt(t, "d/a.txt"); len(got) != 1 || got[0] != store.RemotePathCommitting { + t.Fatalf("d/a.txt rows = %v, want one committing", got) + } + var flushes [][]string + if _, err := f.pushVia(t, Options{}, func(tr transport) transport { return flushRecorder{tr, &flushes} }); err != nil { + t.Fatal(err) + } + staging := path.Dir(stagingName("pics", crash.RunID, stagingKey("d/a.txt"))) + if len(flushes) == 0 || !slices.Contains(flushes[0], "pics/d") || !slices.Contains(flushes[0], staging) { + t.Fatalf("first flush covered %v, want pics/d and %s", flushes, staging) + } + if got := f.rowsAt(t, "d/a.txt"); len(got) != 1 || got[0] != store.RemotePathLive { + t.Fatalf("d/a.txt rows = %v, want one live", got) + } +} + +// blockingTransport holds every Stat until release is closed. +type blockingTransport struct { + transport + release chan struct{} +} + +func (b blockingTransport) Stat(ctx context.Context, name string) (entry, error) { + <-b.release + return b.transport.Stat(ctx, name) +} + +// TestMirrorStallFailsThePush: a transport call that makes no progress +// fails the push after the stall timeout, and a later push to the same +// destination refuses while that call is still inside the system. +func TestMirrorStallFailsThePush(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "alpha two") + f.index(t) + + release := make(chan struct{}) + h := f.handler(t) + h.stallTimeout = 50 * time.Millisecond + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return blockingTransport{transport: raw, release: release}, err + } + if _, err := h.Push(context.Background(), Options{}); !errors.Is(err, errTransportStalled) { + t.Fatalf("stalled push = %v, want errTransportStalled", err) + } + if _, err := f.push(t, Options{}); err == nil || !strings.Contains(err.Error(), "have not returned") { + t.Fatalf("push while a call is stuck = %v, want a refusal", err) + } + close(release) + deadline := time.Now().Add(5 * time.Second) + for stalledCounter("usb").Load() > 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + f.mustPush(t) + if f.readDest(t, "a.txt") != "alpha two" { + t.Fatal("the push after the stall cleared did not land") + } + f.checkInvariants(t, nil) +} + +// corruptingTransport returns every staged file it reads with its first +// byte flipped, as a disk that kept other bytes than it was given. +type corruptingTransport struct{ transport } + +func (c corruptingTransport) Get(ctx context.Context, name string) (io.ReadCloser, error) { + rc, err := c.transport.Get(ctx, name) + if err != nil || !strings.Contains(name, "/"+StagingDirName+"/") { + return rc, err + } + defer func() { _ = rc.Close() }() + b, err := io.ReadAll(rc) + if err != nil { + return nil, err + } + if len(b) > 0 { + b[0] ^= 0xff + } + return io.NopCloser(bytes.NewReader(b)), nil +} + +// TestMirrorReadBackRefusesBytesTheDiskChanged: a staged copy that reads +// back as other bytes than were sent is never committed. The path fails, +// the run fails before its receipt, and the staged copy stays for the next +// push's reconcile. +func TestMirrorReadBackRefusesBytesTheDiskChanged(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + h := f.handler(t) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return corruptingTransport{raw}, err + } + rep, err := h.Push(context.Background(), Options{}) + if err == nil || rep.Status != store.RunStatusFailed { + t.Fatalf("push: status=%q err=%v, want a failed run", rep.Status, err) + } + if len(rep.RcloneResult.FailedFiles) != 1 || !strings.Contains(rep.RcloneResult.FailedFiles[0].Message, errReadBackMismatch.Error()) { + t.Fatalf("failed files = %+v, want a read-back mismatch", rep.RcloneResult.FailedFiles) + } + if _, err := os.Stat(f.dest("a.txt")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("a.txt was committed: %v", err) + } + if rows := f.rows(t); len(rows) != 0 { + t.Fatalf("rows = %+v, want none", rows) + } + staged := filepath.Join(f.dst, filepath.FromSlash(stagingName("pics", rep.RunID, stagingKey("a.txt")))) + if _, err := os.Stat(staged); err != nil { + t.Fatalf("staged copy: %v", err) + } + f.mustPush(t) + if _, err := os.Stat(staged); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the next push left the failed run's staging: %v", err) + } + f.checkInvariants(t, nil) +} diff --git a/sync/mirror_translate.go b/sync/mirror_translate.go new file mode 100644 index 0000000..4255780 --- /dev/null +++ b/sync/mirror_translate.go @@ -0,0 +1,99 @@ +package sync + +import ( + "context" + "fmt" + + "github.com/mbertschler/squirrel/store" +) + +// mirrorOps is the mirror translation of a plan: one operation per present +// delta path and per repair, and the live records the operations were +// decided against. execute keeps live current as it moves versions. +type mirrorOps struct { + volumeID int64 + paths []mirrorPath + live map[string]store.RemotePath // volume-relative path → live row + // inSync counts the live rows that hold their path's present content, + // in the delta or not: what the report calls already correct. + inSync int64 + // repairs counts the paths planned because the destination lost their + // current content, beyond the delta. + repairs int64 +} + +// mirrorPath is one planned path. When the live record already holds the +// delta's content, the path is only confirmed; otherwise the content is +// written, displacing whatever the path holds. +type mirrorPath struct { + delta store.PathDelta + // current: the path's live record holds the delta's content. + current bool +} + +// translate applies the mirror's translation rules to the delta, then adds +// the repairs: present paths whose current content the destination lost +// (a push or a verify pass found other bytes there, or none), written +// again although the index did not change. Rows that are missing, +// offloaded or superseded produce nothing: a destination keeps content the +// source no longer has. +// +// present, live record holds C → confirm (already correct) +// present, live record holds other → write C, displacing the recorded version +// present, no live record → write C, displacing any unrecorded entry +// repair: a lost record holds C → write C, displacing whatever is there +func (h *mirrorHandler) translate(ctx context.Context, p pushPlan) (*mirrorOps, error) { + rows, err := h.store.ListLiveRemotePaths(ctx, h.dest.Name, p.volumeID) + if err != nil { + return nil, fmt.Errorf("list live mirror paths on %q: %w", h.dest.Name, err) + } + inSync, err := h.store.CountInSyncRemotePaths(ctx, h.dest.Name, p.volumeID) + if err != nil { + return nil, err + } + ops := &mirrorOps{volumeID: p.volumeID, live: make(map[string]store.RemotePath, len(rows)), inSync: inSync} + for _, r := range rows { + ops.live[r.Path] = r + } + planned := make(map[string]bool, len(p.delta)) + for _, d := range p.delta { + if d.Status != store.StatusPresent { + continue + } + planned[d.Path] = true + live, ok := ops.live[d.Path] + ops.paths = append(ops.paths, mirrorPath{delta: d, current: ok && live.ContentID == d.ContentID}) + } + return ops, h.addRepairs(ctx, p.volumeID, ops, planned) +} + +// addRepairs plans every repair the delta does not already cover. +func (h *mirrorHandler) addRepairs(ctx context.Context, volumeID int64, ops *mirrorOps, planned map[string]bool) error { + repairs, err := h.store.ListRemotePathRepairs(ctx, h.dest.Name, volumeID) + if err != nil { + return fmt.Errorf("list lost mirror paths on %q: %w", h.dest.Name, err) + } + for _, d := range repairs { + if planned[d.Path] { + continue + } + ops.paths = append(ops.paths, mirrorPath{delta: d}) + ops.repairs++ + } + return nil +} + +// preview counts what execute would do: written paths as Transferred and +// Bytes, confirmed ones as Checked, and every in-sync path as already +// correct. +func (o *mirrorOps) preview(rep *Report) { + rep.AlreadyCorrect = o.inSync + for _, p := range o.paths { + if p.current { + rep.RcloneResult.Checked++ + continue + } + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += p.delta.SizeBytes + } +} diff --git a/sync/mirror_write.go b/sync/mirror_write.go new file mode 100644 index 0000000..a3fe9d1 --- /dev/null +++ b/sync/mirror_write.go @@ -0,0 +1,691 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + gosync "sync" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/runevents" + "github.com/mbertschler/squirrel/store" +) + +// mirrorWriter carries one run's execution: the guarded transport, the +// live records it keeps current, and the tally for the report. Several +// paths are in flight at once, so the records and the tally are shared +// behind mu; transport calls run outside it. +type mirrorWriter struct { + h *mirrorHandler + rep *Report + runID int64 + volumeID int64 + tr transport + // fold is how the destination compares names; names plans the + // writes around the collisions its folding causes. + fold nameFolding + names foldPlan + // concurrency is how many paths are in flight at once. + concurrency int + + progress func(runevents.Progress) + total int + + mu gosync.Mutex + live *liveRecords + // displacing is the rows this batch moved into history, which the + // batch's flush lets it record as displaced; movedAside counts every + // move into history, recorded or not. + displacing []int64 + movedAside int + done int + drifted int + collided int + stalled bool +} + +// execute confirms or writes every planned path, a batch at a time. A +// failure on one path is counted and the rest still run — every version +// that lands now is recorded and saves work on the retry — but any failure +// fails the run before its receipt is written, so the watermark holds. +func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, ops *mirrorOps) error { + tr, err := h.root(ctx, runID) + if err != nil { + return err + } + w := &mirrorWriter{h: h, rep: rep, runID: runID, volumeID: ops.volumeID, tr: tr, + concurrency: pushConcurrency(h.dest), progress: h.progress, total: len(ops.paths)} + rep.AlreadyCorrect = ops.inSync + if ops.repairs > 0 { + rep.Changed = knownChanged(rep.Changed.Int64 + ops.repairs) + rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q lost %d path(s) the index still holds there (found gone or changed); they are written again", h.dest.Name, ops.repairs)) + } + if err := w.learnNames(ctx, ops); err != nil { + return err + } + for _, batch := range batches(ops.paths, writtenBytes) { + if err := ctx.Err(); err != nil { + return err + } + w.writeBatch(ctx, batch) + if w.isStalled() { + break + } + } + return w.result() +} + +// writtenBytes is what a planned path adds to its batch: its bytes when +// it may be written, nothing when it is only confirmed. +func writtenBytes(p mirrorPath) int64 { + if p.current { + return 0 + } + return p.delta.SizeBytes +} + +// learnNames probes how the destination compares names before the first +// path lands, keys the live records the way it does, and on a destination +// that folds them plans around the collisions that causes. +func (w *mirrorWriter) learnNames(ctx context.Context, ops *mirrorOps) error { + if len(ops.paths) == 0 { + return nil + } + var err error + if w.fold, err = w.probeFolding(ctx); err != nil { + return err + } + w.live = newLiveRecords(w.fold, ops.live) + if !w.fold.folds() { + return nil + } + w.names, err = w.planFolding(ctx, ops) + return err +} + +// landing is one planned path on its way through a batch. +type landing struct { + p mirrorPath + staged stagedVersion + // commitID is the path's committing row, once inserted. + commitID int64 + // settled: the path needs no further step, because it was confirmed + // in place, refused, or failed. + settled bool +} + +// writeBatch takes one batch through the steps of a write, each for the +// whole batch before the next: confirm or stage every path, flush, read +// back, clear the way, displace, flush and record the displaced versions, +// commit, flush and record the committed ones. A path whose step fails +// drops out; a stalled transport ends the batch where it is, and the next +// push's reconcile settles what it left recorded in flight. +func (w *mirrorWriter) writeBatch(ctx context.Context, batch []mirrorPath) { + ls := make([]*landing, len(batch)) + for i, p := range batch { + ls[i] = &landing{p: p} + } + steps := []func(context.Context, []*landing){ + w.each(w.prepare), + w.flushOrDrop, + w.readBackAll, + w.clearTheWay, + w.each(w.displaceLanding), + w.recordDisplaced, + w.each(w.commit), + w.recordCommitted, + } + for _, step := range steps { + step(ctx, ls) + if w.isStalled() || ctx.Err() != nil { + return + } + } +} + +// each is the step that runs fn for every path still on its way, with +// w.concurrency of them in flight. A path fn fails drops out. +func (w *mirrorWriter) each(fn func(context.Context, *landing) error) func(context.Context, []*landing) { + return func(ctx context.Context, ls []*landing) { + inFlight(ctx, w.concurrency, active(ls), w.isStalled, func(l *landing) { + if err := fn(ctx, l); err != nil { + w.drop(l, err) + } + }) + } +} + +// active is the batch's paths still on their way. +func active(ls []*landing) []*landing { + var out []*landing + for _, l := range ls { + if !l.settled { + out = append(out, l) + } + } + return out +} + +// prepare refuses a path whose name collides with another's, confirms an +// already-correct one in place, and stages every other. +func (w *mirrorWriter) prepare(ctx context.Context, l *landing) error { + rel := l.p.delta.Path + if other, ok := w.names.refused[rel]; ok { + w.refuseCollision(rel, other) + w.settle(l) + return nil + } + if l.p.current { + ok, err := w.confirm(ctx, l.p.delta) + if err != nil { + return err + } + if ok { + w.settle(l) + return nil + } + } + staged, err := w.stage(ctx, l.p.delta) + l.staged = staged + return err +} + +// flushOrDrop makes the batch's staged files durable; a flush that fails +// drops every path still on its way. +func (w *mirrorWriter) flushOrDrop(ctx context.Context, ls []*landing) { + if len(active(ls)) == 0 { + return + } + if err := w.tr.Flush(ctx); err != nil { + w.dropAll(ls, fmt.Errorf("flush the staged files: %w", err)) + } +} + +// readBackAll reads every staged file back on a disk squirrel reads back. +func (w *mirrorWriter) readBackAll(ctx context.Context, ls []*landing) { + if !readsBack(w.h.dest) { + return + } + w.each(func(ctx context.Context, l *landing) error { + return w.readBackStaged(ctx, l.p.delta, &l.staged) + })(ctx, ls) +} + +// clearTheWay moves aside, one path after another, what stands in the +// way of more than one path's name: versions recorded under another +// spelling of it, and a parent that is not a directory. Each directory is +// looked at once per batch. +func (w *mirrorWriter) clearTheWay(ctx context.Context, ls []*landing) { + cleared := map[string]bool{} + for _, l := range active(ls) { + if w.isStalled() { + return + } + if err := w.clearFor(ctx, l.p.delta.Path, cleared); err != nil { + w.drop(l, err) + } + } +} + +func (w *mirrorWriter) clearFor(ctx context.Context, rel string, cleared map[string]bool) error { + for _, other := range w.names.displace[rel] { + if err := w.displaceSpelling(ctx, other); err != nil { + return err + } + } + return w.clearParents(ctx, rel, cleared) +} + +func (w *mirrorWriter) displaceLanding(ctx context.Context, l *landing) error { + return w.displace(ctx, l.p.delta.Path) +} + +// recordDisplaced flushes the batch's moves into history, so they land +// before any commit, then records the recorded ones as displaced. Until +// then their rows stay displacing, which the next push's reconcile +// settles from where the bytes are. +func (w *mirrorWriter) recordDisplaced(ctx context.Context, ls []*landing) { + w.mu.Lock() + ids, moved := w.displacing, w.movedAside + w.displacing, w.movedAside = nil, 0 + w.mu.Unlock() + if moved == 0 { + return + } + err := w.tr.Flush(ctx) + if err == nil && len(ids) > 0 { + err = w.h.store.ConfirmRemotePathsDisplaced(ctx, ids...) + } + if err != nil { + w.dropAll(ls, fmt.Errorf("record the versions moved into history: %w", err)) + } +} + +// recordCommitted flushes the batch's commits, then records them live +// and counts them. Until then their rows stay committing, which the next +// push's reconcile settles from where the bytes are. +func (w *mirrorWriter) recordCommitted(ctx context.Context, ls []*landing) { + var ids []int64 + for _, l := range active(ls) { + ids = append(ids, l.commitID) + } + if len(ids) == 0 { + return + } + err := w.tr.Flush(ctx) + if err == nil { + err = w.h.store.ConfirmRemotePathsLive(ctx, ids...) + } + if err != nil { + w.dropAll(ls, fmt.Errorf("record the committed paths: %w", err)) + return + } + w.mu.Lock() + defer w.mu.Unlock() + for _, l := range active(ls) { + w.rep.RcloneResult.Transferred++ + w.rep.RcloneResult.Bytes += l.p.delta.SizeBytes + w.settleLocked(l) + } +} + +func (w *mirrorWriter) settle(l *landing) { + w.mu.Lock() + defer w.mu.Unlock() + w.settleLocked(l) +} + +// settleLocked takes l off its way, counts it done and reports progress; +// w.mu is held, so progress arrives in order. +func (w *mirrorWriter) settleLocked(l *landing) { + l.settled = true + w.done++ + if w.progress == nil { + return + } + w.progress(runevents.Progress{ + Stage: runevents.StageUploading, + Done: int64(w.done), + Total: int64(w.total), + BytesDone: w.rep.RcloneResult.Bytes, + }) +} + +// confirm checks an already-correct path with one Lstat. A path whose size +// or mtime disagrees with its record was changed behind squirrel's back: +// the record becomes lost, and the path is written again. +func (w *mirrorWriter) confirm(ctx context.Context, d store.PathDelta) (bool, error) { + live, _ := w.liveAt(d.Path) + e, err := w.tr.Stat(ctx, w.h.liveName(d.Path)) + if err != nil && !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, errParentNotDir) { + return false, err + } + if err == nil && matchesRecord(e, live) { + w.mu.Lock() + w.rep.RcloneResult.Checked++ + w.mu.Unlock() + return true, nil + } + w.mu.Lock() + w.rep.AlreadyCorrect-- + w.mu.Unlock() + if err := w.loseRecord(ctx, live, "no longer matches its record"); err != nil { + return false, err + } + return false, nil +} + +// stagedVersion is one path's version in this run's staging, as the +// destination confirmed it: its mtime, and on a disk squirrel reads back, +// the hex BLAKE3 the read-back confirmed and when. +type stagedVersion struct { + name string + mtime time.Time + checksum string + verifiedAtNs int64 +} + +// stage streams the source into this run's staging and hashes the same +// bytes, then confirms what landed: its size. A source that drifted from +// its indexed hash fails the path with errContentDrift; its staged file +// stays until the next push's reconcile removes it with this run's +// staging. +func (w *mirrorWriter) stage(ctx context.Context, d store.PathDelta) (stagedVersion, error) { + src := filepath.Join(w.h.vol.Path, filepath.FromSlash(d.Path)) + f, err := os.Open(src) + if err != nil { + return stagedVersion{}, fmt.Errorf("open source %s: %w", src, err) + } + defer f.Close() + staged := stagedVersion{name: stagingName(w.h.vol.Name, w.runID, stagingKey(d.Path))} + hasher := blake3.New() + counted := &countWriter{w: hasher} + if err := w.tr.Put(ctx, staged.name, io.TeeReader(f, counted), time.Unix(0, d.MtimeNs)); err != nil { + return stagedVersion{}, fmt.Errorf("stage %s: %w", d.Path, err) + } + if counted.n != d.SizeBytes || !bytes.Equal(hasher.Sum(nil), d.Blake3) { + return stagedVersion{}, fmt.Errorf("%w: %s sent %d bytes hashing to %s, indexed as %d bytes %s — run `squirrel index %s` and sync again", + errContentDrift, d.Path, counted.n, hex.EncodeToString(hasher.Sum(nil)), d.SizeBytes, hex.EncodeToString(d.Blake3), w.h.vol.Name) + } + e, err := w.tr.Stat(ctx, staged.name) + if err != nil { + return stagedVersion{}, fmt.Errorf("confirm staged %s: %w", d.Path, err) + } + if e.size != d.SizeBytes { + return stagedVersion{}, fmt.Errorf("staged %s landed with size %d, want %d", d.Path, e.size, d.SizeBytes) + } + staged.mtime = e.mtime + return staged, nil +} + +// readBackStaged confirms the staged bytes, flushed, are the content +// squirrel sent, and records the fingerprint that earns. +func (w *mirrorWriter) readBackStaged(ctx context.Context, d store.PathDelta, staged *stagedVersion) error { + sum, err := readBack(ctx, w.tr, staged.name) + if err != nil { + return fmt.Errorf("read back staged %s: %w", d.Path, err) + } + if !bytes.Equal(sum, d.Blake3) { + return fmt.Errorf("%w: staged %s hashes to %s, sent %s", errReadBackMismatch, d.Path, hex.EncodeToString(sum), hex.EncodeToString(d.Blake3)) + } + staged.checksum = hex.EncodeToString(sum) + staged.verifiedAtNs = store.NowNs() + w.mu.Lock() + w.rep.Fingerprints++ + w.mu.Unlock() + return nil +} + +// clearParents displaces the first parent of rel that is not a directory +// — a file, a symlink — so rel's directory can be created. cleared holds +// what this batch already found at each parent: a directory (true) or +// nothing (false), below which nothing exists either. +func (w *mirrorWriter) clearParents(ctx context.Context, rel string, cleared map[string]bool) error { + parts := strings.Split(rel, "/") + for i := 1; i < len(parts); i++ { + parent := strings.Join(parts[:i], "/") + if isDir, seen := cleared[parent]; seen { + if !isDir { + return nil + } + continue + } + e, err := w.tr.Stat(ctx, w.h.liveName(parent)) + if errors.Is(err, fs.ErrNotExist) { + cleared[parent] = false + return nil + } + if err != nil { + return err + } + if e.kind == kindDir { + cleared[parent] = true + continue + } + if err := w.displace(ctx, parent); err != nil { + return err + } + cleared[parent] = false + return nil + } + return nil +} + +// displace moves whatever rel holds into this run's history. A version +// whose size and mtime match its live record moves as that record; a +// directory moves with every live record under it; anything else moves as +// unrecorded bytes, and a record they contradict becomes lost, so a +// record in history always vouches for the bytes there. Where rel holds +// no directory, every record under it is lost too. +func (w *mirrorWriter) displace(ctx context.Context, rel string) error { + e, err := w.tr.Stat(ctx, w.h.liveName(rel)) + if errors.Is(err, fs.ErrNotExist) { + if err := w.loseRecordsUnder(ctx, rel); err != nil { + return err + } + return w.loseRecordAt(ctx, rel, "is gone from the destination") + } + if err != nil { + return err + } + if e.kind != kindDir { + if err := w.loseRecordsUnder(ctx, rel); err != nil { + return err + } + } + if live, ok := w.liveAt(rel); ok { + if matchesRecord(e, live) { + return w.moveRecorded(ctx, rel, []int64{live.ID}) + } + if err := w.loseRecord(ctx, live, "no longer matches its record"); err != nil { + return err + } + } + if e.kind == kindDir { + return w.displaceDir(ctx, rel) + } + return w.moveUnrecorded(ctx, rel, e) +} + +// displaceDir moves a directory a file replaced, with every live record +// under it; a record whose bytes changed becomes lost first. +func (w *mirrorWriter) displaceDir(ctx context.Context, dir string) error { + var ids []int64 + for _, live := range w.liveUnder(dir) { + e, err := w.tr.Stat(ctx, w.h.liveName(live.Path)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + if err == nil && matchesRecord(e, live) { + ids = append(ids, live.ID) + continue + } + if err := w.loseRecord(ctx, live, "no longer matches its record"); err != nil { + return err + } + } + if err := w.noteUnrecordedMove(ctx, fmt.Sprintf("directory=%q recorded-versions=%d moving-to=%q", dir, len(ids), w.historyName(dir))); err != nil { + return err + } + if err := w.moveRecorded(ctx, dir, ids); err != nil { + return err + } + w.warn(fmt.Sprintf("destination %q: directory %s was replaced by a file; it moved into %s with the %d version(s) squirrel recorded in it and anything else it held", + w.h.dest.Name, dir, w.historyName(dir), len(ids))) + return nil +} + +// moveRecorded records the move of ids, renames rel into history, and +// leaves the rows for the batch's flush to confirm. If the rename fails, +// or the push ends before that flush, the rows stay displacing, and the +// next push's reconcile settles them from where the bytes are. +func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64) error { + if err := w.h.store.BeginRemotePathsDisplace(ctx, w.runID, ids...); err != nil { + return err + } + if err := w.tr.Rename(ctx, w.h.liveName(rel), w.historyName(rel)); err != nil { + return fmt.Errorf("displace %s: %w", rel, err) + } + w.mu.Lock() + defer w.mu.Unlock() + w.displacing = append(w.displacing, ids...) + w.movedAside++ + for _, r := range w.live.under(rel) { + w.live.remove(r.Path) + } + w.live.remove(rel) + return nil +} + +// moveUnrecorded moves bytes squirrel did not write into history. The +// move is noted in the run's audit trail before it happens, and reported +// as a warning once it did. +func (w *mirrorWriter) moveUnrecorded(ctx context.Context, rel string, e entry) error { + to := w.historyName(rel) + if err := w.noteUnrecordedMove(ctx, fmt.Sprintf("path=%q size=%d moving-to=%q", rel, e.size, to)); err != nil { + return err + } + if err := w.tr.Rename(ctx, w.h.liveName(rel), to); err != nil { + return fmt.Errorf("displace unrecorded %s: %w", rel, err) + } + w.mu.Lock() + w.movedAside++ + w.mu.Unlock() + w.warn(fmt.Sprintf("destination %q: %s held bytes squirrel did not write (%d bytes); they are preserved at %s", w.h.dest.Name, rel, e.size, to)) + return nil +} + +func (w *mirrorWriter) noteUnrecordedMove(ctx context.Context, note string) error { + return w.h.store.AppendRunAudit(ctx, store.RunAuditEntry{ + RunID: w.runID, + Transition: store.TransitionDisplaceUnrecorded, + Note: note, + }) +} + +// commit records the intent and renames the staged version onto its +// path, leaving the row for the batch's flush to confirm. If the rename +// fails, or the push ends before that flush, the row stays committing, +// and the next push's reconcile settles it. +func (w *mirrorWriter) commit(ctx context.Context, l *landing) error { + d, staged := l.p.delta, l.staged + id, err := w.h.store.BeginRemotePathCommit(ctx, store.RemotePathWrite{ + Destination: w.h.dest.Name, + FolderID: d.FolderID, + Name: path.Base(d.Path), + ContentID: d.ContentID, + RunID: w.runID, + MtimeNs: staged.mtime.UnixNano(), + Checksum: staged.checksum, + VerifiedAtNs: staged.verifiedAtNs, + }) + if err != nil { + return err + } + if err := w.tr.Rename(ctx, staged.name, w.h.liveName(d.Path)); err != nil { + return fmt.Errorf("commit %s: %w", d.Path, err) + } + l.commitID = id + w.mu.Lock() + w.live.set(store.RemotePath{ID: id, ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, + MtimeNs: staged.mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes}) + w.mu.Unlock() + return nil +} + +// loseRecordsUnder marks lost every live record below rel, whose +// directory the destination no longer holds. +func (w *mirrorWriter) loseRecordsUnder(ctx context.Context, rel string) error { + for _, live := range w.liveUnder(rel) { + if err := w.loseRecord(ctx, live, "is gone: "+rel+" is not a directory on the destination"); err != nil { + return err + } + } + return nil +} + +// loseRecordAt marks the live record at rel lost, if there is one. +func (w *mirrorWriter) loseRecordAt(ctx context.Context, rel, why string) error { + if live, ok := w.liveAt(rel); ok { + return w.loseRecord(ctx, live, why) + } + return nil +} + +func (w *mirrorWriter) loseRecord(ctx context.Context, live store.RemotePath, why string) error { + if err := w.h.store.MarkRemotePathsLost(ctx, live.ID); err != nil { + return err + } + w.mu.Lock() + w.live.remove(live.Path) + w.mu.Unlock() + w.warn(fmt.Sprintf("destination %q: %s %s — it was changed behind squirrel's back, so its record no longer counts as a copy, and a push writes it again while the index holds it", w.h.dest.Name, live.Path, why)) + return nil +} + +// liveAt is the live record at rel, if there is one. +func (w *mirrorWriter) liveAt(rel string) (store.RemotePath, bool) { + w.mu.Lock() + defer w.mu.Unlock() + return w.live.at(rel) +} + +// liveUnder is every live record below dir, as the destination resolves +// names. +func (w *mirrorWriter) liveUnder(dir string) []store.RemotePath { + w.mu.Lock() + defer w.mu.Unlock() + return w.live.under(dir) +} + +func (w *mirrorWriter) warn(msg string) { + w.mu.Lock() + w.rep.Warnings = append(w.rep.Warnings, msg) + w.mu.Unlock() +} + +func (w *mirrorWriter) historyName(rel string) string { + return historyName(w.h.vol.Name, w.runID, rel) +} + +// drop takes l out of its batch, counting why. +func (w *mirrorWriter) drop(l *landing, err error) { + rel := l.p.delta.Path + w.mu.Lock() + defer w.mu.Unlock() + defer w.settleLocked(l) + switch { + case errors.Is(err, errContentDrift): + w.drifted++ + w.rep.Warnings = append(w.rep.Warnings, err.Error()) + return + case errors.Is(err, errTransportStalled): + w.stalled = true + } + w.rep.RcloneResult.Errors++ + if int64(len(w.rep.RcloneResult.FailedFiles)) < maxFailedFiles { + w.rep.RcloneResult.FailedFiles = append(w.rep.RcloneResult.FailedFiles, FailedFile{Object: rel, Message: err.Error()}) + } +} + +// dropAll takes every path still on its way out of the batch. +func (w *mirrorWriter) dropAll(ls []*landing, err error) { + for _, l := range active(ls) { + w.drop(l, err) + } +} + +func (w *mirrorWriter) isStalled() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.stalled +} + +func (w *mirrorWriter) result() error { + if n := w.rep.RcloneResult.Errors; n > 0 { + return fmt.Errorf("%d path(s) failed to land on %q; the receipt for run %d was not written and the durability vector did not advance", n, w.h.dest.Name, w.runID) + } + if w.drifted > 0 { + return fmt.Errorf("%d path(s) on %q were refused for drifting from their indexed hash; re-index the volume and sync again — the receipt for run %d was not written and the durability vector did not advance", w.drifted, w.h.dest.Name, w.runID) + } + if w.collided > 0 { + return fmt.Errorf("%d path(s) on %q were refused because the destination cannot tell their names apart from another path's; rename one of each pair at the source, index, and sync again — the receipt for run %d was not written and the durability vector did not advance", w.collided, w.h.dest.Name, w.runID) + } + return nil +} + +// matchesRecord reports whether an entry found at a path is the version +// its live record describes, by kind, size and mtime. +func matchesRecord(e entry, live store.RemotePath) bool { + return e.kind == kindFile && e.size == live.SizeBytes && e.mtime.UnixNano() == live.MtimeNs +} diff --git a/sync/naming.go b/sync/naming.go index 5a57988..0de0bd6 100644 --- a/sync/naming.go +++ b/sync/naming.go @@ -123,7 +123,7 @@ const ( // always on a root proven to be keyed under this destination's key. A // fresh root without init is left untouched for the volume-marker gate to // refuse. -func (h *contentPusher) ensureNamingScheme(ctx context.Context, init bool) error { +func (h *rcloneArtifacts) ensureNamingScheme(ctx context.Context, init bool) error { stamp, err := h.checkNamingScheme(ctx) if err != nil { return err @@ -137,12 +137,12 @@ func (h *contentPusher) ensureNamingScheme(ctx context.Context, init bool) error // checkNamingScheme refuses a push to a root whose artifacts are named under // any other scheme, and reports what the root still needs stamped. // Read-only, so a dry run asks it too. -func (h *contentPusher) checkNamingScheme(ctx context.Context) (namingStamp, error) { +func (h *rcloneArtifacts) checkNamingScheme(ctx context.Context) (namingStamp, error) { if !h.dest.HidesArtifactNames() { return stampNone, nil } uri := remoteSubpathURI(h.dest, namingMarkerName) - present, err := h.rcl.statRemoteExists(ctx, uri, checkersArgs(h.dest)...) + present, err := h.rcl.statRemoteExists(ctx, uri, concurrencyArgs(h.dest)...) if err != nil { return stampNone, fmt.Errorf("destination %q: stat %s at %s: %w", h.dest.Name, namingMarkerName, uri, err) } @@ -158,9 +158,9 @@ func (h *contentPusher) checkNamingScheme(ctx context.Context) (namingStamp, err // keyed directory was named some other way — or under other crypt // passwords — and adding keyed names beside it would leave it disclosing // what it always did. -func (h *contentPusher) classifyUnmarkedRoot(ctx context.Context) (namingStamp, error) { +func (h *rcloneArtifacts) classifyUnmarkedRoot(ctx context.Context) (namingStamp, error) { rootURI := underlyingDirURI(h.dest, "") - empty, err := h.rcl.remoteRootEmpty(ctx, rootURI, nil, checkersArgs(h.dest)...) + empty, err := h.rcl.remoteRootEmpty(ctx, rootURI, nil, concurrencyArgs(h.dest)...) if err != nil { return stampNone, fmt.Errorf("destination %q: list %s: %w", h.dest.Name, rootURI, err) } @@ -178,9 +178,9 @@ func (h *contentPusher) classifyUnmarkedRoot(ctx context.Context) (namingStamp, h.dest.Name, rootURI, namingMarkerName, h.vol.Name, h.dest.Name, ErrRefused) } -func (h *contentPusher) holdsKeyedVolumeMarker(ctx context.Context) (bool, error) { +func (h *rcloneArtifacts) holdsKeyedVolumeMarker(ctx context.Context) (bool, error) { uri := remoteSubpathURI(h.dest, path.Join(h.names().volumeDir(h.vol.Name), volmark.MarkerName)) - present, err := h.rcl.statRemoteExists(ctx, uri, checkersArgs(h.dest)...) + present, err := h.rcl.statRemoteExists(ctx, uri, concurrencyArgs(h.dest)...) if err != nil { return false, fmt.Errorf("destination %q: stat %s at %s: %w", h.dest.Name, volmark.MarkerName, uri, err) } @@ -190,7 +190,7 @@ func (h *contentPusher) holdsKeyedVolumeMarker(ctx context.Context) (bool, error // validateNamingScheme refuses the marker at uri when it will not parse or // records a scheme this binary does not write. func validateNamingScheme(ctx context.Context, rcl *Rclone, dest *config.Destination, uri string) error { - data, err := rcl.catRemote(ctx, uri, checkersArgs(dest)...) + data, err := rcl.catRemote(ctx, uri, concurrencyArgs(dest)...) if err != nil { return fmt.Errorf("destination %q: read %s at %s — a root written under other crypt passwords cannot be read with these: %w", dest.Name, namingMarkerName, uri, err) } @@ -206,7 +206,7 @@ func validateNamingScheme(ctx context.Context, rcl *Rclone, dest *config.Destina } // writeNamingMarker stamps the scheme on a fresh destination root. -func (h *contentPusher) writeNamingMarker(ctx context.Context) error { +func (h *rcloneArtifacts) writeNamingMarker(ctx context.Context) error { body, err := json.Marshal(namingMarker{ Naming: namingSchemeKeyed, CreatedAt: time.Now().UTC().Format(time.RFC3339), @@ -214,5 +214,5 @@ func (h *contentPusher) writeNamingMarker(ctx context.Context) error { if err != nil { return fmt.Errorf("encode %s: %w", namingMarkerName, err) } - return h.uploadBytes(ctx, body, remoteSubpathURI(h.dest, namingMarkerName), namingMarkerName) + return putBytes(ctx, h, 0, namingMarkerName, body, namingMarkerName) } diff --git a/sync/naming_test.go b/sync/naming_test.go index bfcaced..acacfa6 100644 --- a/sync/naming_test.go +++ b/sync/naming_test.go @@ -51,16 +51,14 @@ func TestKeyedNamesDiscloseNothing(t *testing.T) { // no key to derive from, so the append-only layouts name artifacts by // content hash and write no naming marker. func TestPlainDestinationKeepsContentHashNames(t *testing.T) { - f := setupPlainContentAddressedFixture(t) + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) f.write(t, "a.txt", "alpha") f.index(t) - if _, err := f.sync(t); err != nil { - t.Fatalf("sync: %v", err) - } - if _, err := os.Stat(f.remotePath(ObjectsDirName, blake3Hex("alpha"))); err != nil { + f.mustPush(t) + if _, err := os.Stat(f.objectPath("alpha")); err != nil { t.Fatalf("object not at its content-hash name: %v", err) } - if _, err := os.Stat(f.remotePath(namingMarkerName)); err == nil { + if _, err := os.Stat(filepath.Join(f.dst, namingMarkerName)); err == nil { t.Fatalf("an unencrypted destination wrote a %s marker", namingMarkerName) } } @@ -369,7 +367,7 @@ func TestKeyedVolumeDirFoundByRecovery(t *testing.T) { f := setupContentAddressedFixture(t) f.write(t, "a.txt", "alpha") f.index(t) - sn := NewSnapshotter(f.store, f.rcl, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) rep, err := RunPair(context.Background(), f.store, Tools{Rclone: f.rcl}, f.pair, Options{Snapshot: sn}) if err != nil { t.Fatalf("sync: %v", err) diff --git a/sync/node.go b/sync/node.go index d3ac559..18e1e83 100644 --- a/sync/node.go +++ b/sync/node.go @@ -50,9 +50,9 @@ func SyncNode(ctx context.Context, s *store.Store, vol *config.Volume, node *con // runNodeSession's deferred finishRun has committed the run's // terminal state by now, so the snapshot reflects this run's own row. // Peer-sync takes the local snapshot only — there is no ride-along to - // peer nodes (dest=nil), and the Snapshotter no-ops on non-terminal + // peer nodes (no shelf), and the Snapshotter no-ops on non-terminal // states and dry-run. - opts.Snapshot.afterSync(ctx, &rep, vol, nil) + opts.Snapshot.afterSync(ctx, &rep, nil) return rep, err } @@ -662,7 +662,8 @@ func isReservedSyncPath(p string) bool { return strings.HasPrefix(p, HistoryDirName+"/") || strings.HasPrefix(p, ConflictsDirName+"/") || strings.HasPrefix(p, RestoreHistoryDirName+"/") || - strings.HasPrefix(p, IndexDirName+"/") + strings.HasPrefix(p, IndexDirName+"/") || + strings.HasPrefix(p, StagingDirName+"/") } // isReservedFolderPath is the folder-path variant of @@ -674,7 +675,7 @@ func isReservedSyncPath(p string) bool { // rejects, aborting the whole walk. func isReservedFolderPath(p string) bool { return p == HistoryDirName || p == ConflictsDirName || p == RestoreHistoryDirName || - p == IndexDirName || isReservedSyncPath(p) + p == IndexDirName || p == StagingDirName || isReservedSyncPath(p) } // phaseTransfer streams every content object the plan asked for to the diff --git a/sync/packed.go b/sync/packed.go index 384d58e..5d6d516 100644 --- a/sync/packed.go +++ b/sync/packed.go @@ -97,7 +97,7 @@ type PackPreview struct { SizeBand int64 // destination pack_size (target compressed pack size) } -// packedHandler pushes a volume to a packed rclone destination. Content at +// packedHandler pushes a volume to a packed destination. Content at // or above dest.PackThreshold lands as a per-hash object exactly as the // content-addressed layout does (reusing contentPusher's object path); // content below the threshold is bundled into immutable tar.zst packs. Each @@ -107,13 +107,12 @@ type PackPreview struct { // // Durability: this handler uploads packs, records them in the local // packs/pack_members tables, reads each pack's scan-back fingerprint into -// remote_packs, and advances the destination durability vector at -// presence+size only once every pack this run assembled is -// fingerprint-verified alongside the placement map and manifest segment -// (see certifyPacked). The offload gate then certifies a packed content -// through its pack's verified remote_packs row. Large files reuse the -// content-addressed object path and keep its per-object remote_objects -// record and fingerprint capture. +// remote_packs, and advances the destination durability vector — as +// fingerprint-verified, never presence+size — only once every present +// content of the pair is fingerprint-verified (see advanceMethod). The +// offload gate then certifies a packed content through its pack's verified +// remote_packs row. Large files reuse the content-addressed object path and +// keep its per-object remote_objects record and fingerprint capture. type packedHandler struct { contentPusher } @@ -123,86 +122,52 @@ func (h *packedHandler) TargetName() string { return h.dest.Name } func (h *packedHandler) sealed() {} func (h *packedHandler) Push(ctx context.Context, opts Options) (Report, error) { - rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} - // Presence+size is the strongest check the packed push claims; it is - // not content-verified (crypt remotes expose no hashes, and packs carry - // no fingerprint until PR 3), so results stay unverified. - rep.Verification.Method = VerifyMethodPresenceSize + defer h.art.close() if h.vol.Name == ObjectsDirName || h.vol.Name == PacksDirName { + rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} + rep.Verification.Method = VerifyMethodPresenceSize return rep, fmt.Errorf("volume %q: the name collides with the destination-root %s/ directory of packed destination %q — rename the volume or use a mirrored destination", h.vol.Name, h.vol.Name, h.dest.Name) } - volID, err := requireIndexedVolume(ctx, h.store, h.vol) - if err != nil { - return rep, err - } - if opts.DryRun { - if _, err := h.checkNamingScheme(ctx); err != nil { - return rep, err - } - return rep, h.previewDryRun(ctx, &rep, volID) - } - if err := h.ensureMarkers(ctx, opts.Init); err != nil { - return rep, err - } - // shallow=true: neither the per-object copyto nor the pack copyto - // carries a BLAKE3 end-to-end check, and the audit trail stays honest. - runID, err := beginSyncRunGuarded(ctx, h.store, false, store.SyncRunSpec{ - VolumeID: volID, - Destination: h.dest.Name, - Shallow: true, - }, h.vol.Name) - if err != nil { - return rep, err - } - rep.RunID = runID - if opts.OnRunID != nil { - opts.OnRunID(runID) - } - - err = h.push(ctx, &rep, volID, runID) - finishHandlerRun(ctx, h.store, &rep, err) - opts.Snapshot.afterSync(ctx, &rep, h.vol, h.dest) - return rep, err -} - -// previewDryRun reports what a real packed push would do — which content -// would upload as per-hash objects vs. be bundled into packs — without -// assembling or uploading any pack and without writing a runs row: -// rep.RunID stays 0 and no packs, pack_members, remote_*, objects, or -// pack artifacts are written. It computes the same delta and routing the -// real push does (watermark → delta → routeBySize); the object side lands -// on rep.RcloneResult exactly as the content-addressed preview reports it, -// the pack side on rep.PackPreview. The watermark check still reads the -// destination, so a layout-flip is refused here too. -func (h *packedHandler) previewDryRun(ctx context.Context, rep *Report, volID int64) error { - watermark, err := h.watermark(ctx, volID) - if err != nil { - return err - } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) - } - rep.Verification.Files = int64(len(delta)) - large, small, err := h.routeBySize(ctx, rep, plannedUploads(delta)) - if err != nil { - return err - } - if err := h.previewObjectUploads(ctx, rep, large); err != nil { - return err - } - rep.PackPreview = h.previewPacks(small) - rep.Status = store.RunStatusSuccess - return nil + return pushThrough(ctx, h.target(), h, opts) } -// previewPacks summarises the small (pack-routed) content routeBySize -// selected, without assembling a pack. small is already hash-sorted, so -// the size-band walk mirrors buildOnePack's — accumulate members until the -// running total reaches PackSize, then close a pack — but over uncompressed -// sizes, yielding an estimated (not bounded) pack count (see PackPreview). -func (h *packedHandler) previewPacks(small []store.PathDelta) PackPreview { - p := PackPreview{SizeBand: h.dest.PackSize} +// packedOps is the packed translation of a plan: the large content routed +// to per-hash objects, the small content still to be packed (hash-sorted, +// so assembly is deterministic), and how much small content an earlier +// pack already holds. execute fills in the packs it landed, which seal +// records. +type packedOps struct { + objects objectUploads + members []store.PathDelta + alreadyInPack int64 + packSize int64 + + packs []landedPack + placements []PlacementEntry +} + +// landedPack is one pack execute landed: the rows to record, and the +// fingerprint the landing confirmed, nil while capture must read one. +type landedPack struct { + write store.PackWrite + fingerprint *remoteChecksum +} + +// preview reports the object side on rep.RcloneResult, exactly as the +// content-addressed preview does, and the pack side on rep.PackPreview. +func (o *packedOps) preview(rep *Report) { + o.objects.preview(rep) + rep.RcloneResult.Checked += o.alreadyInPack + rep.PackPreview = previewPacks(o.members, o.packSize) +} + +// previewPacks summarises the small (pack-routed) content without +// assembling a pack. small is already hash-sorted, so the size-band walk +// mirrors buildOnePack's — accumulate members until the running total +// reaches packSize, then close a pack — but over uncompressed sizes, +// yielding an estimated (not bounded) pack count (see PackPreview). +func previewPacks(small []store.PathDelta, packSize int64) PackPreview { + p := PackPreview{SizeBand: packSize} for i := 0; i < len(small); { var packBytes int64 for i < len(small) { @@ -210,7 +175,7 @@ func (h *packedHandler) previewPacks(small []store.PathDelta) PackPreview { p.Contents++ p.Bytes += small[i].SizeBytes i++ - if packBytes >= h.dest.PackSize { + if packBytes >= packSize { break } } @@ -219,65 +184,62 @@ func (h *packedHandler) previewPacks(small []store.PathDelta) PackPreview { return p } -// push runs the transactional landing: delta → objects (large) + packs -// (small) → placement map → manifest segment → local pack rows → per-pack -// fingerprints → vector advance. rep.Status starts failed and is promoted -// only after every piece is confirmed present, so a partial landing never -// presents as success. -func (h *packedHandler) push(ctx context.Context, rep *Report, volID, runID int64) error { - rep.Status = store.RunStatusFailed - watermark, err := h.watermark(ctx, volID) - if err != nil { - return err - } - // Snapshot the advance before any transfer so a row committed mid-push - // is never folded into it — the same discipline the content-addressed - // handler uses. - advance, err := captureDurabilityAdvance(ctx, h.store, volID) +// translate routes the delta's present content by dest.PackThreshold (see +// routeBySize) and splits the large side by upload record. +func (h *packedHandler) translate(ctx context.Context, p pushPlan) (*packedOps, error) { + large, small, alreadyInPack, err := h.routeBySize(ctx, plannedUploads(p.delta)) if err != nil { - return err - } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) + return nil, err } - rep.Verification.Files = int64(len(delta)) - // Same reading as the content-addressed push: the delta is what this - // run changes at the destination, so an empty one folds as a no-op. - rep.Changed = knownChanged(int64(len(delta))) - large, small, err := h.routeBySize(ctx, rep, plannedUploads(delta)) + objects, err := h.splitRecorded(ctx, large) if err != nil { - return err + return nil, err } - if err := h.uploadObjects(ctx, rep, runID, large); err != nil { + return &packedOps{objects: objects, members: small, alreadyInPack: alreadyInPack, packSize: h.dest.PackSize}, nil +} + +// execute lands the large content as objects, then assembles and uploads +// the small content's packs. Nothing about the packs is recorded in the +// store yet: seal does that once the map and segment landed. +func (h *packedHandler) execute(ctx context.Context, rep *Report, runID int64, ops *packedOps) error { + rep.RcloneResult.Checked += ops.alreadyInPack + if err := h.uploadObjects(ctx, rep, runID, ops.objects); err != nil { return err } - writes, placements, err := h.assembleAndUploadPacks(ctx, rep, runID, small) + packs, placements, err := h.assembleAndUploadPacks(ctx, rep, runID, ops.members) if err != nil { return err } - if err := h.uploadPlacementMap(ctx, placements, runID); err != nil { + ops.packs, ops.placements = packs, placements + return nil +} + +// seal writes the placement map (the layout's landing evidence) and the +// manifest segment, then records the packs and reads their fingerprints. +// A pack_members row therefore always has its bytes, and their location, +// offsite, and a run that failed earlier left nothing here to re-pack. +func (h *packedHandler) seal(ctx context.Context, rep *Report, runID int64, p pushPlan, ops *packedOps) error { + if err := h.uploadPlacementMap(ctx, ops.placements, runID); err != nil { return err } - if err := h.uploadSegment(ctx, delta, runID); err != nil { + if err := h.uploadSegment(ctx, p.delta, runID); err != nil { return err } - // Recorded only after every pack, the map, and the segment confirmed - // landing: a pack_members row always has its bytes (and their location) - // offsite, and a run that failed earlier left nothing here to re-pack. + writes := make([]store.PackWrite, len(ops.packs)) + for i, lp := range ops.packs { + writes[i] = lp.write + } if err := h.store.InsertPacks(ctx, writes); err != nil { return fmt.Errorf("record packs for run %d: %w", runID, err) } - rep.Status = store.RunStatusSuccess - rep.Verification.Bytes = rep.RcloneResult.Bytes - return h.certifyPacked(ctx, rep, volID, runID, writes, advance) + h.capturePackFingerprints(ctx, rep, runID, ops.packs) + return nil } -// certifyPacked closes the durability seam: it records a remote_packs row -// per landed pack, reads each pack's scan-back fingerprint, and advances -// the destination vector to fingerprint-verified only once the whole -// (volume, destination) pair carries a verified fingerprint behind every -// present file content. That whole-state check is +// advanceMethod closes the durability seam: the vector advances as +// fingerprint-verified only once the whole (volume, destination) pair +// carries a verified fingerprint behind every present file content, and is +// held otherwise. That whole-state check is // CountVolumeContentsPendingFingerprint, which counts present contents // lacking a verified remote_objects (per-hash object) or remote_packs (pack // member) fingerprint on this destination — so it covers packs and per-hash @@ -285,11 +247,8 @@ func (h *packedHandler) push(ctx context.Context, rep *Report, volID, runID int6 // // The placement map and manifest segment are deliberately NOT in that // pending set: they are re-derivable squirrel-written metadata that carry -// no scan-back fingerprint. Their durability before this advance is handled -// upstream in push, which uploads and confirms both landed at their -// expected size before promoting the run to success — a run whose map or -// segment failed to land returns failed and never reaches certifyPacked, so -// the vector is untouched. +// no scan-back fingerprint, and seal confirmed both landed at their +// expected size before this runs. // // Gating on the whole pending set rather than this run's writes is the // friction-log F13 fix: a run that packs nothing no longer advances @@ -297,40 +256,33 @@ func (h *packedHandler) push(ctx context.Context, rep *Report, volID, runID int6 // anywhere in the pair holds the whole advance. `squirrel verify` fills a // pending fingerprint later and re-attempts this advance itself (see the // store upgrade), so the vector no longer stalls until the next -// content-writing sync. rep.Verification stays unverified (presence+size is -// not content-verified), so RunPair does not advance the vector a second -// time. -func (h *packedHandler) certifyPacked(ctx context.Context, rep *Report, volID, runID int64, writes []store.PackWrite, advance []store.OriginComponent) error { - h.capturePackFingerprints(ctx, rep, runID, writes) - pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, volID, h.dest.Name) +// content-writing sync. +func (h *packedHandler) advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) { + pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, p.volumeID, h.dest.Name) if err != nil { - return fmt.Errorf("count pending fingerprints for %s: %w", h.dest.Name, err) + return "", fmt.Errorf("count pending fingerprints for %s: %w", h.dest.Name, err) } if pending > 0 { rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %d content(s) are not yet fingerprint-verified; the durability vector was not advanced — run `squirrel verify` to certify them", h.dest.Name, pending)) - return nil - } - if len(advance) == 0 { - return nil - } - if err := h.store.AdvanceDestinationVectorTo(ctx, volID, h.dest.Name, store.VerifyMethodFingerprint, advance); err != nil { - return fmt.Errorf("advance destination vector for %s: %w", h.dest.Name, err) + return "", nil } - return nil + return store.VerifyMethodFingerprint, nil } // capturePackFingerprints records a per-destination upload row for each -// landed pack and fills its scan-back fingerprint, reusing the shared -// capture surface over the packs/ directory. Every pack exceeds the -// multipart threshold, so on s3 the composite ETag is read from the S3 API -// (never rclone's md5 slot, which is blank for a multipart object); other -// backends read `rclone lsjson --hash`. A pack whose fingerprint could not -// be read stays pending (checksum NULL) with a warning — never a fabricated -// value. The whole-pair pending tally (CountVolumeContentsPendingFingerprint) -// is what certifyPacked gates the vector advance on, so this returns nothing. -func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report, runID int64, writes []store.PackWrite) { - targets := make([]captureTarget, 0, len(writes)) - for _, w := range writes { +// landed pack, with the fingerprint its landing confirmed or, failing +// that, one read back over the shared capture surface on the packs/ +// directory. Every pack exceeds the multipart threshold, so on s3 the +// composite ETag is read from the S3 API (never rclone's md5 slot, which +// is blank for a multipart object); other rclone backends read `rclone +// lsjson --hash`. A pack whose fingerprint could not be read stays pending +// (checksum NULL) with a warning — never a fabricated value. The whole-pair +// pending tally (CountVolumeContentsPendingFingerprint) is what +// advanceMethod gates the vector advance on, so this returns nothing. +func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report, runID int64, packs []landedPack) { + targets := make([]captureTarget, 0, len(packs)) + for _, lp := range packs { + w := lp.write pack, err := h.store.GetPackByKey(ctx, w.Pack.PackKey) if err != nil { rep.Warnings = append(rep.Warnings, fmt.Sprintf("look up recorded pack %s: %v", hex.EncodeToString(w.Pack.PackKey), err)) @@ -343,6 +295,14 @@ func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report continue } packID := pack.ID + if cs := lp.fingerprint; cs != nil { + if err := h.store.SetRemotePackFingerprint(ctx, packID, h.dest.Name, cs.Algo, cs.Value, store.NowNs()); err != nil { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("record fingerprint for pack %s: %v", hex.EncodeToString(w.Pack.PackKey), err)) + continue + } + rep.Fingerprints++ + continue + } targets = append(targets, captureTarget{ name: h.names().pack(w.Pack.PackKey), label: "pack", @@ -351,44 +311,31 @@ func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report }, }) } - h.captureScanBackFingerprints(ctx, rep, PacksDirName, targets) + if len(targets) > 0 { + h.art.capture(ctx, rep, PacksDirName, targets) + } } -// watermark resolves the run id the delta starts after: the last -// successful sync of this (volume, destination), or 0 for a fresh -// destination. The last success must still have its placement map at the -// destination — every successful packed run uploads one (empty when no -// small content was new) — so its absence means the recorded history -// belongs to a different layout (a mirror leaves no map, a -// content-addressed root leaves objects and segments but no packs/ map) and -// a delta computed against it would silently skip everything that era -// covered. This is the packed analogue of the content-addressed watermark -// guard, strengthened to also refuse an object-per-hash history. -func (h *packedHandler) watermark(ctx context.Context, volID int64) (int64, error) { - last, err := h.store.LatestSuccessfulSyncRun(ctx, volID, h.dest.Name) - if store.IsNotFound(err) { - return 0, nil - } - if err != nil { - return 0, fmt.Errorf("lookup last successful sync of %s: %w", h.dest.Name, err) - } - mapURI := h.mapURI(last.ID) - if _, err := h.rcl.statRemote(ctx, mapURI, checkersArgs(h.dest)...); err != nil { - if freshStartOnEmptyRoot(ctx, h.rcl, h.dest) { - return 0, nil - } - return 0, fmt.Errorf("destination %q: the last successful sync (run %d) left no pack placement map at %s — its history is not packed (a mirror or content-addressed root); point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w: %w", h.dest.Name, last.ID, mapURI, h.dest.Name, err, ErrRefused) - } - return last.ID, nil +// landed reports whether runID's placement map is at the destination. +// Every successful packed run uploads one (empty when no small content was +// new), so its absence means the recorded history belongs to a different +// layout — a mirror leaves no map, a content-addressed root leaves objects +// and segments but no packs/ map — or a wiped root. +func (h *packedHandler) landed(ctx context.Context, runID int64) (bool, error) { + return h.art.exists(ctx, mapName(runID)) +} + +func (h *packedHandler) foreignHistory(runID int64) error { + return fmt.Errorf("destination %q: the last successful sync (run %d) left no pack placement map at %s — its history is not packed (a mirror or content-addressed root); point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.art.where(mapName(runID)), h.dest.Name, ErrRefused) } // routeBySize splits the planned uploads by dest.PackThreshold: content at // or above it becomes a per-hash object (large), content below it becomes a // pack member (small) unless it is already packed — a pack is // content-global and assembled once, so already-packed content is skipped -// and counted as checked. small is returned sorted by hash so pack -// assembly is deterministic. -func (h *packedHandler) routeBySize(ctx context.Context, rep *Report, planned []store.PathDelta) (large, small []store.PathDelta, err error) { +// and counted. small is returned sorted by hash so pack assembly is +// deterministic. +func (h *packedHandler) routeBySize(ctx context.Context, planned []store.PathDelta) (large, small []store.PathDelta, alreadyInPack int64, err error) { for _, d := range planned { if d.SizeBytes >= h.dest.PackThreshold { large = append(large, d) @@ -396,10 +343,10 @@ func (h *packedHandler) routeBySize(ctx context.Context, rep *Report, planned [] } packed, err := h.store.HasPackMember(ctx, d.ContentID) if err != nil { - return nil, nil, fmt.Errorf("lookup pack member for %s: %w", d.Path, err) + return nil, nil, 0, fmt.Errorf("lookup pack member for %s: %w", d.Path, err) } if packed { - rep.RcloneResult.Checked++ + alreadyInPack++ continue } small = append(small, d) @@ -407,17 +354,17 @@ func (h *packedHandler) routeBySize(ctx context.Context, rep *Report, planned [] slices.SortFunc(small, func(a, b store.PathDelta) int { return bytes.Compare(a.Blake3, b.Blake3) }) - return large, small, nil + return large, small, alreadyInPack, nil } // assembleAndUploadPacks bundles the sorted small content into tar.zst // packs, staging and uploading one pack at a time so memory and disk stay -// bounded regardless of corpus size. It returns the pack rows to record +// bounded regardless of corpus size. It returns the packs to record // locally and the placement entries for the run's map; nothing is recorded // in the store here (push does that only after the map and segment land). -func (h *packedHandler) assembleAndUploadPacks(ctx context.Context, rep *Report, runID int64, small []store.PathDelta) ([]store.PackWrite, []PlacementEntry, error) { +func (h *packedHandler) assembleAndUploadPacks(ctx context.Context, rep *Report, runID int64, small []store.PathDelta) ([]landedPack, []PlacementEntry, error) { level := zstdEncoderLevel(h.dest.ZstdLevel) - var writes []store.PackWrite + var packs []landedPack var placements []PlacementEntry for i := 0; i < len(small); { pack, next, err := h.buildOnePack(small, i, level) @@ -425,15 +372,16 @@ func (h *packedHandler) assembleAndUploadPacks(ctx context.Context, rep *Report, return nil, nil, err } i = next - if err := h.uploadPack(ctx, pack); err != nil { + fingerprint, err := h.uploadPack(ctx, runID, pack) + if err != nil { return nil, nil, err } rep.RcloneResult.Transferred++ rep.RcloneResult.Bytes += pack.compressedSize - writes = append(writes, pack.toWrite(runID)) + packs = append(packs, landedPack{write: pack.toWrite(runID), fingerprint: fingerprint}) placements = append(placements, pack.placements()...) } - return writes, placements, nil + return packs, placements, nil } // buildOnePack assembles content from srcs starting at index start into a @@ -483,25 +431,17 @@ func (h *packedHandler) buildOnePack(srcs []store.PathDelta, start int, level zs return assembledPack{tmpPath: tmp.Name(), key: key, compressedSize: size, members: members}, i, nil } -// uploadPack copies one staged pack to packs/ through the -// crypt overlay and confirms it landed at the compressed size, then removes -// the temp file. Through a crypt overlay the reported size is the decrypted -// length, which is the compressed pack, so it compares directly. -func (h *packedHandler) uploadPack(ctx context.Context, pack assembledPack) error { +// uploadPack lands one staged pack at packs/, confirmed at +// its compressed size and its key — the BLAKE3 of those bytes — then +// removes the temp file. Through a crypt overlay the reported size is the +// decrypted length, which is the compressed pack, so it compares directly. +func (h *packedHandler) uploadPack(ctx context.Context, runID int64, pack assembledPack) (*remoteChecksum, error) { defer func() { _ = os.Remove(pack.tmpPath) }() - hexKey := hex.EncodeToString(pack.key) - uri := h.packURI(pack.key) - if err := h.rcl.copyTo(ctx, pack.tmpPath, uri, checkersArgs(h.dest)...); err != nil { - return fmt.Errorf("upload pack %s: %w", hexKey, err) - } - size, err := h.rcl.statRemote(ctx, uri, checkersArgs(h.dest)...) + fingerprint, err := putArtifact(ctx, h.art, runID, artifactPut{name: h.packName(pack.key), src: pack.tmpPath, size: pack.compressedSize, sum: pack.key}) if err != nil { - return fmt.Errorf("confirm pack %s after upload: %w", hexKey, err) + return nil, fmt.Errorf("upload pack %s: %w", hex.EncodeToString(pack.key), err) } - if size != pack.compressedSize { - return fmt.Errorf("pack %s landed with size %d, want %d", hexKey, size, pack.compressedSize) - } - return nil + return fingerprint, nil } // uploadPlacementMap writes the run's placement map and confirms it landed @@ -513,49 +453,19 @@ func (h *packedHandler) uploadPlacementMap(ctx context.Context, placements []Pla if err != nil { return err } - return h.uploadBytes(ctx, body, h.mapURI(runID), "placement map") -} - -// uploadBytes stages body in a temp file, copies it to uri through the -// crypt overlay, and confirms it landed at len(body). what names the -// artifact in error messages. -func (h *contentPusher) uploadBytes(ctx context.Context, body []byte, uri, what string) error { - tmp, err := os.CreateTemp("", "squirrel-meta-*") - if err != nil { - return fmt.Errorf("stage %s: %w", what, err) - } - defer func() { _ = os.Remove(tmp.Name()) }() - if _, err := tmp.Write(body); err != nil { - _ = tmp.Close() - return fmt.Errorf("write %s: %w", what, err) - } - if err := tmp.Close(); err != nil { - return fmt.Errorf("close %s: %w", what, err) - } - if err := h.rcl.copyTo(ctx, tmp.Name(), uri, checkersArgs(h.dest)...); err != nil { - return fmt.Errorf("upload %s to %s: %w", what, uri, err) - } - size, err := h.rcl.statRemote(ctx, uri, checkersArgs(h.dest)...) - if err != nil { - return fmt.Errorf("confirm %s at %s: %w", what, uri, err) - } - if size != int64(len(body)) { - return fmt.Errorf("%s at %s landed with size %d, want %d", what, uri, size, len(body)) - } - return nil + return putBytes(ctx, h.art, runID, mapName(runID), body, "placement map") } -// packURI addresses one pack under the destination-root packs/ directory, -// through the crypt overlay when the destination has one. The basename is -// namer.pack's. -func (h *packedHandler) packURI(packKey []byte) string { - return remoteSubpathURI(h.dest, path.Join(PacksDirName, h.names().pack(packKey))) +// packName is one pack under the destination-root packs/ directory. The +// basename is namer.pack's. +func (h *packedHandler) packName(packKey []byte) string { + return path.Join(PacksDirName, h.names().pack(packKey)) } -// mapURI addresses one run's placement map under the destination-root -// packs/ directory. -func (h *packedHandler) mapURI(runID int64) string { - return remoteSubpathURI(h.dest, path.Join(PacksDirName, packMapPrefix+strconv.FormatInt(runID, 10))) +// mapName is one run's placement map under the destination-root packs/ +// directory. +func mapName(runID int64) string { + return path.Join(PacksDirName, packMapPrefix+strconv.FormatInt(runID, 10)) } // zstdEncoderLevel maps the config's 1..4 zstd level onto klauspost's diff --git a/sync/push.go b/sync/push.go new file mode 100644 index 0000000..70df788 --- /dev/null +++ b/sync/push.go @@ -0,0 +1,246 @@ +package sync + +import ( + "context" + "fmt" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// pushPlan is what one push must land: the volume's index changes since the +// destination's last confirmed run, and the durability snapshot the push +// advances to once they land. +type pushPlan struct { + volumeID int64 + watermark int64 // last confirmed run; 0 for a fresh destination + delta []store.PathDelta // ListPathDeltaSince(volumeID, watermark) + advance []store.OriginComponent // captured before any transfer; nil on a dry run +} + +// operations is one layout's translation of a plan into work. +type operations interface { + // preview records on rep what executing the operations would transfer. + // It is all a dry run reports. + preview(rep *Report) +} + +// layout is one destination layout's part of a push. pushThrough runs every +// layout through the same sequence, so the watermark rule, run allocation +// and durability advance are decided once for all of them. +type layout[O operations] interface { + // markers gates the push on the destination's markers, writing missing + // ones under opts.Init. A dry run only checks. + markers(ctx context.Context, rep *Report, volumeID int64, opts Options) error + // landed reports whether runID left this layout's landing evidence. + landed(ctx context.Context, runID int64) (bool, error) + // rootEmpty reports whether the destination root holds nothing beyond + // squirrel's markers. + rootEmpty(ctx context.Context) (bool, error) + // foreignHistory is the refusal for a last success at runID that left + // no landing evidence on a destination that is no fresh start. + foreignHistory(runID int64) error + // firstPush gates a push of a volume that never synced to the + // destination, from watermark 0, on what the destination already + // holds: nil, or the refusal. + firstPush(ctx context.Context, volumeID int64) error + // reconcile settles, once at push start, whatever an earlier push left + // in flight on the destination, so translate reads settled records. + reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error + // translate turns the plan into this layout's operations. It reads + // squirrel's records and writes nothing: a dry run is translate alone. + translate(ctx context.Context, p pushPlan) (O, error) + // execute performs the operations and records each confirmed one. + execute(ctx context.Context, rep *Report, runID int64, ops O) error + // seal writes the run's landing evidence once every operation is + // confirmed. + seal(ctx context.Context, rep *Report, runID int64, p pushPlan, ops O) error + // advanceMethod names the evidence the confirmed landing earns. An + // empty method holds the durability vector where it is. + advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) + // shelf is the destination's .squirrel-index/ directory, where + // runID's ride-along index snapshot lands. + shelf(runID int64) snapshotShelf +} + +// pushTarget is the (volume, destination) pair one layout push serves. +type pushTarget struct { + store *store.Store + vol *config.Volume + dest *config.Destination +} + +// pushThrough is the single push driver every layout shares: +// +// requireIndexedVolume → markers → begin run → reconcile → plan → translate → execute → seal → advance → finish → ride-along +// +// A dry run stops after translate and reports the operations' preview; it +// writes no runs row. The runs row records shallow=true: every layout +// confirms what landed by presence and size, and the audit trail says so. +func pushThrough[O operations](ctx context.Context, t pushTarget, l layout[O], opts Options) (Report, error) { + rep := Report{Volume: t.vol.Name, Destination: t.dest.Name, Layout: t.dest.Layout} + // Stamped up front so output renderers key their formatting off the + // method even when the push fails early. + rep.Verification.Method = VerifyMethodPresenceSize + volID, err := requireIndexedVolume(ctx, t.store, t.vol) + if err != nil { + return rep, err + } + if err := l.markers(ctx, &rep, volID, opts); err != nil { + return rep, err + } + if opts.DryRun { + return rep, previewPush(ctx, t, l, &rep, volID) + } + runID, err := beginSyncRunGuarded(ctx, t.store, false, store.SyncRunSpec{ + VolumeID: volID, + Destination: t.dest.Name, + Shallow: true, + }, t.vol.Name) + if err != nil { + return rep, err + } + rep.RunID = runID + if opts.OnRunID != nil { + opts.OnRunID(runID) + } + err = landPush(ctx, t, l, &rep, volID, runID) + finishHandlerRun(ctx, t.store, &rep, err) + opts.Snapshot.afterSync(ctx, &rep, l.shelf(runID)) + return rep, err +} + +// previewPush computes the same plan and translation a real push would, +// then reports the translation's preview. The watermark rule still reads +// the destination, so a dry run refuses exactly what a push would. +func previewPush[O operations](ctx context.Context, t pushTarget, l layout[O], rep *Report, volID int64) error { + p, err := planPush(ctx, t, l, volID, false) + if err != nil { + return err + } + rep.Verification.Files = int64(len(p.delta)) + ops, err := l.translate(ctx, p) + if err != nil { + return err + } + ops.preview(rep) + rep.Status = store.RunStatusSuccess + return nil +} + +// landPush is the transactional landing: plan → operations → evidence → +// vector. rep.Status starts failed and is promoted only after the vector +// advanced: a confirmed landing whose evidence failed to record must not +// present as success, or the next watermark would skip past it. +func landPush[O operations](ctx context.Context, t pushTarget, l layout[O], rep *Report, volID, runID int64) error { + rep.Status = store.RunStatusFailed + if err := l.reconcile(ctx, rep, volID, runID); err != nil { + return err + } + p, err := planPush(ctx, t, l, volID, true) + if err != nil { + return err + } + rep.Verification.Files = int64(len(p.delta)) + // The delta is what this push newly records at the destination, so an + // empty one is a genuine no-op, which is what the runs fold keys on + // (#182). + rep.Changed = knownChanged(int64(len(p.delta))) + ops, err := l.translate(ctx, p) + if err != nil { + return err + } + if err := l.execute(ctx, rep, runID, ops); err != nil { + return err + } + if err := l.seal(ctx, rep, runID, p, ops); err != nil { + return err + } + method, err := l.advanceMethod(ctx, rep, p) + if err != nil { + return err + } + if method != "" && len(p.advance) > 0 { + if err := t.store.AdvanceDestinationVectorTo(ctx, volID, t.dest.Name, method, p.advance); err != nil { + return fmt.Errorf("advance destination vector for %s: %w", t.dest.Name, err) + } + } + rep.Status = store.RunStatusSuccess + rep.Verification.Bytes = rep.RcloneResult.Bytes + return nil +} + +// planPush resolves the watermark and the delta after it. A real push also +// captures the durability advance, before the delta, so a row committed +// mid-push is never folded into it. +func planPush[O operations](ctx context.Context, t pushTarget, l layout[O], volID int64, captureAdvance bool) (pushPlan, error) { + watermark, err := pushWatermark(ctx, t, l, volID) + if err != nil { + return pushPlan{}, err + } + p := pushPlan{volumeID: volID, watermark: watermark} + if captureAdvance { + if p.advance, err = captureDurabilityAdvance(ctx, t.store, volID); err != nil { + return pushPlan{}, err + } + } + if p.delta, err = t.store.ListPathDeltaSince(ctx, volID, watermark); err != nil { + return pushPlan{}, fmt.Errorf("compute path delta since run %d: %w", watermark, err) + } + return p, nil +} + +// pushWatermark applies the watermark rule every layout shares: +// +// 1. no successful sync of this (volume, destination): 0, once the +// layout's firstPush gate passes; +// 2. the last success left its landing evidence: that run's id; +// 3. the evidence is absent but the destination is a fresh start +// (freshStart): 0; +// 4. otherwise refuse, because a delta computed against a history this +// destination no longer shows would silently skip content. +func pushWatermark[O operations](ctx context.Context, t pushTarget, l layout[O], volID int64) (int64, error) { + last, err := t.store.LatestSuccessfulSyncRun(ctx, volID, t.dest.Name) + if store.IsNotFound(err) { + return 0, l.firstPush(ctx, volID) + } + if err != nil { + return 0, fmt.Errorf("lookup last successful sync of %s: %w", t.dest.Name, err) + } + landed, err := l.landed(ctx, last.ID) + if err != nil { + return 0, fmt.Errorf("destination %q: look up the landing evidence of run %d: %w", t.dest.Name, last.ID, err) + } + if landed { + return last.ID, nil + } + fresh, err := freshStart(ctx, t, l) + if err != nil { + return 0, err + } + if fresh { + return 0, nil + } + return 0, l.foreignHistory(last.ID) +} + +// freshStart reports whether a destination whose last success left no +// landing evidence may start over from watermark 0: its root holds nothing +// beyond squirrel's markers, and squirrel holds no upload records for it. +// An empty root with records left behind was wiped without a `squirrel +// destination reset`; starting over would skip every upload those records +// still claim and close the run as success. +func freshStart[O operations](ctx context.Context, t pushTarget, l layout[O]) (bool, error) { + empty, err := l.rootEmpty(ctx) + if err != nil { + return false, fmt.Errorf("destination %q: check whether the root is empty: %w", t.dest.Name, err) + } + if !empty { + return false, nil + } + recorded, err := t.store.DestinationHasUploadRecords(ctx, t.dest.Name) + if err != nil { + return false, err + } + return !recorded, nil +} diff --git a/sync/push_test.go b/sync/push_test.go new file mode 100644 index 0000000..2e61861 --- /dev/null +++ b/sync/push_test.go @@ -0,0 +1,53 @@ +package sync + +import ( + "context" + "errors" + "slices" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +// TestPushRefusesWipedRootWithUploadRecords: a root wiped without a +// `squirrel destination reset` and re-marked looks like a fresh start, but +// the upload records still claim its content. Starting over would skip +// every recorded object, write a segment mapping paths onto bytes that are +// gone, and close the run as success, so the push refuses instead. A reset +// clears the records and lifts the refusal. +func TestPushRefusesWipedRootWithUploadRecords(t *testing.T) { + for layout, setup := range keyedArchiveFixtures() { + t.Run(layout, func(t *testing.T) { + f := setup(t) + f.write(t, "a.txt", "alpha") + f.index(t) + if _, err := f.sync(t); err != nil { + t.Fatalf("first push: %v", err) + } + + f.wipeRemote(t) + f.seedNamingMarker(t) + f.seedMarker(t, "pics") + markersOnly := f.remoteEntries(t) + rep, err := f.sync(t) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "destination reset") { + t.Fatalf("push to a wiped root: err = %v, want a refusal naming `destination reset`", err) + } + if rep.Status != store.RunStatusRefused { + t.Fatalf("Status = %q, want refused", rep.Status) + } + if after := f.remoteEntries(t); !slices.Equal(after, markersOnly) { + t.Fatalf("the refused push wrote to the root: %v, want only the markers %v", after, markersOnly) + } + + if _, _, err := f.store.ResetDestination(context.Background(), "offsite"); err != nil { + t.Fatalf("ResetDestination: %v", err) + } + rep, err = f.sync(t) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push after reset: status=%q err=%v", rep.Status, err) + } + }) + } +} diff --git a/sync/rclone.go b/sync/rclone.go index a2d0bd2..3d7c458 100644 --- a/sync/rclone.go +++ b/sync/rclone.go @@ -650,8 +650,7 @@ func (r *Rclone) listSnapshots(ctx context.Context, dirURI string) ([]string, er } var names []string for _, line := range strings.Split(string(out), "\n") { - name := strings.TrimSpace(line) - if strings.HasPrefix(name, snapshotPrefix) && strings.HasSuffix(name, ".db") { + if name := strings.TrimSpace(line); isSnapshotName(name) { names = append(names, name) } } diff --git a/sync/readback.go b/sync/readback.go new file mode 100644 index 0000000..f83176d --- /dev/null +++ b/sync/readback.go @@ -0,0 +1,39 @@ +package sync + +import ( + "context" + "errors" + "io" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" +) + +// errReadBackMismatch marks a stored file whose bytes, read back, are not +// the bytes squirrel sent: the disk kept something else. +var errReadBackMismatch = errors.New("the stored bytes read back differently from the bytes sent") + +// readsBack reports whether dest is a disk squirrel reads back, BLAKE3 over +// what it just stored, before trusting it: a local destination. On sftp +// squirrel asks the server's hash command instead, and downloads a file +// only to confirm one it finds already at an artifact's name. +func readsBack(dest *config.Destination) bool { + return dest.Type == "local" +} + +// readBack hashes the file at name as the destination returns it. The +// local transport reads past the page cache where the platform allows, so +// the hash covers what reached the disk. +func readBack(ctx context.Context, tr transport, name string) ([]byte, error) { + rc, err := tr.Get(ctx, name) + if err != nil { + return nil, err + } + defer func() { _ = rc.Close() }() + h := blake3.New() + if _, err := io.CopyBuffer(h, ctxReader{ctx: ctx, r: rc}, make([]byte, copyBufferSize)); err != nil { + return nil, err + } + return h.Sum(nil), nil +} diff --git a/sync/recover.go b/sync/recover.go index 003d2c0..30015d0 100644 --- a/sync/recover.go +++ b/sync/recover.go @@ -3,6 +3,9 @@ package sync import ( "context" "fmt" + "io" + "os" + "path" "sort" "strconv" "strings" @@ -43,15 +46,25 @@ func (s IndexSnapshot) Age(now time.Time) (time.Duration, bool) { // DiscoverIndexSnapshots lists the ride-along index snapshots a destination // holds for each named volume, newest first, then by volume. It is // read-only: it lists, it does not fetch, so an operator can be told what -// is recoverable before anything is touched. +// is recoverable before anything is touched. A native destination is +// listed through squirrel's own transport, so rcl may be nil for one. // // A volume directory that does not exist yields no snapshots rather than an // error — a destination that has simply never carried a given volume is a // normal answer to "what do you have", not a failure. func DiscoverIndexSnapshots(ctx context.Context, rcl *Rclone, dest *config.Destination, volumes []string) ([]IndexSnapshot, error) { + list := func(vol string) ([]string, error) { return listSnapshotsStrict(ctx, rcl, indexDirURI(dest, vol)) } + if dest.Native() { + tr, err := openReadOnly(ctx, dest) + if err != nil { + return nil, err + } + defer func() { _ = tr.Close() }() + list = func(vol string) ([]string, error) { return listSnapshotNames(ctx, tr, path.Join(vol, IndexDirName)) } + } var out []IndexSnapshot for _, vol := range volumes { - names, err := listSnapshotsStrict(ctx, rcl, indexDirURI(dest, vol)) + names, err := list(vol) if err != nil { return nil, fmt.Errorf("list index snapshots for %s/%s: %w", dest.Name, vol, err) } @@ -85,8 +98,7 @@ func listSnapshotsStrict(ctx context.Context, rcl *Rclone, dirURI string) ([]str } var names []string for _, line := range strings.Split(string(out), "\n") { - name := strings.TrimSpace(line) - if strings.HasPrefix(name, snapshotPrefix) && strings.HasSuffix(name, ".db") { + if name := strings.TrimSpace(line); isSnapshotName(name) { names = append(names, name) } } @@ -129,14 +141,48 @@ func parseSnapshotName(volume, name string) IndexSnapshot { return snap } -// FetchIndexSnapshot downloads one snapshot to localPath. It only moves the -// file; validating that the bytes are a usable index at this binary's -// schema version is store.PreflightCheckSnapshot's job, and the caller runs -// it before letting the file near the live database. +// FetchIndexSnapshot downloads one snapshot to localPath, which must not +// exist yet. It only moves the file; validating that the bytes are a +// usable index at this binary's schema version is +// store.PreflightCheckSnapshot's job, and the caller runs it before letting +// the file near the live database. rcl may be nil for a native destination. func FetchIndexSnapshot(ctx context.Context, rcl *Rclone, dest *config.Destination, snap IndexSnapshot, localPath string) error { - uri := indexDirURI(dest, snap.Volume) + "/" + snap.Name - if err := rcl.copyTo(ctx, uri, localPath); err != nil { + var err error + if dest.Native() { + err = fetchThroughTransport(ctx, dest, path.Join(snap.Volume, IndexDirName, snap.Name), localPath) + } else { + err = rcl.copyTo(ctx, indexDirURI(dest, snap.Volume)+"/"+snap.Name, localPath) + } + if err != nil { return fmt.Errorf("fetch index snapshot %s from %s: %w", snap.Name, dest.Name, err) } return nil } + +func fetchThroughTransport(ctx context.Context, dest *config.Destination, name, localPath string) error { + tr, err := openReadOnly(ctx, dest) + if err != nil { + return err + } + defer func() { _ = tr.Close() }() + f, err := os.OpenFile(localPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + if err := copyOut(ctx, tr, name, f); err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +// copyOut streams the file at name on tr into w. +func copyOut(ctx context.Context, tr transport, name string, w io.Writer) error { + rc, err := tr.Get(ctx, name) + if err != nil { + return err + } + defer func() { _ = rc.Close() }() + _, err = io.CopyBuffer(w, ctxReader{ctx: ctx, r: rc}, make([]byte, copyBufferSize)) + return err +} diff --git a/sync/restore_archive.go b/sync/restore_archive.go index 1e6b977..c3a7c11 100644 --- a/sync/restore_archive.go +++ b/sync/restore_archive.go @@ -6,14 +6,11 @@ import ( "cmp" "context" "encoding/hex" - "errors" "fmt" "io" "os" "path" - "path/filepath" "slices" - "strconv" "time" "github.com/klauspost/compress/zstd" @@ -28,20 +25,22 @@ import ( // destination. It resolves each requested path to a content hash from the // local index, locates the bytes (a per-hash object under objects/, or a // member inside a tar.zst pack under packs/), fetches through the same -// rclone (crypt) read path sync uses, and re-hashes every extracted -// content to BLAKE3 before writing — the misplacement/corruption check the -// offset/length pack slicing needs. Packs are fetched once per pack and -// every requested member is extracted from that single stream. +// read path sync writes through — squirrel's own transport on a native +// destination, rclone (and its crypt overlay) otherwise — and re-hashes +// every extracted content to BLAKE3 before writing: the +// misplacement/corruption check the offset/length pack slicing needs. +// Packs are fetched once per pack and every requested member is extracted +// from that single stream. type archiveRestore struct { - store *store.Store - rcl *Rclone - vol *config.Volume - dest *config.Destination - volID int64 - runID int64 - target string // resolved local directory (vol.Path or --to) - preserve bool // move overwritten files to .squirrel-restore-history/ - dryRun bool + store *store.Store + // fetchTo copies one destination-root artifact over the local file at + // localPath. + fetchTo func(ctx context.Context, name, localPath string) error + vol *config.Volume + dest *config.Destination + volID int64 + placer restorePlacer + dryRun bool } // restoreArchive orchestrates one content-addressed or packed restore: it @@ -51,28 +50,72 @@ type archiveRestore struct { // reason. Read-only against the index and destination throughout. func restoreArchive(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, dest *config.Destination, volID, runID int64, targetInPlace bool, opts RestoreOptions, rep *Report) error { rep.RunID = runID + fetchTo, release, err := archiveFetcher(ctx, rcl, dest, opts.DryRun) + if err != nil { + finishRestore(ctx, s, opts.DryRun, runID, rep, err) + return err + } + defer release() + ar := &archiveRestore{ + store: s, fetchTo: fetchTo, vol: vol, dest: dest, volID: volID, + placer: newRestorePlacer(vol, runID, targetInPlace, opts), dryRun: opts.DryRun, + } + runErr := ar.run(ctx, rep, opts.IncludeFromFile) + finishRestore(ctx, s, opts.DryRun, runID, rep, runErr) + return runErr +} + +// archiveFetcher is how a restore reads dest's artifacts: through one +// read-only transport for the whole restore on a native destination, +// through rclone otherwise. A dry run only counts, so it gets a nil fetcher. +// release closes what it opened. +func archiveFetcher(ctx context.Context, rcl *Rclone, dest *config.Destination, dryRun bool) (func(context.Context, string, string) error, func(), error) { + if !dest.Native() { + return func(ctx context.Context, name, localPath string) error { + return rcl.copyTo(ctx, remoteSubpathURI(dest, name), localPath, concurrencyArgs(dest)...) + }, func() {}, nil + } + if dryRun { + return nil, func() {}, nil + } + tr, err := openReadOnly(ctx, dest) + if err != nil { + return nil, nil, err + } + fetch := func(ctx context.Context, name, localPath string) error { + f, err := os.OpenFile(localPath, os.O_WRONLY|os.O_TRUNC, 0) + if err != nil { + return err + } + if err := copyOut(ctx, tr, name, f); err != nil { + _ = f.Close() + return err + } + return f.Close() + } + return fetch, func() { _ = tr.Close() }, nil +} + +// newRestorePlacer targets the volume's path, or --to. It preserves what +// it replaces only for an in-place restore that asked to (--in-place), +// mirroring the mirror layout's history contract. +func newRestorePlacer(vol *config.Volume, runID int64, targetInPlace bool, opts RestoreOptions) restorePlacer { target := vol.Path if opts.ToPath != "" { target = opts.ToPath } - ar := newArchiveRestore(s, rcl, vol, dest, volID, runID, target, targetInPlace && opts.InPlace, opts.DryRun) - runErr := ar.run(ctx, rep, opts.IncludeFromFile) + return restorePlacer{target: target, runID: runID, preserve: targetInPlace && opts.InPlace} +} + +// finishRestore writes a restore run's terminal state. A fatal error +// (nothing counted as an individual failure) is turned into a synthesised +// failed-file so the runs row carries the reason. +func finishRestore(ctx context.Context, s *store.Store, dryRun bool, runID int64, rep *Report, runErr error) { if runErr != nil && rep.RcloneResult.Errors == 0 { rep.RcloneResult.FatalError = true rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, FailedFile{Message: runErr.Error()}) } - finishRun(ctx, s, opts.DryRun, runID, rep) - return runErr -} - -// newArchiveRestore builds the restorer. preserve is set only for an -// in-place restore that must keep any overwritten bytes, mirroring the -// mirror layout's --backup-dir contract. -func newArchiveRestore(s *store.Store, rcl *Rclone, vol *config.Volume, dest *config.Destination, volID, runID int64, target string, preserve, dryRun bool) *archiveRestore { - return &archiveRestore{ - store: s, rcl: rcl, vol: vol, dest: dest, - volID: volID, runID: runID, target: target, preserve: preserve, dryRun: dryRun, - } + finishRun(ctx, s, dryRun, runID, rep) } // restoreContent is one content to restore and the volume-relative paths it @@ -224,17 +267,17 @@ func (ar *archiveRestore) restoreObject(ctx context.Context, rep *Report, c rest } tmp, err := ar.fetch(ctx, path.Join(ObjectsDirName, namerFor(ar.dest).object(c.blake3))) if err != nil { - ar.recordFailure(rep, c.firstPath(), err) + recordRestoreFailure(rep, c.firstPath(), err) return } defer func() { _ = os.Remove(tmp) }() digest, err := hashLocalFile(tmp) if err != nil { - ar.recordFailure(rep, c.firstPath(), fmt.Errorf("re-hash object: %w", err)) + recordRestoreFailure(rep, c.firstPath(), fmt.Errorf("re-hash object: %w", err)) return } if !bytes.Equal(digest, c.blake3) { - ar.recordFailure(rep, c.firstPath(), fmt.Errorf("object hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(c.blake3))) + recordRestoreFailure(rep, c.firstPath(), fmt.Errorf("object hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(c.blake3))) return } ar.place(rep, tmp, c) @@ -296,7 +339,7 @@ func (ar *archiveRestore) extractMembers(rep *Report, packTmp string, members [] } if !bytes.Equal(digest, m.content.blake3) { _ = os.Remove(memberTmp) - ar.recordFailure(rep, m.content.firstPath(), fmt.Errorf("pack member hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(m.content.blake3))) + recordRestoreFailure(rep, m.content.firstPath(), fmt.Errorf("pack member hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(m.content.blake3))) continue } ar.place(rep, memberTmp, m.content) @@ -328,9 +371,8 @@ func (ar *archiveRestore) readMember(r io.Reader, length int64) (string, []byte, } // fetch pulls one destination-root subpath (objects/ or -// packs/) to a local temp file through the same rclone read path — -// crypt overlay included — the push uses, and returns the temp path. The -// caller removes it. +// packs/) to a local temp file through the same read path the push +// writes through, and returns the temp path. The caller removes it. func (ar *archiveRestore) fetch(ctx context.Context, subpath string) (string, error) { tmp, err := os.CreateTemp("", "squirrel-restore-*") if err != nil { @@ -340,8 +382,7 @@ func (ar *archiveRestore) fetch(ctx context.Context, subpath string) (string, er _ = os.Remove(tmp.Name()) return "", fmt.Errorf("stage download: %w", err) } - uri := remoteSubpathURI(ar.dest, subpath) - if err := ar.rcl.copyTo(ctx, uri, tmp.Name(), checkersArgs(ar.dest)...); err != nil { + if err := ar.fetchTo(ctx, subpath, tmp.Name()); err != nil { _ = os.Remove(tmp.Name()) return "", fmt.Errorf("fetch %s: %w", subpath, err) } @@ -353,8 +394,8 @@ func (ar *archiveRestore) fetch(ctx context.Context, subpath string) (string, er // failure is recorded and does not stop the others. func (ar *archiveRestore) place(rep *Report, srcTmp string, c restoreContent) { for _, p := range c.paths { - if err := ar.writeOne(p, srcTmp); err != nil { - ar.recordFailure(rep, p.rel, err) + if err := ar.writeOne(p, srcTmp, c.blake3); err != nil { + recordRestoreFailure(rep, p.rel, err) continue } rep.RcloneResult.Transferred++ @@ -362,72 +403,16 @@ func (ar *archiveRestore) place(rep *Report, srcTmp string, c restoreContent) { } } -// writeOne copies the verified bytes to /, creating parent -// directories, refusing to write over a non-regular file (symlink, device, -// directory, …), preserving any overwritten regular file for an in-place -// restore, and stamping the index-recorded mtime. -func (ar *archiveRestore) writeOne(p restorePath, srcTmp string) error { - dst := filepath.Join(ar.target, filepath.FromSlash(p.rel)) - if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { - return fmt.Errorf("create target dir: %w", err) - } - if err := refuseNonRegularTarget(p.rel, dst); err != nil { - return err - } - if ar.preserve { - if err := ar.backupExisting(p.rel, dst); err != nil { - return err - } - } - if err := copyFileContents(srcTmp, dst); err != nil { - return err - } - t := time.Unix(0, p.mtimeNs) - if err := os.Chtimes(dst, t, t); err != nil { - return fmt.Errorf("set mtime on %s: %w", p.rel, err) - } - return nil -} - -// refuseNonRegularTarget refuses to write when the destination already -// exists as anything other than a regular file. Writing through a symlink -// with os.OpenFile would follow it and could clobber a path *outside* the -// restore target — a data-loss path squirrel must never take — so an -// existing symlink, device, fifo, socket, or directory is a hard refusal, -// not a silent skip. An absent path or a plain regular file is allowed. -func refuseNonRegularTarget(rel, dst string) error { - info, err := os.Lstat(dst) - if errors.Is(err, os.ErrNotExist) { - return nil - } +// writeOne places the bytes at srcTmp at p, re-checked against want and +// stamped with the index-recorded mtime. +func (ar *archiveRestore) writeOne(p restorePath, srcTmp string, want []byte) error { + f, err := os.Open(srcTmp) if err != nil { - return fmt.Errorf("stat target %s: %w", rel, err) - } - if !info.Mode().IsRegular() { - return fmt.Errorf("refusing to write %s: destination already exists as a non-regular file (%s) — squirrel will not follow or replace it", rel, info.Mode().Type()) - } - return nil -} - -// backupExisting moves an existing regular file at dst under the per-run -// restore-history subtree so an in-place overwrite never destroys prior -// bytes — the local-side counterpart of sync's --backup-dir. The caller -// has already refused any non-regular destination, so dst is absent or a -// regular file here. -func (ar *archiveRestore) backupExisting(rel, dst string) error { - if _, err := os.Lstat(dst); errors.Is(err, os.ErrNotExist) { - return nil - } else if err != nil { - return fmt.Errorf("stat existing %s: %w", rel, err) - } - backup := filepath.Join(ar.target, RestoreHistoryDirName, "run-"+strconv.FormatInt(ar.runID, 10), filepath.FromSlash(rel)) - if err := os.MkdirAll(filepath.Dir(backup), 0o755); err != nil { - return fmt.Errorf("create restore-history dir: %w", err) - } - if err := os.Rename(dst, backup); err != nil { - return fmt.Errorf("preserve overwritten %s: %w", rel, err) + return fmt.Errorf("open restored bytes: %w", err) } - return nil + defer func() { _ = f.Close() }() + _, err = ar.placer.place(p.rel, f, want, time.Unix(0, p.mtimeNs)) + return err } // countContent tallies the files (and bytes) a content would restore, @@ -437,8 +422,9 @@ func (ar *archiveRestore) countContent(rep *Report, c restoreContent) { rep.RcloneResult.Bytes += c.size * int64(len(c.paths)) } -// recordFailure counts one failed content and captures its message (capped). -func (ar *archiveRestore) recordFailure(rep *Report, object string, err error) { +// recordRestoreFailure counts one failed restore item and captures its +// message (capped). +func recordRestoreFailure(rep *Report, object string, err error) { rep.RcloneResult.Errors++ if int64(len(rep.RcloneResult.FailedFiles)) < maxFailedFiles { rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, FailedFile{Object: object, Message: err.Error()}) @@ -449,7 +435,7 @@ func (ar *archiveRestore) recordFailure(rep *Report, object string, err error) { // used when a whole pack could not be fetched or its stream broke. func (ar *archiveRestore) failMembers(rep *Report, members []packMemberRestore, err error) { for _, m := range members { - ar.recordFailure(rep, m.content.firstPath(), err) + recordRestoreFailure(rep, m.content.firstPath(), err) } } @@ -475,26 +461,3 @@ func loadIncludeSet(pathname string) (map[string]bool, error) { } return set, nil } - -// copyFileContents writes src's bytes to dst, truncating an existing file. -// The bytes are already BLAKE3-verified by the caller, so a plain copy is -// safe. -func copyFileContents(src, dst string) error { - in, err := os.Open(src) - if err != nil { - return fmt.Errorf("open restored bytes: %w", err) - } - defer func() { _ = in.Close() }() - out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) - if err != nil { - return fmt.Errorf("create %s: %w", dst, err) - } - if _, err := io.Copy(out, in); err != nil { - _ = out.Close() - return fmt.Errorf("write %s: %w", dst, err) - } - if err := out.Close(); err != nil { - return fmt.Errorf("close %s: %w", dst, err) - } - return nil -} diff --git a/sync/restore_mirror.go b/sync/restore_mirror.go new file mode 100644 index 0000000..ef17eb8 --- /dev/null +++ b/sync/restore_mirror.go @@ -0,0 +1,246 @@ +package sync + +import ( + "bufio" + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io/fs" + "maps" + "path" + "slices" + "strconv" + "strings" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// mirrorRestore restores a volume from a native mirror through a read-only +// transport. With an index that holds present paths for the volume, it +// fetches each of them by path and checks its bytes against the indexed +// BLAKE3 as they stream. Without one — a fresh machine — it walks the +// mirrored tree and checks each file against the mirror's receipts. +type mirrorRestore struct { + store *store.Store + vol *config.Volume + dest *config.Destination + volID int64 + tr transport + placer restorePlacer + dryRun bool +} + +// restoreMirror runs one native mirror restore and writes the +// kind='restore' runs row's terminal state. +func restoreMirror(ctx context.Context, s *store.Store, vol *config.Volume, dest *config.Destination, volID, runID int64, targetInPlace bool, opts RestoreOptions, rep *Report) error { + rep.RunID = runID + tr, err := openReadOnly(ctx, dest) + if err != nil { + finishRestore(ctx, s, opts.DryRun, runID, rep, err) + return err + } + defer func() { _ = tr.Close() }() + mr := &mirrorRestore{ + store: s, vol: vol, dest: dest, volID: volID, tr: tr, + placer: newRestorePlacer(vol, runID, targetInPlace, opts), dryRun: opts.DryRun, + } + runErr := mr.run(ctx, rep, opts.IncludeFromFile) + finishRestore(ctx, s, opts.DryRun, runID, rep, runErr) + return runErr +} + +func (mr *mirrorRestore) run(ctx context.Context, rep *Report, includeFile string) error { + rows, err := mr.store.ListPresentContent(ctx, mr.volID) + if err != nil { + return fmt.Errorf("list present content for %q: %w", mr.vol.Name, err) + } + switch { + case includeFile != "": + include, err := loadIncludeSet(includeFile) + if err != nil { + return err + } + mr.restoreIndexed(ctx, rep, slices.DeleteFunc(rows, func(r store.PathDelta) bool { return !include[r.Path] })) + case len(rows) > 0: + mr.restoreIndexed(ctx, rep, rows) + default: + if err := mr.restoreWalked(ctx, rep); err != nil { + return err + } + } + if rep.RcloneResult.Errors > 0 { + return fmt.Errorf("restore of %q from %q: %d file(s) failed", mr.vol.Name, mr.dest.Name, rep.RcloneResult.Errors) + } + return nil +} + +// restoreIndexed restores each present path the index names, checked +// against its indexed hash and stamped with its indexed mtime. +func (mr *mirrorRestore) restoreIndexed(ctx context.Context, rep *Report, rows []store.PathDelta) { + for _, r := range rows { + mr.restoreOne(ctx, rep, r.Path, r.SizeBytes, r.Blake3, time.Unix(0, r.MtimeNs)) + } +} + +// restoreWalked restores every file of the mirrored tree. A file a receipt +// names is checked against the content the newest such receipt recorded; +// the rest are restored unchecked, and counted in a warning. +func (mr *mirrorRestore) restoreWalked(ctx context.Context, rep *Report) error { + receipts, err := mr.readReceipts(ctx, rep) + if err != nil { + return err + } + unchecked, companions := 0, 0 + err = mr.walk(ctx, rep, "", func(rel string, e entry, companion bool) { + want, ok := receipts[rel] + switch { + case !ok && companion: + companions++ + return + case !ok: + unchecked++ + } + mr.restoreOne(ctx, rep, rel, e.size, want, e.mtime) + }) + if unchecked > 0 { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("%d file(s) on %q are named in no receipt, so their bytes could not be checked; they are restored unchecked", unchecked, mr.dest.Name)) + } + if companions > 0 { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("%d AppleDouble file(s) (._*) on %q, where macOS kept the extended attributes of the file beside each, are named in no receipt and not restored", companions, mr.dest.Name)) + } + return err +} + +// restoreOne fetches rel from the mirror and places it. A path that +// already holds the wanted bytes is left as it is and counted as already +// correct; a failure is recorded against rel and the restore goes on. +func (mr *mirrorRestore) restoreOne(ctx context.Context, rep *Report, rel string, size int64, want []byte, mtime time.Time) { + if want != nil && mr.placer.holds(rel, size, want) { + rep.RcloneResult.Checked++ + return + } + if mr.dryRun { + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += size + return + } + rc, err := mr.tr.Get(ctx, path.Join(mr.vol.Name, rel)) + if err != nil { + recordRestoreFailure(rep, rel, fmt.Errorf("fetch from %q: %w", mr.dest.Name, err)) + return + } + defer func() { _ = rc.Close() }() + n, err := mr.placer.place(rel, ctxReader{ctx: ctx, r: rc}, want, mtime) + if err != nil { + recordRestoreFailure(rep, rel, err) + return + } + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += n +} + +// walk visits every file of the mirrored tree under dir, leaving out +// squirrel's reserved entries at the volume root, and tells visit whether +// the file is the AppleDouble companion of an entry beside it. An entry +// that is neither a file nor a directory is reported and not restored. +func (mr *mirrorRestore) walk(ctx context.Context, rep *Report, dir string, visit func(rel string, e entry, companion bool)) error { + name := path.Join(mr.vol.Name, dir) + entries, err := mr.tr.List(ctx, name) + if err != nil { + return fmt.Errorf("list %s on %q: %w", name, mr.dest.Name, err) + } + names := entryNames(entries) + for _, e := range entries { + rel := path.Join(dir, e.name) + switch { + case !validName(rel) || path.Base(rel) != e.name: + return fmt.Errorf("list %s on %q: %w: %q", name, mr.dest.Name, errInvalidName, e.name) + case dir == "" && (isReservedFolderPath(e.name) || e.name == volmark.MarkerName): + case e.kind == kindDir: + if err := mr.walk(ctx, rep, rel, visit); err != nil { + return err + } + case e.kind == kindFile: + visit(rel, e, appleDouble(e.name, names)) + default: + rep.Warnings = append(rep.Warnings, fmt.Sprintf("%s on %q is neither a file nor a directory; it is not restored", rel, mr.dest.Name)) + } + } + return nil +} + +// readReceipts folds the mirror's receipts, oldest run first, into the +// BLAKE3 each path last held: a present entry overrides every earlier run. +// A receipt that cannot be read is reported and left out, so the paths it +// covered are checked against older receipts. +func (mr *mirrorRestore) readReceipts(ctx context.Context, rep *Report) (map[string][]byte, error) { + dir := path.Join(mr.vol.Name, IndexDirName) + entries, err := mr.tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("list %s on %q: %w", dir, mr.dest.Name, err) + } + var runs []int64 + for _, e := range entries { + if id, ok := receiptRunID(e); ok { + runs = append(runs, id) + } + } + slices.Sort(runs) + out := map[string][]byte{} + for _, id := range runs { + name := path.Join(dir, "run-"+strconv.FormatInt(id, 10)) + entries, err := readReceipt(ctx, mr.tr, name) + if err != nil { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("receipt %s on %q could not be read (%v); the files it names are checked against older receipts", name, mr.dest.Name, err)) + continue + } + maps.Copy(out, entries) + } + return out, nil +} + +// receiptRunID reads the run id of a receipt, a file named run-. +func receiptRunID(e entry) (int64, bool) { + idText, ok := strings.CutPrefix(e.name, "run-") + if !ok || e.kind != kindFile { + return 0, false + } + id, err := strconv.ParseInt(idText, 10, 64) + return id, err == nil && id > 0 && strconv.FormatInt(id, 10) == idText +} + +// readReceipt maps every present path the receipt at name lists to its +// BLAKE3. +func readReceipt(ctx context.Context, tr transport, name string) (map[string][]byte, error) { + rc, err := tr.Get(ctx, name) + if err != nil { + return nil, err + } + defer func() { _ = rc.Close() }() + out := map[string][]byte{} + sc := bufio.NewScanner(ctxReader{ctx: ctx, r: rc}) + sc.Buffer(make([]byte, 0, 64<<10), 1<<20) + for sc.Scan() { + var e ManifestEntry + if err := json.Unmarshal(sc.Bytes(), &e); err != nil { + return nil, err + } + if e.Status != store.StatusPresent { + continue + } + sum, err := hex.DecodeString(e.Blake3) + if err != nil || len(sum) != 32 { + return nil, fmt.Errorf("%s: blake3 %q is not a 32-byte hex hash", e.Path, e.Blake3) + } + out[e.Path] = sum + } + return out, sc.Err() +} diff --git a/sync/restore_mirror_test.go b/sync/restore_mirror_test.go new file mode 100644 index 0000000..a999ebb --- /dev/null +++ b/sync/restore_mirror_test.go @@ -0,0 +1,209 @@ +package sync + +import ( + "context" + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +func (f *mirrorFixture) restore(t *testing.T, s *store.Store, opts RestoreOptions) (Report, error) { + t.Helper() + return Restore(context.Background(), s, nil, f.pair.Volume, f.pair.Destination, opts) +} + +// scratchFile reads rel under a restore target, "" when it is absent. +func scratchFile(t *testing.T, dir, rel string) string { + t.Helper() + b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel))) + if os.IsNotExist(err) { + return "" + } + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// TestMirrorRestoreFromTheIndex: with an index, a native mirror restore +// fetches each present path through the transport with no rclone, checks +// it against the indexed hash, and leaves a path that already holds its +// bytes alone. A mirrored file whose bytes no longer match the index is +// refused, never placed. +func TestMirrorRestoreFromTheIndex(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.write(t, "2024/cat.jpg", "meow") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + + scratch := t.TempDir() + if err := os.WriteFile(filepath.Join(scratch, "a.txt"), []byte("alpha"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("b.txt"), []byte("BETA"), 0o644); err != nil { + t.Fatal(err) + } + rep, err := f.restore(t, f.store, RestoreOptions{ToPath: scratch}) + if err == nil || rep.RcloneResult.Errors != 1 || rep.RcloneResult.FailedFiles[0].Object != "b.txt" { + t.Fatalf("restore = %v, failures %+v; want b.txt refused", err, rep.RcloneResult.FailedFiles) + } + if rep.RcloneResult.Transferred != 1 || rep.AlreadyCorrect != 1 { + t.Fatalf("counters = %+v already_correct=%d, want cat.jpg fetched and a.txt left alone", rep.RcloneResult, rep.AlreadyCorrect) + } + if scratchFile(t, scratch, "2024/cat.jpg") != "meow" || scratchFile(t, scratch, "b.txt") != "" { + t.Fatal("restore placed the wrong bytes") + } + }) + } +} + +// TestMirrorRestoreOnAFreshMachine: with no index, a restore walks the +// mirrored tree, leaves squirrel's reserved entries out, checks every file +// a receipt names against it, and restores the rest unchecked, counting +// them in a warning. A file that contradicts its receipt is refused. +func TestMirrorRestoreOnAFreshMachine(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.write(t, "2024/cat.jpg", "meow") + f.write(t, "c.txt", "gamma") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + f.mustPush(t) + if err := os.WriteFile(f.dest("foreign.txt"), []byte("not squirrel's"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("c.txt"), []byte("GAMMA"), 0o644); err != nil { + t.Fatal(err) + } + + fresh, err := store.Open(filepath.Join(t.TempDir(), "fresh.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + scratch := t.TempDir() + rep, err := f.restore(t, fresh, RestoreOptions{ToPath: scratch}) + if err == nil || rep.RcloneResult.Errors != 1 || rep.RcloneResult.FailedFiles[0].Object != "c.txt" { + t.Fatalf("restore = %v, failures %+v; want c.txt refused", err, rep.RcloneResult.FailedFiles) + } + for rel, want := range map[string]string{"a.txt": "v2", "2024/cat.jpg": "meow", "foreign.txt": "not squirrel's", "c.txt": ""} { + if got := scratchFile(t, scratch, rel); got != want { + t.Fatalf("%s = %q, want %q", rel, got, want) + } + } + entries, _ := os.ReadDir(scratch) + for _, e := range entries { + if strings.HasPrefix(e.Name(), ".squirrel") { + t.Fatalf("restore brought back squirrel's own %s", e.Name()) + } + } + if !warned(rep, "1 file(s)") || !warned(rep, "restored unchecked") { + t.Fatalf("warnings = %v, want the one unchecked file counted", rep.Warnings) + } + }) + } +} + +// TestMirrorRestoreInPlacePreservesWhatItReplaces: an in-place restore +// moves every file it replaces into the run's restore history, and +// leaves a file that already holds its indexed bytes where it is. +func TestMirrorRestoreInPlacePreservesWhatItReplaces(t *testing.T) { + f := setupMirrorFixtureOn(t, localBackend) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + f.write(t, "b.txt", "local edit") + + rep, err := f.restore(t, f.store, RestoreOptions{InPlace: true}) + if err != nil || rep.RcloneResult.Transferred != 1 || rep.AlreadyCorrect != 1 { + t.Fatalf("restore = %v, counters %+v already_correct=%d; want b.txt replaced and a.txt left alone", err, rep.RcloneResult, rep.AlreadyCorrect) + } + if scratchFile(t, f.src, "b.txt") != "beta" { + t.Fatal("b.txt was not restored") + } + history := filepath.Join(RestoreHistoryDirName, "run-"+strconv.FormatInt(rep.RunID, 10), "b.txt") + if got := scratchFile(t, f.src, history); got != "local edit" { + t.Fatalf("restore history holds %q, want the replaced local edit", got) + } +} + +// escapingListing lists one extra file whose name climbs out of its +// directory, as a hostile or broken server might. +type escapingListing struct{ transport } + +func (e escapingListing) List(ctx context.Context, dir string) ([]entry, error) { + entries, err := e.transport.List(ctx, dir) + return append(entries, entry{name: "../escaped", kind: kindFile, size: 1}), err +} + +// TestMirrorRestoreRefusesAnEscapingName: a walked name that is not a +// single path element stops the restore before anything lands outside +// the target. +func TestMirrorRestoreRefusesAnEscapingName(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + raw, err := openLocalTransport(f.dst) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = raw.Close() }) + parent := t.TempDir() + target := filepath.Join(parent, "target") + mr := &mirrorRestore{store: f.store, vol: f.pair.Volume, dest: f.pair.Destination, + tr: escapingListing{raw}, placer: restorePlacer{target: target}} + var rep Report + if err := mr.restoreWalked(context.Background(), &rep); !errors.Is(err, errInvalidName) { + t.Fatalf("walk over an escaping name = %v, want errInvalidName", err) + } + if _, err := os.Stat(filepath.Join(parent, "escaped")); !os.IsNotExist(err) { + t.Fatalf("a file landed outside the target: %v", err) + } +} + +// TestMirrorRestoreSkipsABrokenReceiptWhole: a receipt that does not +// parse contributes nothing, not even its readable lines, so the files it +// names are checked against the receipts before it. +func TestMirrorRestoreSkipsABrokenReceiptWhole(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + second := f.mustPush(t) + receipt := f.dest(IndexDirName + "/run-" + strconv.FormatInt(second.RunID, 10)) + file, err := os.OpenFile(receipt, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err := file.WriteString("{not json\n"); err != nil { + t.Fatal(err) + } + _ = file.Close() + + fresh, err := store.Open(filepath.Join(t.TempDir(), "fresh.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + rep, err := f.restore(t, fresh, RestoreOptions{ToPath: t.TempDir()}) + if err == nil || rep.RcloneResult.Errors != 1 || !warned(rep, "could not be read") { + t.Fatalf("restore = %v, errors=%d warnings=%v; want the broken receipt reported and a.txt checked against the older one", err, rep.RcloneResult.Errors, rep.Warnings) + } +} diff --git a/sync/restore_place.go b/sync/restore_place.go new file mode 100644 index 0000000..8e79da6 --- /dev/null +++ b/sync/restore_place.go @@ -0,0 +1,161 @@ +package sync + +import ( + "bytes" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "time" + + "github.com/zeebo/blake3" +) + +// restorePlacer lands restored files in a target tree. Each file streams +// into a temporary file beside its path while it is hashed, is checked, +// stamped and flushed, and is then renamed over the path: a crash never +// leaves a half-written file at a path, and bytes that fail their check +// never reach one. With preserve, a file the path already held first moves +// into .squirrel-restore-history/run-/. +type restorePlacer struct { + target string + runID int64 + preserve bool +} + +// place writes the bytes r yields to rel, stamped with mtime. want, when +// set, is the BLAKE3 they must hash to; nil places them unchecked. It +// returns how many bytes it placed. +func (pl restorePlacer) place(rel string, r io.Reader, want []byte, mtime time.Time) (int64, error) { + dst := pl.path(rel) + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + return 0, fmt.Errorf("create target dir: %w", err) + } + if err := refuseNonRegularTarget(rel, dst); err != nil { + return 0, err + } + tmp, n, err := stageRestored(dst, r, want, mtime) + if err != nil { + return 0, fmt.Errorf("restore %s: %w", rel, err) + } + if err := pl.commit(rel, dst, tmp); err != nil { + _ = os.Remove(tmp) + return 0, err + } + return n, nil +} + +// holds reports whether rel already holds size bytes hashing to want, so +// a restore can leave it as it is. +func (pl restorePlacer) holds(rel string, size int64, want []byte) bool { + dst := pl.path(rel) + fi, err := os.Lstat(dst) + if err != nil || !fi.Mode().IsRegular() || fi.Size() != size { + return false + } + digest, err := hashLocalFile(dst) + return err == nil && bytes.Equal(digest, want) +} + +func (pl restorePlacer) path(rel string) string { + return filepath.Join(pl.target, filepath.FromSlash(rel)) +} + +// stageRestored streams r into a fresh temporary file beside dst while +// hashing it, and returns the file's name once its bytes check out, carry +// mtime, and are flushed to disk. +func stageRestored(dst string, r io.Reader, want []byte, mtime time.Time) (string, int64, error) { + f, err := os.CreateTemp(filepath.Dir(dst), ".squirrel-restore-*") + if err != nil { + return "", 0, err + } + h := blake3.New() + n, err := io.CopyBuffer(io.MultiWriter(f, h), r, make([]byte, copyBufferSize)) + if err == nil && want != nil && !bytes.Equal(h.Sum(nil), want) { + err = fmt.Errorf("the bytes hash to %s, want %s", hex.EncodeToString(h.Sum(nil)), hex.EncodeToString(want)) + } + if err == nil { + err = os.Chtimes(f.Name(), mtime, mtime) + } + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + _ = os.Remove(f.Name()) + return "", 0, err + } + return f.Name(), n, nil +} + +// commit renames the staged file over rel, first moving a file rel holds +// aside when the restore preserves what it replaces. +func (pl restorePlacer) commit(rel, dst, tmp string) error { + if pl.preserve { + if err := pl.backupExisting(rel, dst); err != nil { + return err + } + } + if err := os.Rename(tmp, dst); err != nil { + return fmt.Errorf("place %s: %w", rel, err) + } + return syncLocalDir(filepath.Dir(dst)) +} + +// backupExisting moves an existing regular file at dst under the per-run +// restore-history subtree so an in-place restore never destroys prior +// bytes — the local-side counterpart of a mirror's .squirrel-history. The +// caller has already refused any non-regular destination, so dst is absent +// or a regular file here. +func (pl restorePlacer) backupExisting(rel, dst string) error { + if _, err := os.Lstat(dst); errors.Is(err, os.ErrNotExist) { + return nil + } else if err != nil { + return fmt.Errorf("stat existing %s: %w", rel, err) + } + backup := filepath.Join(pl.target, RestoreHistoryDirName, "run-"+strconv.FormatInt(pl.runID, 10), filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(backup), 0o755); err != nil { + return fmt.Errorf("create restore-history dir: %w", err) + } + if err := os.Rename(dst, backup); err != nil { + return fmt.Errorf("preserve overwritten %s: %w", rel, err) + } + return nil +} + +// refuseNonRegularTarget refuses to write when the destination already +// exists as anything other than a regular file — a symlink, device, fifo, +// socket, or directory — and reports it: squirrel replaces only a plain +// file it can preserve. An absent path or a regular file is allowed. +func refuseNonRegularTarget(rel, dst string) error { + info, err := os.Lstat(dst) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("stat target %s: %w", rel, err) + } + if !info.Mode().IsRegular() { + return fmt.Errorf("refusing to write %s: destination already exists as a non-regular file (%s) — squirrel will not follow or replace it", rel, info.Mode().Type()) + } + return nil +} + +// syncLocalDir flushes a directory of this machine, so a name moved into +// it survives a power cut. +func syncLocalDir(dir string) error { + f, err := os.Open(dir) + if err != nil { + return fmt.Errorf("open %s to sync it: %w", dir, err) + } + defer func() { _ = f.Close() }() + if err := f.Sync(); err != nil && !dirSyncUnsupported(err) { + return fmt.Errorf("sync %s: %w", dir, err) + } + return nil +} diff --git a/sync/restore_place_test.go b/sync/restore_place_test.go new file mode 100644 index 0000000..00e0415 --- /dev/null +++ b/sync/restore_place_test.go @@ -0,0 +1,103 @@ +package sync + +import ( + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/zeebo/blake3" +) + +func blake3Of(s string) []byte { + sum := blake3.Sum256([]byte(s)) + return sum[:] +} + +// placeFixture is a target directory whose a.txt holds "old". +func placeFixture(t *testing.T, preserve bool) (restorePlacer, string) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + return restorePlacer{target: dir, runID: 7, preserve: preserve}, dir +} + +// onlyFiles asserts dir holds exactly the named entries: no temporary +// file was left behind. +func onlyFiles(t *testing.T, dir string, want ...string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var got []string + for _, e := range entries { + got = append(got, e.Name()) + } + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("%s holds %v, want %v", dir, got, want) + } +} + +func readFile(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// TestPlaceNeverLeavesAPartialFile: bytes that stop mid-stream, or that +// fail their check, never reach the path, and no temporary file stays. +func TestPlaceNeverLeavesAPartialFile(t *testing.T) { + pl, dir := placeFixture(t, false) + broken := io.MultiReader(strings.NewReader("new"), iotestErrReader{}) + if _, err := pl.place("a.txt", broken, nil, time.Now()); err == nil { + t.Fatal("place of a broken stream succeeded") + } + if _, err := pl.place("a.txt", strings.NewReader("new"), blake3Of("other"), time.Now()); err == nil || !strings.Contains(err.Error(), "hash") { + t.Fatalf("place of mismatching bytes = %v, want a hash refusal", err) + } + if got := readFile(t, filepath.Join(dir, "a.txt")); got != "old" { + t.Fatalf("a.txt = %q after refused places, want old", got) + } + onlyFiles(t, dir, "a.txt") +} + +type iotestErrReader struct{} + +func (iotestErrReader) Read([]byte) (int, error) { return 0, errors.New("the stream broke") } + +// TestPlaceReplacesOrPreserves: a scratch restore renames the new bytes +// over the path; an in-place one first moves the old file into the run's +// restore history. Either way the path ends up with the new bytes and +// their mtime. +func TestPlaceReplacesOrPreserves(t *testing.T) { + mtime := time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC) + for _, preserve := range []bool{false, true} { + pl, dir := placeFixture(t, preserve) + n, err := pl.place("a.txt", strings.NewReader("new!"), blake3Of("new!"), mtime) + if err != nil || n != 4 { + t.Fatalf("preserve=%v: place = %d, %v", preserve, n, err) + } + dst := filepath.Join(dir, "a.txt") + fi, err := os.Stat(dst) + if err != nil || readFile(t, dst) != "new!" || !fi.ModTime().Equal(mtime) { + t.Fatalf("preserve=%v: a.txt = %q at %v, want new! at %v", preserve, readFile(t, dst), fi.ModTime(), mtime) + } + if !preserve { + onlyFiles(t, dir, "a.txt") + continue + } + onlyFiles(t, dir, RestoreHistoryDirName, "a.txt") + if got := readFile(t, filepath.Join(dir, RestoreHistoryDirName, "run-7", "a.txt")); got != "old" { + t.Fatalf("restore history holds %q, want the replaced old", got) + } + } +} diff --git a/sync/scanback.go b/sync/scanback.go index 04d8cb1..c055668 100644 --- a/sync/scanback.go +++ b/sync/scanback.go @@ -32,7 +32,7 @@ type captureTarget struct { // fingerprint left pending. The content-addressed object path and the // packed pack path share this surface, differing only in the dirName they // scan and the record closure each target carries. -func (h *contentPusher) captureScanBackFingerprints(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { +func (h *rcloneArtifacts) captureScanBackFingerprints(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { // A run that uploaded nothing new has nothing to fingerprint; return // before the s3 path would otherwise list the whole prefix (and possibly // warn on a transient failure) for an empty batch. @@ -49,11 +49,11 @@ func (h *contentPusher) captureScanBackFingerprints(ctx context.Context, rep *Re // captureScanBackRclone reads provider checksums via `rclone lsjson // --hash`, batched into one invocation per chunk and scoped by --include // filters so the backend hashes only this run's uploads. -func (h *contentPusher) captureScanBackRclone(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { +func (h *rcloneArtifacts) captureScanBackRclone(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { dirURI := underlyingDirURI(h.dest, dirName) types := captureHashTypes(h.dest) for batch := range slices.Chunk(targets, fingerprintBatchSize) { - extra := checkersArgs(h.dest) + extra := concurrencyArgs(h.dest) for _, t := range batch { extra = append(extra, "--include", listedRemoteName(h.dest, t.name)) } @@ -79,7 +79,7 @@ func (h *contentPusher) captureScanBackRclone(ctx context.Context, rep *Report, // every fingerprint pending with a warning — capture is not on the // durability critical path (the bytes are already confirmed), so `squirrel // verify` is the backstop. -func (h *contentPusher) captureScanBackS3(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { +func (h *rcloneArtifacts) captureScanBackS3(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { reader, err := newS3ETagReader(h.dest, dirName) if err == nil { var etags map[string]string @@ -103,7 +103,7 @@ func (h *contentPusher) captureScanBackS3(ctx context.Context, rep *Report, dirN // listing (byName, present). A target absent from the listing or exposing // no usable checksum stays pending with a warning; the fingerprint is never // fabricated. Each recorded checksum counts toward rep.Fingerprints. -func (h *contentPusher) recordScanBack(ctx context.Context, rep *Report, targets []captureTarget, byName map[string]map[string]string, present map[string]bool) { +func (h *rcloneArtifacts) recordScanBack(ctx context.Context, rep *Report, targets []captureTarget, byName map[string]map[string]string, present map[string]bool) { for _, t := range targets { if !present[t.name] { rep.Warnings = append(rep.Warnings, fmt.Sprintf("%s %s on %q: not yet returned by the remote listing; fingerprint stays pending", t.label, t.name, h.dest.Name)) diff --git a/sync/snapshot.go b/sync/snapshot.go index 0747f84..5315ab7 100644 --- a/sync/snapshot.go +++ b/sync/snapshot.go @@ -2,7 +2,9 @@ package sync import ( "context" + "errors" "fmt" + "io/fs" "os" "path" "path/filepath" @@ -37,7 +39,6 @@ const snapshotPrefix = "index-" // the disabled state and every method is a safe no-op on it. type Snapshotter struct { store *store.Store - rcl *Rclone dir string // resolved local snapshot directory keep int // local rotation bound (0 = no rotation) cloud bool // ride snapshots along to destination buckets @@ -60,12 +61,11 @@ type SnapshotConfig struct { } // NewSnapshotter returns a Snapshotter ready to be shared across one -// invocation's pairs. The store backs the VACUUM INTO snapshot; the -// rclone wrapper (with its Config already written) backs the ride-along. -func NewSnapshotter(s *store.Store, rcl *Rclone, cfg SnapshotConfig) *Snapshotter { +// invocation's pairs. The store backs the VACUUM INTO snapshot; each +// push hands over the shelf its ride-along lands on. +func NewSnapshotter(s *store.Store, cfg SnapshotConfig) *Snapshotter { return &Snapshotter{ store: s, - rcl: rcl, dir: cfg.Dir, keep: cfg.Keep, cloud: cfg.Cloud, @@ -73,13 +73,24 @@ func NewSnapshotter(s *store.Store, rcl *Rclone, cfg SnapshotConfig) *Snapshotte } } -// afterSync is the post-run hook called by Sync and SyncNode once the -// run's terminal state is committed. It takes (once) the local snapshot -// and, for destination syncs with cloud enabled, rides a copy along to -// the destination. Failures are surfaced on rep.SnapshotErr and never -// mutate rep.Status — the snapshot is defense-in-depth, not part of the -// sync's success contract. A nil receiver (feature disabled) is a no-op. -func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, vol *config.Volume, dest *config.Destination) { +// snapshotShelf is a destination's per-volume .squirrel-index/ directory, +// where ride-along snapshots are kept. +type snapshotShelf interface { + // upload copies the local snapshot at localPath onto the shelf as name. + upload(ctx context.Context, localPath, name string) error + // snapshots lists the snapshot names on the shelf. + snapshots(ctx context.Context) ([]string, error) + remove(ctx context.Context, name string) error +} + +// afterSync is the post-run hook every push calls once the run's terminal +// state is committed. It takes (once) the local snapshot and, with cloud +// enabled, rides a copy along to shelf; a nil shelf (peer and kopia +// pushes) keeps the local snapshot only. +// Failures are surfaced on rep.SnapshotErr and never mutate rep.Status — +// the snapshot is defense-in-depth, not part of the sync's success +// contract. A nil receiver (feature disabled) is a no-op. +func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, shelf snapshotShelf) { if sn == nil { return } @@ -101,10 +112,10 @@ func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, vol *config.V // The VACUUM itself failed; there is nothing to ride along. return } - if dest == nil || !sn.cloud { + if shelf == nil || !sn.cloud { return } - if rideErr := sn.rideAlong(ctx, localPath, dest, vol.Name); rideErr != nil { + if rideErr := sn.rideAlong(ctx, localPath, rep, shelf); rideErr != nil { rep.SnapshotErr = rideErr } } @@ -138,32 +149,29 @@ func (sn *Snapshotter) ensureLocalSnapshot(ctx context.Context, runID int64) (st return sn.localPath, sn.takeErr } -// rideAlong uploads localPath to //.squirrel-index/ via the -// rclone wrapper, then rotates that per-volume directory to at most +// rideAlong uploads localPath to the destination's +// /.squirrel-index/, then rotates that directory to at most // cloudKeep snapshots. The uploaded copy keeps the snapshot's filename so // the catalog is traceable to its producing run on the destination too. -func (sn *Snapshotter) rideAlong(ctx context.Context, localPath string, dest *config.Destination, volumeName string) error { - dirURI := indexDirURI(dest, volumeName) - name := filepath.Base(localPath) - if err := sn.rcl.copyTo(ctx, localPath, dirURI+"/"+name); err != nil { - return fmt.Errorf("ride-along upload to %s: %w", dest.Name, err) +func (sn *Snapshotter) rideAlong(ctx context.Context, localPath string, rep *Report, shelf snapshotShelf) error { + if err := shelf.upload(ctx, localPath, filepath.Base(localPath)); err != nil { + return fmt.Errorf("ride-along upload to %s: %w", rep.Destination, err) } - if err := sn.rotateCloud(ctx, dirURI); err != nil { - return fmt.Errorf("rotate %s/%s/%s: %w", dest.Name, volumeName, IndexDirName, err) + if err := sn.rotateCloud(ctx, shelf); err != nil { + return fmt.Errorf("rotate %s/%s/%s: %w", rep.Destination, rep.Volume, IndexDirName, err) } return nil } -// rotateCloud lists the destination's .squirrel-index/ directory and -// deletes the oldest snapshots until at most cloudKeep remain. Snapshots -// are lexically sortable (decision #3), so "newest N" is the tail of the -// name-sorted list — no per-file metadata read required. cloudKeep<=0 -// means "no rotation". -func (sn *Snapshotter) rotateCloud(ctx context.Context, dirURI string) error { +// rotateCloud deletes the oldest snapshots on the shelf until at most +// cloudKeep remain. Snapshots are lexically sortable (decision #3), so +// "newest N" is the tail of the name-sorted list — no per-file metadata +// read required. cloudKeep<=0 means "no rotation". +func (sn *Snapshotter) rotateCloud(ctx context.Context, shelf snapshotShelf) error { if sn.cloudKeep <= 0 { return nil } - names, err := sn.rcl.listSnapshots(ctx, dirURI) + names, err := shelf.snapshots(ctx) if err != nil { return err } @@ -172,13 +180,108 @@ func (sn *Snapshotter) rotateCloud(ctx context.Context, dirURI string) error { } sort.Strings(names) for _, old := range names[:len(names)-sn.cloudKeep] { - if err := sn.rcl.deleteFile(ctx, dirURI+"/"+old); err != nil { + if err := shelf.remove(ctx, old); err != nil { return err } } return nil } +// isSnapshotName reports whether a file name in .squirrel-index/ is a +// ride-along snapshot, index-*.db, as opposed to a receipt. +func isSnapshotName(name string) bool { + return strings.HasPrefix(name, snapshotPrefix) && strings.HasSuffix(name, ".db") +} + +// rcloneShelf is the .squirrel-index/ directory of a destination rclone +// writes, addressed through the same overlay as its data. +type rcloneShelf struct { + rcl *Rclone + dir string // the directory's rclone URI +} + +func (s rcloneShelf) upload(ctx context.Context, localPath, name string) error { + return s.rcl.copyTo(ctx, localPath, s.dir+"/"+name) +} + +func (s rcloneShelf) snapshots(ctx context.Context) ([]string, error) { + return s.rcl.listSnapshots(ctx, s.dir) +} + +func (s rcloneShelf) remove(ctx context.Context, name string) error { + return s.rcl.deleteFile(ctx, s.dir+"/"+name) +} + +// transportShelf is a native destination's /.squirrel-index/, reached +// through runID's guarded transport, which open returns. +type transportShelf struct { + open func(context.Context) (transport, error) + volume string + runID int64 +} + +func (s transportShelf) dir() string { return path.Join(s.volume, IndexDirName) } + +// upload stages the snapshot in runID's staging, then renames it onto +// name, so an upload that fails halfway never leaves a truncated snapshot +// for recovery to offer as the newest. A partial staged copy goes with the +// run's staging at the next push. +func (s transportShelf) upload(ctx context.Context, localPath, name string) error { + tr, err := s.open(ctx) + if err != nil { + return err + } + f, err := os.Open(localPath) + if err != nil { + return err + } + defer f.Close() + fi, err := f.Stat() + if err != nil { + return err + } + staged := stagingName(s.volume, s.runID, stagingKey(path.Join(IndexDirName, name))) + if err := tr.Put(ctx, staged, f, fi.ModTime()); err != nil { + return err + } + return landStaged(ctx, tr, staged, path.Join(s.dir(), name)) +} + +func (s transportShelf) snapshots(ctx context.Context) ([]string, error) { + tr, err := s.open(ctx) + if err != nil { + return nil, err + } + return listSnapshotNames(ctx, tr, s.dir()) +} + +// listSnapshotNames lists the snapshots in dir through tr; a dir that +// does not exist holds none. +func listSnapshotNames(ctx context.Context, tr transport, dir string) ([]string, error) { + entries, err := tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var names []string + for _, e := range entries { + if e.kind == kindFile && isSnapshotName(e.name) { + names = append(names, e.name) + } + } + return names, nil +} + +func (s transportShelf) remove(ctx context.Context, name string) error { + tr, err := s.open(ctx) + if err != nil { + return err + } + return tr.Remove(ctx, path.Join(s.dir(), name)) +} + // indexDirURI returns the rclone URI of the per-volume .squirrel-index/ // directory under dest, addressed the same way the data transfer is // (through the crypt overlay when the destination has one). diff --git a/sync/snapshot_test.go b/sync/snapshot_test.go index bf263e6..26c07ad 100644 --- a/sync/snapshot_test.go +++ b/sync/snapshot_test.go @@ -20,7 +20,7 @@ func (f *syncFixture) snapshotterFor(t *testing.T, cfg SnapshotConfig) *Snapshot if cfg.Dir == "" { cfg.Dir = t.TempDir() } - return NewSnapshotter(f.store, f.rcl, cfg) + return NewSnapshotter(f.store, cfg) } func globOne(t *testing.T, pattern string) string { @@ -174,7 +174,7 @@ func TestSnapshotErrorDoesNotFailSync(t *testing.T) { if err := os.WriteFile(blocker, []byte("x"), 0o644); err != nil { t.Fatal(err) } - sn := NewSnapshotter(f.store, f.rcl, SnapshotConfig{Dir: filepath.Join(blocker, "backups"), Keep: 7, Cloud: true, CloudKeep: 7}) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: filepath.Join(blocker, "backups"), Keep: 7, Cloud: true, CloudKeep: 7}) rep, err := Sync(context.Background(), f.store, f.rcl, f.vol, f.dest, Options{Snapshot: sn}) if err != nil { @@ -357,11 +357,13 @@ func TestSyncFiltersOutIndexDirFromSource(t *testing.T) { // reserved-path predicates exclude .squirrel-index, so a node whose index // carries rows there never re-publishes them. func TestReservedSyncPathCoversIndexDir(t *testing.T) { - if !isReservedSyncPath(IndexDirName + "/index-x-run-1.db") { - t.Fatalf("isReservedSyncPath does not cover %s/", IndexDirName) - } - if !isReservedFolderPath(IndexDirName) { - t.Fatalf("isReservedFolderPath does not cover bare %s", IndexDirName) + for _, dir := range []string{IndexDirName, StagingDirName} { + if !isReservedSyncPath(dir + "/run-1/x") { + t.Fatalf("isReservedSyncPath does not cover %s/", dir) + } + if !isReservedFolderPath(dir) { + t.Fatalf("isReservedFolderPath does not cover bare %s", dir) + } } } @@ -395,23 +397,17 @@ func argsHaveFilter(args []string, want string) bool { // TestSnapshotterWithoutRcloneServesPeerPairs pins the coupling that lets // a peer-only or kopia-only sync run on a host with no rclone installed: -// `runSync` now leaves the wrapper nil for such a batch, and the -// Snapshotter is still constructed and still takes its local snapshot. -// Only the destination ride-along needs rclone, and both handlers that -// never have one (peer sync, kopia) pass a nil destination, which -// afterSync returns on before reaching it. -// -// A test rather than a comment because the safety of the nil is a -// cross-package invariant: it holds only as long as every caller reaching -// rideAlong is an rclone-driven handler. +// the Snapshotter holds no rclone wrapper, and the handlers that have no +// ride-along (peer sync, kopia) pass no shelf, so it still takes its local +// snapshot. func TestSnapshotterWithoutRcloneServesPeerPairs(t *testing.T) { f := setupFixture(t) - sn := NewSnapshotter(f.store, nil, SnapshotConfig{ + sn := NewSnapshotter(f.store, SnapshotConfig{ Dir: filepath.Join(t.TempDir(), "backups"), Keep: 7, Cloud: true, CloudKeep: 7, }) rep := &Report{RunID: 1, Status: store.RunStatusSuccess} - sn.afterSync(context.Background(), rep, f.vol, nil) + sn.afterSync(context.Background(), rep, nil) if rep.SnapshotErr != nil { t.Fatalf("SnapshotErr = %v, want the local snapshot to succeed without rclone", rep.SnapshotErr) diff --git a/sync/sync.go b/sync/sync.go index b43907a..2951e5f 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -50,6 +50,14 @@ const RestoreHistoryDirName = ".squirrel-restore-history" // and from peer-sync so a snapshot is never mistaken for user content. const IndexDirName = ".squirrel-index" +// StagingDirName is the per-volume directory at a native destination that +// holds in-flight writes: //.squirrel-staging/ +// run-/. A mirror version or a content artifact is staged there, +// hashed while it streams, and renamed onto its name once confirmed — a +// mirror version once its predecessor is in history. Like the other +// reserved directories it never travels as user content. +const StagingDirName = ".squirrel-staging" + // ErrRefused marks a preflight safety refusal: a gate that declined to // proceed before any transfer began — a missing or mismatched // .squirrel-volume marker, a kopia connect that found no repository @@ -115,8 +123,12 @@ type Options struct { // was inserted; zero in dry-run mode. RcloneResult is the parsed rclone // summary, surfaced verbatim so callers can render whatever they need. type Report struct { - Volume string - Destination string + Volume string + Destination string + // Layout is the destination's layout for a push through the shared + // planner (config.Layout*), so output renderers can tell a native + // mirror from a content layout; empty for every other push. + Layout string RunID int64 RcloneResult RunResult Status string // success / partial / failed @@ -301,14 +313,12 @@ func Sync(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, return rep, err } - // Marker gate. Local destinations validate the marker on the - // filesystem; remote rclone destinations (sftp/s3/b2/gcs) read and, - // with --init, write it through the same overlay the transfer uses. - // The dry-run path skips: it never writes, and refusing a dry-run on - // an uninitialised destination would prevent the "preview what would - // happen" workflow. + // Marker gate, read and (with --init) written through the same + // overlay the transfer uses. The dry-run path skips: it never writes, + // and refusing a dry-run on an uninitialised destination would + // prevent the "preview what would happen" workflow. if !opts.DryRun { - if merr := ensureDestinationMarker(ctx, s, rcl, dest, vol.Name, opts.Init); merr != nil { + if merr := ensureRemoteDestinationMarker(ctx, s, rcl, dest, vol.Name, opts.Init); merr != nil { // A marker refusal fires before the sync run is allocated, so // record it as its own terminal 'refused' run — otherwise a // month-dead backup disk produces zero red anywhere but agent @@ -353,7 +363,7 @@ func Sync(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, // terminal state by now, so the snapshot reflects this run's own row. // Destination syncs are eligible for the cloud ride-along; the // Snapshotter no-ops on dry-run and on non-terminal-success states. - opts.Snapshot.afterSync(ctx, &rep, vol, dest) + opts.Snapshot.afterSync(ctx, &rep, rcloneShelf{rcl: rcl, dir: indexDirURI(dest, vol.Name)}) return rep, err } @@ -565,16 +575,18 @@ func finishRunRow(ctx context.Context, s *store.Store, runID int64, status, errM } // historyDirInSourceWarning returns a one-line advisory when the source -// volume already contains a literal .squirrel-history directory. Sync -// filters it out of the rclone transfer so it can't pollute the -// destination tree, but the user should know that some local content is -// being silently skipped under the reserved name. +// volume already contains a literal .squirrel-history or .squirrel-staging +// directory. Sync filters them out of the transfer so they can't pollute +// the destination tree, but the user should know that some local content +// is being silently skipped under a reserved name. func historyDirInSourceWarning(vol *config.Volume) string { - if _, err := os.Stat(filepath.Join(vol.Path, HistoryDirName)); err != nil { - return "" + for _, dir := range []string{HistoryDirName, StagingDirName} { + if _, err := os.Stat(filepath.Join(vol.Path, dir)); err == nil { + return fmt.Sprintf("volume %q contains a reserved %s/ directory in its source tree — its contents will not be uploaded; rename or move the directory if you want it synced", + vol.Name, dir) + } } - return fmt.Sprintf("volume %q contains a reserved %s/ directory in its source tree — its contents will not be uploaded; rename or move the directory if you want it synced", - vol.Name, HistoryDirName) + return "" } // localVolumeHasContent reports whether vol.Path contains anything @@ -617,60 +629,15 @@ func validateLocalVolumeMarker(vol *config.Volume) error { return fmt.Errorf("volume %q marker check: %w", vol.Name, err) } -// ensureDestinationMarker validates (or, with init, writes) the -// .squirrel-volume marker at the destination's per-volume root. It is -// the single gate against pushing to a wrong or unmounted root: a -// matching marker passes, a missing marker is bootstrapped only under -// init (refused otherwise, in case the root is a typo or the remote is -// unreachable), and a marker naming a different volume is always -// refused — overwriting it would erase the trail that distinguishes the -// two volumes. -// -// Local destinations reach the marker on the filesystem; remote rclone -// destinations reach it through the same overlay their transfers use. -func ensureDestinationMarker(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, volumeName string, init bool) error { - if dest.Type != "local" { - return ensureRemoteDestinationMarker(ctx, s, rcl, dest, volumeName, init) - } - return ensureLocalDestinationMarker(ctx, s, dest, volumeName, init) -} - -// ensureLocalDestinationMarker is the filesystem gate for local -// destinations. The directory is created on first --init so the marker -// can land even when the destination tree is empty. -func ensureLocalDestinationMarker(ctx context.Context, s *store.Store, dest *config.Destination, volumeName string, init bool) error { - root := filepath.Join(dest.Root, volumeName) - err := volmark.Validate(root, volumeName) - if err == nil { - return nil - } - if _, ok := errors.AsType[*volmark.ErrMismatch](err); ok { - return fmt.Errorf("destination %q: %w (refuse to init over a different volume's tree): %w", dest.Name, err, ErrRefused) - } - if !errors.Is(err, volmark.ErrMissing) { - return fmt.Errorf("destination %q marker check: %w", dest.Name, err) - } - if !init { - return fmt.Errorf("destination %q at %s has no %s marker — re-run with --init to bootstrap (refusing in case the root is a typo): %w", dest.Name, root, volmark.MarkerName, ErrRefused) - } - if err := os.MkdirAll(root, 0o755); err != nil { - return fmt.Errorf("destination %q: mkdir %s: %w", dest.Name, root, err) - } - m, err := selfMarker(ctx, s, volumeName) - if err != nil { - return fmt.Errorf("destination %q: %w", dest.Name, err) - } - if err := volmark.Write(root, m); err != nil { - return fmt.Errorf("destination %q: %w", dest.Name, err) - } - return nil -} - -// ensureRemoteDestinationMarker is the rclone-mediated gate for remote -// destinations (sftp/s3/b2/gcs). It probes the marker at the per-volume -// root through remoteSubpathURI — the same overlay the layout's -// transfers use, so a crypt destination's marker rides the encrypted -// path too — and applies the identical rules as the local gate. +// ensureRemoteDestinationMarker is the gate against pushing to a wrong or +// unreachable root for the destinations rclone writes (crypt mirrors, +// mirrors on s3/b2/gcs, and the content layouts). It validates (or, with +// init, writes) the .squirrel-volume marker at the per-volume root: a +// matching marker passes, a missing one is bootstrapped only under init, +// and one naming a different volume is always refused. It probes the +// marker through remoteSubpathURI — the same overlay the layout's +// transfers use, so a crypt destination's marker rides the encrypted path +// too — and applies the same rules as a native mirror's gate. // Presence is decided by a stat (statRemoteExists), not by the read: // only a definite absence is eligible for an --init bootstrap, a present // marker is read and validated (a mismatch is always refused and never @@ -686,19 +653,19 @@ func ensureRemoteDestinationMarker(ctx context.Context, s *store.Store, rcl *Rcl // A stat that fails for any reason other than a definite absence // refuses without writing — a reachability blip must never be read // as a fresh root. - present, err := rcl.statRemoteExists(ctx, markerURI, checkersArgs(dest)...) + present, err := rcl.statRemoteExists(ctx, markerURI, concurrencyArgs(dest)...) if err != nil { return fmt.Errorf("destination %q: stat %s at %s: %w", dest.Name, volmark.MarkerName, markerURI, err) } if !present { if !init { - return fmt.Errorf("destination %q at %s has no %s marker — re-run with --init to bootstrap (refusing in case the root is a typo)", dest.Name, markerURI, volmark.MarkerName) + return fmt.Errorf("destination %q at %s has no %s marker — re-run with --init to bootstrap (refusing in case the root is a typo): %w", dest.Name, markerURI, volmark.MarkerName, ErrRefused) } return writeRemoteMarker(ctx, s, rcl, dest, markerURI, volumeName) } // Present: read and validate. A volume mismatch or a corrupt/empty // marker always refuses and is never overwritten, even under --init. - data, err := rcl.catRemote(ctx, markerURI, checkersArgs(dest)...) + data, err := rcl.catRemote(ctx, markerURI, concurrencyArgs(dest)...) if err != nil { return fmt.Errorf("destination %q: read %s at %s: %w", dest.Name, volmark.MarkerName, markerURI, err) } @@ -715,8 +682,8 @@ func validateRemoteMarker(dest *config.Destination, markerURI, volumeName string return fmt.Errorf("destination %q: %w at %s", dest.Name, err, markerURI) } if m.Volume != volumeName { - return fmt.Errorf("destination %q: %s at %s names %q, want %q (refuse to sync over a different volume's tree)", - dest.Name, volmark.MarkerName, markerURI, m.Volume, volumeName) + return fmt.Errorf("destination %q: %s at %s names %q, want %q (refuse to sync over a different volume's tree): %w", + dest.Name, volmark.MarkerName, markerURI, m.Volume, volumeName, ErrRefused) } return nil } @@ -746,7 +713,7 @@ func writeRemoteMarker(ctx context.Context, s *store.Store, rcl *Rclone, dest *c if err := tmp.Close(); err != nil { return fmt.Errorf("destination %q: stage marker: %w", dest.Name, err) } - if err := rcl.copyTo(ctx, tmp.Name(), markerURI, checkersArgs(dest)...); err != nil { + if err := rcl.copyTo(ctx, tmp.Name(), markerURI, concurrencyArgs(dest)...); err != nil { return fmt.Errorf("destination %q: write %s to %s: %w", dest.Name, volmark.MarkerName, markerURI, err) } return nil @@ -820,8 +787,11 @@ func buildRcloneArgs(vol *config.Volume, dest *config.Destination, runID int64, // dir from being treated as user content (re-uploaded, or pulled // back down on restore). "--filter", "- /" + IndexDirName + "/**", + // .squirrel-staging holds a native mirror's in-flight writes; + // the name is reserved on every layout. + "--filter", "- /" + StagingDirName + "/**", } - args = append(args, checkersArgs(dest)...) + args = append(args, concurrencyArgs(dest)...) if !EffectiveShallow(dest, opts.Shallow) { args = append(args, "--checksum") } @@ -857,22 +827,6 @@ func remoteSubpathURI(dest *config.Destination, subpath string) string { } } -// freshStartOnEmptyRoot reports whether a missing layout marker (a manifest -// segment or pack placement map absent at the last recorded success) should -// be read as a fresh start rather than a layout conflict. It is true only -// when dest's configured root holds no files on the remote — a wiped or -// repointed destination, or one whose recorded state was cleared by -// `squirrel destination reset` — so the name-keyed run history no longer -// describes anything on disk and a fresh full push is safe (it skips -// nothing). A non-empty root, or any error probing it, returns false so the -// caller keeps its refusal: fail-closed, because refusing a real -// layout-switch is recoverable while a delta against a stale watermark -// silently skips content. -func freshStartOnEmptyRoot(ctx context.Context, rcl *Rclone, dest *config.Destination) bool { - empty, err := rcl.remoteRootEmpty(ctx, remoteSubpathURI(dest, ""), rootMarkerNames(dest), checkersArgs(dest)...) - return err == nil && empty -} - // destinationVolumeURI returns the rclone destination spec for the given // volume under dest. func destinationVolumeURI(dest *config.Destination, volumeName string) string { @@ -982,10 +936,11 @@ func (p Pair) TargetName() string { func (p Pair) IsNode() bool { return p.Node != nil } // DrivesRclone reports whether syncing this pair invokes rclone. Every -// destination does except kopia, which drives its own binary; a peer node -// streams its bytes over the sync API. +// destination does except kopia, which drives its own binary, and a native +// one (local, or sftp without crypt, in any layout), which squirrel writes +// itself; a peer node streams its bytes over the sync API. func (p Pair) DrivesRclone() bool { - return p.Destination != nil && p.Destination.Type != "kopia" + return p.Destination != nil && p.Destination.Type != "kopia" && !p.Destination.Native() } // RestoreOptions shape one Restore invocation. ToPath overrides the local @@ -1019,90 +974,50 @@ type RestoreOptions struct { } // Restore reverses Sync back to the local filesystem, recording a -// kind='restore' runs row. The mirror layout copies the destination's -// per-volume tree down with rclone; the content-addressed and packed -// layouts (which have no mirrored tree) resolve each present path to its -// content hash in the local index, fetch the per-hash object or pack -// member, and re-hash it before writing. Restore is read-only against both -// the index and the destination — it never uploads, never mutates content -// rows — but the rclone mirror path will overwrite whatever exists at the -// target on a hash mismatch, so callers point ToPath at an empty / scratch -// directory unless they explicitly intend to restore in place. +// kind='restore' runs row. A native destination (local, or sftp without +// crypt) is read through squirrel's own transport, so rcl may be nil for +// one. A native mirror's every file is placed through a temporary file +// beside its path, checked against the index — or, on a fresh machine, +// against the mirror's receipts. An rclone mirror is copied down with +// rclone. The content-addressed and packed layouts (which have no mirrored +// tree) resolve each present path to its content hash in the local index, +// fetch the per-hash object or pack member, and re-hash it before writing. +// Restore is read-only against both the index and the destination — it +// never uploads, never mutates content rows. An in-place restore without +// InPlace is refused on a non-empty volume, and with it every file it +// replaces moves into .squirrel-restore-history/run-/. func Restore(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, dest *config.Destination, opts RestoreOptions) (rep Report, err error) { rep = Report{Volume: vol.Name, Destination: dest.Name} if dest.Type == "kopia" { return rep, fmt.Errorf("destination %q is a kopia repository — restore from it with the kopia CLI (`kopia snapshot restore`)", dest.Name) } - archive := dest.Layout == config.LayoutContentAddressed || dest.Layout == config.LayoutPacked - - // "In-place" is the dangerous direction: writing into the live - // volume path. Unsetting ToPath is the canonical request, but a - // caller who explicitly passes ToPath == vol.Path is asking for - // the same thing and must go through the same gates — otherwise - // `--to ` would silently bypass the marker check, the - // non-empty refusal, AND the overwrite backup, reintroducing exactly - // the data-loss path this guard is trying to close. - targetInPlace, err := isInPlaceRestore(vol, opts.ToPath) + targetInPlace, err := checkRestoreTarget(vol, opts) if err != nil { return rep, err } - - // Local target marker check: when restoring into the live volume - // path, insist on a marker that names this volume. A missing or - // mismatched marker is the strongest signal we have that vol.Path - // is a typo or unrelated tree, and overwriting it would be - // irreversible. A genuine scratch --to bypasses the check because - // the operator is explicitly redirecting to an unrelated directory. - if !opts.DryRun && targetInPlace { - if err := validateLocalVolumeMarker(vol); err != nil { - return rep, err - } - } - - // In-place overwrite gate: a non-empty live vol.Path is the - // most likely realistic data-loss path in squirrel today (user - // runs `restore` to recover what they think is missing, and the - // destination's view replaces local edits). When InPlace is unset - // and the directory carries anything beyond the marker/history - // subtree, refuse with the --in-place hint. - if !opts.DryRun && targetInPlace && !opts.InPlace { - hasContent, err := localVolumeHasContent(vol.Path) - if err != nil { - return rep, err - } - if hasContent { - return rep, fmt.Errorf("volume %q at %s is not empty — pass --in-place to overwrite (a per-run history of replaced files lands under %s/run-/) or --to to restore into a different directory", vol.Name, vol.Path, RestoreHistoryDirName) - } - } - - // We deliberately don't require an existing index for the mirror - // pull: the destination is the source of truth there, and a fresh - // laptop may have no DB rows yet. We still create a volumes row so - // the runs row's FK resolves. (The archive pull does need the index - // — that is where path→hash lives — but a fresh volume simply - // resolves to zero present rows and restores nothing.) + // We deliberately don't require an existing index: a fresh machine + // may have no DB rows yet, and a mirror restores from its own tree + // then. We still create a volumes row so the runs row's FK resolves. v, err := getOrCreateVolumeForRestore(ctx, s, vol) if err != nil { return rep, err } - - // The archive layouts re-hash every extracted content locally, so the - // pull is content-verified regardless of --shallow or a crypt overlay; - // the mirror pull records rclone's effective comparison instead. - shallow := EffectiveShallow(dest, opts.Shallow) - if archive { - shallow = false - } + // Squirrel re-hashes every file it restores from a native mirror or an + // archive layout, so those pulls are content-verified regardless of + // --shallow or a crypt overlay; an rclone mirror pull records rclone's + // effective comparison instead. + archive := dest.Layout == config.LayoutContentAddressed || dest.Layout == config.LayoutPacked + shallow := EffectiveShallow(dest, opts.Shallow) && !archive && !dest.Native() runID, err := beginRestoreRun(ctx, s, opts.DryRun, v.ID, dest.Name, shallow) if err != nil { return rep, err } - - if archive { - err = restoreArchive(ctx, s, rcl, vol, dest, v.ID, runID, targetInPlace, opts, &rep) - return rep, err + switch { + case archive: + return rep, restoreArchive(ctx, s, rcl, vol, dest, v.ID, runID, targetInPlace, opts, &rep) + case dest.NativeMirror(): + return rep, restoreMirror(ctx, s, vol, dest, v.ID, runID, targetInPlace, opts, &rep) } - if w := cryptVerificationWarning(dest, opts.Shallow); w != "" { rep.Warnings = append(rep.Warnings, w) } @@ -1113,6 +1028,41 @@ func Restore(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volum return rep, err } +// checkRestoreTarget applies the in-place gates and reports whether the +// restore writes into the live volume path. "In-place" is the dangerous +// direction: an unset ToPath is the canonical request, but a caller who +// explicitly passes ToPath == vol.Path is asking for the same thing and +// must go through the same gates — otherwise `--to ` would +// silently bypass the marker check, the non-empty refusal, AND the +// overwrite backup. +// +// Into the live path, a marker naming this volume is required: a missing +// or mismatched one is the strongest signal that vol.Path is a typo or an +// unrelated tree. And a non-empty live path — the most realistic data-loss +// path, where the destination's view replaces local edits — is refused +// unless InPlace. A genuine scratch --to bypasses both, because the +// operator explicitly redirected to an unrelated directory. +func checkRestoreTarget(vol *config.Volume, opts RestoreOptions) (bool, error) { + targetInPlace, err := isInPlaceRestore(vol, opts.ToPath) + if err != nil || opts.DryRun || !targetInPlace { + return targetInPlace, err + } + if err := validateLocalVolumeMarker(vol); err != nil { + return true, err + } + if opts.InPlace { + return true, nil + } + hasContent, err := localVolumeHasContent(vol.Path) + if err != nil { + return true, err + } + if hasContent { + return true, fmt.Errorf("volume %q at %s is not empty — pass --in-place to overwrite (a per-run history of replaced files lands under %s/run-/) or --to to restore into a different directory", vol.Name, vol.Path, RestoreHistoryDirName) + } + return true, nil +} + // isInPlaceRestore reports whether the restore target equals // vol.Path. The CLI's --to flag is for "restore into a scratch // directory" — when the operator points it at the live volume itself @@ -1196,8 +1146,9 @@ func buildRestoreArgs(vol *config.Volume, dest *config.Destination, runID int64, args = append(args, "--filter", "- /"+volmark.MarkerName) args = append(args, "--filter", "- /"+RestoreHistoryDirName+"/**") args = append(args, "--filter", "- /"+IndexDirName+"/**") + args = append(args, "--filter", "- /"+StagingDirName+"/**") } - args = append(args, checkersArgs(dest)...) + args = append(args, concurrencyArgs(dest)...) if !EffectiveShallow(dest, opts.Shallow) { args = append(args, "--checksum") } diff --git a/sync/transport.go b/sync/transport.go new file mode 100644 index 0000000..2b8ca1f --- /dev/null +++ b/sync/transport.go @@ -0,0 +1,164 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "path" + "strings" + "time" +) + +// transport is byte-level access to one destination root. Names are +// slash-separated and relative to the root, and a name whose path crosses +// a symlink is refused. Put creates exclusively and Rename fails on an +// existing target, so every call leaves bytes already there in place. +// Their effects are durable once a later Flush returns: a caller records +// a location as holding bytes only after that. +type transport interface { + // Stat describes name itself, a symlink as a symlink; fs.ErrNotExist + // when absent. + Stat(ctx context.Context, name string) (entry, error) + // List describes the entries directly in dir ("." is the root). + List(ctx context.Context, dir string) ([]entry, error) + // Get opens the regular file at name for reading. + Get(ctx context.Context, name string) (io.ReadCloser, error) + // Put creates name exclusively (fs.ErrExist if present), creating its + // parents, streams r into it, and sets its mtime. + Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error + // Rename moves from to to, creating to's parents; fs.ErrExist if to + // exists. + Rename(ctx context.Context, from, to string) error + // Flush returns once every Put and Rename that returned before it, and + // the entries of every directory in dirs, are on stable storage, as far + // as the destination can make it so. dirs names directories an earlier + // process may have changed, which a caller is about to rely on. + Flush(ctx context.Context, dirs ...string) error + // Remove deletes the file or empty directory at name. + Remove(ctx context.Context, name string) error + // ServerHash is the destination's own hash of the file at name, run + // where the bytes are: an sftp server's hash command. errNoServerHash + // where there is none. + ServerHash(ctx context.Context, name string) (remoteChecksum, error) + Close() error +} + +// entry describes one name on a destination as the transport found it. +type entry struct { + name string // base name + kind entryKind + size int64 + mtime time.Time +} + +// entryKind is what a name on a destination is. +type entryKind int + +const ( + kindFile entryKind = iota + kindDir + kindSymlink + kindOther +) + +func kindOf(mode fs.FileMode) entryKind { + switch { + case mode.IsRegular(): + return kindFile + case mode.IsDir(): + return kindDir + case mode&fs.ModeSymlink != 0: + return kindSymlink + default: + return kindOther + } +} + +// errSymlinkInPath refuses a name whose parent chain crosses a symlink, +// which the transport never follows. +var errSymlinkInPath = errors.New("a directory along the path is a symlink") + +// errParentNotDir reports that a name's parent chain crosses something +// that is not a directory, so the name cannot exist. +var errParentNotDir = errors.New("a parent along the path is not a directory") + +// errInvalidName refuses a name that is not a clean slash-separated path +// inside the root. +var errInvalidName = errors.New("invalid destination name") + +// errUnexpectedKind refuses an operation on a name that is not the kind of +// entry the operation reads. +var errUnexpectedKind = errors.New("unexpected kind of entry") + +// validName reports whether name is a clean slash-separated path strictly +// below a root. +func validName(name string) bool { + return fs.ValidPath(name) && name != "." +} + +// checkParents refuses a name whose parent chain crosses a symlink or +// something that is not a directory. lstat describes one root-relative +// name without following it. A parent that does not exist ends the check: +// nothing below it exists either. +func checkParents(name string, lstat func(string) (fs.FileInfo, error)) error { + dir := path.Dir(name) + if dir == "." { + return nil + } + parts := strings.Split(dir, "/") + for i := range parts { + p := strings.Join(parts[:i+1], "/") + fi, err := lstat(p) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + switch kindOf(fi.Mode()) { + case kindDir: + case kindSymlink: + return fmt.Errorf("%s: %w", p, errSymlinkInPath) + default: + return fmt.Errorf("%s: %w", p, errParentNotDir) + } + } + return nil +} + +// requireKind refuses name unless it exists and is of kind want. +func requireKind(name string, want entryKind, lstat func(string) (fs.FileInfo, error)) error { + fi, err := lstat(name) + if err != nil { + return err + } + if kindOf(fi.Mode()) != want { + return fmt.Errorf("%s: %w", name, errUnexpectedKind) + } + return nil +} + +func entryOf(fi fs.FileInfo) entry { + return entry{name: fi.Name(), kind: kindOf(fi.Mode()), size: fi.Size(), mtime: fi.ModTime()} +} + +// copyBufferSize is the buffer a copy out of a transport reads with. A +// read this large lets the sftp client split it into concurrent requests, +// so a high-latency link does not cap a download at one round trip per +// 32 KiB. +const copyBufferSize = 1 << 20 + +// ctxReader stops a streaming copy once its context is done. +type ctxReader struct { + ctx context.Context + r io.Reader +} + +func (c ctxReader) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + return c.r.Read(p) +} diff --git a/sync/transport_contract_test.go b/sync/transport_contract_test.go new file mode 100644 index 0000000..2bf9bfb --- /dev/null +++ b/sync/transport_contract_test.go @@ -0,0 +1,283 @@ +package sync + +import ( + "bytes" + "context" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// transportHarness opens a fresh, empty destination root for one contract +// case. plant puts a symlink named name, pointing at target, on the +// destination — something no transport call creates. +type transportHarness func(t *testing.T) (tr transport, plant func(target, name string)) + +// runTransportContract is the behaviour every transport implementation +// must show. It pins the two properties the layouts' safety rests on — +// nothing replaces an existing name, and no symlink is ever followed — +// plus the plain semantics of each call. +func runTransportContract(t *testing.T, open transportHarness) { + cases := []struct { + name string + run func(t *testing.T, tr transport, plant func(target, name string)) + }{ + {"PutThenStatListGet", contractPutThenStatListGet}, + {"PutLandsALargeBodyIntact", contractPutLarge}, + {"PutNeverReplaces", contractPutNeverReplaces}, + {"StatAbsent", contractStatAbsent}, + {"RenameMovesAndCreatesParents", contractRenameMoves}, + {"RenameNeverReplaces", contractRenameNeverReplaces}, + {"RenameMovesDirectories", contractRenameDirectory}, + {"RemoveFilesAndEmptyDirectoriesOnly", contractRemove}, + {"RefusesInvalidNames", contractInvalidNames}, + {"NeverFollowsSymlinks", contractNoSymlinks}, + {"ParentThatIsAFile", contractParentNotDir}, + {"PutStopsOnCancel", contractPutCancel}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + tr, plant := open(t) + t.Cleanup(func() { _ = tr.Close() }) + c.run(t, tr, plant) + }) + } +} + +func TestLocalTransportContract(t *testing.T) { + runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { + dir := t.TempDir() + tr, err := openLocalTransport(dir) + if err != nil { + t.Fatalf("openLocalTransport: %v", err) + } + return tr, func(target, name string) { + p := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, p); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + } + }) +} + +var contractMtime = time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC) + +func mustPut(t *testing.T, tr transport, name, body string) { + t.Helper() + if err := tr.Put(context.Background(), name, strings.NewReader(body), contractMtime); err != nil { + t.Fatalf("Put %s: %v", name, err) + } +} + +func mustRead(t *testing.T, tr transport, name string) string { + t.Helper() + rc, err := tr.Get(context.Background(), name) + if err != nil { + t.Fatalf("Get %s: %v", name, err) + } + defer func() { _ = rc.Close() }() + b, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + return string(b) +} + +func contractPutThenStatListGet(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "a/b/c.txt", "hello") + e, err := tr.Stat(ctx, "a/b/c.txt") + if err != nil { + t.Fatalf("Stat: %v", err) + } + if e.kind != kindFile || e.size != 5 || e.name != "c.txt" { + t.Fatalf("Stat = %+v, want file c.txt of 5 bytes", e) + } + // sftp carries whole seconds, so the contract allows truncation. + if d := contractMtime.Sub(e.mtime); d < 0 || d >= time.Second { + t.Fatalf("mtime = %v, want %v to the second", e.mtime, contractMtime) + } + list, err := tr.List(ctx, "a/b") + if err != nil || len(list) != 1 || list[0].name != "c.txt" { + t.Fatalf("List = %+v, %v; want [c.txt]", list, err) + } + root, err := tr.List(ctx, ".") + if err != nil || len(root) != 1 || root[0].name != "a" || root[0].kind != kindDir { + t.Fatalf("List(.) = %+v, %v; want the directory a", root, err) + } + if got := mustRead(t, tr, "a/b/c.txt"); got != "hello" { + t.Fatalf("Get = %q, want hello", got) + } +} + +// contractPutLarge lands a body spanning many write requests, which an +// sftp transport sends concurrently and a server may apply out of order. +func contractPutLarge(t *testing.T, tr transport, _ func(string, string)) { + body := make([]byte, 5<<20+123) + for i := range body { + body[i] = byte(i * 7 % 251) + } + if err := tr.Put(context.Background(), "big", bytes.NewReader(body), contractMtime); err != nil { + t.Fatalf("Put: %v", err) + } + if got := mustRead(t, tr, "big"); got != string(body) { + t.Fatalf("read back %d bytes, want the %d written", len(got), len(body)) + } +} + +func contractPutNeverReplaces(t *testing.T, tr transport, _ func(string, string)) { + mustPut(t, tr, "x", "first") + err := tr.Put(context.Background(), "x", strings.NewReader("second"), contractMtime) + if !errors.Is(err, fs.ErrExist) { + t.Fatalf("Put over an existing name = %v, want fs.ErrExist", err) + } + if got := mustRead(t, tr, "x"); got != "first" { + t.Fatalf("bytes after a refused Put = %q, want first", got) + } +} + +func contractStatAbsent(t *testing.T, tr transport, _ func(string, string)) { + for _, name := range []string{"nope", "a/nope/x"} { + if _, err := tr.Stat(context.Background(), name); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("Stat %s = %v, want fs.ErrNotExist", name, err) + } + } +} + +func contractRenameMoves(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "x", "body") + if err := tr.Rename(ctx, "x", "d/e/y"); err != nil { + t.Fatalf("Rename: %v", err) + } + if _, err := tr.Stat(ctx, "x"); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("source after Rename: %v, want gone", err) + } + if got := mustRead(t, tr, "d/e/y"); got != "body" { + t.Fatalf("target = %q, want body", got) + } +} + +func contractRenameNeverReplaces(t *testing.T, tr transport, _ func(string, string)) { + mustPut(t, tr, "x", "from") + mustPut(t, tr, "y", "to") + if err := tr.Rename(context.Background(), "x", "y"); !errors.Is(err, fs.ErrExist) { + t.Fatalf("Rename onto an existing name = %v, want fs.ErrExist", err) + } + if mustRead(t, tr, "x") != "from" || mustRead(t, tr, "y") != "to" { + t.Fatal("a refused Rename changed either side") + } +} + +func contractRenameDirectory(t *testing.T, tr transport, _ func(string, string)) { + mustPut(t, tr, "d/f", "inside") + if err := tr.Rename(context.Background(), "d", "h/d"); err != nil { + t.Fatalf("Rename directory: %v", err) + } + if got := mustRead(t, tr, "h/d/f"); got != "inside" { + t.Fatalf("moved file = %q, want inside", got) + } +} + +func contractRemove(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "d/f", "x") + if err := tr.Remove(ctx, "d"); err == nil { + t.Fatal("Remove of a non-empty directory succeeded") + } + if err := tr.Remove(ctx, "d/f"); err != nil { + t.Fatalf("Remove file: %v", err) + } + if err := tr.Remove(ctx, "d"); err != nil { + t.Fatalf("Remove empty directory: %v", err) + } + if _, err := tr.Stat(ctx, "d"); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("removed directory: %v, want gone", err) + } +} + +func contractInvalidNames(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "ok", "x") + for _, name := range []string{"", ".", "../x", "/abs", "a/../b", "a//b", "a/"} { + if _, err := tr.Stat(ctx, name); !errors.Is(err, errInvalidName) { + t.Errorf("Stat %q = %v, want errInvalidName", name, err) + } + if err := tr.Put(ctx, name, strings.NewReader("x"), contractMtime); !errors.Is(err, errInvalidName) { + t.Errorf("Put %q = %v, want errInvalidName", name, err) + } + if err := tr.Rename(ctx, "ok", name); !errors.Is(err, errInvalidName) { + t.Errorf("Rename onto %q = %v, want errInvalidName", name, err) + } + } +} + +func contractNoSymlinks(t *testing.T, tr transport, plant func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "real/file", "target bytes") + plant("real", "link") + plant("file", "real/filelink") + + if e, err := tr.Stat(ctx, "link"); err != nil || e.kind != kindSymlink { + t.Fatalf("Stat of the link = %+v, %v; want the symlink itself", e, err) + } + if _, err := tr.Stat(ctx, "link/file"); !errors.Is(err, errSymlinkInPath) { + t.Fatalf("Stat through the link = %v, want errSymlinkInPath", err) + } + if err := tr.Put(ctx, "link/new", strings.NewReader("x"), contractMtime); !errors.Is(err, errSymlinkInPath) { + t.Fatalf("Put through the link = %v, want errSymlinkInPath", err) + } + if _, err := tr.Stat(ctx, "real/new"); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("a Put through the link landed in its target: %v", err) + } + mustPut(t, tr, "x", "moving") + if err := tr.Rename(ctx, "x", "link/x"); !errors.Is(err, errSymlinkInPath) { + t.Fatalf("Rename through the link = %v, want errSymlinkInPath", err) + } + if _, err := tr.Get(ctx, "real/filelink"); err == nil { + t.Fatal("Get followed a symlink to a file") + } + if _, err := tr.List(ctx, "link"); err == nil { + t.Fatal("List followed a symlink to a directory") + } + // Renaming the link itself moves the link, never its target. + if err := tr.Rename(ctx, "link", "moved"); err != nil { + t.Fatalf("Rename the link: %v", err) + } + if got := mustRead(t, tr, "real/file"); got != "target bytes" { + t.Fatalf("the link's target changed: %q", got) + } +} + +func contractParentNotDir(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "f", "a file") + if _, err := tr.Stat(ctx, "f/x"); !errors.Is(err, errParentNotDir) { + t.Fatalf("Stat under a file = %v, want errParentNotDir", err) + } + if err := tr.Put(ctx, "f/x", strings.NewReader("x"), contractMtime); !errors.Is(err, errParentNotDir) { + t.Fatalf("Put under a file = %v, want errParentNotDir", err) + } +} + +func contractPutCancel(t *testing.T, tr transport, _ func(string, string)) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + body := bytes.NewReader(bytes.Repeat([]byte("x"), 1<<20)) + if err := tr.Put(ctx, "big", body, contractMtime); !errors.Is(err, context.Canceled) { + t.Fatalf("Put with a cancelled context = %v, want context.Canceled", err) + } + list, _ := tr.List(context.Background(), ".") + if i := slices.IndexFunc(list, func(e entry) bool { return e.name == "big" && e.size == 1<<20 }); i >= 0 { + t.Fatal("a cancelled Put landed the whole body") + } +} diff --git a/sync/transport_fault_test.go b/sync/transport_fault_test.go new file mode 100644 index 0000000..e04fcda --- /dev/null +++ b/sync/transport_fault_test.go @@ -0,0 +1,201 @@ +package sync + +import ( + "bytes" + "context" + "errors" + "io" + "io/fs" + "strings" + "sync" + "time" +) + +// errInjectedCrash is the failure a faultTransport reports once it has +// crashed. +var errInjectedCrash = errors.New("injected crash") + +// transportCall names one call a faultTransport saw. +type transportCall struct { + op, name, to string +} + +// crashMode is how the crashing call behaves. +type crashMode int + +const ( + crashBefore crashMode = iota // the call never happens + crashAfter // the call completes, then reports failure + crashMidway // a Put lands one byte of its body +) + +// faultTransport stands in for a process that dies at one transport call: +// the first call crashAt selects behaves as mode says, and every call after +// it fails, as if nothing were left to make it. With powerCut the machine +// loses power instead: the crash also takes back every Put and Rename +// since the last Flush, newest first, except the oldest keep(n) of those n +// (none without keep), as a disk that persists its names in order does. +// A kept Put's name survives but not its bytes: it holds as many zeros, +// with its mtime. Calls run one at a time, so a crash lands between whole +// calls. +type faultTransport struct { + transport + crashAt func(transportCall) bool + mode crashMode + powerCut bool + keep func(n int) int + + mu sync.Mutex + crashed bool + calls []transportCall + unflushed []transportCall +} + +// do runs one call through the crash point. call receives whether it +// should land only part of its effect. +func (f *faultTransport) do(c transportCall, call func(midway bool) error) error { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, c) + if f.crashed { + return errInjectedCrash + } + if f.crashAt == nil || !f.crashAt(c) { + err := call(false) + f.landed(c, err) + return err + } + f.crashed = true + switch f.mode { + case crashAfter: + f.landed(c, call(false)) + case crashMidway: + f.landed(c, call(true)) + } + if f.powerCut { + f.cutPower() + } + return errInjectedCrash +} + +// landed notes what a call that succeeded leaves for the next Flush. +func (f *faultTransport) landed(c transportCall, err error) { + if err != nil { + return + } + switch c.op { + case "put", "rename": + f.unflushed = append(f.unflushed, c) + case "flush": + f.unflushed = nil + } +} + +// cutPower takes back the puts and renames no Flush covered: a put file +// vanishes, a rename is reversed, and a put file whose name survives loses +// its bytes. +func (f *faultTransport) cutPower() { + kept := 0 + if f.keep != nil { + kept = f.keep(len(f.unflushed)) + } + ctx := context.Background() + for i, c := range f.unflushed[:kept] { + if c.op == "put" { + f.loseBytes(ctx, followRenames(c.name, f.unflushed[i+1:kept])) + } + } + for i := len(f.unflushed) - 1; i >= kept; i-- { + c := f.unflushed[i] + switch c.op { + case "put": + if err := f.transport.Remove(ctx, c.name); err != nil && !errors.Is(err, fs.ErrNotExist) { + panic(err) + } + case "rename": + if err := f.transport.Rename(ctx, c.to, c.name); err != nil { + panic(err) + } + } + } + f.unflushed = nil +} + +func (f *faultTransport) Stat(ctx context.Context, name string) (entry, error) { + var e entry + err := f.do(transportCall{op: "stat", name: name}, func(bool) error { + var err error + e, err = f.transport.Stat(ctx, name) + return err + }) + return e, err +} + +func (f *faultTransport) List(ctx context.Context, dir string) ([]entry, error) { + var es []entry + err := f.do(transportCall{op: "list", name: dir}, func(bool) error { + var err error + es, err = f.transport.List(ctx, dir) + return err + }) + return es, err +} + +func (f *faultTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + return f.do(transportCall{op: "put", name: name}, func(midway bool) error { + if midway { + r = io.LimitReader(r, 1) + } + return f.transport.Put(ctx, name, r, mtime) + }) +} + +func (f *faultTransport) Rename(ctx context.Context, from, to string) error { + return f.do(transportCall{op: "rename", name: from, to: to}, func(bool) error { + return f.transport.Rename(ctx, from, to) + }) +} + +// loseBytes replaces the file at name with as many zeros and its mtime. +func (f *faultTransport) loseBytes(ctx context.Context, name string) { + e, err := f.transport.Stat(ctx, name) + if errors.Is(err, fs.ErrNotExist) { + return + } + if err != nil { + panic(err) + } + if err := f.transport.Remove(ctx, name); err != nil { + panic(err) + } + if err := f.transport.Put(ctx, name, bytes.NewReader(make([]byte, e.size)), e.mtime); err != nil { + panic(err) + } +} + +// followRenames is where the file put at name sits after renames, which +// may move it or a directory above it. +func followRenames(name string, renames []transportCall) string { + for _, c := range renames { + switch { + case c.op != "rename": + case c.name == name: + name = c.to + case strings.HasPrefix(name, c.name+"/"): + name = c.to + strings.TrimPrefix(name, c.name) + } + } + return name +} + +func (f *faultTransport) Flush(ctx context.Context, dirs ...string) error { + return f.do(transportCall{op: "flush"}, func(bool) error { + return f.transport.Flush(ctx, dirs...) + }) +} + +func (f *faultTransport) Remove(ctx context.Context, name string) error { + return f.do(transportCall{op: "remove", name: name}, func(bool) error { + return f.transport.Remove(ctx, name) + }) +} diff --git a/sync/transport_guard.go b/sync/transport_guard.go new file mode 100644 index 0000000..39f53ff --- /dev/null +++ b/sync/transport_guard.go @@ -0,0 +1,219 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io/fs" + "path" + "strconv" + "strings" + + "github.com/mbertschler/squirrel/volmark" +) + +// errGuardRefused marks a move or removal the name guard does not permit. +var errGuardRefused = errors.New("the name guard refuses this operation") + +// nameGuard is the only gate on what may move or disappear on a +// destination. Layouts never hold the raw transport: they get a +// guardedTransport, whose Rename and Remove pass through permit first. +type nameGuard struct { + volumeDir string // the volume's directory under the destination root + runID int64 // the push holding the guard + // content marks a content-addressed or packed push, whose commits land + // on artifact names (see artifact); displacement is a mirror's alone. + content bool + // bootstrap lets a push under --init write the volume marker, before + // it holds a run. + bootstrap bool + // finished reports whether a run has ended, so its staging may go. + finished func(runID int64) bool +} + +type guardOp int + +const ( + opRemove guardOp = iota + opRename +) + +// permit is the whole audit surface for destroying or moving bytes on a +// destination. A bootstrap guard allows, run or not: +// +// - Remove of the staged marker, /.squirrel-staging/volume-marker, +// and its Rename onto /.squirrel-volume. +// +// Beyond that, a guard held by no run (runID 0, a dry run's reads) +// refuses everything; otherwise it allows: +// +// - Remove of a staging entry, or an emptied staging run directory, +// of a run that has finished: /.squirrel-staging/run-[/]; +// - Remove of a ride-along snapshot: /.squirrel-index/index-*.db; +// - for a mirror, Remove of the name probe, +// /.squirrel-staging/fold-probe-é; +// - Rename from this run's staging onto a snapshot name (the ride-along), +// or onto what the layout commits: a live name for a mirror, an +// artifact name for a content layout (see artifact); +// - for a mirror, Rename of a live name to the same path under this +// run's history (a displacement): +// /.squirrel-history/run-/. +// +// Every Rename lands on a name that does not exist yet: the transport +// fails one onto an existing name. +func (g nameGuard) permit(op guardOp, name, to string) error { + switch { + case g.bootstrap && name == markerStagingName(g.volumeDir) && (op == opRemove || to == path.Join(g.volumeDir, volmark.MarkerName)): + return nil + case g.runID == 0: + case op == opRemove: + if g.removable(name) { + return nil + } + case op == opRename: + if rel, ok := g.liveRel(name); ok && !g.content && to == historyName(g.volumeDir, g.runID, rel) { + return nil + } + if g.stagedByThisRun(name) && (g.snapshot(to) || g.commitTarget(to)) { + return nil + } + } + return fmt.Errorf("%w: %s %q → %q", errGuardRefused, [...]string{"remove", "rename"}[op], name, to) +} + +// commitTarget reports whether a staged file may be committed onto name. +func (g nameGuard) commitTarget(name string) bool { + if g.content { + return g.artifact(name) + } + _, ok := g.liveRel(name) + return ok +} + +// artifact reports whether name is one a content layout's run commits: a +// content object, objects/; a pack, packs/; this run's placement +// map, packs/map-; or this run's manifest segment, +// /index/run-. +func (g nameGuard) artifact(name string) bool { + dir, base := path.Split(name) + run := strconv.FormatInt(g.runID, 10) + switch dir { + case ObjectsDirName + "/": + return isStagingKey(base) + case PacksDirName + "/": + return isStagingKey(base) || base == packMapPrefix+run + case g.volumeDir + "/" + ManifestDirName + "/": + return base == "run-"+run + } + return false +} + +// snapshot reports whether name is a ride-along snapshot of the volume: +// /.squirrel-index/index-*.db. +func (g nameGuard) snapshot(name string) bool { + rel, ok := strings.CutPrefix(name, g.volumeDir+"/"+IndexDirName+"/") + return ok && !strings.Contains(rel, "/") && isSnapshotName(rel) +} + +func (g nameGuard) removable(name string) bool { + if g.snapshot(name) || (!g.content && name == foldProbeName(g.volumeDir)) { + return true + } + runID, key, ok := g.stagingParts(name) + if !ok || runID == g.runID || !g.finished(runID) { + return false + } + return key == "" || isStagingKey(key) +} + +func (g nameGuard) stagedByThisRun(name string) bool { + runID, key, ok := g.stagingParts(name) + return ok && runID == g.runID && isStagingKey(key) +} + +// stagingParts splits /.squirrel-staging/run-[/]. +func (g nameGuard) stagingParts(name string) (runID int64, key string, ok bool) { + rest, found := strings.CutPrefix(name, g.volumeDir+"/"+StagingDirName+"/run-") + if !found { + return 0, "", false + } + idText, key, _ := strings.Cut(rest, "/") + id, err := strconv.ParseInt(idText, 10, 64) + if err != nil || id <= 0 || strconv.FormatInt(id, 10) != idText || strings.Contains(key, "/") { + return 0, "", false + } + return id, key, true +} + +// liveRel returns the volume-relative path of a name in the mirrored tree: +// inside the volume directory, outside every reserved directory, and not +// the volume marker. +func (g nameGuard) liveRel(name string) (string, bool) { + rel, found := strings.CutPrefix(name, g.volumeDir+"/") + if !found || !fs.ValidPath(rel) || rel == "." || rel == volmark.MarkerName { + return "", false + } + top, _, _ := strings.Cut(rel, "/") + if isReservedFolderPath(top) { + return "", false + } + return rel, true +} + +// historyName is where a displacement by runID moves the volume-relative +// path rel: /.squirrel-history/run-/. +func historyName(volumeDir string, runID int64, rel string) string { + return path.Join(volumeDir, HistoryDirName, "run-"+strconv.FormatInt(runID, 10), rel) +} + +// markerStagingBase is the staging name the volume marker is written to +// before it is renamed onto .squirrel-volume. +const markerStagingBase = "volume-marker" + +// markerStagingName is where a --init push stages the volume marker: +// /.squirrel-staging/volume-marker. +func markerStagingName(volumeDir string) string { + return path.Join(volumeDir, StagingDirName, markerStagingBase) +} + +// stagingName is where runID stages the path whose key is key: +// /.squirrel-staging/run-/. +func stagingName(volumeDir string, runID int64, key string) string { + return path.Join(volumeDir, StagingDirName, "run-"+strconv.FormatInt(runID, 10), key) +} + +// isStagingKey reports whether key is the staging name of one path: the +// lowercase hex BLAKE3 of the volume-relative path, so it stays unique on a +// destination that folds case. +func isStagingKey(key string) bool { + if len(key) != 64 { + return false + } + for _, c := range key { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + +// guardedTransport is the transport a layout holds: every Rename and +// Remove passes the name guard first. +type guardedTransport struct { + transport + guard nameGuard +} + +func (t guardedTransport) Rename(ctx context.Context, from, to string) error { + if err := t.guard.permit(opRename, from, to); err != nil { + return err + } + return t.transport.Rename(ctx, from, to) +} + +func (t guardedTransport) Remove(ctx context.Context, name string) error { + if err := t.guard.permit(opRemove, name, ""); err != nil { + return err + } + return t.transport.Remove(ctx, name) +} diff --git a/sync/transport_guard_test.go b/sync/transport_guard_test.go new file mode 100644 index 0000000..a650f7c --- /dev/null +++ b/sync/transport_guard_test.go @@ -0,0 +1,143 @@ +package sync + +import ( + "errors" + "strings" + "testing" +) + +// TestNameGuardPermits is the table behind the name guard, the whole audit +// surface for moving or destroying bytes on a destination. +func TestNameGuardPermits(t *testing.T) { + key := strings.Repeat("ab", 32) + g := nameGuard{volumeDir: "pics", runID: 7, finished: func(id int64) bool { return id != 9 }} + cases := []struct { + name string + op guardOp + from, to string + want bool + }{ + {"commit from this run's staging", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/2024/cat.jpg", true}, + {"commit from another run's staging", opRename, "pics/.squirrel-staging/run-6/" + key, "pics/2024/cat.jpg", false}, + {"commit of a foreign staging name", opRename, "pics/.squirrel-staging/run-7/notes.txt", "pics/2024/cat.jpg", false}, + {"commit onto the marker", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-volume", false}, + {"commit into history", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-history/run-7/cat.jpg", false}, + {"commit into another volume", opRename, "pics/.squirrel-staging/run-7/" + key, "docs/cat.jpg", false}, + {"displace into this run's history", opRename, "pics/2024/cat.jpg", "pics/.squirrel-history/run-7/2024/cat.jpg", true}, + {"displace a directory", opRename, "pics/2024", "pics/.squirrel-history/run-7/2024", true}, + {"displace into another run's history", opRename, "pics/2024/cat.jpg", "pics/.squirrel-history/run-6/2024/cat.jpg", false}, + {"displace under another path", opRename, "pics/2024/cat.jpg", "pics/.squirrel-history/run-7/dog.jpg", false}, + {"move history back out", opRename, "pics/.squirrel-history/run-3/cat.jpg", "pics/.squirrel-history/run-7/.squirrel-history/run-3/cat.jpg", false}, + {"displace the marker", opRename, "pics/.squirrel-volume", "pics/.squirrel-history/run-7/.squirrel-volume", false}, + {"rename between live names", opRename, "pics/a.jpg", "pics/b.jpg", false}, + {"escape the volume", opRename, "pics/../x", "pics/.squirrel-history/run-7/../x", false}, + {"remove a finished run's staging", opRemove, "pics/.squirrel-staging/run-6/" + key, "", true}, + {"remove a finished run's staging directory", opRemove, "pics/.squirrel-staging/run-6", "", true}, + {"remove this run's staging", opRemove, "pics/.squirrel-staging/run-7/" + key, "", false}, + {"remove a running run's staging", opRemove, "pics/.squirrel-staging/run-9/" + key, "", false}, + {"remove a foreign file in staging", opRemove, "pics/.squirrel-staging/run-6/notes.txt", "", false}, + {"remove a malformed run directory", opRemove, "pics/.squirrel-staging/run-06/" + key, "", false}, + {"remove a snapshot", opRemove, "pics/.squirrel-index/index-20260101T000000.000Z-run-6.db", "", true}, + {"remove a receipt", opRemove, "pics/.squirrel-index/run-6", "", false}, + {"remove a live file", opRemove, "pics/2024/cat.jpg", "", false}, + {"remove history", opRemove, "pics/.squirrel-history/run-6/cat.jpg", "", false}, + {"remove another volume's staging", opRemove, "docs/.squirrel-staging/run-6/" + key, "", false}, + {"ride a snapshot along from this run's staging", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", true}, + {"stage onto a receipt", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-index/run-7", false}, + {"ride a snapshot along from another run's staging", opRename, "pics/.squirrel-staging/run-6/" + key, "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", false}, + {"move a live file onto a snapshot name", opRename, "pics/a.db", "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", false}, + {"marker bootstrap without --init", opRename, "pics/.squirrel-staging/volume-marker", "pics/.squirrel-volume", false}, + {"remove the staged marker without --init", opRemove, "pics/.squirrel-staging/volume-marker", "", false}, + {"remove the name probe", opRemove, foldProbeName("pics"), "", true}, + {"remove the name probe decomposed", opRemove, "pics/.squirrel-staging/" + foldProbeNorm, "", false}, + {"remove another volume's name probe", opRemove, foldProbeName("docs"), "", false}, + {"commit the name probe", opRename, foldProbeName("pics"), "pics/a.txt", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if err := (nameGuard{volumeDir: "pics", finished: g.finished}).permit(c.op, c.from, c.to); err == nil { + t.Fatal("a guard no run holds permitted the operation") + } + err := g.permit(c.op, c.from, c.to) + if got := err == nil; got != c.want { + t.Fatalf("permit = %v, want allowed=%t", err, c.want) + } + if err != nil && !errors.Is(err, errGuardRefused) { + t.Fatalf("refusal %v does not wrap errGuardRefused", err) + } + }) + } +} + +// TestNameGuardContentLayout: a content layout's guard commits this run's +// staging onto artifact names alone, and displaces nothing. +func TestNameGuardContentLayout(t *testing.T) { + key := strings.Repeat("ab", 32) + staged := "pics/.squirrel-staging/run-7/" + key + g := nameGuard{volumeDir: "pics", runID: 7, content: true, finished: func(id int64) bool { return id != 7 }} + cases := []struct { + name string + op guardOp + from, to string + want bool + }{ + {"commit an object", opRename, staged, "objects/" + key, true}, + {"commit a pack", opRename, staged, "packs/" + key, true}, + {"commit this run's placement map", opRename, staged, "packs/map-7", true}, + {"commit another run's placement map", opRename, staged, "packs/map-6", false}, + {"commit this run's segment", opRename, staged, "pics/index/run-7", true}, + {"commit another run's segment", opRename, staged, "pics/index/run-6", false}, + {"commit another volume's segment", opRename, staged, "docs/index/run-7", false}, + {"commit an object from another run's staging", opRename, "pics/.squirrel-staging/run-6/" + key, "objects/" + key, false}, + {"commit an object under a name that is no hash", opRename, staged, "objects/cat.jpg", false}, + {"commit an object below objects", opRename, staged, "objects/ab/" + key, false}, + {"commit onto the mirrored tree", opRename, staged, "pics/2024/cat.jpg", false}, + {"ride a snapshot along", opRename, staged, "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", true}, + {"displace a segment", opRename, "pics/index/run-6", "pics/.squirrel-history/run-7/index/run-6", false}, + {"move an object", opRename, "objects/" + key, "packs/" + key, false}, + {"remove an object", opRemove, "objects/" + key, "", false}, + {"remove a finished run's staging", opRemove, "pics/.squirrel-staging/run-6/" + key, "", true}, + {"remove a mirror's name probe", opRemove, foldProbeName("pics"), "", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := g.permit(c.op, c.from, c.to) + if got := err == nil; got != c.want { + t.Fatalf("permit = %v, want allowed=%t", err, c.want) + } + }) + } + mirror := nameGuard{volumeDir: "pics", runID: 7} + if err := mirror.permit(opRename, staged, "objects/"+key); err == nil { + t.Fatal("a mirror's guard committed onto an object name") + } +} + +// TestNameGuardBootstrap: under --init the guard also lets the marker be +// staged, renamed onto .squirrel-volume, and a stale staged copy removed — +// run or not — and nothing more. +func TestNameGuardBootstrap(t *testing.T) { + cases := []struct { + name string + op guardOp + from, to string + want bool + }{ + {"rename the staged marker onto the marker", opRename, "pics/.squirrel-staging/volume-marker", "pics/.squirrel-volume", true}, + {"remove a stale staged marker", opRemove, "pics/.squirrel-staging/volume-marker", "", true}, + {"rename the staged marker elsewhere", opRename, "pics/.squirrel-staging/volume-marker", "pics/a.txt", false}, + {"rename something else onto the marker", opRename, "pics/a.txt", "pics/.squirrel-volume", false}, + {"remove the marker", opRemove, "pics/.squirrel-volume", "", false}, + {"another volume's staged marker", opRename, "docs/.squirrel-staging/volume-marker", "docs/.squirrel-volume", false}, + {"remove a live file", opRemove, "pics/a.txt", "", false}, + } + g := nameGuard{volumeDir: "pics", bootstrap: true} + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := g.permit(c.op, c.from, c.to) + if got := err == nil; got != c.want { + t.Fatalf("permit = %v, want allowed=%t", err, c.want) + } + }) + } +} diff --git a/sync/transport_local.go b/sync/transport_local.go new file mode 100644 index 0000000..fb3b99b --- /dev/null +++ b/sync/transport_local.go @@ -0,0 +1,295 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "time" +) + +// localTransport is the transport onto a directory of this machine's +// filesystem. os.Root confines every name to the root; on top of that each +// operation checks its name's parent chain with Lstat and refuses a +// symlink anywhere along it, because os.Root follows symlinks that stay +// inside the root. Put and Get keep their pages out of the cache where +// the platform allows (bypassCache), so reading back a file just written +// reads what reached the disk. Flush makes durable in one go every file +// Put left open and every directory whose entries changed since the last +// one (flushLocal). +type localTransport struct { + root *os.Root + + mu sync.Mutex + pending []*os.File + dirty map[string]bool + closed bool +} + +func openLocalTransport(dir string) (*localTransport, error) { + root, err := os.OpenRoot(dir) + if err != nil { + return nil, fmt.Errorf("open destination root %s: %w", dir, err) + } + return &localTransport{root: root, dirty: map[string]bool{}}, nil +} + +func (t *localTransport) Close() error { + t.mu.Lock() + for _, f := range t.pending { + _ = f.Close() + } + t.pending, t.closed = nil, true + t.mu.Unlock() + return t.root.Close() +} + +func (t *localTransport) Stat(_ context.Context, name string) (entry, error) { + if err := t.checkName(name); err != nil { + return entry{}, err + } + fi, err := t.root.Lstat(filepath.FromSlash(name)) + if err != nil { + return entry{}, err + } + return entryOf(fi), nil +} + +func (t *localTransport) List(_ context.Context, dir string) ([]entry, error) { + if dir != "." { + if err := t.checkName(dir); err != nil { + return nil, err + } + if err := requireKind(dir, kindDir, t.lstat); err != nil { + return nil, err + } + } + f, err := t.root.Open(filepath.FromSlash(dir)) + if err != nil { + return nil, err + } + defer f.Close() + des, err := f.ReadDir(-1) + if err != nil { + return nil, fmt.Errorf("list %s: %w", dir, err) + } + out := make([]entry, 0, len(des)) + for _, de := range des { + fi, err := de.Info() + if err != nil { + return nil, fmt.Errorf("list %s: %w", dir, err) + } + out = append(out, entryOf(fi)) + } + return out, nil +} + +func (t *localTransport) Get(_ context.Context, name string) (io.ReadCloser, error) { + if err := t.checkName(name); err != nil { + return nil, err + } + if err := requireKind(name, kindFile, t.lstat); err != nil { + return nil, err + } + f, err := t.root.Open(filepath.FromSlash(name)) + if err != nil { + return nil, err + } + bypassCache(f) + return f, nil +} + +func (t *localTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if err := t.checkName(name); err != nil { + return err + } + if err := t.mkdirParents(name); err != nil { + return err + } + f, err := t.root.OpenFile(filepath.FromSlash(name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + return err + } + bypassCache(f) + t.markDirty(path.Dir(name)) + if err := t.fill(ctx, f, name, r, mtime); err != nil { + _ = f.Close() + return err + } + return t.settle(f, name) +} + +// settle moves a filled file toward the disk as the platform does it +// (settleFile), and holds it open for the next Flush where that flush +// needs it. +func (t *localTransport) settle(f *os.File, name string) error { + keep, err := settleFile(f) + if err != nil { + _ = f.Close() + return fmt.Errorf("sync %s: %w", name, err) + } + if !keep { + if err := f.Close(); err != nil { + return fmt.Errorf("close %s: %w", name, err) + } + return nil + } + t.mu.Lock() + defer t.mu.Unlock() + if t.closed { + return f.Close() + } + t.pending = append(t.pending, f) + return nil +} + +// fill streams r into the freshly created f and stamps mtime. +func (t *localTransport) fill(ctx context.Context, f *os.File, name string, r io.Reader, mtime time.Time) error { + if _, err := io.Copy(f, ctxReader{ctx: ctx, r: r}); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + if err := t.root.Chtimes(filepath.FromSlash(name), mtime, mtime); err != nil { + return fmt.Errorf("set mtime of %s: %w", name, err) + } + return nil +} + +func (t *localTransport) Rename(_ context.Context, from, to string) error { + if err := t.checkName(from); err != nil { + return err + } + if err := t.checkName(to); err != nil { + return err + } + if _, err := t.root.Lstat(filepath.FromSlash(from)); err != nil { + return err + } + if err := t.mkdirParents(to); err != nil { + return err + } + t.markDirty(path.Dir(to)) + if err := renameNoReplace(t.root, from, to); err != nil { + return err + } + t.markDirty(path.Dir(from)) + return nil +} + +// Flush makes every file Put left open, every directory a call changed, +// and dirs durable, then releases the files. +func (t *localTransport) Flush(_ context.Context, dirs ...string) error { + t.mu.Lock() + for _, d := range dirs { + t.dirty[d] = true + } + files, dirty := t.pending, t.dirty + t.pending, t.dirty = nil, map[string]bool{} + t.mu.Unlock() + defer func() { + for _, f := range files { + _ = f.Close() + } + }() + sorted := make([]string, 0, len(dirty)) + for d := range dirty { + sorted = append(sorted, d) + } + slices.Sort(sorted) + return flushLocal(t.root, files, sorted) +} + +func (t *localTransport) Remove(_ context.Context, name string) error { + if err := t.checkName(name); err != nil { + return err + } + return t.root.Remove(filepath.FromSlash(name)) +} + +// ServerHash is errNoServerHash on a local disk: squirrel reads its bytes +// back itself (readBack). +func (t *localTransport) ServerHash(context.Context, string) (remoteChecksum, error) { + return remoteChecksum{}, errNoServerHash +} + +// checkName refuses a name that is not a clean path below the root, or +// whose parent chain crosses a symlink or a non-directory. +func (t *localTransport) checkName(name string) error { + if !validName(name) || (runtime.GOOS == "windows" && strings.ContainsRune(name, '\\')) { + return fmt.Errorf("%w: %q", errInvalidName, name) + } + return checkParents(name, t.lstat) +} + +func (t *localTransport) lstat(name string) (fs.FileInfo, error) { + return t.root.Lstat(filepath.FromSlash(name)) +} + +// mkdirParents creates name's missing parents, one at a time, so the +// directory holding each new one is flushed with the next Flush. +func (t *localTransport) mkdirParents(name string) error { + dir := path.Dir(name) + if dir == "." { + return nil + } + if fi, err := t.lstat(dir); err == nil && fi.IsDir() { + return nil + } + parts := strings.Split(dir, "/") + for i := range parts { + p := strings.Join(parts[:i+1], "/") + err := t.root.Mkdir(filepath.FromSlash(p), 0o755) + switch { + case err == nil: + t.markDirty(path.Dir(p)) + case !errors.Is(err, fs.ErrExist): + return fmt.Errorf("create %s: %w", dir, err) + } + } + return nil +} + +func (t *localTransport) markDirty(dir string) { + t.mu.Lock() + t.dirty[dir] = true + t.mu.Unlock() +} + +// syncDir flushes a directory's entries where the filesystem can. +func syncDir(root *os.Root, dir string, flush func(*os.File) error) error { + f, err := root.Open(filepath.FromSlash(dir)) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("open %s to sync it: %w", dir, err) + } + defer f.Close() + if err := flush(f); err != nil && !dirSyncUnsupported(err) { + return fmt.Errorf("sync %s: %w", dir, err) + } + return nil +} + +// renameCheckThenMove is the rename for a filesystem without a no-replace +// rename, exFAT for one: an Lstat, then a plain rename. A writer outside +// squirrel could slip a file in between the two; squirrel cannot collide +// with itself there, because the run guard and the volume marker already +// exclude a second squirrel writer. +func renameCheckThenMove(root *os.Root, from, to string) error { + _, err := root.Lstat(filepath.FromSlash(to)) + if err == nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: fs.ErrExist} + } + if !errors.Is(err, fs.ErrNotExist) { + return err + } + return root.Rename(filepath.FromSlash(from), filepath.FromSlash(to)) +} diff --git a/sync/transport_local_darwin.go b/sync/transport_local_darwin.go new file mode 100644 index 0000000..9a46bca --- /dev/null +++ b/sync/transport_local_darwin.go @@ -0,0 +1,65 @@ +package sync + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +// renameNoReplace moves from to to inside root with renameatx_np's +// RENAME_EXCL, which fails with EEXIST instead of replacing to. A +// filesystem that does not support the flag gets renameCheckThenMove. +func renameNoReplace(root *os.Root, from, to string) error { + err := withParentDirs(root, from, to, func(fromDir, toDir *os.File, fromBase, toBase string) error { + return unix.RenameatxNp(int(fromDir.Fd()), fromBase, int(toDir.Fd()), toBase, unix.RENAME_EXCL) + }) + if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) { + return renameCheckThenMove(root, from, to) + } + if err != nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: err} + } + return nil +} + +// bypassCache sets F_NOCACHE on f, so its reads and writes go to the +// device and leave no pages in the cache behind: a read of a file written +// that way returns what the disk holds. +func bypassCache(f *os.File) { + _, _ = unix.FcntlInt(f.Fd(), unix.F_NOCACHE, 1) +} + +// settleFile moves f's bytes to the device with a plain fsync. The drive's +// cache is flushed once for the whole batch by flushLocal, so f stays open +// until then. +func settleFile(f *os.File) (bool, error) { + return true, unix.Fsync(int(f.Fd())) +} + +// flushLocal fsyncs every changed directory, then flushes the drive's +// cache once with F_FULLFSYNC (os.File.Sync), which also persists +// everything fsynced on the device before it: the files settleFile +// fsynced included. A file carries that flush where there is one, since +// some filesystems cannot flush a directory. +func flushLocal(root *os.Root, files []*os.File, dirs []string) error { + for _, d := range dirs { + if err := syncDir(root, d, fsyncPlain); err != nil { + return err + } + } + if len(files) > 0 { + return files[0].Sync() + } + if len(dirs) == 0 { + return nil + } + return syncDir(root, ".", (*os.File).Sync) +} + +func fsyncPlain(f *os.File) error { return unix.Fsync(int(f.Fd())) } + +// dirSyncUnsupported reports a filesystem that cannot flush a directory. +func dirSyncUnsupported(err error) bool { + return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) +} diff --git a/sync/transport_local_dirs.go b/sync/transport_local_dirs.go new file mode 100644 index 0000000..4bcb3f6 --- /dev/null +++ b/sync/transport_local_dirs.go @@ -0,0 +1,26 @@ +//go:build linux || darwin + +package sync + +import ( + "os" + "path" + "path/filepath" +) + +// withParentDirs opens the parent directories of from and to inside root +// and hands fn their handles and the two base names, for the directory +// relative system calls a no-replace rename needs. +func withParentDirs(root *os.Root, from, to string, fn func(fromDir, toDir *os.File, fromBase, toBase string) error) error { + fromDir, err := root.Open(filepath.FromSlash(path.Dir(from))) + if err != nil { + return err + } + defer fromDir.Close() + toDir, err := root.Open(filepath.FromSlash(path.Dir(to))) + if err != nil { + return err + } + defer toDir.Close() + return fn(fromDir, toDir, path.Base(from), path.Base(to)) +} diff --git a/sync/transport_local_linux.go b/sync/transport_local_linux.go new file mode 100644 index 0000000..40e81de --- /dev/null +++ b/sync/transport_local_linux.go @@ -0,0 +1,56 @@ +package sync + +import ( + "errors" + "fmt" + "os" + + "golang.org/x/sys/unix" +) + +// renameNoReplace moves from to to inside root with renameat2's +// RENAME_NOREPLACE, which fails with EEXIST instead of replacing to. A +// filesystem that does not support the flag gets renameCheckThenMove. +func renameNoReplace(root *os.Root, from, to string) error { + err := withParentDirs(root, from, to, func(fromDir, toDir *os.File, fromBase, toBase string) error { + return unix.Renameat2(int(fromDir.Fd()), fromBase, int(toDir.Fd()), toBase, unix.RENAME_NOREPLACE) + }) + if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOSYS) || errors.Is(err, unix.ENOTSUP) { + return renameCheckThenMove(root, from, to) + } + if err != nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: err} + } + return nil +} + +// bypassCache drops f's clean pages from the cache, so the next read of +// what was synced comes from the device. +func bypassCache(f *os.File) { + _ = unix.Fadvise(int(f.Fd()), 0, 0, unix.FADV_DONTNEED) +} + +// settleFile leaves f to flushLocal: fsync flushes the drive itself on +// Linux, so each file is fsynced once, at the flush. +func settleFile(*os.File) (bool, error) { return true, nil } + +// flushLocal fsyncs every pending file and changed directory together, so +// the filesystem's journal commits the batch at once. +func flushLocal(root *os.Root, files []*os.File, dirs []string) error { + for _, f := range files { + if err := f.Sync(); err != nil { + return fmt.Errorf("sync %s: %w", f.Name(), err) + } + } + for _, d := range dirs { + if err := syncDir(root, d, (*os.File).Sync); err != nil { + return err + } + } + return nil +} + +// dirSyncUnsupported reports a filesystem that cannot flush a directory. +func dirSyncUnsupported(err error) bool { + return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) +} diff --git a/sync/transport_local_other.go b/sync/transport_local_other.go new file mode 100644 index 0000000..d91fc70 --- /dev/null +++ b/sync/transport_local_other.go @@ -0,0 +1,33 @@ +//go:build !linux && !darwin + +package sync + +import "os" + +// renameNoReplace moves from to to inside root. This platform offers +// squirrel no no-replace rename, so it checks, then renames. +func renameNoReplace(root *os.Root, from, to string) error { + return renameCheckThenMove(root, from, to) +} + +// bypassCache: this platform gives squirrel no handle on the cache, so a +// read may be served from it. +func bypassCache(*os.File) {} + +// settleFile flushes f as its Put ends: this platform offers squirrel no +// flush that covers several files. +func settleFile(f *os.File) (bool, error) { return false, f.Sync() } + +// flushLocal flushes every changed directory where the platform can. +func flushLocal(root *os.Root, _ []*os.File, dirs []string) error { + for _, d := range dirs { + if err := syncDir(root, d, (*os.File).Sync); err != nil { + return err + } + } + return nil +} + +// dirSyncUnsupported: a directory cannot be flushed through a handle on +// this platform, so the sync is best effort. +func dirSyncUnsupported(error) bool { return true } diff --git a/sync/transport_sftp.go b/sync/transport_sftp.go new file mode 100644 index 0000000..73f8535 --- /dev/null +++ b/sync/transport_sftp.go @@ -0,0 +1,218 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "strings" + "sync" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +// sftpTransport is the transport onto a directory of an sftp server. The +// server resolves symlinks itself, so every operation checks its name's +// parent chain with Lstat and refuses a symlink anywhere along it. The +// protocol's own create-exclusive and rename are not trusted to refuse an +// existing name on every server, so Put and Rename Lstat their target +// first. +type sftpTransport struct { + conn *ssh.Client + client *sftp.Client + root string // the destination root on the server + // fsync is whether the server offers fsync@openssh.com, which Put + // uses to flush a file to stable storage before it returns. + fsync bool + // hashAlgo is the destination's hash_algo: the hash command + // ServerHash runs, probed once (probed, probeErr). + hashAlgo string + probeMu sync.Mutex + probed bool + probeErr error +} + +// Close drops the ssh connection first: the sftp client's own Close +// waits for the server to end the session, which a hung server never does. +func (t *sftpTransport) Close() error { + err := t.conn.Close() + _ = t.client.Close() + return err +} + +func (t *sftpTransport) Stat(_ context.Context, name string) (entry, error) { + if err := t.checkName(name); err != nil { + return entry{}, err + } + fi, err := t.lstat(name) + if err != nil { + return entry{}, err + } + return entryOf(fi), nil +} + +func (t *sftpTransport) List(_ context.Context, dir string) ([]entry, error) { + full := t.root + if dir != "." { + if err := t.checkName(dir); err != nil { + return nil, err + } + if err := requireKind(dir, kindDir, t.lstat); err != nil { + return nil, err + } + full = t.full(dir) + } + fis, err := t.client.ReadDir(full) + if err != nil { + return nil, fmt.Errorf("list %s: %w", dir, err) + } + out := make([]entry, 0, len(fis)) + for _, fi := range fis { + switch name := fi.Name(); { + case name == "." || name == "..": + case !validName(name) || strings.Contains(name, "/"): + return nil, fmt.Errorf("list %s: the server listed %q: %w", dir, name, errInvalidName) + default: + out = append(out, entryOf(fi)) + } + } + return out, nil +} + +func (t *sftpTransport) Get(_ context.Context, name string) (io.ReadCloser, error) { + if err := t.checkName(name); err != nil { + return nil, err + } + if err := requireKind(name, kindFile, t.lstat); err != nil { + return nil, err + } + return t.client.Open(t.full(name)) +} + +func (t *sftpTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if err := t.checkName(name); err != nil { + return err + } + if err := t.refuseExisting("put", name); err != nil { + return err + } + if err := t.mkdirParents(name); err != nil { + return err + } + f, err := t.client.OpenFile(t.full(name), os.O_WRONLY|os.O_CREATE|os.O_EXCL) + if err != nil { + if exists := t.refuseExisting("put", name); exists != nil { + return exists + } + return err + } + if err := t.fill(ctx, f, name, r, mtime); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return fmt.Errorf("close %s: %w", name, err) + } + return nil +} + +// fill streams r into the freshly created f with concurrent writes, so a +// high-latency link does not cap throughput, stamps mtime, and flushes +// the file where the server offers it. +func (t *sftpTransport) fill(ctx context.Context, f *sftp.File, name string, r io.Reader, mtime time.Time) error { + if _, err := f.ReadFromWithConcurrency(ctxReader{ctx: ctx, r: r}, 0); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + if err := t.client.Chtimes(t.full(name), mtime, mtime); err != nil { + return fmt.Errorf("set mtime of %s: %w", name, err) + } + if !t.fsync { + return nil + } + if err := f.Sync(); err != nil { + return fmt.Errorf("sync %s: %w", name, err) + } + return nil +} + +func (t *sftpTransport) Rename(_ context.Context, from, to string) error { + if err := t.checkName(from); err != nil { + return err + } + if err := t.checkName(to); err != nil { + return err + } + if _, err := t.lstat(from); err != nil { + return err + } + if err := t.mkdirParents(to); err != nil { + return err + } + if err := t.refuseExisting("rename", to); err != nil { + return err + } + if err := t.client.Rename(t.full(from), t.full(to)); err != nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: err} + } + return nil +} + +// Flush returns at once: each Put already flushed its file through +// fsync@openssh.com where the server offers it, and flushing a directory +// is beyond the protocol. +func (t *sftpTransport) Flush(context.Context, ...string) error { return nil } + +func (t *sftpTransport) Remove(_ context.Context, name string) error { + if err := t.checkName(name); err != nil { + return err + } + fi, err := t.lstat(name) + if err != nil { + return err + } + if fi.IsDir() { + return t.client.RemoveDirectory(t.full(name)) + } + return t.client.Remove(t.full(name)) +} + +// refuseExisting fails with fs.ErrExist when name is present. +func (t *sftpTransport) refuseExisting(op, name string) error { + _, err := t.lstat(name) + if err == nil { + return &fs.PathError{Op: op, Path: name, Err: fs.ErrExist} + } + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err +} + +func (t *sftpTransport) checkName(name string) error { + if !validName(name) { + return fmt.Errorf("%w: %q", errInvalidName, name) + } + return checkParents(name, t.lstat) +} + +func (t *sftpTransport) lstat(name string) (fs.FileInfo, error) { + return t.client.Lstat(t.full(name)) +} + +func (t *sftpTransport) full(name string) string { return path.Join(t.root, name) } + +func (t *sftpTransport) mkdirParents(name string) error { + dir := path.Dir(name) + if dir == "." { + return nil + } + if err := t.client.MkdirAll(t.full(dir)); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + return nil +} diff --git a/sync/transport_sftp_dial.go b/sync/transport_sftp_dial.go new file mode 100644 index 0000000..8dfe4a4 --- /dev/null +++ b/sync/transport_sftp_dial.go @@ -0,0 +1,170 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "strings" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" + + "github.com/mbertschler/squirrel/config" +) + +// sftpConnectTimeout bounds the TCP connect and the ssh handshake of one +// sftp session. +const sftpConnectTimeout = time.Minute + +// fsyncExtension is the OpenSSH extension that flushes an open file to +// stable storage. +const fsyncExtension = "fsync@openssh.com" + +// dialSFTP opens an sftp session to dest's server and returns the +// transport onto dest's root. The server's host key must be one +// known_hosts pins for it. +func dialSFTP(ctx context.Context, dest *config.Destination) (*sftpTransport, error) { + keys, err := loadHostKeys(dest) + if err != nil { + return nil, fmt.Errorf("destination %q: %w", dest.Name, err) + } + auth, release, err := sftpAuth(dest) + if err != nil { + return nil, fmt.Errorf("destination %q: %w", dest.Name, err) + } + cfg := &ssh.ClientConfig{User: dest.Params["user"], Auth: auth, HostKeyCallback: keys.check} + if algos := dest.Params["host_key_algorithms"]; algos != "" { + cfg.HostKeyAlgorithms = strings.Fields(algos) + } + tr, err := dialSession(ctx, sftpAddress(dest), cfg, keys) + release() + if err != nil { + return nil, fmt.Errorf("destination %q: %w", dest.Name, err) + } + tr.root = dest.Root + tr.hashAlgo = dest.HashAlgo + return tr, nil +} + +// sftpAddress is the host:port dest's server listens on. +func sftpAddress(dest *config.Destination) string { + port := dest.Params["port"] + if port == "" { + port = "22" + } + return net.JoinHostPort(dest.Params["host"], port) +} + +// dialSession connects to addr, completes the ssh handshake and starts +// the sftp session, all within sftpConnectTimeout. Unless the config pins +// them, the host key algorithms follow the keys known_hosts pins, settled +// once the peer's address is known, since known_hosts may pin keys by +// address. +func dialSession(ctx context.Context, addr string, cfg *ssh.ClientConfig, keys hostKeys) (*sftpTransport, error) { + ctx, cancel := context.WithTimeout(ctx, sftpConnectTimeout) + defer cancel() + var d net.Dialer + tcp, err := d.DialContext(ctx, "tcp", addr) + if err != nil { + return nil, fmt.Errorf("connect to %s: %w", addr, err) + } + if cfg.HostKeyAlgorithms == nil { + cfg.HostKeyAlgorithms = keys.algorithms(addr, tcp.RemoteAddr()) + } + deadline, _ := ctx.Deadline() + _ = tcp.SetDeadline(deadline) + c, chans, reqs, err := ssh.NewClientConn(tcp, addr, cfg) + if err != nil { + _ = tcp.Close() + return nil, fmt.Errorf("ssh to %s: %w", addr, err) + } + conn := ssh.NewClient(c, chans, reqs) + client, err := sftp.NewClient(conn, sftp.UseConcurrentWrites(true)) + if err != nil { + _ = conn.Close() + return nil, fmt.Errorf("start sftp on %s: %w", addr, err) + } + _ = tcp.SetDeadline(time.Time{}) + data, ok := client.HasExtension(fsyncExtension) + return &sftpTransport{conn: conn, client: client, fsync: ok && data == "1"}, nil +} + +// sftpAuth is how squirrel logs in: with the key file and the password +// where configured, else with the keys ssh-agent holds. +func sftpAuth(dest *config.Destination) ([]ssh.AuthMethod, func(), error) { + var auth []ssh.AuthMethod + if file := dest.Params["key_file"]; file != "" { + signer, err := readPrivateKey(file) + if err != nil { + return nil, nil, err + } + auth = append(auth, ssh.PublicKeys(signer)) + } + if pw := dest.Params["password"]; pw != "" { + auth = append(auth, ssh.Password(pw), ssh.KeyboardInteractive(answerWith(pw))) + } + if len(auth) > 0 { + return auth, func() {}, nil + } + return agentAuth() +} + +func readPrivateKey(file string) (ssh.Signer, error) { + b, err := os.ReadFile(expandHome(file)) + if err != nil { + return nil, fmt.Errorf("read key_file: %w", err) + } + signer, err := ssh.ParsePrivateKey(b) + if _, ok := errors.AsType[*ssh.PassphraseMissingError](err); ok { + return nil, fmt.Errorf("key_file %s is protected by a passphrase, which squirrel cannot enter unattended: load it into ssh-agent and leave key_file and password unset", file) + } + if err != nil { + return nil, fmt.Errorf("parse key_file %s: %w", file, err) + } + return signer, nil +} + +// answerWith answers every keyboard-interactive prompt with the password, +// for servers that ask for it that way. +func answerWith(pw string) ssh.KeyboardInteractiveChallenge { + return func(_, _ string, questions []string, _ []bool) ([]string, error) { + answers := make([]string, len(questions)) + for i := range answers { + answers[i] = pw + } + return answers, nil + } +} + +// agentAuth offers the keys of the ssh-agent at SSH_AUTH_SOCK. The agent +// signs during the handshake, so its connection stays open until release. +func agentAuth() ([]ssh.AuthMethod, func(), error) { + sock := os.Getenv("SSH_AUTH_SOCK") + if sock == "" { + return nil, nil, errors.New("no password or key_file is set, and there is no ssh-agent to log in with (SSH_AUTH_SOCK is unset)") + } + c, err := net.Dial("unix", sock) + if err != nil { + return nil, nil, fmt.Errorf("no password or key_file is set, and the ssh-agent at %s is unreachable: %w", sock, err) + } + auth := []ssh.AuthMethod{ssh.PublicKeysCallback(agent.NewClient(c).Signers)} + return auth, func() { _ = c.Close() }, nil +} + +// expandHome expands a leading ~/ to the user's home directory. +func expandHome(p string) string { + rest, ok := strings.CutPrefix(p, "~/") + if !ok { + return p + } + home, err := os.UserHomeDir() + if err != nil { + return p + } + return filepath.Join(home, rest) +} diff --git a/sync/transport_sftp_hash.go b/sync/transport_sftp_hash.go new file mode 100644 index 0000000..06c12c5 --- /dev/null +++ b/sync/transport_sftp_hash.go @@ -0,0 +1,184 @@ +package sync + +import ( + "bytes" + "context" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "path" + "regexp" + "strings" + + "github.com/zeebo/blake3" + "golang.org/x/crypto/ssh" +) + +// errNoServerHash marks a destination that offers squirrel no hash of its +// own for a file: a local disk, whose bytes squirrel reads back instead, an +// sftp server that runs no hash command, or a name the command line may +// not carry. +var errNoServerHash = errors.New("the destination offers no hash of its own") + +// serverHashCommands are the commands an sftp server runs for each +// hash_algo squirrel's own transport supports. +var serverHashCommands = map[string]string{ + "md5": "md5sum", + "sha1": "sha1sum", + "sha256": "sha256sum", + "blake3": "b3sum", +} + +// newArtifactHash is the hash algo names, computed on this machine: what +// the server's command must agree with. +func newArtifactHash(algo string) hash.Hash { + switch algo { + case "md5": + return md5.New() + case "sha1": + return sha1.New() + case "sha256": + return sha256.New() + case "blake3": + return blake3.New() + } + return nil +} + +// commandSafe matches what a server command line may carry unquoted. +var commandSafe = regexp.MustCompile(`^[A-Za-z0-9._/-]+$`) + +// serverHashProbe is the input the probe hashes on the server. +const serverHashProbe = "squirrel server hash probe\n" + +// maxHashOutput bounds what squirrel reads from one hash command. +const maxHashOutput = 4 << 10 + +// ServerHash runs the configured hash command on the server over the file +// at name. The command line is built from the destination root and name +// alone, and only when both hold nothing but letters, digits, '.', '_', '-' +// and '/' and name ends in a lowercase hex artifact name — never from a +// mirror path, which is a user's file name. The command is probed once per +// session, by hashing a known input; a server without it gets +// errNoServerHash. +func (t *sftpTransport) ServerHash(_ context.Context, name string) (remoteChecksum, error) { + if err := t.checkName(name); err != nil { + return remoteChecksum{}, err + } + if err := requireKind(name, kindFile, t.lstat); err != nil { + return remoteChecksum{}, err + } + target, err := t.hashTarget(name) + if err != nil { + return remoteChecksum{}, err + } + if err := t.probeServerHash(); err != nil { + return remoteChecksum{}, err + } + out, err := t.runCommand(serverHashCommands[t.hashAlgo]+" "+target, nil) + if err != nil { + return remoteChecksum{}, err + } + sum, err := parseHashOutput(out, newArtifactHash(t.hashAlgo).Size()) + if err != nil { + return remoteChecksum{}, fmt.Errorf("hash %s on the server: %w", name, err) + } + return remoteChecksum{Algo: t.hashAlgo, Value: sum}, nil +} + +// hashTarget is the command-line argument naming name on the server, or +// errNoServerHash when the command line may not carry it. +func (t *sftpTransport) hashTarget(name string) (string, error) { + if _, ok := serverHashCommands[t.hashAlgo]; !ok { + return "", fmt.Errorf("%w: no hash_algo names a command squirrel runs", errNoServerHash) + } + full := path.Join(t.root, name) + if !commandSafe.MatchString(full) || !isStagingKey(path.Base(name)) { + return "", fmt.Errorf("%w: %s holds characters squirrel never puts on a server command line", errNoServerHash, full) + } + if !strings.HasPrefix(full, "/") { + full = "./" + full + } + return full, nil +} + +// probeServerHash asks the server to hash a known input, and remembers +// whether its command agreed with this machine once the server has +// answered: a session that could not even start the command is asked +// again next time. +func (t *sftpTransport) probeServerHash() error { + t.probeMu.Lock() + defer t.probeMu.Unlock() + if !t.probed { + t.probed, t.probeErr = t.runProbe() + } + return t.probeErr +} + +func (t *sftpTransport) runProbe() (bool, error) { + h := newArtifactHash(t.hashAlgo) + h.Write([]byte(serverHashProbe)) + command := serverHashCommands[t.hashAlgo] + out, err := t.runCommand(command, strings.NewReader(serverHashProbe)) + if err != nil { + _, answered := errors.AsType[*ssh.ExitError](err) + return answered, fmt.Errorf("%w: %w", errNoServerHash, err) + } + sum, err := parseHashOutput(out, h.Size()) + if err != nil || sum != hex.EncodeToString(h.Sum(nil)) { + return true, fmt.Errorf("%w: %s on the server does not compute %s", errNoServerHash, command, t.hashAlgo) + } + return true, nil +} + +// runCommand runs cmd in a session of its own and returns what it printed. +func (t *sftpTransport) runCommand(cmd string, stdin io.Reader) (string, error) { + s, err := t.conn.NewSession() + if err != nil { + return "", fmt.Errorf("open a session for %s: %w", cmd, err) + } + defer func() { _ = s.Close() }() + var out bytes.Buffer + s.Stdin = stdin + s.Stdout = &limitedWriter{w: &out, n: maxHashOutput} + if err := s.Run(cmd); err != nil { + return "", fmt.Errorf("run %s on the server: %w", cmd, err) + } + return out.String(), nil +} + +// parseHashOutput reads the digest a sum command printed first: size bytes +// of lowercase hex. +func parseHashOutput(out string, size int) (string, error) { + fields := strings.Fields(out) + if len(fields) == 0 { + return "", errors.New("the command printed nothing") + } + sum := strings.ToLower(fields[0]) + if b, err := hex.DecodeString(sum); err != nil || len(b) != size { + return "", fmt.Errorf("the command printed %q, not a digest", fields[0]) + } + return sum, nil +} + +// limitedWriter keeps the first n bytes written to it and drops the rest. +type limitedWriter struct { + w io.Writer + n int +} + +func (l *limitedWriter) Write(p []byte) (int, error) { + keep := min(len(p), l.n) + if keep > 0 { + if _, err := l.w.Write(p[:keep]); err != nil { + return 0, err + } + l.n -= keep + } + return len(p), nil +} diff --git a/sync/transport_sftp_hash_test.go b/sync/transport_sftp_hash_test.go new file mode 100644 index 0000000..d1cf332 --- /dev/null +++ b/sync/transport_sftp_hash_test.go @@ -0,0 +1,110 @@ +package sync + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// hashFixture serves root from a test server that runs commands, and +// plants one artifact, objects/, holding "alpha". +func hashFixture(t *testing.T, commands map[string]string) (*sftpTransport, string) { + t.Helper() + srv := startSFTPServer(t) + srv.runsHashCommands(commands) + root := t.TempDir() + key := strings.Repeat("ab", 32) + if err := os.MkdirAll(filepath.Join(root, ObjectsDirName), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, ObjectsDirName, key), []byte("alpha"), 0o644); err != nil { + t.Fatal(err) + } + dest := srv.destination(t, root) + dest.HashAlgo = "sha256" + tr := mustDialSFTP(t, dest) + t.Cleanup(func() { _ = tr.Close() }) + return tr, ObjectsDirName + "/" + key +} + +// TestServerHashRunsTheCommand: a server with the command hashes an +// artifact where it lies, and the value is what this machine computes. +func TestServerHashRunsTheCommand(t *testing.T) { + tr, name := hashFixture(t, map[string]string{"sha256sum": "sha256"}) + got, err := tr.ServerHash(context.Background(), name) + if err != nil { + t.Fatalf("ServerHash: %v", err) + } + want := sha256.Sum256([]byte("alpha")) + if got.Algo != "sha256" || got.Value != hex.EncodeToString(want[:]) { + t.Fatalf("ServerHash = %+v, want sha256 %x", got, want) + } +} + +// TestServerHashRefusesWhatItCannotTrust: a server that runs no programs, +// or whose command computes another hash, offers no server hash; neither +// does a name that is no hex artifact name, a root the command line may not +// carry, or a local disk. +func TestServerHashRefusesWhatItCannotTrust(t *testing.T) { + ctx := context.Background() + for _, c := range []struct { + name string + commands map[string]string + }{ + {"no programs", nil}, + {"a command computing another hash", map[string]string{"sha256sum": "blake3"}}, + } { + t.Run(c.name, func(t *testing.T) { + tr, name := hashFixture(t, c.commands) + if _, err := tr.ServerHash(ctx, name); !errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash = %v, want errNoServerHash", err) + } + }) + } + tr, _ := hashFixture(t, map[string]string{"sha256sum": "sha256"}) + if err := os.WriteFile(filepath.Join(tr.root, "cat; rm -rf x.jpg"), []byte("meow"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := tr.ServerHash(ctx, "cat; rm -rf x.jpg"); !errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash of a user's file name = %v, want errNoServerHash", err) + } + tr.root += "/with space" + unsafe := filepath.Join(tr.root, ObjectsDirName) + if err := os.MkdirAll(unsafe, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(unsafe, strings.Repeat("ab", 32)), []byte("alpha"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := tr.ServerHash(ctx, ObjectsDirName+"/"+strings.Repeat("ab", 32)); !errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash under an unsafe root = %v, want errNoServerHash", err) + } + local, err := openLocalTransport(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = local.Close() }() + if _, err := local.ServerHash(ctx, "objects/x"); !errors.Is(err, errNoServerHash) { + t.Fatalf("local ServerHash = %v, want errNoServerHash", err) + } +} + +// TestServerHashProbesOnce: the probe runs once per session, so a server +// that stops running the command afterwards fails the hash itself. +func TestServerHashProbesOnce(t *testing.T) { + srvCommands := map[string]string{"sha256sum": "sha256"} + tr, name := hashFixture(t, srvCommands) + ctx := context.Background() + if _, err := tr.ServerHash(ctx, name); err != nil { + t.Fatalf("first ServerHash: %v", err) + } + tr.hashAlgo = "sha1" + if _, err := tr.ServerHash(ctx, name); err == nil || errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash after the probe = %v, want the command's own failure", err) + } +} diff --git a/sync/transport_sftp_hostkey.go b/sync/transport_sftp_hostkey.go new file mode 100644 index 0000000..ac0e487 --- /dev/null +++ b/sync/transport_sftp_hostkey.go @@ -0,0 +1,120 @@ +package sync + +import ( + "crypto/ed25519" + "crypto/rand" + "errors" + "fmt" + "io/fs" + "net" + "os" + "path/filepath" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" + + "github.com/mbertschler/squirrel/config" +) + +// errUnknownHostKey refuses an sftp server whose host key known_hosts does +// not pin. +var errUnknownHostKey = errors.New("the sftp server's host key is not in known_hosts") + +// errHostKeyChanged refuses an sftp server whose host key differs from +// the one known_hosts pins for it. +var errHostKeyChanged = errors.New("the sftp server's host key differs from the one known_hosts pins") + +// knownHostsFile is where dest's pinned host keys live: known_hosts_file, +// else ~/.ssh/known_hosts. +func knownHostsFile(dest *config.Destination) (string, error) { + if f := dest.Params["known_hosts_file"]; f != "" { + return expandHome(f), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("find ~/.ssh/known_hosts (set known_hosts_file instead): %w", err) + } + return filepath.Join(home, ".ssh", "known_hosts"), nil +} + +// hostKeys is the host key check for one destination: the keys its +// known_hosts file pins. +type hostKeys struct { + file string + // known is knownhosts' own check, which reports an unknown host as a + // KeyError listing no key. + known ssh.HostKeyCallback +} + +// loadHostKeys reads dest's known_hosts. A missing file pins nothing, so +// every host is unknown. +func loadHostKeys(dest *config.Destination) (hostKeys, error) { + file, err := knownHostsFile(dest) + if err != nil { + return hostKeys{}, err + } + known, err := knownhosts.New(file) + if errors.Is(err, fs.ErrNotExist) { + known = func(string, net.Addr, ssh.PublicKey) error { return &knownhosts.KeyError{} } + } else if err != nil { + return hostKeys{}, fmt.Errorf("read known_hosts %s: %w", file, err) + } + return hostKeys{file: file, known: known}, nil +} + +// check accepts only a host key known_hosts pins for the server. An +// unknown host is refused with its fingerprint and the line that would +// trust it. +func (h hostKeys) check(host string, remote net.Addr, key ssh.PublicKey) error { + err := h.known(host, remote, key) + ke, ok := errors.AsType[*knownhosts.KeyError](err) + switch { + case !ok: + return err + case len(ke.Want) == 0: + return fmt.Errorf("%w: %s presented %s key %s, and squirrel refuses hosts it does not know — if that is the server's fingerprint, trust it by adding this line to %s:\n%s", + errUnknownHostKey, host, key.Type(), ssh.FingerprintSHA256(key), h.file, knownhosts.Line([]string{knownhosts.Normalize(host)}, key)) + default: + return fmt.Errorf("%w: %s presented %s key %s, but %s pins another key for it — the server was reinstalled, or something is intercepting the connection; confirm the new key with the server's operator before replacing the entry", + errHostKeyChanged, host, key.Type(), ssh.FingerprintSHA256(key), h.file) + } +} + +// algorithms lists the host key algorithms of the keys known_hosts pins +// for host, so the handshake asks the server for a key squirrel can check. +// It returns nil, the client's defaults, when known_hosts pins nothing for +// host. +func (h hostKeys) algorithms(host string, remote net.Addr) []string { + probe, err := probeKey() + if err != nil { + return nil + } + ke, ok := errors.AsType[*knownhosts.KeyError](h.known(host, remote, probe)) + if !ok { + return nil + } + var algos []string + for _, k := range ke.Want { + algos = append(algos, algorithmsFor(k.Key.Type())...) + } + return algos +} + +// probeKey is a fresh key no known_hosts file holds: checking it against +// a host yields the keys known_hosts pins for that host. +func probeKey() (ssh.PublicKey, error) { + pub, _, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, err + } + return ssh.NewPublicKey(pub) +} + +// algorithmsFor names the signature algorithms a host key of keyType +// signs with. +func algorithmsFor(keyType string) []string { + if keyType == ssh.KeyAlgoRSA { + return []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA} + } + return []string{keyType} +} diff --git a/sync/transport_sftp_test.go b/sync/transport_sftp_test.go new file mode 100644 index 0000000..191b127 --- /dev/null +++ b/sync/transport_sftp_test.go @@ -0,0 +1,489 @@ +package sync + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/rsa" + "encoding/pem" + "errors" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" + "golang.org/x/crypto/ssh/knownhosts" + + "github.com/mbertschler/squirrel/config" +) + +// sftpTestServer is an in-process ssh server whose sftp subsystem serves +// the real filesystem, with password "p" for user "u" and one client key +// allowed. +type sftpTestServer struct { + addr string + hostKeys []ssh.Signer + // clientKey is the private half of the one client key the server + // accepts. + clientKey ed25519.PrivateKey + // hung, once closed, makes the sftp subsystem stop reading requests, + // as a server whose disk hangs does. + hung chan struct{} + + mu sync.Mutex + // commands maps each hash command the server runs to the hash it + // actually computes; a server with none runs no programs. + commands map[string]string +} + +// runsHashCommands lets the server run the given sum commands, each +// computing the hash its value names. +func (s *sftpTestServer) runsHashCommands(commands map[string]string) { + s.mu.Lock() + defer s.mu.Unlock() + s.commands = commands +} + +func (s *sftpTestServer) hashCommand(name string) (string, bool) { + s.mu.Lock() + defer s.mu.Unlock() + algo, ok := s.commands[name] + return algo, ok +} + +func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + s, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatal(err) + } + return priv, s +} + +func newSigner(t *testing.T) ssh.Signer { + t.Helper() + _, s := newKey(t) + return s +} + +// startSFTPServer serves until the test ends. With no host keys given it +// presents one fresh ed25519 key. +func startSFTPServer(t *testing.T, hostKeys ...ssh.Signer) *sftpTestServer { + t.Helper() + if len(hostKeys) == 0 { + hostKeys = []ssh.Signer{newSigner(t)} + } + clientKey, clientSigner := newKey(t) + srv := &sftpTestServer{hostKeys: hostKeys, clientKey: clientKey, hung: make(chan struct{})} + cfg := &ssh.ServerConfig{ + PasswordCallback: func(c ssh.ConnMetadata, pw []byte) (*ssh.Permissions, error) { + if c.User() == "u" && string(pw) == "p" { + return nil, nil + } + return nil, errors.New("wrong password") + }, + PublicKeyCallback: func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + if string(key.Marshal()) == string(clientSigner.PublicKey().Marshal()) { + return nil, nil + } + return nil, errors.New("unknown key") + }, + } + for _, k := range hostKeys { + cfg.AddHostKey(k) + } + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close() }) + srv.addr = l.Addr().String() + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + go serveSSH(c, cfg, srv) + } + }() + return srv +} + +func serveSSH(c net.Conn, cfg *ssh.ServerConfig, srv *sftpTestServer) { + defer func() { _ = c.Close() }() + _, chans, reqs, err := ssh.NewServerConn(c, cfg) + if err != nil { + return + } + go ssh.DiscardRequests(reqs) + for nc := range chans { + if nc.ChannelType() != "session" { + _ = nc.Reject(ssh.UnknownChannelType, "session only") + continue + } + ch, chReqs, err := nc.Accept() + if err != nil { + return + } + go func() { + for r := range chReqs { + switch { + case r.Type == "subsystem" && len(r.Payload) > 4 && string(r.Payload[4:]) == "sftp": + _ = r.Reply(true, nil) + go serveSFTP(ch, srv.hung) + case r.Type == "exec" && len(r.Payload) > 4: + _ = r.Reply(true, nil) + go srv.serveExec(ch, string(r.Payload[4:])) + default: + _ = r.Reply(false, nil) + } + } + }() + } +} + +// serveExec runs a sum command the way coreutils does — over the named +// file, or over stdin when none is named — and exits 127 for a command the +// server does not have. +func (s *sftpTestServer) serveExec(ch ssh.Channel, cmd string) { + defer func() { _ = ch.Close() }() + status := uint32(0) + defer func() { _, _ = ch.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{status})) }() + fields := strings.Fields(cmd) + algo, ok := s.hashCommand(fields[0]) + if !ok || len(fields) > 2 { + status = 127 + return + } + var in io.Reader = ch + name := "-" + if len(fields) == 2 { + f, err := os.Open(fields[1]) + if err != nil { + status = 1 + return + } + defer f.Close() + in, name = f, fields[1] + } + h := newArtifactHash(algo) + if _, err := io.Copy(h, in); err != nil { + status = 1 + return + } + _, _ = fmt.Fprintf(ch, "%x %s\n", h.Sum(nil), name) +} + +func serveSFTP(ch ssh.Channel, hung chan struct{}) { + defer func() { _ = ch.Close() }() + s, err := sftp.NewServer(hangingChannel{Channel: ch, hung: hung}) + if err != nil { + return + } + _ = s.Serve() +} + +// hangingChannel stops delivering requests, even the end of the session, +// once hung is closed. +type hangingChannel struct { + ssh.Channel + hung chan struct{} +} + +func (h hangingChannel) Read(p []byte) (int, error) { + n, err := h.Channel.Read(p) + select { + case <-h.hung: + select {} + default: + return n, err + } +} + +// knownHosts writes a known_hosts file pinning keys for the server. +func (s *sftpTestServer) knownHosts(t *testing.T, keys ...ssh.PublicKey) string { + t.Helper() + var lines []string + for _, k := range keys { + lines = append(lines, knownhosts.Line([]string{knownhosts.Normalize(s.addr)}, k)) + } + p := filepath.Join(t.TempDir(), "known_hosts") + if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +// destination is an sftp destination onto root on the server, logging in +// with password "p" and pinning the server's first host key. +func (s *sftpTestServer) destination(t *testing.T, root string) *config.Destination { + t.Helper() + host, port, _ := net.SplitHostPort(s.addr) + return &config.Destination{Name: "box", Type: "sftp", Root: root, Layout: config.LayoutMirror, Params: map[string]string{ + "host": host, "port": port, "user": "u", "password": "p", + "known_hosts_file": s.knownHosts(t, s.hostKeys[0].PublicKey()), + }} +} + +func mustDialSFTP(t *testing.T, dest *config.Destination) *sftpTransport { + t.Helper() + tr, err := dialSFTP(context.Background(), dest) + if err != nil { + t.Fatalf("dialSFTP: %v", err) + } + return tr +} + +func plantSymlink(t *testing.T, dir string) func(target, name string) { + return func(target, name string) { + p := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, p); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + } +} + +func TestSFTPTransportContract(t *testing.T) { + srv := startSFTPServer(t) + runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { + dir := t.TempDir() + return mustDialSFTP(t, srv.destination(t, dir)), plantSymlink(t, dir) + }) +} + +// TestSFTPServersRenameOverAnExistingName pins why the transport checks a +// rename's target itself: the raw protocol rename of both test servers — +// pkg/sftp's own, and rclone serve sftp, the testbed's — replaces an +// existing name. +func TestSFTPServersRenameOverAnExistingName(t *testing.T) { + servers := map[string]func(t *testing.T) *sftpTransport{ + "pkg-sftp": func(t *testing.T) *sftpTransport { + return mustDialSFTP(t, startSFTPServer(t).destination(t, t.TempDir())) + }, + "rclone-serve": rcloneServeTransport, + } + for name, open := range servers { + t.Run(name, func(t *testing.T) { + tr := open(t) + t.Cleanup(func() { _ = tr.Close() }) + mustPut(t, tr, "x", "from") + mustPut(t, tr, "y", "to") + if err := tr.client.Rename(tr.full("x"), tr.full("y")); err != nil { + t.Skipf("this server refuses the replacing rename itself: %v", err) + } + if got := mustRead(t, tr, "y"); got != "from" { + t.Fatalf("y after the raw rename = %q, want from", got) + } + }) + } +} + +// TestSFTPHungServerReleasesTheTransport: a server that stops answering +// neither wedges Close nor a dial past its deadline, so a push that gave +// up on a stalled call can always end. +func TestSFTPHungServerReleasesTheTransport(t *testing.T) { + srv := startSFTPServer(t) + tr := mustDialSFTP(t, srv.destination(t, t.TempDir())) + close(srv.hung) + closed := make(chan error, 1) + go func() { closed <- tr.Close() }() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatal("Close blocked on a hung server") + } + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + if _, err := dialSFTP(ctx, srv.destination(t, t.TempDir())); err == nil { + t.Fatal("dial of a server whose sftp subsystem never answers succeeded") + } +} + +func TestSFTPRefusesUnknownHostKey(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + dest.Params["known_hosts_file"] = srv.knownHosts(t) + _, err := dialSFTP(context.Background(), dest) + if !errors.Is(err, errUnknownHostKey) { + t.Fatalf("dial with an empty known_hosts = %v, want errUnknownHostKey", err) + } + want := knownhosts.Line([]string{knownhosts.Normalize(srv.addr)}, srv.hostKeys[0].PublicKey()) + for _, s := range []string{ssh.FingerprintSHA256(srv.hostKeys[0].PublicKey()), want} { + if !strings.Contains(err.Error(), s) { + t.Fatalf("refusal lacks %q:\n%v", s, err) + } + } + + dest.Params["known_hosts_file"] = filepath.Join(t.TempDir(), "absent") + if _, err := dialSFTP(context.Background(), dest); !errors.Is(err, errUnknownHostKey) { + t.Fatalf("dial with no known_hosts file = %v, want errUnknownHostKey", err) + } +} + +func TestSFTPRefusesChangedHostKey(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + dest.Params["known_hosts_file"] = srv.knownHosts(t, newSigner(t).PublicKey()) + if _, err := dialSFTP(context.Background(), dest); !errors.Is(err, errHostKeyChanged) { + t.Fatalf("dial with another pinned key = %v, want errHostKeyChanged", err) + } +} + +// TestSFTPNegotiatesThePinnedHostKeyType: a server offering an ed25519 and +// an RSA key, pinned only by its RSA key, is still accepted — the +// handshake asks for the key type known_hosts holds. +func TestSFTPNegotiatesThePinnedHostKeyType(t *testing.T) { + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + rsaSigner, err := ssh.NewSignerFromKey(rsaKey) + if err != nil { + t.Fatal(err) + } + srv := startSFTPServer(t, newSigner(t), rsaSigner) + dest := srv.destination(t, t.TempDir()) + dest.Params["known_hosts_file"] = srv.knownHosts(t, rsaSigner.PublicKey()) + tr := mustDialSFTP(t, dest) + _ = tr.Close() +} + +func TestSFTPAuthenticatesByKeyFile(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + delete(dest.Params, "password") + block, err := ssh.MarshalPrivateKey(srv.clientKey, "") + if err != nil { + t.Fatal(err) + } + keyFile := filepath.Join(t.TempDir(), "id") + if err := os.WriteFile(keyFile, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + dest.Params["key_file"] = keyFile + tr := mustDialSFTP(t, dest) + _ = tr.Close() +} + +func TestSFTPAuthenticatesThroughAgent(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + delete(dest.Params, "password") + keyring := agent.NewKeyring() + if err := keyring.Add(agent.AddedKey{PrivateKey: srv.clientKey}); err != nil { + t.Fatal(err) + } + sock := filepath.Join(shortTempDir(t), "agent.sock") + l, err := net.Listen("unix", sock) + if err != nil { + t.Skipf("unix sockets unavailable: %v", err) + } + t.Cleanup(func() { _ = l.Close() }) + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + go func() { _ = agent.ServeAgent(keyring, c); _ = c.Close() }() + } + }() + t.Setenv("SSH_AUTH_SOCK", sock) + tr := mustDialSFTP(t, dest) + _ = tr.Close() + + t.Setenv("SSH_AUTH_SOCK", "") + if _, err := dialSFTP(context.Background(), dest); err == nil || !strings.Contains(err.Error(), "SSH_AUTH_SOCK") { + t.Fatalf("dial with no credentials and no agent = %v, want a refusal naming SSH_AUTH_SOCK", err) + } +} + +// shortTempDir is a temporary directory with a path short enough for a +// unix socket. +func shortTempDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "sq") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + return dir +} + +// TestSFTPTransportContractAgainstRcloneServe runs the contract against +// the testbed's server, `rclone serve sftp`. That server hides symlinks, +// so the symlink cases skip there. +func TestSFTPTransportContractAgainstRcloneServe(t *testing.T) { + runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { + return rcloneServeTransport(t), func(string, string) { t.Skip("rclone serve sftp hides symlinks") } + }) +} + +// rcloneServeTransport serves a fresh directory with `rclone serve sftp` +// and dials it; the test skips without rclone on PATH. +func rcloneServeTransport(t *testing.T) *sftpTransport { + t.Helper() + rclone, err := exec.LookPath("rclone") + if err != nil { + t.Skip("rclone not on PATH") + } + hostPriv, hostKey := newKey(t) + keyFile := filepath.Join(t.TempDir(), "host_key") + block, err := ssh.MarshalPrivateKey(hostPriv, "") + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(keyFile, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + srv := startRcloneServe(t, rclone, t.TempDir(), keyFile, hostKey) + return mustDialSFTP(t, srv.destination(t, "/")) +} + +// startRcloneServe serves dir with `rclone serve sftp` on a free loopback +// port until the test ends. +func startRcloneServe(t *testing.T, rclone, dir, keyFile string, hostKey ssh.Signer) *sftpTestServer { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() + cmd := exec.Command(rclone, "serve", "sftp", dir, "--addr", addr, "--user", "u", "--pass", "p", + "--key", keyFile, "--config", filepath.Join(t.TempDir(), "rclone.conf")) + if err := cmd.Start(); err != nil { + t.Fatalf("start rclone serve sftp: %v", err) + } + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }) + for i := 0; ; i++ { + c, err := net.DialTimeout("tcp", addr, time.Second) + if err == nil { + _ = c.Close() + break + } + if i == 100 { + t.Fatalf("rclone serve sftp never listened on %s: %v", addr, err) + } + time.Sleep(50 * time.Millisecond) + } + return &sftpTestServer{addr: addr, hostKeys: []ssh.Signer{hostKey}} +} diff --git a/sync/transport_stall.go b/sync/transport_stall.go new file mode 100644 index 0000000..7fcc0c8 --- /dev/null +++ b/sync/transport_stall.go @@ -0,0 +1,224 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "sync" + "sync/atomic" + "time" +) + +// errTransportStalled marks a transport call that made no progress for +// its allowance: a hung disk, or a server that stopped answering. +var errTransportStalled = errors.New("transport call made no progress") + +// stalledCalls counts, per destination name, the transport calls a push +// gave up on that have not returned yet. A local call blocked in the +// kernel cannot be interrupted, so it may still complete a move after its +// push failed; a later push to the same destination refuses while any +// remain, so it never reconciles against a move still in flight. +var stalledCalls sync.Map // destination name → *atomic.Int64 + +func stalledCounter(destination string) *atomic.Int64 { + c, _ := stalledCalls.LoadOrStore(destination, new(atomic.Int64)) + return c.(*atomic.Int64) +} + +// stallBytesPerSecond is the slowest flush rate the allowance for a +// Put's final sync assumes, after its body has been read. +const stallBytesPerSecond = 1 << 20 + +// stallTransport bounds every call of the transport it wraps by progress +// rather than wall-clock: a call that makes none for timeout fails with +// errTransportStalled. A Put makes progress with every chunk it reads; a +// Flush is also allowed the time the bytes put since the last one take at +// stallBytesPerSecond, counted in unflushed where the push keeps a count. +type stallTransport struct { + transport + timeout time.Duration + stalled *atomic.Int64 + unflushed *atomic.Int64 +} + +// bounded runs call on its own goroutine and returns its result, or +// errTransportStalled once call went timeout without calling progress. A +// call given up on keeps its result to itself when it finally returns. +// progress resets the allowance to the duration it is given. +func bounded[T any](ctx context.Context, s stallTransport, what string, call func(ctx context.Context, progress func(time.Duration)) (T, error)) (T, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + allowance := make(chan time.Duration, 1) + progress := func(d time.Duration) { + select { + case <-allowance: + default: + } + allowance <- d + } + type result struct { + v T + err error + } + done := make(chan result, 1) + go func() { + v, err := call(ctx, progress) + done <- result{v, err} + }() + timer := time.NewTimer(s.timeout) + defer timer.Stop() + for { + select { + case r := <-done: + return r.v, r.err + case d := <-allowance: + timer.Reset(d) + case <-timer.C: + s.stalled.Add(1) + go func() { <-done; s.stalled.Add(-1) }() + var zero T + return zero, fmt.Errorf("%w: %s, none for %s", errTransportStalled, what, s.timeout) + } + } +} + +func (s stallTransport) Stat(ctx context.Context, name string) (entry, error) { + return bounded(ctx, s, "stat "+name, func(ctx context.Context, _ func(time.Duration)) (entry, error) { + return s.transport.Stat(ctx, name) + }) +} + +func (s stallTransport) List(ctx context.Context, dir string) ([]entry, error) { + return bounded(ctx, s, "list "+dir, func(ctx context.Context, _ func(time.Duration)) ([]entry, error) { + return s.transport.List(ctx, dir) + }) +} + +// Get bounds the open, and every Read of the file it returns, by the same +// allowance. +func (s stallTransport) Get(ctx context.Context, name string) (io.ReadCloser, error) { + rc, err := bounded(ctx, s, "get "+name, func(ctx context.Context, _ func(time.Duration)) (io.ReadCloser, error) { + return s.transport.Get(ctx, name) + }) + if err != nil { + return nil, err + } + return &stallReader{ctx: ctx, s: s, name: name, rc: rc}, nil +} + +func (s stallTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + body := &progressingReader{timeout: s.timeout} + _, err := bounded(ctx, s, "put "+name, func(ctx context.Context, progress func(time.Duration)) (struct{}, error) { + body.r, body.progress = r, progress + return struct{}{}, s.transport.Put(ctx, name, body, mtime) + }) + if s.unflushed != nil { + s.unflushed.Add(body.read()) + } + return err +} + +func (s stallTransport) Flush(ctx context.Context, dirs ...string) error { + var pending int64 + if s.unflushed != nil { + pending = s.unflushed.Load() + } + _, err := bounded(ctx, s, "flush", func(ctx context.Context, progress func(time.Duration)) (struct{}, error) { + progress(s.timeout + time.Duration(pending/stallBytesPerSecond)*time.Second) + return struct{}{}, s.transport.Flush(ctx, dirs...) + }) + if err == nil && s.unflushed != nil { + s.unflushed.Add(-pending) + } + return err +} + +func (s stallTransport) Rename(ctx context.Context, from, to string) error { + _, err := bounded(ctx, s, "rename "+from, func(ctx context.Context, _ func(time.Duration)) (struct{}, error) { + return struct{}{}, s.transport.Rename(ctx, from, to) + }) + return err +} + +func (s stallTransport) Remove(ctx context.Context, name string) error { + _, err := bounded(ctx, s, "remove "+name, func(ctx context.Context, _ func(time.Duration)) (struct{}, error) { + return struct{}{}, s.transport.Remove(ctx, name) + }) + return err +} + +// ServerHash allows the server the time its bytes take to read at the +// slowest rate squirrel expects, beyond the usual allowance. +func (s stallTransport) ServerHash(ctx context.Context, name string) (remoteChecksum, error) { + e, err := s.Stat(ctx, name) + if err != nil { + return remoteChecksum{}, err + } + return bounded(ctx, s, "hash "+name, func(ctx context.Context, progress func(time.Duration)) (remoteChecksum, error) { + progress(s.timeout + time.Duration(e.size/stallBytesPerSecond)*time.Second) + return s.transport.ServerHash(ctx, name) + }) +} + +// stallReader bounds each Read of a file Get opened. A Read runs into the +// reader's own buffer, so one given up on can finish later without +// touching the caller's; after that the reader only reports the stall. +type stallReader struct { + ctx context.Context + s stallTransport + name string + rc io.ReadCloser + buf []byte + err error // the stall, once one happened +} + +func (r *stallReader) Read(p []byte) (int, error) { + if r.err != nil { + return 0, r.err + } + if cap(r.buf) < len(p) { + r.buf = make([]byte, len(p)) + } + buf := r.buf[:len(p)] + n, err := bounded(r.ctx, r.s, "read "+r.name, func(context.Context, func(time.Duration)) (int, error) { + return r.rc.Read(buf) + }) + if errors.Is(err, errTransportStalled) { + r.err = err + return 0, err + } + return copy(p, buf[:n]), err +} + +func (r *stallReader) Close() error { + if r.err != nil { + go func() { _ = r.rc.Close() }() + return nil + } + return r.rc.Close() +} + +// progressingReader reports each chunk it reads as progress, and at the +// end of the body allows the time to settle what it read. A Put given up +// on may still be reading, so the count is atomic. +type progressingReader struct { + r io.Reader + timeout time.Duration + progress func(time.Duration) + n atomic.Int64 +} + +func (p *progressingReader) Read(b []byte) (int, error) { + n, err := p.r.Read(b) + total := p.n.Add(int64(n)) + switch { + case errors.Is(err, io.EOF): + p.progress(p.timeout + time.Duration(total/stallBytesPerSecond)*time.Second) + case n > 0: + p.progress(p.timeout) + } + return n, err +} + +func (p *progressingReader) read() int64 { return p.n.Load() } diff --git a/sync/transport_stall_test.go b/sync/transport_stall_test.go new file mode 100644 index 0000000..7ee578e --- /dev/null +++ b/sync/transport_stall_test.go @@ -0,0 +1,63 @@ +package sync + +import ( + "context" + "errors" + "io" + "strings" + "sync/atomic" + "testing" + "time" +) + +// hangingReads is a transport whose files read their first bytes, then +// hang until release is closed. +type hangingReads struct { + transport + release chan struct{} +} + +func (h hangingReads) Get(context.Context, string) (io.ReadCloser, error) { + return io.NopCloser(io.MultiReader(strings.NewReader("first"), blockUntil(h.release))), nil +} + +type blockUntil chan struct{} + +func (b blockUntil) Read([]byte) (int, error) { + <-b + return 0, io.EOF +} + +// TestStallBoundsEveryRead: a file whose reads stop making progress fails +// with errTransportStalled once the allowance runs out, keeps failing, +// and counts as a call given up on until the read finally returns. +func TestStallBoundsEveryRead(t *testing.T) { + release := make(chan struct{}) + stalled := new(atomic.Int64) + s := stallTransport{transport: hangingReads{release: release}, timeout: 50 * time.Millisecond, stalled: stalled} + rc, err := s.Get(context.Background(), "f") + if err != nil { + t.Fatalf("Get: %v", err) + } + buf := make([]byte, 16) + if n, err := rc.Read(buf); err != nil || string(buf[:n]) != "first" { + t.Fatalf("first Read = %q, %v; want the bytes that were there", buf[:n], err) + } + if _, err := rc.Read(buf); !errors.Is(err, errTransportStalled) { + t.Fatalf("hanging Read = %v, want errTransportStalled", err) + } + if _, err := rc.Read(buf); !errors.Is(err, errTransportStalled) { + t.Fatalf("Read after a stall = %v, want the stall again", err) + } + if stalled.Load() != 1 { + t.Fatalf("calls given up on = %d, want 1", stalled.Load()) + } + _ = rc.Close() + close(release) + for deadline := time.Now().Add(5 * time.Second); stalled.Load() > 0 && time.Now().Before(deadline); { + time.Sleep(10 * time.Millisecond) + } + if stalled.Load() != 0 { + t.Fatal("the read that finally returned is still counted as outstanding") + } +} diff --git a/sync/vector_wiring_test.go b/sync/vector_wiring_test.go index 3c923a5..003f2c0 100644 --- a/sync/vector_wiring_test.go +++ b/sync/vector_wiring_test.go @@ -2,8 +2,6 @@ package sync import ( "context" - "os" - "path/filepath" "testing" "github.com/mbertschler/squirrel/store" @@ -28,55 +26,6 @@ func volumeComponents(t *testing.T, s *store.Store, volName, dest string) []stor return out } -// TestRunPairAdvancesVectorOnVerifiedPush: a checksum-verified successful -// mirror push advances the destination's durability vector for the -// volume's origins. -func TestRunPairAdvancesVectorOnVerifiedPush(t *testing.T) { - f := setupFixture(t) - if err := os.WriteFile(filepath.Join(f.vol.Path, "a.txt"), []byte("alpha"), 0o644); err != nil { - t.Fatal(err) - } - f.runIndex(t) - - p := Pair{Volume: f.vol, Destination: f.dest} - rep, err := RunPair(context.Background(), f.store, Tools{Rclone: f.rcl}, p, Options{}) - if err != nil { - t.Fatalf("RunPair: %v (rep=%+v)", err, rep) - } - if !rep.Verification.Verified() { - t.Fatalf("Verification = %+v, want verified", rep.Verification) - } - comps := volumeComponents(t, f.store, f.vol.Name, f.dest.Name) - if len(comps) != 1 { - t.Fatalf("components = %+v, want exactly one self component", comps) - } - if comps[0].OriginRunID < 1 { - t.Fatalf("origin_run_id = %d, want >= 1", comps[0].OriginRunID) - } -} - -// TestRunPairShallowPushLeavesVectorAlone: a shallow push is not -// content-verified, so the vector keeps its prior state. -func TestRunPairShallowPushLeavesVectorAlone(t *testing.T) { - f := setupFixture(t) - if err := os.WriteFile(filepath.Join(f.vol.Path, "a.txt"), []byte("alpha"), 0o644); err != nil { - t.Fatal(err) - } - f.runIndex(t) - - p := Pair{Volume: f.vol, Destination: f.dest} - rep, err := RunPair(context.Background(), f.store, Tools{Rclone: f.rcl}, p, Options{Shallow: true}) - if err != nil { - t.Fatalf("RunPair: %v (rep=%+v)", err, rep) - } - if rep.Verification.Verified() { - t.Fatalf("Verification = %+v, want unverified for shallow", rep.Verification) - } - if comps := volumeComponents(t, f.store, f.vol.Name, f.dest.Name); len(comps) != 0 { - t.Fatalf("components = %+v, want none after shallow push", comps) - } -} - // TestKopiaPushAdvancesVector: a kopia push whose snapshot verify // succeeds advances the vector exactly like a verified bucket push. func TestKopiaPushAdvancesVector(t *testing.T) { diff --git a/sync/verify_mirror.go b/sync/verify_mirror.go new file mode 100644 index 0000000..052d917 --- /dev/null +++ b/sync/verify_mirror.go @@ -0,0 +1,234 @@ +package sync + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "path" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// mirrorRereadShare is the share of a local mirror's stored bytes one +// verify pass re-reads, least recently verified first: a tenth, so every +// byte is read again within about ten passes. +const mirrorRereadShare = 10 + +// verifyMirror checks every copy a native mirror holds by squirrel's +// records, the live and the displaced ones: each gets one Lstat against its +// recorded size and mtime, and on a local disk a slice of them is re-read +// through BLAKE3. A copy that is gone or changed is marked lost, which +// latches the destination's alarm, demotes its volume's evidence to +// presence+size, and makes the next push write the path again if the index +// still holds that content there. +func verifyMirror(ctx context.Context, s *store.Store, dest *config.Destination, rep *RemoteVerifyReport) error { + rows, err := s.ListStoredRemotePaths(ctx, dest.Name) + if err != nil { + return fmt.Errorf("list recorded mirror copies for %q: %w", dest.Name, err) + } + rep.Paths = len(rows) + if len(rows) == 0 { + return nil + } + runID, err := s.BeginRemoteVerifyRun(ctx) + if err != nil { + return fmt.Errorf("record verify run: %w", err) + } + rep.RunID = runID + pass := &mirrorPass{s: s, dest: dest, rep: rep, lostIn: map[int64]bool{}} + verifyErr := pass.run(ctx, rows) + if err := pass.demoteLostVolumes(ctx); err != nil && verifyErr == nil { + verifyErr = err + } + if err := recordVerifyOutcome(ctx, s, rep, verifyErr); err != nil { + return err + } + if verifyErr == nil && rep.Clean() { + return upgradeFingerprintVectors(ctx, s, dest.Name) + } + return verifyErr +} + +// mirrorPass is one verify pass over a native mirror: where it reports, and +// the volumes it found a copy lost in. +type mirrorPass struct { + s *store.Store + dest *config.Destination + rep *RemoteVerifyReport + lostIn map[int64]bool +} + +// mirrorCopy is one recorded copy as a verify pass addresses it. +type mirrorCopy struct { + store.StoredRemotePath + name string // where the copy is, relative to the destination root +} + +// run checks every volume's marker before any of its copies, so a disk +// that is not mounted, or a share emptied from under its root, fails the +// pass instead of reading as every copy gone. +func (p *mirrorPass) run(ctx context.Context, rows []store.StoredRemotePath) error { + tr, err := openReadOnly(ctx, p.dest) + if err != nil { + return err + } + defer func() { _ = tr.Close() }() + if err := requireVolumeMarkers(ctx, tr, p.dest, storedVolumes(rows)); err != nil { + return err + } + var intact []mirrorCopy + for _, r := range rows { + c := mirrorCopy{StoredRemotePath: r, name: storedCopyName(r)} + ok, err := p.statCopy(ctx, tr, c) + if err != nil { + return err + } + if ok { + intact = append(intact, c) + } + } + if !readsBack(p.dest) { + return nil + } + return p.rereadCopies(ctx, tr, rereadSlice(intact)) +} + +func storedVolumes(rows []store.StoredRemotePath) []string { + var out []string + seen := map[string]bool{} + for _, r := range rows { + if !seen[r.Volume] { + seen[r.Volume] = true + out = append(out, r.Volume) + } + } + return out +} + +// requireVolumeMarkers fails unless each volume's directory on the root +// holds the .squirrel-volume marker naming it. +func requireVolumeMarkers(ctx context.Context, tr transport, dest *config.Destination, volumes []string) error { + for _, v := range volumes { + name := path.Join(v, volmark.MarkerName) + data, err := readSmallFile(ctx, tr, name, maxMarkerBytes) + if err != nil { + return fmt.Errorf("destination %q: read %s: %w — the disk may not be mounted, or the root is wrong; nothing was checked", dest.Name, name, err) + } + m, err := volmark.Parse(data) + if err == nil && m.Volume != v { + err = fmt.Errorf("it names volume %q", m.Volume) + } + if err != nil { + return fmt.Errorf("destination %q: %s: %w — nothing was checked", dest.Name, name, err) + } + } + return nil +} + +// storedCopyName is where a live copy sits, /, or a displaced +// one, /.squirrel-history/run-/. +func storedCopyName(r store.StoredRemotePath) string { + if r.State == store.RemotePathDisplaced { + return historyName(r.Volume, r.DisplacedRunID.Int64, r.Path) + } + return path.Join(r.Volume, r.Path) +} + +// statCopy checks one copy's size and mtime and reports whether it is +// intact. A copy that is gone or changed is recorded as a finding. +func (p *mirrorPass) statCopy(ctx context.Context, tr transport, c mirrorCopy) (bool, error) { + e, err := tr.Stat(ctx, c.name) + switch { + case errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir): + return false, p.loseCopy(ctx, c, &p.rep.PathsMissing) + case err != nil: + return false, fmt.Errorf("stat %s: %w", c.name, err) + case !matchesRecord(e, c.RemotePath): + return false, p.loseCopy(ctx, c, &p.rep.PathsChanged) + } + return true, nil +} + +// rereadSlice picks the copies one pass re-reads: least recently verified +// first, until they cover mirrorRereadShare of the bytes the destination +// holds, and always at least one. +func rereadSlice(copies []mirrorCopy) []mirrorCopy { + var total int64 + for _, c := range copies { + total += c.SizeBytes + } + var read int64 + for i, c := range copies { + if i > 0 && read*mirrorRereadShare >= total { + return copies[:i] + } + read += c.SizeBytes + } + return copies +} + +// rereadCopies hashes each copy as the disk returns it and compares it with +// the fingerprint its row records, or with its content's BLAKE3 while it +// records none: a match re-stamps the fingerprint, other bytes are a +// finding. A copy a push moved since the pass read its row is left to the +// next pass. +func (p *mirrorPass) rereadCopies(ctx context.Context, tr transport, copies []mirrorCopy) error { + for _, c := range copies { + sum, err := readBack(ctx, tr, c.name) + if errors.Is(err, fs.ErrNotExist) { + if err := p.loseCopy(ctx, c, &p.rep.PathsMissing); err != nil { + return err + } + continue + } + if err != nil { + return fmt.Errorf("re-read %s: %w", c.name, err) + } + want := hex.EncodeToString(c.Blake3) + if c.Checksum.Valid { + want = c.Checksum.String + } + if got := hex.EncodeToString(sum); got != want { + if err := p.loseCopy(ctx, c, &p.rep.PathsChanged); err != nil { + return err + } + continue + } + stamped, err := p.s.RecordRemotePathVerified(ctx, c.ID, want, store.NowNs()) + if err != nil { + return err + } + if stamped { + p.rep.PathsReread++ + } + } + return nil +} + +// loseCopy marks a copy lost and lists its name under the finding, unless a +// push moved its row since the pass read it. +func (p *mirrorPass) loseCopy(ctx context.Context, c mirrorCopy, finding *[]string) error { + moved, err := p.s.LoseStoredRemotePath(ctx, c.ID, c.State) + if err != nil || !moved { + return err + } + *finding = append(*finding, c.name) + p.lostIn[c.VolumeID] = true + return nil +} + +// demoteLostVolumes demotes the evidence of every volume the pass found a +// copy lost in, so the offload gate stops taking the destination's word +// for that volume as a whole until a push writes the copies again. +func (p *mirrorPass) demoteLostVolumes(ctx context.Context) error { + for volumeID := range p.lostIn { + if err := p.s.DemoteFingerprintVerifiedVector(ctx, volumeID, p.dest.Name); err != nil { + return err + } + } + return nil +} diff --git a/sync/verify_mirror_test.go b/sync/verify_mirror_test.go new file mode 100644 index 0000000..76665ac --- /dev/null +++ b/sync/verify_mirror_test.go @@ -0,0 +1,172 @@ +package sync + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +func (f *mirrorFixture) verify(t *testing.T) RemoteVerifyReport { + t.Helper() + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil { + t.Fatalf("VerifyRemote: %v", err) + } + return rep +} + +// TestVerifyMirrorChecksEveryStoredCopy: a pass checks the live and the +// displaced copies without rclone, re-reads a slice of them on a local +// disk, and stays clean while they hold what squirrel stored. +func TestVerifyMirrorChecksEveryStoredCopy(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "v1") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + f.mustPush(t) + + rep := f.verify(t) + if !rep.Clean() || rep.Paths != 3 || rep.PathsReread == 0 || rep.RunID == 0 { + t.Fatalf("rep = %+v, want a clean pass over 3 copies that re-read some", rep) + } + run, err := f.store.GetRun(context.Background(), rep.RunID) + if err != nil || run.Status != store.RunStatusSuccess || run.FileCount != 3 { + t.Fatalf("run = %+v, %v; want a successful audit over 3 copies", run, err) + } +} + +// TestVerifyMirrorRereadRotates: successive passes re-read the least +// recently verified copies first, so every copy is re-read in turn. +func TestVerifyMirrorRereadRotates(t *testing.T) { + f := setupMirrorFixture(t) + for _, name := range []string{"a", "b", "c", "d"} { + f.write(t, name, "same size") + } + f.index(t) + f.mustPush(t) + reread := map[int64]bool{} + for range 4 { + next, err := f.store.ListStoredRemotePaths(context.Background(), "usb") + if err != nil { + t.Fatal(err) + } + if rep := f.verify(t); rep.PathsReread != 1 { + t.Fatalf("pass re-read %d copies, want the one a tenth of the bytes needs", rep.PathsReread) + } + reread[next[0].ID] = true + } + if len(reread) != 4 { + t.Fatalf("four passes re-read %d distinct copies, want all four in turn", len(reread)) + } +} + +// TestVerifyMirrorFindingsMarkCopiesLost: a copy deleted, changed in size +// and mtime, or changed behind an unchanged size and mtime is a finding: +// its row becomes lost, the destination's alarm latches, and the next push +// writes each path again although the index did not change. +func TestVerifyMirrorFindingsMarkCopiesLost(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "gone.txt", "gone") + f.write(t, "grown.txt", "grown") + f.write(t, "flipped.txt", "flipped") + f.index(t) + f.mustPush(t) + + if err := os.Remove(f.dest("gone.txt")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("grown.txt"), []byte("grown, and longer"), 0o644); err != nil { + t.Fatal(err) + } + flipped := f.dest("flipped.txt") + fi, _ := os.Stat(flipped) + if err := os.WriteFile(flipped, []byte("FLIPPED"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(flipped, fi.ModTime(), fi.ModTime()); err != nil { + t.Fatal(err) + } + found := f.verify(t) + if found.Clean() || len(found.PathsMissing) != 1 || len(found.PathsChanged) != 2 || !found.AlarmRaised { + t.Fatalf("rep = %+v, want one copy missing, two changed, and the alarm raised", found) + } + if got := f.lostPaths(t); len(got) != 3 { + t.Fatalf("lost = %v, want all three copies", got) + } + if comps := volumeComponents(t, f.store, "pics", "usb"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { + t.Fatalf("vector after the findings = %+v, want it demoted to presence+size", comps) + } + + rep := f.mustPush(t) + if rep.RcloneResult.Transferred != 3 { + t.Fatalf("repair push transferred %d, want the three lost paths", rep.RcloneResult.Transferred) + } + if f.readDest(t, "gone.txt") != "gone" || f.readDest(t, "grown.txt") != "grown" || f.readDest(t, "flipped.txt") != "flipped" { + t.Fatal("the repair push did not restore the lost copies") + } + f.checkInvariants(t, nil) + if comps := volumeComponents(t, f.store, "pics", "usb"); comps[0].VerifyMethod != store.VerifyMethodFingerprint { + t.Fatalf("vector after the repair = %+v, want fingerprint-verified again", comps) + } + if rep := f.verify(t); !rep.Clean() { + t.Fatalf("pass after the repair = %+v, want clean", rep) + } +} + +func (f *mirrorFixture) lostPaths(t *testing.T) []string { + t.Helper() + var out []string + for _, r := range f.rows(t) { + if r.State == store.RemotePathLost { + out = append(out, r.Path) + } + } + return out +} + +// TestVerifyMirrorOverSFTPChecksWithoutReading: over sftp a pass checks +// size and mtime alone, and finds a copy that went missing. +func TestVerifyMirrorOverSFTPChecksWithoutReading(t *testing.T) { + f := setupMirrorFixtureOn(t, sftpBackend) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + if rep := f.verify(t); !rep.Clean() || rep.Paths != 2 || rep.PathsReread != 0 { + t.Fatalf("rep = %+v, want a clean size-and-mtime pass", rep) + } + if err := os.Remove(filepath.Join(f.dst, "pics", "a.txt")); err != nil { + t.Fatal(err) + } + rep := f.verify(t) + if len(rep.PathsMissing) != 1 || rep.PathsMissing[0] != "pics/a.txt" { + t.Fatalf("missing = %v, want pics/a.txt", rep.PathsMissing) + } +} + +// TestVerifyMirrorRefusesAnUnmountedRoot: a root emptied from under the +// mirror — a disk that is not mounted — fails the pass on the missing +// marker, and marks no copy lost. +func TestVerifyMirrorRefusesAnUnmountedRoot(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + if err := os.RemoveAll(filepath.Join(f.dst, "pics")); err != nil { + t.Fatal(err) + } + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err == nil || !strings.Contains(err.Error(), "nothing was checked") { + t.Fatalf("VerifyRemote = %+v, %v; want the pass refused", rep, err) + } + if lost := f.lostPaths(t); len(lost) != 0 || rep.AlarmRaised { + t.Fatalf("lost = %v, alarm raised = %t; want no record touched", lost, rep.AlarmRaised) + } +} diff --git a/sync/verify_native.go b/sync/verify_native.go new file mode 100644 index 0000000..7878bfa --- /dev/null +++ b/sync/verify_native.go @@ -0,0 +1,113 @@ +package sync + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "io/fs" + "path" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// transportChecksums reads a native destination's checksums through +// squirrel's own transport: a local disk's artifacts are read back through +// BLAKE3, and through any other hash their upload rows recorded; an sftp +// server's are hashed by its hash command, and fingerprint nothing on a +// server without one. +type transportChecksums struct { + tr transport + dest *config.Destination +} + +func (c transportChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (artifactChecksums, error) { + names := namerFor(c.dest) + want := make(map[string]string, len(rows)) + for _, r := range rows { + want[names.object(r.Blake3)] = r.ChecksumAlgo.String + } + return c.read(ctx, ObjectsDirName, want) +} + +func (c transportChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (artifactChecksums, error) { + names := namerFor(c.dest) + want := make(map[string]string, len(packs)) + for _, p := range packs { + want[names.pack(p.PackKey)] = p.ChecksumAlgo.String + } + return c.read(ctx, PacksDirName, want) +} + +// read lists dir and hashes each file a row recorded; want maps a +// basename to the algo its row recorded, "" while pending. A dir that does +// not exist holds nothing. +func (c transportChecksums) read(ctx context.Context, dir string, want map[string]string) (artifactChecksums, error) { + out := artifactChecksums{byName: map[string]map[string]string{}, unchecked: map[string]bool{}} + entries, err := c.tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return out, nil + } + if err != nil { + return artifactChecksums{}, err + } + for _, e := range entries { + if e.kind != kindFile { + continue + } + recorded, ok := want[e.name] + if !ok { + out.byName[e.name] = nil + continue + } + hashes, err := c.hash(ctx, path.Join(dir, e.name), recorded) + if err != nil { + return artifactChecksums{}, fmt.Errorf("hash %s: %w", e.name, err) + } + out.byName[e.name] = hashes + out.unchecked[e.name] = hashes == nil + } + return out, nil +} + +// hash is the checksums of the file at name: its BLAKE3, and the hash its +// row recorded when this machine computes that one too, read back from a +// local disk; the server's hash command's answer on sftp. It is nil when +// the sftp server cannot answer for the row: no command squirrel trusts, or +// a row recorded under another hash_algo. +func (c transportChecksums) hash(ctx context.Context, name, recorded string) (map[string]string, error) { + if !readsBack(c.dest) { + if recorded != "" && recorded != c.dest.HashAlgo { + return nil, nil + } + cs, err := c.tr.ServerHash(ctx, name) + if errors.Is(err, errNoServerHash) { + return nil, nil + } + if err != nil { + return nil, err + } + return map[string]string{cs.Algo: cs.Value}, nil + } + hashers := map[string]hash.Hash{store.ChecksumAlgoBlake3: blake3.New()} + if h := newArtifactHash(recorded); h != nil { + hashers[recorded] = h + } + writers := make([]io.Writer, 0, len(hashers)) + for _, h := range hashers { + writers = append(writers, h) + } + if err := copyOut(ctx, c.tr, name, io.MultiWriter(writers...)); err != nil { + return nil, err + } + out := make(map[string]string, len(hashers)) + for algo, h := range hashers { + out[algo] = hex.EncodeToString(h.Sum(nil)) + } + return out, nil +} diff --git a/sync/verify_remote.go b/sync/verify_remote.go index 6d47a93..fc21cc9 100644 --- a/sync/verify_remote.go +++ b/sync/verify_remote.go @@ -12,9 +12,9 @@ import ( ) // RemoteVerifyReport summarises one verification pass over a -// destination's recorded content-addressed objects. Every recorded -// object lands in exactly one of Verified, Populated, Pending, Missing, -// or Mismatched. +// destination's recorded content-addressed objects and packs, or a native +// mirror's recorded copies. Every recorded object lands in exactly one of +// Verified, Populated, Pending, Missing, or Mismatched. type RemoteVerifyReport struct { Destination string RunID int64 @@ -38,6 +38,11 @@ type RemoteVerifyReport struct { // remote listing. Missing []string Mismatched []RemoteObjectMismatch + // Unchecked counts recorded objects and packs that are present but + // that the destination could not hash this pass (an sftp server + // without the hash command, or one recorded under another hash_algo): + // neither re-confirmed nor a finding. + Unchecked int // Pack counters mirror the object ones for a packed destination's // per-pack sweep — one fingerprint check per pack vouches for every @@ -57,6 +62,19 @@ type RemoteVerifyReport struct { // the recorded one (Hash holds the pack key hex). PackMismatched []RemoteObjectMismatch + // Paths counts a native mirror's recorded copies, the live and the + // displaced ones; each is checked by size and mtime. Zero on the + // content layouts. + Paths int + // PathsReread counts the copies a re-read through BLAKE3 confirmed: + // on a local disk, the least recently verified share of them. + PathsReread int + // PathsMissing and PathsChanged name, relative to the destination root, + // the copies found gone and the ones found with another size, mtime or + // BLAKE3. Their records are marked lost. + PathsMissing []string + PathsChanged []string + // AlarmRaised is true when this pass latched a new standing alarm on // the destination because it was not clean (#157, F30). A pass on an // already-alarmed destination leaves it false (the latch was already @@ -80,11 +98,19 @@ type RemoteObjectMismatch struct { Actual string } -// Clean reports whether every recorded object and pack was accounted for -// without a mismatch. +// Clean reports whether every recorded object, pack and mirror copy was +// accounted for without a mismatch. func (r RemoteVerifyReport) Clean() bool { return len(r.Missing) == 0 && len(r.Mismatched) == 0 && - len(r.PacksMissing) == 0 && len(r.PackMismatched) == 0 + len(r.PacksMissing) == 0 && len(r.PackMismatched) == 0 && + len(r.PathsMissing) == 0 && len(r.PathsChanged) == 0 +} + +// failures counts the recorded artifacts this pass found missing or +// changed. +func (r RemoteVerifyReport) failures() int { + return len(r.Missing) + len(r.Mismatched) + len(r.PacksMissing) + len(r.PackMismatched) + + len(r.PathsMissing) + len(r.PathsChanged) } // VerifyRemote re-reads the provider checksums of every object recorded @@ -93,7 +119,12 @@ func (r RemoteVerifyReport) Clean() bool { // against the fingerprints recorded at upload time. Matches stamp // verified_at_ns; objects with a pending fingerprint get one recorded; // mismatches and missing objects land loudly on the report. The pass -// reads destination metadata and updates local verification state only. +// reads the destination and updates local verification state only. +// +// A native destination is read through squirrel's own transport instead, +// so rcl may be nil for one: a local disk's artifacts are read back through +// BLAKE3, an sftp server's hashed by its hash command, and a native +// mirror's copies are checked by verifyMirror. // // The pass is recorded as a kind='audit' run: success when every object // checked out, partial when objects mismatched or went missing, failed @@ -101,8 +132,11 @@ func (r RemoteVerifyReport) Clean() bool { // carries the destination name and counters. func VerifyRemote(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination) (RemoteVerifyReport, error) { rep := RemoteVerifyReport{Destination: dest.Name} + if dest.NativeMirror() { + return rep, verifyMirror(ctx, s, dest, &rep) + } if dest.Layout != config.LayoutContentAddressed && dest.Layout != config.LayoutPacked { - return rep, fmt.Errorf("destination %q has layout %q — verify covers the recorded objects and packs of content-addressed and packed destinations", dest.Name, dest.Layout) + return rep, fmt.Errorf("destination %q is an rclone mirror — verify covers the recorded objects and packs of content-addressed and packed destinations, and the recorded copies of a mirror squirrel writes itself", dest.Name) } rows, err := s.ListRemoteObjects(ctx, dest.Name) if err != nil { @@ -128,7 +162,7 @@ func VerifyRemote(ctx context.Context, s *store.Store, rcl *Rclone, dest *config } rep.RunID = runID - verifyErr := verifyRecorded(ctx, s, rcl, dest, rows, packs, &rep) + verifyErr := verifyThrough(ctx, s, rcl, dest, rows, packs, &rep) if err := recordVerifyOutcome(ctx, s, &rep, verifyErr); err != nil { return rep, err } @@ -170,28 +204,110 @@ func upgradeFingerprintVectors(ctx context.Context, s *store.Store, destination return nil } +// checksumSource reads the checksums a verify pass compares for a +// destination's recorded objects and packs. +type checksumSource interface { + objects(ctx context.Context, rows []store.RemoteObjectRecord) (artifactChecksums, error) + packs(ctx context.Context, packs []store.RemotePackRecord) (artifactChecksums, error) +} + +// artifactChecksums is what a pass read of a destination's artifacts: the +// checksums of each stored one, keyed by basename then hash name (none for +// one nobody recorded), and the recorded ones present but not hashed this +// pass, which count neither as verified nor as a finding. +type artifactChecksums struct { + byName map[string]map[string]string + unchecked map[string]bool +} + +// verifyThrough runs the sweeps against dest through squirrel's own +// transport on a native destination, once its volume markers show the +// root is the right one, and through rclone (and the S3 API) otherwise. +func verifyThrough(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, rows []store.RemoteObjectRecord, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { + if !dest.Native() { + return verifyRecorded(ctx, s, rcloneChecksums{rcl: rcl, dest: dest}, dest, rows, packs, rep) + } + volumes, err := syncedVolumes(ctx, s, dest.Name) + if err != nil { + return err + } + tr, err := openReadOnly(ctx, dest) + if err != nil { + return err + } + defer func() { _ = tr.Close() }() + if err := requireVolumeMarkers(ctx, tr, dest, volumes); err != nil { + return err + } + return verifyRecorded(ctx, s, transportChecksums{tr: tr, dest: dest}, dest, rows, packs, rep) +} + +// syncedVolumes names the volumes that have a successful sync to the +// destination: those whose marker its root must hold. +func syncedVolumes(ctx context.Context, s *store.Store, destination string) ([]string, error) { + all, err := s.ListVolumes(ctx) + if err != nil { + return nil, fmt.Errorf("list volumes: %w", err) + } + var out []string + for _, v := range all { + _, err := s.LatestSuccessfulSyncRun(ctx, v.ID, destination) + switch { + case err == nil: + out = append(out, v.Name) + case !store.IsNotFound(err): + return nil, fmt.Errorf("lookup last successful sync of %q to %q: %w", v.Name, destination, err) + } + } + return out, nil +} + // verifyRecorded sweeps a destination's recorded content objects (the // large-file per-object sweep, shared with content-addressed) and, for a // packed destination, its recorded packs — one fingerprint check per pack // vouching for all its members. Either sweep can be empty. -func verifyRecorded(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, rows []store.RemoteObjectRecord, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { +func verifyRecorded(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, rows []store.RemoteObjectRecord, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { if len(rows) > 0 { - if err := verifyRecordedObjects(ctx, s, rcl, dest, rows, rep); err != nil { + if err := verifyRecordedObjects(ctx, s, src, dest, rows, rep); err != nil { return err } } if len(packs) > 0 { - if err := verifyRecordedPacks(ctx, s, rcl, dest, packs, rep); err != nil { + if err := verifyRecordedPacks(ctx, s, src, dest, packs, rep); err != nil { return err } } return nil } +// countUnchecked counts an artifact the destination could not hash this +// pass: as unchecked when its row records a fingerprint, as still pending +// when it records none. +func countUnchecked(rep *RemoteVerifyReport, fingerprinted bool, pending *int) { + if fingerprinted { + rep.Unchecked++ + return + } + *pending++ +} + +// contentMismatch is the finding when a plain destination reports the +// BLAKE3 of an artifact whose name says what its BLAKE3 must be (an +// object's content hash, a pack's key) and the two differ. It holds for +// any backend that exposes BLAKE3; behind crypt the stored bytes are +// ciphertext, so it never applies there. +func contentMismatch(dest *config.Destination, hashes map[string]string, want []byte) (RemoteObjectMismatch, bool) { + got := hashes[store.ChecksumAlgoBlake3] + if dest.Crypt != nil || got == "" || got == hex.EncodeToString(want) { + return RemoteObjectMismatch{}, false + } + return RemoteObjectMismatch{Hash: hex.EncodeToString(want), Algo: store.ChecksumAlgoBlake3, Recorded: hex.EncodeToString(want), Actual: got}, true +} + // verifyRecordedObjects compares the remote listing against the recorded // rows and applies the per-object outcome to the store and the report. -func verifyRecordedObjects(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, rows []store.RemoteObjectRecord, rep *RemoteVerifyReport) error { - byName, err := readObjectChecksums(ctx, rcl, dest, rows) +func verifyRecordedObjects(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, rows []store.RemoteObjectRecord, rep *RemoteVerifyReport) error { + got, err := src.objects(ctx, rows) if err != nil { return fmt.Errorf("read object checksums from %q: %w", dest.Name, err) } @@ -199,12 +315,20 @@ func verifyRecordedObjects(ctx context.Context, s *store.Store, rcl *Rclone, des matched := 0 for _, row := range rows { hash := hex.EncodeToString(row.Blake3) - hashes, ok := byName[names.object(row.Blake3)] + hashes, ok := got.byName[names.object(row.Blake3)] if !ok { rep.Missing = append(rep.Missing, hash) continue } matched++ + if got.unchecked[names.object(row.Blake3)] { + countUnchecked(rep, row.ChecksumAlgo.Valid, &rep.Pending) + continue + } + if m, bad := contentMismatch(dest, hashes, row.Blake3); bad { + rep.Mismatched = append(rep.Mismatched, m) + continue + } if !row.ChecksumAlgo.Valid { if err := populateFingerprint(ctx, s, dest, row, hashes, rep); err != nil { return err @@ -226,10 +350,27 @@ func verifyRecordedObjects(ctx context.Context, s *store.Store, rcl *Rclone, des Actual: actual, }) } - rep.Unrecorded = len(byName) - matched + rep.Unrecorded = len(got.byName) - matched return nil } +// rcloneChecksums reads a destination's checksums through rclone, and +// through the S3 API on s3. +type rcloneChecksums struct { + rcl *Rclone + dest *config.Destination +} + +func (c rcloneChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (artifactChecksums, error) { + byName, err := readObjectChecksums(ctx, c.rcl, c.dest, rows) + return artifactChecksums{byName: byName}, err +} + +func (c rcloneChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (artifactChecksums, error) { + byName, err := readPackChecksums(ctx, c.rcl, c.dest, packs) + return artifactChecksums{byName: byName}, err +} + // readObjectChecksums reads the provider checksums verification compares, // keyed by object basename (namer.object) then rclone hash name. s3 reads raw // ETags straight from the S3 API — the only surface exposing a multipart @@ -253,7 +394,7 @@ func readObjectChecksums(ctx context.Context, rcl *Rclone, dest *config.Destinat } return byName, nil } - entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, ObjectsDirName), verifyObjectHashTypes(dest, rows), checkersArgs(dest)...) + entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, ObjectsDirName), verifyObjectHashTypes(dest, rows), concurrencyArgs(dest)...) if err != nil { return nil, err } @@ -300,19 +441,27 @@ func verifyObjectHashTypes(dest *config.Destination, rows []store.RemoteObjectRe // recorded pack rows and applies the per-pack outcome. One fingerprint // check per pack vouches for every content it holds, so a packed // destination is swept per pack rather than per member. -func verifyRecordedPacks(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { - byName, err := readPackChecksums(ctx, rcl, dest, packs) +func verifyRecordedPacks(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { + got, err := src.packs(ctx, packs) if err != nil { return fmt.Errorf("read pack checksums from %q: %w", dest.Name, err) } names := namerFor(dest) for _, row := range packs { key := hex.EncodeToString(row.PackKey) - hashes, ok := byName[names.pack(row.PackKey)] + hashes, ok := got.byName[names.pack(row.PackKey)] if !ok { rep.PacksMissing = append(rep.PacksMissing, key) continue } + if got.unchecked[names.pack(row.PackKey)] { + countUnchecked(rep, row.ChecksumAlgo.Valid, &rep.PacksPending) + continue + } + if m, bad := contentMismatch(dest, hashes, row.PackKey); bad { + rep.PackMismatched = append(rep.PackMismatched, m) + continue + } if !row.ChecksumAlgo.Valid { if err := populatePackFingerprint(ctx, s, dest, row, hashes, rep); err != nil { return err @@ -361,7 +510,7 @@ func readPackChecksums(ctx context.Context, rcl *Rclone, dest *config.Destinatio } return byName, nil } - entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, PacksDirName), verifyPackHashTypes(dest, packs), checkersArgs(dest)...) + entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, PacksDirName), verifyPackHashTypes(dest, packs), concurrencyArgs(dest)...) if err != nil { return nil, err } @@ -436,12 +585,12 @@ func recordVerifyOutcome(ctx context.Context, s *store.Store, rep *RemoteVerifyR errMsg = verifyErr.Error() case !rep.Clean(): status = store.RunStatusPartial - failed := len(rep.Missing) + len(rep.Mismatched) + len(rep.PacksMissing) + len(rep.PackMismatched) - errMsg = fmt.Sprintf("%d object(s)/pack(s) failed verification on %q", failed, rep.Destination) + errMsg = fmt.Sprintf("%d object(s)/pack(s)/mirror copies failed verification on %q", rep.failures(), rep.Destination) } - note := fmt.Sprintf("destination=%s objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d", + note := fmt.Sprintf("destination=%s objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d unchecked=%d paths=%d paths_reread=%d paths_changed=%d paths_missing=%d", rep.Destination, rep.Objects, rep.Verified, rep.Populated, rep.Pending, len(rep.Mismatched), len(rep.Missing), rep.Unrecorded, - rep.Packs, rep.PacksVerified, rep.PacksPopulated, rep.PacksPending, len(rep.PackMismatched), len(rep.PacksMissing)) + rep.Packs, rep.PacksVerified, rep.PacksPopulated, rep.PacksPending, len(rep.PackMismatched), len(rep.PacksMissing), + rep.Unchecked, rep.Paths, rep.PathsReread, len(rep.PathsChanged), len(rep.PathsMissing)) if err := s.AppendRunAudit(ctx, store.RunAuditEntry{ RunID: rep.RunID, Transition: store.TransitionVerifyDestination, Note: note, }); err != nil { @@ -454,7 +603,7 @@ func recordVerifyOutcome(ctx context.Context, s *store.Store, rep *RemoteVerifyR // noise (#182). A pass that found a mismatch or a missing object is // 'partial' or 'failed' and stays visible on status alone. changed := int64(rep.Populated + rep.PacksPopulated) - if err := s.FinishRunChanged(ctx, rep.RunID, status, errMsg, int64(rep.Objects+rep.Packs), changed); err != nil { + if err := s.FinishRunChanged(ctx, rep.RunID, status, errMsg, int64(rep.Objects+rep.Packs+rep.Paths), changed); err != nil { return fmt.Errorf("finish verify run %d: %w", rep.RunID, err) } return applyVerifyAlarm(ctx, s, rep, verifyErr) @@ -462,18 +611,20 @@ func recordVerifyOutcome(ctx context.Context, s *store.Store, rep *RemoteVerifyR // applyVerifyAlarm latches or clears the destination's standing alarm from // this pass's outcome (#157, F30). A pass that detected a mismatch or a -// missing object/pack raises the alarm (idempotent — a re-detection keeps -// the original "in alarm since"); a clean pass auto-clears any standing -// alarm, recording the clear against this verify run. A pass that aborted -// (verifyErr != nil) proves nothing about the destination's integrity, so -// it neither raises nor clears — its failed run row is the record. +// missing object/pack/copy raises the alarm (idempotent — a re-detection +// keeps the original "in alarm since"), even when it aborted afterwards: a +// mirror's findings are already recorded by then. A clean pass auto-clears +// any standing alarm, recording the clear against this verify run. A pass +// that aborted with no finding proves nothing about the destination's +// integrity, so it neither raises nor clears — its failed run row is the +// record. func applyVerifyAlarm(ctx context.Context, s *store.Store, rep *RemoteVerifyReport, verifyErr error) error { - if verifyErr != nil { + if verifyErr != nil && rep.Clean() { return nil } if !rep.Clean() { - detail := fmt.Sprintf("objects mismatched=%d missing=%d, packs mismatched=%d missing=%d", - len(rep.Mismatched), len(rep.Missing), len(rep.PackMismatched), len(rep.PacksMissing)) + detail := fmt.Sprintf("objects mismatched=%d missing=%d, packs mismatched=%d missing=%d, mirror copies changed=%d missing=%d", + len(rep.Mismatched), len(rep.Missing), len(rep.PackMismatched), len(rep.PacksMissing), len(rep.PathsChanged), len(rep.PathsMissing)) // AlarmRaised reflects only a *newly* created latch, taken from the // atomic insert itself — so the CLI shouts on first detection but a // concurrent second raise (which found the latch already there) diff --git a/sync/verify_remote_test.go b/sync/verify_remote_test.go index 2373268..94b1883 100644 --- a/sync/verify_remote_test.go +++ b/sync/verify_remote_test.go @@ -288,11 +288,13 @@ func TestVerifyRemoteNoRecordedObjects(t *testing.T) { } } -func TestVerifyRemoteRefusesMirrorDestination(t *testing.T) { +// TestVerifyRemoteRefusesRcloneMirror: an rclone mirror records nothing a +// pass could re-check. +func TestVerifyRemoteRefusesRcloneMirror(t *testing.T) { f := setupContentAddressedFixture(t) - dest := &config.Destination{Name: "mirror", Type: "sftp", Root: "/data", Layout: config.LayoutMirror} + dest := &config.Destination{Name: "mirror", Type: "sftp", Root: "/data", Layout: config.LayoutMirror, Crypt: &config.Crypt{Password: "x"}} _, err := VerifyRemote(context.Background(), f.store, f.rcl, dest) - if err == nil || !strings.Contains(err.Error(), "content-addressed") { - t.Fatalf("err = %v, want content-addressed refusal", err) + if err == nil || !strings.Contains(err.Error(), "rclone mirror") { + t.Fatalf("err = %v, want an rclone-mirror refusal", err) } }