feat(vfs/localfs): local vfs.FS with renameat2 NOREPLACE and lazy birth time (2A.1)

ReadDir has lstat semantics and resolves symlink targets (NavigableDir for
links to directories, Target=nil + LinkErr for broken links: U-P1-2 at the
data level). Birth time is only computed through BirthTimer. NoReplace falls
back to link+unlink, then to an Lstat check, when renameat2 is unsupported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 23:22:49 +03:00
parent 2db51e9385
commit c3de5a06ef
7 changed files with 458 additions and 0 deletions

View file

@ -0,0 +1,26 @@
//go:build linux
package localfs
import (
"context"
"time"
"golang.org/x/sys/unix"
)
// statx is a hook so tests can verify ReadDir never asks for birth times.
var statx = unix.Statx
// BirthTime returns the creation time of p (without following a final
// symlink) when the kernel and file system report it.
func (*FS) BirthTime(_ context.Context, p string) (time.Time, bool) {
var st unix.Statx_t
if err := statx(unix.AT_FDCWD, p, unix.AT_SYMLINK_NOFOLLOW, unix.STATX_BTIME, &st); err != nil {
return time.Time{}, false
}
if st.Mask&unix.STATX_BTIME == 0 {
return time.Time{}, false
}
return time.Unix(st.Btime.Sec, int64(st.Btime.Nsec)), true
}

View file

@ -0,0 +1,11 @@
//go:build !linux
package localfs
import (
"context"
"time"
)
// BirthTime is not available on this platform.
func (*FS) BirthTime(context.Context, string) (time.Time, bool) { return time.Time{}, false }

View file

