steal.v

23.3 KB · raw

1//! Stealing: bringing another machine's saves in, and combining when both2//! machines moved.3//!4//! The order is always the same, and it is what makes an interrupted steal5//! harmless: read everything from the remote first, then land it in one6//! transaction, then write the working tree. Divergence is resolved per file —7//! a clash is never blended line by line, it is chosen.89module exchange1011import src.apply12import src.events13import src.fmt14import src.history15import src.remote16import src.snapshot17import src.storage18import strconv1920pub enum Side {21	mine22	theirs23}2425// Clash is one file both machines changed differently. `stat` is the short26// diff stat the terminal prompt shows, so the choice is informed.27pub struct Clash {28pub mut:29	path         string30	mine         snapshot.FileEntry31	theirs       snapshot.FileEntry32	base         snapshot.FileEntry33	mine_stat    string34	theirs_stat  string35	mine_patch   string36	theirs_patch string37	mine_save    history.Save38	theirs_save  history.Save39}4041pub struct StealPreview {42pub:43	repo      string44	base      history.Save45	local     []history.Save46	remote    []SaveRecord47	changed   int48	automatic int49	identical int50	clashes   []Clash51	yes       bool52	all_side  string53}5455pub struct StealOptions {56pub mut:57	mine   bool // resolve every clash as mine58	theirs bool // resolve every clash as theirs59	// Shown the whole combine and asked about every clash. Nil means "nobody to ask".60	guide   fn (preview StealPreview) !map[string]Side = unsafe { nil }61	yes     bool62	json    bool63	approve fn (saves int, events int, yes bool, json bool) ! = unsafe { nil }64}6566pub struct StealReport {67pub mut:68	repo            string69	forward         bool70	fetched_saves   int71	fetched_objects int72	fetched_events  int73	clashes         []string74	kept_mine       int75	replayed        int76	removed         int77	head            string78	flagged         []events.Flag // incoming saves that are flagged79	// Set when a combine took this machine's saves off the line: loading it80	// brings back the tree from before the steal, less anything stripped.81	previous_head string82	kept_versions []string83	unsafe_paths  []string84}8586pub const dirty_tree = 'save or checkpoint first — steal needs a clean tree'8788// ClashError is a clash nobody was there to decide. It carries the paths because the advice89// depends on the command: `koh steal` takes --mine or --theirs, `koh offer` does not.90pub struct ClashError {91	Error92pub:93	paths []string94}9596pub fn (e ClashError) msg() string {97	return '${e.paths.join(', ')} changed on both machines — run on a terminal to choose, or pass --mine or --theirs with --yes'98}99100pub const no_saves_here = 'this folder has files but no saves — steal a repo into an empty folder with "koh steal <name>"'101102// steal brings the remote's new saves in. Inside a repo with its own work this103// may have to combine; a repo with nothing of its own simply fast-forwards.104pub fn steal(store &storage.Store, mut backend remote.Backend, opts StealOptions) !StealReport {105	name := repo_name(store, mut backend)!106	if snapshot.restore_pending(store) {107		return error(snapshot.restore_unfinished)108	}109	head_before := history.head(store)110	// Combining rewrites the working tree, so unsaved work would be lost.111	if dirty(store, head_before)! {112		if head_before == none {113			return error(no_saves_here)114		}115		return error(dirty_tree)116	}117	fetched := fetch_back_to_known(store, mut backend, name)!118	mut report := StealReport{119		repo:            name120		fetched_saves:   fetched.saves.len121		fetched_objects: fetched.repo_objects.len122		fetched_events:  fetched.events_out.len123		head:            fetched.head124		unsafe_paths:    fetched.unsafe_paths125	}126	mut local_only := []history.Save{}127	if head := head_before {128		// The remote builds on `base`. If that save is here but no longer on129		// the line, neither line contains the other; jumping to the remote130		// would silently leave this line behind.131		local_only = saves_after(store, head.id, fetched.base) or {132			return error('the remote builds on save ${fetched.base}, which is not on this line — load the save you want, then offer')133		}134	}135	if fetched.base == '' && local_only.len > 0 {136		return error('the remote keeps a different history — it shares no save with this repo')137	}138	if (fetched.saves.len > 0 || fetched.events_out.len > 0)139		&& !(fetched.saves.len > 0 && local_only.len > 0 && opts.guide != unsafe { nil })140		&& opts.approve != unsafe { nil } {141		opts.approve(fetched.saves.len, fetched.events_out.len, opts.yes, opts.json)!142	}143	if fetched.saves.len > 0 {144		store.begin()!145		write_fetched_records(store, fetched) or {146			store.rollback()147			return err148		}149		store.end()!150	}151152	strips_before := events.strip_events(store)!.len153	mut clashes := []Clash{}154	mut side_of := map[string]Side{}155	if fetched.saves.len > 0 && local_only.len > 0 {156		clashes = combine_clashes(store, fetched, local_only)!157		report.clashes = clashes.map(it.path)158		if opts.guide != unsafe { nil } {159			side_of = opts.guide(combine_preview(store, name, fetched, local_only, clashes,160				opts.yes, if opts.mine {161					'mine'162				} else if opts.theirs { 'theirs' } else { '' })!)!163		} else {164			// Asked before the write lock: a person thinking must not stall every165			// agent's save on this repo.166			side_of = choose_sides(clashes, opts)!167		}168	}169	for clash in clashes {170		if side_of[clash.path] == .theirs {171			report.kept_versions << '${clash.path}:${local_only.last().id}'172		}173	}174175	store.begin() or { return err }176	// The questions ran without the lock. If a save or an edit landed177	// meanwhile, the answers were about a line that no longer exists.178	if moved := changed_since(store, head_before, strips_before) {179		if moved {180			store.rollback()181			return error('this repo changed while steal was asking — run koh steal again')182		}183	} else {184		store.rollback()185		return err186	}187	final := (write_and_combine(store, fetched, local_only, clashes, side_of, mut report) or {188		store.rollback()189		return err190	})191	files := history.files_of(store, final.id) or {192		store.rollback()193		return err194	}195	snapshot.check_links(store.root, files) or {196		store.rollback()197		return err198	}199	// The files follow the transaction; the mark lands with it, in one step.200	// No head before means a fresh steal, whose whole tree is new.201	moved := if head := head_before { final.id != head.id } else { true }202	if moved {203		snapshot.mark_restore(store) or {204			store.rollback()205			return err206		}207	}208	store.end() or { return err }209	report.head = final.id210	if local_only.len > 0 && report.fetched_saves > 0 {211		report.previous_head = local_only.last().id212	}213	flags := events.latest_flags(store)!214	for record in fetched.saves {215		if flag := flags[record.id] {216			if flag.flagged {217				report.flagged << flag218			}219		}220	}221222	if head := head_before {223		if final.id == head.id {224			// The line did not move, so neither does the working tree.225			return report226		}227		mut wanted := map[string]bool{}228		for file in files {229			wanted[file.path] = true230		}231		mut remove := []string{}232		for file in history.files_of(store, head.id)! {233			if file.path !in wanted {234				remove << file.path235			}236		}237		result := snapshot.restore_files(store, store.root, snapshot.load(store.root), files,238			remove)!239		report.removed = result.removed240	} else {241		snapshot.restore_files(store, store.root, snapshot.load(store.root), files, [])!242	}243	history.refresh_log_md(store)244	return report245}246247// write_and_combine lands a fetch and, when the local line has saves the remote248// lacks, replays them on top of the remote head. It runs inside the caller's249// transaction and returns the new head.250fn write_and_combine(store &storage.Store, fetched Fetched, local_only []history.Save, clashes []Clash, side_of map[string]Side, mut report StealReport) !history.Save {251	write_fetched(store, fetched)!252	if fetched.saves.len == 0 {253		// The remote head is already on this line: level, or this machine is254		// ahead and the offer that follows a steal sends the rest.255		return history.head(store) or { return error('this repo has no head') }256	}257	if local_only.len == 0 {258		// Nothing of ours is missing from the remote: the line simply moves on.259		history.set_head(store, fetched.head)!260		report.forward = true261		return history.head(store) or { return error('the remote head did not land') }262	}263	remote_files := history.files_of(store, fetched.head)!264	mut mine_files := []snapshot.FileEntry{}265	if our_head := history.head(store) {266		mine_files = history.files_of(store, our_head.id)!267	}268269	// A file the remote changed is a clash, decided below, or one this machine270	// left as it was or changed the same way, so the remote's version stands.271	// Replaying this machine's steps on it could only conflict: an edit it272	// later undid would no longer apply.273	base_files := history.files_of(store, fetched.base)!274	settled := changed_paths(base_files, remote_files)275276	// Take the remote's line first, so the replayed saves chain onto it.277	history.set_head(store, fetched.head)!278	mut current := remote_files.clone()279	for save in local_only {280		parent_files := if save.parent != '' {281			history.files_of(store, save.parent)!282		} else {283			[]snapshot.FileEntry{}284		}285		target_files := history.files_of(store, save.id)!286		plan := apply.three_way(current, parent_files, target_files, [], settled)287		if apply.conflicts(plan) {288			return error('combine could not apply ${plan.conflict} — it is not a clash file')289		}290		if plan.applied.len == 0 {291			// Everything this save touched was a file the remote changed.292			continue293		}294		history.record_save(store, '', plan.files, history.SaveInput{295			message:       save.message296			created_at:    save.created_at297			machine:       save.machine298			agent:         save.agent299			session:       save.session300			is_checkpoint: save.is_checkpoint301			replayed_from: save.id302		})!303		current = plan.files.clone()304		report.replayed++305	}306307	mut mine_paths := []string{}308	for clash in clashes {309		if side_of[clash.path] == .mine {310			mine_paths << clash.path311		}312	}313	if mine_paths.len > 0 {314		// One last save puts my versions of the chosen files back.315		final_plan := apply.three_way(current, current, mine_files, mine_paths, [])316		if final_plan.applied.len > 0 {317			history.record_save(store, '', final_plan.files, history.SaveInput{318				message: 'combine: kept mine for ${mine_paths.len} ${if mine_paths.len == 1 {319					'file'320				} else {321					'files'322				}}'323			})!324			report.kept_mine = mine_paths.len325		}326	}327	return history.head(store) or { return error('the combined line has no head') }328}329330// find_clashes lists the files both sides changed, differently. Files changed331// identically on both sides are not clashes: there is nothing to decide.332pub fn find_clashes(base []snapshot.FileEntry, mine []snapshot.FileEntry, theirs []snapshot.FileEntry) []Clash {333	base_map := snapshot.index_files(base)334	mine_map := snapshot.index_files(mine)335	theirs_map := snapshot.index_files(theirs)336	mut paths := mine_map.keys()337	for path in theirs_map.keys() {338		if path !in mine_map {339			paths << path340		}341	}342	paths.sort()343	mut clashes := []Clash{}344	for path in paths {345		here := mine_map[path] or {346			snapshot.FileEntry{347				path: path348			}349		}350		there := theirs_map[path] or {351			snapshot.FileEntry{352				path: path353			}354		}355		was := base_map[path] or {356			snapshot.FileEntry{357				path: path358			}359		}360		if same(here, there) {361			continue362		}363		if same(here, was) || same(there, was) {364			continue365		}366		clashes << Clash{367			path:   path368			mine:   here369			theirs: there370			base:   was371		}372	}373	return clashes374}375376// changed_paths lists the paths whose entry differs between two trees.377fn changed_paths(before []snapshot.FileEntry, after []snapshot.FileEntry) []string {378	was := snapshot.index_files(before)379	now := snapshot.index_files(after)380	mut paths := []string{}381	for path, entry in now {382		if !same(entry, was[path] or { snapshot.FileEntry{} }) {383			paths << path384		}385	}386	for path, _ in was {387		if path !in now {388			paths << path389		}390	}391	return paths392}393394// combine_clashes finds the files both lines changed, with the diff stat each395// prompt shows. It reads the remote head from the fetch, not the store, so it396// can run before anything is written.397fn combine_clashes(store &storage.Store, fetched Fetched, local_only []history.Save) ![]Clash {398	base_files := if fetched.base != '' {399		history.files_of(store, fetched.base)!400	} else {401		[]snapshot.FileEntry{}402	}403	head := history.head(store) or { return []Clash{} }404	// The transaction applies every known strip before it replays, so the405	// clashes are found on the trees as they will be then, or the answers406	// would be about files that are no longer there.407	strips := known_strips(store, fetched)!408	remote_head := fetched.saves.last()409	mut clashes := find_clashes(after_strips(base_files, fetched.base, strips), after_strips(history.files_of(store,410		head.id)!, head.id, strips), after_strips(to_files(remote_head), remote_head.id, strips))411	// One cache for the whole clash pass: each save's file list is read once,412	// not once per clash on either side.413	mut trees := map[string]map[string]snapshot.FileEntry{}414	for mut clash in clashes {415		base := fetched_bytes(store, fetched, clash.base)!416		mine := fetched_bytes(store, fetched, clash.mine)!417		theirs := fetched_bytes(store, fetched, clash.theirs)!418		mine_delta := snapshot.diff_bytes(clash.path, 'modified', base, mine)!419		theirs_delta := snapshot.diff_bytes(clash.path, 'modified', base, theirs)!420		clash.mine_stat = delta_stat(mine_delta, clash.mine.size)421		clash.theirs_stat = delta_stat(theirs_delta, clash.theirs.size)422		clash.mine_patch = mine_delta.patch423		clash.theirs_patch = theirs_delta.patch424		clash.mine_save = last_touch(store, local_only, clash.path, mut trees)!425		clash.theirs_save = last_touch(store, fetched.saves.map(to_save(it)), clash.path, mut trees)!426	}427	return clashes428}429430fn delta_stat(delta snapshot.Delta, size i64) string {431	if delta.binary {432		return fmt.human_bytes(size)433	}434	return '+${delta.added} -${delta.removed}'435}436437// last_touch is the newest save that changed `path`, walking back from the end.438// `trees` is the caller's cache, so each save's list is indexed once per steal439// rather than once per clash.440fn last_touch(store &storage.Store, saves []history.Save, path string, mut trees map[string]map[string]snapshot.FileEntry) !history.Save {441	for index := saves.len - 1; index >= 0; index-- {442		save := saves[index]443		here := save_tree(store, mut trees, save.id)!444		current := here[path] or { snapshot.FileEntry{} }445		mut parent := snapshot.FileEntry{}446		if save.parent != '' {447			was := save_tree(store, mut trees, save.parent)!448			parent = was[path] or { snapshot.FileEntry{} }449		}450		if !same(current, parent) {451			return save452		}453	}454	return saves.last()455}456457// save_tree is a save's files indexed by path, read once and kept for the rest458// of the steal.459fn save_tree(store &storage.Store, mut trees map[string]map[string]snapshot.FileEntry, save_id string) !map[string]snapshot.FileEntry {460	if index := trees[save_id] {461		return index462	}463	index := snapshot.index_files(history.files_of(store, save_id)!)464	trees[save_id] = index465	return index466}467468// combine_preview counts what a combine would do to the paths either side changed since `base`:469// `identical` were changed the same way on both sides, `clashes` need a choice, the rest go in by themselves.470fn combine_preview(store &storage.Store, name string, fetched Fetched, local []history.Save, clashes []Clash, yes bool, all_side string) !StealPreview {471	base := history.files_of(store, fetched.base)!472	mine := history.files_of(store, local.last().id)!473	theirs := history.files_of(store, fetched.head)!474	mine_changed := changed_paths(base, mine)475	theirs_changed := changed_paths(base, theirs)476	mut changed := map[string]bool{}477	for path in mine_changed {478		changed[path] = true479	}480	for path in theirs_changed {481		changed[path] = true482	}483	mut identical := 0484	base_map := snapshot.index_files(base)485	mine_map := snapshot.index_files(mine)486	theirs_map := snapshot.index_files(theirs)487	for path, _ in changed {488		if !same(mine_map[path] or { snapshot.FileEntry{} }, base_map[path] or { snapshot.FileEntry{} })489			&& same(mine_map[path] or { snapshot.FileEntry{} }, theirs_map[path] or { snapshot.FileEntry{} }) {490			identical++491		}492	}493	return StealPreview{494		repo:      name495		base:      history.by_id(store, fetched.base) or { history.Save{} }496		local:     local497		remote:    fetched.saves498		changed:   changed.len499		automatic: changed.len - identical - clashes.len500		identical: identical501		clashes:   clashes502		yes:       yes503		all_side:  all_side504	}505}506507// after_strips is a save's file list once the given strip events are applied,508// by the same rule write_fetched uses.509fn after_strips(files []snapshot.FileEntry, save_id string, strips []events.Event) []snapshot.FileEntry {510	return files.filter(fn [strips, save_id] (file snapshot.FileEntry) bool {511		return !strips.any(reaches(it, save_id) && covers(it.path, file.path))512	})513}514515// fetched_bytes reads one side of a clash: from the fetch when it has just516// arrived, else from the store. An absent side is empty.517fn fetched_bytes(store &storage.Store, fetched Fetched, entry snapshot.FileEntry) ![]u8 {518	if entry.hash == '' {519		return []u8{}520	}521	if blob := fetched.repo_objects[entry.hash] {522		return storage.inflate_bounded(blob, storage.max_file_size)!523	}524	return store.get_object(entry.hash)!525}526527fn choose_sides(clashes []Clash, opts StealOptions) !map[string]Side {528	mut sides := map[string]Side{}529	if clashes.len == 0 {530		return sides531	}532	for clash in clashes {533		if opts.mine {534			sides[clash.path] = .mine535			continue536		}537		if opts.theirs {538			sides[clash.path] = .theirs539			continue540		}541		return ClashError{542			paths: clashes.map(it.path)543		}544	}545	return sides546}547548fn same(a snapshot.FileEntry, b snapshot.FileEntry) bool {549	if a.hash == '' && b.hash == '' {550		return true551	}552	return a.hash == b.hash && a.executable == b.executable553}554555fn changed_since(store &storage.Store, before ?history.Save, strips_before int) !bool {556	if events.strip_events(store)!.len != strips_before {557		return true558	}559	now := history.head(store)560	if now or { history.Save{} }.id != before or { history.Save{} }.id {561		return true562	}563	return dirty(store, now)!564}565566// dirty reports whether the working tree holds anything a steal would567// overwrite. With no saves yet, that is every file but the untouched ignore568// list `koh init` wrote.569pub fn dirty(store &storage.Store, head ?history.Save) !bool {570	files := snapshot.walk(store, store.root, snapshot.load(store.root))!571	if saved := head {572		return !snapshot.same_tree(history.files_of(store, saved.id)!, files)573	}574	seed := storage.hash_hex(snapshot.default_ignore.bytes())575	return files.any(it.path != snapshot.ignore_file || it.hash != seed)576}577578// fetch_repo takes a whole repo — head, saves, objects and events — for579// `koh steal <name>`, which lands a copy in a new folder.580pub fn fetch_repo(mut backend remote.Backend, name string) !Fetched {581	check_format(mut backend, name)!582	remote_head := backend.get(head_key(name))!583	if !remote_head.found {584		return error('the remote has no repo called "${name}"')585	}586	mut fetched := Fetched{587		head: remote_head.body.bytestr().trim_space()588	}589	if !valid_save_id(fetched.head) {590		return error('the remote head has invalid save ID ${fetched.head}')591	}592	mut bundle := &Bundle{593		fetched: fetched594	}595	if fetch_bundle(mut backend, bundle_key(name), mut bundle)! {596		fetched = bundle.fetched597	} else {598		for kind in ['objects', 'saves', 'events'] {599			for key in backend.list('${name}/${kind}')! {600				body := backend.get(key)!601				if body.found {602					take(mut fetched, key.all_after('${name}/'), body.body)!603				}604			}605		}606	}607	fetched.saves = parent_first(fetched.saves)!608	if !fetched.saves.any(it.id == fetched.head) {609		return error('the remote is missing its head save ${fetched.head}')610	}611	fetched.events_out.sort(a.id < b.id)612	return fetched613}614615// fetch_bundle reads §22.7's bundle, when the remote has one. Over HTTPS it is read as it arrives:616// held whole, a 282 MB bundle cost 2.5 GB, mostly copies the HTTP client makes.617fn fetch_bundle(mut backend remote.Backend, key string, mut bundle Bundle) !bool {618	found := if mut backend is remote.Web {619		backend.stream(key, fn [mut bundle] (piece []u8) ! {620			bundle.feed(piece)!621		})!622	} else {623		whole := backend.get(key)!624		if whole.found {625			bundle.feed(whole.body)!626		}627		whole.found628	}629	if found {630		bundle.finish()!631	}632	return found633}634635// Bundle takes §22.7's bundle — `<key> <length>\n` and then that many bytes, over and over, until636// `end 0` — a piece at a time, into what one GET of each key would have returned. A connection637// that drops between two entries still looks like a whole bundle, so only the end line proves it638// arrived.639struct Bundle {640mut:641	fetched Fetched642	pending []u8 // the start of an entry still arriving643	ended   bool644}645646fn (mut b Bundle) feed(piece []u8) ! {647	b.pending << piece648	mut at := 0649	for at < b.pending.len {650		// Scanned in place: a slice copies on this V, and copying the rest per entry is quadratic.651		mut newline := at652		for newline < b.pending.len && b.pending[newline] != `\n` {653			newline++654		}655		if newline == b.pending.len {656			break657		}658		header := b.pending[at..newline].bytestr()659		if b.ended {660			return error('the bundle goes on after its end')661		}662		if header == 'end 0' {663			b.ended = true664			at = newline + 1665			continue666		}667		length := strconv.atoi(header.all_after(' '))!668		start := newline + 1669		if length < 0 {670			return error('the bundle has a negative length for ${header.all_before(' ')}')671		}672		if length > b.pending.len - start {673			break674		}675		take(mut b.fetched, header.all_before(' '), b.pending[start..start + length])!676		at = start + length677	}678	if at > 0 {679		b.pending = b.pending[at..]680	}681}682683fn (b &Bundle) finish() ! {684	if !b.ended || b.pending.len > 0 {685		return error('the bundle was cut short — try the steal again')686	}687}688689// take files one fetched key, relative to the repo: an object, a save or an event.690fn take(mut fetched Fetched, key string, body []u8) ! {691	id := key.all_after('/')692	match key.all_before('/') {693		'objects' {694			if !storage.valid_hash(id) {695				return error('the remote has invalid object hash ${id}')696			}697			fetched.repo_objects[id] = body698		}699		'saves' {700			mut record := decode_save(body)!701			validate_save(record, id)!702			fetched.unsafe_paths << drop_unsafe_paths(mut record)703			validate_hashes(record.id, record.files)!704			fetched.saves << record705		}706		'events' {707			if !valid_event_id(id) {708				return error('the remote has invalid event ID ${id}')709			}710			event := decode_event(body)!711			if event.id != id {712				return error('remote event record ID ${event.id} disagrees with key ${id}')713			}714			if !ignored_strip(event) {715				fetched.events_out << event716			}717		}718		else {719			return error('the remote sent "${key}", which is not part of a repo')720		}721	}722}723724// parent_first orders saves so every parent lands before its children, as the725// foreign key on `parent` demands. Time cannot do it: a replayed save keeps its726// original, older time but sits on a newer parent.727fn parent_first(records []SaveRecord) ![]SaveRecord {728	mut by_id := map[string]SaveRecord{}729	for record in records {730		by_id[record.id] = record731	}732	mut placed := map[string]bool{}733	mut ordered := []SaveRecord{}734	for record in records {735		mut chain := []SaveRecord{}736		mut cursor := record.id737		for cursor != '' && cursor !in placed {738			if chain.len > records.len {739				return error('the save records on the remote form a loop')740			}741			current := by_id[cursor] or { return error('the remote is missing save ${cursor}') }742			chain << current743			cursor = current.parent744		}745		chain.reverse_in_place()746		for current in chain {747			placed[current.id] = true748			ordered << current749		}750	}751	return ordered752}