exchange.v

14.3 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.history16import src.remote17import src.snapshot18import src.storage1920// Where the repo's name on the remote is remembered.21const repo_state_key = 'remote_repo'2223// The remote head as of this machine's last successful offer: a record for the24// person or a future feature. Nothing depends on it.25const remote_head_key = 'remote_head'2627pub const no_saves = 'this repo has no saves yet — nothing to offer'2829// The only remote layout this koh reads or writes. A repo offered before the30// key existed has no `format` key and counts as this version.31const format_value = 'koh-remote 1'3233// put_format records the layout on a repo that has none. put_if_absent never34// overwrites, so a machine that wrote one while this one read wins the race:35// its value is read back and checked, never assumed.36fn put_format(mut backend remote.Backend, repo string) ! {37	if backend.put_if_absent(format_key(repo), format_value.bytes())! {38		return39	}40	check_format(mut backend, repo)!41}4243// check_format reads <repo>/format and refuses a remote written by a koh that44// speaks another layout, so two versions never half-understand one bucket. An45// empty answer means the key is missing: version 1, which `offer` records.46fn check_format(mut backend remote.Backend, repo string) !string {47	existing := backend.get(format_key(repo))!48	if !existing.found {49		return ''50	}51	value := existing.body.bytestr().trim_space()52	if value != format_value {53		return error('the remote "${repo}" is "${value}" — this koh speaks "${format_value}"; update koh')54	}55	return value56}5758pub struct OfferReport {59pub mut:60	repo    string61	saves   int62	objects int63	events  int64	head    string65}6667// remember_repo binds a repo to its name on the remote. A steal into a new folder does it at68// once: its folder may be renamed before it ever offers.69pub fn remember_repo(store &storage.Store, name string) ! {70	store.set_state(repo_state_key, name)!71}7273// repo_name is the folder's name at first offer, lowercased so it makes the same74// Kepr URL whatever the folder's case (June, 2026-10-01), and remembered in the75// repo so renaming the folder later changes nothing.76pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {77	if remembered := store.state(repo_state_key) {78		return follow_rename(store, mut backend, remembered)!79	}80	name := os.base(store.root).to_lower()81	// Before the clash check below: a remote this koh cannot read is a "update82	// koh" answer, not a "rename the folder" one.83	check_format(mut backend, name)!84	existing := backend.get(head_key(name))!85	if existing.found {86		theirs := existing.body.bytestr().trim_space()87		if history.by_id(store, theirs) == none {88			return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')89		}90	}91	store.set_state(repo_state_key, name)!92	return name93}9495// follow_rename follows the marker Kepr leaves when it renames a repo, `.kepr/renamed/<old>`96// holding the new name (§30, 2026-10-01), for as long as the remembered name has no `head`, and97// remembers where it led. A few hops cover a repo renamed more than once.98fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !string {99	mut name := remembered100	for _ in 0 .. 5 {101		if backend.get(head_key(name))!.found {102			break103		}104		marker := backend.get('.kepr/renamed/${name}')!105		next := marker.body.bytestr().trim_space()106		if !marker.found || next == '' || next.contains('/') || next.contains('\\') || next in [107			'.',108			'..',109		] {110			break111		}112		name = next113	}114	if name != remembered {115		store.set_state(repo_state_key, name)!116	}117	return name118}119120// offer sends what the remote lacks and then swaps `head`. Nothing is ever121// queued: the next offer simply sends everything the remote does not have.122pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {123	name := repo_name(store, mut backend)!124	local := history.head(store) or { return error(no_saves) }125	mut report := OfferReport{126		repo: name127		head: local.id128	}129	if check_format(mut backend, name)! == '' {130		// Offered before this key existed: record the layout now.131		put_format(mut backend, name)!132	}133	remote_head := backend.get(head_key(name))!134	// Records offered by a machine that has not applied a strip would put the135	// stripped path back on the remote, where nothing would rewrite it again.136	if unapplied_strips(store, mut backend, name)!.len > 0 {137		return error(strip_not_applied)138	}139	mut uploaded := Uploaded{}140	if remote_head.found {141		theirs := remote_head.body.bytestr().trim_space()142		newer := saves_after(store, local.id, theirs) or {143			return error('remote has new saves — run koh steal')144		}145		for save in newer {146			upload_save(store, mut backend, name, save, mut report, mut uploaded)!147		}148	} else {149		oldest_first := history.line(store)!150		for index := oldest_first.len - 1; index >= 0; index-- {151			upload_save(store, mut backend, name, oldest_first[index], mut report, mut uploaded)!152		}153	}154	upload_events(store, mut backend, name, mut report)!155	// A strip sends its event before it lists the saves to rewrite, so one156	// missed here lists them after these records landed and rewrites them. One157	// seen here may have rewritten before they landed: take back what it reaches.158	late := unapplied_strips(store, mut backend, name)!159	if late.len > 0 {160		take_back(store, mut backend, name, uploaded, late)!161		return error(strip_not_applied)162	}163	if !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {164		return error('remote has new saves — run koh steal')165	}166	store.set_state(remote_head_key, local.id)!167	return report168}169170// saves_after lists the local saves newer than `theirs`, oldest first. It fails171// when `theirs` is not on this line, which is the honest answer: we cannot172// offer on top of a save we do not have.173fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {174	mut newer := []history.Save{}175	mut cursor := ours176	for cursor != '' && cursor != theirs {177		save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }178		newer << save179		cursor = save.parent180	}181	if cursor != theirs {182		return error('${theirs} is not on this line')183	}184	newer.reverse_in_place()185	return newer186}187188const strip_not_applied = 'the remote has a strip this repo has not applied — run koh steal'189190// Uploaded is what one offer put on the remote, so a late strip can take it back.191struct Uploaded {192mut:193	saves   []string194	objects map[string]bool195}196197// take_back deletes the records an offer or Doctor's resend put, which head198// never reached, and every object it put that a strip reaches in a save here.199fn take_back(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {200	mut reached := map[string]bool{}201	for save in history.all_saves(store)! {202		for file in history.files_of(store, save.id)! {203			if file.hash in uploaded.objects && strips.any(reaches(it, save.id) && covers(it.path, file.path)) {204				reached[file.hash] = true205			}206		}207	}208	for id in uploaded.saves {209		backend.delete(save_key(repo, id))!210	}211	for hash, _ in reached {212		backend.delete(object_key(repo, hash))!213	}214}215216// upload_save puts a save's new objects, then its record, so a record on the remote always finds its217// objects there. Both are put_if_absent, so a retry after a partial offer is safe; `uploaded` keeps218// what this call created, which is all take_back may delete.219fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport, mut uploaded Uploaded) ! {220	files := history.files_of(store, save.id)!221	// Saves go up oldest first and head moves only once all of them landed, so222	// the parent and its objects are on the remote already: only content new223	// in this save travels, not a round trip per file in the repo.224	mut sent := map[string]bool{}225	if save.parent != '' {226		for file in history.files_of(store, save.parent)! {227			sent[file.hash] = true228		}229	}230	for file in files {231		if file.hash in sent {232			continue233		}234		sent[file.hash] = true235		if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {236			report.objects++237			uploaded.objects[file.hash] = true238		}239	}240	record := save_record(store, save)!241	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {242		report.saves++243		uploaded.saves << save.id244	}245}246247// upload_events sends every event the remote does not have. Events are tiny, so248// listing them costs less than tracking which ones were sent.249fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, mut report OfferReport) ! {250	already := backend.list(events_prefix(repo))!251	mut already_sent := map[string]bool{}252	for key in already {253		already_sent[os.base(key)] = true254	}255	for event in events.all(store)! {256		if event.id in already_sent {257			continue258		}259		if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {260			report.events++261		}262	}263}264265// fetched holds everything a steal read from the remote, before any of it is266// written locally. Network work happens first; the database gets one267// transaction, so a failure leaves nothing half-applied.268pub struct Fetched {269pub mut:270	repo_objects map[string][]u8271	saves        []SaveRecord // oldest first272	events_out   []events.Event273	head         string274	base         string // the newest save both sides already shared, '' when none275	unsafe_paths []string276}277278// fetch_back_to_known walks from the remote head along parents until it meets a save on this line279// (`base`), reading only the objects this repo lacks. Nothing is written here: write_fetched lands it.280// A save held locally but off the line, from an earlier steal, is taken from the local copy.281pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {282	check_format(mut backend, repo)!283	remote_head := backend.get(head_key(repo))!284	if !remote_head.found {285		return error('the remote has no "${repo}" yet — run koh offer here first')286	}287	mut fetched := Fetched{288		head: remote_head.body.bytestr().trim_space()289	}290	mut on_line := map[string]bool{}291	for save in history.line(store)! {292		on_line[save.id] = true293	}294	mut cursor := fetched.head295	for cursor != '' && cursor !in on_line {296		mut record := if saved := history.by_id(store, cursor) {297			save_record(store, saved)!298		} else {299			record_object := backend.get(save_key(repo, cursor))!300			if !record_object.found {301				return error('the remote is missing save ${cursor} — run koh offer there')302			}303			decode_save(record_object.body)!304		}305		fetched.unsafe_paths << drop_unsafe_paths(mut record)306		for file in record.files {307			if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects {308				blob := backend.get(object_key(repo, file.hash))!309				if !blob.found {310					return error('the remote is missing object ${file.hash} that save ${record.id} needs')311				}312				fetched.repo_objects[file.hash] = blob.body313			}314		}315		fetched.saves << record316		cursor = record.parent317	}318	fetched.saves.reverse_in_place()319	fetched.base = cursor320	fetched.events_out = fetch_events(store, mut backend, repo)!321	return fetched322}323324fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {325	have := events.all(store)!326	mut known := map[string]bool{}327	for event in have {328		known[event.id] = true329	}330	mut incoming := []events.Event{}331	for key in backend.list(events_prefix(repo))! {332		id := os.base(key)333		if id in known {334			continue335		}336		body := backend.get(event_key(repo, id))!337		if !body.found {338			continue339		}340		event := decode_event(body.body)!341		if !ignored_strip(event) {342			incoming << event343		}344	}345	return incoming346}347348// write_fetched lands a fetch in one transaction: objects first (verified),349// then the events, then the saves they belong to. A strip bans its path from350// all of history, so it reaches every save, here or arriving, whenever made.351pub fn write_fetched(store &storage.Store, fetched Fetched) ! {352	for hash, blob in fetched.repo_objects {353		store.put_object_blob(hash, blob)!354	}355	mut stripped := false356	for event in fetched.events_out {357		if !events.receive(store, event)! {358			continue359		}360		if event.kind == events.kind_strip {361			remove_path(store, event.path, event.save_id)!362			stripped = true363		}364	}365	strips := known_strips(store, fetched)!366	for record in fetched.saves {367		import_arriving(store, record, strips)!368	}369	if stripped {370		store.drop_unreferenced_objects()!371	}372}373374// write_fetched_records makes network work durable without changing the line.375// Events wait for the combine transaction because a strip can rewrite history.376pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {377	for hash, blob in fetched.repo_objects {378		store.put_object_blob(hash, blob)!379	}380	strips := known_strips(store, fetched)!381	for record in fetched.saves {382		import_arriving(store, record, strips)!383	}384}385386// known_strips is every strip held here and every one the fetch brings: an387// arriving save loses what any of them reaches, not only what arrived with it.388fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {389	mut strips := events.strip_events(store)!390	strips << fetched.events_out.filter(it.kind == events.kind_strip)391	return strips392}393394// import_arriving lands one save from the remote, unless it is already here, less every path a395// strip that `reaches` it removed.396fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {397	if history.by_id(store, record.id) != none {398		return399	}400	files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {401		return snapshot.legal_path(file.path)402			&& !strips.any(reaches(it, record.id) && covers(it.path, file.path))403	})404	history.import_save(store, to_save(record), files)!405}406407// reaches reports whether a strip event applies to a save: its one save, or408// every save there is, whenever it was made.409fn reaches(strip events.Event, save_id string) bool {410	return strip.save_id == '' || strip.save_id == save_id411}