Files
magpie/internal/steady/steady.go
T
yetone 8173854168 steady: a file whose folder isn't there is said gone without the wait (#1665)
On Windows, Stat and ReadThere wait up to 15 x 1ms on a file not there,
in case it is being renamed over. filememo remembers a file gone after
its first look, but every start pays that first look once per path, and
most agents aren't installed: each agent's part of a catalog sync took
at least ~22ms, 1.3s a round of 116 agents. Windows tells a folder on
the way not there (ERROR_PATH_NOT_FOUND, 3) apart from the file alone
not there (ERROR_FILE_NOT_FOUND, 2); nothing is renamed into a folder
that isn't there, so that one is said gone at once. A file alone not
there is waited on as before.

Measured on xiaomi-gpu (Windows 11), an empty sandbox HOME, magpie web
--gateway for 27s, the second start (files settled), with a build
counting each stat and timing each sync round (instrumentation not
committed):
  before            round 1308ms, 2307 stats
  this + next       round   96ms,  988 stats
Agents not installed now take 0ms each; the slowest left are the two
WSL agents (~25ms, they ask WSL) and reasonix (~23ms).
Probed on the same box: os.Stat of a missing file gives errno 2, of a
file in a missing folder 3 (one and two levels deep).

Run:
- TestStatOfAFileWithNoFolderWaitsNothing (all OSes, Windows faked) and
  TestNoFolderIsPathNotFound (Windows, the real os.Stat): both red with
  the errPathNotFound check taken out by hand ("looked 16 times"), green
  with it, on mote and on xiaomi-gpu.
- xiaomi-gpu: go test ./internal/steady ./internal/edit ./internal/filememo
  ./internal/settings ok.
- mote, at the pushed head with the next commit: gofmt -l internal clean;
  GOOS=linux/windows/darwin go vet of steady, edit, filememo, settings and
  agent clean; go test -count=1 of steady, edit, filememo, settings,
  agent, provider, catalog and library ok. internal/gui is red only on
  TestMainWindowCorners, mote's macOS 27 (#3949, red on main before this).
2026-10-28 13:43:37 +08:00

143 lines
4.2 KiB
Go

// Package steady reads and replaces files that another process may be
// replacing at that moment. On Windows a file being renamed over refuses
// to open, and one held open refuses to be renamed over, both for a
// moment ("Access is denied"): read as none, a file of accounts is no
// accounts, and the next write leaves them out. A file being renamed over
// is also, for a moment (two milliseconds seen), not there at all, to
// another process or thread: Stat and ReadThere wait that out for a file
// that was there. Elsewhere a rename is atomic and these are os.Stat,
// os.ReadFile and os.Rename.
package steady
import (
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"syscall"
"time"
)
// tries and pause bound the wait to half a second: what holds the file is
// another read or rename, done in milliseconds.
const (
tries = 50
pause = 10 * time.Millisecond
)
// goneTries and gonePause bound the wait on a file not there to 15ms or
// so: the moment a rename over it leaves is a couple of milliseconds, and
// a file that is really not there is waited on that long.
const (
goneTries = 15
gonePause = time.Millisecond
)
// errPathNotFound is Windows' ERROR_PATH_NOT_FOUND: a folder on the way to
// the file isn't there (ERROR_FILE_NOT_FOUND, 2, is the file alone).
const errPathNotFound = syscall.Errno(3)
// windows is whether files behave as Windows' do; a test sets it.
var windows = runtime.GOOS == "windows"
// stat and readFile are os.Stat and os.ReadFile; a test stands in for them.
var (
stat = os.Stat
readFile = os.ReadFile
)
func retry(f func() error) error {
err := f()
for i := 0; err != nil && windows && !errors.Is(err, fs.ErrNotExist) && i < tries; i++ {
time.Sleep(pause)
err = f()
}
return err
}
// retryGone is retry, waiting out a moment of the file not there too,
// unless its folder isn't there either: nothing is being renamed into it.
// Most agents aren't installed, and the first look at each of their files
// waited the whole 15ms (#1665: ~22ms an agent each catalog sync, 2.6s a
// round of 116 on Windows).
func retryGone(f func() error) error {
err := retry(f)
for i := 0; err != nil && windows && errors.Is(err, fs.ErrNotExist) && !errors.Is(err, errPathNotFound) && i < goneTries; i++ {
time.Sleep(gonePause)
err = retry(f)
}
return err
}
// Stat is os.Stat of a file that was there: one being replaced is waited
// for, so it isn't taken for gone. A file not there costs the wait, so a
// caller asking again remembers it gone (filememo does).
func Stat(p string) (fs.FileInfo, error) {
var fi fs.FileInfo
err := retryGone(func() (err error) {
fi, err = stat(p)
return err
})
return fi, err
}
// ReadThere is ReadFile of a file just found there (Stat): not there now is
// it being replaced, waited out.
func ReadThere(p string) ([]byte, error) {
var b []byte
err := retryGone(func() (err error) {
b, err = readFile(p)
return err
})
return b, err
}
// ReadFile is os.ReadFile, waiting out a file being replaced.
func ReadFile(p string) ([]byte, error) {
var b []byte
err := retry(func() (err error) {
b, err = readFile(p)
return err
})
return b, err
}
// Rename is os.Rename, waiting out a reader holding newpath open.
func Rename(oldpath, newpath string) error {
return retry(func() error { return os.Rename(oldpath, newpath) })
}
// Sync is (*os.File).Sync; a test stands in for it to make a flush fail.
var Sync = (*os.File).Sync
// WriteFile replaces p with b, mode perm, through a temp file beside it
// that is flushed to the disk before it is renamed over p. A rename reaches
// the disk on its own schedule and the data behind it later: a Windows
// machine that went down between the two left logins.json and
// plugin-auth.json at their full length with every byte zero (#1505). A
// write or flush that fails removes the temp file and leaves p as it was.
func WriteFile(p string, b []byte, perm fs.FileMode) error {
tmp, err := os.CreateTemp(filepath.Dir(p), "."+filepath.Base(p)+".*")
if err != nil {
return err
}
_, err = tmp.Write(b)
if err == nil {
err = tmp.Chmod(perm)
}
if err == nil {
err = Sync(tmp)
}
if cerr := tmp.Close(); err == nil {
err = cerr
}
if err == nil {
err = Rename(tmp.Name(), p)
}
if err != nil {
os.Remove(tmp.Name())
}
return err
}