folder.v

6.7 KB · raw

1//! The folder backend: a remote that is just a directory.2//!3//! Every sync test in the project runs against this backend, because it needs4//! no network and no account. It is also a real backend in its own right — a5//! sync folder on an external disk or a NAS is a perfectly good remote.6//!7// Publish is a hard link, which fails when the name already exists: no partial8// file and no overwrite is ever visible to a reader. Where the filesystem has9// no hard links (exFAT, FAT, many SMB shares) an exclusive create stands in.1011module remote1213import crypto.blake314import time15import os1617#flag -I@VMODROOT/vendor/shim18#flag @VMODROOT/vendor/shim/koh_create.c19#flag @VMODROOT/vendor/shim/koh_process.c20#include "koh_create.h"21#include "koh_process.h"2223fn C.koh_create_exclusive(path &char, data voidptr, len usize) int24fn C.koh_pid_alive(pid int) int2526pub struct Folder {27pub:28	base string29}3031// new_folder points a backend at a directory, creating it when missing.32pub fn new_folder(base string) !Folder {33	os.mkdir_all(base, os.MkdirParams{})!34	return Folder{35		base: base36	}37}3839pub fn (mut f Folder) get(key string) !Object {40	path := f.path_of(key)41	if !os.is_file(path) {42		return Object{}43	}44	body := os.read_bytes(path)!45	return Object{46		found: true47		body:  body48		tag:   tag_of(body)49	}50}5152// list_dirs names the immediate folders under `prefix`, one level down, in one53// read: `koh steal --list` needs the repo folders, not every key under them.54pub fn (mut f Folder) list_dirs(prefix string) ![]string {55	dir := f.path_of(prefix)56	if !os.is_dir(dir) {57		return []string{}58	}59	mut names := []string{}60	for name in os.ls(dir)! {61		if os.is_dir(os.join_path(dir, name)) && !is_scratch(name) {62			names << name63		}64	}65	names.sort()66	return names67}6869pub fn (mut f Folder) list(prefix string) ![]string {70	dir := os.join_path(f.base, prefix)71	if !os.is_dir(dir) {72		return []string{}73	}74	mut keys := []string{}75	mut walk := [prefix]76	for walk.len > 0 {77		relative := walk.pop()78		for name in os.ls(f.path_of(relative))! {79			child := if relative == '' { name } else { '${relative}/${name}' }80			if os.is_dir(f.path_of(child)) {81				walk << child82			} else if !is_scratch(name) {83				keys << child84			}85		}86	}87	keys.sort()88	return keys89}9091// put_if_absent writes a temp file in the target directory and hard-links it92// into place. `link` fails when the name is taken, so a racing writer loses93// cleanly instead of overwriting. A link error on an absent name means the94// filesystem has no hard links; create_exclusive finishes the job there.95pub fn (mut f Folder) put_if_absent(key string, body []u8) !bool {96	path := f.path_of(key)97	dir := os.dir(path)98	os.mkdir_all(dir, os.MkdirParams{})!99	temporary := '${path}.tmp-${os.getpid()}'100	os.write_file_array(temporary, body)!101	defer {102		if os.exists(temporary) {103			os.rm(temporary) or {}104		}105	}106	os.link(temporary, path) or {107		if os.exists(path) {108			return false109		}110		return create_exclusive(path, body)111	}112	return true113}114115// create_exclusive publishes on filesystems with no hard links (exFAT, FAT,116// many SMB shares), where `link` fails even for an absent name. O_EXCL keeps117// the same guarantee: the kernel creates the name or reports it taken, so two118// racing writers still produce exactly one winner.119fn create_exclusive(path string, body []u8) !bool {120	match unsafe { C.koh_create_exclusive(&char(path.str), body.data, usize(body.len)) } {121		1 { return true }122		0 { return false }123		else { return error('cannot create ${path}') }124	}125}126127// put_if_match compares the current content's tag to the one the caller read128// before writing. A lock file taken with an exclusive create serialises the129// compare-and-swap, so two machines cannot both believe they won.130pub fn (mut f Folder) put_if_match(key string, body []u8, tag string) !bool {131	path := f.path_of(key)132	os.mkdir_all(os.dir(path), os.MkdirParams{})!133	guard := '${path}.lock'134	if !take_lock(guard)! {135		clear_stale_lock(guard)136		if !take_lock(guard)! {137			return false138		}139	}140	defer {141		release_lock(guard)142	}143	if tag != '' {144		current := f.get(key)!145		if !current.found || current.tag != tag {146			return false147		}148	} else if f.get(key)!.found {149		return false150	}151	temporary := '${path}.tmp-${os.getpid()}'152	os.write_file_array(temporary, body)!153	// V's rename, like mv(1), would move the file INTO a directory there.154	if os.is_dir(path) {155		os.rm(temporary) or {}156		return error('${key} is a directory on the remote')157	}158	os.rename(temporary, path)!159	return true160}161162// take_lock claims a lock path by hard-linking a fresh file into place. `link`163// fails when the name exists, so exactly one writer can hold it. Without hard164// links the same claim is an exclusive create.165fn take_lock(path string) !bool {166	pid := '${os.getpid()}'167	fresh := '${path}.${pid}.${time.now().unix_nano()}'168	// The host goes with the pid: on a shared folder the lock may be another machine's.169	owner := '${os.hostname() or { '' }} ${pid}'170	os.write_file(fresh, owner)!171	defer {172		os.rm(fresh) or {}173	}174	os.link(fresh, path) or {175		if os.exists(path) {176			return false177		}178		return create_exclusive(path, owner.bytes())179	}180	return true181}182183// is_scratch recognises the temp and lock files this backend writes beside a184// key while publishing it. Keys themselves never contain a dot.185fn is_scratch(name string) bool {186	return name.contains('.tmp-') || name.contains('.lock')187}188189fn release_lock(path string) {190	os.rm(path) or {}191}192193// clear_stale_lock removes a lock left behind by a writer that died mid-swap.194// A lock a minute old is not a swap in progress; it is debris, and leaving it195// would block this remote for ever. The pid inside it is checked first: deleting196// a lock whose writer is still alive would let a second writer in. Only a lock197// this machine wrote names a pid worth asking about; for any other, age decides.198fn clear_stale_lock(path string) {199	info := os.stat(path) or { return }200	if time.now().unix() - info.mtime <= 60 {201		return202	}203	body := os.read_file(path) or { return }204	host := body.trim_space().all_before_last(' ')205	pid := body.trim_space().all_after_last(' ').int()206	if host != '' && host == (os.hostname() or { '' }) && pid > 0 && C.koh_pid_alive(pid) != 0 {207		return208	}209	// The file may have been replaced between the two reads; only the exact210	// stale lock that was examined is removed.211	again := os.stat(path) or { return }212	if again.mtime != info.mtime {213		return214	}215	os.rm(path) or {}216}217218pub fn (mut f Folder) delete(key string) ! {219	path := f.path_of(key)220	if os.exists(path) {221		os.rm(path)!222	}223}224225fn (f &Folder) path_of(key string) string {226	return os.join_path(f.base, key)227}228229// tag_of is the version tag of a folder object: the hash of its bytes. A230// reader can compute it without asking anyone, which is what the lock-free231// compare-and-swap needs.232pub fn tag_of(body []u8) string {233	return blake3.sum256(body).hex()234}