commit e4c27b1dfd2e042bec843651538086a2b8a3d823
parent dd687a0aa676b79117f5954aa8703f5fe144062e
Author: anon <anon@example.com>
Date: Thu, 5 Nov 2026 05:51:59 +0000
Disable verbose logging and browser profiling by default
Diffstat:
9 files changed, 124 insertions(+), 10 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -20,8 +20,11 @@ Distribute `ao-server` by itself (or the corresponding Windows binary). It can
run from an empty directory; static resources are served directly from the
binary. Mutable world state is stored in `data/world.sqlite` and certificates in
`data/https/`. Server logs go to `logs/server.log` and profiles to `logs/profiles/`.
-Packet, movement and HTTP request traces stay in `logs/server.log`; the terminal
-shows startup, connections and errors.
+By default, the terminal and log file contain startup/shutdown, player connections
+and errors. Pass `-trace` when debugging to also write packet, movement and HTTP
+request traces to `logs/server.log`.
+Browser profiling is also off by default; open the game with `?profile=1` to
+collect and upload a diagnostic profile.
Back up `data/` when moving servers. Paths are relative to the working directory.
The SQLite database contains character identity and credentials, stats, poses,
diff --git a/client/runtime/browser_profile.js b/client/runtime/browser_profile.js
@@ -83,6 +83,7 @@ addToLibrary({
ao_profile_start__proxy: 'sync',
ao_profile_start: (currentFunction, phase, thread) => {
const detailed = new URLSearchParams(location.search).get('profile') === '1';
+ if (!detailed) return 0;
const session = crypto.randomUUID();
let worker;
try {
diff --git a/client/tests/browser_profile.mjs b/client/tests/browser_profile.mjs
@@ -83,6 +83,45 @@ await boundedSamplingAndFailedUpload();
await slowUploadDoesNotAccumulateRequests();
console.log('PASS: gameplay profile summaries, sampling, queue bounds and failed/slow uploads');
+// Normal play starts no worker, timers or collection channel.
+for (const search of ['', '?profile=0', '?profile=other']) {
+ let library;
+ const context = vm.createContext({
+ addToLibrary: value => { library = value; }, URLSearchParams,
+ location: {search}, _browser_profile_configuration: () => 0
+ });
+ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context);
+ context.AOProfile = library.$AOProfile;
+ assert.equal(library.ao_profile_start(4, 8, 7), 0);
+ assert.equal(context.AOProfile.begin('render scene'), 0);
+ context.AOProfile.frame();
+ context.AOProfile.flush();
+ assert.equal(context.AOProfile.events.length, 0);
+ assert.equal(context.AOProfile.frames.length, 0);
+ assert.equal(Object.keys(context.AOProfile.metrics).length, 0);
+}
+
+// Explicit opt-in starts the collector with the detailed configuration.
+{
+ let library;
+ const workers = [], messages = [];
+ const context = vm.createContext({
+ addToLibrary: value => { library = value; }, URLSearchParams, URL,
+ location: {search: '?profile=1'}, crypto: {randomUUID: () => 'test'},
+ Worker: class { constructor(url) { workers.push(url.pathname); } postMessage(message) { messages.push(message); } },
+ BroadcastChannel: class {}, wasmMemory: {buffer: new SharedArrayBuffer(64)},
+ document: {baseURI: 'https://example.test/', visibilityState: 'visible', addEventListener() {}},
+ navigator: {userAgent: 'test'}, Module: {canvas: {width: 640, height: 480}},
+ performance: {timeOrigin: 1000, now: () => 10}, stringToNewUTF8: value => value
+ });
+ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context);
+ assert.equal(library.ao_profile_start(4, 8, 7), '1:test:8:7');
+ assert.deepEqual(workers, ['/wasm/profile-worker.js']);
+ assert.equal(messages.length, 1);
+ assert.equal(messages[0].init.detailed, true);
+}
+console.log('PASS: profiling stays off until explicitly enabled');
+
async function clientSpansRestorePhases() {
let library, now = 0;
const sent = [];
diff --git a/server/logging_test.go b/server/logging_test.go
@@ -0,0 +1,55 @@
+package main
+
+import (
+ "bytes"
+ "io"
+ "log"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestPlayerLogsStayHighLevelWithOptionalTraces(t *testing.T) {
+ for _, tracing := range []bool{false, true} {
+ t.Run(map[bool]string{false: "default", true: "trace"}[tracing], func(t *testing.T) {
+ world := newCheckpointWorld(t)
+ var operational, trace bytes.Buffer
+ previousLog, previousTrace := log.Writer(), traceLog.Writer()
+ log.SetOutput(&operational)
+ traceLog.SetOutput(io.Discard)
+ if tracing {
+ traceLog.SetOutput(&trace)
+ }
+ t.Cleanup(func() {
+ log.SetOutput(previousLog)
+ traceLog.SetOutput(previousTrace)
+ })
+ input := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
+ for range 20 {
+ input = append(input, npcMovementPacket(world.characters[1], 1)...)
+ input = append(input, npcMovementPacket(world.characters[1], 2)...)
+ }
+ connection := &combatInterestConn{input: bytes.NewReader(input)}
+
+ if err := world.serveWorldClient(&worldClient{conn: connection}); err != nil {
+ t.Fatal(err)
+ }
+ world.httpHandler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/missing", nil))
+
+ if strings.Count(operational.String(), "\n") != 2 ||
+ !strings.Contains(operational.String(), `Player connected: "Explorer" (character 1)`) ||
+ !strings.Contains(operational.String(), `Player disconnected: "Explorer" (character 1)`) {
+ t.Fatal("unexpected operational log", operational.String())
+ }
+ if tracing {
+ for _, message := range []string{"World C2S:", "World S2C:", "Character 1 action=1 position=", "HTTP GET /missing"} {
+ if !strings.Contains(trace.String(), message) {
+ t.Fatal("missing diagnostic trace", message)
+ }
+ }
+ } else if trace.Len() != 0 {
+ t.Fatal("trace output enabled by default", trace.String())
+ }
+ })
+ }
+}
diff --git a/server/main.go b/server/main.go
@@ -19,7 +19,7 @@ import (
"time"
)
-// Protocol and movement traces are written only to the server log file.
+// Detailed traces are disabled unless explicitly enabled at startup.
var traceLog = log.New(io.Discard, "", log.LstdFlags)
func main() {
@@ -27,6 +27,7 @@ func main() {
worldPort := flag.Int("world-port", 7501, "world port")
httpPort := flag.Int("http-port", 8080, "HTTP and admin port")
baseURL := flag.String("base-url", "/", "URL path prefix (must start and end with /)")
+ trace := flag.Bool("trace", false, "write packet, movement and HTTP traces to logs/server.log")
flag.Parse()
if !strings.HasPrefix(*baseURL, "/") || !strings.HasSuffix(*baseURL, "/") ||
(*baseURL != "/" && path.Clean(*baseURL)+"/" != *baseURL) || strings.ContainsAny(*baseURL, "?#\\%") {
@@ -40,7 +41,7 @@ func main() {
if *worldPort == 65535 || *worldPort+1 == *loginPort || *worldPort+1 == *httpPort || *worldPort+1 == 8443 {
log.Fatal("the port immediately after the world port must be available for chat")
}
- // Keep operational logs in the terminal and file, and detailed traces in the file.
+ // Keep operational logs in the terminal and file; traces require an explicit flag.
if err := os.MkdirAll("logs", 0755); err != nil {
log.Fatal(err)
}
@@ -50,7 +51,9 @@ func main() {
}
defer logFile.Close()
log.SetOutput(io.MultiWriter(os.Stderr, logFile))
- traceLog.SetOutput(logFile)
+ if *trace {
+ traceLog.SetOutput(logFile)
+ }
if err := prepareHTTPS(); err != nil {
log.Fatal(err)
@@ -78,6 +81,7 @@ func main() {
signal.Notify(stopping, os.Interrupt, syscall.SIGTERM)
go func() {
<-stopping
+ log.Print("Server shutting down")
server.updateMutex.Lock()
if err := server.flushPositions(time.Now().Add(20 * time.Second)); err != nil {
log.Printf("Saving positions on shutdown: %v", err)
@@ -241,7 +245,6 @@ func (server *server) serveWorld() {
}
go func() {
defer conn.Close()
- log.Print("World connection opened")
if err := server.serveWorldConnection(conn); err != nil {
log.Printf("World connection: %v", err)
}
@@ -357,6 +360,8 @@ func (server *server) serveWorldClient(client *worldClient) error {
character.movement = playerMovement{}
character.body = playerCollisionBody{}
server.clients[character.id] = client
+ log.Printf("Player connected: %q (character %d)", character.name, character.id)
+ defer log.Printf("Player disconnected: %q (character %d)", character.name, character.id)
now := time.Now()
for index := range character.activeNanos {
if character.activeNanos[index].expiresAt.IsZero() {
diff --git a/tools/client/sweep_browser.py b/tools/client/sweep_browser.py
@@ -237,7 +237,7 @@ class Controller(http.server.BaseHTTPRequestHandler):
with (output / 'server.log').open('a') as server_log:
inhibitor = subprocess.Popen(['gnome-session-inhibit', '--reason', 'AO WASM playfield coverage', '--inhibit-only'], stdout=server_log, stderr=server_log)
- server = subprocess.Popen([str(work / 'server'), '-login-port', '7520', '-world-port', '7521', '-http-port', '8082'], cwd=fixture, stdout=server_log, stderr=server_log)
+ server = subprocess.Popen([str(work / 'server'), '-trace', '-login-port', '7520', '-world-port', '7521', '-http-port', '8082'], cwd=fixture, stdout=server_log, stderr=server_log)
try:
subprocess.run(['xset', 'dpms', 'force', 'on'], check=True)
for attempt in range(60):
diff --git a/tools/client/sweep_playfields.py b/tools/client/sweep_playfields.py
@@ -217,7 +217,7 @@ def run_zone(zone, phase):
# Own all test processes, character data and logs; preserve the user's server state.
with (output / 'server.log').open('a') as server_log:
inhibitor = subprocess.Popen(['gnome-session-inhibit', '--reason', 'AO playfield coverage', '--inhibit-only'], stdout=server_log, stderr=server_log)
- server = subprocess.Popen([str(work / 'server'), '-login-port', '7520', '-world-port', '7521', '-http-port', '8082'], cwd=fixture, stdout=server_log, stderr=server_log)
+ server = subprocess.Popen([str(work / 'server'), '-trace', '-login-port', '7520', '-world-port', '7521', '-http-port', '8082'], cwd=fixture, stdout=server_log, stderr=server_log)
try:
subprocess.run(['xset', 'dpms', 'force', 'on'], check=True)
for attempt in range(60):
diff --git a/tools/client/test_admin.mjs b/tools/client/test_admin.mjs
@@ -13,6 +13,10 @@ let game;
try {
const context = await browser.newContext({viewport: {width: 1280, height: 900}, hasTouch: true});
const page = await context.newPage();
+ const profileRequests = [];
+ context.on('request', request => {
+ if (request.url().includes('/browser-profile/')) profileRequests.push(request.url());
+ });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
@@ -121,10 +125,17 @@ try {
assert.equal(await page.getByLabel('Conditions', {exact: true}).locator('option', {hasText: 'Automatic'}).count(), 0);
await game.save(output + '/game');
+ assert.equal(profileRequests.length, 0);
+ assert.equal(client.workers().filter(worker => worker.url().includes('profile-worker.js')).length, 0);
+ const uploaded = client.waitForResponse(response => response.url().includes('/browser-profile/') && response.status() === 204);
+ await client.goto(url + '?profile=1');
+ await uploaded;
+ assert(profileRequests.length > 0);
+
assert(mapResponses.every(response => response.npcs.length <= 500 && response.warps.length <= 500));
assert.deepEqual(errors, []);
assert.equal(game.errors.length, 0);
- console.log('PASS: admin account creation/password pages, login/logout, expanding SQL table/CSV, responsive touch map, native weather packets and rendered frames');
+ console.log('PASS: admin account creation/password pages, login/logout, expanding SQL table/CSV, responsive touch map, native weather, profiling off by default and explicit opt-in');
} finally {
await browser.close();
}
diff --git a/tools/client/verify_linux_game.py b/tools/client/verify_linux_game.py
@@ -39,7 +39,7 @@ def run_linux():
(fixture / 'logs').mkdir(exist_ok=True)
(fixture / 'logs/server.log').write_text('')
with (output / 'server.log').open('w') as log:
- server = subprocess.Popen([str(fixture / 'server')], cwd=fixture,
+ server = subprocess.Popen([str(fixture / 'server'), '-trace'], cwd=fixture,
stdout=log, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 10