folder.v

5.4 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}4849pub fn (mut f Folder) list(prefix string) ![]string {50	dir := os.join_path(f.base, prefix)51	if !os.is_dir(dir) {52		return []string{}53	}54	mut keys := []string{}55	mut walk := [prefix]56	for walk.len > 0 {57		relative := walk.pop()58		for name in os.ls(f.path_of(relative))! {59			child := if relative == '' { name } else { '${relative}/${name}' }60			if os.is_dir(f.path_of(child)) {61				walk << child62			} else if !is_scratch(name) {63				keys << child64			}65		}66	}67	keys.sort()68	return keys69}7071// put_if_absent writes a temp file in the target directory and hard-links it72// into place. `link` fails when the name is taken, so a racing writer loses73// cleanly instead of overwriting. A link error on an absent name means the74// filesystem has no hard links; create_exclusive finishes the job there.75pub fn (mut f Folder) put_if_absent(key string, body []u8) !bool {76	path := f.path_of(key)77	dir := os.dir(path)78	os.mkdir_all(dir, os.MkdirParams{})!79	temporary := '${path}.tmp-${os.getpid()}'80	os.write_file_array(temporary, body)!81	defer {82		if os.exists(temporary) {83			os.rm(temporary) or {}84		}85	}86	os.link(temporary, path) or {87		if os.exists(path) {88			return false89		}90		return create_exclusive(path, body)91	}92	return true93}9495// create_exclusive publishes on filesystems with no hard links (exFAT, FAT,96// many SMB shares), where `link` fails even for an absent name. O_EXCL keeps97// the same guarantee: the kernel creates the name or reports it taken, so two98// racing writers still produce exactly one winner.99fn create_exclusive(path string, body []u8) !bool {100	match unsafe { C.koh_create_exclusive(&char(path.str), body.data, usize(body.len)) } {101		1 { return true }102		0 { return false }103		else { return error('cannot create ${path}') }104	}105}106107// put_if_match compares the current content's tag to the one the caller read108// before writing. A lock file taken with an exclusive create serialises the109// compare-and-swap, so two machines cannot both believe they won.110pub fn (mut f Folder) put_if_match(key string, body []u8, tag string) !bool {111	path := f.path_of(key)112	os.mkdir_all(os.dir(path), os.MkdirParams{})!113	guard := '${path}.lock'114	if !take_lock(guard)! {115		clear_stale_lock(guard)116		if !take_lock(guard)! {117			return false118		}119	}120	defer {121		release_lock(guard)122	}123	if tag != '' {124		current := f.get(key)!125		if !current.found || current.tag != tag {126			return false127		}128	} else if f.get(key)!.found {129		return false130	}131	temporary := '${path}.tmp-${os.getpid()}'132	os.write_file_array(temporary, body)!133	// V's rename, like mv(1), would move the file INTO a directory there.134	if os.is_dir(path) {135		os.rm(temporary) or {}136		return error('${key} is a directory on the remote')137	}138	os.rename(temporary, path)!139	return true140}141142// take_lock claims a lock path by hard-linking a fresh file into place. `link`143// fails when the name exists, so exactly one writer can hold it. Without hard144// links the same claim is an exclusive create.145fn take_lock(path string) !bool {146	pid := '${os.getpid()}'147	fresh := '${path}.${pid}.${time.now().unix_nano()}'148	os.write_file(fresh, pid)!149	defer {150		os.rm(fresh) or {}151	}152	os.link(fresh, path) or {153		if os.exists(path) {154			return false155		}156		return create_exclusive(path, pid.bytes())157	}158	return true159}160161// is_scratch recognises the temp and lock files this backend writes beside a162// key while publishing it. Keys themselves never contain a dot.163fn is_scratch(name string) bool {164	return name.contains('.tmp-') || name.contains('.lock')165}166167fn release_lock(path string) {168	os.rm(path) or {}169}170171// clear_stale_lock removes a lock left behind by a writer that died mid-swap.172// A lock a minute old is not a swap in progress; it is debris, and leaving it173// would block this remote for ever.174fn clear_stale_lock(path string) {175	info := os.stat(path) or { return }176	if time.now().unix() - info.mtime > 60 {177		os.rm(path) or {}178	}179}180181pub fn (mut f Folder) delete(key string) ! {182	path := f.path_of(key)183	if os.exists(path) {184		os.rm(path)!185	}186}187188fn (f &Folder) path_of(key string) string {189	return os.join_path(f.base, key)190}191192// tag_of is the version tag of a folder object: the hash of its bytes. A193// reader can compute it without asking anyone, which is what the lock-free194// compare-and-swap needs.195pub fn tag_of(body []u8) string {196	return blake3.sum256(body).hex()197}