exchange.v

28.1 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// put_format records the layout on a repo that has none and returns the value in32// force: a machine that wrote one first wins the race, and its value is used.33fn put_format(mut backend remote.Backend, repo string, value string) !string {34	if backend.put_if_absent(format_key(repo), value.bytes())! {35		return value36	}37	return check_format(mut backend, repo)!38}3940// check_format reads <repo>/format and refuses a remote written by a koh that41// speaks another layout, so two versions never half-understand one bucket. An42// empty answer means the key is missing: version 1, which `offer` records.43fn check_format(mut backend remote.Backend, repo string) !string {44	existing := backend.get(format_key(repo))!45	if !existing.found {46		return ''47	}48	value := existing.body.bytestr().trim_space()49	if value !in [format_v1, format_v2] {50		return error('the remote "${repo}" is "${value}" — this koh speaks "${format_v1}" and "${format_v2}"; update koh')51	}52	return value53}5455pub struct OfferReport {56pub mut:57	repo    string58	saves   int59	objects int60	events  int61	head    string62}6364// remember_repo binds a repo to its name on the remote. A steal into a new folder does it at65// once: its folder may be renamed before it ever offers.66pub fn remember_repo(store &storage.Store, name string) ! {67	store.set_state(repo_state_key, name)!68}6970// valid_repo_name is the one name rule: what Kepr serves, what `host/repo` carries and71// what a key on the remote may be built from. A name with a space, a slash or a colon72// would make a key nothing else can address, so every way in checks it first.73pub fn valid_repo_name(name string) bool {74	if name == '' || name == '.' || name == '..' {75		return false76	}77	return name.bytes().all(it.is_alnum() || it in [`-`, `.`, `_`])78}7980// repo_name is the folder's name at first offer, lowercased so it makes the same81// Kepr URL whatever the folder's case (June, 2026-10-01), and remembered in the82// repo so renaming the folder later changes nothing.83pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {84	name, _ := repo_name_with_head(store, mut backend)!85	return name86}8788// repo_name_with_head is repo_name for a caller that needs the remote head as89// well: resolving the name has to read it, so `offer` gets it here instead of90// asking the remote for it a second time.91fn repo_name_with_head(store &storage.Store, mut backend remote.Backend) !(string, remote.Object) {92	if remembered := store.state(repo_state_key) {93		return follow_rename(store, mut backend, remembered)!94	}95	name := os.base(store.root).to_lower()96	// Before any read: a name Kepr cannot serve would only be refused later, with a97	// key already built from it.98	if !valid_repo_name(name) {99		return error('"${name}" is not a repo name — a repo name is letters, digits, ., _ and -; rename the folder')100	}101	// Before the clash check below: a remote this koh cannot read is a "update102	// koh" answer, not a "rename the folder" one.103	check_format(mut backend, name)!104	existing := backend.get(head_key(name))!105	if existing.found {106		theirs := existing.body.bytestr().trim_space()107		if history.by_id(store, theirs) == none {108			return error('the remote already has "${name}" with a history this repo does not share — rename the folder, or use another remote')109		}110	}111	store.set_state(repo_state_key, name)!112	return name, existing113}114115// follow_rename follows the marker Kepr leaves when it renames a repo, `.kepr/renamed/<old>`116// holding the new name (§30, 2026-10-01), for as long as the remembered name has no `head`, and117// remembers where it led. A few hops cover a repo renamed more than once. The head it returns is118// the one for the name it returns, read again after a hop, so the caller needs no second read.119fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !(string, remote.Object) {120	mut name := remembered121	mut head := backend.get(head_key(name))!122	for _ in 0 .. 5 {123		if head.found {124			break125		}126		marker := backend.get('.kepr/renamed/${name}')!127		next := marker.body.bytestr().trim_space()128		if !marker.found || !valid_repo_name(next) {129			break130		}131		name = next132		head = backend.get(head_key(name))!133	}134	if name != remembered {135		store.set_state(repo_state_key, name)!136	}137	return name, head138}139140// offer sends what the remote lacks and then swaps `head`. Nothing is ever141// queued: the next offer simply sends everything the remote does not have.142pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {143	name, remote_head := repo_name_with_head(store, mut backend)!144	local := history.head(store) or { return error(no_saves) }145	mut report := OfferReport{146		repo: name147		head: local.id148	}149	mut format := check_format(mut backend, name)!150	if format == '' {151		// A repo with a head keeps version 1; only a new repo starts at 2 (§9.2).152		format = put_format(mut backend, name, if remote_head.found { format_v1 } else { format_v2 })!153	}154	// One listing serves both the strip check and the upload. An event that155	// lands after it is caught by undo_late_strips below.156	event_keys := backend.list(events_prefix(name))!157	// Records offered by a machine that has not applied a strip would put the158	// stripped path back on the remote, where nothing would rewrite it again.159	if unapplied_strips(store, mut backend, event_keys)!.len > 0 {160		return error(strip_not_applied)161	}162	mut uploaded := Uploaded{}163	upload_line(store, mut backend, name, local.id, remote_head, format, event_keys, mut report,164		mut uploaded) or { return after_failed_upload(store, mut backend, name, uploaded, err) }165	// A strip sends its event before it lists the saves to rewrite, so one166	// missed here lists them after these records landed and rewrites them. One167	// seen here may have rewritten before they landed: take back what it reaches.168	// With nothing uploaded there is nothing to take back; a strip that landed169	// during a no-op offer is caught by the check above on the next one.170	if (uploaded.saves.len > 0 || uploaded.objects.len > 0)171		&& undo_late_strips(store, mut backend, name, uploaded)! {172		return error(strip_not_applied)173	}174	// A head already naming these saves needs no write: skipping the PUT saves175	// a request, and its tag stays as it was.176	if remote_head.body.bytestr().trim_space() != local.id177		&& !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {178		// A lost answer to a retried PUT lands here too: the tag is stale because179		// the write already happened. Read the head back before calling it a clash.180		again := backend.get(head_key(name))!181		if !again.found || again.body.bytestr().trim_space() != local.id {182			return error('remote has new saves — run koh steal')183		}184	}185	store.set_state(remote_head_key, local.id)!186	return report187}188189// saves_after lists the local saves newer than `theirs`, oldest first. It fails190// when `theirs` is not on this line, which is the honest answer: we cannot191// offer on top of a save we do not have.192fn saves_after(store &storage.Store, ours string, theirs string) ![]history.Save {193	mut newer := []history.Save{}194	mut cursor := ours195	for cursor != '' && cursor != theirs {196		save := history.by_id(store, cursor) or { return error('save ${cursor} is missing') }197		newer << save198		cursor = save.parent199	}200	if cursor != theirs {201		return error('${theirs} is not on this line')202	}203	newer.reverse_in_place()204	return newer205}206207const strip_not_applied = 'the remote has a strip this repo has not applied — run koh steal'208209// Uploaded is what one upload put on the remote, so a late strip can take it back.210struct Uploaded {211mut:212	saves   []string213	objects map[string]bool214	deleted int // damaged remote copies removed before their replacement215}216217fn (u Uploaded) done() []string {218	mut done := done_text('deleted', u.deleted, 'damaged remote object')219	if u.saves.len + u.objects.len > 0 {220		done << 'uploaded ${fmt.plural(u.objects.len, 'object')} and ${fmt.plural(u.saves.len, 'save record')}'221	}222	return done223}224225// upload_line sends every save after the remote head, then the events. `sent_manifests`226// is kept across the whole line so a folder two saves share is uploaded once.227fn upload_line(store &storage.Store, mut backend remote.Backend, name string, local string, remote_head remote.Object, format string, event_keys []string, mut report OfferReport, mut uploaded Uploaded) ! {228	mut sent_manifests := map[string]bool{}229	if remote_head.found {230		theirs := remote_head.body.bytestr().trim_space()231		newer := saves_after(store, local, theirs) or {232			return error('remote has new saves — run koh steal')233		}234		for save in newer {235			upload_save(store, mut backend, name, save, format, mut sent_manifests, mut report,236				mut uploaded)!237		}238	} else {239		oldest_first := history.line(store)!240		for index := oldest_first.len - 1; index >= 0; index-- {241			upload_save(store, mut backend, name, oldest_first[index], format, mut sent_manifests,242				mut report, mut uploaded)!243		}244	}245	upload_events(store, mut backend, name, event_keys, mut report)!246}247248// after_failed_upload still applies a strip that landed before the failure249// to what the upload had put.250fn after_failed_upload(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, failure IError) IError {251	undo_late_strips(store, mut backend, repo, uploaded) or {252		return error('${failure.msg()}; removing what a strip on the remote covers also failed: ${err.msg()}')253	}254	return failure255}256257// unsettled_key keeps what an upload sent when settling a late strip failed,258// for Doctor to finish once a steal brings the strip here.259pub const unsettled_key = 'upload_unsettled'260261pub fn unsettled(store &storage.Store) ![]string {262	text := store.state(unsettled_key) or { return []string{} }263	return json2.decode[[]string](text) or {264		return error('the note of an unsettled upload is unreadable; it is kept for recovery')265	}266}267268fn undo_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {269	return settle_late_strips(store, mut backend, repo, uploaded) or {270		failure := err271		mut kept := unsettled(store) or { return error('${failure.msg()}; ${err.msg()}') }272		kept << uploaded.objects.keys().filter(it !in kept)273		store.set_state(unsettled_key, json2.encode(kept)) or {274			return error('${failure.msg()}; ${err.msg()}')275		}276		return failure277	}278}279280// settle_late_strips applies strips that reached the remote during an upload281// to what it put, and reports whether there were any. Records stay, less the282// stripped paths, as another offer or head may name them. Notes go first and283// objects last, so a stop part way leaves a note and no record without its object.284fn settle_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {285	event_keys := backend.list(events_prefix(repo))!286	strips := unapplied_strips(store, mut backend, event_keys)!287	if strips.len == 0 {288		return false289	}290	for strip in strips {291		queue_strip(store, strip.path, [strip.save_id], uploaded.objects.keys())!292	}293	for id in uploaded.saves {294		strip_record(store, mut backend, repo, save_key(repo, id), id, strips)!295	}296	drop_stripped_objects(store, mut backend, repo, uploaded, strips)!297	return true298}299300// strip_record rewrites one remote record without what `strips` cover, reading301// it again when it moved. A version-2 record is rewritten as its tree: the new302// folders go up before the record names a new root.303fn strip_record(store &storage.Store, mut backend remote.Backend, repo string, key string, id string, strips []events.Event) ! {304	mut manifests := map[string]string{}305	mut sent := map[string]bool{}306	mut rewriter := Rewriter{}307	for _ in 0 .. 5 {308		object := backend.get(key)!309		if !object.found {310			return311		}312		record := decode_save(object.body)!313		if record.manifest != '' {314			fetch_manifests(mut backend, repo, record.manifest, mut manifests)!315			store_manifests(store, manifests)!316			mut root := record.manifest317			for strip in strips {318				if !reaches(strip, id) {319					continue320				}321				rewritten := rewriter.rewrite(store, root, strip.path.trim_right('/'))!322				if rewritten.changed {323					root = rewritten.hash324				}325			}326			if root == record.manifest {327				return328			}329			upload_manifests(store, mut backend, repo, root, mut sent)!330			if backend.put_if_match(key, encode_save(rewrite(record, record.files, root)).bytes(), object.tag)! {331				return332			}333			continue334		}335		kept := record.files.filter(fn [strips, id] (file FileRecord) bool {336			return !strips.any(reaches(it, id) && covers(it.path, file.path))337		})338		if kept.len == record.files.len339			|| backend.put_if_match(key, encode_save(rewrite(record, kept, '')).bytes(), object.tag)! {340			return341		}342	}343	return error('the remote copy of save ${id} kept changing while a stripped path was removed; run koh doctor again')344}345346// Partway is a failure after some work had already landed. `done` says what,347// so Doctor can report both.348pub struct Partway {349	Error350pub:351	done   string352	reason string353}354355pub fn (e Partway) msg() string {356	return e.reason357}358359// done_text is what a step finished before it failed, if anything.360pub fn done_text(verb string, done int, noun string) []string {361	return if done == 0 { []string{} } else { ['${verb} ${fmt.plural(done, noun)}'] }362}363364// partway adds what was `done` before `failure` to it, including what a365// failing step of its own had done.366pub fn partway(done []string, failure IError) IError {367	mut all := done.clone()368	if failure is Partway {369		all << failure.done370	}371	if all.len == 0 {372		return failure373	}374	return Partway{375		done:   all.join('; ')376		reason: failure.msg()377	}378}379380// drop_stripped_objects deletes what an upload put that a strip reaches in a381// save here, unless a remote record lists it under a path no strip covers:382// another machine may hold the same bytes there.383fn drop_stripped_objects(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded, strips []events.Event) ! {384	mut reached := map[string]bool{}385	// A local save that still names it under another path may have no other copy.386	mut kept := map[string]bool{}387	for save in history.all_saves(store)! {388		for file in history.files_of(store, save.id)!.filter(it.hash in uploaded.objects) {389			if strips.any(reaches(it, save.id) && covers(it.path, file.path)) {390				reached[file.hash] = true391			} else {392				kept[file.hash] = true393			}394		}395	}396	if reached.len == 0 {397		return398	}399	mut manifests := map[string]string{}400	for key in backend.list('${repo}/saves')! {401		object := backend.get(key)!402		if object.found {403			record := decode_save(object.body)!404			for file in record_files(mut backend, repo, record, mut manifests)! {405				if !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {406					reached.delete(file.hash)407				}408			}409		}410	}411	for hash, _ in reached {412		if hash !in kept {413			backend.delete(object_key(repo, hash))!414		}415	}416}417418// upload_save puts a save's new objects, its manifest tree, then its record, so a record on the419// remote finds both. Retrying after a partial offer is safe; `uploaded` keeps what this call420// created, which is all undo_late_strips may delete.421fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, format string, mut sent_manifests map[string]bool, mut report OfferReport, mut uploaded Uploaded) ! {422	files := history.files_of(store, save.id)!423	// Saves go up oldest first and head moves only once all of them landed, so424	// the parent and its objects are on the remote already: only content new425	// in this save travels, not a round trip per file in the repo.426	mut sent := map[string]bool{}427	if save.parent != '' {428		for file in history.files_of(store, save.parent)! {429			sent[file.hash] = true430		}431	}432	for file in files {433		if file.hash in sent {434			continue435		}436		sent[file.hash] = true437		if backend.put_if_absent(object_key(repo, file.hash), store.object_blob(file.hash)!)! {438			report.objects++439			uploaded.objects[file.hash] = true440		}441	}442	// Manifests travel before the record naming them (spec §9.2).443	mut record := SaveRecord{}444	if format == format_v2 {445		upload_manifests(store, mut backend, repo, save.manifest, mut sent_manifests)!446		record = save_record_v2(store, save)!447	} else {448		record = save_record(store, save)!449	}450	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {451		report.saves++452		uploaded.saves << save.id453	}454}455456// upload_manifests sends every folder a save's tree names, once per offer: a457// key is the same body however many saves reach it.458fn upload_manifests(store &storage.Store, mut backend remote.Backend, repo string, root string, mut sent map[string]bool) ! {459	mut pending := [root]460	for pending.len > 0 {461		hash := pending.pop()462		if hash in sent {463			continue464		}465		sent[hash] = true466		backend.put_if_absent(manifest_key(repo, hash), store.manifest_body(hash)!.bytes())!467		for entry in store.manifest_entries(hash)! {468			if entry.kind == storage.folder_kind {469				pending << entry.manifest470			}471		}472	}473}474475// fetch_manifests reads every folder a version-2 tree names, checking each body476// against its key. A fetch writes nothing until its transaction.477pub fn fetch_manifests(mut backend remote.Backend, repo string, root string, mut manifests map[string]string) ! {478	mut pending := [root]479	for pending.len > 0 {480		hash := pending.pop()481		if hash in manifests {482			continue483		}484		object := backend.get(manifest_key(repo, hash))!485		if !object.found {486			return error('the remote is missing manifest ${hash}')487		}488		if storage.hash_hex(object.body) != hash {489			return error('remote manifest ${hash} fails Blake3 verification')490		}491		body := object.body.bytestr()492		manifests[hash] = body493		entries := json2.decode[storage.Manifest](body) or {494			return error('remote manifest ${hash} is unreadable: ${err.msg()}')495		}496		for entry in entries.entries {497			if entry.kind == storage.folder_kind {498				pending << entry.manifest499			}500		}501	}502}503504// store_manifests writes freshly read bodies into the local table for a505// rewriter. An identical body is already there, so writing it again is a no-op.506fn store_manifests(store &storage.Store, manifests map[string]string) ! {507	for _, body in manifests {508		store.put_manifest(body)!509	}510}511512// flatten_files is a fetched tree as record entries; a record carries no sizes.513fn flatten_files(manifests map[string]string, root string) ![]FileRecord {514	files := storage.flatten_bodies(manifests, root)!515	mut records := []FileRecord{cap: files.len}516	for file in files {517		records << FileRecord{518			path:       file.path519			hash:       file.hash520			executable: file.executable521		}522	}523	return records524}525526// record_files reads a record's list from the remote, flattening its tree when527// it names one, whatever layout wrote it. `manifests` is the caller's cache, so528// a walk over many records fetches each shared folder once.529pub fn record_files(mut backend remote.Backend, repo string, record SaveRecord, mut manifests map[string]string) ![]FileRecord {530	if record.manifest == '' {531		return record.files532	}533	fetch_manifests(mut backend, repo, record.manifest, mut manifests)!534	return flatten_files(manifests, record.manifest)535}536537// upload_events sends every event the remote does not have. Events are tiny, so538// a listing costs less than tracking which ones were sent; `already` is the539// listing the caller already had.540fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, already []string, mut report OfferReport) ! {541	mut already_sent := map[string]bool{}542	for key in already {543		already_sent[os.base(key)] = true544	}545	for event in events.all(store)! {546		if event.id in already_sent {547			continue548		}549		if backend.put_if_absent(event_key(repo, event.id), encode_event(event).bytes())! {550			report.events++551		}552	}553}554555// fetched holds everything a steal read from the remote, before any of it is556// written locally. Network work happens first; the database gets one557// transaction, so a failure leaves nothing half-applied.558pub struct Fetched {559pub mut:560	repo_objects map[string][]u8561	// A version-2 record's tree, read before anything is written.562	manifests    map[string]string563	object_bytes int          // repo_objects, so a big steal is written in batches564	saves        []SaveRecord // oldest first565	events_out   []events.Event566	head         string567	base         string // the newest save both sides already shared, '' when none568	unsafe_paths []string569}570571// Objects that arrived are written once this much is held. They are572// content-addressed, so an interrupted steal leaves only unreferenced rows,573// which Doctor can remove; the saves and events still land in one transaction.574const object_batch_bytes = 64 * 1024 * 1024575576fn (mut f Fetched) add_object(store &storage.Store, hash string, blob []u8) ! {577	f.repo_objects[hash] = blob578	f.object_bytes += blob.len579	if f.object_bytes >= object_batch_bytes {580		for key, bytes in f.repo_objects {581			store.put_object_blob(key, bytes)!582		}583		f.repo_objects.clear()584		f.object_bytes = 0585	}586}587588// fetch_back_to_known walks from the remote head along parents until it meets a save on this line589// (`base`), reading only the objects this repo lacks. Objects are written in batches as they590// arrive; the saves and events land together in write_fetched's transaction.591// A save held locally but off the line, from an earlier steal, is taken from the local copy.592pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {593	format := check_format(mut backend, repo)!594	// A repo with no format key counts as version 1 (spec §9.2), so a record595	// must match its repo's layout either way.596	layout := if format == '' { format_v1 } else { format }597	remote_head := backend.get(head_key(repo))!598	if !remote_head.found {599		return error('the remote has no "${repo}" yet — run koh offer here first')600	}601	mut fetched := Fetched{602		head: remote_head.body.bytestr().trim_space()603	}604	if !valid_save_id(fetched.head) {605		return error('the remote head has invalid save ID ${fetched.head}')606	}607	mut on_line := map[string]bool{}608	for save in history.line(store)! {609		on_line[save.id] = true610	}611	// Strips come first: an object only a stripped path named may be gone.612	fetched.events_out = fetch_events(store, mut backend, repo)!613	strips := known_strips(store, fetched)!614	mut cursor := fetched.head615	mut seen := map[string]bool{}616	for cursor != '' && cursor !in on_line {617		if cursor in seen {618			return error('the remote history has a parent cycle at ${cursor}')619		}620		seen[cursor] = true621		mut record := if saved := history.by_id(store, cursor) {622			save_record(store, saved)!623		} else {624			record_object := backend.get(save_key(repo, cursor))!625			if !record_object.found {626				return error('the remote is missing save ${cursor} — run koh offer there')627			}628			mut decoded := decode_save(record_object.body)!629			validate_save(decoded, cursor)!630			record_layout := if decoded.manifest == '' { format_v1 } else { format_v2 }631			if record_layout != layout {632				return error('the remote "${repo}" is ${layout} but save ${cursor} is a ${record_layout} record — update koh on the machine that offered it')633			}634			if decoded.manifest != '' {635				fetch_manifests(mut backend, repo, decoded.manifest, mut fetched.manifests)!636				decoded.files = flatten_files(fetched.manifests, decoded.manifest)!637			}638			decoded639		}640		fetched.unsafe_paths << drop_unsafe_paths(mut record)641		validate_hashes(record.id, record.files)!642		for file in record.files {643			if !store.has_object(file.hash)! && file.hash !in fetched.repo_objects644				&& !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {645				blob := backend.get(object_key(repo, file.hash))!646				if !blob.found {647					return error('the remote is missing object ${file.hash} that save ${record.id} needs')648				}649				fetched.add_object(store, file.hash, blob.body)!650			}651		}652		fetched.saves << record653		cursor = record.parent654	}655	fetched.saves.reverse_in_place()656	fetched.base = cursor657	return fetched658}659660fn fetch_events(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {661	have := events.all(store)!662	mut known := map[string]bool{}663	for event in have {664		known[event.id] = true665	}666	mut incoming := []events.Event{}667	for key in backend.list(events_prefix(repo))! {668		id := os.base(key)669		if !valid_event_id(id) {670			return error('the remote has invalid event ID ${id}')671		}672		if id in known {673			continue674		}675		body := backend.get(event_key(repo, id))!676		if !body.found {677			continue678		}679		event := decode_event(body.body)!680		if event.id != id {681			return error('remote event record ID ${event.id} disagrees with key ${id}')682		}683		if !ignored_strip(event) {684			incoming << event685		}686	}687	return incoming688}689690// write_fetched lands a fetch in one transaction: objects (verified), events,691// manifests, saves. A strip reaches every save, here or arriving, whenever692// made; its rewrite collects the folders no save reaches, and the arriving693// saves are not rows yet, so their manifests go in after it and before them.694pub fn write_fetched(store &storage.Store, fetched Fetched) ! {695	for hash, blob in fetched.repo_objects {696		store.put_object_blob(hash, blob)!697	}698	mut freed := []string{}699	for event in fetched.events_out {700		if !events.receive(store, event)! {701			continue702		}703		if events.valid_strip(event) {704			freed << stripped_hashes(store, event.path, event.save_id)!705			remove_path(store, event.path, event.save_id)!706		}707	}708	for hash, body in fetched.manifests {709		store.put_manifest(body)!710	}711	strips := known_strips(store, fetched)!712	for record in fetched.saves {713		for file in record.files {714			if file.hash in fetched.repo_objects715				&& strips.any(reaches(it, record.id) && covers(it.path, file.path)) {716				freed << file.hash717			}718		}719		import_arriving(store, record, strips)!720	}721	store.drop_unused(freed)!722}723724// write_fetched_records makes network work durable without changing the line.725// Events wait for the combine transaction because a strip can rewrite history.726pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {727	for hash, body in fetched.manifests {728		store.put_manifest(body)!729	}730	for hash, blob in fetched.repo_objects {731		store.put_object_blob(hash, blob)!732	}733	strips := known_strips(store, fetched)!734	for record in fetched.saves {735		import_arriving(store, record, strips)!736	}737}738739// known_strips is every valid strip held here and every one the fetch brings:740// an arriving save loses what any of them reaches, not only what arrived with it.741fn known_strips(store &storage.Store, fetched Fetched) ![]events.Event {742	mut strips := events.strip_events(store)!743	strips << fetched.events_out744	return strips.filter(events.valid_strip(it))745}746747// import_arriving lands one save from the remote, unless it is already here, less every path a748// strip that `reaches` it removed.749fn import_arriving(store &storage.Store, record SaveRecord, strips []events.Event) ! {750	if history.by_id(store, record.id) != none {751		return752	}753	validate_save(record, record.id)!754	safe := record.files.filter(snapshot.legal_path(it.path))755	validate_hashes(record.id, safe)!756	files := to_files(record).filter(fn [strips, record] (file snapshot.FileEntry) bool {757		return snapshot.legal_path(file.path)758			&& !strips.any(reaches(it, record.id) && covers(it.path, file.path))759	})760	// Nothing was filtered, so the arriving manifests are exactly this list and761	// the save names that tree; a strip that removed something rebuilds it.762	mut save := to_save(record)763	save.manifest = ''764	if record.manifest != '' && files.len == record.files.len {765		save.manifest = record.manifest766	}767	history.import_save(store, save, files)!768}769770// reaches reports whether a strip event applies to a save: its one save, or771// every save there is, whenever it was made.772fn reaches(strip events.Event, save_id string) bool {773	return strip.save_id == '' || strip.save_id == save_id774}