exchange.v

21.4 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 json214import os15import src.events16import src.fmt17import src.history18import src.remote19import src.snapshot20import src.storage2122// Where the repo's name on the remote is remembered.23const repo_state_key = 'remote_repo'2425// The remote head as of this machine's last successful offer: a record for the26// person or a future feature. Nothing depends on it.27const remote_head_key = 'remote_head'2829pub const no_saves = 'this repo has no saves yet — nothing to offer'3031// The only remote layout this koh reads or writes. A repo offered before the32// key existed has no `format` key and counts as this version.33const format_value = 'koh-remote 1'3435// put_format records the layout on a repo that has none. put_if_absent never36// overwrites, so a machine that wrote one while this one read wins the race:37// its value is read back and checked, never assumed.38fn put_format(mut backend remote.Backend, repo string) ! {39	if backend.put_if_absent(format_key(repo), format_value.bytes())! {40		return41	}42	check_format(mut backend, repo)!43}4445// check_format reads <repo>/format and refuses a remote written by a koh that46// speaks another layout, so two versions never half-understand one bucket. An47// empty answer means the key is missing: version 1, which `offer` records.48fn check_format(mut backend remote.Backend, repo string) !string {49	existing := backend.get(format_key(repo))!50	if !existing.found {51		return ''52	}53	value := existing.body.bytestr().trim_space()54	if value != format_value {55		return error('the remote "${repo}" is "${value}" — this koh speaks "${format_value}"; update koh')56	}57	return value58}5960pub struct OfferReport {61pub mut:62	repo    string63	saves   int64	objects int65	events  int66	head    string67}6869// remember_repo binds a repo to its name on the remote. A steal into a new folder does it at70// once: its folder may be renamed before it ever offers.71pub fn remember_repo(store &storage.Store, name string) ! {72	store.set_state(repo_state_key, name)!73}7475// repo_name is the folder's name at first offer, lowercased so it makes the same76// Kepr URL whatever the folder's case (June, 2026-10-01), and remembered in the77// repo so renaming the folder later changes nothing.78pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {79	name, _ := repo_name_with_head(store, mut backend)!80	return name81}8283// repo_name_with_head is repo_name for a caller that needs the remote head as84// well: resolving the name has to read it, so `offer` gets it here instead of85// asking the remote for it a second time.86fn repo_name_with_head(store &storage.Store, mut backend remote.Backend) !(string, remote.Object) {87	if remembered := store.state(repo_state_key) {88		return follow_rename(store, mut backend, remembered)!89	}90	name := os.base(store.root).to_lower()91	// Before the clash check below: a remote this koh cannot read is a "update92	// koh" answer, not a "rename the folder" one.93	check_format(mut backend, name)!94	existing := backend.get(head_key(name))!95	if existing.found {96		theirs := existing.body.bytestr().trim_space()97		if history.by_id(store, theirs) == none {98			return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')99		}100	}101	store.set_state(repo_state_key, name)!102	return name, existing103}104105// follow_rename follows the marker Kepr leaves when it renames a repo, `.kepr/renamed/<old>`106// holding the new name (§30, 2026-10-01), for as long as the remembered name has no `head`, and107// remembers where it led. A few hops cover a repo renamed more than once. The head it returns is108// the one for the name it returns, read again after a hop, so the caller needs no second read.109fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !(string, remote.Object) {110	mut name := remembered111	mut head := backend.get(head_key(name))!112	for _ in 0 .. 5 {113		if head.found {114			break115		}116		marker := backend.get('.kepr/renamed/${name}')!117		next := marker.body.bytestr().trim_space()118		if !marker.found || next == '' || next.contains('/') || next.contains('\\') || next in [119			'.',120			'..',121		] {122			break123		}124		name = next125		head = backend.get(head_key(name))!126	}127	if name != remembered {128		store.set_state(repo_state_key, name)!129	}130	return name, head131}132133// offer sends what the remote lacks and then swaps `head`. Nothing is ever134// queued: the next offer simply sends everything the remote does not have.135pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {136	name, remote_head := repo_name_with_head(store, mut backend)!137	local := history.head(store) or { return error(no_saves) }138	mut report := OfferReport{139		repo: name140		head: local.id141	}142	if check_format(mut backend, name)! == '' {143		// Offered before this key existed: record the layout now.144		put_format(mut backend, name)!145	}146	// One listing serves both the strip check and the upload. An event that147	// lands after it is caught by undo_late_strips below.148	event_keys := backend.list(events_prefix(name))!149	// Records offered by a machine that has not applied a strip would put the150	// stripped path back on the remote, where nothing would rewrite it again.151	if unapplied_strips(store, mut backend, event_keys)!.len > 0 {152		return error(strip_not_applied)153	}154	mut uploaded := Uploaded{}155	upload_line(store, mut backend, name, local.id, remote_head, event_keys, mut report,156		mut uploaded) or { return after_failed_upload(store, mut backend, name, uploaded, err) }157	// A strip sends its event before it lists the saves to rewrite, so one158	// missed here lists them after these records landed and rewrites them. One159	// seen here may have rewritten before they landed: take back what it reaches.160	// With nothing uploaded there is nothing to take back; a strip that landed161	// during a no-op offer is caught by the check above on the next one.162	if (uploaded.saves.len > 0 || uploaded.objects.len > 0)163		&& undo_late_strips(store, mut backend, name, uploaded)! {164		return error(strip_not_applied)165	}166	// A head already naming these saves needs no write: skipping the PUT saves167	// a request, and its tag stays as it was.168	if remote_head.body.bytestr().trim_space() != local.id169		&& !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {170		return error('remote has new saves — run koh steal')171	}172	store.set_state(remote_head_key, local.id)!173	return report174}175176// saves_after lists the local saves newer than `theirs`, oldest first. It fails177// when `theirs` is not on this line, which is the honest answer: we cannot178// offer on top of a save we do not have.179fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {180	mut newer := []history.Save{}181	mut cursor := ours182	for cursor != '' && cursor != theirs {183		save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }184		newer << save185		cursor = save.parent186	}187	if cursor != theirs {188		return error('${theirs} is not on this line')189	}190	newer.reverse_in_place()191	return newer192}193194const strip_not_applied = 'the remote has a strip this repo has not applied — run koh steal'195196// Uploaded is what one upload put on the remote, so a late strip can take it back.197struct Uploaded {198mut:199	saves   []string200	objects map[string]bool201	deleted int // damaged remote copies removed before their replacement202}203204fn (u Uploaded) done() []string {205	mut done := done_text('deleted', u.deleted, 'damaged remote object')206	if u.saves.len + u.objects.len > 0 {207		done << 'uploaded ${fmt.plural(u.objects.len, 'object')} and ${fmt.plural(u.saves.len, 'save record')}'208	}209	return done210}211212// upload_line sends every save after the remote head, then the events.213fn upload_line(store &storage.Store, mut backend remote.Backend, name string, local string, remote_head remote.Object, event_keys []string, mut report OfferReport, mut uploaded Uploaded) ! {214	if remote_head.found {215		theirs := remote_head.body.bytestr().trim_space()216		newer := saves_after(store, local, theirs) or {217			return error('remote has new saves — run koh steal')218		}219		for save in newer {220			upload_save(store, mut backend, name, save, mut report, mut uploaded)!221		}222	} else {223		oldest_first := history.line(store)!224		for index := oldest_first.len - 1; index >= 0; index-- {225			upload_save(store, mut backend, name, oldest_first[index], mut report, mut uploaded)!226		}227	}228	upload_events(store, mut backend, name, event_keys, mut report)!229}230231// after_failed_upload still applies a strip that landed before the failure232// to what the upload had put.233fn after_failed_upload(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, failure IError) IError {234	undo_late_strips(store, mut backend, repo, uploaded) or {235		return error('${failure.msg()}; removing what a strip on the remote covers also failed: ${err.msg()}')236	}237	return failure238}239240// unsettled_key keeps what an upload sent when settling a late strip failed,241// for Doctor to finish once a steal brings the strip here.242pub const unsettled_key = 'upload_unsettled'243244pub fn unsettled(store &storage.Store) ![]string {245	text := store.state(unsettled_key) or { return []string{} }246	return json2.decode[[]string](text) or {247		return error('the note of an unsettled upload is unreadable; it is kept for recovery')248	}249}250251fn undo_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {252	return settle_late_strips(store, mut backend, repo, uploaded) or {253		failure := err254		mut kept := unsettled(store) or { return error('${failure.msg()}; ${err.msg()}') }255		kept << uploaded.objects.keys().filter(it !in kept)256		store.set_state(unsettled_key, json2.encode(kept)) or {257			return error('${failure.msg()}; ${err.msg()}')258		}259		return failure260	}261}262263// settle_late_strips applies strips that reached the remote during an upload264// to what it put, and reports whether there were any. Records stay, less the265// stripped paths, as another offer or head may name them. Notes go first and266// objects last, so a stop part way leaves a note and no record without its object.267fn settle_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {268	event_keys := backend.list(events_prefix(repo))!269	strips := unapplied_strips(store, mut backend, event_keys)!270	if strips.len == 0 {271		return false272	}273	for strip in strips {274		queue_strip(store, strip.path, [strip.save_id], uploaded.objects.keys())!275	}276	for id in uploaded.saves {277		strip_record(mut backend, save_key(repo, id), id, strips)!278	}279	drop_stripped_objects(store, mut backend, repo, uploaded, strips)!280	return true281}282283// strip_record rewrites one remote record without what `strips` cover. A284// record that moved meanwhile is read again, since the other writer may have285// kept a path these strips name.286fn strip_record(mut backend remote.Backend, key string, id string, strips []events.Event) ! {287	for _ in 0 .. 5 {288		object := backend.get(key)!289		if !object.found {290			return291		}292		record := decode_save(object.body)!293		kept := record.files.filter(fn [strips, id] (file FileRecord) bool {294			return !strips.any(reaches(it, id) && covers(it.path, file.path))295		})296		if kept.len == record.files.len297			|| backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), object.tag)! {298			return299		}300	}301	return error('the remote copy of save ${id} kept changing while a stripped path was removed; run koh doctor again')302}303304// Partway is a failure after some work had already landed. `done` says what,305// so Doctor can report both.306pub struct Partway {307	Error308pub:309	done   string310	reason string311}312313pub fn (e Partway) msg() string {314	return e.reason315}316317// done_text is what a step finished before it failed, if anything.318pub fn done_text(verb string, done int, noun string) []string {319	return if done == 0 { []string{} } else { ['${verb} ${fmt.plural(done, noun)}'] }320}321322// partway adds what was `done` before `failure` to it, including what a323// failing step of its own had done.324pub fn partway(done []string, failure IError) IError {325	mut all := done.clone()326	if failure is Partway {327		all << failure.done328	}329	if all.len == 0 {330		return failure331	}332	return Partway{333		done:   all.join('; ')334		reason: failure.msg()335	}336}337338// drop_stripped_objects deletes what an upload put that a strip reaches in a339// save here, unless a remote record lists it under a path no strip covers:340// another machine may hold the same bytes there.341fn drop_stripped_objects(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {342	mut reached := map[string]bool{}343	// A local save that still names it under another path may have no other copy.344	mut kept := map[string]bool{}345	for save in history.all_saves(store)! {346		for file in history.files_of(store, save.id)!.filter(it.hash in uploaded.objects) {347			if strips.any(reaches(it, save.id) && covers(it.path, file.path)) {348				reached[file.hash] = true349			} else {350				kept[file.hash] = true351			}352		}353	}354	if reached.len == 0 {355		return356	}357	for key in backend.list('${repo}/saves')! {358		object := backend.get(key)!359		if object.found {360			record := decode_save(object.body)!361			for file in record.files {362				if !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {363					reached.delete(file.hash)364				}365			}366		}367	}368	for hash, _ in reached {369		if hash !in kept {370			backend.delete(object_key(repo, hash))!371		}372	}373}374375// upload_save puts a save's new objects, then its record, so a record on the remote always finds its376// objects there. Both are put_if_absent, so a retry after a partial offer is safe; `uploaded` keeps377// what this call created, which is all undo_late_strips may delete.378fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport, mut uploaded Uploaded) ! {379	files := history.files_of(store, save.id)!380	// Saves go up oldest first and head moves only once all of them landed, so381	// the parent and its objects are on the remote already: only content new382	// in this save travels, not a round trip per file in the repo.383	mut sent := map[string]bool{}384	if save.parent != '' {385		for file in history.files_of(store, save.parent)! {386			sent[file.hash] = true387		}388	}389	for file in files {390		if file.hash in sent {391			continue392		}393		sent[file.hash] = true394		if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {395			report.objects++396			uploaded.objects[file.hash] = true397		}398	}399	record := save_record(store, save)!400	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {401		report.saves++402		uploaded.saves << save.id403	}404}405406// upload_events sends every event the remote does not have. Events are tiny, so407// a listing costs less than tracking which ones were sent; `already` is the408// listing the caller already had.409fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, already []string, mut report OfferReport) ! {410	mut already_sent := map[string]bool{}411	for key in already {412		already_sent[os.base(key)] = true413	}414	for event in events.all(store)! {415		if event.id in already_sent {416			continue417		}418		if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {419			report.events++420		}421	}422}423424// fetched holds everything a steal read from the remote, before any of it is425// written locally. Network work happens first; the database gets one426// transaction, so a failure leaves nothing half-applied.427pub struct Fetched {428pub mut:429	repo_objects map[string][]u8430	saves        []SaveRecord // oldest first431	events_out   []events.Event432	head         string433	base         string // the newest save both sides already shared, '' when none434	unsafe_paths []string435}436437// fetch_back_to_known walks from the remote head along parents until it meets a save on this line438// (`base`), reading only the objects this repo lacks. Nothing is written here: write_fetched lands it.439// A save held locally but off the line, from an earlier steal, is taken from the local copy.440pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {441	check_format(mut backend, repo)!442	remote_head := backend.get(head_key(repo))!443	if !remote_head.found {444		return error('the remote has no "${repo}" yet — run koh offer here first')445	}446	mut fetched := Fetched{447		head: remote_head.body.bytestr().trim_space()448	}449	if !valid_save_id(fetched.head) {450		return error('the remote head has invalid save ID ${fetched.head}')451	}452	mut on_line := map[string]bool{}453	for save in history.line(store)! {454		on_line[save.id] = true455	}456	// Strips come first: an object only a stripped path named may be gone.457	fetched.events_out = fetch_events(store, mut backend, repo)!458	strips := known_strips(store, fetched)!459	mut cursor := fetched.head460	mut seen := map[string]bool{}461	for cursor != '' && cursor !in on_line {462		if cursor in seen {463			return error('the remote history has a parent cycle at ${cursor}')464		}465		seen[cursor] = true466		mut record := if saved := history.by_id(store, cursor) {467			save_record(store, saved)!468		} else {469			record_object := backend.get(save_key(repo, cursor))!470			if !record_object.found {471				return error('the remote is missing save ${cursor} — run koh offer there')472			}473			decoded := decode_save(record_object.body)!474			validate_save(decoded, cursor)!475			decoded476		}477		fetched.unsafe_paths << drop_unsafe_paths(mut record)478		validate_hashes(record.id, record.files)!479		for file in record.files {480			if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects481				&& !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {482				blob := backend.get(object_key(repo, file.hash))!483				if !blob.found {484					return error('the remote is missing object ${file.hash} that save ${record.id} needs')485				}486				fetched.repo_objects[file.hash] = blob.body487			}488		}489		fetched.saves << record490		cursor = record.parent491	}492	fetched.saves.reverse_in_place()493	fetched.base = cursor494	return fetched495}496497fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {498	have := events.all(store)!499	mut known := map[string]bool{}500	for event in have {501		known[event.id] = true502	}503	mut incoming := []events.Event{}504	for key in backend.list(events_prefix(repo))! {505		id := os.base(key)506		if !valid_event_id(id) {507			return error('the remote has invalid event ID ${id}')508		}509		if id in known {510			continue511		}512		body := backend.get(event_key(repo, id))!513		if !body.found {514			continue515		}516		event := decode_event(body.body)!517		if event.id != id {518			return error('remote event record ID ${event.id} disagrees with key ${id}')519		}520		if !ignored_strip(event) {521			incoming << event522		}523	}524	return incoming525}526527// write_fetched lands a fetch in one transaction: objects first (verified),528// then the events, then the saves they belong to. A strip bans its path from529// all of history, so it reaches every save, here or arriving, whenever made.530pub fn write_fetched(store &storage.Store, fetched Fetched) ! {531	for hash, blob in fetched.repo_objects {532		store.put_object_blob(hash, blob)!533	}534	mut freed := []string{}535	for event in fetched.events_out {536		if !events.receive(store, event)! {537			continue538		}539		if events.valid_strip(event) {540			freed << stripped_hashes(store, event.path, event.save_id)!541			remove_path(store, event.path, event.save_id)!542		}543	}544	strips := known_strips(store, fetched)!545	for record in fetched.saves {546		for file in record.files {547			if file.hash in fetched.repo_objects548				&& strips.any(reaches(it, record.id) && covers(it.path, file.path)) {549				freed << file.hash550			}551		}552		import_arriving(store, record, strips)!553	}554	store.drop_unused(freed)!555}556557// write_fetched_records makes network work durable without changing the line.558// Events wait for the combine transaction because a strip can rewrite history.559pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {560	for hash, blob in fetched.repo_objects {561		store.put_object_blob(hash, blob)!562	}563	strips := known_strips(store, fetched)!564	for record in fetched.saves {565		import_arriving(store, record, strips)!566	}567}568569// known_strips is every valid strip held here and every one the fetch brings:570// an arriving save loses what any of them reaches, not only what arrived with it.571fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {572	mut strips := events.strip_events(store)!573	strips << fetched.events_out574	return strips.filter(events.valid_strip(it))575}576577// import_arriving lands one save from the remote, unless it is already here, less every path a578// strip that `reaches` it removed.579fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {580	if history.by_id(store, record.id) != none {581		return582	}583	validate_save(record, record.id)!584	safe := record.files.filter(snapshot.legal_path(it.path))585	validate_hashes(record.id, safe)!586	files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {587		return snapshot.legal_path(file.path)588			&& !strips.any(reaches(it, record.id) && covers(it.path, file.path))589	})590	history.import_save(store, to_save(record), files)!591}592593// reaches reports whether a strip event applies to a save: its one save, or594// every save there is, whenever it was made.595fn reaches(strip events.Event, save_id string) bool {596	return strip.save_id == '' || strip.save_id == save_id597}