exchange.v

17.8 KB · raw

1//! Sync: offer and steal.2//!3//! All the cleverness sits here, above the five-operation remote interface, so4//! the backends stay thin and this logic is written once and tested offline.5//!6//! The remote is a line of saves, the same shape as the local one. `offer`7//! sends local saves the remote lacks; `steal` takes remote saves and, when8//! both sides moved, replays the local work on top of the remote's. Divergence9//! is resolved per file, never per line.1011module exchange1213import os14import src.events15import src.fmt16import src.history17import src.remote18import src.snapshot19import src.storage2021// Where the repo's name on the remote is remembered.22const repo_state_key = 'remote_repo'2324// The remote head as of this machine's last successful offer: a record for the25// person or a future feature. Nothing depends on it.26const remote_head_key = 'remote_head'2728pub const no_saves = 'this repo has no saves yet — nothing to offer'2930// The only remote layout this koh reads or writes. A repo offered before the31// key existed has no `format` key and counts as this version.32const format_value = 'koh-remote 1'3334// put_format records the layout on a repo that has none. put_if_absent never35// overwrites, so a machine that wrote one while this one read wins the race:36// its value is read back and checked, never assumed.37fn 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}4344// check_format reads <repo>/format and refuses a remote written by a koh that45// speaks another layout, so two versions never half-understand one bucket. An46// empty answer means the key is missing: version 1, which `offer` records.47fn 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}6768// remember_repo binds a repo to its name on the remote. A steal into a new folder does it at69// once: its folder may be renamed before it ever offers.70pub fn remember_repo(store &storage.Store, name string) ! {71	store.set_state(repo_state_key, name)!72}7374// repo_name is the folder's name at first offer, lowercased so it makes the same75// Kepr URL whatever the folder's case (June, 2026-10-01), and remembered in the76// repo so renaming the folder later changes nothing.77pub 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	// Before the clash check below: a remote this koh cannot read is a "update83	// koh" answer, not a "rename the folder" one.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}9596// follow_rename follows the marker Kepr leaves when it renames a repo, `.kepr/renamed/<old>`97// holding the new name (§30, 2026-10-01), for as long as the remembered name has no `head`, and98// remembers where it led. A few hops cover a repo renamed more than once.99fn 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}120121// offer sends what the remote lacks and then swaps `head`. Nothing is ever122// queued: the next offer simply sends everything the remote does not have.123pub 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		// Offered before this key existed: record the layout now.132		put_format(mut backend, name)!133	}134	remote_head := backend.get(head_key(name))!135	// Records offered by a machine that has not applied a strip would put the136	// stripped path back on the remote, where nothing would rewrite it again.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	// A strip sends its event before it lists the saves to rewrite, so one145	// missed here lists them after these records landed and rewrites them. One146	// seen here may have rewritten before they landed: take back what it reaches.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}156157// saves_after lists the local saves newer than `theirs`, oldest first. It fails158// when `theirs` is not on this line, which is the honest answer: we cannot159// offer on top of a save we do not have.160fn 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'176177// Uploaded is what one upload put on the remote, so a late strip can take it back.178struct 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}191192// upload_line sends every save after the remote head, then the events.193fn 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}210211// after_failed_upload still applies a strip that landed before the failure212// to what the upload had put.213fn 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}219220// undo_late_strips applies strips that reached the remote during an upload to221// what the upload put, and reports whether there were any. Records stay, less222// the stripped paths: another offer, or head itself, may already name them.223// If this fails, Doctor's remote audit finds what is left and sends the strip224// again once this repo holds it.225fn 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	// Objects go first: a record that still lists the path is what lets231	// Doctor's remote audit find the strip again if this stops part way.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}238239// strip_record rewrites one remote record without what `strips` cover. A240// record that moved meanwhile is read again, since the other writer may have241// kept a path these strips name.242fn 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}259260// Partway is a failure after some work had already landed. `done` says what,261// so Doctor can report both.262pub struct Partway {263	Error264pub:265	done   string266	reason string267}268269pub fn (e Partway) msg() string {270	return e.reason271}272273// partway adds what was `done` before `failure` to it, including what a274// failing step of its own had done.275pub 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}288289// drop_stripped_objects deletes what an upload put that a strip reaches in a290// save here, unless a remote record lists it under a path no strip covers:291// another machine may hold the same bytes there.292fn 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}319320// upload_save puts a save's new objects, then its record, so a record on the remote always finds its321// objects there. Both are put_if_absent, so a retry after a partial offer is safe; `uploaded` keeps322// what this call created, which is all undo_late_strips may delete.323fn 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	// Saves go up oldest first and head moves only once all of them landed, so326	// the parent and its objects are on the remote already: only content new327	// in this save travels, not a round trip per file in the repo.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}350351// upload_events sends every event the remote does not have. Events are tiny, so352// listing them costs less than tracking which ones were sent.353fn 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}368369// fetched holds everything a steal read from the remote, before any of it is370// written locally. Network work happens first; the database gets one371// transaction, so a failure leaves nothing half-applied.372pub struct Fetched {373pub mut:374	repo_objects map[string][]u8375	saves        []SaveRecord // oldest first376	events_out   []events.Event377	head         string378	base         string // the newest save both sides already shared, '' when none379	unsafe_paths []string380}381382// fetch_back_to_known walks from the remote head along parents until it meets a save on this line383// (`base`), reading only the objects this repo lacks. Nothing is written here: write_fetched lands it.384// A save held locally but off the line, from an earlier steal, is taken from the local copy.385pub 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}451452// write_fetched lands a fetch in one transaction: objects first (verified),453// then the events, then the saves they belong to. A strip bans its path from454// all of history, so it reaches every save, here or arriving, whenever made.455pub 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}477478// write_fetched_records makes network work durable without changing the line.479// Events wait for the combine transaction because a strip can rewrite history.480pub 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}489490// known_strips is every valid strip held here and every one the fetch brings:491// an arriving save loses what any of them reaches, not only what arrived with it.492fn 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}497498// import_arriving lands one save from the remote, unless it is already here, less every path a499// strip that `reaches` it removed.500fn 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}510511// reaches reports whether a strip event applies to a save: its one save, or512// every save there is, whenever it was made.513fn reaches(strip events.Event, save_id string) bool {514	return strip.save_id == '' || strip.save_id == save_id515}