//! Manifests: one folder's immediate entries, content-addressed. //! //! A save names its root manifest. Each folder is one row whose hash is the //! Blake3 of its canonical body, so a folder two saves share is stored once, //! and changing one file only writes the folders on its path. module storage import json2 pub const file_kind = 'file' pub const folder_kind = 'folder' // One immediate entry: a file names its object, a folder names its manifest. pub struct ManifestEntry { pub: name string kind string hash string size i64 executable bool manifest string } // The canonical body. Field order is the encoding, so it is the schema. pub struct Manifest { pub: entries []ManifestEntry } // One file in a flattened tree, with its repo-relative path. pub struct ManifestFile { pub: path string hash string size i64 executable bool } // put_manifest stores a body and returns its hash. An identical body is // already there, so writing it again is a no-op. pub fn (s &Store) put_manifest(body string) !string { hash := hash_hex(body.bytes()) mut stmt := s.db.prepare('INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)')! defer { stmt.finalize() } stmt.bind_text(1, hash)! stmt.bind_text(2, body)! stmt.step()! return hash } pub fn (s &Store) manifest_body(hash string) !string { mut stmt := s.db.prepare('SELECT body FROM manifests WHERE hash = ?')! defer { stmt.finalize() } stmt.bind_text(1, hash)! if !stmt.step()! { return error('manifest ${hash} is missing') } return stmt.text(0) } // decode_manifest checks the shape every reader depends on: a known kind, and // the field that kind requires. Names are not checked — a damaged tree keeps // its odd names so a strip can still name and remove one. fn decode_manifest(body string) ![]ManifestEntry { decoded := json2.decode[Manifest](body) or { return error('its body is not readable: ${err.msg()}') } for entry in decoded.entries { if entry.name == '' { return error('it has an entry with no name') } if entry.kind == file_kind { if !valid_hash(entry.hash) { return error('its entry ${entry.name} has an invalid object hash ${entry.hash}') } if entry.size < 0 { return error('its entry ${entry.name} has a negative size') } } else if entry.kind == folder_kind { if !valid_hash(entry.manifest) { return error('its entry ${entry.name} has an invalid manifest hash ${entry.manifest}') } } else { return error('its entry ${entry.name} has unknown kind "${entry.kind}"') } } return decoded.entries } pub fn (s &Store) manifest_entries(hash string) ![]ManifestEntry { body := s.manifest_body(hash)! return decode_manifest(body) or { return error('manifest ${hash} is invalid: ${err.msg()}') } } // manifest_tree builds and stores the folders of `files` (repo-relative, // `/`-separated) and returns the root hash. pub fn (s &Store) manifest_tree(files []ManifestFile) !string { mut sorted := files.clone() sorted.sort(a.path < b.path) return s.manifest_level('', sorted) } fn (s &Store) manifest_level(prefix string, files []ManifestFile) !string { mut entries := []ManifestEntry{} mut i := 0 for i < files.len { rest := files[i].path[prefix.len..] slash := rest.index('/') or { -1 } if slash < 0 { entries << ManifestEntry{ name: rest kind: file_kind hash: files[i].hash size: files[i].size executable: files[i].executable } i++ continue } name := rest[..slash] start := i for i < files.len && segment_at(files[i].path, prefix) == name { i++ } child := s.manifest_level('${prefix}${name}/', files[start..i])! entries << ManifestEntry{ name: name kind: folder_kind manifest: child } } entries.sort_with_compare(fn (a &ManifestEntry, b &ManifestEntry) int { if a.name != b.name { return if a.name < b.name { -1 } else { 1 } } return kind_rank(a.kind) - kind_rank(b.kind) }) return s.put_manifest(json2.encode(Manifest{ entries: entries }))! } fn segment_at(path string, prefix string) string { rest := path[prefix.len..] slash := rest.index('/') or { -1 } return if slash < 0 { rest } else { rest[..slash] } } fn kind_rank(kind string) int { return if kind == file_kind { 0 } else { 1 } } // manifest_files flattens a tree back to sorted repo-relative paths. pub fn (s &Store) manifest_files(root string) ![]ManifestFile { mut files := []ManifestFile{} s.manifest_flatten(root, '', mut files, []string{})! files.sort(a.path < b.path) return files } fn (s &Store) manifest_flatten(hash string, prefix string, mut out []ManifestFile, ancestors []string) ! { if hash in ancestors { return error('manifest ${hash} refers to itself') } mut deeper := ancestors.clone() deeper << hash entries := s.manifest_entries(hash)! for entry in entries { if entry.kind == file_kind { out << ManifestFile{ path: prefix + entry.name hash: entry.hash size: entry.size executable: entry.executable } } else { s.manifest_flatten(entry.manifest, '${prefix}${entry.name}/', mut out, deeper)! } } } // flatten_bodies flattens a tree from bodies read off the remote. A tree that // names itself is refused rather than walked forever. pub fn flatten_bodies(bodies map[string]string, root string) ![]ManifestFile { mut files := []ManifestFile{} flatten_body(bodies, root, '', mut files, []string{})! files.sort(a.path < b.path) return files } fn flatten_body(bodies map[string]string, hash string, prefix string, mut out []ManifestFile, ancestors []string) ! { if hash in ancestors { return error('manifest ${hash} refers to itself') } body := bodies[hash] or { return error('manifest ${hash} is missing') } entries := decode_manifest(body) or { return error('manifest ${hash} is invalid: ${err.msg()}') } mut deeper := ancestors.clone() deeper << hash for entry in entries { if entry.kind == file_kind { out << ManifestFile{ path: prefix + entry.name hash: entry.hash size: entry.size executable: entry.executable } } else { flatten_body(bodies, entry.manifest, '${prefix}${entry.name}/', mut out, deeper)! } } } pub fn (s &Store) manifest_count() !i64 { mut stmt := s.db.prepare('SELECT COUNT(*) FROM manifests')! defer { stmt.finalize() } if !stmt.step()! { return 0 } return stmt.int(0) } // manifest_bodies lists every stored body in hash order, for Doctor. pub fn (s &Store) manifest_bodies() ![]string { mut stmt := s.db.prepare('SELECT body FROM manifests ORDER BY hash')! defer { stmt.finalize() } mut bodies := []string{} for stmt.step()! { bodies << stmt.text(0) } return bodies } // manifest_object_hashes is every object any stored manifest names, in one pass. // A damaged manifest is an error: with the reference set unknown, nothing may // conclude an object is unused. fn (s &Store) manifest_object_hashes() !map[string]bool { mut used := map[string]bool{} mut stmt := s.db.prepare('SELECT hash, body FROM manifests')! defer { stmt.finalize() } for stmt.step()! { hash := stmt.text(0) entries := decode_manifest(stmt.text(1)) or { return error('manifest ${hash} is invalid: ${err.msg()}') } for entry in entries { if entry.kind == file_kind { used[entry.hash] = true } } } return used } // drop_unreachable_manifests removes folder rows no save's tree reaches. A // rewrite replaces the folders on one path and never mutates a row, so the // old ones would otherwise keep naming objects nothing uses. pub fn (s &Store) drop_unreachable_manifests() !i64 { mut reachable := map[string]bool{} mut roots := s.db.prepare('SELECT DISTINCT manifest FROM saves')! for roots.step()! { s.mark_manifest(roots.text(0), mut reachable)! } roots.finalize() mut hashes := s.db.prepare('SELECT hash FROM manifests')! mut stale := []string{} for hashes.step()! { hash := hashes.text(0) if hash !in reachable { stale << hash } } hashes.finalize() mut delete := s.db.prepare('DELETE FROM manifests WHERE hash = ?')! defer { delete.finalize() } mut dropped := i64(0) for hash in stale { delete.bind_text(1, hash)! delete.step()! delete.reset() dropped += s.db.changes() } return dropped } fn (s &Store) mark_manifest(hash string, mut reachable map[string]bool) ! { if hash in reachable { return } reachable[hash] = true entries := s.manifest_entries(hash)! for entry in entries { if entry.kind == folder_kind { s.mark_manifest(entry.manifest, mut reachable)! } } }