exchange.v

12.7 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, as the document24// asks; nothing reads it back yet.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, remembered in the repo so74// renaming the folder later changes nothing.75pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {76	if remembered := store.state(repo_state_key) {77		return remembered78	}79	name := os.base(store.root)80	// Before the clash check below: a remote this koh cannot read is a "update81	// koh" answer, not a "rename the folder" one.82	check_format(mut backend, name)!83	existing := backend.get(head_key(name))!84	if existing.found {85		theirs := existing.body.bytestr().trim_space()86		if history.by_id(store, theirs) == none {87			return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')88		}89	}90	store.set_state(repo_state_key, name)!91	return name92}9394// offer sends what the remote lacks and then swaps `head`. Nothing is ever95// queued: the next offer simply sends everything the remote does not have.96pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {97	name := repo_name(store, mut backend)!98	local := history.head(store) or { return error(no_saves) }99	mut report := OfferReport{100		repo: name101		head: local.id102	}103	if check_format(mut backend, name)! == '' {104		// Offered before this key existed: record the layout now.105		put_format(mut backend, name)!106	}107	remote_head := backend.get(head_key(name))!108	// Records offered by a machine that has not applied a strip would put the109	// stripped path back on the remote, where nothing would rewrite it again.110	if unapplied_strips(store, mut backend, name)!.len > 0 {111		return error(strip_not_applied)112	}113	mut uploaded := Uploaded{}114	if remote_head.found {115		theirs := remote_head.body.bytestr().trim_space()116		newer := saves_after(store, local.id, theirs) or {117			return error('remote has new saves — run koh steal')118		}119		for save in newer {120			upload_save(store, mut backend, name, save, mut report, mut uploaded)!121		}122	} else {123		oldest_first := history.line(store)!124		for index := oldest_first.len - 1; index >= 0; index-- {125			upload_save(store, mut backend, name, oldest_first[index], mut report, mut uploaded)!126		}127	}128	upload_events(store, mut backend, name, mut report)!129	// A strip sends its event before it lists the saves to rewrite, so one130	// missed here lists them after these records landed and rewrites them. One131	// seen here may have rewritten before they landed: take back what it reaches.132	late := unapplied_strips(store, mut backend, name)!133	if late.len > 0 {134		take_back(store, mut backend, name, uploaded, late)!135		return error(strip_not_applied)136	}137	if !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {138		return error('remote has new saves — run koh steal')139	}140	store.set_state(remote_head_key, local.id)!141	return report142}143144// saves_after lists the local saves newer than `theirs`, oldest first. It fails145// when `theirs` is not on this line, which is the honest answer: we cannot146// offer on top of a save we do not have.147fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {148	mut newer := []history.Save{}149	mut cursor := ours150	for cursor != '' && cursor != theirs {151		save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }152		newer << save153		cursor = save.parent154	}155	if cursor != theirs {156		return error('${theirs} is not on this line')157	}158	newer.reverse_in_place()159	return newer160}161162const strip_not_applied = 'the remote has a strip this repo has not applied — run koh steal'163164// Uploaded is what one offer put on the remote, so a late strip can take it back.165struct Uploaded {166mut:167	saves   []string168	objects map[string]bool169}170171// take_back deletes the records an offer put, which head never reached, and172// every object it put that a strip reaches in one of them.173fn take_back(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {174	for id in uploaded.saves {175		for file in history.files_of(store, id)! {176			if file.hash in uploaded.objects && strips.any(reaches(it, id) && covers(it.path, file.path)) {177				backend.delete(object_key(repo, file.hash))!178			}179		}180		backend.delete(save_key(repo, id))!181	}182}183184fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport, mut uploaded Uploaded) ! {185	files := history.files_of(store, save.id)!186	// Saves go up oldest first and head moves only once all of them landed, so187	// the parent and its objects are on the remote already: only content new188	// in this save travels, not a round trip per file in the repo.189	mut sent := map[string]bool{}190	if save.parent != '' {191		for file in history.files_of(store, save.parent)! {192			sent[file.hash] = true193		}194	}195	for file in files {196		if file.hash in sent {197			continue198		}199		sent[file.hash] = true200		if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {201			report.objects++202			uploaded.objects[file.hash] = true203		}204	}205	record := save_record(store, save)!206	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {207		report.saves++208		uploaded.saves << save.id209	}210}211212// upload_events sends every event the remote does not have. Events are tiny, so213// listing them costs less than tracking which ones were sent.214fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, mut report OfferReport) ! {215	already := backend.list(events_prefix(repo))!216	mut already_sent := map[string]bool{}217	for key in already {218		already_sent[os.base(key)] = true219	}220	for event in events.all(store)! {221		if event.id in already_sent {222			continue223		}224		if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {225			report.events++226		}227	}228}229230// fetched holds everything a steal read from the remote, before any of it is231// written locally. Network work happens first; the database gets one232// transaction, so a failure leaves nothing half-applied.233pub struct Fetched {234pub mut:235	repo_objects map[string][]u8236	saves        []SaveRecord // oldest first237	events_out   []events.Event238	head         string239	base         string // the newest save both sides already shared, '' when none240	unsafe_paths []string241}242243pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {244	check_format(mut backend, repo)!245	remote_head := backend.get(head_key(repo))!246	if !remote_head.found {247		return error('the remote has no "${repo}" yet — run koh offer here first')248	}249	mut fetched := Fetched{250		head: remote_head.body.bytestr().trim_space()251	}252	mut on_line := map[string]bool{}253	for save in history.line(store)! {254		on_line[save.id] = true255	}256	mut cursor := fetched.head257	for cursor != '' && cursor !in on_line {258		mut record := if saved := history.by_id(store, cursor) {259			save_record(store, saved)!260		} else {261			record_object := backend.get(save_key(repo, cursor))!262			if !record_object.found {263				return error('the remote is missing save ${cursor} — run koh offer there')264			}265			decode_save(record_object.body)!266		}267		fetched.unsafe_paths << drop_unsafe_paths(mut record)268		for file in record.files {269			if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects {270				blob := backend.get(object_key(repo, file.hash))!271				if !blob.found {272					return error('the remote is missing object ${file.hash} that save ${record.id} needs')273				}274				fetched.repo_objects[file.hash] = blob.body275			}276		}277		fetched.saves << record278		cursor = record.parent279	}280	fetched.saves.reverse_in_place()281	fetched.base = cursor282	fetched.events_out = fetch_events(store, mut backend, repo)!283	return fetched284}285286fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {287	have := events.all(store)!288	mut known := map[string]bool{}289	for event in have {290		known[event.id] = true291	}292	mut incoming := []events.Event{}293	for key in backend.list(events_prefix(repo))! {294		id := os.base(key)295		if id in known {296			continue297		}298		body := backend.get(event_key(repo, id))!299		if !body.found {300			continue301		}302		event := decode_event(body.body)!303		if !ignored_strip(event) {304			incoming << event305		}306	}307	return incoming308}309310// write_fetched lands a fetch in one transaction: objects first (verified),311// then the events, then the saves they belong to. A strip bans its path from312// all of history, so it reaches every save, here or arriving, whenever made.313pub fn write_fetched(store &storage.Store, fetched Fetched) ! {314	for hash, blob in fetched.repo_objects {315		store.put_object_blob(hash, blob)!316	}317	mut stripped := false318	for event in fetched.events_out {319		if !events.receive(store, event)! {320			continue321		}322		if event.kind == events.kind_strip {323			remove_path(store, event.path, event.save_id)!324			stripped = true325		}326	}327	strips := known_strips(store, fetched)!328	for record in fetched.saves {329		import_arriving(store, record, strips)!330	}331	if stripped {332		store.drop_unreferenced_objects()!333	}334}335336// write_fetched_records makes network work durable without changing the line.337// Events wait for the combine transaction because a strip can rewrite history.338pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {339	for hash, blob in fetched.repo_objects {340		store.put_object_blob(hash, blob)!341	}342	strips := known_strips(store, fetched)!343	for record in fetched.saves {344		import_arriving(store, record, strips)!345	}346}347348// known_strips is every strip held here and every one the fetch brings: an349// arriving save loses what any of them reaches, not only what arrived with it.350fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {351	mut strips := events.strip_events(store)!352	strips << fetched.events_out.filter(it.kind == events.kind_strip)353	return strips354}355356// import_arriving lands one save from the remote, unless it is already here, less every path a357// strip that `reaches` it removed.358fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {359	if history.by_id(store, record.id) != none {360		return361	}362	files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {363		return snapshot.legal_path(file.path)364			&& !strips.any(reaches(it, record.id) && covers(it.path, file.path))365	})366	history.import_save(store, to_save(record), files)!367}368369// reaches reports whether a strip event applies to a save: its one save, or370// every save there is, whenever it was made.371fn reaches(strip events.Event, save_id string) bool {372	return strip.save_id == '' || strip.save_id == save_id373}