1234567891011module exchange1213import os14import src.events15import src.fmt16import src.history17import src.remote18import src.snapshot19import src.storage202122const repo_state_key = 'remote_repo'23242526const remote_head_key = 'remote_head'2728pub const no_saves = 'this repo has no saves yet — nothing to offer'29303132const format_value = 'koh-remote 1'3334353637fn put_format(mut backend remote.Backend, repo string) ! {38 if backend.put_if_absent(format_key(repo), format_value.bytes())! {39 return40 }41 check_format(mut backend, repo)!42}4344454647fn check_format(mut backend remote.Backend, repo string) !string {48 existing := backend.get(format_key(repo))!49 if !existing.found {50 return ''51 }52 value := existing.body.bytestr().trim_space()53 if value != format_value {54 return error('the remote "${repo}" is "${value}" — this koh speaks "${format_value}"; update koh')55 }56 return value57}5859pub struct OfferReport {60pub mut:61 repo string62 saves int63 objects int64 events int65 head string66}67686970pub fn remember_repo(store &storage.Store, name string) ! {71 store.set_state(repo_state_key, name)!72}7374757677pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {78 if remembered := store.state(repo_state_key) {79 return follow_rename(store, mut backend, remembered)!80 }81 name := os.base(store.root).to_lower()82 83 84 check_format(mut backend, name)!85 existing := backend.get(head_key(name))!86 if existing.found {87 theirs := existing.body.bytestr().trim_space()88 if history.by_id(store, theirs) == none {89 return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')90 }91 }92 store.set_state(repo_state_key, name)!93 return name94}9596979899fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !string {100 mut name := remembered101 for _ in 0 .. 5 {102 if backend.get(head_key(name))!.found {103 break104 }105 marker := backend.get('.kepr/renamed/${name}')!106 next := marker.body.bytestr().trim_space()107 if !marker.found || next == '' || next.contains('/') || next.contains('\\') || next in [108 '.',109 '..',110 ] {111 break112 }113 name = next114 }115 if name != remembered {116 store.set_state(repo_state_key, name)!117 }118 return name119}120121122123pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {124 name := repo_name(store, mut backend)!125 local := history.head(store) or { return error(no_saves) }126 mut report := OfferReport{127 repo: name128 head: local.id129 }130 if check_format(mut backend, name)! == '' {131 132 put_format(mut backend, name)!133 }134 remote_head := backend.get(head_key(name))!135 136 137 if unapplied_strips(store, mut backend, name)!.len > 0 {138 return error(strip_not_applied)139 }140 mut uploaded := Uploaded{}141 upload_line(store, mut backend, name, local.id, remote_head, mut report, mut uploaded) or {142 return after_failed_upload(store, mut backend, name, uploaded, err)143 }144 145 146 147 if undo_late_strips(store, mut backend, name, uploaded)! {148 return error(strip_not_applied)149 }150 if !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {151 return error('remote has new saves — run koh steal')152 }153 store.set_state(remote_head_key, local.id)!154 return report155}156157158159160fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {161 mut newer := []history.Save{}162 mut cursor := ours163 for cursor != '' && cursor != theirs {164 save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }165 newer << save166 cursor = save.parent167 }168 if cursor != theirs {169 return error('${theirs} is not on this line')170 }171 newer.reverse_in_place()172 return newer173}174175const strip_not_applied = 'the remote has a strip this repo has not applied — run koh steal'176177178struct Uploaded {179mut:180 saves []string181 objects map[string]bool182}183184fn (u Uploaded) done() []string {185 return if u.saves.len + u.objects.len == 0 {186 []string{}187 } else {188 ['uploaded ${fmt.plural(u.objects.len, 'object')} and ${fmt.plural(u.saves.len, 'save record')}']189 }190}191192193fn upload_line(store &storage.Store, mut backend remote.Backend, name string, local string, remote_head remote.Object, mut report OfferReport, mut uploaded Uploaded) ! {194 if remote_head.found {195 theirs := remote_head.body.bytestr().trim_space()196 newer := saves_after(store, local, theirs) or {197 return error('remote has new saves — run koh steal')198 }199 for save in newer {200 upload_save(store, mut backend, name, save, mut report, mut uploaded)!201 }202 } else {203 oldest_first := history.line(store)!204 for index := oldest_first.len - 1; index >= 0; index-- {205 upload_save(store, mut backend, name, oldest_first[index], mut report, mut uploaded)!206 }207 }208 upload_events(store, mut backend, name, mut report)!209}210211212213fn after_failed_upload(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, failure IError) IError {214 undo_late_strips(store, mut backend, repo, uploaded) or {215 return error('${failure.msg()}; removing what a strip on the remote covers also failed: ${err.msg()}')216 }217 return failure218}219220221222223224225fn undo_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {226 strips := unapplied_strips(store, mut backend, repo)!227 if strips.len == 0 {228 return false229 }230 231 232 drop_stripped_objects(store, mut backend, repo, uploaded, strips)!233 for id in uploaded.saves {234 strip_record(mut backend, save_key(repo, id), id, strips)!235 }236 return true237}238239240241242fn strip_record(mut backend remote.Backend, key string, id string, strips []events.Event) ! {243 for _ in 0 .. 5 {244 object := backend.get(key)!245 if !object.found {246 return247 }248 record := decode_save(object.body)!249 kept := record.files.filter(fn [strips, id] (file FileRecord) bool {250 return !strips.any(reaches(it, id) && covers(it.path, file.path))251 })252 if kept.len == record.files.len253 || backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), object.tag)! {254 return255 }256 }257 return error('the remote copy of save ${id} kept changing while a stripped path was removed; run koh doctor again')258}259260261262pub struct Partway {263 Error264pub:265 done string266 reason string267}268269pub fn (e Partway) msg() string {270 return e.reason271}272273274275pub fn partway(done []string, failure IError) IError {276 mut all := done.clone()277 if failure is Partway {278 all << failure.done279 }280 if all.len == 0 {281 return failure282 }283 return Partway{284 done: all.join('; ')285 reason: failure.msg()286 }287}288289290291292fn drop_stripped_objects(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {293 mut reached := map[string]bool{}294 for save in history.all_saves(store)! {295 for file in history.files_of(store, save.id)! {296 if file.hash in uploaded.objects && strips.any(reaches(it, save.id) && covers(it.path, file.path)) {297 reached[file.hash] = true298 }299 }300 }301 if reached.len == 0 {302 return303 }304 for key in backend.list('${repo}/saves')! {305 object := backend.get(key)!306 if object.found {307 record := decode_save(object.body)!308 for file in record.files {309 if !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {310 reached.delete(file.hash)311 }312 }313 }314 }315 for hash, _ in reached {316 backend.delete(object_key(repo, hash))!317 }318}319320321322323fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport, mut uploaded Uploaded) ! {324 files := history.files_of(store, save.id)!325 326 327 328 mut sent := map[string]bool{}329 if save.parent != '' {330 for file in history.files_of(store, save.parent)! {331 sent[file.hash] = true332 }333 }334 for file in files {335 if file.hash in sent {336 continue337 }338 sent[file.hash] = true339 if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {340 report.objects++341 uploaded.objects[file.hash] = true342 }343 }344 record := save_record(store, save)!345 if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {346 report.saves++347 uploaded.saves << save.id348 }349}350351352353fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, mut report OfferReport) ! {354 already := backend.list(events_prefix(repo))!355 mut already_sent := map[string]bool{}356 for key in already {357 already_sent[os.base(key)] = true358 }359 for event in events.all(store)! {360 if event.id in already_sent {361 continue362 }363 if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {364 report.events++365 }366 }367}368369370371372pub struct Fetched {373pub mut:374 repo_objects map[string][]u8375 saves []SaveRecord 376 events_out []events.Event377 head string378 base string 379 unsafe_paths []string380}381382383384385pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {386 check_format(mut backend, repo)!387 remote_head := backend.get(head_key(repo))!388 if !remote_head.found {389 return error('the remote has no "${repo}" yet — run koh offer here first')390 }391 mut fetched := Fetched{392 head: remote_head.body.bytestr().trim_space()393 }394 mut on_line := map[string]bool{}395 for save in history.line(store)! {396 on_line[save.id] = true397 }398 mut cursor := fetched.head399 for cursor != '' && cursor !in on_line {400 mut record := if saved := history.by_id(store, cursor) {401 save_record(store, saved)!402 } else {403 record_object := backend.get(save_key(repo, cursor))!404 if !record_object.found {405 return error('the remote is missing save ${cursor} — run koh offer there')406 }407 decode_save(record_object.body)!408 }409 fetched.unsafe_paths << drop_unsafe_paths(mut record)410 for file in record.files {411 if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects {412 blob := backend.get(object_key(repo, file.hash))!413 if !blob.found {414 return error('the remote is missing object ${file.hash} that save ${record.id} needs')415 }416 fetched.repo_objects[file.hash] = blob.body417 }418 }419 fetched.saves << record420 cursor = record.parent421 }422 fetched.saves.reverse_in_place()423 fetched.base = cursor424 fetched.events_out = fetch_events(store, mut backend, repo)!425 return fetched426}427428fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {429 have := events.all(store)!430 mut known := map[string]bool{}431 for event in have {432 known[event.id] = true433 }434 mut incoming := []events.Event{}435 for key in backend.list(events_prefix(repo))! {436 id := os.base(key)437 if id in known {438 continue439 }440 body := backend.get(event_key(repo, id))!441 if !body.found {442 continue443 }444 event := decode_event(body.body)!445 if !ignored_strip(event) {446 incoming << event447 }448 }449 return incoming450}451452453454455pub fn write_fetched(store &storage.Store, fetched Fetched) ! {456 for hash, blob in fetched.repo_objects {457 store.put_object_blob(hash, blob)!458 }459 mut stripped := false460 for event in fetched.events_out {461 if !events.receive(store, event)! {462 continue463 }464 if events.valid_strip(event) {465 remove_path(store, event.path, event.save_id)!466 stripped = true467 }468 }469 strips := known_strips(store, fetched)!470 for record in fetched.saves {471 import_arriving(store, record, strips)!472 }473 if stripped {474 store.drop_unreferenced_objects()!475 }476}477478479480pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {481 for hash, blob in fetched.repo_objects {482 store.put_object_blob(hash, blob)!483 }484 strips := known_strips(store, fetched)!485 for record in fetched.saves {486 import_arriving(store, record, strips)!487 }488}489490491492fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {493 mut strips := events.strip_events(store)!494 strips << fetched.events_out495 return strips.filter(events.valid_strip(it))496}497498499500fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {501 if history.by_id(store, record.id) != none {502 return503 }504 files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {505 return snapshot.legal_path(file.path)506 && !strips.any(reaches(it, record.id) && covers(it.path, file.path))507 })508 history.import_save(store, to_save(record), files)!509}510511512513fn reaches(strip events.Event, save_id string) bool {514 return strip.save_id == '' || strip.save_id == save_id515}