strip.v

17.3 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	// Reading the layout refuses a bucket this koh does not speak, before a rewrite.167	check_format(mut backend, name)!168	mut upload := OfferReport{169		repo: name170	}171	defer {172		report.event_sent = upload.events > 0173	}174	event_keys := backend.list(events_prefix(name))!175	upload_events(store, mut backend, name, event_keys, mut upload)!176	mut freed := map[string]bool{}177	for hash in note.hashes {178		freed[hash] = true179	}180	every_save := '' in note.saves181	target := path.trim_right('/')182	mut needed := map[string]bool{}183	// One copy of each remote tree serves every record that shares it: `manifests`184	// the bodies read, `sent` what is already on the remote.185	mut manifests := map[string]string{}186	mut sent := map[string]bool{}187	mut rewriter := Rewriter{}188	for key in backend.list('${name}/saves')! {189		remote_object := backend.get(key)!190		if !remote_object.found {191			continue192		}193		record := decode_save(remote_object.body)!194		mut before := record.files.map(storage.ManifestFile{195			path:       it.path196			hash:       it.hash197			executable: it.executable198		})199		if record.manifest != '' {200			fetch_manifests(mut backend, name, record.manifest, mut manifests)!201			store_manifests(store, manifests)!202			before = store.manifest_files(record.manifest)!203		}204		reached := every_save || record.id in note.saves205		// One rule for both layouts: what the record names now, and what it named.206		after := before.filter(fn [reached, path] (file storage.ManifestFile) bool {207			return !reached || !covers(path, file.path)208		})209		if after.len == before.len {210			for file in before {211				needed[file.hash] = true212			}213			continue214		}215		mut still := map[string]bool{}216		for file in after {217			still[file.hash] = true218			needed[file.hash] = true219		}220		// A hash the record still names elsewhere is not freed; the path goes221		// whatever the object's fate.222		mut dropped := []string{}223		for file in before {224			if file.hash !in still && file.hash !in dropped {225				dropped << file.hash226				freed[file.hash] = true227			}228		}229		mut next := rewrite(record, after.map(FileRecord{230			path:       it.path231			hash:       it.hash232			executable: it.executable233		}), '')234		if record.manifest != '' {235			// The folders on the path are new bodies, up before the record that236			// names them. Old ones stay: no manifest is ever deleted.237			rewritten := rewriter.rewrite(store, record.manifest, target)!238			upload_manifests(store, mut backend, name, rewritten.hash, mut sent)!239			next = rewrite(record, record.files, rewritten.hash)240		}241		// Once rewritten, the record no longer names these objects; the note242		// keeps them so a retry can still delete them.243		queue_strip(store, path, []string{}, dropped)!244		encoded := encode_save(next)245		if !backend.put_if_match(key, encoded.bytes(), remote_object.tag)! {246			return error('the remote copy of save ${record.id} moved while stripping — run koh steal, then strip again')247		}248		report.records++249	}250	for hash, _ in freed {251		if hash in needed || !storage.valid_hash(hash) || store.has_object(hash)!252			|| store.paths_of_object(hash)!.len > 0 {253			continue254		}255		backend.delete(object_key(name, hash))!256		report.objects++257	}258	store.remove_state(pending_key(path))!259}260261// requeue_strip notes every valid recorded strip of `path` again, so that262// send_strip removes the path from remote records that still hold it.263pub fn requeue_strip(store &storage.Store, path string) ! {264	recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path)265	if recorded.len == 0 {266		return error('this repo has no recorded strip of ${path}; run koh steal, then koh doctor')267	}268	queue_strip(store, path, recorded.map(it.save_id), []string{})!269}270271// queue_strip adds scopes and objects to the note send_strip works from,272// writing it only when something is new. Only object hashes are noted.273fn queue_strip(store &storage.Store, path string, scopes []string, hashes []string) ! {274	mut note := read_pending(store, path)!275	count := note.saves.len + note.hashes.len276	note.saves << scopes.filter(it !in note.saves)277	note.hashes << hashes.filter(it !in note.hashes && storage.valid_hash(it))278	if note.saves.len + note.hashes.len > count {279		store.set_state(pending_key(path), json2.encode(note))!280	}281}282283// unapplied_strips are the strip events on the remote this repo has not284// received yet, found in `event_keys`, the listing the caller took (so the285// repo name is not needed here). offer asks before uploading, and again after,286// because a strip that lands in between would otherwise leave the stripped287// path in the bucket.288fn unapplied_strips(store &storage.Store, mut backend remote.Backend, event_keys []string) ![]events.Event {289	mut known := map[string]bool{}290	for event in events.all(store)! {291		known[event.id] = true292	}293	mut strips := []events.Event{}294	for key in event_keys {295		if os.base(key) in known {296			continue297		}298		body := backend.get(key)!299		if !body.found {300			continue301		}302		event := decode_event(body.body)!303		if events.valid_strip(event) && !ignored_strip(event) {304			strips << event305		}306	}307	return strips308}309310// rewrite returns the save record with a new file list and root manifest. A311// version-2 record keeps its empty list and names the tree it now has.312fn rewrite(record SaveRecord, files []FileRecord, manifest string) SaveRecord {313	return SaveRecord{314		...record315		files:    files316		manifest: manifest317	}318}319320struct Covered {321	files  int322	saves  int323	hashes []string324}325326// Subtree is one folder's files, counted once and reused.327struct Subtree {328	files  int329	hashes []string330}331332struct SaveTree {333	id       string334	manifest string335}336337fn save_trees(store &storage.Store, only_save string) ![]SaveTree {338	mut stmt := store.db.prepare('SELECT id, manifest FROM saves ORDER BY id')!339	defer {340		stmt.finalize()341	}342	mut trees := []SaveTree{}343	for stmt.step()! {344		id := stmt.text(0)345		if only_save != '' && id != only_save {346			continue347		}348		trees << SaveTree{349			id:       id350			manifest: stmt.text(1)351		}352	}353	return trees354}355356struct FoundEntry {357	ok    bool358	entry storage.ManifestEntry359}360361// find_entry follows `path`'s segments from the root. A folder where a file362// was expected is no match, and a folder entry named exactly the remaining363// path covers its whole subtree.364fn find_entry(store &storage.Store, root string, path string) !FoundEntry {365	mut hash := root366	mut rest := path367	for {368		entries := store.manifest_entries(hash)!369		for entry in entries {370			if entry.name == rest {371				return FoundEntry{372					ok:    true373					entry: entry374				}375			}376		}377		slash := rest.index('/') or { return FoundEntry{} }378		segment := rest[..slash]379		mut child := ''380		for entry in entries {381			if entry.name == segment && entry.kind == storage.folder_kind {382				child = entry.manifest383				break384			}385		}386		if child == '' {387			return FoundEntry{}388		}389		hash = child390		rest = rest[slash + 1..]391	}392	return FoundEntry{}393}394395// subtree counts one folder's files, memoized by manifest hash so a tree two396// saves share is walked once.397fn subtree(store &storage.Store, hash string, mut memo map[string]Subtree, mut busy map[string]bool) !Subtree {398	if hash in memo {399		return memo[hash]400	}401	if busy[hash] {402		return error('manifest ${hash} refers to itself')403	}404	busy[hash] = true405	mut files := 0406	mut hashes := map[string]bool{}407	entries := store.manifest_entries(hash)!408	for entry in entries {409		if entry.kind == storage.file_kind {410			files++411			hashes[entry.hash] = true412		} else {413			child := subtree(store, entry.manifest, mut memo, mut busy)!414			files += child.files415			for h in child.hashes {416				hashes[h] = true417			}418		}419	}420	busy.delete(hash)421	summary := Subtree{422		files:  files423		hashes: hashes.keys()424	}425	memo[hash] = summary426	return summary427}428429// stripped_hashes is the content a strip of `path` would free.430fn stripped_hashes(store &storage.Store, path string, only_save string) ![]string {431	return covered_by(store, path.trim_right('/'), only_save)!.hashes432}433434// remove_path rewrites every save that holds the path and returns the files it435// removed; callers drop the freed objects once nothing references them.436fn remove_path(store &storage.Store, path string, only_save string) !int {437	target := path.trim_right('/')438	covered := covered_by(store, target, only_save)!439	rewrite_saves(store, target, only_save)!440	store.drop_unreachable_manifests()!441	return covered.files442}443444// covered_by counts the files `path` reaches, the saves that hold them and the445// distinct content they carry.446fn covered_by(store &storage.Store, path string, only_save string) !Covered {447	mut files := 0448	mut saves := 0449	mut hashes := map[string]bool{}450	mut memo := map[string]Subtree{}451	mut busy := map[string]bool{}452	for tree in save_trees(store, only_save)! {453		found := find_entry(store, tree.manifest, path)!454		if found.ok {455			entry := found.entry456			mut here := 0457			if entry.kind == storage.file_kind {458				here = 1459				hashes[entry.hash] = true460			} else {461				summary := subtree(store, entry.manifest, mut memo, mut busy)!462				here = summary.files463				for hash in summary.hashes {464					hashes[hash] = true465				}466			}467			if here > 0 {468				files += here469				saves++470			}471		}472	}473	mut distinct := hashes.keys()474	distinct.sort()475	return Covered{476		files:  files477		saves:  saves478		hashes: distinct479	}480}481482// Rewriter rebuilds the folders on one path without mutating a row. The memo483// keeps old folder hash to new, so identical subtrees are rewritten once.484struct Rewriter {485mut:486	memo map[string]string487	busy map[string]bool488}489490struct Rewritten {491	changed bool492	hash    string493}494495// rewrite returns `hash` with `path` removed, or unchanged when the tree does496// not hold it.497fn (mut r Rewriter) rewrite(store &storage.Store, hash string, path string) !Rewritten {498	key := '${hash}\x00${path}'499	if key in r.memo {500		found := r.memo[key]501		if found == '' {502			return Rewritten{}503		}504		return Rewritten{505			changed: true506			hash:    found507		}508	}509	if r.busy[key] {510		return error('manifest ${hash} refers to itself')511	}512	r.busy[key] = true513	entries := store.manifest_entries(hash)!514	mut kept := []storage.ManifestEntry{}515	mut exact := false516	for entry in entries {517		if entry.name == path {518			exact = true519		}520	}521	if exact {522		for entry in entries {523			if entry.name != path {524				kept << entry525			}526		}527	} else {528		slash := path.index('/') or { -1 }529		if slash < 0 {530			r.miss(key)531			return Rewritten{}532		}533		segment := path[..slash]534		mut at := -1535		for i, entry in entries {536			if entry.name == segment && entry.kind == storage.folder_kind {537				at = i538				break539			}540		}541		if at < 0 {542			r.miss(key)543			return Rewritten{}544		}545		child := r.rewrite(store, entries[at].manifest, path[slash + 1..])!546		if child.changed {547			kept = entries.clone()548			kept[at] = storage.ManifestEntry{549				name:     entries[at].name550				kind:     storage.folder_kind551				manifest: child.hash552			}553		} else {554			r.miss(key)555			return Rewritten{}556		}557	}558	new_hash := store.put_manifest(json2.encode(storage.Manifest{559		entries: kept560	}))!561	r.busy.delete(key)562	r.memo[key] = new_hash563	return Rewritten{564		changed: true565		hash:    new_hash566	}567}568569// miss remembers that this folder does not hold the path.570fn (mut r Rewriter) miss(key string) {571	r.busy.delete(key)572	r.memo[key] = ''573}574575// rewrite_saves points every save that holds `path` at its rewritten root.576// A save whose tree does not hold the path is not touched.577fn rewrite_saves(store &storage.Store, path string, only_save string) ! {578	mut rewriter := Rewriter{}579	mut update := store.db.prepare('UPDATE saves SET manifest = ? WHERE id = ?')!580	defer {581		update.finalize()582	}583	for tree in save_trees(store, only_save)! {584		rewritten := rewriter.rewrite(store, tree.manifest, path)!585		if rewritten.changed {586			update.bind_text(1, rewritten.hash)!587			update.bind_text(2, tree.id)!588			update.step()!589			update.reset()590		}591	}592}