Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
2a7d7ce
test(native): reject root mutation while native writer is active
Seagulls Oct 30, 2026
5274dfa
fix(native): coordinate root topology changes with admitted writers
Seagulls Oct 30, 2026
5cd0a18
fix(native): coordinate root topology changes with admitted writers
Seagulls Oct 30, 2026
089ad2f
fix(native): coordinate root topology changes with admitted writers
Seagulls Oct 30, 2026
a2b92ca
test(native): verify lifetime of daemon presence lock
Seagulls Oct 30, 2026
62acfd2
fix(cli): require daemon presence admission for offline root edits
Seagulls Oct 30, 2026
ec8ff81
fix(cli): require daemon presence admission for offline root edits
Seagulls Oct 30, 2026
0dfeb69
fix(cli): require daemon presence admission for offline root edits
Seagulls Oct 30, 2026
d9d2a16
fix(native): retain root topology reservation across sync admission a…
Seagulls Oct 30, 2026
b1bb0dd
fix(native): retain root topology reservation across sync admission a…
Seagulls Oct 30, 2026
fcdbb29
fix(native): retain root topology reservation across sync admission a…
Seagulls Oct 30, 2026
cf132ba
fix(native): retain root topology reservation across sync admission a…
Seagulls Oct 30, 2026
ab36a00
test(sync): cover queued writers and root topology rejection
Seagulls Oct 30, 2026
bded266
test(e2e): retry transient native topology 409 after initial sync drains
Seagulls Oct 30, 2026
1b65e76
fix(native): bounded context-aware wait around existing topology rese…
Seagulls Oct 31, 2026
b77c2e8
fix(api): wait up to 30 seconds before refusing busy root edits
Seagulls Oct 31, 2026
10dd814
fix(api): bound primary-path admission and fail closed on combined pa…
Seagulls Oct 31, 2026
424e9d7
fix(api): remove daemon presence lock incompatible with desktop startup
Seagulls Oct 31, 2026
7610084
fix(cli): extract cross-process daemon/CLI admission to separate life…
Seagulls Oct 31, 2026
bf261db
test(api): move daemon presence ownership proof out of PR139
Seagulls Oct 31, 2026
cec3a36
refactor(cli): restore baseline commands; move daemon ownership to se…
Seagulls Oct 31, 2026
02624f5
refactor(cli): restore baseline commands; move daemon ownership to se…
Seagulls Oct 31, 2026
6a4ade8
test(api): permit short per-server topology admission deadline
Seagulls Oct 31, 2026
525db76
test(api): make bounded wait deterministic with per-server test timeout
Seagulls Oct 31, 2026
ca995ab
test(api): bound active-writer 409 checks without 30-second test hangs
Seagulls Oct 31, 2026
66b7efa
test(api): one root request waits for native writer and preserves bytes
Seagulls Oct 31, 2026
eea37f7
test(e2e): rely on one server-side bounded wait, not repeated client …
Seagulls Oct 31, 2026
985ef27
fix(native): avoid blocking timer drain on cancelled admission
Seagulls Oct 31, 2026
8159c99
fix(native): reconcile topology admission with merged upstream and fo…
Nov 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions internal/api/root_topology_admission_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package api

import (
"net/http"
"os"
"path/filepath"
"testing"
"time"
)

// Root API mutations must observe native admission for the duration of the
// Store write, not merely sample an active-writer count.
func TestRootTopologyRefusesActiveNativeWriter(t *testing.T) {
ts := startTestServer(t)
ts.server.topologyWaitFor = 25 * time.Millisecond
id := trackProbeGame(t, ts)
dir := filepath.Join(t.TempDir(), "config")
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
resp, body := ts.do(t, http.MethodPost, "/api/games/"+id+"/roots",
map[string]string{"name": "config", "path": dir})
if resp.StatusCode != http.StatusOK {
t.Fatalf("cannot establish mapped root: HTTP %d %v", resp.StatusCode, body)
}

releaseWriter := ts.daemon.P2P.Sync.Writing(id)
resp, _ = ts.do(t, http.MethodDelete, "/api/games/"+id+"/roots/config", nil)
if resp.StatusCode != http.StatusConflict {
t.Errorf("RemoveRoot during native write: got HTTP %d, want 409", resp.StatusCode)
}
other := filepath.Join(t.TempDir(), "other")
if err := os.MkdirAll(other, 0700); err != nil {
t.Fatal(err)
}
resp, _ = ts.do(t, http.MethodPost, "/api/games/"+id+"/roots",
map[string]string{"name": "config", "path": other})
if resp.StatusCode != http.StatusConflict {
t.Errorf("AddRoot remap during native write: got HTTP %d, want 409", resp.StatusCode)
}
roots, err := ts.daemon.Store.GameRootPaths(id)
if err != nil || roots["config"] != dir {
t.Fatalf("mapping changed during writer: roots=%v err=%v", roots, err)
}
releaseWriter()

resp, body = ts.do(t, http.MethodDelete, "/api/games/"+id+"/roots/config", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("safe removal after writer drained: HTTP %d %v", resp.StatusCode, body)
}
roots, err = ts.daemon.Store.GameRootPaths(id)
if err != nil || roots["config"] != "" {
t.Fatalf("root still mapped after successful removal: %v err=%v", roots, err)
}
}
57 changes: 57 additions & 0 deletions internal/api/root_topology_wait_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package api

