1234567891011module exchange1213import json214import os15import src.events16import src.fmt17import src.history18import src.remote19import src.snapshot20import src.storage212223const repo_state_key = 'remote_repo'24252627const remote_head_key = 'remote_head'2829pub const no_saves = 'this repo has no saves yet — nothing to offer'30313233fn put_format(mut backend remote.Backend, repo string, value string) !string {34 if backend.put_if_absent(format_key(repo), value.bytes())! {35 return value36 }37 return check_format(mut backend, repo)!38}3940414243fn check_format(mut backend remote.Backend, repo string) !string {44 existing := backend.get(format_key(repo))!45 if !existing.found {46 return ''47 }48 value := existing.body.bytestr().trim_space()49 if value !in [format_v1, format_v2] {50 return error('the remote "${repo}" is "${value}" — this koh speaks "${format_v1}" and "${format_v2}"; update koh')51 }52 return value53}5455pub struct OfferReport {56pub mut:57 repo string58 saves int59 objects int60 events int61 head string62}63646566pub fn remember_repo(store &storage.Store, name string) ! {67 store.set_state(repo_state_key, name)!68}6970717273pub fn valid_repo_name(name string) bool {74 if name == '' || name == '.' || name == '..' {75 return false76 }77 return name.bytes().all(it.is_alnum() || it in [`-`, `.`, `_`])78}7980818283pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {84 name, _ := repo_name_with_head(store, mut backend)!85 return name86}8788899091fn repo_name_with_head(store &storage.Store, mut backend remote.Backend) !(string, remote.Object) {92 if remembered := store.state(repo_state_key) {93 return follow_rename(store, mut backend, remembered)!94 }95 name := os.base(store.root).to_lower()96 97 98 if !valid_repo_name(name) {99 return error('"${name}" is not a repo name — a repo name is letters, digits, ., _ and -; rename the folder')100 }101 102 103 check_format(mut backend, name)!104 existing := backend.get(head_key(name))!105 if existing.found {106 theirs := existing.body.bytestr().trim_space()107 if history.by_id(store, theirs) == none {108 return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')109 }110 }111 store.set_state(repo_state_key, name)!112 return name, existing113}114115116117118119fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !(string, remote.Object) {120 mut name := remembered121 mut head := backend.get(head_key(name))!122 for _ in 0 .. 5 {123 if head.found {124 break125 }126 marker := backend.get('.kepr/renamed/${name}')!127 next := marker.body.bytestr().trim_space()128 if !marker.found || !valid_repo_name(next) {129 break130 }131 name = next132 head = backend.get(head_key(name))!133 }134 if name != remembered {135 store.set_state(repo_state_key, name)!136 }137 return name, head138}139140141142pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {143 name, remote_head := repo_name_with_head(store, mut backend)!144 local := history.head(store) or { return error(no_saves) }145 mut report := OfferReport{146 repo: name147 head: local.id148 }149 mut format := check_format(mut backend, name)!150 if format == '' {151 152 format = put_format(mut backend, name, if remote_head.found { format_v1 } else { format_v2 })!153 }154 155 156 event_keys := backend.list(events_prefix(name))!157 158 159 if unapplied_strips(store, mut backend, event_keys)!.len > 0 {160 return error(strip_not_applied)161 }162 mut uploaded := Uploaded{}163 upload_line(store, mut backend, name, local.id, remote_head, format, event_keys, mut report,164 mut uploaded) or { return after_failed_upload(store, mut backend, name, uploaded, err) }165 166 167 168 169 170 if (uploaded.saves.len > 0 || uploaded.objects.len > 0)171 && undo_late_strips(store, mut backend, name, uploaded)! {172 return error(strip_not_applied)173 }174 175 176 if remote_head.body.bytestr().trim_space() != local.id177 && !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {178 179 180 again := backend.get(head_key(name))!181 if !again.found || again.body.bytestr().trim_space() != local.id {182 return error('remote has new saves — run koh steal')183 }184 }185 store.set_state(remote_head_key, local.id)!186 return report187}188189190191192fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {193 mut newer := []history.Save{}194 mut cursor := ours195 for cursor != '' && cursor != theirs {196 save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }197 newer << save198 cursor = save.parent199 }200 if cursor != theirs {201 return error('${theirs} is not on this line')202 }203 newer.reverse_in_place()204 return newer205}206207const strip_not_applied = 'the remote has a strip this repo has not applied — run koh steal'208209210struct Uploaded {211mut:212 saves []string213 objects map[string]bool214 deleted int 215}216217fn (u Uploaded) done() []string {218 mut done := done_text('deleted', u.deleted, 'damaged remote object')219 if u.saves.len + u.objects.len > 0 {220 done << 'uploaded ${fmt.plural(u.objects.len, 'object')} and ${fmt.plural(u.saves.len, 'save record')}'221 }222 return done223}224225226227fn upload_line(store &storage.Store, mut backend remote.Backend, name string, local string, remote_head remote.Object, format string, event_keys []string, mut report OfferReport, mut uploaded Uploaded) ! {228 mut sent_manifests := map[string]bool{}229 if remote_head.found {230 theirs := remote_head.body.bytestr().trim_space()231 newer := saves_after(store, local, theirs) or {232 return error('remote has new saves — run koh steal')233 }234 for save in newer {235 upload_save(store, mut backend, name, save, format, mut sent_manifests, mut report,236 mut uploaded)!237 }238 } else {239 oldest_first := history.line(store)!240 for index := oldest_first.len - 1; index >= 0; index-- {241 upload_save(store, mut backend, name, oldest_first[index], format, mut sent_manifests,242 mut report, mut uploaded)!243 }244 }245 upload_events(store, mut backend, name, event_keys, mut report)!246}247248249250fn after_failed_upload(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, failure IError) IError {251 undo_late_strips(store, mut backend, repo, uploaded) or {252 return error('${failure.msg()}; removing what a strip on the remote covers also failed: ${err.msg()}')253 }254 return failure255}256257258259pub const unsettled_key = 'upload_unsettled'260261pub fn unsettled(store &storage.Store) ![]string {262 text := store.state(unsettled_key) or { return []string{} }263 return json2.decode[[]string](text) or {264 return error('the note of an unsettled upload is unreadable; it is kept for recovery')265 }266}267268fn undo_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {269 return settle_late_strips(store, mut backend, repo, uploaded) or {270 failure := err271 mut kept := unsettled(store) or { return error('${failure.msg()}; ${err.msg()}') }272 kept << uploaded.objects.keys().filter(it !in kept)273 store.set_state(unsettled_key, json2.encode(kept)) or {274 return error('${failure.msg()}; ${err.msg()}')275 }276 return failure277 }278}279280281282283284fn settle_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {285 event_keys := backend.list(events_prefix(repo))!286 strips := unapplied_strips(store, mut backend, event_keys)!287 if strips.len == 0 {288 return false289 }290 for strip in strips {291 queue_strip(store, strip.path, [strip.save_id], uploaded.objects.keys())!292 }293 for id in uploaded.saves {294 strip_record(store, mut backend, repo, save_key(repo, id), id, strips)!295 }296 drop_stripped_objects(store, mut backend, repo, uploaded, strips)!297 return true298}299300301302303fn strip_record(store &storage.Store, mut backend remote.Backend, repo string, key string, id string, strips []events.Event) ! {304 mut manifests := map[string]string{}305 mut sent := map[string]bool{}306 mut rewriter := Rewriter{}307 for _ in 0 .. 5 {308 object := backend.get(key)!309 if !object.found {310 return311 }312 record := decode_save(object.body)!313 if record.manifest != '' {314 fetch_manifests(mut backend, repo, record.manifest, mut manifests)!315 store_manifests(store, manifests)!316 mut root := record.manifest317 for strip in strips {318 if !reaches(strip, id) {319 continue320 }321 rewritten := rewriter.rewrite(store, root, strip.path.trim_right('/'))!322 if rewritten.changed {323 root = rewritten.hash324 }325 }326 if root == record.manifest {327 return328 }329 upload_manifests(store, mut backend, repo, root, mut sent)!330 if backend.put_if_match(key, encode_save(rewrite(record, record.files, root)).bytes(), object.tag)! {331 return332 }333 continue334 }335 kept := record.files.filter(fn [strips, id] (file FileRecord) bool {336 return !strips.any(reaches(it, id) && covers(it.path, file.path))337 })338 if kept.len == record.files.len339 || backend.put_if_match(key, encode_save(rewrite(record, kept, '')).bytes(), object.tag)! {340 return341 }342 }343 return error('the remote copy of save ${id} kept changing while a stripped path was removed; run koh doctor again')344}345346347348pub struct Partway {349 Error350pub:351 done string352 reason string353}354355pub fn (e Partway) msg() string {356 return e.reason357}358359360pub fn done_text(verb string, done int, noun string) []string {361 return if done == 0 { []string{} } else { ['${verb} ${fmt.plural(done, noun)}'] }362}363364365366pub fn partway(done []string, failure IError) IError {367 mut all := done.clone()368 if failure is Partway {369 all << failure.done370 }371 if all.len == 0 {372 return failure373 }374 return Partway{375 done: all.join('; ')376 reason: failure.msg()377 }378}379380381382383fn drop_stripped_objects(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {384 mut reached := map[string]bool{}385 386 mut kept := map[string]bool{}387 for save in history.all_saves(store)! {388 for file in history.files_of(store, save.id)!.filter(it.hash in uploaded.objects) {389 if strips.any(reaches(it, save.id) && covers(it.path, file.path)) {390 reached[file.hash] = true391 } else {392 kept[file.hash] = true393 }394 }395 }396 if reached.len == 0 {397 return398 }399 mut manifests := map[string]string{}400 for key in backend.list('${repo}/saves')! {401 object := backend.get(key)!402 if object.found {403 record := decode_save(object.body)!404 for file in record_files(mut backend, repo, record, mut manifests)! {405 if !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {406 reached.delete(file.hash)407 }408 }409 }410 }411 for hash, _ in reached {412 if hash !in kept {413 backend.delete(object_key(repo, hash))!414 }415 }416}417418419420421fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, format string, mut sent_manifests map[string]bool, mut report OfferReport, mut uploaded Uploaded) ! {422 files := history.files_of(store, save.id)!423 424 425 426 mut sent := map[string]bool{}427 if save.parent != '' {428 for file in history.files_of(store, save.parent)! {429 sent[file.hash] = true430 }431 }432 for file in files {433 if file.hash in sent {434 continue435 }436 sent[file.hash] = true437 if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {438 report.objects++439 uploaded.objects[file.hash] = true440 }441 }442 443 mut record := SaveRecord{}444 if format == format_v2 {445 upload_manifests(store, mut backend, repo, save.manifest, mut sent_manifests)!446 record = save_record_v2(store, save)!447 } else {448 record = save_record(store, save)!449 }450 if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {451 report.saves++452 uploaded.saves << save.id453 }454}455456457458fn upload_manifests(store &storage.Store, mut backend remote.Backend, repo string, root string, mut sent map[string]bool) ! {459 mut pending := [root]460 for pending.len > 0 {461 hash := pending.pop()462 if hash in sent {463 continue464 }465 sent[hash] = true466 backend.put_if_absent(manifest_key(repo, hash), store.manifest_body(hash)!.bytes())!467 for entry in store.manifest_entries(hash)! {468 if entry.kind == storage.folder_kind {469 pending << entry.manifest470 }471 }472 }473}474475476477pub fn fetch_manifests(mut backend remote.Backend, repo string, root string, mut manifests map[string]string) ! {478 mut pending := [root]479 for pending.len > 0 {480 hash := pending.pop()481 if hash in manifests {482 continue483 }484 object := backend.get(manifest_key(repo, hash))!485 if !object.found {486 return error('the remote is missing manifest ${hash}')487 }488 if storage.hash_hex(object.body) != hash {489 return error('remote manifest ${hash} fails Blake3 verification')490 }491 body := object.body.bytestr()492 manifests[hash] = body493 entries := json2.decode[storage.Manifest](body) or {494 return error('remote manifest ${hash} is unreadable: ${err.msg()}')495 }496 for entry in entries.entries {497 if entry.kind == storage.folder_kind {498 pending << entry.manifest499 }500 }501 }502}503504505506fn store_manifests(store &storage.Store, manifests map[string]string) ! {507 for _, body in manifests {508 store.put_manifest(body)!509 }510}511512513fn flatten_files(manifests map[string]string, root string) ![]FileRecord {514 files := storage.flatten_bodies(manifests, root)!515 mut records := []FileRecord{cap: files.len}516 for file in files {517 records << FileRecord{518 path: file.path519 hash: file.hash520 executable: file.executable521 }522 }523 return records524}525526527528529pub fn record_files(mut backend remote.Backend, repo string, record SaveRecord, mut manifests map[string]string) ![]FileRecord {530 if record.manifest == '' {531 return record.files532 }533 fetch_manifests(mut backend, repo, record.manifest, mut manifests)!534 return flatten_files(manifests, record.manifest)535}536537538539540fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, already []string, mut report OfferReport) ! {541 mut already_sent := map[string]bool{}542 for key in already {543 already_sent[os.base(key)] = true544 }545 for event in events.all(store)! {546 if event.id in already_sent {547 continue548 }549 if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {550 report.events++551 }552 }553}554555556557558pub struct Fetched {559pub mut:560 repo_objects map[string][]u8561 562 manifests map[string]string563 object_bytes int 564 saves []SaveRecord 565 events_out []events.Event566 head string567 base string 568 unsafe_paths []string569}570571572573574const object_batch_bytes = 64 * 1024 * 1024575576fn (mut f Fetched) add_object(store &storage.Store, hash string, blob []u8) ! {577 f.repo_objects[hash] = blob578 f.object_bytes += blob.len579 if f.object_bytes >= object_batch_bytes {580 for key, bytes in f.repo_objects {581 store.put_object_blob(key, bytes)!582 }583 f.repo_objects.clear()584 f.object_bytes = 0585 }586}587588589590591592pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {593 format := check_format(mut backend, repo)!594 595 596 layout := if format == '' { format_v1 } else { format }597 remote_head := backend.get(head_key(repo))!598 if !remote_head.found {599 return error('the remote has no "${repo}" yet — run koh offer here first')600 }601 mut fetched := Fetched{602 head: remote_head.body.bytestr().trim_space()603 }604 if !valid_save_id(fetched.head) {605 return error('the remote head has invalid save ID ${fetched.head}')606 }607 mut on_line := map[string]bool{}608 for save in history.line(store)! {609 on_line[save.id] = true610 }611 612 fetched.events_out = fetch_events(store, mut backend, repo)!613 strips := known_strips(store, fetched)!614 mut cursor := fetched.head615 mut seen := map[string]bool{}616 for cursor != '' && cursor !in on_line {617 if cursor in seen {618 return error('the remote history has a parent cycle at ${cursor}')619 }620 seen[cursor] = true621 mut record := if saved := history.by_id(store, cursor) {622 save_record(store, saved)!623 } else {624 record_object := backend.get(save_key(repo, cursor))!625 if !record_object.found {626 return error('the remote is missing save ${cursor} — run koh offer there')627 }628 mut decoded := decode_save(record_object.body)!629 validate_save(decoded, cursor)!630 record_layout := if decoded.manifest == '' { format_v1 } else { format_v2 }631 if record_layout != layout {632 return error('the remote "${repo}" is ${layout} but save ${cursor} is a ${record_layout} record — update koh on the machine that offered it')633 }634 if decoded.manifest != '' {635 fetch_manifests(mut backend, repo, decoded.manifest, mut fetched.manifests)!636 decoded.files = flatten_files(fetched.manifests, decoded.manifest)!637 }638 decoded639 }640 fetched.unsafe_paths << drop_unsafe_paths(mut record)641 validate_hashes(record.id, record.files)!642 for file in record.files {643 if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects644 && !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {645 blob := backend.get(object_key(repo, file.hash))!646 if !blob.found {647 return error('the remote is missing object ${file.hash} that save ${record.id} needs')648 }649 fetched.add_object(store, file.hash, blob.body)!650 }651 }652 fetched.saves << record653 cursor = record.parent654 }655 fetched.saves.reverse_in_place()656 fetched.base = cursor657 return fetched658}659660fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {661 have := events.all(store)!662 mut known := map[string]bool{}663 for event in have {664 known[event.id] = true665 }666 mut incoming := []events.Event{}667 for key in backend.list(events_prefix(repo))! {668 id := os.base(key)669 if !valid_event_id(id) {670 return error('the remote has invalid event ID ${id}')671 }672 if id in known {673 continue674 }675 body := backend.get(event_key(repo, id))!676 if !body.found {677 continue678 }679 event := decode_event(body.body)!680 if event.id != id {681 return error('remote event record ID ${event.id} disagrees with key ${id}')682 }683 if !ignored_strip(event) {684 incoming << event685 }686 }687 return incoming688}689690691692693694pub fn write_fetched(store &storage.Store, fetched Fetched) ! {695 for hash, blob in fetched.repo_objects {696 store.put_object_blob(hash, blob)!697 }698 mut freed := []string{}699 for event in fetched.events_out {700 if !events.receive(store, event)! {701 continue702 }703 if events.valid_strip(event) {704 freed << stripped_hashes(store, event.path, event.save_id)!705 remove_path(store, event.path, event.save_id)!706 }707 }708 for hash, body in fetched.manifests {709 store.put_manifest(body)!710 }711 strips := known_strips(store, fetched)!712 for record in fetched.saves {713 for file in record.files {714 if file.hash in fetched.repo_objects715 && strips.any(reaches(it, record.id) && covers(it.path, file.path)) {716 freed << file.hash717 }718 }719 import_arriving(store, record, strips)!720 }721 store.drop_unused(freed)!722}723724725726pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {727 for hash, body in fetched.manifests {728 store.put_manifest(body)!729 }730 for hash, blob in fetched.repo_objects {731 store.put_object_blob(hash, blob)!732 }733 strips := known_strips(store, fetched)!734 for record in fetched.saves {735 import_arriving(store, record, strips)!736 }737}738739740741fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {742 mut strips := events.strip_events(store)!743 strips << fetched.events_out744 return strips.filter(events.valid_strip(it))745}746747748749fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {750 if history.by_id(store, record.id) != none {751 return752 }753 validate_save(record, record.id)!754 safe := record.files.filter(snapshot.legal_path(it.path))755 validate_hashes(record.id, safe)!756 files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {757 return snapshot.legal_path(file.path)758 && !strips.any(reaches(it, record.id) && covers(it.path, file.path))759 })760 761 762 mut save := to_save(record)763 save.manifest = ''764 if record.manifest != '' && files.len == record.files.len {765 save.manifest = record.manifest766 }767 history.import_save(store, save, files)!768}769770771772fn reaches(strip events.Event, save_id string) bool {773 return strip.save_id == '' || strip.save_id == save_id774}