12345678module exchange910import json211import os12import src.events13import src.fmt14import src.remote15import src.storage161718pub struct Scope {19pub:20 files int21 saves int22 objects int23}2425pub struct LocalStrip {26pub:27 files_removed int28 objects_dropped i6429}303132pub struct SendReport {33pub mut:34 records int35 objects int36 event_sent bool37}3839404142pub struct Pending {43mut:44 saves []string45 hashes []string46}4748fn pending_key(path string) string {49 return 'strip_pending:${path}'50}515253545556pub fn read_pending(store &storage.Store, path string) !Pending {57 text := store.state(pending_key(path)) or { return Pending{} }58 note := json2.decode[Pending](text) or {59 return error('the unfinished strip note for ${path} is unreadable; it is kept for recovery')60 }61 if !note.hashes.all(storage.valid_hash(it)) {62 return error('the unfinished strip note for ${path} names something other than an object; it is kept for recovery')63 }64 recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path)65 if note.saves.len == 0 || !note.saves.all(fn [recorded] (scope string) bool {66 return recorded.any(it.save_id == scope)67 }) {68 return error('no recorded strip matches the unfinished strip note for ${path}; it is kept for recovery, and koh steal brings a strip made elsewhere')69 }70 return note71}727374pub fn strip_pending(store &storage.Store, path string) bool {75 return store.state(pending_key(path)) != none76}77787980fn covers(path string, file string) bool {81 return file == path || file.starts_with('${path.trim_right('/')}/')82}83848586pub fn strip_scope(store &storage.Store, path string, only_save string) !Scope {87 covered := covered_by(store, path.trim_right('/'), only_save)!88 return Scope{89 files: covered.files90 saves: covered.saves91 objects: covered.hashes.len92 }93}94959697pub fn strip_local(store &storage.Store, path string, only_save string) !LocalStrip {98 store.begin()!99 report := strip_rows(store, path, only_save) or {100 store.rollback()101 return err102 }103 store.end()!104 return report105}106107108pub fn strip_local_batch(store &storage.Store, paths []string, only_save string) ![]LocalStrip {109 store.begin()!110 mut reports := []LocalStrip{}111 for path in paths {112 reports << strip_rows(store, path, only_save) or {113 store.rollback()114 return err115 }116 }117 store.end() or {118 store.rollback()119 return err120 }121 return reports122}123124125126fn strip_rows(store &storage.Store, path string, only_save string) !LocalStrip {127 target := path.trim_right('/')128 covered := covered_by(store, target, only_save)!129 if covered.hashes.len == 0 {130 131 return LocalStrip{}132 }133 rewrite_saves(store, target, only_save)!134 store.drop_unreachable_manifests()!135 dropped := store.drop_unused(covered.hashes)!136 events.strip(store, only_save, path)!137 138 139 queue_strip(store, path, [only_save], covered.hashes)!140 return LocalStrip{141 files_removed: covered.files142 objects_dropped: dropped143 }144}145146147148149150151pub fn send_strip(store &storage.Store, mut backend remote.Backend, path string) !SendReport {152 mut report := SendReport{}153 send_steps(store, mut backend, path, mut report) or {154 mut done := []string{}155 if report.event_sent || report.records + report.objects > 0 {156 done << '${if report.event_sent { 'sent its event, ' } else { '' }}rewrote ${fmt.plural(report.records, 'remote record')} and deleted ${fmt.plural(report.objects, 'remote object')} for ${path}'157 }158 return partway(done, err)159 }160 return report161}162163fn send_steps(store &storage.Store, mut backend remote.Backend, path string, mut report SendReport) ! {164 note := read_pending(store, path)!165 name := repo_name(store, mut backend)!166 167 check_format(mut backend, name)!168 mut upload := OfferReport{169 repo: name170 }171 defer {172 report.event_sent = upload.events > 0173 }174 event_keys := backend.list(events_prefix(name))!175 upload_events(store, mut backend, name, event_keys, mut upload)!176 mut freed := map[string]bool{}177 for hash in note.hashes {178 freed[hash] = true179 }180 every_save := '' in note.saves181 target := path.trim_right('/')182 mut needed := map[string]bool{}183 184 185 mut manifests := map[string]string{}186 mut sent := map[string]bool{}187 mut rewriter := Rewriter{}188 for key in backend.list('${name}/saves')! {189 remote_object := backend.get(key)!190 if !remote_object.found {191 continue192 }193 record := decode_save(remote_object.body)!194 mut before := record.files.map(storage.ManifestFile{195 path: it.path196 hash: it.hash197 executable: it.executable198 })199 if record.manifest != '' {200 fetch_manifests(mut backend, name, record.manifest, mut manifests)!201 store_manifests(store, manifests)!202 before = store.manifest_files(record.manifest)!203 }204 reached := every_save || record.id in note.saves205 206 after := before.filter(fn [reached, path] (file storage.ManifestFile) bool {207 return !reached || !covers(path, file.path)208 })209 if after.len == before.len {210 for file in before {211 needed[file.hash] = true212 }213 continue214 }215 mut still := map[string]bool{}216 for file in after {217 still[file.hash] = true218 needed[file.hash] = true219 }220 221 222 mut dropped := []string{}223 for file in before {224 if file.hash !in still && file.hash !in dropped {225 dropped << file.hash226 freed[file.hash] = true227 }228 }229 mut next := rewrite(record, after.map(FileRecord{230 path: it.path231 hash: it.hash232 executable: it.executable233 }), '')234 if record.manifest != '' {235 236 237 rewritten := rewriter.rewrite(store, record.manifest, target)!238 upload_manifests(store, mut backend, name, rewritten.hash, mut sent)!239 next = rewrite(record, record.files, rewritten.hash)240 }241 242 243 queue_strip(store, path, []string{}, dropped)!244 encoded := encode_save(next)245 if !backend.put_if_match(key, encoded.bytes(), remote_object.tag)! {246 return error('the remote copy of save ${record.id} moved while stripping — run koh steal, then strip again')247 }248 report.records++249 }250 for hash, _ in freed {251 if hash in needed || !storage.valid_hash(hash) || store.has_object(hash)!252 || store.paths_of_object(hash)!.len > 0 {253 continue254 }255 backend.delete(object_key(name, hash))!256 report.objects++257 }258 store.remove_state(pending_key(path))!259}260261262263pub fn requeue_strip(store &storage.Store, path string) ! {264 recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path)265 if recorded.len == 0 {266 return error('this repo has no recorded strip of ${path}; run koh steal, then koh doctor')267 }268 queue_strip(store, path, recorded.map(it.save_id), []string{})!269}270271272273fn queue_strip(store &storage.Store, path string, scopes []string, hashes []string) ! {274 mut note := read_pending(store, path)!275 count := note.saves.len + note.hashes.len276 note.saves << scopes.filter(it !in note.saves)277 note.hashes << hashes.filter(it !in note.hashes && storage.valid_hash(it))278 if note.saves.len + note.hashes.len > count {279 store.set_state(pending_key(path), json2.encode(note))!280 }281}282283284285286287288fn unapplied_strips(store &storage.Store, mut backend remote.Backend, event_keys []string) ![]events.Event {289 mut known := map[string]bool{}290 for event in events.all(store)! {291 known[event.id] = true292 }293 mut strips := []events.Event{}294 for key in event_keys {295 if os.base(key) in known {296 continue297 }298 body := backend.get(key)!299 if !body.found {300 continue301 }302 event := decode_event(body.body)!303 if events.valid_strip(event) && !ignored_strip(event) {304 strips << event305 }306 }307 return strips308}309310311312fn rewrite(record SaveRecord, files []FileRecord, manifest string) SaveRecord {313 return SaveRecord{314 ...record315 files: files316 manifest: manifest317 }318}319320struct Covered {321 files int322 saves int323 hashes []string324}325326327struct Subtree {328 files int329 hashes []string330}331332struct SaveTree {333 id string334 manifest string335}336337fn save_trees(store &storage.Store, only_save string) ![]SaveTree {338 mut stmt := store.db.prepare('SELECT id, manifest FROM saves ORDER BY id')!339 defer {340 stmt.finalize()341 }342 mut trees := []SaveTree{}343 for stmt.step()! {344 id := stmt.text(0)345 if only_save != '' && id != only_save {346 continue347 }348 trees << SaveTree{349 id: id350 manifest: stmt.text(1)351 }352 }353 return trees354}355356struct FoundEntry {357 ok bool358 entry storage.ManifestEntry359}360361362363364fn find_entry(store &storage.Store, root string, path string) !FoundEntry {365 mut hash := root366 mut rest := path367 for {368 entries := store.manifest_entries(hash)!369 for entry in entries {370 if entry.name == rest {371 return FoundEntry{372 ok: true373 entry: entry374 }375 }376 }377 slash := rest.index('/') or { return FoundEntry{} }378 segment := rest[..slash]379 mut child := ''380 for entry in entries {381 if entry.name == segment && entry.kind == storage.folder_kind {382 child = entry.manifest383 break384 }385 }386 if child == '' {387 return FoundEntry{}388 }389 hash = child390 rest = rest[slash + 1..]391 }392 return FoundEntry{}393}394395396397fn subtree(store &storage.Store, hash string, mut memo map[string]Subtree, mut busy map[string]bool) !Subtree {398 if hash in memo {399 return memo[hash]400 }401 if busy[hash] {402 return error('manifest ${hash} refers to itself')403 }404 busy[hash] = true405 mut files := 0406 mut hashes := map[string]bool{}407 entries := store.manifest_entries(hash)!408 for entry in entries {409 if entry.kind == storage.file_kind {410 files++411 hashes[entry.hash] = true412 } else {413 child := subtree(store, entry.manifest, mut memo, mut busy)!414 files += child.files415 for h in child.hashes {416 hashes[h] = true417 }418 }419 }420 busy.delete(hash)421 summary := Subtree{422 files: files423 hashes: hashes.keys()424 }425 memo[hash] = summary426 return summary427}428429430fn stripped_hashes(store &storage.Store, path string, only_save string) ![]string {431 return covered_by(store, path.trim_right('/'), only_save)!.hashes432}433434435436fn remove_path(store &storage.Store, path string, only_save string) !int {437 target := path.trim_right('/')438 covered := covered_by(store, target, only_save)!439 rewrite_saves(store, target, only_save)!440 store.drop_unreachable_manifests()!441 return covered.files442}443444445446fn covered_by(store &storage.Store, path string, only_save string) !Covered {447 mut files := 0448 mut saves := 0449 mut hashes := map[string]bool{}450 mut memo := map[string]Subtree{}451 mut busy := map[string]bool{}452 for tree in save_trees(store, only_save)! {453 found := find_entry(store, tree.manifest, path)!454 if found.ok {455 entry := found.entry456 mut here := 0457 if entry.kind == storage.file_kind {458 here = 1459 hashes[entry.hash] = true460 } else {461 summary := subtree(store, entry.manifest, mut memo, mut busy)!462 here = summary.files463 for hash in summary.hashes {464 hashes[hash] = true465 }466 }467 if here > 0 {468 files += here469 saves++470 }471 }472 }473 mut distinct := hashes.keys()474 distinct.sort()475 return Covered{476 files: files477 saves: saves478 hashes: distinct479 }480}481482483484struct Rewriter {485mut:486 memo map[string]string487 busy map[string]bool488}489490struct Rewritten {491 changed bool492 hash string493}494495496497fn (mut r Rewriter) rewrite(store &storage.Store, hash string, path string) !Rewritten {498 key := '${hash}\x00${path}'499 if key in r.memo {500 found := r.memo[key]501 if found == '' {502 return Rewritten{}503 }504 return Rewritten{505 changed: true506 hash: found507 }508 }509 if r.busy[key] {510 return error('manifest ${hash} refers to itself')511 }512 r.busy[key] = true513 entries := store.manifest_entries(hash)!514 mut kept := []storage.ManifestEntry{}515 mut exact := false516 for entry in entries {517 if entry.name == path {518 exact = true519 }520 }521 if exact {522 for entry in entries {523 if entry.name != path {524 kept << entry525 }526 }527 } else {528 slash := path.index('/') or { -1 }529 if slash < 0 {530 r.miss(key)531 return Rewritten{}532 }533 segment := path[..slash]534 mut at := -1535 for i, entry in entries {536 if entry.name == segment && entry.kind == storage.folder_kind {537 at = i538 break539 }540 }541 if at < 0 {542 r.miss(key)543 return Rewritten{}544 }545 child := r.rewrite(store, entries[at].manifest, path[slash + 1..])!546 if child.changed {547 kept = entries.clone()548 kept[at] = storage.ManifestEntry{549 name: entries[at].name550 kind: storage.folder_kind551 manifest: child.hash552 }553 } else {554 r.miss(key)555 return Rewritten{}556 }557 }558 new_hash := store.put_manifest(json2.encode(storage.Manifest{559 entries: kept560 }))!561 r.busy.delete(key)562 r.memo[key] = new_hash563 return Rewritten{564 changed: true565 hash: new_hash566 }567}568569570fn (mut r Rewriter) miss(key string) {571 r.busy.delete(key)572 r.memo[key] = ''573}574575576577fn rewrite_saves(store &storage.Store, path string, only_save string) ! {578 mut rewriter := Rewriter{}579 mut update := store.db.prepare('UPDATE saves SET manifest = ? WHERE id = ?')!580 defer {581 update.finalize()582 }583 for tree in save_trees(store, only_save)! {584 rewritten := rewriter.rewrite(store, tree.manifest, path)!585 if rewritten.changed {586 update.bind_text(1, rewritten.hash)!587 update.bind_text(2, tree.id)!588 update.step()!589 update.reset()590 }591 }592}