import (
"net/http"
"os"
"path/filepath"
"testing"
"time"
)

// One actual request waits for the in-flight writer and then succeeds.
// This does not rely on an E2E helper repeatedly retrying a refused request.
func TestRootTopologySingleRequestWaitsForWriterAndPreservesFiles(t *testing.T) {
ts := startTestServer(t)
ts.server.topologyWaitFor = time.Second
id := trackProbeGame(t, ts)
dir := filepath.Join(t.TempDir(), "config")
if err := os.Mkdir(dir, 0700); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "slot.sav")
if err := os.WriteFile(path, []byte("ORIGINAL"), 0600); err != nil {
t.Fatal(err)
}
resp, body := ts.do(t, http.MethodPost, "/api/games/"+id+"/roots", map[string]string{"name": "config", "path": dir})
if resp.StatusCode != http.StatusOK {
t.Fatalf("setup failed HTTP %d: %v", resp.StatusCode, body)
}
writer := ts.daemon.P2P.Sync.Writing(id)
result := make(chan int, 1)
go func() {
response, _ := ts.do(t, http.MethodDelete, "/api/games/"+id+"/roots/config", nil)
result <- response.StatusCode
}()
select {
case status := <-result:
t.Fatalf("mutated while writer active: HTTP %d", status)
case <-time.After(60 * time.Millisecond):
}
roots, err := ts.daemon.Store.GameRootPaths(id)
if err != nil || roots["config"] != dir {
t.Fatalf("mapping moved during writer: %v %v", roots, err)
}
writer()
select {
case status := <-result:
if status != http.StatusOK {
t.Fatalf("after drain HTTP %d", status)
}
case <-time.After(3 * time.Second):
t.Fatal("single API request never resumed")
}
bytes, err := os.ReadFile(path)
if err != nil || string(bytes) != "ORIGINAL" {
t.Fatalf("physical save modified: %s %v", bytes, err)
}
}
14 changes: 14 additions & 0 deletions internal/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,13 @@ func (s *Server) handleUpdateGame(w http.ResponseWriter, r *http.Request) {
}
game.SavePath = abs
}
// A combined path+exclusion change would rebase agreement from a new
// path before admission. Refuse rather than claim old lineage for new
// save bytes; a safe combined transition needs a separate explicit design.
if game.SavePath != oldSavePath && s.Daemon.IgnoreText(game) != oldIgnore {
writeError(w, http.StatusConflict, "Change save location and sync exclusions separately.")
return
}
// Cover art: a user-set custom URL is always kept. An empty cover, or
// a previously auto-generated Steam cover, is (re)derived from the
// AppID — so changing the AppID refreshes the art.
Expand Down Expand Up @@ -489,6 +496,13 @@ func (s *Server) handleUpdateGame(w http.ResponseWriter, r *http.Request) {
game.LastManifestHash = s.Daemon.LastSnapshotHashUnder(game, oldIgnore)
}

