objects.v

7.5 KB · raw

1//! The object table: content-addressed file bytes.2//!3//! Objects are Blake3-addressed and stored zlib-compressed, exactly as Koh 24//! stored them on disk, so the same bytes migrate without a re-hash and a5//! future reader can decompress them with any zlib. Objects are shared between6//! saves: identical content is stored once.78module storage910import compress.zlib11import crypto.blake31213pub const max_file_size = 512 * 1024 * 10241415struct InflateSink {16mut:17	out     []u818	limit   int19	aborted bool20}2122// inflate_bounded decompresses a blob that came from a remote. Its size on the23// wire says nothing about its size in memory, so inflation stops once the24// total would pass `limit` rather than letting a small blob expand. An aborted25// stream skips checksum verification, which is fine: callers check the content26// hash of what they get back.27pub fn inflate_bounded(blob []u8, limit int) ![]u8 {28	mut sink := &InflateSink{29		limit: limit30	}31	zlib.decompress_with_callback(blob, fn (chunk []u8, sink &InflateSink) int {32		if sink.out.len + chunk.len > sink.limit {33			unsafe {34				sink.aborted = true35			}36			return 037		}38		unsafe {39			sink.out << chunk40		}41		return chunk.len42	}, sink)!43	if sink.aborted {44		return error('object would inflate past ${limit} bytes')45	}46	return sink.out47}4849pub fn hash_hex(data []u8) string {50	return blake3.sum256(data).hex()51}5253// put_object stores `data` and returns its hash. Writing an object that is54// already present is a no-op, which is what makes repeated saves cheap.55pub fn (s &Store) put_object(data []u8) !string {56	hash := hash_hex(data)57	if s.has_object(hash)! {58		return hash59	}60	packed := zlib.compress(data)!61	mut stmt := s.db.prepare('INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)')!62	defer {63		stmt.finalize()64	}65	stmt.bind_text(1, hash)!66	stmt.bind_int(2, i64(data.len))!67	stmt.bind_blob(3, packed)!68	stmt.step()!69	return hash70}7172// object_blob returns the bytes exactly as they sit in the table — the73// zlib-compressed form a remote receives.74pub fn (s &Store) object_blob(hash string) ![]u8 {75	mut stmt := s.db.prepare('SELECT data FROM objects WHERE hash = ?')!76	defer {77		stmt.finalize()78	}79	stmt.bind_text(1, hash)!80	if !stmt.step()! {81		return error('object ${hash} is missing')82	}83	return stmt.blob(0)84}8586// put_object_blob stores a blob that came from a remote. The content is87// decompressed to check it hashes back to its key, and the blob itself is kept88// as it arrived.89pub fn (s &Store) put_object_blob(hash string, blob []u8) ! {90	if s.has_object(hash)! {91		return92	}93	data := inflate_bounded(blob, max_file_size) or {94		return error('object ${hash} is damaged: ${err.msg()}')95	}96	if hash_hex(data) != hash {97		return error('object ${hash} is damaged: it does not match its hash')98	}99	mut stmt := s.db.prepare('INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)')!100	defer {101		stmt.finalize()102	}103	stmt.bind_text(1, hash)!104	stmt.bind_int(2, i64(data.len))!105	stmt.bind_blob(3, blob)!106	stmt.step()!107}108109pub fn (s &Store) has_object(hash string) !bool {110	mut stmt := s.db.prepare('SELECT 1 FROM objects WHERE hash = ?')!111	defer {112		stmt.finalize()113	}114	stmt.bind_text(1, hash)!115	return stmt.step()!116}117118// get_object returns the uncompressed bytes and refuses anything that does not119// hash back to the key it was asked for.120pub fn (s &Store) get_object(hash string) ![]u8 {121	mut stmt := s.db.prepare('SELECT data FROM objects WHERE hash = ?')!122	defer {123		stmt.finalize()124	}125	stmt.bind_text(1, hash)!126	if !stmt.step()! {127		return error('object ${hash} is missing')128	}129	packed := stmt.blob(0)130	data := zlib.decompress(packed)!131	if hash_hex(data) != hash {132		return error('object ${hash} does not match its hash')133	}134	return data135}136137pub fn (s &Store) object_size(hash string) !i64 {138	mut stmt := s.db.prepare('SELECT size FROM objects WHERE hash = ?')!139	defer {140		stmt.finalize()141	}142	stmt.bind_text(1, hash)!143	if !stmt.step()! {144		return error('object ${hash} is missing')145	}146	return stmt.int(0)147}148149pub fn (s &Store) object_count() !i64 {150	mut stmt := s.db.prepare('SELECT COUNT(*) FROM objects')!151	defer {152		stmt.finalize()153	}154	if !stmt.step()! {155		return 0156	}157	return stmt.int(0)158}159160// drop_unreferenced_objects removes objects no save points at any more. Only161// `strip` leaves objects behind, so this is what makes a strip permanent.162pub fn (s &Store) drop_unreferenced_objects() !i64 {163	before := s.object_count()!164	mut stmt := s.db.prepare('DELETE FROM objects WHERE hash NOT IN (SELECT hash FROM save_files)')!165	defer {166		stmt.finalize()167	}168	stmt.step()!169	after := s.object_count()!170	return before - after171}172173// valid_hash is the shape of an object key: 64 lowercase hex characters, so it174// can name nothing but an object.175pub fn valid_hash(hash string) bool {176	return hash.len == 64 && hash.bytes().all((it >= `0` && it <= `9`) || (it >= `a` && it <= `f`))177}178179// drop_unused removes those of `hashes` no save points at any more. Other180// unused objects stay: with damaged rows one may be the only copy of saved181// content, and Doctor offers their removal separately.182pub fn (s &Store) drop_unused(hashes []string) !i64 {183	mut stmt := s.db.prepare('DELETE FROM objects WHERE hash = ?1184		AND NOT EXISTS (SELECT 1 FROM save_files WHERE hash = ?1)')!185	defer {186		stmt.finalize()187	}188	mut dropped := i64(0)189	for hash in hashes {190		stmt.reset()191		stmt.bind_text(1, hash)!192		stmt.step()!193		dropped += s.db.changes()194	}195	return dropped196}197198/// An object Doctor found damaged or missing.199pub struct ObjectProblem {200pub:201	hash   string202	detail string203}204205/// Verify every stored object's content hash and declared size.206pub fn (s &Store) check_objects() ![]ObjectProblem {207	mut problems := []ObjectProblem{}208	mut stmt := s.db.prepare('SELECT hash FROM objects ORDER BY hash')!209	defer {210		stmt.finalize()211	}212	mut hashes := []string{}213	for stmt.step()! {214		hashes << stmt.text(0)215	}216	for hash in hashes {217		data := s.get_object(hash) or {218			problems << ObjectProblem{hash, 'object ${hash}: ${err.msg()}'}219			continue220		}221		if s.object_size(hash)! != data.len {222			problems << ObjectProblem{hash, 'object ${hash}: stored size does not match ${data.len} bytes'}223		}224	}225	return problems226}227228/// Find missing objects, including damage from writes with foreign keys disabled.229pub fn (s &Store) check_save_files() ![]ObjectProblem {230	mut problems := []ObjectProblem{}231	mut stmt := s.db.prepare('SELECT DISTINCT f.save_id, f.hash FROM save_files f232		LEFT JOIN objects o ON o.hash = f.hash WHERE o.hash IS NULL')!233	defer {234		stmt.finalize()235	}236	for stmt.step()! {237		problems << ObjectProblem{stmt.text(1), 'save ${stmt.text(0)} needs missing object ${stmt.text(1)}'}238	}239	return problems240}241242/// Store verified bytes for `hash`, replacing a damaged row in place so the243/// saves that refer to it keep their rows.244pub fn (s &Store) repair_object(hash string, data []u8) ! {245	if hash_hex(data) != hash {246		return error('the copy of object ${hash} does not match its hash')247	}248	packed := zlib.compress(data)!249	mut stmt := s.db.prepare('INSERT INTO objects (hash, size, data) VALUES (?, ?, ?)250		ON CONFLICT(hash) DO UPDATE SET size = excluded.size, data = excluded.data')!251	defer {252		stmt.finalize()253	}254	stmt.bind_text(1, hash)!255	stmt.bind_int(2, i64(data.len))!256	stmt.bind_blob(3, packed)!257	stmt.step()!258}259260/// Saved paths whose content is `hash`, where a working copy may still exist.261pub fn (s &Store) paths_of_object(hash string) ![]string {262	mut stmt := s.db.prepare('SELECT DISTINCT path FROM save_files WHERE hash = ?')!263	defer {264		stmt.finalize()265	}266	stmt.bind_text(1, hash)!267	mut paths := []string{}268	for stmt.step()! {269		paths << stmt.text(0)270	}271	return paths272}