@ -0,0 +1,216 @@
// Package localfs implements vfs.FS on the local disk (design §2.3).
package localfs
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"syscall"
"time"
"vcom/internal/vfs"
)
// FS is the local file system. The zero value is not usable; call New.
type FS struct {
trash trashConfig
}
var (
_ vfs.FS = (*FS)(nil)
_ vfs.BirthTimer = (*FS)(nil)
)
// New returns the local FS.
func New() *FS { return &FS{trash: defaultTrashConfig()} }
func (*FS) Kind() vfs.Kind { return vfs.KindLocal }
func (*FS) Volume() vfs.VolumeID { return "local" }
func (*FS) Label() string { return "local" }
func (*FS) Paths() vfs.PathOps { return vfs.NativePaths }
func (*FS) String() string { return "local" }
func (*FS) Caps() vfs.Caps {
return vfs.Caps{
AtomicReplace: true,
NoReplace: true,
Symlinks: true,
Chmod: true,
Chtimes: true,
Fsync: true,
Exec: true,
}
}
// mapErr adds the vfs sentinels that the os errors do not already match:
// EROFS → ErrReadOnly. fs.ErrNotExist/ErrExist/ErrPermission and
// errors.ErrUnsupported match *os.PathError natively.
func mapErr(err error) error {
if err == nil {
return nil
}
if errors.Is(err, syscall.EROFS) {
return fmt.Errorf("%w: %w", vfs.ErrReadOnly, err)
}
return err
}
func toInfo(name string, fi os.FileInfo) vfs.FileInfo {
return vfs.FileInfo{Name: name, Size: fi.Size(), Mode: fi.Mode(), ModTime: fi.ModTime()}
}
// withTarget fills Target/LinkErr for a symlink entry at p.
func withTarget(p string, info vfs.FileInfo) vfs.FileInfo {
if !info.IsSymlink() {
return info
}
t, err := os.Stat(p)
if err != nil {
info.LinkErr = mapErr(err)
return info
}
ti := toInfo(info.Name, t)
info.Target = &ti
return info
}
func (*FS) Stat(_ context.Context, p string) (vfs.FileInfo, error) {
fi, err := os.Stat(p)
if err != nil {
return vfs.FileInfo{}, mapErr(err)
}
return toInfo(filepath.Base(p), fi), nil
}
func (*FS) Lstat(_ context.Context, p string) (vfs.FileInfo, error) {
fi, err := os.Lstat(p)
if err != nil {
return vfs.FileInfo{}, mapErr(err)
}
return withTarget(p, toInfo(filepath.Base(p), fi)), nil
}
// ReadDir lists p with lstat semantics and resolves symlink targets. It does
// not compute birth times (see BirthTime). Entries that vanish between the
// listing and their lstat are skipped.
func (*FS) ReadDir(ctx context.Context, p string) ([]vfs.FileInfo, error) {
ents, err := os.ReadDir(p)
if err != nil {
return nil, mapErr(err)
}
out := make([]vfs.FileInfo, 0, len(ents))
for i, e := range ents {
if i&1023 == 1023 {
if err := ctx.Err(); err != nil {
return nil, err
}
}
fi, err := e.Info()
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
continue
}
return nil, mapErr(err)
}
out = append(out, withTarget(filepath.Join(p, e.Name()), toInfo(e.Name(), fi)))
}
return out, nil
}
func (*FS) ReadLink(_ context.Context, p string) (string, error) {
s, err := os.Readlink(p)
return s, mapErr(err)
}
func (*FS) RealPath(_ context.Context, p string) (string, error) {
abs, err := filepath.Abs(p)
if err != nil {
return "", err
}
r, err := filepath.EvalSymlinks(abs)
return r, mapErr(err)
}
// file adapts *os.File to vfs.File.
type file struct{ *os.File }
func (f file) Stat() (vfs.FileInfo, error) {
fi, err := f.File.Stat()
if err != nil {
return vfs.FileInfo{}, mapErr(err)
}
return toInfo(filepath.Base(f.Name()), fi), nil
}
// Open opens p for reading. It does not refuse FIFOs or devices: callers that
// read content (preview, transfer) check IsRegularLike first (U-P1-10).
func (*FS) Open(_ context.Context, p string) (vfs.File, error) {
f, err := os.Open(p)
if err != nil {
return nil, mapErr(err)
}
return file{f}, nil
}
func (*FS) Create(_ context.Context, p string, perm fs.FileMode, mode vfs.CreateMode) (vfs.File, error) {
flag := os.O_RDWR | os.O_CREATE
switch mode {
case vfs.CreateExcl:
flag |= os.O_EXCL
case vfs.CreateTrunc:
flag |= os.O_TRUNC
default:
return nil, fmt.Errorf("create %s: unknown mode %d", p, mode)
}
f, err := os.OpenFile(p, flag, perm)
if err != nil {
return nil, mapErr(err)
}
return file{f}, nil
}
func (*FS) Mkdir(_ context.Context, p string, perm fs.FileMode) error {
return mapErr(os.Mkdir(p, perm))
}
// Remove unlinks a file or symlink, or removes an empty directory. A link is
// removed itself, never its target.
func (*FS) Remove(_ context.Context, p string) error {
return mapErr(os.Remove(p))
}
func (*FS) Rename(_ context.Context, from, to string, mode vfs.RenameMode) error {
switch mode {
case vfs.Replace:
return mapErr(os.Rename(from, to))
case vfs.NoReplace:
return mapErr(renameNoReplace(from, to))
}
return fmt.Errorf("rename %s: unknown mode %d", from, mode)
}
func (*FS) Symlink(_ context.Context, target, p string) error {
return mapErr(os.Symlink(target, p))
}
func (*FS) Chmod(_ context.Context, p string, mode fs.FileMode) error {
return mapErr(os.Chmod(p, mode))
}
func (*FS) Chtimes(_ context.Context, p string, atime, mtime time.Time) error {
return mapErr(os.Chtimes(p, atime, mtime))
}
// renameByCheck is the non-atomic NoReplace fallback: Lstat the target, then
// rename. A file created at `to` between the two calls is replaced (narrow
// TOCTOU window, accepted where the kernel offers nothing better).
func renameByCheck(from, to string) error {
if _, err := os.Lstat(to); err == nil {
return &os.LinkError{Op: "rename", Old: from, New: to, Err: fs.ErrExist}
} else if !errors.Is(err, fs.ErrNotExist) {
return err
}
return os.Rename(from, to)
}

