folder.v

5.8 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#include "koh_create.h"2021fn C.koh_create_exclusive(path &char, data voidptr, len usize) int2223pub struct Folder {24pub:25	base string26}2728// new_folder points a backend at a directory, creating it when missing.29pub fn new_folder(base string) !Folder {30	os.mkdir_all(base, os.MkdirParams{})!31	return Folder{32		base: base33	}34}3536pub fn (mut f Folder) get(key string) !Object {37	path := f.path_of(key)38	if !os.is_file(path) {39		return Object{}40	}41	body := os.read_bytes(path)!42	return Object{43		found: true44		body:  body45		tag:   tag_of(body)46	}47}4849// list_dirs names the immediate folders under `prefix`, one level down, in one50// read: `koh steal --list` needs the repo folders, not every key under them.51pub fn (mut f Folder) list_dirs(prefix string) ![]string {52	dir := f.path_of(prefix)53	if !os.is_dir(dir) {54		return []string{}55	}56	mut names := []string{}57	for name in os.ls(dir)! {58		if os.is_dir(os.join_path(dir, name)) && !is_scratch(name) {59			names << name60		}61	}62	names.sort()63	return names64}6566pub fn (mut f Folder) list(prefix string) ![]string {67	dir := os.join_path(f.base, prefix)68	if !os.is_dir(dir) {69		return []string{}70	}71	mut keys := []string{}72	mut walk := [prefix]73	for walk.len > 0 {74		relative := walk.pop()75		for name in os.ls(f.path_of(relative))! {76			child := if relative == '' { name } else { '${relative}/${name}' }77			if os.is_dir(f.path_of(child)) {78				walk << child79			} else if !is_scratch(name) {80				keys << child81			}82		}83	}84	keys.sort()85	return keys86}8788// put_if_absent writes a temp file in the target directory and hard-links it89// into place. `link` fails when the name is taken, so a racing writer loses90// cleanly instead of overwriting. A link error on an absent name means the91// filesystem has no hard links; create_exclusive finishes the job there.92pub fn (mut f Folder) put_if_absent(key string, body []u8) !bool {93	path := f.path_of(key)94	dir := os.dir(path)95	os.mkdir_all(dir, os.MkdirParams{})!96	temporary := '${path}.tmp-${os.getpid()}'97	os.write_file_array(temporary, body)!98	defer {99		if os.exists(temporary) {100			os.rm(temporary) or {}101		}102	}103	os.link(temporary, path) or {104		if os.exists(path) {105			return false106		}107		return create_exclusive(path, body)108	}109	return true110}111112// create_exclusive publishes on filesystems with no hard links (exFAT, FAT,113// many SMB shares), where `link` fails even for an absent name. O_EXCL keeps114// the same guarantee: the kernel creates the name or reports it taken, so two115// racing writers still produce exactly one winner.116fn create_exclusive(path string, body []u8) !bool {117	match unsafe { C.koh_create_exclusive(&char(path.str), body.data, usize(body.len)) } {118		1 { return true }119		0 { return false }120		else { return error('cannot create ${path}') }121	}122}123124// put_if_match compares the current content's tag to the one the caller read125// before writing. A lock file taken with an exclusive create serialises the126// compare-and-swap, so two machines cannot both believe they won.127pub fn (mut f Folder) put_if_match(key string, body []u8, tag string) !bool {128	path := f.path_of(key)129	os.mkdir_all(os.dir(path), os.MkdirParams{})!130	guard := '${path}.lock'131	if !take_lock(guard)! {132		clear_stale_lock(guard)133		if !take_lock(guard)! {134			return false135		}136	}137	defer {138		release_lock(guard)139	}140	if tag != '' {141		current := f.get(key)!142		if !current.found || current.tag != tag {143			return false144		}145	} else if f.get(key)!.found {146		return false147	}148	temporary := '${path}.tmp-${os.getpid()}'149	os.write_file_array(temporary, body)!150	// V's rename, like mv(1), would move the file INTO a directory there.151	if os.is_dir(path) {152		os.rm(temporary) or {}153		return error('${key} is a directory on the remote')154	}155	os.rename(temporary, path)!156	return true157}158159// take_lock claims a lock path by hard-linking a fresh file into place. `link`160// fails when the name exists, so exactly one writer can hold it. Without hard161// links the same claim is an exclusive create.162fn take_lock(path string) !bool {163	pid := '${os.getpid()}'164	fresh := '${path}.${pid}.${time.now().unix_nano()}'165	os.write_file(fresh, pid)!166	defer {167		os.rm(fresh) or {}168	}169	os.link(fresh, path) or {170		if os.exists(path) {171			return false172		}173		return create_exclusive(path, pid.bytes())174	}175	return true176}177178// is_scratch recognises the temp and lock files this backend writes beside a179// key while publishing it. Keys themselves never contain a dot.180fn is_scratch(name string) bool {181	return name.contains('.tmp-') || name.contains('.lock')182}183184fn release_lock(path string) {185	os.rm(path) or {}186}187188// clear_stale_lock removes a lock left behind by a writer that died mid-swap.189// A lock a minute old is not a swap in progress; it is debris, and leaving it190// would block this remote for ever.191fn clear_stale_lock(path string) {192	info := os.stat(path) or { return }193	if time.now().unix() - info.mtime > 60 {194		os.rm(path) or {}195	}196}197198pub fn (mut f Folder) delete(key string) ! {199	path := f.path_of(key)200	if os.exists(path) {201		os.rm(path)!202	}203}204205fn (f &Folder) path_of(key string) string {206	return os.join_path(f.base, key)207}208209// tag_of is the version tag of a folder object: the hash of its bytes. A210// reader can compute it without asking anyone, which is what the lock-free211// compare-and-swap needs.212pub fn tag_of(body []u8) string {213	return blake3.sum256(body).hex()214}