exchange.v

17.5 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	for id in uploaded.saves {231		strip_record(mut backend, save_key(repo, id), id, strips)!232	}233	drop_stripped_objects(store, mut backend, repo, uploaded, strips)!234	return true235}236237// strip_record rewrites one remote record without what `strips` cover. A238// record that moved meanwhile is read again, since the other writer may have239// kept a path these strips name.240fn strip_record(mut backend remote.Backend, key string, id string, strips []events.Event) ! {241	for _ in 0 .. 5 {242		object := backend.get(key)!243		if !object.found {244			return245		}246		record := decode_save(object.body)!247		kept := record.files.filter(fn [strips, id] (file FileRecord) bool {248			return !strips.any(reaches(it, id) && covers(it.path, file.path))249		})250		if kept.len == record.files.len251			|| backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), object.tag)! {252			return253		}254	}255	return error('the remote copy of save ${id} kept changing while a stripped path was removed; run koh doctor again')256}257258// Partway is a failure after some work had already landed. `done` says what,259// so Doctor can report both.260pub struct Partway {261	Error262pub:263	done   string264	reason string265}266267pub fn (e Partway) msg() string {268	return e.reason269}270271// partway adds what was `done` before `failure` to it, including what a272// failing step of its own had done.273pub fn partway(done []string, failure IError) IError {274	mut all := done.clone()275	if failure is Partway {276		all << failure.done277	}278	if all.len == 0 {279		return failure280	}281	return Partway{282		done:   all.join('; ')283		reason: failure.msg()284	}285}286287// drop_stripped_objects deletes what an upload put that a strip reaches in a288// save here, unless a remote record still lists it: another machine may hold289// the same bytes under a path no strip names.290fn drop_stripped_objects(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {291	mut reached := map[string]bool{}292	for save in history.all_saves(store)! {293		for file in history.files_of(store, save.id)! {294			if file.hash in uploaded.objects && strips.any(reaches(it, save.id) && covers(it.path, file.path)) {295				reached[file.hash] = true296			}297		}298	}299	if reached.len == 0 {300		return301	}302	for key in backend.list('${repo}/saves')! {303		object := backend.get(key)!304		if object.found {305			for file in decode_save(object.body)!.files {306				reached.delete(file.hash)307			}308		}309	}310	for hash, _ in reached {311		backend.delete(object_key(repo, hash))!312	}313}314315// upload_save puts a save's new objects, then its record, so a record on the remote always finds its316// objects there. Both are put_if_absent, so a retry after a partial offer is safe; `uploaded` keeps317// what this call created, which is all undo_late_strips may delete.318fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport, mut uploaded Uploaded) ! {319	files := history.files_of(store, save.id)!320	// Saves go up oldest first and head moves only once all of them landed, so321	// the parent and its objects are on the remote already: only content new322	// in this save travels, not a round trip per file in the repo.323	mut sent := map[string]bool{}324	if save.parent != '' {325		for file in history.files_of(store, save.parent)! {326			sent[file.hash] = true327		}328	}329	for file in files {330		if file.hash in sent {331			continue332		}333		sent[file.hash] = true334		if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {335			report.objects++336			uploaded.objects[file.hash] = true337		}338	}339	record := save_record(store, save)!340	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {341		report.saves++342		uploaded.saves << save.id343	}344}345346// upload_events sends every event the remote does not have. Events are tiny, so347// listing them costs less than tracking which ones were sent.348fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, mut report OfferReport) ! {349	already := backend.list(events_prefix(repo))!350	mut already_sent := map[string]bool{}351	for key in already {352		already_sent[os.base(key)] = true353	}354	for event in events.all(store)! {355		if event.id in already_sent {356			continue357		}358		if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {359			report.events++360		}361	}362}363364// fetched holds everything a steal read from the remote, before any of it is365// written locally. Network work happens first; the database gets one366// transaction, so a failure leaves nothing half-applied.367pub struct Fetched {368pub mut:369	repo_objects map[string][]u8370	saves        []SaveRecord // oldest first371	events_out   []events.Event372	head         string373	base         string // the newest save both sides already shared, '' when none374	unsafe_paths []string375}376377// fetch_back_to_known walks from the remote head along parents until it meets a save on this line378// (`base`), reading only the objects this repo lacks. Nothing is written here: write_fetched lands it.379// A save held locally but off the line, from an earlier steal, is taken from the local copy.380pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {381	check_format(mut backend, repo)!382	remote_head := backend.get(head_key(repo))!383	if !remote_head.found {384		return error('the remote has no "${repo}" yet — run koh offer here first')385	}386	mut fetched := Fetched{387		head: remote_head.body.bytestr().trim_space()388	}389	mut on_line := map[string]bool{}390	for save in history.line(store)! {391		on_line[save.id] = true392	}393	mut cursor := fetched.head394	for cursor != '' && cursor !in on_line {395		mut record := if saved := history.by_id(store, cursor) {396			save_record(store, saved)!397		} else {398			record_object := backend.get(save_key(repo, cursor))!399			if !record_object.found {400				return error('the remote is missing save ${cursor} — run koh offer there')401			}402			decode_save(record_object.body)!403		}404		fetched.unsafe_paths << drop_unsafe_paths(mut record)405		for file in record.files {406			if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects {407				blob := backend.get(object_key(repo, file.hash))!408				if !blob.found {409					return error('the remote is missing object ${file.hash} that save ${record.id} needs')410				}411				fetched.repo_objects[file.hash] = blob.body412			}413		}414		fetched.saves << record415		cursor = record.parent416	}417	fetched.saves.reverse_in_place()418	fetched.base = cursor419	fetched.events_out = fetch_events(store, mut backend, repo)!420	return fetched421}422423fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {424	have := events.all(store)!425	mut known := map[string]bool{}426	for event in have {427		known[event.id] = true428	}429	mut incoming := []events.Event{}430	for key in backend.list(events_prefix(repo))! {431		id := os.base(key)432		if id in known {433			continue434		}435		body := backend.get(event_key(repo, id))!436		if !body.found {437			continue438		}439		event := decode_event(body.body)!440		if !ignored_strip(event) {441			incoming << event442		}443	}444	return incoming445}446447// write_fetched lands a fetch in one transaction: objects first (verified),448// then the events, then the saves they belong to. A strip bans its path from449// all of history, so it reaches every save, here or arriving, whenever made.450pub fn write_fetched(store &storage.Store, fetched Fetched) ! {451	for hash, blob in fetched.repo_objects {452		store.put_object_blob(hash, blob)!453	}454	mut stripped := false455	for event in fetched.events_out {456		if !events.receive(store, event)! {457			continue458		}459		if events.valid_strip(event) {460			remove_path(store, event.path, event.save_id)!461			stripped = true462		}463	}464	strips := known_strips(store, fetched)!465	for record in fetched.saves {466		import_arriving(store, record, strips)!467	}468	if stripped {469		store.drop_unreferenced_objects()!470	}471}472473// write_fetched_records makes network work durable without changing the line.474// Events wait for the combine transaction because a strip can rewrite history.475pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {476	for hash, blob in fetched.repo_objects {477		store.put_object_blob(hash, blob)!478	}479	strips := known_strips(store, fetched)!480	for record in fetched.saves {481		import_arriving(store, record, strips)!482	}483}484485// known_strips is every valid strip held here and every one the fetch brings:486// an arriving save loses what any of them reaches, not only what arrived with it.487fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {488	mut strips := events.strip_events(store)!489	strips << fetched.events_out490	return strips.filter(events.valid_strip(it))491}492493// import_arriving lands one save from the remote, unless it is already here, less every path a494// strip that `reaches` it removed.495fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {496	if history.by_id(store, record.id) != none {497		return498	}499	files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {500		return snapshot.legal_path(file.path)501			&& !strips.any(reaches(it, record.id) && covers(it.path, file.path))502	})503	history.import_save(store, to_save(record), files)!504}505506// reaches reports whether a strip event applies to a save: its one save, or507// every save there is, whenever it was made.508fn reaches(strip events.Event, save_id string) bool {509	return strip.save_id == '' || strip.save_id == save_id510}