manifest.v

8.4 KB · raw

1//! Manifests: one folder's immediate entries, content-addressed.2//!3//! A save names its root manifest. Each folder is one row whose hash is the4//! Blake3 of its canonical body, so a folder two saves share is stored once,5//! and changing one file only writes the folders on its path.67module storage89import json21011pub const file_kind = 'file'12pub const folder_kind = 'folder'1314// One immediate entry: a file names its object, a folder names its manifest.15pub struct ManifestEntry {16pub:17	name       string18	kind       string19	hash       string20	size       i6421	executable bool22	manifest   string23}2425// The canonical body. Field order is the encoding, so it is the schema.26pub struct Manifest {27pub:28	entries []ManifestEntry29}3031// One file in a flattened tree, with its repo-relative path.32pub struct ManifestFile {33pub:34	path       string35	hash       string36	size       i6437	executable bool38}3940// put_manifest stores a body and returns its hash. An identical body is41// already there, so writing it again is a no-op.42pub fn (s &Store) put_manifest(body string) !string {43	hash := hash_hex(body.bytes())44	mut stmt := s.db.prepare('INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)')!45	defer {46		stmt.finalize()47	}48	stmt.bind_text(1, hash)!49	stmt.bind_text(2, body)!50	stmt.step()!51	return hash52}5354pub fn (s &Store) manifest_body(hash string) !string {55	mut stmt := s.db.prepare('SELECT body FROM manifests WHERE hash = ?')!56	defer {57		stmt.finalize()58	}59	stmt.bind_text(1, hash)!60	if !stmt.step()! {61		return error('manifest ${hash} is missing')62	}63	return stmt.text(0)64}6566// decode_manifest checks the shape every reader depends on: a known kind, and67// the field that kind requires. Names are not checked — a damaged tree keeps68// its odd names so a strip can still name and remove one.69fn decode_manifest(body string) ![]ManifestEntry {70	decoded := json2.decode[Manifest](body) or {71		return error('its body is not readable: ${err.msg()}')72	}73	for entry in decoded.entries {74		if entry.name == '' {75			return error('it has an entry with no name')76		}77		if entry.kind == file_kind {78			if !valid_hash(entry.hash) {79				return error('its entry ${entry.name} has an invalid object hash ${entry.hash}')80			}81			if entry.size < 0 {82				return error('its entry ${entry.name} has a negative size')83			}84		} else if entry.kind == folder_kind {85			if !valid_hash(entry.manifest) {86				return error('its entry ${entry.name} has an invalid manifest hash ${entry.manifest}')87			}88		} else {89			return error('its entry ${entry.name} has unknown kind "${entry.kind}"')90		}91	}92	return decoded.entries93}9495pub fn (s &Store) manifest_entries(hash string) ![]ManifestEntry {96	body := s.manifest_body(hash)!97	return decode_manifest(body) or { return error('manifest ${hash} is invalid: ${err.msg()}') }98}99100// manifest_tree builds and stores the folders of `files` (repo-relative,101// `/`-separated) and returns the root hash.102pub fn (s &Store) manifest_tree(files []ManifestFile) !string {103	mut sorted := files.clone()104	sorted.sort(a.path < b.path)105	return s.manifest_level('', sorted)106}107108fn (s &Store) manifest_level(prefix string, files []ManifestFile) !string {109	mut entries := []ManifestEntry{}110	mut i := 0111	for i < files.len {112		rest := files[i].path[prefix.len..]113		slash := rest.index('/') or { -1 }114		if slash < 0 {115			entries << ManifestEntry{116				name:       rest117				kind:       file_kind118				hash:       files[i].hash119				size:       files[i].size120				executable: files[i].executable121			}122			i++123			continue124		}125		name := rest[..slash]126		start := i127		for i < files.len && segment_at(files[i].path, prefix) == name {128			i++129		}130		child := s.manifest_level('${prefix}${name}/', files[start..i])!131		entries << ManifestEntry{132			name:     name133			kind:     folder_kind134			manifest: child135		}136	}137	entries.sort_with_compare(fn (a &ManifestEntry, b &ManifestEntry) int {138		if a.name != b.name {139			return if a.name < b.name { -1 } else { 1 }140		}141		return kind_rank(a.kind) - kind_rank(b.kind)142	})143	return s.put_manifest(json2.encode(Manifest{144		entries: entries145	}))!146}147148fn segment_at(path string, prefix string) string {149	rest := path[prefix.len..]150	slash := rest.index('/') or { -1 }151	return if slash < 0 { rest } else { rest[..slash] }152}153154fn kind_rank(kind string) int {155	return if kind == file_kind { 0 } else { 1 }156}157158// manifest_files flattens a tree back to sorted repo-relative paths.159pub fn (s &Store) manifest_files(root string) ![]ManifestFile {160	mut files := []ManifestFile{}161	s.manifest_flatten(root, '', mut files, []string{})!162	files.sort(a.path < b.path)163	return files164}165166fn (s &Store) manifest_flatten(hash string, prefix string, mut out []ManifestFile, ancestors []string) ! {167	if hash in ancestors {168		return error('manifest ${hash} refers to itself')169	}170	mut deeper := ancestors.clone()171	deeper << hash172	entries := s.manifest_entries(hash)!173	for entry in entries {174		if entry.kind == file_kind {175			out << ManifestFile{176				path:       prefix + entry.name177				hash:       entry.hash178				size:       entry.size179				executable: entry.executable180			}181		} else {182			s.manifest_flatten(entry.manifest, '${prefix}${entry.name}/', mut out, deeper)!183		}184	}185}186187// flatten_bodies flattens a tree from bodies read off the remote. A tree that188// names itself is refused rather than walked forever.189pub fn flatten_bodies(bodies map[string]string, root string) ![]ManifestFile {190	mut files := []ManifestFile{}191	flatten_body(bodies, root, '', mut files, []string{})!192	files.sort(a.path < b.path)193	return files194}195196fn flatten_body(bodies map[string]string, hash string, prefix string, mut out []ManifestFile, ancestors []string) ! {197	if hash in ancestors {198		return error('manifest ${hash} refers to itself')199	}200	body := bodies[hash] or { return error('manifest ${hash} is missing') }201	entries := decode_manifest(body) or { return error('manifest ${hash} is invalid: ${err.msg()}') }202	mut deeper := ancestors.clone()203	deeper << hash204	for entry in entries {205		if entry.kind == file_kind {206			out << ManifestFile{207				path:       prefix + entry.name208				hash:       entry.hash209				size:       entry.size210				executable: entry.executable211			}212		} else {213			flatten_body(bodies, entry.manifest, '${prefix}${entry.name}/', mut out, deeper)!214		}215	}216}217218pub fn (s &Store) manifest_count() !i64 {219	mut stmt := s.db.prepare('SELECT COUNT(*) FROM manifests')!220	defer {221		stmt.finalize()222	}223	if !stmt.step()! {224		return 0225	}226	return stmt.int(0)227}228229// manifest_bodies lists every stored body in hash order, for Doctor.230pub fn (s &Store) manifest_bodies() ![]string {231	mut stmt := s.db.prepare('SELECT body FROM manifests ORDER BY hash')!232	defer {233		stmt.finalize()234	}235	mut bodies := []string{}236	for stmt.step()! {237		bodies << stmt.text(0)238	}239	return bodies240}241242// manifest_object_hashes is every object any stored manifest names, in one pass.243// A damaged manifest is an error: with the reference set unknown, nothing may244// conclude an object is unused.245fn (s &Store) manifest_object_hashes() !map[string]bool {246	mut used := map[string]bool{}247	mut stmt := s.db.prepare('SELECT hash, body FROM manifests')!248	defer {249		stmt.finalize()250	}251	for stmt.step()! {252		hash := stmt.text(0)253		entries := decode_manifest(stmt.text(1)) or {254			return error('manifest ${hash} is invalid: ${err.msg()}')255		}256		for entry in entries {257			if entry.kind == file_kind {258				used[entry.hash] = true259			}260		}261	}262	return used263}264265// drop_unreachable_manifests removes folder rows no save's tree reaches. A266// rewrite replaces the folders on one path and never mutates a row, so the267// old ones would otherwise keep naming objects nothing uses.268pub fn (s &Store) drop_unreachable_manifests() !i64 {269	mut reachable := map[string]bool{}270	mut roots := s.db.prepare('SELECT DISTINCT manifest FROM saves')!271	for roots.step()! {272		s.mark_manifest(roots.text(0), mut reachable)!273	}274	roots.finalize()275	mut hashes := s.db.prepare('SELECT hash FROM manifests')!276	mut stale := []string{}277	for hashes.step()! {278		hash := hashes.text(0)279		if hash !in reachable {280			stale << hash281		}282	}283	hashes.finalize()284	mut delete := s.db.prepare('DELETE FROM manifests WHERE hash = ?')!285	defer {286		delete.finalize()287	}288	mut dropped := i64(0)289	for hash in stale {290		delete.bind_text(1, hash)!291		delete.step()!292		delete.reset()293		dropped += s.db.changes()294	}295	return dropped296}297298fn (s &Store) mark_manifest(hash string, mut reachable map[string]bool) ! {299	if hash in reachable {300		return301	}302	reachable[hash] = true303	entries := s.manifest_entries(hash)!304	for entry in entries {305		if entry.kind == folder_kind {306			s.mark_manifest(entry.manifest, mut reachable)!307		}308	}309}