Skip to content
14 changes: 12 additions & 2 deletions internal/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,8 +482,18 @@ 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 {
writeError(w, notFoundToStatus(err), err.Error())
var updateErr error
if game.SavePath != oldSavePath {
updateErr = s.Daemon.Store.UpdateGamePathIf(game, oldSavePath)
} else {
updateErr = s.Daemon.Store.UpdateGame(game)
}
if updateErr != nil {
if errors.Is(updateErr, store.ErrGamePathChanged) {
writeError(w, http.StatusConflict, updateErr.Error())
} else {
writeError(w, notFoundToStatus(updateErr), updateErr.Error())
}
return
}
if game.Name != oldName {
Expand Down
10 changes: 9 additions & 1 deletion internal/cliapp/commands_games.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func cmdGame(d *daemon.Daemon, args []string) int {
if err != nil {
return fail(asJSON, unknownGameError(d, gameID, err))
}
originalPath := game.SavePath

switch key {
case "name":
Expand Down Expand Up @@ -78,7 +79,14 @@ func cmdGame(d *daemon.Daemon, args []string) int {
return fail(asJSON, fmt.Errorf("unknown setting %q\n\n%s", key, gameUsage))
}

if err := d.Store.UpdateGame(game); err != nil {
if key == "path" {
// This caller supplies the path it read, so concurrent relocation is
// rejected rather than unintentionally overwritten.
err = d.Store.UpdateGamePathIf(game, originalPath)
} else {
err = d.Store.UpdateGame(game)
}
if err != nil {
return fail(asJSON, err)
}
// Re-watch so a path or auto-sync change takes effect immediately rather
Expand Down
2 changes: 1 addition & 1 deletion internal/daemon/missing.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func (d *Daemon) AcceptRelocation(gameID, path string) error {
}
old := game.SavePath
game.SavePath = newPath
if err := d.Store.UpdateGame(game); err != nil {
if err := d.Store.UpdateGamePathIf(game, old); err != nil {
return fmt.Errorf("could not switch %q to %s: %w", game.Name, newPath, err)
}
d.missingMu.Lock()
Expand Down
3 changes: 2 additions & 1 deletion internal/daemon/relocate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,9 @@ func TestRelocateToOtherDrive_AnOfferIsStaleOnceTheFolderIsSetByHand(t *testing.

byHand := t.TempDir()
g, _ := d.Store.GetGame("g")
previousPath := g.SavePath
g.SavePath = byHand
if err := d.Store.UpdateGame(g); err != nil {
if err := d.Store.UpdateGamePathIf(g, previousPath); err != nil {
t.Fatal(err)
}

Expand Down
6 changes: 6 additions & 0 deletions internal/presets/index_nowait_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,15 @@ New Game:
if err := os.Chtimes(yamlPath, downloaded, downloaded); err != nil {
t.Fatal(err)
}
// Force the rebuild to remain in progress for this assertion. On a fast
// runner it can otherwise finish before the nonblocking read returns,
// which is valid production behaviour and makes this test intermittent.
release, builds := slowBuilds(t, sc)
if got := sc.loadManifestIndexNoWait(); len(got) != 0 {
t.Fatalf("got %+v, want nothing until the index is built", got)
}
waitUntil(t, "the background rebuild to start", func() bool { return builds.Load() > 0 })
release()
deadline := time.Now().Add(30 * time.Second)
for {
if _, err := os.Stat(indexPath); err == nil {
Expand Down
3 changes: 2 additions & 1 deletion internal/snapshot/snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,9 @@ func TestSingleFileSaveMode(t *testing.T) {
if err != nil {
t.Fatal(err)
}
previousPath := game.SavePath
game.SavePath = saveFile
if err := env.store.UpdateGame(game); err != nil {
if err := env.store.UpdateGamePathIf(game, previousPath); err != nil {
t.Fatal(err)
}

Expand Down
32 changes: 32 additions & 0 deletions internal/store/game_stale_path_admission_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package store

import (
"errors"
"testing"
)

func TestMetadataCannotResurrectPriorSavePath(t *testing.T) {
s := openTestStore(t)
if err := s.CreateGame(Game{ID: "stale", Name: "Original", SavePath: "/old"}); err != nil { t.Fatal(err) }
stale, err := s.GetGame("stale")
if err != nil { t.Fatal(err) }
moved := stale
moved.SavePath = "/new"
if err := s.UpdateGamePathIf(moved, "/old"); err != nil { t.Fatal(err) }
stale.Name = "Renamed"
if err := s.UpdateGame(stale); !errors.Is(err, ErrGamePathChanged) { t.Fatalf("stale metadata mutation: %v", err) }
actual, err := s.GetGame("stale")
if err != nil { t.Fatal(err) }
if actual.SavePath != "/new" || actual.Name != "Original" { t.Fatalf("stale metadata changed record: %#v", actual) }
}

func TestIntentionalPathMoveNeedsExpectedPreviousPath(t *testing.T) {
s := openTestStore(t)
if err := s.CreateGame(Game{ID: "stale", Name: "Original", SavePath: "/old"}); err != nil { t.Fatal(err) }
g, err := s.GetGame("stale")
if err != nil { t.Fatal(err) }
g.SavePath = "/new"
if err := s.UpdateGame(g); !errors.Is(err, ErrGamePathChanged) { t.Fatalf("unadmitted path change accepted: %v", err) }
if err := s.UpdateGamePathIf(g, "/other"); !errors.Is(err, ErrGamePathChanged) { t.Fatalf("stale expected old accepted: %v", err) }
if err := s.UpdateGamePathIf(g, "/old"); err != nil { t.Fatal(err) }
}
31 changes: 26 additions & 5 deletions internal/store/games.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,27 @@ func (s *Store) ListGames() ([]Game, error) {
return games, nil
}

// UpdateGame overwrites the mutable fields of a game (settings/patch-style
// update — id, save_path are updatable too since the UI allows relocating
// a tracked save folder).
// ErrGamePathChanged means the path at SQL commit differs from the path
// observed by a caller. A stale metadata edit must not restore an old path.
var ErrGamePathChanged = errors.New("game save path changed; refresh and retry")

// UpdateGame changes metadata only while its observed path is still current.
// Intentional relocation must use UpdateGamePathIf after native admission.
func (s *Store) UpdateGame(g Game) error {
return s.updateGameAtPath(g, g.SavePath)
}

// UpdateGamePathIf changes a path only while its expected old value remains
// current. The caller is responsible for native writer/topology admission.
func (s *Store) UpdateGamePathIf(g Game, expectedOldPath string) error {
return s.updateGameAtPath(g, expectedOldPath)
}

func (s *Store) updateGameAtPath(g Game, expectedOldPath string) error {
arg := struct {
Game
ExpectedSavePath string `db:"expected_save_path"`
}{Game: g, ExpectedSavePath: expectedOldPath}
res, err := s.db.NamedExec(`
UPDATE games SET
name = :name,
Expand All @@ -165,11 +182,15 @@ func (s *Store) UpdateGame(g Game) error {
last_manifest_hash = :last_manifest_hash,
sync_ignore = :sync_ignore,
sync_device_settings = :sync_device_settings
WHERE id = :id`, g)
WHERE id = :id AND save_path = :expected_save_path`, arg)
if err != nil {
return fmt.Errorf("update game %s: %w", g.ID, err)
}
return checkRowAffected(res)
n, err := res.RowsAffected()
if err != nil { return err }
if n == 1 { return nil }
if _, err := s.GetGame(g.ID); err != nil { return err }
return ErrGamePathChanged
}

// SetLastManifestHash records the manifest hash captured at auto-snapshot
Expand Down
Loading