doctor_repair.v

6.8 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 audit that found none45		// other there lets Doctor guess.46		audited := !report.checks.any(it.name == 'remote audit')47		tip := only_tip(store) or { '' }48		seen := report.head_id49		if tip != '' && (!has_remote || (audited && report.remote_head in ['', tip])) {50			repairs << DoctorRepair{'point head at [${tip}], the only save nothing follows', fn [store, tip, seen] () ! {51				store.begin()!52				set_only_tip(store, tip, seen) or {53					store.rollback()54					return err55				}56				store.end()!57			}}58		}59	}60	if report.strip_residue {61		repairs << DoctorRepair{'remove stripped paths that saves still hold', fn [store] () ! {62			exchange.reapply_strips(store)!63		}}64	}65	if report.restore_unfinished {66		repairs << DoctorRepair{'finish the interrupted restore (koh revert keeps the current files in a checkpoint)', fn [store] () ! {67			finish_restore(store)!68		}}69	}70	if report.pending_strips.len > 0 && writable_remote {71		paths := report.pending_strips72		repairs << DoctorRepair{'send ${fmt.plural(paths.len, 'unfinished strip')} to the remote', fn [store, paths, remote_repo] () ! {73			mut backend, _ := doctor_backend(store, '', remote_repo)!74			for path in paths {75				exchange.send_strip(store, mut backend, path)!76			}77		}}78	}79	// With damaged rows an unused object may be the only copy of saved content.80	if report.unreferenced_objects > 0 && report.problems.len == 0 {81		repairs << DoctorRepair{'delete ${fmt.plural(int(report.unreferenced_objects), 'object')} no save uses', fn [store] () ! {82			store.begin()!83			store.drop_unreferenced_objects() or {84				store.rollback()85				return err86			}87			store.end()!88		}}89	}90	if writable_remote {91		hashes := report.remote_bad_objects.filter(stored_intact(store, it))92		ids := report.remote_missing_saves.filter(history.by_id(store, it) != none)93		if hashes.len + ids.len > 0 {94			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] () ! {95				mut backend, repo := doctor_backend(store, '', remote_repo)!96				exchange.resend(store, mut backend, repo, hashes, ids)!97			}}98		}99	}100	return repairs101}102103// PartialRepair is a repair that wrote some of its changes before it failed;104// Doctor reports both halves.105struct PartialRepair {106	Error107	done   string108	reason string109}110111fn (e PartialRepair) msg() string {112	return e.reason113}114115// Each copy must hash back to its key before it replaces anything: first the116// stored bytes (only the size was wrong), then working files, then the remote.117fn repair_objects(store &storage.Store, hashes []string, source string, remote_repo string) ! {118	mut lost := []string{}119	for hash in hashes {120		if data := local_copy(store, hash) {121			store.repair_object(hash, data)!122			continue123		}124		if source == '' && !machine.has_remote() {125			lost << hash126			continue127		}128		mut backend, repo := doctor_backend(store, source, remote_repo)!129		blob := backend.get(exchange.object_key(repo, hash))!130		data := zlib.decompress(blob.body) or { []u8{} }131		if !blob.found || storage.hash_hex(data) != hash {132			lost << hash133			continue134		}135		store.repair_object(hash, data)!136	}137	if lost.len > 0 {138		reason := 'no verified copy here or on the remote of ${lost.join(', ')}'139		if lost.len < hashes.len {140			return PartialRepair{141				done:   'restore ${fmt.plural(hashes.len - lost.len, 'damaged or missing object')} from verified copies'142				reason: reason143			}144		}145		return error(reason)146	}147}148149fn stored_intact(store &storage.Store, hash string) bool {150	store.get_object(hash) or { return false }151	return true152}153154fn local_copy(store &storage.Store, hash string) ?[]u8 {155	if data := store.get_object(hash) {156		return data157	}158	for path in store.paths_of_object(hash) or { return none } {159		if !snapshot.legal_path(path) {160			continue161		}162		data := os.read_bytes(os.join_path(store.root, path)) or { continue }163		if storage.hash_hex(data) == hash {164			return data165		}166	}167	return none168}169170// A head lost with no remote copy can only be guessed safely when exactly one171// save has no successor.172fn only_tip(store &storage.Store) ?string {173	saves := history.all_saves(store) or { return none }174	mut parents := map[string]bool{}175	for save in saves {176		parents[save.parent] = true177	}178	tips := saves.filter(it.id !in parents)179	return if tips.len == 1 { tips[0].id } else { none }180}181182// Another koh command may have saved while Doctor asked; the tip seen then183// is the head only if nothing has changed since.184fn set_only_tip(store &storage.Store, tip string, seen string) ! {185	if (store.state(storage.head_key) or { '' }) != seen || (only_tip(store) or { '' }) != tip {186		return error('history changed since Doctor checked it; run koh doctor again')187	}188	history.set_head(store, tip)!189}190191// The same steps as koh revert, without its output, which would break --json.192fn finish_restore(store &storage.Store) ! {193	head := history.head(store) or { return error('this repo has no head to restore') }194	if !compare_with_head(store, head)!.dirty {195		snapshot.clear_restore_mark(store)!196		return197	}198	plan := plan_restore(store, head)!199	apply_restore(store, head, 'revert', plan, true)!200	snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files, plan.remove)!201}