strip.v

15.5 KB · raw

1//! Strip: removing a path from history, here and on the remote.2//!3//! The local half is one transaction: the saved files go, the objects nobody4//! references go, a strip event is recorded, and so is a note of which objects5//! the remote may now drop. The remote half reads that note, so it can be6//! re-run after an interruption even though the local rows are long gone.78module exchange910import json211import os12import src.events13import src.fmt14import src.remote15import src.storage1617// Scope is what a strip would remove, for the warning shown before it runs.18pub struct Scope {19pub:20	files   int21	saves   int22	objects int23}2425pub struct LocalStrip {26pub:27	files_removed   int28	objects_dropped i6429}3031// SendReport says what a strip managed to make visible on the remote.32pub struct SendReport {33pub mut:34	records    int35	objects    int36	event_sent bool37}3839// Pending is the note a strip leaves until its remote half has finished: which40// saves it covered ('' for every save) and which objects it freed. One note per41// path, so strips of the same path that did not finish are finished together.42pub struct Pending {43mut:44	saves  []string45	hashes []string46}4748fn pending_key(path string) string {49	return 'strip_pending:${path}'50}5152// read_pending refuses a note it cannot parse, one naming something other53// than an object, or one claiming a scope no recorded strip of the path has:54// sending it would lose the retry, delete outside the repo's objects, or55// remove the path where no strip asked. The note stays for recovery.56pub fn read_pending(store &storage.Store, path string) !Pending {57	text := store.state(pending_key(path)) or { return Pending{} }58	note := json2.decode[Pending](text) or {59		return error('the unfinished strip note for ${path} is unreadable; it is kept for recovery')60	}61	if !note.hashes.all(storage.valid_hash(it)) {62		return error('the unfinished strip note for ${path} names something other than an object; it is kept for recovery')63	}64	recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path)65	if note.saves.len == 0 || !note.saves.all(fn [recorded] (scope string) bool {66		return recorded.any(it.save_id == scope)67	}) {68		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')69	}70	return note71}7273// strip_pending is true while the remote half of a strip has not finished.74pub fn strip_pending(store &storage.Store, path string) bool {75	return store.state(pending_key(path)) != none76}7778// covers is the one rule for what a strip removes: the path itself, or79// anything beneath it when it names a folder.80fn covers(path string, file string) bool {81	return file == path || file.starts_with('${path.trim_right('/')}/')82}8384// strip_scope counts what strip_rows will remove, using the same trie walk. `objects` is the85// distinct content they hold; content another path still uses is kept, so fewer may be deleted.86pub fn strip_scope(store &storage.Store, path string, only_save string) !Scope {87	covered := covered_by(store, path.trim_right('/'), only_save)!88	return Scope{89		files:   covered.files90		saves:   covered.saves91		objects: covered.hashes.len92	}93}9495// strip_local removes the path in one transaction and leaves the note the96// remote half needs.97pub fn strip_local(store &storage.Store, path string, only_save string) !LocalStrip {98	store.begin()!99	report := strip_rows(store, path, only_save) or {100		store.rollback()101		return err102	}103	store.end()!104	return report105}106107/// Strip the batch in one transaction; failures leave history unchanged.108pub fn strip_local_batch(store &storage.Store, paths []string, only_save string) ![]LocalStrip {109	store.begin()!110	mut reports := []LocalStrip{}111	for path in paths {112		reports << strip_rows(store, path, only_save) or {113			store.rollback()114			return err115		}116	}117	store.end() or {118		store.rollback()119		return err120	}121	return reports122}123124// strip_rows is the body of strip_local's transaction. Its event has no save id for a whole-history125// strip (spec §10.2), and that empty id is what bans the path from every later walk.126fn strip_rows(store &storage.Store, path string, only_save string) !LocalStrip {127	target := path.trim_right('/')128	covered := covered_by(store, target, only_save)!129	if covered.hashes.len == 0 {130		// Already stripped: keep the pending note an unfinished remote needs.131		return LocalStrip{}132	}133	rewrite_saves(store, target, only_save)!134	store.drop_unreachable_manifests()!135	dropped := store.drop_unused(covered.hashes)!136	events.strip(store, only_save, path)!137	// An earlier strip of the same path may not have finished on the remote,138	// so the note grows rather than resets.139	queue_strip(store, path, [only_save], covered.hashes)!140	return LocalStrip{141		files_removed:   covered.files142		objects_dropped: dropped143	}144}145146// send_strip makes a strip visible on the remote: the event travels like any147// other, every remote save record listing the path is rewritten, and objects148// the strip freed are deleted once no remote record and no local save needs149// them. Every step is safe to repeat, and the pending note is cleared only150// when all of them have succeeded.151pub fn send_strip(store &storage.Store, mut backend remote.Backend, path string) !SendReport {152	mut report := SendReport{}153	send_steps(store, mut backend, path, mut report) or {154		mut done := []string{}155		if report.event_sent || report.records + report.objects > 0 {156			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}'157		}158		return partway(done, err)159	}160	return report161}162163fn send_steps(store &storage.Store, mut backend remote.Backend, path string, mut report SendReport) ! {164	note := read_pending(store, path)!165	name := repo_name(store, mut backend)!166	mut upload := OfferReport{167		repo: name168	}169	defer {170		report.event_sent = upload.events > 0171	}172	event_keys := backend.list(events_prefix(name))!173	upload_events(store, mut backend, name, event_keys, mut upload)!174	mut freed := map[string]bool{}175	for hash in note.hashes {176		freed[hash] = true177	}178	every_save := '' in note.saves179	mut needed := map[string]bool{}180	for key in backend.list('${name}/saves')! {181		remote_object := backend.get(key)!182		if !remote_object.found {183			continue184		}185		record := decode_save(remote_object.body)!186		mut kept := []FileRecord{}187		mut dropped := []string{}188		for file in record.files {189			if (every_save || record.id in note.saves) && covers(path, file.path) {190				freed[file.hash] = true191				dropped << file.hash192				continue193			}194			kept << file195			needed[file.hash] = true196		}197		if kept.len == record.files.len {198			continue199		}200		// Once rewritten, the record no longer names these objects; the note201		// keeps them so a retry can still delete them.202		queue_strip(store, path, []string{}, dropped)!203		if !backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), remote_object.tag)! {204			return error('the remote copy of save ${record.id} moved while stripping — run koh steal, then strip again')205		}206		report.records++207	}208	for hash, _ in freed {209		if hash in needed || !storage.valid_hash(hash) || store.has_object(hash)!210			|| store.paths_of_object(hash)!.len > 0 {211			continue212		}213		backend.delete(object_key(name, hash))!214		report.objects++215	}216	store.remove_state(pending_key(path))!217}218219// requeue_strip notes every valid recorded strip of `path` again, so that220// send_strip removes the path from remote records that still hold it.221pub fn requeue_strip(store &storage.Store, path string) ! {222	recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path)223	if recorded.len == 0 {224		return error('this repo has no recorded strip of ${path}; run koh steal, then koh doctor')225	}226	queue_strip(store, path, recorded.map(it.save_id), []string{})!227}228229// queue_strip adds scopes and objects to the note send_strip works from,230// writing it only when something is new. Only object hashes are noted.231fn queue_strip(store &storage.Store, path string, scopes []string, hashes []string) ! {232	mut note := read_pending(store, path)!233	count := note.saves.len + note.hashes.len234	note.saves << scopes.filter(it !in note.saves)235	note.hashes << hashes.filter(it !in note.hashes && storage.valid_hash(it))236	if note.saves.len + note.hashes.len > count {237		store.set_state(pending_key(path), json2.encode(note))!238	}239}240241// unapplied_strips are the strip events on the remote this repo has not242// received yet, found in `event_keys`, the listing the caller took (so the243// repo name is not needed here). offer asks before uploading, and again after,244// because a strip that lands in between would otherwise leave the stripped245// path in the bucket.246fn unapplied_strips(store &storage.Store, mut backend remote.Backend, event_keys []string) ![]events.Event {247	mut known := map[string]bool{}248	for event in events.all(store)! {249		known[event.id] = true250	}251	mut strips := []events.Event{}252	for key in event_keys {253		if os.base(key) in known {254			continue255		}256		body := backend.get(key)!257		if !body.found {258			continue259		}260		event := decode_event(body.body)!261		if events.valid_strip(event) && !ignored_strip(event) {262			strips << event263		}264	}265	return strips266}267268// rewrite returns the save record with a new file list.269fn rewrite(record SaveRecord, files []FileRecord) SaveRecord {270	return SaveRecord{271		...record272		files: files273	}274}275276struct Covered {277	files  int278	saves  int279	hashes []string280}281282// Subtree is one folder's files, counted once and reused.283struct Subtree {284	files  int285	hashes []string286}287288struct SaveTree {289	id       string290	manifest string291}292293fn save_trees(store &storage.Store, only_save string) ![]SaveTree {294	mut stmt := store.db.prepare('SELECT id, manifest FROM saves ORDER BY id')!295	defer {296		stmt.finalize()297	}298	mut trees := []SaveTree{}299	for stmt.step()! {300		id := stmt.text(0)301		if only_save != '' && id != only_save {302			continue303		}304		trees << SaveTree{305			id:       id306			manifest: stmt.text(1)307		}308	}309	return trees310}311312struct FoundEntry {313	ok    bool314	entry storage.ManifestEntry315}316317// find_entry follows `path`'s segments from the root. A folder where a file318// was expected is no match, and a folder entry named exactly the remaining319// path covers its whole subtree.320fn find_entry(store &storage.Store, root string, path string) !FoundEntry {321	mut hash := root322	mut rest := path323	for {324		entries := store.manifest_entries(hash)!325		for entry in entries {326			if entry.name == rest {327				return FoundEntry{328					ok:    true329					entry: entry330				}331			}332		}333		slash := rest.index('/') or { return FoundEntry{} }334		segment := rest[..slash]335		mut child := ''336		for entry in entries {337			if entry.name == segment && entry.kind == storage.folder_kind {338				child = entry.manifest339				break340			}341		}342		if child == '' {343			return FoundEntry{}344		}345		hash = child346		rest = rest[slash + 1..]347	}348	return FoundEntry{}349}350351// subtree counts one folder's files, memoized by manifest hash so a tree two352// saves share is walked once.353fn subtree(store &storage.Store, hash string, mut memo map[string]Subtree, mut busy map[string]bool) !Subtree {354	if hash in memo {355		return memo[hash]356	}357	if busy[hash] {358		return error('manifest ${hash} refers to itself')359	}360	busy[hash] = true361	mut files := 0362	mut hashes := map[string]bool{}363	entries := store.manifest_entries(hash)!364	for entry in entries {365		if entry.kind == storage.file_kind {366			files++367			hashes[entry.hash] = true368		} else {369			child := subtree(store, entry.manifest, mut memo, mut busy)!370			files += child.files371			for h in child.hashes {372				hashes[h] = true373			}374		}375	}376	busy.delete(hash)377	summary := Subtree{378		files:  files379		hashes: hashes.keys()380	}381	memo[hash] = summary382	return summary383}384385// stripped_hashes is the content a strip of `path` would free.386fn stripped_hashes(store &storage.Store, path string, only_save string) ![]string {387	return covered_by(store, path.trim_right('/'), only_save)!.hashes388}389390// remove_path rewrites every save that holds the path and returns the files it391// removed; callers drop the freed objects once nothing references them.392fn remove_path(store &storage.Store, path string, only_save string) !int {393	target := path.trim_right('/')394	covered := covered_by(store, target, only_save)!395	rewrite_saves(store, target, only_save)!396	store.drop_unreachable_manifests()!397	return covered.files398}399400// covered_by counts the files `path` reaches, the saves that hold them and the401// distinct content they carry.402fn covered_by(store &storage.Store, path string, only_save string) !Covered {403	mut files := 0404	mut saves := 0405	mut hashes := map[string]bool{}406	mut memo := map[string]Subtree{}407	mut busy := map[string]bool{}408	for tree in save_trees(store, only_save)! {409		found := find_entry(store, tree.manifest, path)!410		if found.ok {411			entry := found.entry412			mut here := 0413			if entry.kind == storage.file_kind {414				here = 1415				hashes[entry.hash] = true416			} else {417				summary := subtree(store, entry.manifest, mut memo, mut busy)!418				here = summary.files419				for hash in summary.hashes {420					hashes[hash] = true421				}422			}423			if here > 0 {424				files += here425				saves++426			}427		}428	}429	mut distinct := hashes.keys()430	distinct.sort()431	return Covered{432		files:  files433		saves:  saves434		hashes: distinct435	}436}437438// Rewriter rebuilds the folders on one path without mutating a row. The memo439// keeps old folder hash to new, so identical subtrees are rewritten once.440struct Rewriter {441mut:442	memo map[string]string443	busy map[string]bool444}445446struct Rewritten {447	changed bool448	hash    string449}450451// rewrite returns `hash` with `path` removed, or unchanged when the tree does452// not hold it.453fn (mut r Rewriter) rewrite(store &storage.Store, hash string, path string) !Rewritten {454	key := '${hash}\x00${path}'455	if key in r.memo {456		found := r.memo[key]457		if found == '' {458			return Rewritten{}459		}460		return Rewritten{461			changed: true462			hash:    found463		}464	}465	if r.busy[key] {466		return error('manifest ${hash} refers to itself')467	}468	r.busy[key] = true469	entries := store.manifest_entries(hash)!470	mut kept := []storage.ManifestEntry{}471	mut exact := false472	for entry in entries {473		if entry.name == path {474			exact = true475		}476	}477	if exact {478		for entry in entries {479			if entry.name != path {480				kept << entry481			}482		}483	} else {484		slash := path.index('/') or { -1 }485		if slash < 0 {486			r.miss(key)487			return Rewritten{}488		}489		segment := path[..slash]490		mut at := -1491		for i, entry in entries {492			if entry.name == segment && entry.kind == storage.folder_kind {493				at = i494				break495			}496		}497		if at < 0 {498			r.miss(key)499			return Rewritten{}500		}501		child := r.rewrite(store, entries[at].manifest, path[slash + 1..])!502		if child.changed {503			kept = entries.clone()504			kept[at] = storage.ManifestEntry{505				name:     entries[at].name506				kind:     storage.folder_kind507				manifest: child.hash508			}509		} else {510			r.miss(key)511			return Rewritten{}512		}513	}514	new_hash := store.put_manifest(json2.encode(storage.Manifest{515		entries: kept516	}))!517	r.busy.delete(key)518	r.memo[key] = new_hash519	return Rewritten{520		changed: true521		hash:    new_hash522	}523}524525// miss remembers that this folder does not hold the path.526fn (mut r Rewriter) miss(key string) {527	r.busy.delete(key)528	r.memo[key] = ''529}530531// rewrite_saves points every save that holds `path` at its rewritten root.532// A save whose tree does not hold the path is not touched.533fn rewrite_saves(store &storage.Store, path string, only_save string) ! {534	mut rewriter := Rewriter{}535	mut update := store.db.prepare('UPDATE saves SET manifest = ? WHERE id = ?')!536	defer {537		update.finalize()538	}539	for tree in save_trees(store, only_save)! {540		rewritten := rewriter.rewrite(store, tree.manifest, path)!541		if rewritten.changed {542			update.bind_text(1, rewritten.hash)!543			update.bind_text(2, tree.id)!544			update.step()!545			update.reset()546		}547	}548}