sync.v

8.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//! pushes local saves the remote lacks; `steal` pulls 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 sync1213import 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'2223pub const no_saves = 'this repo has no saves yet — nothing to offer'2425pub struct OfferReport {26pub mut:27	repo    string28	saves   int29	objects int30	events  int31	head    string32}3334// remember_repo binds a repo to its name on the remote. A clone does it at35// once: its folder may be renamed before it ever offers.36pub fn remember_repo(store &storage.Store, name string) ! {37	store.set_state(repo_state_key, name)!38}3940// repo_name is the folder's name at first offer, remembered in the repo so41// renaming the folder later changes nothing.42pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {43	if remembered := store.state(repo_state_key) {44		return remembered45	}46	name := os.base(store.root)47	existing := backend.get(head_key(name))!48	if existing.found {49		theirs := existing.body.bytestr().trim_space()50		if history.by_id(store, theirs) == none {51			return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')52		}53	}54	store.set_state(repo_state_key, name)!55	return name56}5758// offer sends what the remote lacks and then swaps `head`. Nothing is ever59// queued: the next offer simply sends everything the remote does not have.60pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {61	name := repo_name(store, mut backend)!62	local := history.head(store) or { return error(no_saves) }63	mut report := OfferReport{64		repo: name65		head: local.id66	}67	remote_head := backend.get(head_key(name))!68	// Records offered by a machine that has not applied a strip would put the69	// stripped path back on the remote, where nothing would rewrite it again.70	// ponytail: an offer racing a strip on another machine inside the same few71	// seconds can still slip through; closing that needs a remote lock.72	if unapplied_strip(store, mut backend, name)! {73		return error('the remote has a strip this repo has not applied — run koh steal')74	}75	if remote_head.found {76		theirs := remote_head.body.bytestr().trim_space()77		newer := saves_after(store, local.id, theirs) or {78			return error('remote has new saves — run koh steal')79		}80		for save in newer {81			upload_save(store, mut backend, name, save, mut report)!82		}83	} else {84		oldest_first := history.line(store)!85		for index := oldest_first.len - 1; index >= 0; index-- {86			upload_save(store, mut backend, name, oldest_first[index], mut report)!87		}88	}89	upload_events(store, mut backend, name, mut report)!90	if !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {91		return error('remote has new saves — run koh steal')92	}93	return report94}9596// saves_after lists the local saves newer than `theirs`, oldest first. It fails97// when `theirs` is not on this line, which is the honest answer: we cannot98// offer on top of a save we do not have.99fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {100	mut newer := []history.Save{}101	mut cursor := ours102	for cursor != '' && cursor != theirs {103		save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }104		newer << save105		cursor = save.parent106	}107	if cursor != theirs {108		return error('${theirs} is not on this line')109	}110	newer.reverse_in_place()111	return newer112}113114fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport) ! {115	files := history.files_of(store, save.id)!116	for file in files {117		if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {118			report.objects++119		}120	}121	record := save_record(store, save)!122	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {123		report.saves++124	}125}126127// upload_events sends every event the remote does not have. Events are tiny, so128// listing them costs less than tracking which ones were sent.129fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, mut report OfferReport) ! {130	already := backend.list(events_prefix(repo))!131	mut already_sent := map[string]bool{}132	for key in already {133		already_sent[os.base(key)] = true134	}135	for event in events.all(store)! {136		if event.id in already_sent {137			continue138		}139		if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {140			report.events++141		}142	}143}144145// fetched holds everything a steal read from the remote, before any of it is146// written locally. Network work happens first; the database gets one147// transaction, so a failure leaves nothing half-applied.148pub struct Fetched {149pub mut:150	repo_objects map[string][]u8151	saves        []SaveRecord // oldest first152	events_out   []events.Event153	head         string154	base         string // the newest save both sides already shared, '' when none155}156157pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {158	remote_head := backend.get(head_key(repo))!159	if !remote_head.found {160		return error('the remote has no "${repo}" yet — run koh offer here first')161	}162	mut fetched := Fetched{163		head: remote_head.body.bytestr().trim_space()164	}165	mut cursor := fetched.head166	for cursor != '' && history.by_id(store, cursor) == none {167		record_object := backend.get(save_key(repo, cursor))!168		if !record_object.found {169			return error('the remote is missing save ${cursor} — run koh offer there')170		}171		record := decode_save(record_object.body)!172		for file in record.files {173			if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects {174				blob := backend.get(object_key(repo, file.hash))!175				if !blob.found {176					return error('the remote is missing object ${file.hash} that save ${record.id} needs')177				}178				fetched.repo_objects[file.hash] = blob.body179			}180		}181		fetched.saves << record182		cursor = record.parent183	}184	fetched.saves.reverse_in_place()185	fetched.base = cursor186	fetched.events_out = fetch_events(store, mut backend, repo)!187	return fetched188}189190fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {191	have := events.all(store)!192	mut known := map[string]bool{}193	for event in have {194		known[event.id] = true195	}196	mut incoming := []events.Event{}197	for key in backend.list(events_prefix(repo))! {198		id := os.base(key)199		if id in known {200			continue201		}202		body := backend.get(event_key(repo, id))!203		if !body.found {204			continue205		}206		incoming << decode_event(body.body)!207	}208	return incoming209}210211// write_fetched lands a fetch in one transaction: objects first (verified),212// then the events, then the saves they belong to. A new strip reaches every213// save already here, but an arriving save only when `reaches` says so: one214// made after the strip is new work, not what the strip removed.215pub fn write_fetched(store &storage.Store, fetched Fetched) ! {216	for hash, blob in fetched.repo_objects {217		store.put_object_blob(hash, blob)!218	}219	mut strips := []events.Event{}220	for event in fetched.events_out {221		if !events.receive(store, event)! {222			continue223		}224		if event.kind == events.kind_strip {225			// Somebody stripped a path: remove it here too, so the two226			// histories agree from now on. Objects go once the saves are in.227			remove_path(store, event.path, event.save_id)!228			strips << event229		}230	}231	for record in fetched.saves {232		files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {233			return !strips.any(reaches(it, record.id, record.created_at)234				&& covers(it.path, file.path))235		})236		history.import_save(store, to_save(record), files)!237	}238	if strips.len > 0 {239		store.drop_unreferenced_objects()!240	}241}242243// reaches reports whether a strip event applies to a save arriving from the244// remote. A strip of every save covers the saves made up to its own time.245fn reaches(strip events.Event, save_id string, created_at i64) bool {246	if strip.save_id != '' {247		return strip.save_id == save_id248	}249	return created_at <= strip.created_at250}