//! Strip: removing a path from history, here and on the remote. //! //! The local half is one transaction: the saved files go, the objects nobody //! references go, a strip event is recorded, and so is a note of which objects //! the remote may now drop. The remote half reads that note, so it can be //! re-run after an interruption even though the local rows are long gone. module exchange import json2 import os import src.events import src.fmt import src.remote import src.storage // Scope is what a strip would remove, for the warning shown before it runs. pub struct Scope { pub: files int saves int objects int } pub struct LocalStrip { pub: files_removed int objects_dropped i64 } // SendReport says what a strip managed to make visible on the remote. pub struct SendReport { pub mut: records int objects int event_sent bool } // Pending is the note a strip leaves until its remote half has finished: which // saves it covered ('' for every save) and which objects it freed. One note per // path, so strips of the same path that did not finish are finished together. pub struct Pending { mut: saves []string hashes []string } fn pending_key(path string) string { return 'strip_pending:${path}' } // read_pending refuses a note it cannot parse, one naming something other // than an object, or one claiming a scope no recorded strip of the path has: // sending it would lose the retry, delete outside the repo's objects, or // remove the path where no strip asked. The note stays for recovery. pub fn read_pending(store &storage.Store, path string) !Pending { text := store.state(pending_key(path)) or { return Pending{} } note := json2.decode[Pending](text) or { return error('the unfinished strip note for ${path} is unreadable; it is kept for recovery') } if !note.hashes.all(storage.valid_hash(it)) { return error('the unfinished strip note for ${path} names something other than an object; it is kept for recovery') } recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path) if note.saves.len == 0 || !note.saves.all(fn [recorded] (scope string) bool { return recorded.any(it.save_id == scope) }) { return error('no recorded strip matches the unfinished strip note for ${path}; it is kept for recovery, and koh steal brings a strip made elsewhere') } return note } // strip_pending is true while the remote half of a strip has not finished. pub fn strip_pending(store &storage.Store, path string) bool { return store.state(pending_key(path)) != none } // covers is the one rule for what a strip removes: the path itself, or // anything beneath it when it names a folder. fn covers(path string, file string) bool { return file == path || file.starts_with('${path.trim_right('/')}/') } // strip_scope counts what strip_rows will remove, using the same trie walk. `objects` is the // distinct content they hold; content another path still uses is kept, so fewer may be deleted. pub fn strip_scope(store &storage.Store, path string, only_save string) !Scope { covered := covered_by(store, path.trim_right('/'), only_save)! return Scope{ files: covered.files saves: covered.saves objects: covered.hashes.len } } // strip_local removes the path in one transaction and leaves the note the // remote half needs. pub fn strip_local(store &storage.Store, path string, only_save string) !LocalStrip { store.begin()! report := strip_rows(store, path, only_save) or { store.rollback() return err } store.end()! return report } /// Strip the batch in one transaction; failures leave history unchanged. pub fn strip_local_batch(store &storage.Store, paths []string, only_save string) ![]LocalStrip { store.begin()! mut reports := []LocalStrip{} for path in paths { reports << strip_rows(store, path, only_save) or { store.rollback() return err } } store.end() or { store.rollback() return err } return reports } // strip_rows is the body of strip_local's transaction. Its event has no save id for a whole-history // strip (spec §10.2), and that empty id is what bans the path from every later walk. fn strip_rows(store &storage.Store, path string, only_save string) !LocalStrip { target := path.trim_right('/') covered := covered_by(store, target, only_save)! if covered.hashes.len == 0 { // Already stripped: keep the pending note an unfinished remote needs. return LocalStrip{} } rewrite_saves(store, target, only_save)! store.drop_unreachable_manifests()! dropped := store.drop_unused(covered.hashes)! events.strip(store, only_save, path)! // An earlier strip of the same path may not have finished on the remote, // so the note grows rather than resets. queue_strip(store, path, [only_save], covered.hashes)! return LocalStrip{ files_removed: covered.files objects_dropped: dropped } } // send_strip makes a strip visible on the remote: the event travels like any // other, every remote save record listing the path is rewritten, and objects // the strip freed are deleted once no remote record and no local save needs // them. Every step is safe to repeat, and the pending note is cleared only // when all of them have succeeded. pub fn send_strip(store &storage.Store, mut backend remote.Backend, path string) !SendReport { mut report := SendReport{} send_steps(store, mut backend, path, mut report) or { mut done := []string{} if report.event_sent || report.records + report.objects > 0 { done << '${if report.event_sent { 'sent its event, ' } else { '' }}rewrote ${fmt.plural(report.records, 'remote record')} and deleted ${fmt.plural(report.objects, 'remote object')} for ${path}' } return partway(done, err) } return report } fn send_steps(store &storage.Store, mut backend remote.Backend, path string, mut report SendReport) ! { note := read_pending(store, path)! name := repo_name(store, mut backend)! mut upload := OfferReport{ repo: name } defer { report.event_sent = upload.events > 0 } event_keys := backend.list(events_prefix(name))! upload_events(store, mut backend, name, event_keys, mut upload)! mut freed := map[string]bool{} for hash in note.hashes { freed[hash] = true } every_save := '' in note.saves mut needed := map[string]bool{} for key in backend.list('${name}/saves')! { remote_object := backend.get(key)! if !remote_object.found { continue } record := decode_save(remote_object.body)! mut kept := []FileRecord{} mut dropped := []string{} for file in record.files { if (every_save || record.id in note.saves) && covers(path, file.path) { freed[file.hash] = true dropped << file.hash continue } kept << file needed[file.hash] = true } if kept.len == record.files.len { continue } // Once rewritten, the record no longer names these objects; the note // keeps them so a retry can still delete them. queue_strip(store, path, []string{}, dropped)! if !backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), remote_object.tag)! { return error('the remote copy of save ${record.id} moved while stripping — run koh steal, then strip again') } report.records++ } for hash, _ in freed { if hash in needed || !storage.valid_hash(hash) || store.has_object(hash)! || store.paths_of_object(hash)!.len > 0 { continue } backend.delete(object_key(name, hash))! report.objects++ } store.remove_state(pending_key(path))! } // requeue_strip notes every valid recorded strip of `path` again, so that // send_strip removes the path from remote records that still hold it. pub fn requeue_strip(store &storage.Store, path string) ! { recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path) if recorded.len == 0 { return error('this repo has no recorded strip of ${path}; run koh steal, then koh doctor') } queue_strip(store, path, recorded.map(it.save_id), []string{})! } // queue_strip adds scopes and objects to the note send_strip works from, // writing it only when something is new. Only object hashes are noted. fn queue_strip(store &storage.Store, path string, scopes []string, hashes []string) ! { mut note := read_pending(store, path)! count := note.saves.len + note.hashes.len note.saves << scopes.filter(it !in note.saves) note.hashes << hashes.filter(it !in note.hashes && storage.valid_hash(it)) if note.saves.len + note.hashes.len > count { store.set_state(pending_key(path), json2.encode(note))! } } // unapplied_strips are the strip events on the remote this repo has not // received yet, found in `event_keys`, the listing the caller took (so the // repo name is not needed here). offer asks before uploading, and again after, // because a strip that lands in between would otherwise leave the stripped // path in the bucket. fn unapplied_strips(store &storage.Store, mut backend remote.Backend, event_keys []string) ![]events.Event { mut known := map[string]bool{} for event in events.all(store)! { known[event.id] = true } mut strips := []events.Event{} for key in event_keys { if os.base(key) in known { continue } body := backend.get(key)! if !body.found { continue } event := decode_event(body.body)! if events.valid_strip(event) && !ignored_strip(event) { strips << event } } return strips } // rewrite returns the save record with a new file list. fn rewrite(record SaveRecord, files []FileRecord) SaveRecord { return SaveRecord{ ...record files: files } } struct Covered { files int saves int hashes []string } // Subtree is one folder's files, counted once and reused. struct Subtree { files int hashes []string } struct SaveTree { id string manifest string } fn save_trees(store &storage.Store, only_save string) ![]SaveTree { mut stmt := store.db.prepare('SELECT id, manifest FROM saves ORDER BY id')! defer { stmt.finalize() } mut trees := []SaveTree{} for stmt.step()! { id := stmt.text(0) if only_save != '' && id != only_save { continue } trees << SaveTree{ id: id manifest: stmt.text(1) } } return trees } struct FoundEntry { ok bool entry storage.ManifestEntry } // find_entry follows `path`'s segments from the root. A folder where a file // was expected is no match, and a folder entry named exactly the remaining // path covers its whole subtree. fn find_entry(store &storage.Store, root string, path string) !FoundEntry { mut hash := root mut rest := path for { entries := store.manifest_entries(hash)! for entry in entries { if entry.name == rest { return FoundEntry{ ok: true entry: entry } } } slash := rest.index('/') or { return FoundEntry{} } segment := rest[..slash] mut child := '' for entry in entries { if entry.name == segment && entry.kind == storage.folder_kind { child = entry.manifest break } } if child == '' { return FoundEntry{} } hash = child rest = rest[slash + 1..] } return FoundEntry{} } // subtree counts one folder's files, memoized by manifest hash so a tree two // saves share is walked once. fn subtree(store &storage.Store, hash string, mut memo map[string]Subtree, mut busy map[string]bool) !Subtree { if hash in memo { return memo[hash] } if busy[hash] { return error('manifest ${hash} refers to itself') } busy[hash] = true mut files := 0 mut hashes := map[string]bool{} entries := store.manifest_entries(hash)! for entry in entries { if entry.kind == storage.file_kind { files++ hashes[entry.hash] = true } else { child := subtree(store, entry.manifest, mut memo, mut busy)! files += child.files for h in child.hashes { hashes[h] = true } } } busy.delete(hash) summary := Subtree{ files: files hashes: hashes.keys() } memo[hash] = summary return summary } // stripped_hashes is the content a strip of `path` would free. fn stripped_hashes(store &storage.Store, path string, only_save string) ![]string { return covered_by(store, path.trim_right('/'), only_save)!.hashes } // remove_path rewrites every save that holds the path and returns the files it // removed; callers drop the freed objects once nothing references them. fn remove_path(store &storage.Store, path string, only_save string) !int { target := path.trim_right('/') covered := covered_by(store, target, only_save)! rewrite_saves(store, target, only_save)! store.drop_unreachable_manifests()! return covered.files } // covered_by counts the files `path` reaches, the saves that hold them and the // distinct content they carry. fn covered_by(store &storage.Store, path string, only_save string) !Covered { mut files := 0 mut saves := 0 mut hashes := map[string]bool{} mut memo := map[string]Subtree{} mut busy := map[string]bool{} for tree in save_trees(store, only_save)! { found := find_entry(store, tree.manifest, path)! if found.ok { entry := found.entry mut here := 0 if entry.kind == storage.file_kind { here = 1 hashes[entry.hash] = true } else { summary := subtree(store, entry.manifest, mut memo, mut busy)! here = summary.files for hash in summary.hashes { hashes[hash] = true } } if here > 0 { files += here saves++ } } } mut distinct := hashes.keys() distinct.sort() return Covered{ files: files saves: saves hashes: distinct } } // Rewriter rebuilds the folders on one path without mutating a row. The memo // keeps old folder hash to new, so identical subtrees are rewritten once. struct Rewriter { mut: memo map[string]string busy map[string]bool } struct Rewritten { changed bool hash string } // rewrite returns `hash` with `path` removed, or unchanged when the tree does // not hold it. fn (mut r Rewriter) rewrite(store &storage.Store, hash string, path string) !Rewritten { key := '${hash}\x00${path}' if key in r.memo { found := r.memo[key] if found == '' { return Rewritten{} } return Rewritten{ changed: true hash: found } } if r.busy[key] { return error('manifest ${hash} refers to itself') } r.busy[key] = true entries := store.manifest_entries(hash)! mut kept := []storage.ManifestEntry{} mut exact := false for entry in entries { if entry.name == path { exact = true } } if exact { for entry in entries { if entry.name != path { kept << entry } } } else { slash := path.index('/') or { -1 } if slash < 0 { r.miss(key) return Rewritten{} } segment := path[..slash] mut at := -1 for i, entry in entries { if entry.name == segment && entry.kind == storage.folder_kind { at = i break } } if at < 0 { r.miss(key) return Rewritten{} } child := r.rewrite(store, entries[at].manifest, path[slash + 1..])! if child.changed { kept = entries.clone() kept[at] = storage.ManifestEntry{ name: entries[at].name kind: storage.folder_kind manifest: child.hash } } else { r.miss(key) return Rewritten{} } } new_hash := store.put_manifest(json2.encode(storage.Manifest{ entries: kept }))! r.busy.delete(key) r.memo[key] = new_hash return Rewritten{ changed: true hash: new_hash } } // miss remembers that this folder does not hold the path. fn (mut r Rewriter) miss(key string) { r.busy.delete(key) r.memo[key] = '' } // rewrite_saves points every save that holds `path` at its rewritten root. // A save whose tree does not hold the path is not touched. fn rewrite_saves(store &storage.Store, path string, only_save string) ! { mut rewriter := Rewriter{} mut update := store.db.prepare('UPDATE saves SET manifest = ? WHERE id = ?')! defer { update.finalize() } for tree in save_trees(store, only_save)! { rewritten := rewriter.rewrite(store, tree.manifest, path)! if rewritten.changed { update.bind_text(1, rewritten.hash)! update.bind_text(2, tree.id)! update.step()! update.reset() } } }