records.v

8.5 KB · raw

1//! What a save and an event look like on the remote.2//!3//! Records are JSON so a person can read the bucket, and the layout is the4//! same for every backend:5//!6//   <repo>/format          the remote layout, `koh-remote 1` or `koh-remote 2`7//   <repo>/objects/<hash>   the object's compressed bytes, as in the table8//   <repo>/manifests/<hash> one folder of a version-2 save's tree9//   <repo>/saves/<id>       the save record: a file list, or a root manifest10//   <repo>/events/<id>      one flag, clear or strip event11//   <repo>/head             the ID of the newest save on the line12//13// Only `head` is ever overwritten, and only with a matching version tag.1415module exchange1617import json218import src.events19import src.history20import src.snapshot21import src.storage22import strconv2324// The two layouts this koh reads and writes. A version-2 record names a root25// manifest; a version-1 record carries its flat file list.26pub const format_v1 = 'koh-remote 1'27pub const format_v2 = 'koh-remote 2'2829// One spelling for each key of the layout above (spec §9.2), so no caller builds a path by hand.30pub fn format_key(repo string) string {31	return '${repo}/format'32}3334pub fn object_key(repo string, hash string) string {35	return '${repo}/objects/${hash}'36}3738pub fn manifest_key(repo string, hash string) string {39	return '${repo}/manifests/${hash}'40}4142pub fn save_key(repo string, id string) string {43	return '${repo}/saves/${id}'44}4546pub fn event_key(repo string, id string) string {47	return '${repo}/events/${id}'48}4950pub fn head_key(repo string) string {51	return '${repo}/head'52}5354pub fn bundle_key(repo string) string {55	return '${repo}/bundle'56}5758pub fn events_prefix(repo string) string {59	return '${repo}/events'60}6162pub struct FileRecord {63pub:64	path       string65	hash       string66	executable bool67}6869pub struct SaveRecord {70pub:71	id            string72	parent        string73	message       string74	created_at    i6475	machine       string76	is_checkpoint bool77	size_bytes    i6478	agent         string79	session       string80	restores      string81	replayed_from string82pub mut:83	files []FileRecord84	// A version-2 record's root manifest, omitted from a version-1 record's bytes.85	manifest string @[omitempty]86}8788// record_fields is every field both layouts share, so a record is built once.89fn record_fields(save history.Save) SaveRecord {90	return SaveRecord{91		id:            save.id92		parent:        save.parent93		message:       save.message94		created_at:    save.created_at95		machine:       save.machine96		is_checkpoint: save.is_checkpoint97		size_bytes:    save.size_bytes98		agent:         save.agent99		session:       save.session100		restores:      save.restores101		replayed_from: save.replayed_from102	}103}104105// save_record is the version-1 record: its file list travels with it.106pub fn save_record(store &storage.Store, save history.Save) !SaveRecord {107	mut record := record_fields(save)108	for file in history.files_of(store, save.id)! {109		record.files << FileRecord{110			path:       file.path111			hash:       file.hash112			executable: file.executable113		}114	}115	return record116}117118pub fn encode_save(record SaveRecord) string {119	return json2.encode(record)120}121122// save_record_v2 names the root manifest instead of listing files; `store`123// proves the tree is here first.124pub fn save_record_v2(store &storage.Store, save history.Save) !SaveRecord {125	if save.manifest == '' {126		return error('save ${save.id} has no manifest to name on a ${format_v2} remote')127	}128	store.manifest_body(save.manifest)!129	mut record := record_fields(save)130	record.manifest = save.manifest131	return record132}133134pub fn valid_save_id(id string) bool {135	return id.len in [6, 12]136		&& id.bytes().all((it >= `0` && it <= `9`) || (it >= `a` && it <= `f`))137}138139pub fn valid_event_id(id string) bool {140	return id.len == 12 && valid_save_id(id)141}142143pub fn validate_save(record SaveRecord, expected string) ! {144	if !valid_save_id(expected) {145		return error('the remote has invalid save ID ${expected}')146	}147	if record.id != expected {148		return error('remote save record ID ${record.id} disagrees with key ${expected}')149	}150	if ![record.parent, record.restores, record.replayed_from].all(it == '' || valid_save_id(it)) {151		return error('remote save ${record.id} has an invalid save ID')152	}153	if record.created_at < 0 || record.size_bytes < 0 {154		return error('remote save ${record.id} has invalid metadata')155	}156	if record.manifest != '' && !storage.valid_hash(record.manifest) {157		return error('remote save ${record.id} has an invalid manifest hash ${record.manifest}')158	}159}160161pub fn validate_hashes(id string, files []FileRecord) ! {162	for file in files {163		if !storage.valid_hash(file.hash) {164			return error('remote save ${id} has invalid object hash ${file.hash}')165		}166	}167}168169// decode_save reads a record the remote holds. A lone surrogate escape fails only its path,170// not the whole record (spec §5.5).171pub fn decode_save(body []u8) !SaveRecord {172	return json2.decode[SaveRecord](lone_surrogates_as_bytes(body).bytestr())!173}174175// ignored_strip is a strip whose path breaks §5.5. No save can hold such a path,176// so Koh and Kepr both leave the event out rather than guess what it meant.177fn ignored_strip(event events.Event) bool {178	return event.kind == events.kind_strip && !snapshot.legal_path(event.path)179}180181// lone_surrogates_as_bytes writes a `\\uXXXX` surrogate escape with no partner as its182// three bytes. json2 refuses such an escape outright, which would refuse the whole183// save; as bytes it decodes, and the one path holding it fails legal_path (§5.5).184fn lone_surrogates_as_bytes(body []u8) []u8 {185	mut out := []u8{cap: body.len}186	mut i := 0187	for i < body.len {188		if body[i] != `\\` || i + 1 >= body.len {189			out << body[i]190			i++191			continue192		}193		unit := escaped_surrogate(body, i)194		if unit >= 0xd800 && unit <= 0xdbff && escaped_surrogate(body, i + 6) >= 0xdc00 {195			out << body[i..i + 12]196			i += 12197		} else if unit >= 0 {198			out << [u8(0xe0 | (unit >> 12)), u8(0x80 | ((unit >> 6) & 0x3f)), u8(0x80 | (unit & 0x3f))]199			i += 6200		} else {201			// Any other escape, `\\\\` included, passes through whole.202			out << body[i..i + 2]203			i += 2204		}205	}206	return out207}208209// escaped_surrogate reads a `\\uD800`–`\\uDFFF` escape at `at`, or returns -1.210fn escaped_surrogate(body []u8, at int) int {211	if at + 6 > body.len || body[at] != `\\` || body[at + 1] != `u` {212		return -1213	}214	unit := strconv.parse_int(body[at + 2..at + 6].bytestr(), 16, 32) or { return -1 }215	return if unit >= 0xd800 && unit <= 0xdfff { int(unit) } else { -1 }216}217218// drop_unsafe_paths applies the shared path contract before an arriving record is used.219// Dropping a path drops the record's manifest too: it must be rebuilt from what lands.220pub fn drop_unsafe_paths(mut record SaveRecord) []string {221	mut kept := []FileRecord{}222	mut dropped := []string{}223	for file in record.files {224		if snapshot.legal_path(file.path) {225			kept << file226		} else {227			dropped << snapshot.escape_path(file.path)228		}229	}230	record.files = kept231	if dropped.len > 0 {232		record.manifest = ''233	}234	dropped.sort()235	return dropped236}237238pub fn to_save(record SaveRecord) history.Save {239	return history.Save{240		id:            record.id241		parent:        record.parent242		manifest:      record.manifest243		message:       record.message244		created_at:    record.created_at245		machine:       record.machine246		is_checkpoint: record.is_checkpoint247		size_bytes:    record.size_bytes248		agent:         record.agent249		session:       record.session250		restores:      record.restores251		replayed_from: record.replayed_from252	}253}254255pub fn to_files(record SaveRecord) []snapshot.FileEntry {256	mut files := []snapshot.FileEntry{}257	for file in record.files {258		files << snapshot.FileEntry{259			path:       file.path260			hash:       file.hash261			executable: file.executable262		}263	}264	return files265}266267pub struct EventRecord {268pub:269	id         string270	kind       string271	save_id    string272	path       string273	reason     string274	created_at i64275	machine    string276}277278pub fn event_record(event events.Event) EventRecord {279	return EventRecord{280		id:         event.id281		kind:       event.kind282		save_id:    event.save_id283		path:       event.path284		reason:     event.reason285		created_at: event.created_at286		machine:    event.machine287	}288}289290pub fn encode_event(event events.Event) string {291	return json2.encode(event_record(event))292}293294// decode_event applies the same lone-surrogate rule as decode_save.295pub fn decode_event(body []u8) !events.Event {296	record := json2.decode[EventRecord](lone_surrogates_as_bytes(body).bytestr())!297	return events.Event{298		id:         record.id299		kind:       record.kind300		save_id:    record.save_id301		path:       record.path302		reason:     record.reason303		created_at: record.created_at304		machine:    record.machine305	}306}