View file

@ -0,0 +1,157 @@
package localfs
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"golang.org/x/sys/unix"
"vcom/internal/testutil/fstree"
"vcom/internal/vfs"
)
var ctx = context.Background()
func TestRenameNoReplaceExisting(t *testing.T) {
dir := t.TempDir()
fstree.Build(t, dir, fstree.Spec{
fstree.File("src", "new"),
fstree.File("dst", "old"),
fstree.Dir("d1"),
fstree.Dir("d2"),
})
fsys := New()
err := fsys.Rename(ctx, filepath.Join(dir, "src"), filepath.Join(dir, "dst"), vfs.NoReplace)
if !errors.Is(err, vfs.ErrExist) {
t.Fatalf("rename onto existing file: %v, want ErrExist", err)
}
if b, _ := os.ReadFile(filepath.Join(dir, "dst")); string(b) != "old" {
t.Fatalf("target changed: %q", b)
}
if _, err := os.Stat(filepath.Join(dir, "src")); err != nil {
t.Fatalf("source gone: %v", err)
}
// An empty directory is an existing target too (plain rename(2) would replace it).
if err := fsys.Rename(ctx, filepath.Join(dir, "d1"), filepath.Join(dir, "d2"), vfs.NoReplace); !errors.Is(err, vfs.ErrExist) {
t.Fatalf("rename dir onto empty dir: %v, want ErrExist", err)
}
// The fallbacks keep the same contract.
if err := renameByCheck(filepath.Join(dir, "src"), filepath.Join(dir, "dst")); !errors.Is(err, vfs.ErrExist) {
t.Fatalf("renameByCheck: %v", err)
}
// Free target: moves.
if err := fsys.Rename(ctx, filepath.Join(dir, "src"), filepath.Join(dir, "free"), vfs.NoReplace); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(filepath.Join(dir, "free")); string(b) != "new" {
t.Fatalf("moved content %q", b)
}
// Replace mode replaces.
if err := fsys.Rename(ctx, filepath.Join(dir, "free"), filepath.Join(dir, "dst"), vfs.Replace); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(filepath.Join(dir, "dst")); string(b) != "new" {
t.Fatalf("replace content %q", b)
}
}
func TestReadDirSymlinkTarget(t *testing.T) {
dir := t.TempDir()
fstree.Build(t, dir, fstree.Spec{
fstree.Dir("real"),
fstree.File("real/f", "x"),
fstree.File("plain", "abc"),
fstree.Symlink("todir", "real"),
fstree.Symlink("tofile", "plain"),
fstree.Symlink("broken", "missing"),
})
ents, err := New().ReadDir(ctx, dir)
if err != nil {
t.Fatal(err)
}
byName := map[string]vfs.FileInfo{}
for _, e := range ents {
byName[e.Name] = e
}
if len(byName) != 5 {
t.Fatalf("entries: %v", ents)
}
td := byName["todir"]
if !td.IsSymlink() || td.IsDir() || !td.NavigableDir() || td.Target == nil || !td.Target.IsDir() {
t.Fatalf("todir = %+v", td)
}
tf := byName["tofile"]
if tf.NavigableDir() || !tf.IsRegularLike() || tf.Target.Size != 3 {
t.Fatalf("tofile = %+v", tf)
}
br := byName["broken"]
if !br.IsSymlink() || br.Target != nil || br.LinkErr == nil || br.NavigableDir() {
t.Fatalf("broken = %+v", br)
}
if !errors.Is(br.LinkErr, vfs.ErrNotExist) {
t.Fatalf("broken LinkErr = %v", br.LinkErr)
}
if !byName["real"].IsDir() || byName["plain"].Size != 3 {
t.Fatalf("plain entries wrong: %+v", byName)
}
// Lstat agrees with ReadDir.
li, err := New().Lstat(ctx, filepath.Join(dir, "todir"))
if err != nil || !li.NavigableDir() || li.IsDir() {
t.Fatalf("Lstat todir = %+v, %v", li, err)
}
}
func TestReadDirNoBirthByDefault(t *testing.T) {
dir := t.TempDir()
fstree.Build(t, dir, fstree.Spec{fstree.File("a", ""), fstree.File("b", ""), fstree.Dir("c")})
calls := 0
orig := statx
statx = func(dirfd int, path string, flags, mask int, st *unix.Statx_t) error {
calls++
return orig(dirfd, path, flags, mask, st)
}
t.Cleanup(func() { statx = orig })
fsys := New()
if _, err := fsys.ReadDir(ctx, dir); err != nil {
t.Fatal(err)
}
if calls != 0 {
t.Fatalf("ReadDir made %d statx calls, want 0", calls)
}
if _, ok := fsys.BirthTime(ctx, filepath.Join(dir, "a")); calls != 1 {
t.Fatalf("BirthTime made %d statx calls (ok=%v), want 1", calls, ok)
}
}
func TestCreateExclAndErrors(t *testing.T) {
dir := t.TempDir()
fsys := New()
p := filepath.Join(dir, "f")
f, err := fsys.Create(ctx, p, 0o600, vfs.CreateExcl)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write([]byte("hello")); err != nil {
t.Fatal(err)
}
if err := f.Sync(); err != nil {
t.Fatal(err)
}
if fi, err := f.Stat(); err != nil || fi.Size != 5 || fi.Name != "f" {
t.Fatalf("stat = %+v, %v", fi, err)
}
f.Close()
if _, err := fsys.Create(ctx, p, 0o600, vfs.CreateExcl); !errors.Is(err, vfs.ErrExist) {
t.Fatalf("excl on existing: %v", err)
}
if _, err := fsys.Stat(ctx, filepath.Join(dir, "nope")); !errors.Is(err, vfs.ErrNotExist) {
t.Fatalf("stat missing: %v", err)
}
if err := mapErr(&os.PathError{Op: "open", Path: "x", Err: unix.EROFS}); !errors.Is(err, vfs.ErrReadOnly) || !errors.Is(err, unix.EROFS) {
t.Fatalf("EROFS mapping: %v", err)
}
}

