steal.v

22.5 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	for mut clash in clashes {412		base := fetched_bytes(store, fetched, clash.base)!413		mine := fetched_bytes(store, fetched, clash.mine)!414		theirs := fetched_bytes(store, fetched, clash.theirs)!415		mine_delta := snapshot.diff_bytes(clash.path, 'modified', base, mine)!416		theirs_delta := snapshot.diff_bytes(clash.path, 'modified', base, theirs)!417		clash.mine_stat = delta_stat(mine_delta, clash.mine.size)418		clash.theirs_stat = delta_stat(theirs_delta, clash.theirs.size)419		clash.mine_patch = mine_delta.patch420		clash.theirs_patch = theirs_delta.patch421		clash.mine_save = last_touch(store, local_only, clash.path)!422		clash.theirs_save = last_touch(store, fetched.saves.map(to_save(it)), clash.path)!423	}424	return clashes425}426427fn delta_stat(delta snapshot.Delta, size i64) string {428	if delta.binary {429		return fmt.human_bytes(size)430	}431	return '+${delta.added} -${delta.removed}'432}433434fn last_touch(store &storage.Store, saves []history.Save, path string) !history.Save {435	for index := saves.len - 1; index >= 0; index-- {436		save := saves[index]437		current := snapshot.index_files(history.files_of(store, save.id)!)[path] or {438			snapshot.FileEntry{}439		}440		parent := if save.parent != '' {441			snapshot.index_files(history.files_of(store, save.parent)!)[path] or {442				snapshot.FileEntry{}443			}444		} else {445			snapshot.FileEntry{}446		}447		if !same(current, parent) {448			return save449		}450	}451	return saves.last()452}453454// combine_preview counts what a combine would do to the paths either side changed since `base`:455// `identical` were changed the same way on both sides, `clashes` need a choice, the rest go in by themselves.456fn combine_preview(store &storage.Store, name string, fetched Fetched, local []history.Save, clashes []Clash, yes bool, all_side string) !StealPreview {457	base := history.files_of(store, fetched.base)!458	mine := history.files_of(store, local.last().id)!459	theirs := history.files_of(store, fetched.head)!460	mine_changed := changed_paths(base, mine)461	theirs_changed := changed_paths(base, theirs)462	mut changed := map[string]bool{}463	for path in mine_changed {464		changed[path] = true465	}466	for path in theirs_changed {467		changed[path] = true468	}469	mut identical := 0470	base_map := snapshot.index_files(base)471	mine_map := snapshot.index_files(mine)472	theirs_map := snapshot.index_files(theirs)473	for path, _ in changed {474		if !same(mine_map[path] or { snapshot.FileEntry{} }, base_map[path] or { snapshot.FileEntry{} })475			&& same(mine_map[path] or { snapshot.FileEntry{} }, theirs_map[path] or { snapshot.FileEntry{} }) {476			identical++477		}478	}479	return StealPreview{480		repo:      name481		base:      history.by_id(store, fetched.base) or { history.Save{} }482		local:     local483		remote:    fetched.saves484		changed:   changed.len485		automatic: changed.len - identical - clashes.len486		identical: identical487		clashes:   clashes488		yes:       yes489		all_side:  all_side490	}491}492493// after_strips is a save's file list once the given strip events are applied,494// by the same rule write_fetched uses.495fn after_strips(files []snapshot.FileEntry, save_id string, strips []events.Event) []snapshot.FileEntry {496	return files.filter(fn [strips, save_id] (file snapshot.FileEntry) bool {497		return !strips.any(reaches(it, save_id) && covers(it.path, file.path))498	})499}500501// fetched_bytes reads one side of a clash: from the fetch when it has just502// arrived, else from the store. An absent side is empty.503fn fetched_bytes(store &storage.Store, fetched Fetched, entry snapshot.FileEntry) ![]u8 {504	if entry.hash == '' {505		return []u8{}506	}507	if blob := fetched.repo_objects[entry.hash] {508		return storage.inflate_bounded(blob, storage.max_file_size)!509	}510	return store.get_object(entry.hash)!511}512513fn choose_sides(clashes []Clash, opts StealOptions) !map[string]Side {514	mut sides := map[string]Side{}515	if clashes.len == 0 {516		return sides517	}518	for clash in clashes {519		if opts.mine {520			sides[clash.path] = .mine521			continue522		}523		if opts.theirs {524			sides[clash.path] = .theirs525			continue526		}527		return ClashError{528			paths: clashes.map(it.path)529		}530	}531	return sides532}533534fn same(a snapshot.FileEntry, b snapshot.FileEntry) bool {535	if a.hash == '' && b.hash == '' {536		return true537	}538	return a.hash == b.hash && a.executable == b.executable539}540541fn changed_since(store &storage.Store, before ?history.Save, strips_before int) !bool {542	if events.strip_events(store)!.len != strips_before {543		return true544	}545	now := history.head(store)546	if now or { history.Save{} }.id != before or { history.Save{} }.id {547		return true548	}549	return dirty(store, now)!550}551552// dirty reports whether the working tree holds anything a steal would553// overwrite. With no saves yet, that is every file but the untouched ignore554// list `koh init` wrote.555pub fn dirty(store &storage.Store, head ?history.Save) !bool {556	files := snapshot.walk(store, store.root, snapshot.load(store.root))!557	if saved := head {558		return !snapshot.same_tree(history.files_of(store, saved.id)!, files)559	}560	seed := storage.hash_hex(snapshot.default_ignore.bytes())561	return files.any(it.path != snapshot.ignore_file || it.hash != seed)562}563564// fetch_repo takes a whole repo — head, saves, objects and events — for565// `koh steal <name>`, which lands a copy in a new folder.566pub fn fetch_repo(mut backend remote.Backend, name string) !Fetched {567	check_format(mut backend, name)!568	remote_head := backend.get(head_key(name))!569	if !remote_head.found {570		return error('the remote has no repo called "${name}"')571	}572	mut fetched := Fetched{573		head: remote_head.body.bytestr().trim_space()574	}575	if !valid_save_id(fetched.head) {576		return error('the remote head has invalid save ID ${fetched.head}')577	}578	mut bundle := &Bundle{579		fetched: fetched580	}581	if fetch_bundle(mut backend, bundle_key(name), mut bundle)! {582		fetched = bundle.fetched583	} else {584		for kind in ['objects', 'saves', 'events'] {585			for key in backend.list('${name}/${kind}')! {586				body := backend.get(key)!587				if body.found {588					take(mut fetched, key.all_after('${name}/'), body.body)!589				}590			}591		}592	}593	fetched.saves = parent_first(fetched.saves)!594	if !fetched.saves.any(it.id == fetched.head) {595		return error('the remote is missing its head save ${fetched.head}')596	}597	fetched.events_out.sort(a.id < b.id)598	return fetched599}600601// fetch_bundle reads §22.7's bundle, when the remote has one. Over HTTPS it is read as it arrives:602// held whole, a 282 MB bundle cost 2.5 GB, mostly copies the HTTP client makes.603fn fetch_bundle(mut backend remote.Backend, key string, mut bundle Bundle) !bool {604	found := if mut backend is remote.Web {605		backend.stream(key, fn [mut bundle] (piece []u8) ! {606			bundle.feed(piece)!607		})!608	} else {609		whole := backend.get(key)!610		if whole.found {611			bundle.feed(whole.body)!612		}613		whole.found614	}615	if found {616		bundle.finish()!617	}618	return found619}620621// Bundle takes §22.7's bundle — `<key> <length>\n` and then that many bytes, over and over, until622// `end 0` — a piece at a time, into what one GET of each key would have returned. A connection623// that drops between two entries still looks like a whole bundle, so only the end line proves it624// arrived.625struct Bundle {626mut:627	fetched Fetched628	pending []u8 // the start of an entry still arriving629	ended   bool630}631632fn (mut b Bundle) feed(piece []u8) ! {633	b.pending << piece634	mut at := 0635	for at < b.pending.len {636		// Scanned in place: a slice copies on this V, and copying the rest per entry is quadratic.637		mut newline := at638		for newline < b.pending.len && b.pending[newline] != `\n` {639			newline++640		}641		if newline == b.pending.len {642			break643		}644		header := b.pending[at..newline].bytestr()645		if b.ended {646			return error('the bundle goes on after its end')647		}648		if header == 'end 0' {649			b.ended = true650			at = newline + 1651			continue652		}653		length := strconv.atoi(header.all_after(' '))!654		start := newline + 1655		if length < 0 {656			return error('the bundle has a negative length for ${header.all_before(' ')}')657		}658		if length > b.pending.len - start {659			break660		}661		take(mut b.fetched, header.all_before(' '), b.pending[start..start + length])!662		at = start + length663	}664	if at > 0 {665		b.pending = b.pending[at..]666	}667}668669fn (b &Bundle) finish() ! {670	if !b.ended || b.pending.len > 0 {671		return error('the bundle was cut short — try the steal again')672	}673}674675// take files one fetched key, relative to the repo: an object, a save or an event.676fn take(mut fetched Fetched, key string, body []u8) ! {677	id := key.all_after('/')678	match key.all_before('/') {679		'objects' {680			if !storage.valid_hash(id) {681				return error('the remote has invalid object hash ${id}')682			}683			fetched.repo_objects[id] = body684		}685		'saves' {686			mut record := decode_save(body)!687			validate_save(record, id)!688			fetched.unsafe_paths << drop_unsafe_paths(mut record)689			validate_hashes(record.id, record.files)!690			fetched.saves << record691		}692		'events' {693			if !valid_event_id(id) {694				return error('the remote has invalid event ID ${id}')695			}696			event := decode_event(body)!697			if event.id != id {698				return error('remote event record ID ${event.id} disagrees with key ${id}')699			}700			if !ignored_strip(event) {701				fetched.events_out << event702			}703		}704		else {705			return error('the remote sent "${key}", which is not part of a repo')706		}707	}708}709710// parent_first orders saves so every parent lands before its children, as the711// foreign key on `parent` demands. Time cannot do it: a replayed save keeps its712// original, older time but sits on a newer parent.713fn parent_first(records []SaveRecord) ![]SaveRecord {714	mut by_id := map[string]SaveRecord{}715	for record in records {716		by_id[record.id] = record717	}718	mut placed := map[string]bool{}719	mut ordered := []SaveRecord{}720	for record in records {721		mut chain := []SaveRecord{}722		mut cursor := record.id723		for cursor != '' && cursor !in placed {724			if chain.len > records.len {725				return error('the save records on the remote form a loop')726			}727			current := by_id[cursor] or { return error('the remote is missing save ${cursor}') }728			chain << current729			cursor = current.parent730		}731		chain.reverse_in_place()732		for current in chain {733			placed[current.id] = true734			ordered << current735		}736	}737	return ordered738}