Files
magpie/internal/filememo/filememo.go
T
yetone 206dc085be provider: a magpie run from a terminal that only lists accounts no longer writes logins.json, and every change to it is made under a lock the gateway holds too, so a token the gateway just refreshed is never written back over (#1674, FaintGhost)
Every CLI command that reached Logins() (magpie ls, providers, sessions,
usage) ran rememberLogins, whose 30-second throttle (loginsSeenAt) lives
in the process, so in a new process it never held: each run moved Seen on
for the signed-in Codex and Claude accounts and wrote logins.json back.
loginsMu was an in-process mutex, so that read-modify-write could
interleave with the gateway's renewSavedLogin: the CLI reads, the gateway
writes a refreshed sign-in, the CLI writes what it read. Codex/OpenAI
refresh tokens are single use, so the account would be signed out.

- rememberLogins writes nothing when the only change is Seen and the saved
  Seen is less than seenEvery (10 minutes) old (onlySeenMoved, comparing
  with what was read, IDs and order normalised as writeLogins writes them;
  sortLogins is split out of writeLogins for that).
- internal/filelock (new): davsync's TryLock/Unlock (flock; LockFileEx on
  Windows) moved here and davsync uses it; Lock(path, wait) and
  filelock.Mutex, a sync.Mutex that also holds the OS lock on a lock file.
  A lock another magpie holds is waited for up to filelock.Wait (10s),
  then gone on without, as before, so a stuck magpie never hangs others.
- loginsMu is a filelock.Mutex on logins.json.lock, so all 107 existing
  Lock sites (every writeLogins is under one) are cross-process with no
  change at the call sites. Taking it calls filememo.Look (new), so the
  read under it isn't a parse filememo.Hold kept from before another
  magpie's write. savedTokenMu holds logins.json.renew.lock the same way:
  two magpies never refresh one saved account at once.
