doctor_repair.v

7.7 KB · raw

1//! Doctor's repairs (spec §7.6.2). Each one puts back verified data or2//! finishes interrupted work; none changes what a save contains.34module cli56import compress.zlib7import os8import src.exchange9import src.fmt10import src.history11import src.machine12import src.snapshot13import src.storage1415struct DoctorRepair {16	action string17	run    fn () ! @[required]18}1920fn plan_repairs(store &storage.Store, report DoctorJson) []DoctorRepair {21	mut repairs := []DoctorRepair{}22	has_remote := report.source != '' || machine.has_remote()23	// A source is read-only, so only this machine's own remote takes uploads.24	writable_remote := report.source == '' && machine.has_remote()25	source, remote_repo := report.source, report.remote_repo26	if report.checks.any(it.name == 'SQLite integrity' && it.status == 'fail') {27		repairs << DoctorRepair{'rebuild the database indexes', fn [store] () ! {28			store.db.exec('REINDEX')!29		}}30	}31	if report.damaged_objects.len > 0 {32		hashes := report.damaged_objects33		repairs << DoctorRepair{'restore ${fmt.plural(hashes.len, 'damaged or missing object')} from verified copies', fn [store, hashes, source, remote_repo] () ! {34			repair_objects(store, hashes, source, remote_repo)!35		}}36	}37	if report.missing_saves.len > 0 && has_remote {38		ids := report.missing_saves39		repairs << DoctorRepair{'fetch ${fmt.plural(ids.len, 'missing save')} from the remote', fn [store, ids, source, remote_repo] () ! {40			mut backend, repo := doctor_backend(store, source, remote_repo)!41			exchange.fetch_missing(store, mut backend, repo, ids)!42		}}43	} else if report.metadata_available && report.saves > 0 && report.head.id == '' {44		// A remote may hold a newer head; only a full, stable audit that found45		// none other there lets Doctor guess, and the remote is asked again.46		audited := !report.checks.any(it.name in ['remote audit', 'remote stability']47			&& it.status != 'pass')48		tip := only_tip(store) or { '' }49		seen := report.head_id50		if tip != '' && (!has_remote || (audited && report.remote_head in ['', tip])) {51			repairs << DoctorRepair{'point head at [${tip}], the only save nothing follows', fn [store, tip, seen, has_remote, source, remote_repo] () ! {52				if has_remote {53					mut backend, repo := doctor_backend(store, source, remote_repo)!54					theirs := backend.get(exchange.head_key(repo))!55					if theirs.found && theirs.body.bytestr().trim_space() != tip {56						return error('the remote now has another head; run koh doctor again')57					}58				}59				store.begin()!60				set_only_tip(store, tip, seen) or {61					store.rollback()62					return err63				}64				store.end()!65			}}66		}67	}68	if report.strip_residue {69		repairs << DoctorRepair{'remove stripped paths that saves still hold', fn [store] () ! {70			exchange.reapply_strips(store)!71		}}72	}73	if report.restore_unfinished {74		repairs << DoctorRepair{'finish the interrupted restore (koh revert keeps the current files in a checkpoint)', fn [store] () ! {75			finish_restore(store)!76		}}77	}78	if report.pending_strips.len > 0 && writable_remote {79		paths := report.pending_strips80		repairs << DoctorRepair{'send ${fmt.plural(paths.len, 'unfinished strip')} to the remote', fn [store, paths, remote_repo] () ! {81			mut backend, _ := doctor_backend(store, '', remote_repo)!82			for index, path in paths {83				exchange.send_strip(store, mut backend, path) or {84					return partial('sent', index, 'unfinished strip', err)85				}86			}87		}}88	}89	// With damaged rows an unused object may be the only copy of saved content.90	if report.unreferenced_objects > 0 && report.problems.len == 0 {91		repairs << DoctorRepair{'delete ${fmt.plural(int(report.unreferenced_objects), 'object')} no save uses', fn [store] () ! {92			store.begin()!93			store.drop_unreferenced_objects() or {94				store.rollback()95				return err96			}97			store.end()!98		}}99	}100	if writable_remote {101		hashes := report.remote_bad_objects.filter(stored_intact(store, it))102		ids := report.remote_missing_saves.filter(history.by_id(store, it) != none)103		if hashes.len + ids.len > 0 {104			repairs << DoctorRepair{'upload ${fmt.plural(hashes.len, 'object')} and ${fmt.plural(ids.len, 'save')} the remote lacks or holds damaged', fn [store, hashes, ids, remote_repo] () ! {105				mut backend, repo := doctor_backend(store, '', remote_repo)!106				exchange.resend(store, mut backend, repo, hashes, ids)!107			}}108		}109	}110	return repairs111}112113// PartialRepair is a repair that wrote some of its changes before it failed;114// Doctor reports both halves.115struct PartialRepair {116	Error117	done   string118	reason string119}120121fn (e PartialRepair) msg() string {122	return e.reason123}124125// Each copy must hash back to its key before it replaces anything: first the126// stored bytes (only the size was wrong), then working files, then the remote.127fn repair_objects(store &storage.Store, hashes []string, source string, remote_repo string) ! {128	mut lost := []string{}129	for index, hash in hashes {130		restored := restore_object(store, hash, source, remote_repo) or {131			return partial('restored', index - lost.len, 'damaged or missing object', err)132		}133		if !restored {134			lost << hash135		}136	}137	if lost.len > 0 {138		failure := error('no verified copy here or on the remote of ${lost.join(', ')}')139		return partial('restored', hashes.len - lost.len, 'damaged or missing object', failure)140	}141}142143// partial reports the `done` items a repair finished before `failure`, if any.144fn partial(verb string, done int, noun string, failure IError) IError {145	if done == 0 {146		return failure147	}148	return PartialRepair{149		done:   '${verb} ${fmt.plural(done, noun)}'150		reason: failure.msg()151	}152}153154fn restore_object(store &storage.Store, hash string, source string, remote_repo string) !bool {155	if data := local_copy(store, hash) {156		store.repair_object(hash, data)!157		return true158	}159	if source == '' && !machine.has_remote() {160		return false161	}162	mut backend, repo := doctor_backend(store, source, remote_repo)!163	blob := backend.get(exchange.object_key(repo, hash))!164	data := zlib.decompress(blob.body) or { return false }165	if !blob.found || storage.hash_hex(data) != hash {166		return false167	}168	store.repair_object(hash, data)!169	return true170}171172fn stored_intact(store &storage.Store, hash string) bool {173	store.get_object(hash) or { return false }174	return true175}176177fn local_copy(store &storage.Store, hash string) ?[]u8 {178	if data := store.get_object(hash) {179		return data180	}181	for path in store.paths_of_object(hash) or { return none } {182		if !snapshot.legal_path(path) {183			continue184		}185		data := os.read_bytes(os.join_path(store.root, path)) or { continue }186		if storage.hash_hex(data) == hash {187			return data188		}189	}190	return none191}192193// A head lost with no remote copy can only be guessed safely when exactly one194// save has no successor.195fn only_tip(store &storage.Store) ?string {196	saves := history.all_saves(store) or { return none }197	mut parents := map[string]bool{}198	for save in saves {199		parents[save.parent] = true200	}201	tips := saves.filter(it.id !in parents)202	return if tips.len == 1 { tips[0].id } else { none }203}204205// Another koh command may have saved while Doctor asked; the tip seen then206// is the head only if nothing has changed since.207fn set_only_tip(store &storage.Store, tip string, seen string) ! {208	if (store.state(storage.head_key) or { '' }) != seen || (only_tip(store) or { '' }) != tip {209		return error('history changed since Doctor checked it; run koh doctor again')210	}211	history.set_head(store, tip)!212}213214// The same steps as koh revert, without its output, which would break --json.215fn finish_restore(store &storage.Store) ! {216	head := history.head(store) or { return error('this repo has no head to restore') }217	if !compare_with_head(store, head)!.dirty {218		snapshot.clear_restore_mark(store)!219		return220	}221	plan := plan_restore(store, head)!222	apply_restore(store, head, 'revert', plan, true)!223	snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files, plan.remove)!224}