if game.SavePath != oldSavePath {
done, ok := s.acquireRootTopology(w, r, gameID)
if !ok {
return
}
defer done()
}
if err := s.Daemon.Store.UpdateGame(game); err != nil {
status := notFoundToStatus(err)
if errors.Is(err, store.ErrOwnershipClaimsChanged) || errors.Is(err, store.ErrGamePathOwned) {
Expand Down
41 changes: 41 additions & 0 deletions internal/api/routes_roots.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package api

import (
"context"
"errors"
"net/http"
"net/url"
"strings"
"time"

"github.com/go-chi/chi/v5"
"github.com/opensave/opensave/internal/store"
Expand Down Expand Up @@ -71,6 +73,13 @@ func (s *Server) handleAddGameRoot(w http.ResponseWriter, r *http.Request) {
}
path = abs
}
// A root that is currently being written by an in-flight transfer must
// not be remapped out from under that transfer (issue #60).
done, ok := s.acquireRootTopology(w, r, gameID)
if !ok {
return
}
defer done()
// Rejections here are the overlap and naming rules, which are the user's
// to hear about rather than a server fault: "that folder is already
// covered by the main save" is a sentence, not a 500.
Expand Down Expand Up @@ -98,6 +107,13 @@ func (s *Server) handleRemoveGameRoot(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid location name")
return
}
// Refuse while any transfer still holds a captured path for this game
// (issue #60). The mapping must stay until the last write finishes.
done, ok := s.acquireRootTopology(w, r, gameID)
if !ok {
return
}
defer done()
oldRoots, _ := s.Daemon.Store.GameRootPaths(gameID)
if err := s.Daemon.Store.RemoveGameRoot(gameID, name); err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
Expand All @@ -110,3 +126,28 @@ func (s *Server) handleRemoveGameRoot(w http.ResponseWriter, r *http.Request) {
s.BroadcastGamesUpdate()
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}

// acquireRootTopology waits for interactive edits only. The 30-second bound
// covers acquiring the reservation; the database/watcher phase may take longer.
func (s *Server) acquireRootTopology(w http.ResponseWriter, r *http.Request, gameID string) (func(), bool) {
if s.Daemon == nil || s.Daemon.P2P == nil || s.Daemon.P2P.Sync == nil {
writeError(w, http.StatusServiceUnavailable, "Save-location admission is unavailable.")
return nil, false
}
limit := s.topologyWaitFor
if limit <= 0 {
limit = 30 * time.Second
}
ctx, cancel := context.WithTimeout(r.Context(), limit)
defer cancel()
done, err := s.Daemon.P2P.Sync.WaitTopologyMutation(ctx, gameID, 100*time.Millisecond)
if err == nil {
return done, true
}
if errors.Is(err, context.DeadlineExceeded) && r.Context().Err() == nil {
writeError(w, http.StatusConflict, "A sync of this game is in progress. Try again in a moment.")
} else if r.Context().Err() == nil {
writeError(w, http.StatusServiceUnavailable, "Save-location admission was cancelled or is unavailable.")
}
return nil, false
}
5 changes: 3 additions & 2 deletions internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ type Server struct {
Daemon *daemon.Daemon
Hub *Hub

httpServer *http.Server
listener net.Listener
httpServer *http.Server
listener net.Listener
topologyWaitFor time.Duration // test-injectable admission limit; defaults to 30s
// instance marks every response from this process (instanceHeader), so
// Start can tell whether 127.0.0.1 at its port is really answered by it.
instance string
Expand Down
19 changes: 18 additions & 1 deletion internal/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,21 @@ func isDuplicateGameID(err error) bool {
return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed: games.id")
}

// withRootTopology holds this process's mapping reservation across a path write.
// A second process cannot see the reservation; the CLI must use the running
// daemon's HTTP API instead of opening its own store.
func (d *Daemon) withRootTopology(gameID string, fn func() error) error {
if d.P2P == nil || d.P2P.Sync == nil {
return fmt.Errorf("root topology admission unavailable")
}
done, ok := d.P2P.Sync.TryTopologyMutation(gameID)
if !ok {
return fmt.Errorf("cannot change save locations while a sync is active")
}
defer done()
return fn()
}

// 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) {
Expand Down Expand Up @@ -1265,7 +1280,9 @@ func (d *Daemon) LinkGames(canonicalID, aliasID string) error {
}
var addErr error
if root.Mapped() {
addErr = d.Store.AddGameRoot(canonicalID, root.Name, root.Path)
addErr = d.withRootTopology(canonicalID, func() error {
return d.Store.AddGameRoot(canonicalID, root.Name, root.Path)
})
} else {
addErr = d.Store.NoteGameRoot(canonicalID, root.Name)
}
Expand Down
4 changes: 3 additions & 1 deletion internal/daemon/registry_setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ func (d *Daemon) setUpRegistryCapture(game store.Game) {
"could not prepare the registry location for %q: %v", game.Name, err))
return
}
if err := d.Store.AddGameRoot(game.ID, winreg.LocationName, dir); err != nil {
if err := d.withRootTopology(game.ID, func() error {
return d.Store.AddGameRoot(game.ID, winreg.LocationName, dir)
}); err != nil {
d.Log.Log("warn", fmt.Sprintf(
"could not add the registry save location for %q: %v", game.Name, err))
return
Expand Down
Loading
Loading