commit cf736bfde29ff2e71fe35a208bb680f8b1e387bf
parent e778246f47c25ee9ebb2ec6e7e5510786773781d
Author: anon <anon@example.com>
Date: Sat, 17 Oct 2026 20:29:06 +0000
Record browser gameplay profiles without blocking the game worker
Diffstat:
23 files changed, 687 insertions(+), 26 deletions(-)
diff --git a/server/browser_profile.go b/server/browser_profile.go
@@ -0,0 +1,62 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "net/http"
+ "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) {
+ id := r.PathValue("session")
+ if !browserProfileID.MatchString(id) {
+ http.Error(w, "Invalid profile session", http.StatusBadRequest)
+ return
+ }
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 2*1024*1024))
+ if err != nil {
+ http.Error(w, "Profile batch too large or unreadable", http.StatusRequestEntityTooLarge)
+ return
+ }
+ var compact bytes.Buffer
+ if err := json.Compact(&compact, body); err != nil {
+ http.Error(w, "Invalid profile JSON", http.StatusBadRequest)
+ return
+ }
+ compact.WriteByte('\n')
+
+ // Serialize whole batches independently of the game server's state lock.
+ browserProfileMutex.Lock()
+ defer browserProfileMutex.Unlock()
+ if err := os.MkdirAll("local/profiles", 0755); err != nil {
+ http.Error(w, "Cannot create profile directory", http.StatusInternalServerError)
+ return
+ }
+ file, err := os.OpenFile(filepath.Join("local/profiles", id+".ndjson"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
+ if err != nil {
+ http.Error(w, "Cannot open profile", http.StatusInternalServerError)
+ return
+ }
+ defer file.Close()
+ info, err := file.Stat()
+ if err != nil {
+ http.Error(w, "Cannot inspect profile", http.StatusInternalServerError)
+ return
+ }
+ if info.Size()+int64(compact.Len()) > 128*1024*1024 {
+ http.Error(w, "Profile session is full", http.StatusRequestEntityTooLarge)
+ return
+ }
+ if _, err := file.Write(compact.Bytes()); err != nil {
+ http.Error(w, "Cannot save profile", http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/server/browser_profile_test.go b/server/browser_profile_test.go
@@ -0,0 +1,85 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestBrowserProfileAppendsJSONLines(t *testing.T) {
+ t.Chdir(t.TempDir())
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /browser-profile/{session}", browserProfile)
+ url := "/browser-profile/12345678-1234-1234-1234-123456789abc"
+
+ for _, body := range []string{"{\n \"sequence\": 0\n}", `{"sequence":1}`} {
+ response := httptest.NewRecorder()
+ mux.ServeHTTP(response, httptest.NewRequest("POST", url, strings.NewReader(body)))
+ if response.Code != http.StatusNoContent {
+ t.Fatalf("upload: %d %s", response.Code, response.Body.String())
+ }
+ }
+
+ body, err := os.ReadFile("local/profiles/12345678-1234-1234-1234-123456789abc.ndjson")
+ if err != nil || string(body) != "{\"sequence\":0}\n{\"sequence\":1}\n" {
+ t.Fatalf("profile: %q %v", body, err)
+ }
+}
+
+func TestBrowserProfileRejectsInvalidUploads(t *testing.T) {
+ for _, test := range []struct {
+ name, session, body string
+ status int
+ }{
+ {"path", "../../outside", `{}`, http.StatusBadRequest},
+ {"json", "12345678-1234-1234-1234-123456789abc", `{`, http.StatusBadRequest},
+ {"size", "12345678-1234-1234-1234-123456789abc", strings.Repeat(" ", 2*1024*1024+1), http.StatusRequestEntityTooLarge},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ t.Chdir(t.TempDir())
+ request := httptest.NewRequest("POST", "/", strings.NewReader(test.body))
+ request.SetPathValue("session", test.session)
+ response := httptest.NewRecorder()
+
+ browserProfile(response, request)
+
+ if response.Code != test.status {
+ t.Fatalf("response: %d", response.Code)
+ }
+ if _, err := os.Stat("local"); !os.IsNotExist(err) {
+ t.Fatalf("invalid request created profile storage: %v", err)
+ }
+ })
+ }
+}
+
+func TestBrowserProfileSessionLimit(t *testing.T) {
+ t.Chdir(t.TempDir())
+ if err := os.MkdirAll("local/profiles", 0755); err != nil {
+ t.Fatal(err)
+ }
+ path := "local/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); err != nil {
+ t.Fatal(err)
+ }
+ file.Close()
+ request := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
+ request.SetPathValue("session", "12345678-1234-1234-1234-123456789abc")
+ response := httptest.NewRecorder()
+
+ browserProfile(response, request)
+
+ if response.Code != http.StatusRequestEntityTooLarge {
+ t.Fatal(response.Code)
+ }
+ info, err := os.Stat(path)
+ if err != nil || info.Size() != 128*1024*1024 {
+ t.Fatalf("size: %v %v", info, err)
+ }
+}
diff --git a/server/main.go b/server/main.go
@@ -54,6 +54,7 @@ func main() {
http.HandleFunc("POST /browser-launch", server.browserLaunch)
http.HandleFunc("GET /browser-world", server.browserWorld)
http.HandleFunc("GET /browser-manifest", browserManifest)
+ http.HandleFunc("POST /browser-profile/{session}", browserProfile)
http.HandleFunc("GET /wasm/", browserClient)
browserFiles := http.StripPrefix("/browser/", http.FileServer(http.Dir("old_wip/browser")))
http.HandleFunc("GET /browser/", func(w http.ResponseWriter, r *http.Request) {
diff --git a/src/Makefile.wasm b/src/Makefile.wasm
@@ -3,7 +3,7 @@ CPPFLAGS := -Iruntime -Igame -Idata -DRECOMP_PORTABLE
# Keep exception landing pads in Wasm so JSPI can yield through guest calls.
CFLAGS := -O2 -fno-strict-aliasing -pthread -sSUPPORT_LONGJMP=wasm
PORT_FLAGS := -sUSE_SDL=2 -sUSE_FREETYPE=1
-RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_gdi.c runtime/linux_audio.c runtime/linux_music.c runtime/browser_audio.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_snapshot.c runtime/browser_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_rtti.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c runtime/linux_path.c runtime/browser_host.c
+RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_gdi.c runtime/linux_audio.c runtime/linux_music.c runtime/browser_audio.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_snapshot.c runtime/browser_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_rtti.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c runtime/linux_path.c runtime/browser_host.c runtime/browser_profile.c
GAME_SOURCES := $(wildcard game/*/*.c) game/dispatch.c
DATA_SOURCES := $(wildcard data/*.c)
VENDOR_SOURCES := $(wildcard vendor/msvcp60/source/*.c) $(wildcard vendor/ace/source/*.c)
@@ -11,15 +11,19 @@ OBJECTS := $(patsubst %.c,build/wasm/objects/%.o,$(GAME_SOURCES) $(DATA_SOURCES)
.DEFAULT_GOAL := all
.PHONY: all objects
-all: build/wasm/web/game.js build/wasm/web/game.wasm build/wasm/web/index.html
+all: build/wasm/web/game.js build/wasm/web/game.wasm build/wasm/web/index.html build/wasm/web/profile-worker.js
+
+build/wasm/web/profile-worker.js: browser/profile-worker.js
+ @mkdir -p $(@D)
+ cp $< $@
build/wasm/web/resource-dispatch-test.html: tests/browser_resource_queue.c runtime/browser_host.c
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) $^ -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@
-build/wasm/web/game.js build/wasm/web/game.wasm &: $(OBJECTS) runtime/browser_network.js runtime/browser_host.js runtime/browser_fetch.js runtime/browser_audio.js ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a Makefile.wasm
+build/wasm/web/game.js build/wasm/web/game.wasm &: $(OBJECTS) runtime/browser_network.js runtime/browser_host.js runtime/browser_fetch.js runtime/browser_audio.js runtime/browser_profile.js ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a Makefile.wasm
@mkdir -p $(@D)
- $(CC) $(CFLAGS) $(PORT_FLAGS) $(OBJECTS) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=8 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sOFFSCREENCANVAS_SUPPORT -sJSPI -sALLOW_MEMORY_GROWTH -sINITIAL_MEMORY=268435456 -sSTACK_SIZE=8388608 --js-library runtime/browser_network.js --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_audio.js --emit-symbol-map -o build/wasm/web/game.js
+ $(CC) $(CFLAGS) $(PORT_FLAGS) $(OBJECTS) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=8 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sOFFSCREENCANVAS_SUPPORT -sJSPI -sALLOW_MEMORY_GROWTH -sINITIAL_MEMORY=268435456 -sSTACK_SIZE=8388608 --js-library runtime/browser_network.js --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_audio.js --js-library runtime/browser_profile.js --emit-symbol-map -o build/wasm/web/game.js
build/wasm/web/index.html: browser/index.html
@mkdir -p $(@D)
@@ -37,39 +41,39 @@ build/wasm/objects/%.o: %.c
-include $(OBJECTS:.o=.d)
-build/wasm/web/runtime-test.html: tests/browser_runtime.c runtime/browser_host.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js runtime/browser_fetch.js runtime/browser_network.js
+build/wasm/web/runtime-test.html: tests/browser_runtime.c runtime/browser_host.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js runtime/browser_fetch.js runtime/browser_network.js runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_network.js -o $@
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_network.js -o $@ --js-library runtime/browser_profile.js
-build/wasm/web/files-test.html: tests/files.c runtime/linux_file.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/linux_file.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h
+build/wasm/web/files-test.html: tests/files.c runtime/linux_file.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/linux_file.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -o $@
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -o $@ --js-library runtime/browser_profile.js
-build/wasm/web/storage-test.html: tests/browser_storage.c runtime/browser_host.c runtime/browser_host.js runtime/browser_fetch.js Makefile.wasm
+build/wasm/web/storage-test.html: tests/browser_storage.c runtime/browser_host.c runtime/browser_host.js runtime/browser_fetch.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js -o $@
+ $(CC) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js -o $@ --js-library runtime/browser_profile.js
-build/wasm/web/suspension-test.html: tests/browser_suspension.c runtime/browser_host.js Makefile.wasm
+build/wasm/web/suspension-test.html: tests/browser_suspension.c runtime/browser_host.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CFLAGS) $< --js-library runtime/browser_host.js -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@
+ $(CC) $(CFLAGS) $< --js-library runtime/browser_host.js -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@ runtime/browser_profile.c --js-library runtime/browser_profile.js
-build/wasm/web/pacing-test.html: tests/browser_pacing.c runtime/linux_graphics.c runtime/linux_window.c runtime/gl_renderer.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js Makefile.wasm
+build/wasm/web/pacing-test.html: tests/browser_pacing.c runtime/linux_graphics.c runtime/linux_window.c runtime/gl_renderer.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) --js-library runtime/browser_host.js -sUSE_SDL=2 -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -Wl,--wrap=clock_nanosleep -o $@
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) --js-library runtime/browser_host.js -sUSE_SDL=2 -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -Wl,--wrap=clock_nanosleep -o $@ --js-library runtime/browser_profile.js
build/wasm/web/audio-output-test.html: tests/browser_audio.html build/wasm/web/audio-output-test.js
cp $< $@
-build/wasm/web/audio-output-test.js: tests/browser_audio.c runtime/browser_audio.c runtime/browser_audio.h runtime/browser_audio.js Makefile.wasm
+build/wasm/web/audio-output-test.js: tests/browser_audio.c runtime/browser_audio.c runtime/browser_audio.h runtime/browser_audio.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CPPFLAGS) $(CFLAGS) -sUSE_SDL=2 $(filter %.c,$^) --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@
+ $(CC) $(CPPFLAGS) $(CFLAGS) -sUSE_SDL=2 $(filter %.c,$^) --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@ --js-library runtime/browser_profile.js
build/wasm/web/mixer-test.html: tests/browser_mixer.html build/wasm/web/mixer-test.js
cp $< $@
-build/wasm/web/mixer-test.js: tests/audio.c runtime/linux_audio.c runtime/browser_audio.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/browser_audio.h runtime/browser_audio.js runtime/linux_audio.h runtime/guest_heap.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h Makefile.wasm
+build/wasm/web/mixer-test.js: tests/audio.c runtime/linux_audio.c runtime/browser_audio.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/browser_audio.h runtime/browser_audio.js runtime/linux_audio.h runtime/guest_heap.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CPPFLAGS) $(CFLAGS) -I../local/wasm/deps/include -sUSE_SDL=2 $(filter %.c,$^) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -Wl,--wrap=audio_output_open,--wrap=sf_open -o $@
+ $(CC) $(CPPFLAGS) $(CFLAGS) -I../local/wasm/deps/include -sUSE_SDL=2 $(filter %.c,$^) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -Wl,--wrap=audio_output_open,--wrap=sf_open -o $@ --js-library runtime/browser_profile.js
build/wasm/terrain-line.js: tests/terrain_line.c game/llr.dll/lifted-0023.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h
@mkdir -p $(@D)
@@ -127,6 +131,6 @@ build/wasm/web/music-test.html: tests/music.c runtime/linux_music.c runtime/linu
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -o $@
-build/wasm/web/stdio-concurrency-test.html: tests/stdio_concurrency.c runtime/guest_stdio.c runtime/guest_crt.c runtime/guest_format.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/guest_stdio.h
+build/wasm/web/stdio-concurrency-test.html: tests/stdio_concurrency.c runtime/guest_stdio.c runtime/guest_crt.c runtime/guest_format.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/guest_stdio.h runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
- $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -Wl,--wrap=read -o $@
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -Wl,--wrap=read -o $@ --js-library runtime/browser_profile.js
diff --git a/src/browser/index.html b/src/browser/index.html
@@ -11,6 +11,7 @@
pre { padding: 12px; white-space: pre-wrap; }
</style>
<header><button id="start">Enter Rubi-Ka</button> <span id="status">Ready</span></header>
+<div id="profile-status" style="padding:0 12px"></div>
<canvas id="canvas" width="1024" height="768" tabindex="0"></canvas>
<details style="padding:12px">
<summary>Frame capture</summary>
diff --git a/src/browser/profile-worker.js b/src/browser/profile-worker.js
@@ -0,0 +1,78 @@
+// Collect and upload outside the game and browser UI threads. All queues are bounded.
+let configuration, memory, uploading = false, sequence = 0, dropped = 0;
+let events = [], frames = [], metrics = {}, visibility = 'visible', build = null;
+let started = 0;
+
+function record(event) {
+ if (events.length < 4096) events.push(event);
+ else ++dropped;
+}
+
+onmessage = event => {
+ const data = event.data;
+ if (data.init) {
+ configuration = data.init;
+ visibility = configuration.visibility;
+ memory = new Uint32Array(configuration.memory);
+ started = configuration.started;
+ fetch('/wasm/build.json').then(response => {
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ return response.json();
+ }).then(value => { build = value.source_commit; }).catch(error => {
+ postMessage(`Profiling: build identity unavailable (${error.message})`);
+ });
+ if (configuration.detailed) setInterval(() => {
+ // Best-effort guest function residency, including host calls and waits.
+ // This is not an instruction-pointer or CPU-time sample.
+ record({name: 'guest sample', ph: 'i', s: 't', pid: 1, tid: configuration.thread,
+ ts: (performance.timeOrigin + performance.now()) * 1000,
+ args: {function: Atomics.load(memory, configuration.currentFunction >>> 2),
+ phase: Atomics.load(memory, configuration.phase >>> 2)}});
+ }, 4);
+ setInterval(upload, configuration.detailed ? 5000 : 30000);
+ postMessage(`${configuration.detailed ? 'Detailed profile' : 'Performance summaries'}: ${configuration.session}`);
+ return;
+ }
+ if (data.visibility) { upload(); visibility = data.visibility; return; }
+ for (const item of data.events) record(item);
+ for (const duration of data.frames) {
+ if (frames.length < 120000) frames.push(duration);
+ else ++dropped;
+ }
+ dropped += data.dropped;
+ for (const [name, value] of Object.entries(data.metrics)) {
+ const metric = metrics[name] ||= {count: 0, ms: 0, max: 0};
+ metric.count += value.count; metric.ms += value.ms;
+ metric.max = Math.max(metric.max, value.max);
+ }
+};
+
+async function upload() {
+ if (uploading) return;
+ const ended = performance.timeOrigin + performance.now();
+ frames.sort((a, b) => a - b);
+ const sum = frames.reduce((total, value) => total + value, 0);
+ const batch = {version: 1, sequence: sequence++, build, detailed: configuration.detailed,
+ client: configuration.client, started, ended, visibility, dropped,
+ frames: {count: frames.length, mean: frames.length ? sum / frames.length : 0,
+ p95: frames[Math.floor(frames.length * .95)] || 0,
+ p99: frames[Math.floor(frames.length * .99)] || 0, max: frames.at(-1) || 0,
+ over50: frames.filter(value => value > 50).length,
+ over100: frames.filter(value => value > 100).length}, metrics, traceEvents: events};
+ events = []; frames = []; metrics = {}; dropped = 0; started = ended;
+ uploading = true;
+ try {
+ const response = await fetch(`/browser-profile/${configuration.session}`, {
+ method: 'POST', headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify(batch), signal: AbortSignal.timeout(10000)
+ });
+ if (response.status !== 204) throw new Error(`HTTP ${response.status}`);
+ postMessage(`Profile saved: local/profiles/${configuration.session}.ndjson (batch ${batch.sequence})`);
+ } catch (error) {
+ // Failed uploads are discarded, never retried on the game thread.
+ dropped += batch.dropped + batch.traceEvents.length + batch.frames.count;
+ postMessage(`Profile upload failed: ${error.message}; gameplay continues`);
+ } finally {
+ uploading = false;
+ }
+}
diff --git a/src/runtime/browser_audio.c b/src/runtime/browser_audio.c
@@ -1,3 +1,4 @@
+#include "browser_profile.h"
#include "browser_audio.h"
#include <assert.h>
#include <pthread.h>
@@ -35,9 +36,11 @@ static void *mix_audio(void *argument)
if (pthread_mutex_unlock(&output->mutex)) abort();
break;
}
+ double profile_start = ready ? ao_profile_begin("audio mix") : 0;
if (ready)
output->format.callback(output->format.userdata, buffer, output->format.size);
if (pthread_mutex_unlock(&output->mutex)) abort();
+ ao_profile_end("audio mix", profile_start, NULL);
double delay = ready ? ao_audio_submit(output->handle, buffer, output->format.samples) : 10;
usleep((unsigned)(delay * 1000));
}
diff --git a/src/runtime/browser_fetch.js b/src/runtime/browser_fetch.js
@@ -4,7 +4,7 @@ addToLibrary({
browser_prefetch_resource_js: (kind, identity) => AOResourcePrefetch.request(kind, identity),
_wasmfs_create_fetch_backend_js__deps: [
'$wasmFS$backends', '_wasmfs_fetch_get_file_url', '_wasmfs_fetch_get_chunk_size',
- '$AOResourcePrefetch', 'browser_prefetch_resource_ready'
+ '$AOResourcePrefetch', '$AOProfile', 'browser_prefetch_resource_ready'
],
_wasmfs_create_fetch_backend_js: async function(backend) {
const files = new Map();
@@ -80,6 +80,16 @@ addToLibrary({
// Fetch the bytes and file size together, without a separate HEAD request.
async function fetchChunks(file, first, last) {
+ const start = AOProfile.begin('asset network');
+ try {
+ return await fetchChunkBytes(file, first, last);
+ } finally {
+ AOProfile.end('asset network', start,
+ `${new URL(file.url).pathname} bytes ${first * file.chunkSize}-${(last + 1) * file.chunkSize - 1}`);
+ }
+ }
+
+ async function fetchChunkBytes(file, first, last) {
const start = first * file.chunkSize;
const end = (last + 1) * file.chunkSize - 1;
// Validate against the server, not an older partial response in the HTTP cache.
diff --git a/src/runtime/browser_host.js b/src/runtime/browser_host.js
@@ -1,6 +1,14 @@
addToLibrary({
ao_present_yield__async: 'auto',
- ao_present_yield: () => new Promise(resolve => requestAnimationFrame(resolve)),
+ ao_present_yield__deps: ['$AOProfile'],
+ ao_present_yield: () => {
+ AOProfile.frame();
+ const start = AOProfile.begin('raf wait');
+ return new Promise(resolve => requestAnimationFrame(() => {
+ AOProfile.end('raf wait', start);
+ resolve();
+ }));
+ },
$AOSoundSizes: {},
ao_asset_manifest__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOSoundSizes'],
ao_asset_manifest: (base) => {
diff --git a/src/runtime/browser_profile.c b/src/runtime/browser_profile.c
@@ -0,0 +1,17 @@
+#include "browser_profile.h"
+#include <emscripten.h>
+#include <pthread.h>
+
+static char *configuration;
+static uint32_t phase;
+char *ao_profile_start(uint32_t *current_function, uint32_t *phase, uintptr_t thread);
+
+EMSCRIPTEN_KEEPALIVE const char *browser_profile_configuration(void)
+{
+ return configuration;
+}
+
+void browser_profile_initialize(uint32_t *current_function)
+{
+ configuration = ao_profile_start(current_function, &phase, (uintptr_t)pthread_self());
+}
diff --git a/src/runtime/browser_profile.h b/src/runtime/browser_profile.h
@@ -0,0 +1,15 @@
+#ifndef BROWSER_PROFILE_H
+#define BROWSER_PROFILE_H
+
+#ifdef __EMSCRIPTEN__
+#include <stdint.h>
+void browser_profile_initialize(uint32_t *current_function);
+double ao_profile_begin(const char *name);
+void ao_profile_end(const char *name, double start, const char *detail);
+#else
+static inline double ao_profile_begin(const char *name) { (void)name; return 0; }
+static inline void ao_profile_end(const char *name, double start, const char *detail)
+{ (void)name; (void)start; (void)detail; }
+#endif
+
+#endif
diff --git a/src/runtime/browser_profile.js b/src/runtime/browser_profile.js
@@ -0,0 +1,117 @@
+addToLibrary({
+ $AOProfile__deps: ['browser_profile_configuration', 'pthread_self', '$UTF8ToString'],
+ $AOProfile: {
+ channel: null,
+ detailed: false,
+ events: [],
+ metrics: {},
+ dropped: 0,
+ frames: [],
+ previousFrame: 0,
+ lastFlush: 0,
+ phases: [],
+ phaseAddress: 0,
+ connect() {
+ if (this.channel) return true;
+ const configuration = _browser_profile_configuration();
+ if (!configuration) return false;
+ const [detailed, session, phase, thread] = UTF8ToString(configuration).split(':');
+ this.detailed = detailed === '1';
+ this.thread = _pthread_self();
+ this.phaseAddress = this.detailed && this.thread === Number(thread) ? Number(phase) : 0;
+ this.channel = new BroadcastChannel(`ao-profile-${session}`);
+ this.lastFlush = this.now();
+ setInterval(() => this.flush(), 1000);
+ return true;
+ },
+ now() { return performance.timeOrigin + performance.now(); },
+ begin(name) {
+ if (!this.connect()) return 0;
+ if (this.phaseAddress) {
+ this.phases.push(Atomics.load(HEAPU32, this.phaseAddress >>> 2));
+ const phase = name === 'raf wait' ? 1 : name === 'render scene' ? 2 :
+ name === 'file read' ? 3 : name === 'asset setup' ? 4 : 5;
+ Atomics.store(HEAPU32, this.phaseAddress >>> 2, phase);
+ }
+ return this.now();
+ },
+ end(name, start, detail) {
+ if (!start) return;
+ const now = this.now(), duration = now - start;
+ if (this.phaseAddress) Atomics.store(HEAPU32, this.phaseAddress >>> 2, this.phases.pop());
+ const metric = this.metrics[name] ||= {count: 0, ms: 0, max: 0};
+ ++metric.count;
+ metric.ms += duration;
+ metric.max = Math.max(metric.max, duration);
+ // Cached reads remain in aggregates without crowding out meaningful waits.
+ if (this.detailed && (name !== 'file read' || duration >= 0.1)) {
+ if (this.events.length < 2048)
+ this.events.push({name, ph: 'X', ts: start * 1000, dur: duration * 1000,
+ pid: 1, tid: this.thread, args: detail ? {detail: detail.slice(0, 128)} : {}});
+ else ++this.dropped;
+ }
+ // The game worker cannot run its timer while it is inside guest code.
+ if (this.events.length >= 128 || now - this.lastFlush >= 1000 ||
+ name === 'sound load/decode' || name === 'music load/decode') this.flush();
+ },
+ frame() {
+ if (!this.connect()) return;
+ const now = this.now();
+ if (this.previousFrame) {
+ const duration = now - this.previousFrame;
+ if (this.detailed) {
+ if (this.events.length < 2048)
+ this.events.push({name: 'frame interval', ph: 'X', ts: this.previousFrame * 1000,
+ dur: duration * 1000, pid: 1, tid: 0});
+ else ++this.dropped;
+ }
+ this.frames.push(duration);
+ if (this.frames.length >= 120) this.flush();
+ }
+ this.previousFrame = now;
+ },
+ flush() {
+ if (!this.events.length && !this.frames.length && !Object.keys(this.metrics).length) return;
+ this.channel.postMessage({events: this.events, frames: this.frames,
+ metrics: this.metrics, dropped: this.dropped});
+ this.lastFlush = this.now();
+ this.events = []; this.frames = []; this.metrics = {}; this.dropped = 0;
+ }
+ },
+ ao_profile_start__deps: ['$stringToNewUTF8'],
+ ao_profile_start__proxy: 'sync',
+ ao_profile_start: (currentFunction, phase, thread) => {
+ const detailed = new URLSearchParams(location.search).get('profile') === '1';
+ const session = crypto.randomUUID();
+ let worker;
+ try {
+ worker = new Worker('/wasm/profile-worker.js');
+ } catch (error) {
+ console.warn('Profiling unavailable; gameplay continues', error);
+ return 0;
+ }
+ const channel = new BroadcastChannel(`ao-profile-${session}`);
+ channel.onmessage = event => worker.postMessage(event.data);
+ worker.postMessage({init: {session, detailed, memory: wasmMemory.buffer,
+ currentFunction, phase, thread, started: performance.timeOrigin + performance.now(), visibility: document.visibilityState,
+ client: {userAgent: navigator.userAgent, width: Module.canvas.width, height: Module.canvas.height}}});
+ worker.onmessage = event => {
+ const status = document.getElementById('profile-status');
+ if (status) status.textContent = event.data;
+ };
+ worker.onerror = () => {
+ channel.close();
+ const status = document.getElementById('profile-status');
+ if (status) status.textContent = 'Profiler stopped; gameplay continues';
+ };
+ document.addEventListener('visibilitychange', () => {
+ worker.postMessage({visibility: document.visibilityState});
+ });
+ return stringToNewUTF8(`${detailed ? 1 : 0}:${session}:${phase}:${thread}`);
+ },
+ ao_profile_begin__deps: ['$AOProfile'],
+ ao_profile_begin: name => AOProfile.begin(UTF8ToString(name)),
+ ao_profile_end__deps: ['$AOProfile'],
+ ao_profile_end: (name, start, detail) => AOProfile.end(UTF8ToString(name), start,
+ detail ? UTF8ToString(detail) : '')
+});
diff --git a/src/runtime/guest_stdio.c b/src/runtime/guest_stdio.c
@@ -1,4 +1,5 @@
#define _GNU_SOURCE
+#include "browser_profile.h"
#include "linux_path.h"
#include <pthread.h>
#include "guest_stdio.h"
@@ -489,8 +490,10 @@ static int fill_input(struct stream *stream)
stream->lookahead = -1;
count = 1;
} else {
+ double profile_start = ao_profile_begin("file read");
do count = read(stream->descriptor, buffer, flags & 4 ? 2 : MEM32(file + 24));
while (count < 0 && errno == EINTR);
+ ao_profile_end("file read", profile_start, NULL);
}
/* Text buffers expose translated bytes even to inline guest getc code. */
diff --git a/src/runtime/linux_audio.c b/src/runtime/linux_audio.c
@@ -1,3 +1,4 @@
+#include "browser_profile.h"
#include "linux_path.h"
#include "linux_audio.h"
#include "guest_heap.h"
@@ -95,6 +96,7 @@ static void *load_audio(void *unused)
/* File access, decoding and resampling never hold a playback lock. */
int state = -1;
if (!canceled) {
+ double profile_start = ao_profile_begin("sound load/decode");
char *path = linux_path(asset->filename);
SF_INFO info = {0};
SNDFILE *file = sf_open(path, SFM_READ, &info);
@@ -123,6 +125,7 @@ static void *load_audio(void *unused)
}
free(decoded);
} else fprintf(stderr, "[linux-audio] sound %s: %s\n", path, sf_strerror(NULL));
+ ao_profile_end("sound load/decode", profile_start, asset->filename);
free(path);
}
@@ -546,6 +549,7 @@ static void open_stream(void)
int channels = driver->format.channels, rate = driver->format.freq;
if (pthread_mutex_unlock(&audio_mutex)) abort();
+ double profile_start = ao_profile_begin("music load/decode");
/* Decode the file once; SDL converts its channels/rate into driver-format floats. */
char *path = linux_path((const char *)ADDR(filename));
SF_INFO info = {0};
@@ -592,6 +596,7 @@ static void open_stream(void)
}
if (pthread_mutex_unlock(&audio_mutex)) abort();
} else fprintf(stderr, "[linux-audio] stream %s: %s\n", path, sf_strerror(NULL));
+ ao_profile_end("music load/decode", profile_start, path);
free(path);
}
diff --git a/src/runtime/linux_file.c b/src/runtime/linux_file.c
@@ -1,4 +1,5 @@
#define _GNU_SOURCE
+#include "browser_profile.h"
#include "linux_path.h"
#include <pthread.h>
#include "linux_file.h"
@@ -168,10 +169,12 @@ static void read_file_locked(void)
if ((output | size | position) & 511) { MEM32(g_fs_base + 0x34) = 87; return; }
if (posix_memalign(&buffer, 4096, size)) { MEM32(g_fs_base + 0x34) = 8; return; }
}
+ double profile_start = ao_profile_begin("file read");
ssize_t result;
do {
result = read(handle->descriptor, buffer, size);
} while (result < 0 && errno == EINTR);
+ ao_profile_end("file read", profile_start, NULL);
if (result < 0) MEM32(g_fs_base + 0x34) = file_error(errno);
if (handle->unbuffered && size) {
if (result > 0) memcpy((void *)ADDR(output), buffer, result);
diff --git a/src/runtime/linux_graphics.c b/src/runtime/linux_graphics.c
@@ -1,3 +1,4 @@
+#include "browser_profile.h"
#include "linux_graphics.h"
#include "linux_window.h"
#include "guest_heap.h"
@@ -1549,10 +1550,13 @@ static void device_caps(void)
g_esp += 12;
}
+static double scene_profile_start;
+
static void device_begin_scene(void)
{
struct device_object *device = find_device(MEM32(g_esp + 4));
g_eax = device->scene ? 0x887602f8u : 0;
+ if (!device->scene) scene_profile_start = ao_profile_begin("render scene");
device->scene = 1;
g_esp += 8;
}
@@ -1561,6 +1565,7 @@ static void device_end_scene(void)
{
struct device_object *device = find_device(MEM32(g_esp + 4));
g_eax = device->scene ? 0 : 0x887602f9u;
+ if (device->scene) ao_profile_end("render scene", scene_profile_start, NULL);
device->scene = 0;
g_esp += 8;
}
diff --git a/src/runtime/linux_host.c b/src/runtime/linux_host.c
@@ -1,4 +1,5 @@
#define _GNU_SOURCE
+#include "browser_profile.h"
#include "recomp_types.h"
#include "game-data.h"
#include "game-modules.h"
@@ -238,7 +239,10 @@ int main(int argc, char **argv)
extern char **environ;
#ifdef __EMSCRIPTEN__
extern void browser_initialize(void);
+ browser_profile_initialize(&g_cur_func);
+ double setup_start = ao_profile_begin("asset setup");
browser_initialize();
+ ao_profile_end("asset setup", setup_start, NULL);
#endif
setvbuf(stderr, NULL, _IONBF, 0);
for (int i = 0; i < game_module_count; ++i) {
diff --git a/src/tests/browser_fetch.mjs b/src/tests/browser_fetch.mjs
@@ -10,6 +10,7 @@ async function fixture(bytes, wholeFile = false, storage, version = '"one"') {
const heap = new Uint8Array(64);
let library;
const context = vm.createContext({
+ AOProfile: {begin: () => 0, end: () => {}},
Map, Uint8Array, Error, Number, Math, URL, Response, HEAPU8: heap,
caches: storage, console: {warn: (...args) => warnings.push(args)},
UTF8ToString: value => value,
diff --git a/src/tests/browser_prefetch.mjs b/src/tests/browser_prefetch.mjs
@@ -6,7 +6,8 @@ const names = new Map([[1,'boots_sand_01.wav'],[2,'boots_sand_02.wav'],[3,'boots
[4,'boots_sand_04.wav'],[5,'boots_sand_05.wav'],[6,'boots_con_01.wav']]);
const requests = [], pending = [], timers = [];
let library;
-const context = vm.createContext({Map, Set, URL, Response, Uint8Array, console,
+const context = vm.createContext({
+ AOProfile: {begin: () => 0, end: () => {}},Map, Set, URL, Response, Uint8Array, console,
HEAPU8:new Uint8Array(64), UTF8ToString: value => value,
__wasmfs_fetch_get_file_url: handle => {
assert(names.has(handle), 'Must not inspect a freed file');
diff --git a/src/tests/browser_profile.mjs b/src/tests/browser_profile.mjs
@@ -0,0 +1,182 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+
+function fixture(detailed, status = 204) {
+ const uploads = [], timers = [], messages = [];
+ let rejectUpload = false, pendingUpload;
+ const memory = new SharedArrayBuffer(16);
+ new Uint32Array(memory).set([0x12345678, 3]);
+ const context = vm.createContext({
+ Uint32Array, Atomics, performance: {timeOrigin: 1000, now: () => 100},
+ setInterval: (callback, delay) => timers.push({callback, delay}),
+ postMessage: message => messages.push(message), AbortSignal,
+ fetch: async (url, options) => {
+ if (!options) return {ok: true, json: async () => ({source_commit: 'build-test'})};
+ uploads.push(JSON.parse(options.body));
+ if (rejectUpload) throw new Error('offline');
+ if (pendingUpload) await pendingUpload;
+ return {status};
+ }
+ });
+ vm.runInContext(fs.readFileSync(new URL('../browser/profile-worker.js', import.meta.url), 'utf8'), context);
+ context.onmessage({data: {init: {session: 'test', detailed, memory,
+ currentFunction: 0, phase: 4, thread: 7, started: 1000, visibility: 'visible'}}});
+ return {uploads, timers, messages, send: data => context.onmessage({data}),
+ offline: () => { rejectUpload = true; }, hold: promise => { pendingUpload = promise; }};
+}
+
+async function summaries() {
+ const test = fixture(false);
+ test.send({events: [], frames: [10, 20, 60, 110], dropped: 0,
+ metrics: {'file read': {count: 2, ms: 50, max: 40}}});
+
+ await test.timers[0].callback();
+
+ assert.equal(test.timers.length, 1);
+ assert.equal(test.timers[0].delay, 30000);
+ assert.deepEqual(test.uploads[0].frames, {count: 4, mean: 50, p95: 110, p99: 110, max: 110, over50: 2, over100: 1});
+ assert.deepEqual(test.uploads[0].traceEvents, []);
+ assert.deepEqual(test.uploads[0].metrics['file read'], {count: 2, ms: 50, max: 40});
+}
+
+async function boundedSamplingAndFailedUpload() {
+ const test = fixture(true);
+ test.offline();
+
+ for (let index = 0; index < 4106; ++index) test.timers[0].callback();
+ await test.timers[1].callback();
+ await test.timers[1].callback();
+
+ assert.equal(test.uploads[0].traceEvents.length, 4096);
+ assert.equal(test.uploads[0].dropped, 10);
+ assert.deepEqual(test.uploads[0].traceEvents[0].args, {function: 0x12345678, phase: 3});
+ assert.equal(test.uploads[1].traceEvents.length, 0);
+ assert.equal(test.uploads[1].dropped, 4106);
+ assert.match(test.messages.at(-1), /upload failed.*offline/);
+}
+
+async function slowUploadDoesNotAccumulateRequests() {
+ const test = fixture(true);
+ let release;
+ test.hold(new Promise(resolve => { release = resolve; }));
+
+ const pending = test.timers[1].callback();
+ await test.timers[1].callback();
+ for (let index = 0; index < 4106; ++index) test.timers[0].callback();
+ release();
+ await pending;
+ await test.timers[1].callback();
+
+ assert.equal(test.uploads.length, 2);
+ assert.equal(test.uploads[1].traceEvents.length, 4096);
+ assert.equal(test.uploads[1].dropped, 10);
+}
+
+await summaries();
+await boundedSamplingAndFailedUpload();
+await slowUploadDoesNotAccumulateRequests();
+console.log('PASS: gameplay profile summaries, sampling, queue bounds and failed/slow uploads');
+
+async function clientSpansRestorePhases() {
+ let library, now = 0;
+ const sent = [];
+ const heap = new Uint32Array(new SharedArrayBuffer(16));
+ const context = vm.createContext({
+ Atomics, HEAPU32: heap, performance: {timeOrigin: 1000, now: () => now},
+ _browser_profile_configuration: () => '1:test:4:7', _pthread_self: () => 7,
+ UTF8ToString: value => value, setInterval: () => {},
+ BroadcastChannel: class { postMessage(value) { sent.push(value); } },
+ addToLibrary: value => { library = value; }
+ });
+ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context);
+ context.AOProfile = library.$AOProfile;
+
+ const render = library.ao_profile_begin('render scene');
+ const read = library.ao_profile_begin('file read');
+ assert.equal(heap[1], 3);
+ now = 170;
+ library.ao_profile_end('file read', read, 0);
+ assert.equal(heap[1], 2);
+ now = 180;
+ library.ao_profile_end('render scene', render, 0);
+ context.AOProfile.frame();
+ now = 200;
+ context.AOProfile.frame();
+ context.AOProfile.flush();
+
+ assert.equal(heap[1], 0);
+ assert.equal(sent.length, 1);
+ assert.equal(sent[0].metrics['file read'].ms, 170);
+ assert.equal(sent[0].metrics['render scene'].ms, 180);
+ assert.equal(sent[0].frames[0], 20);
+ assert.equal(sent[0].events[2].name, 'frame interval');
+ assert.equal(sent[0].events[2].dur, 20000);
+}
+
+await clientSpansRestorePhases();
+console.log('PASS: nested client spans, frame intervals and wait phase restoration');
+
+async function oldServerDoesNotReportSuccess() {
+ const test = fixture(false, 200);
+
+ await test.timers[0].callback();
+
+ assert.match(test.messages.at(-1), /upload failed: HTTP 200/);
+}
+
+await oldServerDoesNotReportSuccess();
+console.log('PASS: an old server response cannot be mistaken for a saved profile');
+
+function cachedReadsStayInAggregates() {
+ let library, now = 0;
+ const context = vm.createContext({
+ performance: {timeOrigin: 1000, now: () => now},
+ _browser_profile_configuration: () => '1:test:0:7', _pthread_self: () => 7,
+ UTF8ToString: value => value, setInterval: () => {},
+ BroadcastChannel: class { postMessage() {} },
+ addToLibrary: value => { library = value; }
+ });
+ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context);
+ context.AOProfile = library.$AOProfile;
+
+ const start = library.ao_profile_begin('file read');
+ now = 0.01;
+ library.ao_profile_end('file read', start, 0);
+
+ assert.equal(context.AOProfile.events.length, 0);
+ assert.equal(context.AOProfile.metrics['file read'].count, 1);
+ assert.ok(context.AOProfile.metrics['file read'].ms > 0);
+}
+
+cachedReadsStayInAggregates();
+console.log('PASS: tiny cached reads are counted without flooding the detailed trace');
+
+function busyWorkersFlushWithoutJSTimers() {
+ let library, now = 0;
+ const sent = [];
+ const context = vm.createContext({
+ performance: {timeOrigin: 1000, now: () => now},
+ _browser_profile_configuration: () => '0:test:0:7', _pthread_self: () => 7,
+ UTF8ToString: value => value, setInterval: () => {},
+ BroadcastChannel: class { postMessage(value) { sent.push(value); } },
+ addToLibrary: value => { library = value; }
+ });
+ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context);
+ context.AOProfile = library.$AOProfile;
+
+ const mix = library.ao_profile_begin('audio mix');
+ now = 1001;
+ library.ao_profile_end('audio mix', mix, 0);
+ const decode = library.ao_profile_begin('sound load/decode');
+ now = 1002;
+ library.ao_profile_end('sound load/decode', decode, 0);
+
+ assert.equal(sent.length, 2);
+ assert.equal(sent[0].metrics['audio mix'].count, 1);
+ assert.equal(sent[1].metrics['sound load/decode'].ms, 1);
+ assert.equal(sent[0].events.length, 0);
+}
+
+busyWorkersFlushWithoutJSTimers();
+console.log('PASS: busy and short-lived audio workers deliver aggregates without JS timer callbacks');
diff --git a/src/tests/browser_resource_prefetch.mjs b/src/tests/browser_resource_prefetch.mjs
@@ -14,7 +14,8 @@ for (const [entry, identity, offset] of [[0,17,64],[1,18,128],[2,19,192],
const database = Uint8Array.from({length:512}, (_, i) => i % 251);
const requests = [], pending = new Map(), warnings = [];
let library, ready = 0;
-const context = vm.createContext({Map, Set, URL, Response, Uint8Array, DataView,
+const context = vm.createContext({
+ AOProfile: {begin: () => 0, end: () => {}},Map, Set, URL, Response, Uint8Array, DataView,
HEAPU8:new Uint8Array(64), AOResourcePrefetch:{}, wasmFS$backends:{},
console:{warn:(...args) => warnings.push(args)},
_browser_prefetch_resource_ready:() => ++ready,
diff --git a/tools/client/publish_wasm.py b/tools/client/publish_wasm.py
@@ -15,7 +15,7 @@ staging = root / 'src/build/wasm/publish'
staging.mkdir(exist_ok=True)
# Publish one matching JS/WASM pair; gzip keeps the binary small enough for Git.
-for name in ['game.js', 'index.html']:
+for name in ['game.js', 'index.html', 'profile-worker.js']:
shutil.copyfile(source / name, staging / name)
with (source / 'game.wasm').open('rb') as input_file:
with (staging / 'game.wasm.gz').open('wb') as output_file:
@@ -38,7 +38,7 @@ metadata = {
]).decode().splitlines()[0],
'files': {},
}
-for name in ['game.js', 'game.wasm.gz', 'index.html']:
+for name in ['game.js', 'game.wasm.gz', 'index.html', 'profile-worker.js']:
path = staging / name
metadata['files'][name] = {
'bytes': path.stat().st_size,
diff --git a/tools/client/read_profile.py b/tools/client/read_profile.py
@@ -0,0 +1,55 @@
+"""Summarize a gameplay profile and export its detailed Chrome Trace timeline."""
+import collections
+import json
+import pathlib
+import sys
+
+path = pathlib.Path(sys.argv[1])
+events = []
+metrics = {}
+functions = collections.Counter()
+phases = collections.Counter()
+frames = 0
+frame_ms = 0
+stalls = 0
+dropped = 0
+builds = set()
+
+# Summaries are weighted by their actual frame count, including loading frames.
+with path.open() as source:
+ for line in source:
+ batch = json.loads(line)
+ builds.add(batch['build'])
+ frames += batch['frames']['count']
+ frame_ms += batch['frames']['count'] * batch['frames']['mean']
+ stalls += batch['frames']['over100']
+ dropped += batch['dropped']
+ for name, value in batch['metrics'].items():
+ metric = metrics.setdefault(name, {'count': 0, 'ms': 0, 'max': 0})
+ metric['count'] += value['count']
+ metric['ms'] += value['ms']
+ metric['max'] = max(metric['max'], value['max'])
+ for event in batch['traceEvents']:
+ if event['name'] == 'guest sample':
+ phase = event['args']['phase']
+ phases[phase] += 1
+ address = event['args']['function']
+ event['name'] = f'sub_{address:08X} (wall sample, phase {phase})'
+ # Exclude explicit pacing and I/O; other unmarked host waits can remain.
+ if phase in (0, 2):
+ functions[address] += 1
+ events.append(event)
+
+print('Builds:', ', '.join(str(build) for build in builds))
+print(f'Frames: {frames}; mean interval: {frame_ms / frames if frames else 0:.2f} ms; '
+ f'over 100 ms: {stalls}; dropped observations: {dropped}')
+for name, metric in sorted(metrics.items(), key=lambda item: -item[1]['ms']):
+ print(f"{name}: {metric['count']} calls, {metric['ms']:.1f} ms total, {metric['max']:.1f} ms maximum")
+print('Wall-time sample phases (0 guest/host, 1 RAF, 2 render, 3 file, 4 setup, 5 other):', dict(phases))
+print('Guest/render residency samples, NOT CPU self-time:')
+for address, count in functions.most_common(20):
+ print(f' sub_{address:08X}: {count}')
+if events:
+ output = path.with_suffix('.trace.json')
+ output.write_text(json.dumps({'traceEvents': events}, separators=(',', ':')) + '\n')
+ print('Timeline:', output)