commit 2899d9a21758daa8f485897d60cac447bd24e650
parent 25998f1e55725fed0c80eac28332e66597ca4f14
Author: anon <anon@example.com>
Date: Sat, 7 Nov 2026 06:48:55 +0000
Give profiling file writes a channel owner and explicit shutdown
Diffstat:
8 files changed, 129 insertions(+), 27 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -52,9 +52,10 @@ research separately. More screenshots and test cases do not count as new gamepla
Routed fixtures now use production partitioning, and native connection,
inventory and restart tests are moving onto production service ownership.
The browser resource index publishes immutable results through completion
- channels instead of a global mutex. Simulation mutexes and their dependent
- harnesses remain; audit the shared geometry cache separately. Completion requires source
- inspection, race coverage of the migrated harnesses, and real-server protocol
+ channels instead of a global mutex, and a service-owned writer serializes
+ profile batches and their size checks. Simulation mutexes and their dependent
+ harnesses remain; audit the shared geometry cache separately. Completion
+ requires source inspection, race coverage of the migrated harnesses, and real-server protocol
verification; the existing production isolation tests alone are insufficient.
- [x] **Use the original native character creation flow.** Login credentials are
diff --git a/server/browser_profile.go b/server/browser_profile.go
@@ -8,13 +8,44 @@ import (
"os"
"path/filepath"
"regexp"
- "sync"
)
var browserProfileID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
-var browserProfileMutex sync.Mutex
-func browserProfile(w http.ResponseWriter, r *http.Request) {
+type profileWriter struct {
+ requests chan profileBatch
+ done chan struct{}
+}
+
+type profileBatch struct {
+ session string
+ data []byte
+ reply chan profileResult
+}
+
+type profileResult struct {
+ status int
+ message string
+}
+
+func newProfileWriter() *profileWriter {
+ writer := &profileWriter{requests: make(chan profileBatch), done: make(chan struct{})}
+ go func() {
+ defer close(writer.done)
+ for batch := range writer.requests {
+ batch.reply <- batch.write()
+ }
+ }()
+ return writer
+}
+
+// HTTP producers finish before shutdown drains the accepted file writes.
+func (writer *profileWriter) stop() {
+ close(writer.requests)
+ <-writer.done
+}
+
+func (writer *profileWriter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("session")
if !browserProfileID.MatchString(id) {
http.Error(w, "Invalid profile session", http.StatusBadRequest)
@@ -32,31 +63,35 @@ func browserProfile(w http.ResponseWriter, r *http.Request) {
}
compact.WriteByte('\n')
- // Serialize whole batches independently of the game server's state lock.
- browserProfileMutex.Lock()
- defer browserProfileMutex.Unlock()
- if err := os.MkdirAll("logs/profiles", 0755); err != nil {
- http.Error(w, "Cannot create profile directory", http.StatusInternalServerError)
+ batch := profileBatch{session: id, data: compact.Bytes(), reply: make(chan profileResult, 1)}
+ writer.requests <- batch
+ result := <-batch.reply
+ if result.message != "" {
+ http.Error(w, result.message, result.status)
return
}
- file, err := os.OpenFile(filepath.Join("logs/profiles", id+".ndjson"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
+ w.WriteHeader(result.status)
+}
+
+func (batch profileBatch) write() profileResult {
+ // Size validation and append belong to the same owner operation.
+ if err := os.MkdirAll("logs/profiles", 0755); err != nil {
+ return profileResult{http.StatusInternalServerError, "Cannot create profile directory"}
+ }
+ file, err := os.OpenFile(filepath.Join("logs/profiles", batch.session+".ndjson"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
- http.Error(w, "Cannot open profile", http.StatusInternalServerError)
- return
+ return profileResult{http.StatusInternalServerError, "Cannot open profile"}
}
defer file.Close()
info, err := file.Stat()
if err != nil {
- http.Error(w, "Cannot inspect profile", http.StatusInternalServerError)
- return
+ return profileResult{http.StatusInternalServerError, "Cannot inspect profile"}
}
- if info.Size()+int64(compact.Len()) > 128*1024*1024 {
- http.Error(w, "Profile session is full", http.StatusRequestEntityTooLarge)
- return
+ if info.Size()+int64(len(batch.data)) > 128*1024*1024 {
+ return profileResult{http.StatusRequestEntityTooLarge, "Profile session is full"}
}
- if _, err := file.Write(compact.Bytes()); err != nil {
- http.Error(w, "Cannot save profile", http.StatusInternalServerError)
- return
+ if _, err := file.Write(batch.data); err != nil {
+ return profileResult{http.StatusInternalServerError, "Cannot save profile"}
}
- w.WriteHeader(http.StatusNoContent)
+ return profileResult{status: http.StatusNoContent}
}
diff --git a/server/browser_profile_test.go b/server/browser_profile_test.go
@@ -67,8 +67,10 @@ func TestBrowserProfileAdministratorBoundary(t *testing.T) {
func TestBrowserProfileAppendsJSONLines(t *testing.T) {
t.Chdir(t.TempDir())
+ writer := newProfileWriter()
+ defer writer.stop()
mux := http.NewServeMux()
- mux.HandleFunc("POST /browser-profile/{session}", browserProfile)
+ mux.Handle("POST /browser-profile/{session}", writer)
url := "/browser-profile/12345678-1234-1234-1234-123456789abc"
for _, body := range []string{"{\n \"sequence\": 0\n}", `{"sequence":1}`} {
@@ -96,11 +98,13 @@ func TestBrowserProfileRejectsInvalidUploads(t *testing.T) {
} {
t.Run(test.name, func(t *testing.T) {
t.Chdir(t.TempDir())
+ writer := newProfileWriter()
+ defer writer.stop()
request := httptest.NewRequest("POST", "/", strings.NewReader(test.body))
request.SetPathValue("session", test.session)
response := httptest.NewRecorder()
- browserProfile(response, request)
+ writer.ServeHTTP(response, request)
if response.Code != test.status {
t.Fatalf("response: %d", response.Code)
@@ -114,6 +118,8 @@ func TestBrowserProfileRejectsInvalidUploads(t *testing.T) {
func TestBrowserProfileSessionLimit(t *testing.T) {
t.Chdir(t.TempDir())
+ writer := newProfileWriter()
+ defer writer.stop()
if err := os.MkdirAll("logs/profiles", 0755); err != nil {
t.Fatal(err)
}
@@ -130,7 +136,7 @@ func TestBrowserProfileSessionLimit(t *testing.T) {
request.SetPathValue("session", "12345678-1234-1234-1234-123456789abc")
response := httptest.NewRecorder()
- browserProfile(response, request)
+ writer.ServeHTTP(response, request)
if response.Code != http.StatusRequestEntityTooLarge {
t.Fatal(response.Code)
@@ -140,3 +146,51 @@ func TestBrowserProfileSessionLimit(t *testing.T) {
t.Fatalf("size: %v %v", info, err)
}
}
+
+func TestBrowserProfileConcurrentUploadsCannotExceedSessionLimit(t *testing.T) {
+ t.Chdir(t.TempDir())
+ writer := newProfileWriter()
+ defer writer.stop()
+ if err := os.MkdirAll("logs/profiles", 0755); err != nil {
+ t.Fatal(err)
+ }
+ path := "logs/profiles/12345678-1234-1234-1234-123456789abc.ndjson"
+ file, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := file.Truncate(128*1024*1024 - 3); err != nil {
+ file.Close()
+ t.Fatal(err)
+ }
+ file.Close()
+ statuses := make(chan int, 16)
+ for range 16 {
+ go func() {
+ request := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
+ request.SetPathValue("session", "12345678-1234-1234-1234-123456789abc")
+ response := httptest.NewRecorder()
+ writer.ServeHTTP(response, request)
+ statuses <- response.Code
+ }()
+ }
+
+ accepted, full := 0, 0
+ for range 16 {
+ switch status := <-statuses; status {
+ case http.StatusNoContent:
+ accepted++
+ case http.StatusRequestEntityTooLarge:
+ full++
+ default:
+ t.Errorf("unexpected upload status %d", status)
+ }
+ }
+ if accepted != 1 || full != 15 {
+ t.Fatal("concurrent batches did not share one size decision", accepted, full)
+ }
+ info, err := os.Stat(path)
+ if err != nil || info.Size() != 128*1024*1024 {
+ t.Fatal("concurrent appends exceeded the session limit", info, err)
+ }
+}
diff --git a/server/database.go b/server/database.go
@@ -57,6 +57,7 @@ func (server *server) openDatabase() (*sql.DB, error) {
server.db = db
server.databaseWriter = newDatabaseWriter(db)
server.passwordHasher = newPasswordHasher()
+ server.profileWriter = newProfileWriter()
return db, nil
}
diff --git a/server/database_writer.go b/server/database_writer.go
@@ -117,6 +117,10 @@ func (server *server) closeDatabase() error {
server.teamService.stop()
server.teamService = nil
}
+ if server.profileWriter != nil {
+ server.profileWriter.stop()
+ server.profileWriter = nil
+ }
if server.passwordHasher != nil {
server.passwordHasher.stop()
server.passwordHasher = nil
diff --git a/server/http.go b/server/http.go
@@ -55,7 +55,7 @@ func (server *server) httpHandler() http.Handler {
func (state *server) adminHandler() http.Handler {
admin := http.NewServeMux()
- admin.HandleFunc("POST /admin/browser-profile/{session}", browserProfile)
+ admin.Handle("POST /admin/browser-profile/{session}", state.profileWriter)
admin.HandleFunc("GET /admin", state.controlPage)
admin.HandleFunc("GET /admin/{$}", state.controlPage)
admin.HandleFunc("GET /admin/players", state.usersPage)
diff --git a/server/service_shutdown_test.go b/server/service_shutdown_test.go
@@ -249,6 +249,7 @@ func TestServiceShutdownClosesDetachedBrowserStreams(t *testing.T) {
func TestServiceShutdownReportsFailedFinalWriteAndClosesWorkers(t *testing.T) {
fixture := newCheckpointWorld(t)
+ profiles := fixture.profileWriter
fixture.characters[1].nextPositionSave = time.Now().Add(time.Hour)
shutdown := startTestService(t, fixture)
owner, err := fixture.world.owner(1)
@@ -275,6 +276,11 @@ func TestServiceShutdownReportsFailedFinalWriteAndClosesWorkers(t *testing.T) {
default:
t.Fatal("failed shutdown retained input producers")
}
+ select {
+ case <-profiles.done:
+ default:
+ t.Fatal("failed shutdown retained the profile writer")
+ }
if fixture.db.Stats().OpenConnections != 0 {
t.Fatal("failed final save leaked the database")
}
diff --git a/server/state.go b/server/state.go
@@ -131,6 +131,7 @@ type server struct {
retiredMission *acceptedMission
databaseQueries atomic.Uint64
passwordHasher *passwordHasher
+ profileWriter *profileWriter
db *sql.DB
databaseWriter *databaseWriter
teamService *teamDirectory