diff --git a/docs/import-ownership-admission.md b/docs/import-ownership-admission.md new file mode 100644 index 00000000..ebbd9d99 --- /dev/null +++ b/docs/import-ownership-admission.md @@ -0,0 +1,59 @@ +# Backup import ownership admission + +Untracked imports reserve native save-path ownership before touching the +restore destination. The reservation remains held through extraction, +authoritative registration, and any returned-error recovery. Recovery does not +roll back files after registration has committed. This is not a durable +filesystem transaction or a guarantee of recovery after process or power loss. + +Ordinary game creation (including peer auto-registration), primary-path updates, +and mapped-root additions/remaps cooperate with the same cross-process claim. +They wait up to 30 seconds, checking every 100 ms, before returning +`ErrPathClaimBusy`. This matches the bounded-wait policy for native topology +admission. The bound covers acquisition, not the subsequent operation. Native +ownership preparation and the SQLite commit are both inside the claim, with +filesystem resolution outside the SQLite transaction. Imports still refuse +immediately when admission is busy. + +Busy is distinct from `ErrGamePathOwned`: contention does not establish an +ownership collision. Interactive registration and path-edit APIs return HTTP +409 for busy admission. Their request contexts cancel the wait before mutation; +legacy Store callers without a request context retain the bounded default. +Real ownership collisions are checked again after acquisition and still fail. + +## Native lock identity + +On Unix, the persistent sidecar is `.path-claim.lock`. +It must not be unlinked on release, or later callers could lock different +inodes. Symlink and relative path spellings resolve to the same sidecar, +independently of HOME or the caller's working directory. The lock implementation +never opens/closes the SQLite file: closing a separate descriptor to that inode +can drop SQLite's process-wide POSIX locks. + +Unix guarded mutations refuse databases with more than one hard link. Adjacent +sidecars cannot coordinate arbitrary hardlink spellings, and SQLite itself does +not safely support independently named journals for those aliases. This replaces +the previous hardlink admission promise with explicit refusal; it does not claim +to make opening SQLite through hardlinks safe. + +Windows retains its database-file-identity named mutex and dedicated pinned +owner thread. Acquisition remains nonblocking at the native layer; ordinary +callers use the common bounded waiter. Abandoned claims fail separately from +ownership collisions and ordinary contention. + +Noncooperating old binaries, external tools, concurrent alias replacement and +symlink swaps remain outside this admission contract. These claims do not +provide daemon lifecycle takeover or cross-process sync topology coordination. + +## Regression coverage + +- 24 simultaneous disjoint registrations across two Store handles all succeed. +- A registration resumes after an import releases its claim. +- Timeout/cancellation leave no new record and do not leak the claim. +- A waiting registration rechecks ownership after the import commits. +- The interactive handler propagates cancellation and resumes after contention. +- A child-process POSIX-lock probe remains blocked after claim release on Linux. +- Cross-process, symlink, different-cwd and different-HOME claims still exclude. +- Unix hardlinked databases fail closed; Windows mutex recursion/release tests + remain native Windows tests. +- Existing primary/named/nested import ownership and recovery regressions remain. diff --git a/internal/api/registration_claim_wait_test.go b/internal/api/registration_claim_wait_test.go new file mode 100644 index 00000000..9822b01d --- /dev/null +++ b/internal/api/registration_claim_wait_test.go @@ -0,0 +1,68 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/opensave/opensave/internal/store" +) + +// Exercise the interactive handler through daemon registration, not just the +// Store waiter: cancellation must not become a delayed successful mutation. +func TestRegistrationClaimHandlerWaitAndCancellation(t *testing.T) { + for _, cancelled := range []bool{false, true} { + name := "drains" + if cancelled { + name = "cancelled" + } + t.Run(name, func(t *testing.T) { + ts := startTestServer(t) + a, err := ts.daemon.Store.BeginImportPath(filepath.Join(t.TempDir(), "import"), "incoming") + if err != nil { + t.Fatal(err) + } + defer a.Release() + body, _ := json.Marshal(map[string]string{"name": "Claim Wait", "savePath": ts.saveDir}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + req := httptest.NewRequest(http.MethodPost, "/api/games", bytes.NewReader(body)).WithContext(ctx) + response := httptest.NewRecorder() + done := make(chan struct{}) + go func() { ts.server.handleTrackGame(response, req); close(done) }() + select { + case <-done: + t.Fatalf("handler refused without waiting: %d %s", response.Code, response.Body) + case <-time.After(60 * time.Millisecond): + } + if cancelled { + cancel() + } else { + a.Release() + } + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("handler did not finish") + } + a.Release() + _, err = ts.daemon.Store.FindGameBySavePath(ts.saveDir) + if cancelled { + if !errors.Is(err, store.ErrNotFound) { + t.Fatalf("cancelled request registered game: %v", err) + } + if response.Code != http.StatusConflict { + t.Fatalf("busy cancellation HTTP %d: %s", response.Code, response.Body) + } + } else if err != nil || response.Code != http.StatusOK { + t.Fatalf("drained request HTTP %d, game error %v: %s", response.Code, err, response.Body) + } + }) + } +} diff --git a/internal/api/routes.go b/internal/api/routes.go index 1d95be2d..e0521d99 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -374,12 +374,12 @@ func (s *Server) handleTrackGame(w http.ResponseWriter, r *http.Request) { return } - game, err := s.Daemon.TrackGame(store.Game{Name: body.Name, SavePath: body.SavePath, AppID: body.AppID, ExePath: body.ExePath}) + game, err := s.Daemon.TrackGameContext(r.Context(), store.Game{Name: body.Name, SavePath: body.SavePath, AppID: body.AppID, ExePath: body.ExePath}) if err != nil { // Duplicates (id or path) are conflicts; anything else the daemon // rejects is bad input. status := http.StatusBadRequest - if errors.Is(err, store.ErrGamePathOwned) || errors.Is(err, store.ErrOwnershipClaimsChanged) || + if errors.Is(err, store.ErrGamePathOwned) || errors.Is(err, store.ErrPathClaimBusy) || errors.Is(err, store.ErrOwnershipClaimsChanged) || strings.Contains(err.Error(), "already track") || strings.Contains(err.Error(), "already exists") { status = http.StatusConflict @@ -489,9 +489,9 @@ func (s *Server) handleUpdateGame(w http.ResponseWriter, r *http.Request) { game.LastManifestHash = s.Daemon.LastSnapshotHashUnder(game, oldIgnore) } - if err := s.Daemon.Store.UpdateGame(game); err != nil { + if err := s.Daemon.Store.UpdateGameContext(r.Context(), game); err != nil { status := notFoundToStatus(err) - if errors.Is(err, store.ErrOwnershipClaimsChanged) || errors.Is(err, store.ErrGamePathOwned) { + if errors.Is(err, store.ErrPathClaimBusy) || errors.Is(err, store.ErrOwnershipClaimsChanged) || errors.Is(err, store.ErrGamePathOwned) { status = http.StatusConflict } writeError(w, status, err.Error()) diff --git a/internal/api/routes_roots.go b/internal/api/routes_roots.go index 13451115..36085e42 100644 --- a/internal/api/routes_roots.go +++ b/internal/api/routes_roots.go @@ -75,9 +75,9 @@ func (s *Server) handleAddGameRoot(w http.ResponseWriter, r *http.Request) { // to hear about rather than a server fault: "that folder is already // covered by the main save" is a sentence, not a 500. oldRoots, _ := s.Daemon.Store.GameRootPaths(gameID) - if err := s.Daemon.Store.AddGameRoot(gameID, body.Name, path); err != nil { + if err := s.Daemon.Store.AddGameRootContext(r.Context(), gameID, body.Name, path); err != nil { status := http.StatusBadRequest - if errors.Is(err, store.ErrOwnershipClaimsChanged) || errors.Is(err, store.ErrGamePathOwned) { + if errors.Is(err, store.ErrPathClaimBusy) || errors.Is(err, store.ErrOwnershipClaimsChanged) || errors.Is(err, store.ErrGamePathOwned) { status = http.StatusConflict } writeError(w, status, err.Error()) diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 2a87f813..ec76a05f 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -802,7 +802,13 @@ func isDuplicateGameID(err error) bool { // TrackGame adds a new game, takes its initial snapshot (when the save // location already has content), and starts watching it. func (d *Daemon) TrackGame(game store.Game) (store.Game, error) { - return d.trackGameAdmitted(game, nil) + return d.TrackGameContext(context.Background(), game) +} + +// TrackGameContext allows an abandoned interactive request to cancel while +// waiting for another process's save-path claim. +func (d *Daemon) TrackGameContext(ctx context.Context, game store.Game) (store.Game, error) { + return d.trackGameAdmitted(ctx, game, nil) } // TrackImportedGame reuses native tracking while retaining the cross-process @@ -811,10 +817,10 @@ func (d *Daemon) TrackImportedGame(game store.Game, admission *store.ImportPathA if admission == nil { return store.Game{}, fmt.Errorf("missing import admission") } - return d.trackGameAdmitted(game, admission) + return d.trackGameAdmitted(context.Background(), game, admission) } -func (d *Daemon) trackGameAdmitted(game store.Game, admission *store.ImportPathAdmission) (store.Game, error) { +func (d *Daemon) trackGameAdmitted(ctx context.Context, game store.Game, admission *store.ImportPathAdmission) (store.Game, error) { abs, err := d.ValidateSavePath(game.SavePath) if err != nil { return store.Game{}, err @@ -894,7 +900,7 @@ func (d *Daemon) trackGameAdmitted(game store.Game, admission *store.ImportPathA if admission != nil { createErr = d.Store.CreateGameAdmitted(game, admission) } else { - createErr = d.Store.CreateGame(game) + createErr = d.Store.CreateGameContext(ctx, game) } if err := createErr; err != nil { // The id was free a moment ago. If it is taken now, a paired device diff --git a/internal/store/db.go b/internal/store/db.go index 71407db6..94b5fcac 100644 --- a/internal/store/db.go +++ b/internal/store/db.go @@ -11,6 +11,7 @@ import ( "runtime" "sort" "strings" + "time" "github.com/jmoiron/sqlx" _ "modernc.org/sqlite" @@ -23,8 +24,9 @@ var migrationsFS embed.FS // methods (see settings.go, games.go, branches.go, snapshots.go, peers.go, // cloudtokens.go). type Store struct { - db *sqlx.DB - path string // the database file, for EnableIncrementalVacuum's space check + db *sqlx.DB + claimWaitFor time.Duration // test-injectable admission bound; defaults to 30s + path string // the database file, for EnableIncrementalVacuum's space check } // Open creates (if needed) and opens the SQLite database at path, applying diff --git a/internal/store/game_roots.go b/internal/store/game_roots.go index 01250370..7b42f8ef 100644 --- a/internal/store/game_roots.go +++ b/internal/store/game_roots.go @@ -1,6 +1,7 @@ package store import ( + "context" "database/sql" "errors" "fmt" @@ -152,7 +153,12 @@ func isAbsoluteAnyOS(p string) bool { // A path that overlaps the game's primary location or another of its // locations is refused; see overlaps. func (s *Store) AddGameRoot(gameID, name, path string) error { - done, err := s.claimLock() + return s.AddGameRootContext(context.Background(), gameID, name, path) +} + +// AddGameRootContext stops waiting for ownership admission when the caller cancels. +func (s *Store) AddGameRootContext(ctx context.Context, gameID, name, path string) error { + done, err := s.claimLockContext(ctx) if err != nil { return err } diff --git a/internal/store/games.go b/internal/store/games.go index 01ddda14..7abfe98f 100644 --- a/internal/store/games.go +++ b/internal/store/games.go @@ -1,6 +1,7 @@ package store import ( + "context" "database/sql" "errors" "fmt" @@ -82,7 +83,12 @@ type Game struct { // CreateGame inserts a new game and its default "main" branch in one // transaction. func (s *Store) CreateGame(g Game) error { - done, err := s.claimLock() + return s.CreateGameContext(context.Background(), g) +} + +// CreateGameContext stops waiting for ownership admission when the caller cancels. +func (s *Store) CreateGameContext(ctx context.Context, g Game) error { + done, err := s.claimLockContext(ctx) if err != nil { return err } @@ -171,7 +177,12 @@ func (s *Store) ListGames() ([]Game, error) { // update — id, save_path are updatable too since the UI allows relocating // a tracked save folder). func (s *Store) UpdateGame(g Game) error { - done, err := s.claimLock() + return s.UpdateGameContext(context.Background(), g) +} + +// UpdateGameContext stops waiting for ownership admission when the caller cancels. +func (s *Store) UpdateGameContext(ctx context.Context, g Game) error { + done, err := s.claimLockContext(ctx) if err != nil { return err } diff --git a/internal/store/import_admission.go b/internal/store/import_admission.go index 837a6ce4..01e62a67 100644 --- a/internal/store/import_admission.go +++ b/internal/store/import_admission.go @@ -1,8 +1,11 @@ package store import ( + "context" + "errors" "fmt" "path/filepath" + "time" ) // ImportPathAdmission owns the native cross-process path claim throughout @@ -14,10 +17,60 @@ type ImportPathAdmission struct { release func() } -// claimLock protects native registrations of primary/named save roots and -// untracked backup extraction. The lock is the database file itself, so a -// different HOME, cwd, or hardlink spelling still contends. +// ErrPathClaimBusy means admission timed out or another import holds the +// claim. It is not evidence that any save location overlaps another game. +var ErrPathClaimBusy = errors.New("save-location changes are busy; try again in a moment") + +const pathClaimWait = 30 * time.Second +const pathClaimPoll = 100 * time.Millisecond + +// Ordinary registrations wait for short-lived work, just as native topology +// edits do. The claim covers preparation AND commit, without holding a SQLite +// transaction while waiting or resolving filesystem paths. func (s *Store) claimLock() (func(), error) { + return s.claimLockContext(context.Background()) +} + +func (s *Store) claimLockContext(parent context.Context) (func(), error) { + limit := s.claimWaitFor + if limit <= 0 { + limit = pathClaimWait + } + ctx, cancel := context.WithTimeout(parent, limit) + defer cancel() + return s.waitClaimLock(ctx) +} + +func (s *Store) waitClaimLock(ctx context.Context) (func(), error) { + for { + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("%w: %w", ErrPathClaimBusy, err) + } + release, err := s.tryClaimLock() + if err == nil { + // Cancellation racing acquisition must not admit a new mutation. + if err := ctx.Err(); err != nil { + release() + return nil, fmt.Errorf("%w: %w", ErrPathClaimBusy, err) + } + return release, nil + } + if !errors.Is(err, ErrPathClaimBusy) { + return nil, err + } + timer := time.NewTimer(pathClaimPoll) + select { + case <-ctx.Done(): + timer.Stop() + return nil, fmt.Errorf("%w: %w", ErrPathClaimBusy, ctx.Err()) + case <-timer.C: + } + } +} + +// Imports retain immediate refusal. Resolving symlinks makes aliases share the +// same sidecar on Unix; HOME and cwd never determine the lock location. +func (s *Store) tryClaimLock() (func(), error) { canonical, err := filepath.Abs(s.path) if err != nil { return nil, err @@ -36,7 +89,7 @@ func (s *Store) claimLock() (func(), error) { // BeginImportPath reserves ownership through every filesystem effect and the // eventual game registration. A read failure always refuses admission. func (s *Store) BeginImportPath(path, incomingGameID string) (*ImportPathAdmission, error) { - release, err := s.claimLock() + release, err := s.tryClaimLock() if err != nil { return nil, err } diff --git a/internal/store/import_admission_test.go b/internal/store/import_admission_test.go index ca5cb2b0..36fa9325 100644 --- a/internal/store/import_admission_test.go +++ b/internal/store/import_admission_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) // Two SQLite handles stand in for independently running native processes. @@ -24,6 +25,7 @@ func TestImportPathAdmissionSerializesIndependentRegistrations(t *testing.T) { t.Fatal(err) } defer b.Close() + b.claimWaitFor = 25 * time.Millisecond owner := filepath.Join(t.TempDir(), "owner") nested := filepath.Join(owner, "config") if err := os.MkdirAll(nested, 0700); err != nil { @@ -35,10 +37,10 @@ func TestImportPathAdmissionSerializesIndependentRegistrations(t *testing.T) { t.Fatal(err) } defer admission.Release() - if err := b.CreateGame(Game{ID: "competing", Name: "Competing", SavePath: owner}); !errors.Is(err, ErrGamePathOwned) { + if err := b.CreateGame(Game{ID: "competing", Name: "Competing", SavePath: owner}); !errors.Is(err, ErrPathClaimBusy) { t.Fatalf("concurrent game registration escaped admission: %v", err) } - if _, err := b.CreateGameUnlessAliased(Game{ID: "autocreate", Name: "Peer", SavePath: owner}); !errors.Is(err, ErrGamePathOwned) { + if _, err := b.CreateGameUnlessAliased(Game{ID: "autocreate", Name: "Peer", SavePath: owner}); !errors.Is(err, ErrPathClaimBusy) { t.Fatalf("concurrent auto-track escaped admission: %v", err) } if err := a.CreateGameAdmitted(Game{ID: "incoming", Name: "Incoming", SavePath: nested}, admission); err != nil { @@ -83,6 +85,7 @@ func TestImportAdmissionRefusesConcurrentRootRelocationAndWrongToken(t *testing. t.Fatal(err) } defer b.Close() + b.claimWaitFor = 25 * time.Millisecond original := filepath.Join(t.TempDir(), "ordinary") target := filepath.Join(t.TempDir(), "target") if err := b.CreateGame(Game{ID: "ordinary", Name: "Ordinary", SavePath: original}); err != nil { @@ -94,7 +97,7 @@ func TestImportAdmissionRefusesConcurrentRootRelocationAndWrongToken(t *testing. } defer admission.Release() - if err := b.AddGameRoot("ordinary", "new", target); !errors.Is(err, ErrGamePathOwned) { + if err := b.AddGameRoot("ordinary", "new", target); !errors.Is(err, ErrPathClaimBusy) { t.Fatalf("concurrent AddRoot was not excluded: %v", err) } game, err := b.GetGame("ordinary") @@ -102,7 +105,7 @@ func TestImportAdmissionRefusesConcurrentRootRelocationAndWrongToken(t *testing. t.Fatal(err) } game.SavePath = target - if err := b.UpdateGame(game); !errors.Is(err, ErrGamePathOwned) { + if err := b.UpdateGame(game); !errors.Is(err, ErrPathClaimBusy) { t.Fatalf("concurrent relocation was not excluded: %v", err) } if err := a.CreateGameAdmitted(Game{ID: "wrong", Name: "Wrong", SavePath: target}, admission); !errors.Is(err, ErrGamePathOwned) { @@ -114,29 +117,25 @@ func TestImportAdmissionRefusesConcurrentRootRelocationAndWrongToken(t *testing. } // Alternate path spelling of the same DB file must contend for the same lock. -func TestImportPathAdmissionSameInodeDifferentPath(t *testing.T) { +func TestImportPathAdmissionSameDatabaseSymlink(t *testing.T) { dir := t.TempDir() db1 := filepath.Join(dir, "native.db") - db2 := filepath.Join(dir, "native-hardlink.db") + db2 := filepath.Join(dir, "native-symlink.db") a, err := Open(db1) if err != nil { t.Fatal(err) } defer a.Close() - // Create a hard link so the two paths share the same inode. - if err := os.Link(db1, db2); err != nil { - t.Skip("hard links not supported on this filesystem") + // A symlink resolves to the canonical database and sidecar. + if err := os.Symlink(db1, db2); err != nil { + t.Skip("symlinks not supported on this filesystem") } b, err := Open(db2) if err != nil { - // SQLite WAL names its journal from the path, so two hardlink spellings - // cannot be opened in one process. The child-process test covers the lock. - if strings.Contains(err.Error(), "disk I/O error") { - t.Skip(err.Error()) - } t.Fatal(err) } defer b.Close() + b.claimWaitFor = 25 * time.Millisecond target := filepath.Join(t.TempDir(), "claimed") if err := os.MkdirAll(target, 0700); err != nil { @@ -147,8 +146,8 @@ func TestImportPathAdmissionSameInodeDifferentPath(t *testing.T) { t.Fatal(err) } defer admission.Release() - if err := b.CreateGame(Game{ID: "other", Name: "Other", SavePath: target}); !errors.Is(err, ErrGamePathOwned) { - t.Fatalf("hard-linked DB path escaped admission: %v", err) + if err := b.CreateGame(Game{ID: "other", Name: "Other", SavePath: target}); !errors.Is(err, ErrPathClaimBusy) { + t.Fatalf("symlink DB path escaped admission: %v", err) } } @@ -163,13 +162,14 @@ func TestImportPathClaimChildProcess(t *testing.T) { t.Fatal(err) } defer s.Close() + s.claimWaitFor = 25 * time.Millisecond err = s.CreateGame(Game{ID: "competing", Name: "Competing", SavePath: filepath.Join(t.TempDir(), "save")}) - if !errors.Is(err, ErrGamePathOwned) { + if !errors.Is(err, ErrPathClaimBusy) { t.Fatalf("cross-process exclusion failed: %v", err) } } -func TestImportPathClaimCrossProcessCWDAndHardlink(t *testing.T) { +func TestImportPathClaimCrossProcessCWDAndSymlink(t *testing.T) { dir := t.TempDir() db := filepath.Join(dir, "native.db") aliasDir := filepath.Join(dir, "alias") @@ -185,16 +185,19 @@ func TestImportPathClaimCrossProcessCWDAndHardlink(t *testing.T) { t.Fatal(err) } defer s.Close() - alias := filepath.Join(aliasDir, "native-hardlink.db") - if err := os.Link(db, alias); err != nil { - t.Skipf("hardlinks unavailable: %v", err) + alias := filepath.Join(aliasDir, "native-symlink.db") + paths := []string{db} + if err := os.Symlink(db, alias); err != nil { + t.Logf("symlink alias unavailable; canonical cross-process case still runs: %v", err) + } else { + paths = append(paths, alias) } admission, err := s.BeginImportPath(filepath.Join(dir, "target"), "incoming") if err != nil { t.Fatal(err) } defer admission.Release() - for _, dbPath := range []string{db, alias} { + for _, dbPath := range paths { cmd := exec.Command(os.Args[0], "-test.run=^TestImportPathClaimChildProcess$", "-test.v") cmd.Dir = childDir cmd.Env = append(os.Environ(), "OPENSAVE_IMPORT_CLAIM_CHILD=1", "OPENSAVE_IMPORT_CLAIM_DB="+dbPath) @@ -214,8 +217,9 @@ func TestImportPathClaimChildDifferentHome(t *testing.T) { t.Fatal(err) } defer s.Close() + s.claimWaitFor = 25 * time.Millisecond err = s.CreateGame(Game{ID: "competing", Name: "Competing", SavePath: filepath.Join(t.TempDir(), "save")}) - if !errors.Is(err, ErrGamePathOwned) { + if !errors.Is(err, ErrPathClaimBusy) { t.Fatalf("cross-home exclusion failed: %v", err) } } diff --git a/internal/store/import_claim_identity_unix.go b/internal/store/import_claim_identity_unix.go index cbc3e80b..1b195245 100644 --- a/internal/store/import_claim_identity_unix.go +++ b/internal/store/import_claim_identity_unix.go @@ -23,15 +23,27 @@ func nativeDBFileIdentity(path string) (string, error) { return fmt.Sprintf("unix:%d:%d", st.Dev, st.Ino), nil } -// flock on the database inode is independent of SQLite's fcntl range locks, -// and every hardlink of that file contends for the same flock. +// Never open/close the SQLite inode for our lock: closing ANY descriptor for +// that inode can discard SQLite's POSIX locks in this process. Keep the sidecar +// in place after release so concurrent callers always lock the same inode. func claimNativeDB(path string) (func(), error) { - release, ok, err := fsx.TryLock(path) + info, err := os.Stat(path) + if err != nil { + return nil, err + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return nil, fmt.Errorf("unsupported DB file identity on this platform") + } + if st.Nlink != 1 { + return nil, fmt.Errorf("hard-linked SQLite databases are unsupported; use one canonical database path") + } + release, ok, err := fsx.TryLock(path + ".path-claim.lock") if err != nil { return nil, err } if !ok { - return nil, fmt.Errorf("%w: another import or registration is active", ErrGamePathOwned) + return nil, ErrPathClaimBusy } return release, nil } diff --git a/internal/store/import_claim_identity_windows.go b/internal/store/import_claim_identity_windows.go index 16ac67a5..e1272d19 100644 --- a/internal/store/import_claim_identity_windows.go +++ b/internal/store/import_claim_identity_windows.go @@ -34,7 +34,7 @@ func nativeDBFileIdentity(path string) (string, error) { // // A dedicated pinned goroutine owns acquisition and ReleaseMutex. Callers can // release from any goroutine and return only after the native lock is released. -// This is nonblocking: concurrent admissions receive ErrGamePathOwned. +// This is nonblocking: concurrent admissions receive ErrPathClaimBusy. func claimNativeDB(path string) (func(), error) { identity, err := nativeDBFileIdentity(path) if err != nil { @@ -77,10 +77,10 @@ func claimNativeDB(path string) (func(), error) { // previous owner died while possibly mutating an import. Refuse // to treat that state as an ordinary safe admission. _ = windows.ReleaseMutex(handle) - ready <- fmt.Errorf("%w: previous import claim was abandoned", ErrGamePathOwned) + ready <- fmt.Errorf("previous import claim was abandoned; inspect import recovery before retrying") return default: - ready <- fmt.Errorf("%w: another import or registration is active", ErrGamePathOwned) + ready <- ErrPathClaimBusy return } diff --git a/internal/store/import_claim_identity_windows_test.go b/internal/store/import_claim_identity_windows_test.go index 89bd93ea..368d7873 100644 --- a/internal/store/import_claim_identity_windows_test.go +++ b/internal/store/import_claim_identity_windows_test.go @@ -29,11 +29,11 @@ func TestWindowsImportClaimNeverRecursivelyAdmitsAnotherCaller(t *testing.T) { } // In particular, the ordinary same-goroutine caller cannot silently // inherit a recursively owned Windows mutex. - if done, err := s.claimLock(); err == nil { + if done, err := s.tryClaimLock(); err == nil { done() claim.Release() t.Fatalf("round %d: competing same-goroutine claim was admitted", round) - } else if !errors.Is(err, ErrGamePathOwned) { + } else if !errors.Is(err, ErrPathClaimBusy) { claim.Release() t.Fatalf("round %d: wrong error from denied claim: %v", round, err) } @@ -45,7 +45,7 @@ func TestWindowsImportClaimNeverRecursivelyAdmitsAnotherCaller(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - done, err := s.claimLock() + done, err := s.tryClaimLock() if err == nil { done() errs <- fmt.Errorf("competing goroutine acquired an active import claim") @@ -57,7 +57,7 @@ func TestWindowsImportClaimNeverRecursivelyAdmitsAnotherCaller(t *testing.T) { wg.Wait() close(errs) for err := range errs { - if !errors.Is(err, ErrGamePathOwned) { + if !errors.Is(err, ErrPathClaimBusy) { claim.Release() t.Fatalf("round %d: competing claim was not refused: %v", round, err) } @@ -75,7 +75,7 @@ func TestWindowsImportClaimNeverRecursivelyAdmitsAnotherCaller(t *testing.T) { case <-time.After(5 * time.Second): t.Fatalf("round %d: release deadlocked across OS threads", round) } - done, err := s.claimLock() + done, err := s.tryClaimLock() if err != nil { t.Fatalf("round %d: mutex remained locked after release: %v", round, err) } diff --git a/internal/store/import_claim_posix_test.go b/internal/store/import_claim_posix_test.go new file mode 100644 index 00000000..42829d07 --- /dev/null +++ b/internal/store/import_claim_posix_test.go @@ -0,0 +1,85 @@ +//go:build linux + +package store + +import ( + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" +) + +// A disposable POSIX lock models SQLite's database-file lock. A child process +// probes it without opening a second SQLite connection or touching live data. +func TestClaimReleasePreservesPOSIXLock(t *testing.T) { + path := filepath.Join(t.TempDir(), "synthetic.db") + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + t.Fatal(err) + } + defer f.Close() + lock := syscall.Flock_t{Type: syscall.F_WRLCK, Whence: 0, Start: 0, Len: 1} + if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &lock); err != nil { + t.Fatal(err) + } + probe := func() string { + cmd := exec.Command(os.Args[0], "-test.run=^TestClaimPOSIXProbe$") + cmd.Env = append(os.Environ(), "OPENSAVE_POSIX_PROBE="+path) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("probe: %v %s", err, out) + } + return string(out) + } + if got := probe(); got != "blocked\n" { + t.Fatalf("initial POSIX lock not held: %q", got) + } + release, err := claimNativeDB(path) + if err != nil { + t.Fatal(err) + } + release() + if got := probe(); got != "blocked\n" { + t.Fatalf("claim release dropped pre-existing POSIX lock: child %q", got) + } +} + +func TestClaimPOSIXProbe(t *testing.T) { + path := os.Getenv("OPENSAVE_POSIX_PROBE") + if path == "" { + return + } + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + os.Exit(2) + } + lock := syscall.Flock_t{Type: syscall.F_WRLCK, Whence: 0, Start: 0, Len: 1} + err = syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &lock) + if err == syscall.EAGAIN || err == syscall.EACCES { + os.Stdout.WriteString("blocked\n") + os.Exit(0) + } + if err != nil { + os.Exit(2) + } + os.Stdout.WriteString("acquired\n") + os.Exit(0) +} + +func TestClaimRefusesHardLinkedDatabase(t *testing.T) { + path := filepath.Join(t.TempDir(), "synthetic.db") + if err := os.WriteFile(path, nil, 0600); err != nil { + t.Fatal(err) + } + if err := os.Link(path, path+".alias"); err != nil { + t.Skip(err) + } + for _, p := range []string{path, path + ".alias"} { + release, err := claimNativeDB(p) + if err == nil { + release() + t.Fatal("hard-linked database admitted with independent sidecar") + } + } +} diff --git a/internal/store/import_claim_wait_test.go b/internal/store/import_claim_wait_test.go new file mode 100644 index 00000000..94d4209c --- /dev/null +++ b/internal/store/import_claim_wait_test.go @@ -0,0 +1,173 @@ +package store + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "testing" + "time" +) + +func TestConcurrentDisjointRegistrations(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "native.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + other, err := Open(s.path) + if err != nil { + t.Fatal(err) + } + defer other.Close() + stores := []*Store{s, other} + root := t.TempDir() + start := make(chan struct{}) + results := make(chan error, 24) + for i := 0; i < 24; i++ { + go func(i int) { + <-start + results <- stores[i%len(stores)].CreateGame(Game{ID: fmt.Sprintf("game-%d", i), Name: fmt.Sprintf("Game %d", i), SavePath: filepath.Join(root, fmt.Sprintf("save-%d", i))}) + }(i) + } + close(start) + failures := 0 + for i := 0; i < 24; i++ { + if err := <-results; err != nil { + failures++ + t.Log(err) + } + } + if failures != 0 { + t.Fatalf("%d/24 disjoint registrations failed", failures) + } +} + +func TestRegistrationWaitsForImportClaim(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "native.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + a, err := s.BeginImportPath(filepath.Join(t.TempDir(), "import"), "incoming") + if err != nil { + t.Fatal(err) + } + defer a.Release() + result := make(chan error, 1) + root := filepath.Join(t.TempDir(), "unrelated") + go func() { result <- s.CreateGame(Game{ID: "unrelated", Name: "Unrelated", SavePath: root}) }() + select { + case err := <-result: + t.Fatalf("registration returned before claim release: %v", err) + case <-time.After(150 * time.Millisecond): + } + a.Release() + select { + case err := <-result: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("registration did not resume") + } +} + +func TestRegistrationClaimTimeoutIsBusyWithoutMutation(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "native.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.claimWaitFor = 40 * time.Millisecond + target := filepath.Join(t.TempDir(), "target") + a, err := s.BeginImportPath(target, "incoming") + if err != nil { + t.Fatal(err) + } + defer a.Release() + start := time.Now() + err = s.CreateGame(Game{ID: "waiting", Name: "Waiting", SavePath: target}) + if !errors.Is(err, ErrPathClaimBusy) || !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, ErrGamePathOwned) { + t.Fatalf("wrong timeout classification: %v", err) + } + if time.Since(start) < s.claimWaitFor { + t.Fatal("refused before bounded wait elapsed") + } + if _, err := s.GetGame("waiting"); !errors.Is(err, ErrNotFound) { + t.Fatalf("timed out registration mutated state: %v", err) + } + a.Release() + if err := s.CreateGame(Game{ID: "waiting", Name: "Waiting", SavePath: target}); err != nil { + t.Fatalf("claim leaked after timeout: %v", err) + } +} + +func TestClaimWaitCancellationDoesNotAcquireOrLeak(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "native.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + a, err := s.BeginImportPath(filepath.Join(t.TempDir(), "target"), "incoming") + if err != nil { + t.Fatal(err) + } + defer a.Release() + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { + result <- s.CreateGameContext(ctx, Game{ID: "cancelled", Name: "Cancelled", SavePath: filepath.Join(t.TempDir(), "cancelled")}) + }() + cancel() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) || !errors.Is(err, ErrPathClaimBusy) { + t.Fatalf("wrong cancellation: %v", err) + } + case <-time.After(time.Second): + t.Fatal("cancelled admission did not return") + } + a.Release() + if _, err := s.GetGame("cancelled"); !errors.Is(err, ErrNotFound) { + t.Fatalf("cancelled registration mutated state: %v", err) + } + release, err := s.tryClaimLock() + if err != nil { + t.Fatal(err) + } + release() +} + +func TestRegistrationRechecksOwnershipAfterWaiting(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "native.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + target := filepath.Join(t.TempDir(), "target") + a, err := s.BeginImportPath(target, "incoming") + if err != nil { + t.Fatal(err) + } + defer a.Release() + result := make(chan error, 1) + go func() { result <- s.CreateGame(Game{ID: "other", Name: "Other", SavePath: target}) }() + select { + case err := <-result: + t.Fatalf("returned before release: %v", err) + case <-time.After(150 * time.Millisecond): + } + if err := s.CreateGameAdmitted(Game{ID: "incoming", Name: "Incoming", SavePath: target}, a); err != nil { + t.Fatal(err) + } + a.Release() + select { + case err := <-result: + if !errors.Is(err, ErrGamePathOwned) || errors.Is(err, ErrPathClaimBusy) { + t.Fatalf("ownership not rechecked: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("registration never resumed") + } +}