doctor.v

2.7 KB · raw

1//! Repository structure and storage measurements used by Doctor.2module storage34/// Storage counts and structural findings from one database snapshot.5pub struct DoctorStats {6pub mut:7	objects      i648	saves        i649	checkpoints  i6410	cached_files i6411	manifests    i6412	object_bytes i6413	packed_bytes i6414	unused       i6415	pending      []string16	state        map[string]string17	problems     []string18}1920/// Inspect references, scalar storage invariants and machine-local state.21pub fn (s &Store) doctor_stats() !DoctorStats {22	mut out := DoctorStats{}23	mut sizes := s.db.prepare('SELECT COUNT(*), COALESCE(SUM(size), 0),24		COALESCE(SUM(length(data)), 0) FROM objects')!25	defer { sizes.finalize() }26	if sizes.step()! {27		out.objects = sizes.int(0)28		out.object_bytes = sizes.int(1)29		out.packed_bytes = sizes.int(2)30	}31	mut counts := s.db.prepare('SELECT32		(SELECT COUNT(*) FROM saves),33		(SELECT COUNT(*) FROM saves WHERE is_checkpoint = 1),34		(SELECT COUNT(*) FROM file_cache),35		(SELECT COUNT(*) FROM manifests)')!36	defer { counts.finalize() }37	if counts.step()! {38		out.saves = counts.int(0)39		out.checkpoints = counts.int(1)40		out.cached_files = counts.int(2)41		out.manifests = counts.int(3)42	}43	used := s.manifest_object_hashes()!44	mut objects := s.db.prepare('SELECT hash FROM objects')!45	defer { objects.finalize() }46	for objects.step()! {47		if objects.text(0) !in used {48			out.unused++49		}50	}51	mut foreign := s.db.prepare('PRAGMA foreign_key_check')!52	defer { foreign.finalize() }53	for foreign.step()! {54		out.problems << 'broken reference in ${foreign.text(0)} row ${foreign.int(1)} to ${foreign.text(2)}'55	}56	mut invalid := s.db.prepare("SELECT id FROM saves57		WHERE is_checkpoint NOT IN (0, 1)58		OR typeof(is_checkpoint) != 'integer'59		OR id = ''60		OR typeof(created_at) != 'integer'61		OR created_at < 062		OR typeof(size_bytes) != 'integer'63		OR size_bytes < 0")!64	defer { invalid.finalize() }65	for invalid.step()! {66		out.problems << 'invalid metadata in save ${invalid.text(0)}'67	}68	mut manifests := s.db.prepare('SELECT hash, body FROM manifests')!69	defer { manifests.finalize() }70	for manifests.step()! {71		hash := manifests.text(0)72		body := manifests.text(1)73		if hash_hex(body.bytes()) != hash {74			out.problems << 'invalid metadata in manifest ${hash}: its hash does not match its body'75			continue76		}77		decode_manifest(body) or {78			out.problems << 'invalid metadata in manifest ${hash}: ${err.msg()}'79		}80	}81	mut state := s.db.prepare('SELECT key, value FROM state')!82	defer { state.finalize() }83	for state.step()! {84		key := state.text(0)85		out.state[key] = state.text(1)86		if key.starts_with('strip_pending:') {87			out.pending << key.all_after('strip_pending:')88		}89	}90	out.pending.sort()91	return out92}