- Siblings: caller-keys.json (access.mu: magpie keys from the CLI vs the
  window; a lost revoke would bring a key back) and mcp-signins.json
  (mcpauth.fileMu, plus mcp-signins.json.renew.lock around renew, since
  library's MCP check renews from the CLI too) get the same lock.
  plugin-auth.json already has one (plugin-auth.json.lock, shared with
  host.js). Not covered: providers.json (33 store sites with no
  in-process lock either; user-entered keys, nothing refreshed there),
  migrations.json/settings.json (no credentials), and the agents' own
  files (~/.codex/auth.json etc.: the agent itself writes them without
  any lock of ours, so a magpie-only lock can't make them safe).

Tests:
- TestReadOnlyRunLeavesLogins: Codex and Claude signed in, Seen a minute
  old, file time set back; three "new processes" of Logins("")/codex/
  claude/All() leave logins.json's bytes and mtime as they were. Seen an
  hour old is written; Codex's own refresh is written at once.
- TestLoginsKeepAnotherMagpiesWrite: between this process's read and write
  (beforeLoginsWrite hook) a second test process (TestLoginsOtherMagpie,
  os.Args[0] -test.run) renews the saved work@ account's refresh token;
  both the renewed token and this process's change are in the file.
- TestLoginsReadAfreshUnderLock: with filememo.Hold held, a write
  filememo never heard of is seen by a read under loginsMu.
- TestLockAcrossProcesses (filelock): a holder subprocess makes Lock wait
  and give up after its wait; killed, the lock is free; a Mutex holds it.

Broken by hand: onlySeenMoved bypassed -> TestReadOnlyRunLeavesLogins
FAIL "a run that only listed the accounts wrote logins.json"; the file
lock taken out of filelock.Mutex.Lock -> TestLoginsKeepAnotherMagpiesWrite
FAIL "the other magpie's renewed sign-in was written over"; Locked hook
emptied -> TestLoginsReadAfreshUnderLock FAIL. Each restored, green.

Ran: gofmt -l (nothing); go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags
nogui, GOOS=windows go build; go test -tags nogui -count=1 ./... under a
temp HOME with pinned caches: all ok but internal/provider, whose
TestReadOnlyRunLeavesLogins failed at that point from its own fixture
(two rewrites of one size given the same mtime read as unchanged by
filememo); fixed in the test, then internal/provider, access, mcpauth,
filememo, filelock and davsync -count=1 all ok, and the three new provider
tests -race -count=10 ok.

Not tried: the reporter's Linux arm64 box with a real systemd gateway and
real Codex accounts; Windows (LockFileEx path) only vetted and built, not
run on the Windows box.
2026-10-12 05:20:26 +08:00

173 lines
4.5 KiB
Go

// Package filememo keeps what was parsed from a file until the file
// changes, so a page that asks many times over reads it once.
package filememo
import (
"bytes"
"errors"
"io/fs"
"os"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/steady"
)
type entry struct {
mod time.Time
size int64
v any
// the bytes parsed, while the file's time is too recent to tell a
// second write by: Linux stamps a file from a clock a tick (a few
// milliseconds) coarse, so two writes of one size inside a tick (two
// accounts swapped) leave the same time and size
raw []byte
// when the file was last found unchanged, while a request held them
// (Hold), and in which of Forget's generations
checked time.Time
gen uint64
}
// settled is how old a file's time must be for any later write to stamp
// a later one, many ticks of the coarsest clock.
const settled = 2 * time.Second
var (
mu sync.Mutex
seen = map[string]entry{}
// holds is how many requests hold what was read (Hold); gen is moved
// on by every write magpie makes (Forget)
holds int
gen uint64
// gone is the files found not there last time looked at, not waited
// on again (steady.Stat): one there before and not now may be being
// replaced (Windows), and is
gone = map[string]bool{}
)
// heldFor is how long a file found unchanged is taken as unchanged, while
// a request holds what was read, before it is looked at again.
const heldFor = time.Second
// Hold has a file found unchanged not looked at again, for a request that
// only reads, until release is called or a second has gone by: the GUI's
// state looked at each agent's files hundreds of times over, a few
// thousand looks at the disk that a slow one (a Mac's antivirus looking
// at each) made seconds. A write meanwhile (Forget) has them looked at.
func Hold() (release func()) {
mu.Lock()
holds++
mu.Unlock()
return sync.OnceFunc(func() {
mu.Lock()
holds--
mu.Unlock()
})
}
// Forget has every file looked at again on its next read: magpie wrote
// one.
func Forget() {
mu.Lock()
gen++
mu.Unlock()
}
// Look has the file at path looked at on its next read, even while a
// request holds what was read (Hold): another magpie may have written it,
// which Forget, moved on by this one's writes alone, can't know of.
func Look(path string) {
mu.Lock()
defer mu.Unlock()
for k, e := range seen {
if strings.HasSuffix(k, "\x00"+path) && !e.checked.IsZero() {
e.checked = time.Time{}
seen[k] = e
}
}
}
// Read is parse of the file at path, from what it gave last time when the
// file has the same size and time as then (and, written just now, the same
// bytes). kind tells apart two parses of
// one file. What it returns is shared: the caller must not change it.
func Read[T any](kind, path string, parse func([]byte) (T, error)) (T, error) {
var zero T
key := kind + "\x00" + path
mu.Lock()
e, ok := seen[key]
if ok && holds > 0 && e.raw == nil && e.gen == gen && time.Since(e.checked) < heldFor {
mu.Unlock()
return e.v.(T), nil
}
g := gen
mu.Unlock()
fi, err := statFile(path)
if err != nil {
return zero, err
}
if ok && e.mod.Equal(fi.ModTime()) && e.size == fi.Size() && e.raw == nil {
mu.Lock()
if holds > 0 && g == gen {
e.checked, e.gen = time.Now(), g
seen[key] = e
}
mu.Unlock()
return e.v.(T), nil
}
b, err := steady.ReadThere(path)
if err != nil {
return zero, err
}
if ok && e.mod.Equal(fi.ModTime()) && bytes.Equal(b, e.raw) {
if time.Since(e.mod) > settled {
mu.Lock()
e.raw = nil
seen[key] = e
mu.Unlock()
}
return e.v.(T), nil
}
v, err := parse(b)
if err != nil {
return zero, err
}
mu.Lock()
e = entry{mod: fi.ModTime(), size: fi.Size(), v: v}
if time.Since(e.mod) <= settled {
e.raw = b
} else if holds > 0 && g == gen {
e.checked, e.gen = time.Now(), g
}
seen[key] = e
mu.Unlock()
return v, nil
}
// statFile is os.Stat of path, waiting out a moment of it not there
// (another process replacing it, on Windows) unless it wasn't there last
// time either: taken for gone, a file of accounts read as no accounts, and
// the next write left them all out (Packing1 on Discord, Windows 11:
// Antigravity's account gone after an update).
func statFile(path string) (os.FileInfo, error) {
mu.Lock()
wasGone := gone[path]
mu.Unlock()
var fi os.FileInfo
var err error
if wasGone {
fi, err = os.Stat(path)
} else {
fi, err = steady.Stat(path)
}
mu.Lock()
if errors.Is(err, fs.ErrNotExist) {
gone[path] = true
} else {
delete(gone, path)
}
mu.Unlock()
return fi, err
}