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 mut upload := OfferReport{167 repo: name168 }169 defer {170 report.event_sent = upload.events > 0171 }172 event_keys := backend.list(events_prefix(name))!173 upload_events(store, mut backend, name, event_keys, mut upload)!174 mut freed := map[string]bool{}175 for hash in note.hashes {176 freed[hash] = true177 }178 every_save := '' in note.saves179 mut needed := map[string]bool{}180 for key in backend.list('${name}/saves')! {181 remote_object := backend.get(key)!182 if !remote_object.found {183 continue184 }185 record := decode_save(remote_object.body)!186 mut kept := []FileRecord{}187 mut dropped := []string{}188 for file in record.files {189 if (every_save || record.id in note.saves) && covers(path, file.path) {190 freed[file.hash] = true191 dropped << file.hash192 continue193 }194 kept << file195 needed[file.hash] = true196 }197 if kept.len == record.files.len {198 continue199 }200 201 202 queue_strip(store, path, []string{}, dropped)!203 if !backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), remote_object.tag)! {204 return error('the remote copy of save ${record.id} moved while stripping — run koh steal, then strip again')205 }206 report.records++207 }208 for hash, _ in freed {209 if hash in needed || !storage.valid_hash(hash) || store.has_object(hash)!210 || store.paths_of_object(hash)!.len > 0 {211 continue212 }213 backend.delete(object_key(name, hash))!214 report.objects++215 }216 store.remove_state(pending_key(path))!217}218219220221pub fn requeue_strip(store &storage.Store, path string) ! {222 recorded := events.strip_events(store)!.filter(events.valid_strip(it) && it.path == path)223 if recorded.len == 0 {224 return error('this repo has no recorded strip of ${path}; run koh steal, then koh doctor')225 }226 queue_strip(store, path, recorded.map(it.save_id), []string{})!227}228229230231fn queue_strip(store &storage.Store, path string, scopes []string, hashes []string) ! {232 mut note := read_pending(store, path)!233 count := note.saves.len + note.hashes.len234 note.saves << scopes.filter(it !in note.saves)235 note.hashes << hashes.filter(it !in note.hashes && storage.valid_hash(it))236 if note.saves.len + note.hashes.len > count {237 store.set_state(pending_key(path), json2.encode(note))!238 }239}240241242243244245246fn unapplied_strips(store &storage.Store, mut backend remote.Backend, event_keys []string) ![]events.Event {247 mut known := map[string]bool{}248 for event in events.all(store)! {249 known[event.id] = true250 }251 mut strips := []events.Event{}252 for key in event_keys {253 if os.base(key) in known {254 continue255 }256 body := backend.get(key)!257 if !body.found {258 continue259 }260 event := decode_event(body.body)!261 if events.valid_strip(event) && !ignored_strip(event) {262 strips << event263 }264 }265 return strips266}267268269fn rewrite(record SaveRecord, files []FileRecord) SaveRecord {270 return SaveRecord{271 ...record272 files: files273 }274}275276struct Covered {277 files int278 saves int279 hashes []string280}281282283struct Subtree {284 files int285 hashes []string286}287288struct SaveTree {289 id string290 manifest string291}292293fn save_trees(store &storage.Store, only_save string) ![]SaveTree {294 mut stmt := store.db.prepare('SELECT id, manifest FROM saves ORDER BY id')!295 defer {296 stmt.finalize()297 }298 mut trees := []SaveTree{}299 for stmt.step()! {300 id := stmt.text(0)301 if only_save != '' && id != only_save {302 continue303 }304 trees << SaveTree{305 id: id306 manifest: stmt.text(1)307 }308 }309 return trees310}311312struct FoundEntry {313 ok bool314 entry storage.ManifestEntry315}316317318319320fn find_entry(store &storage.Store, root string, path string) !FoundEntry {321 mut hash := root322 mut rest := path323 for {324 entries := store.manifest_entries(hash)!325 for entry in entries {326 if entry.name == rest {327 return FoundEntry{328 ok: true329 entry: entry330 }331 }332 }333 slash := rest.index('/') or { return FoundEntry{} }334 segment := rest[..slash]335 mut child := ''336 for entry in entries {337 if entry.name == segment && entry.kind == storage.folder_kind {338 child = entry.manifest339 break340 }341 }342 if child == '' {343 return FoundEntry{}344 }345 hash = child346 rest = rest[slash + 1..]347 }348 return FoundEntry{}349}350351352353fn subtree(store &storage.Store, hash string, mut memo map[string]Subtree, mut busy map[string]bool) !Subtree {354 if hash in memo {355 return memo[hash]356 }357 if busy[hash] {358 return error('manifest ${hash} refers to itself')359 }360 busy[hash] = true361 mut files := 0362 mut hashes := map[string]bool{}363 entries := store.manifest_entries(hash)!364 for entry in entries {365 if entry.kind == storage.file_kind {366 files++367 hashes[entry.hash] = true368 } else {369 child := subtree(store, entry.manifest, mut memo, mut busy)!370 files += child.files371 for h in child.hashes {372 hashes[h] = true373 }374 }375 }376 busy.delete(hash)377 summary := Subtree{378 files: files379 hashes: hashes.keys()380 }381 memo[hash] = summary382 return summary383}384385386fn stripped_hashes(store &storage.Store, path string, only_save string) ![]string {387 return covered_by(store, path.trim_right('/'), only_save)!.hashes388}389390391392fn remove_path(store &storage.Store, path string, only_save string) !int {393 target := path.trim_right('/')394 covered := covered_by(store, target, only_save)!395 rewrite_saves(store, target, only_save)!396 store.drop_unreachable_manifests()!397 return covered.files398}399400401402fn covered_by(store &storage.Store, path string, only_save string) !Covered {403 mut files := 0404 mut saves := 0405 mut hashes := map[string]bool{}406 mut memo := map[string]Subtree{}407 mut busy := map[string]bool{}408 for tree in save_trees(store, only_save)! {409 found := find_entry(store, tree.manifest, path)!410 if found.ok {411 entry := found.entry412 mut here := 0413 if entry.kind == storage.file_kind {414 here = 1415 hashes[entry.hash] = true416 } else {417 summary := subtree(store, entry.manifest, mut memo, mut busy)!418 here = summary.files419 for hash in summary.hashes {420 hashes[hash] = true421 }422 }423 if here > 0 {424 files += here425 saves++426 }427 }428 }429 mut distinct := hashes.keys()430 distinct.sort()431 return Covered{432 files: files433 saves: saves434 hashes: distinct435 }436}437438439440struct Rewriter {441mut:442 memo map[string]string443 busy map[string]bool444}445446struct Rewritten {447 changed bool448 hash string449}450451452453fn (mut r Rewriter) rewrite(store &storage.Store, hash string, path string) !Rewritten {454 key := '${hash}\x00${path}'455 if key in r.memo {456 found := r.memo[key]457 if found == '' {458 return Rewritten{}459 }460 return Rewritten{461 changed: true462 hash: found463 }464 }465 if r.busy[key] {466 return error('manifest ${hash} refers to itself')467 }468 r.busy[key] = true469 entries := store.manifest_entries(hash)!470 mut kept := []storage.ManifestEntry{}471 mut exact := false472 for entry in entries {473 if entry.name == path {474 exact = true475 }476 }477 if exact {478 for entry in entries {479 if entry.name != path {480 kept << entry481 }482 }483 } else {484 slash := path.index('/') or { -1 }485 if slash < 0 {486 r.miss(key)487 return Rewritten{}488 }489 segment := path[..slash]490 mut at := -1491 for i, entry in entries {492 if entry.name == segment && entry.kind == storage.folder_kind {493 at = i494 break495 }496 }497 if at < 0 {498 r.miss(key)499 return Rewritten{}500 }501 child := r.rewrite(store, entries[at].manifest, path[slash + 1..])!502 if child.changed {503 kept = entries.clone()504 kept[at] = storage.ManifestEntry{505 name: entries[at].name506 kind: storage.folder_kind507 manifest: child.hash508 }509 } else {510 r.miss(key)511 return Rewritten{}512 }513 }514 new_hash := store.put_manifest(json2.encode(storage.Manifest{515 entries: kept516 }))!517 r.busy.delete(key)518 r.memo[key] = new_hash519 return Rewritten{520 changed: true521 hash: new_hash522 }523}524525526fn (mut r Rewriter) miss(key string) {527 r.busy.delete(key)528 r.memo[key] = ''529}530531532533fn rewrite_saves(store &storage.Store, path string, only_save string) ! {534 mut rewriter := Rewriter{}535 mut update := store.db.prepare('UPDATE saves SET manifest = ? WHERE id = ?')!536 defer {537 update.finalize()538 }539 for tree in save_trees(store, only_save)! {540 rewritten := rewriter.rewrite(store, tree.manifest, path)!541 if rewritten.changed {542 update.bind_text(1, rewritten.hash)!543 update.bind_text(2, tree.id)!544 update.step()!545 update.reset()546 }547 }548}