View file

@ -0,0 +1,36 @@
//go:build linux
package localfs
import (
"errors"
"os"
"golang.org/x/sys/unix"
)
// renameNoReplace uses renameat2(RENAME_NOREPLACE). If the file system does
// not support it (EINVAL/ENOSYS), files fall back to link+unlink (also
// atomic against an existing target) and directories to renameByCheck.
func renameNoReplace(from, to string) error {
err := unix.Renameat2(unix.AT_FDCWD, from, unix.AT_FDCWD, to, unix.RENAME_NOREPLACE)
if err == nil {
return nil
}
if !errors.Is(err, unix.EINVAL) && !errors.Is(err, unix.ENOSYS) {
return &os.LinkError{Op: "rename", Old: from, New: to, Err: err}
}
fi, lerr := os.Lstat(from)
if lerr != nil {
return lerr
}
if !fi.IsDir() {
if err := os.Link(from, to); err == nil {
return os.Remove(from)
} else if errors.Is(err, os.ErrExist) {
return err
}
// No hard links on this FS (vfat, some FUSE): fall through.
}
return renameByCheck(from, to)
}

View file

@ -0,0 +1,6 @@
//go:build !linux
package localfs
// renameNoReplace has no atomic primitive here; see renameByCheck.
func renameNoReplace(from, to string) error { return renameByCheck(from, to) }

View file

@ -0,0 +1,6 @@
package localfs
// trashConfig is filled in by the trash implementation (2A.4).
type trashConfig struct{}
func defaultTrashConfig() trashConfig { return trashConfig{} }