12345678module storage910import compress.zlib11import crypto.blake31213pub const max_file_size = 512 * 1024 * 10241415struct InflateSink {16mut:17 out []u818 limit int19 aborted bool20}21222324252627pub 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}52535455pub 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}71727374pub 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}8586878889pub 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}117118119120pub 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}159160161162pub fn (s &Store) drop_unreferenced_objects() !i64 {163 before := s.object_count()!164 used := s.manifest_object_hashes()!165 mut stmt := s.db.prepare('DELETE FROM objects WHERE hash = ?')!166 defer {167 stmt.finalize()168 }169 mut hashes := s.db.prepare('SELECT hash FROM objects')!170 defer {171 hashes.finalize()172 }173 mut stale := []string{}174 for hashes.step()! {175 hash := hashes.text(0)176 if hash !in used {177 stale << hash178 }179 }180 for hash in stale {181 stmt.bind_text(1, hash)!182 stmt.step()!183 stmt.reset()184 }185 after := s.object_count()!186 return before - after187}188189190191pub fn valid_hash(hash string) bool {192 return hash.len == 64 && hash.bytes().all((it >= `0` && it <= `9`) || (it >= `a` && it <= `f`))193}194195196197198pub fn (s &Store) drop_unused(hashes []string) !i64 {199 used := s.manifest_object_hashes()!200 mut stmt := s.db.prepare('DELETE FROM objects WHERE hash = ?')!201 defer {202 stmt.finalize()203 }204 mut dropped := i64(0)205 for hash in hashes {206 if hash in used {207 continue208 }209 stmt.bind_text(1, hash)!210 stmt.step()!211 dropped += s.db.changes()212 stmt.reset()213 }214 return dropped215}216217218pub struct ObjectProblem {219pub:220 hash string221 detail string222}223224225pub fn (s &Store) check_objects() ![]ObjectProblem {226 mut problems := []ObjectProblem{}227 mut stmt := s.db.prepare('SELECT hash FROM objects ORDER BY hash')!228 defer {229 stmt.finalize()230 }231 mut hashes := []string{}232 for stmt.step()! {233 hashes << stmt.text(0)234 }235 for hash in hashes {236 data := s.get_object(hash) or {237 problems << ObjectProblem{hash, 'object ${hash}: ${err.msg()}'}238 continue239 }240 if s.object_size(hash)! != data.len {241 problems << ObjectProblem{hash, 'object ${hash}: stored size does not match ${data.len} bytes'}242 }243 }244 return problems245}246247248249pub fn (s &Store) check_save_files() ![]ObjectProblem {250 mut problems := []ObjectProblem{}251 mut stmt := s.db.prepare('SELECT hash, body FROM manifests ORDER BY hash')!252 defer {253 stmt.finalize()254 }255 mut seen := map[string]bool{}256 for stmt.step()! {257 manifest := stmt.text(0)258 entries := decode_manifest(stmt.text(1)) or { continue }259 for entry in entries {260 if entry.kind != file_kind {261 continue262 }263 key := '${manifest} ${entry.hash}'264 if key in seen {265 continue266 }267 seen[key] = true268 if !s.has_object(entry.hash)! {269 problems << ObjectProblem{entry.hash, 'manifest ${manifest} needs missing object ${entry.hash}'}270 }271 }272 }273 return problems274}275276277278pub fn (s &Store) repair_object(hash string, data []u8) ! {279 if hash_hex(data) != hash {280 return error('the copy of object ${hash} does not match its hash')281 }282 packed := zlib.compress(data)!283 mut stmt := s.db.prepare('INSERT INTO objects (hash, size, data) VALUES (?, ?, ?)284 ON CONFLICT(hash) DO UPDATE SET size = excluded.size, data = excluded.data')!285 defer {286 stmt.finalize()287 }288 stmt.bind_text(1, hash)!289 stmt.bind_int(2, i64(data.len))!290 stmt.bind_blob(3, packed)!291 stmt.step()!292}293294295pub fn (s &Store) paths_of_object(hash string) ![]string {296 mut stmt := s.db.prepare('SELECT DISTINCT manifest FROM saves')!297 defer {298 stmt.finalize()299 }300 mut roots := []string{}301 for stmt.step()! {302 roots << stmt.text(0)303 }304 mut memo := map[string][]ManifestFile{}305 mut paths := map[string]bool{}306 for root in roots {307 if root !in memo {308 memo[root] = s.manifest_files(root)!309 }310 for file in memo[root] {311 if file.hash == hash {312 paths[file.path] = true313 }314 }315 }316 mut out := paths.keys()317 out.sort()318 return out319}