exchange.v

22.0 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// valid_repo_name is the one name rule: what Kepr serves, what `host/repo` carries and76// what a key on the remote may be built from. A name with a space, a slash or a colon77// would make a key nothing else can address, so every way in checks it first.78pub fn valid_repo_name(name string) bool {79	if name == '' || name == '.' || name == '..' {80		return false81	}82	return name.bytes().all(it.is_alnum() || it in [`-`, `.`, `_`])83}8485// repo_name is the folder's name at first offer, lowercased so it makes the same86// Kepr URL whatever the folder's case (June, 2026-10-01), and remembered in the87// repo so renaming the folder later changes nothing.88pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {89	name, _ := repo_name_with_head(store, mut backend)!90	return name91}9293// repo_name_with_head is repo_name for a caller that needs the remote head as94// well: resolving the name has to read it, so `offer` gets it here instead of95// asking the remote for it a second time.96fn repo_name_with_head(store &storage.Store, mut backend remote.Backend) !(string, remote.Object) {97	if remembered := store.state(repo_state_key) {98		return follow_rename(store, mut backend, remembered)!99	}100	name := os.base(store.root).to_lower()101	// Before any read: a name Kepr cannot serve would only be refused later, with a102	// key already built from it.103	if !valid_repo_name(name) {104		return error('"${name}" is not a repo name — a repo name is letters, digits, ., _ and -; rename the folder')105	}106	// Before the clash check below: a remote this koh cannot read is a "update107	// koh" answer, not a "rename the folder" one.108	check_format(mut backend, name)!109	existing := backend.get(head_key(name))!110	if existing.found {111		theirs := existing.body.bytestr().trim_space()112		if history.by_id(store, theirs) == none {113			return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')114		}115	}116	store.set_state(repo_state_key, name)!117	return name, existing118}119120// follow_rename follows the marker Kepr leaves when it renames a repo, `.kepr/renamed/<old>`121// holding the new name (§30, 2026-10-01), for as long as the remembered name has no `head`, and122// remembers where it led. A few hops cover a repo renamed more than once. The head it returns is123// the one for the name it returns, read again after a hop, so the caller needs no second read.124fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !(string, remote.Object) {125	mut name := remembered126	mut head := backend.get(head_key(name))!127	for _ in 0 .. 5 {128		if head.found {129			break130		}131		marker := backend.get('.kepr/renamed/${name}')!132		next := marker.body.bytestr().trim_space()133		if !marker.found || !valid_repo_name(next) {134			break135		}136		name = next137		head = backend.get(head_key(name))!138	}139	if name != remembered {140		store.set_state(repo_state_key, name)!141	}142	return name, head143}144145// offer sends what the remote lacks and then swaps `head`. Nothing is ever146// queued: the next offer simply sends everything the remote does not have.147pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {148	name, remote_head := repo_name_with_head(store, mut backend)!149	local := history.head(store) or { return error(no_saves) }150	mut report := OfferReport{151		repo: name152		head: local.id153	}154	if check_format(mut backend, name)! == '' {155		// Offered before this key existed: record the layout now.156		put_format(mut backend, name)!157	}158	// One listing serves both the strip check and the upload. An event that159	// lands after it is caught by undo_late_strips below.160	event_keys := backend.list(events_prefix(name))!161	// Records offered by a machine that has not applied a strip would put the162	// stripped path back on the remote, where nothing would rewrite it again.163	if unapplied_strips(store, mut backend, event_keys)!.len > 0 {164		return error(strip_not_applied)165	}166	mut uploaded := Uploaded{}167	upload_line(store, mut backend, name, local.id, remote_head, event_keys, mut report,168		mut uploaded) or { return after_failed_upload(store, mut backend, name, uploaded, err) }169	// A strip sends its event before it lists the saves to rewrite, so one170	// missed here lists them after these records landed and rewrites them. One171	// seen here may have rewritten before they landed: take back what it reaches.172	// With nothing uploaded there is nothing to take back; a strip that landed173	// during a no-op offer is caught by the check above on the next one.174	if (uploaded.saves.len > 0 || uploaded.objects.len > 0)175		&& undo_late_strips(store, mut backend, name, uploaded)! {176		return error(strip_not_applied)177	}178	// A head already naming these saves needs no write: skipping the PUT saves179	// a request, and its tag stays as it was.180	if remote_head.body.bytestr().trim_space() != local.id181		&& !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {182		return error('remote has new saves — run koh steal')183	}184	store.set_state(remote_head_key, local.id)!185	return report186}187188// saves_after lists the local saves newer than `theirs`, oldest first. It fails189// when `theirs` is not on this line, which is the honest answer: we cannot190// offer on top of a save we do not have.191fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {192	mut newer := []history.Save{}193	mut cursor := ours194	for cursor != '' && cursor != theirs {195		save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }196		newer << save197		cursor = save.parent198	}199	if cursor != theirs {200		return error('${theirs} is not on this line')201	}202	newer.reverse_in_place()203	return newer204}205206const strip_not_applied = 'the remote has a strip this repo has not applied — run koh steal'207208// Uploaded is what one upload put on the remote, so a late strip can take it back.209struct Uploaded {210mut:211	saves   []string212	objects map[string]bool213	deleted int // damaged remote copies removed before their replacement214}215216fn (u Uploaded) done() []string {217	mut done := done_text('deleted', u.deleted, 'damaged remote object')218	if u.saves.len + u.objects.len > 0 {219		done << 'uploaded ${fmt.plural(u.objects.len, 'object')} and ${fmt.plural(u.saves.len, 'save record')}'220	}221	return done222}223224// upload_line sends every save after the remote head, then the events.225fn 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) ! {226	if remote_head.found {227		theirs := remote_head.body.bytestr().trim_space()228		newer := saves_after(store, local, theirs) or {229			return error('remote has new saves — run koh steal')230		}231		for save in newer {232			upload_save(store, mut backend, name, save, mut report, mut uploaded)!233		}234	} else {235		oldest_first := history.line(store)!236		for index := oldest_first.len - 1; index >= 0; index-- {237			upload_save(store, mut backend, name, oldest_first[index], mut report, mut uploaded)!238		}239	}240	upload_events(store, mut backend, name, event_keys, mut report)!241}242243// after_failed_upload still applies a strip that landed before the failure244// to what the upload had put.245fn after_failed_upload(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, failure IError) IError {246	undo_late_strips(store, mut backend, repo, uploaded) or {247		return error('${failure.msg()}; removing what a strip on the remote covers also failed: ${err.msg()}')248	}249	return failure250}251252// unsettled_key keeps what an upload sent when settling a late strip failed,253// for Doctor to finish once a steal brings the strip here.254pub const unsettled_key = 'upload_unsettled'255256pub fn unsettled(store &storage.Store) ![]string {257	text := store.state(unsettled_key) or { return []string{} }258	return json2.decode[[]string](text) or {259		return error('the note of an unsettled upload is unreadable; it is kept for recovery')260	}261}262263fn undo_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {264	return settle_late_strips(store, mut backend, repo, uploaded) or {265		failure := err266		mut kept := unsettled(store) or { return error('${failure.msg()}; ${err.msg()}') }267		kept << uploaded.objects.keys().filter(it !in kept)268		store.set_state(unsettled_key, json2.encode(kept)) or {269			return error('${failure.msg()}; ${err.msg()}')270		}271		return failure272	}273}274275// settle_late_strips applies strips that reached the remote during an upload276// to what it put, and reports whether there were any. Records stay, less the277// stripped paths, as another offer or head may name them. Notes go first and278// objects last, so a stop part way leaves a note and no record without its object.279fn settle_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {280	event_keys := backend.list(events_prefix(repo))!281	strips := unapplied_strips(store, mut backend, event_keys)!282	if strips.len == 0 {283		return false284	}285	for strip in strips {286		queue_strip(store, strip.path, [strip.save_id], uploaded.objects.keys())!287	}288	for id in uploaded.saves {289		strip_record(mut backend, save_key(repo, id), id, strips)!290	}291	drop_stripped_objects(store, mut backend, repo, uploaded, strips)!292	return true293}294295// strip_record rewrites one remote record without what `strips` cover. A296// record that moved meanwhile is read again, since the other writer may have297// kept a path these strips name.298fn strip_record(mut backend remote.Backend, key string, id string, strips []events.Event) ! {299	for _ in 0 .. 5 {300		object := backend.get(key)!301		if !object.found {302			return303		}304		record := decode_save(object.body)!305		kept := record.files.filter(fn [strips, id] (file FileRecord) bool {306			return !strips.any(reaches(it, id) && covers(it.path, file.path))307		})308		if kept.len == record.files.len309			|| backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), object.tag)! {310			return311		}312	}313	return error('the remote copy of save ${id} kept changing while a stripped path was removed; run koh doctor again')314}315316// Partway is a failure after some work had already landed. `done` says what,317// so Doctor can report both.318pub struct Partway {319	Error320pub:321	done   string322	reason string323}324325pub fn (e Partway) msg() string {326	return e.reason327}328329// done_text is what a step finished before it failed, if anything.330pub fn done_text(verb string, done int, noun string) []string {331	return if done == 0 { []string{} } else { ['${verb} ${fmt.plural(done, noun)}'] }332}333334// partway adds what was `done` before `failure` to it, including what a335// failing step of its own had done.336pub fn partway(done []string, failure IError) IError {337	mut all := done.clone()338	if failure is Partway {339		all << failure.done340	}341	if all.len == 0 {342		return failure343	}344	return Partway{345		done:   all.join('; ')346		reason: failure.msg()347	}348}349350// drop_stripped_objects deletes what an upload put that a strip reaches in a351// save here, unless a remote record lists it under a path no strip covers:352// another machine may hold the same bytes there.353fn drop_stripped_objects(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {354	mut reached := map[string]bool{}355	// A local save that still names it under another path may have no other copy.356	mut kept := map[string]bool{}357	for save in history.all_saves(store)! {358		for file in history.files_of(store, save.id)!.filter(it.hash in uploaded.objects) {359			if strips.any(reaches(it, save.id) && covers(it.path, file.path)) {360				reached[file.hash] = true361			} else {362				kept[file.hash] = true363			}364		}365	}366	if reached.len == 0 {367		return368	}369	for key in backend.list('${repo}/saves')! {370		object := backend.get(key)!371		if object.found {372			record := decode_save(object.body)!373			for file in record.files {374				if !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {375					reached.delete(file.hash)376				}377			}378		}379	}380	for hash, _ in reached {381		if hash !in kept {382			backend.delete(object_key(repo, hash))!383		}384	}385}386387// upload_save puts a save's new objects, then its record, so a record on the remote always finds its388// objects there. Both are put_if_absent, so a retry after a partial offer is safe; `uploaded` keeps389// what this call created, which is all undo_late_strips may delete.390fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport, mut uploaded Uploaded) ! {391	files := history.files_of(store, save.id)!392	// Saves go up oldest first and head moves only once all of them landed, so393	// the parent and its objects are on the remote already: only content new394	// in this save travels, not a round trip per file in the repo.395	mut sent := map[string]bool{}396	if save.parent != '' {397		for file in history.files_of(store, save.parent)! {398			sent[file.hash] = true399		}400	}401	for file in files {402		if file.hash in sent {403			continue404		}405		sent[file.hash] = true406		if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {407			report.objects++408			uploaded.objects[file.hash] = true409		}410	}411	record := save_record(store, save)!412	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {413		report.saves++414		uploaded.saves << save.id415	}416}417418// upload_events sends every event the remote does not have. Events are tiny, so419// a listing costs less than tracking which ones were sent; `already` is the420// listing the caller already had.421fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, already []string, mut report OfferReport) ! {422	mut already_sent := map[string]bool{}423	for key in already {424		already_sent[os.base(key)] = true425	}426	for event in events.all(store)! {427		if event.id in already_sent {428			continue429		}430		if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {431			report.events++432		}433	}434}435436// fetched holds everything a steal read from the remote, before any of it is437// written locally. Network work happens first; the database gets one438// transaction, so a failure leaves nothing half-applied.439pub struct Fetched {440pub mut:441	repo_objects map[string][]u8442	saves        []SaveRecord // oldest first443	events_out   []events.Event444	head         string445	base         string // the newest save both sides already shared, '' when none446	unsafe_paths []string447}448449// fetch_back_to_known walks from the remote head along parents until it meets a save on this line450// (`base`), reading only the objects this repo lacks. Nothing is written here: write_fetched lands it.451// A save held locally but off the line, from an earlier steal, is taken from the local copy.452pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {453	check_format(mut backend, repo)!454	remote_head := backend.get(head_key(repo))!455	if !remote_head.found {456		return error('the remote has no "${repo}" yet — run koh offer here first')457	}458	mut fetched := Fetched{459		head: remote_head.body.bytestr().trim_space()460	}461	if !valid_save_id(fetched.head) {462		return error('the remote head has invalid save ID ${fetched.head}')463	}464	mut on_line := map[string]bool{}465	for save in history.line(store)! {466		on_line[save.id] = true467	}468	// Strips come first: an object only a stripped path named may be gone.469	fetched.events_out = fetch_events(store, mut backend, repo)!470	strips := known_strips(store, fetched)!471	mut cursor := fetched.head472	mut seen := map[string]bool{}473	for cursor != '' && cursor !in on_line {474		if cursor in seen {475			return error('the remote history has a parent cycle at ${cursor}')476		}477		seen[cursor] = true478		mut record := if saved := history.by_id(store, cursor) {479			save_record(store, saved)!480		} else {481			record_object := backend.get(save_key(repo, cursor))!482			if !record_object.found {483				return error('the remote is missing save ${cursor} — run koh offer there')484			}485			decoded := decode_save(record_object.body)!486			validate_save(decoded, cursor)!487			decoded488		}489		fetched.unsafe_paths << drop_unsafe_paths(mut record)490		validate_hashes(record.id, record.files)!491		for file in record.files {492			if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects493				&& !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {494				blob := backend.get(object_key(repo, file.hash))!495				if !blob.found {496					return error('the remote is missing object ${file.hash} that save ${record.id} needs')497				}498				fetched.repo_objects[file.hash] = blob.body499			}500		}501		fetched.saves << record502		cursor = record.parent503	}504	fetched.saves.reverse_in_place()505	fetched.base = cursor506	return fetched507}508509fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {510	have := events.all(store)!511	mut known := map[string]bool{}512	for event in have {513		known[event.id] = true514	}515	mut incoming := []events.Event{}516	for key in backend.list(events_prefix(repo))! {517		id := os.base(key)518		if !valid_event_id(id) {519			return error('the remote has invalid event ID ${id}')520		}521		if id in known {522			continue523		}524		body := backend.get(event_key(repo, id))!525		if !body.found {526			continue527		}528		event := decode_event(body.body)!529		if event.id != id {530			return error('remote event record ID ${event.id} disagrees with key ${id}')531		}532		if !ignored_strip(event) {533			incoming << event534		}535	}536	return incoming537}538539// write_fetched lands a fetch in one transaction: objects first (verified),540// then the events, then the saves they belong to. A strip bans its path from541// all of history, so it reaches every save, here or arriving, whenever made.542pub fn write_fetched(store &storage.Store, fetched Fetched) ! {543	for hash, blob in fetched.repo_objects {544		store.put_object_blob(hash, blob)!545	}546	mut freed := []string{}547	for event in fetched.events_out {548		if !events.receive(store, event)! {549			continue550		}551		if events.valid_strip(event) {552			freed << stripped_hashes(store, event.path, event.save_id)!553			remove_path(store, event.path, event.save_id)!554		}555	}556	strips := known_strips(store, fetched)!557	for record in fetched.saves {558		for file in record.files {559			if file.hash in fetched.repo_objects560				&& strips.any(reaches(it, record.id) && covers(it.path, file.path)) {561				freed << file.hash562			}563		}564		import_arriving(store, record, strips)!565	}566	store.drop_unused(freed)!567}568569// write_fetched_records makes network work durable without changing the line.570// Events wait for the combine transaction because a strip can rewrite history.571pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {572	for hash, blob in fetched.repo_objects {573		store.put_object_blob(hash, blob)!574	}575	strips := known_strips(store, fetched)!576	for record in fetched.saves {577		import_arriving(store, record, strips)!578	}579}580581// known_strips is every valid strip held here and every one the fetch brings:582// an arriving save loses what any of them reaches, not only what arrived with it.583fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {584	mut strips := events.strip_events(store)!585	strips << fetched.events_out586	return strips.filter(events.valid_strip(it))587}588589// import_arriving lands one save from the remote, unless it is already here, less every path a590// strip that `reaches` it removed.591fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {592	if history.by_id(store, record.id) != none {593		return594	}595	validate_save(record, record.id)!596	safe := record.files.filter(snapshot.legal_path(it.path))597	validate_hashes(record.id, safe)!598	files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {599		return snapshot.legal_path(file.path)600			&& !strips.any(reaches(it, record.id) && covers(it.path, file.path))601	})602	history.import_save(store, to_save(record), files)!603}604605// reaches reports whether a strip event applies to a save: its one save, or606// every save there is, whenever it was made.607fn reaches(strip events.Event, save_id string) bool {608	return strip.save_id == '' || strip.save_id == save_id609}