aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/client/sweep_browser.py (13172B)


      1 """Run an isolated WASM sweep; open the printed URL and press Start WASM sweep."""
      2 import base64
      3 import hashlib
      4 import http.server
      5 import json
      6 import pathlib
      7 import re
      8 import shutil
      9 import socket
     10 import subprocess
     11 import sys
     12 import time
     13 import urllib.parse
     14 import urllib.request
     15 
     16 root = pathlib.Path(__file__).resolve().parents[2]
     17 sys.path.insert(0, str(root))
     18 import tools.client.playfield_catalog
     19 import tools.client.server_fixture
     20 
     21 work = root / 'local/playfield-sweep'
     22 assert len(sys.argv) <= 2, 'usage: sweep_browser.py [previous-run-directory]'
     23 resuming = len(sys.argv) == 2
     24 output = pathlib.Path(sys.argv[1]).resolve() if resuming else work / ('wasm-sweep-' + time.strftime('%Y%m%d-%H%M%S'))
     25 build = work / 'browser-build'
     26 assert (build / 'sweep-game.wasm').exists(), 'Build objects and run build_browser_sweep.py first'
     27 for port in [7520, 7521, 8082, 8083]:
     28     with socket.socket() as connection:
     29         assert connection.connect_ex(('127.0.0.1', port)) != 0, port
     30 # Embed the sweep client and pages only in this isolated test binary.
     31 overlay = work / 'browser-server-overlay.json'
     32 overlay.write_text(json.dumps({'Replace': {
     33     str(root / 'server/assets/client' / name): str(source)
     34     for name, source in [
     35         ('sweep-game.js', build / 'sweep-game.js'),
     36         ('sweep-game.wasm', build / 'sweep-game.wasm'),
     37         ('sweep.html', root / 'tools/client/sweep_browser.html'),
     38         ('sweep-client.html', root / 'tools/client/sweep_browser_client.html'),
     39     ]
     40 }}))
     41 subprocess.run(['go', 'build', '-tags', 'embedassets', '-overlay', str(overlay), '-o', str(work / 'server'), './server'], cwd=root, check=True)
     42 
     43 # The browser copies preferences into private WASM memory; HTTP assets are read-only.
     44 fixture = output / 'server'
     45 if not resuming:
     46     (fixture / 'data').mkdir(parents=True)
     47     (fixture / 'client').mkdir()
     48     (fixture / 'anarchy-assets-14.9.1').symlink_to(root / 'anarchy-assets-14.9.1')
     49     tools.client.server_fixture.create_player(fixture, 'WASM Sweep', [0, 0, 0, 1])
     50     for name in ['sweep-game.js', 'sweep-game.wasm']:
     51         shutil.copyfile(build / name, fixture / 'client' / name)
     52     shutil.copyfile(build / 'build.json', output / 'client-build.json')
     53 for source, target in [('sweep_browser.html', 'sweep.html'), ('sweep_browser_client.html', 'sweep-client.html')]:
     54     shutil.copyfile(root / 'tools/client' / source, fixture / 'client' / target)
     55 
     56 catalog = tools.client.playfield_catalog.read(root, fixture / 'anarchy-assets-14.9.1')
     57 priority = [120, 127, 1931, 4107, 152, 124, 641, 706, 4704, 705, 695]
     58 zones = sorted([row for row in catalog if 'skip' not in row], key=lambda row: (priority.index(row['id']) if row['id'] in priority else len(priority), row['id']))
     59 with (fixture / 'client/sweep-game.wasm').open('rb') as module:
     60     module_hash = hashlib.file_digest(module, 'sha256').hexdigest()
     61 assert json.loads((output / 'client-build.json').read_text())['module_sha256'] == module_hash
     62 metadata = {
     63     'source_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip(),
     64     'working_diff': subprocess.check_output(['git', 'diff', 'HEAD'], cwd=root, text=True),
     65     'module_sha256': module_hash, 'started': time.time(), 'client': 'WASM/WebGL browser',
     66     'coverage': 'CharacterReady, ten seconds and 30 presented frames, turn/walk, server pose and screenshot; screenshots require visual review',
     67     'resume_behavior': 'fresh browser client at the first unfinished playfield',
     68 }
     69 completed = {}
     70 if resuming:
     71     assert json.loads((output / 'catalog.json').read_text()) == catalog
     72     assert json.loads((output / 'build.json').read_text())['module_sha256'] == module_hash
     73     if (output / 'results.jsonl').exists():
     74         for line in (output / 'results.jsonl').read_text().splitlines():
     75             row = json.loads(line)
     76             completed[row['phase'], row['id']] = row
     77     (output / ('resume-' + time.strftime('%Y%m%d-%H%M%S') + '.json')).write_text(json.dumps(metadata, indent=2) + '\n')
     78 else:
     79     (output / 'build.json').write_text(json.dumps(metadata, indent=2) + '\n')
     80     (output / 'catalog.json').write_text(json.dumps(catalog, indent=2) + '\n')
     81 queue = [(phase, zone) for phase in ['transition', 'cold'] for zone in zones if (phase, zone['id']) not in completed]
     82 for zone in reversed(zones):
     83     previous = completed.get(('transition', zone['id']))
     84     if previous and previous['status'] != 'ready-and-rendering' and ('cold-repro', zone['id']) not in completed:
     85         queue.insert(0, ('cold-repro', zone))
     86 active = None
     87 instance = 0
     88 need_launch = True
     89 disconnect_started = None
     90 
     91 
     92 admin = tools.client.server_fixture.admin_opener(fixture)
     93 
     94 
     95 def request(path, fields=None):
     96     data = urllib.parse.urlencode(fields).encode() if fields is not None else None
     97     return admin.open('http://127.0.0.1:8082' + path, data, timeout=10).read()
     98 
     99 
    100 def character_pose():
    101     # Live pose comes from the player feed.
    102     player = next(player for player in json.loads(request('/admin/map-players?offline=1'))['players'] if player['id'] == 73)
    103     return {field: player[field] for field in ['position', 'rotation']}
    104 
    105 
    106 def tick(message):
    107     global active, instance, need_launch, disconnect_started
    108     player = json.loads(request('/admin/map-players?offline=1'))['players'][0]
    109     if active is None:
    110         if not queue:
    111             return {'action': 'done'}
    112         phase, zone = queue[0]
    113         need_launch = need_launch or phase != 'transition'
    114         if need_launch and player['connected']:
    115             if disconnect_started is None:
    116                 disconnect_started = time.time()
    117             assert time.time() - disconnect_started < 10, 'server did not observe browser disconnect'
    118             return {'action': 'unload'}
    119         disconnect_started = None
    120         queue.pop(0)
    121         log_start = (fixture / 'logs/server.log').stat().st_size
    122         request('/admin/players/73/teleport', {'playfield': zone['id']})
    123         request('/admin/time', {'hour': 13, 'minute': 30})
    124         active = dict(zone, phase=phase, started=time.time(), status='loading',
    125             server_log_start=log_start, cold_start=need_launch, user_agent=message['user_agent'])
    126         if need_launch:
    127             instance += 1
    128             need_launch = False
    129             active['instance'] = instance
    130             return {'action': 'launch', 'instance': instance, 'id': zone['id'], 'phase': phase}
    131         active['instance'] = instance
    132         player = json.loads(request('/admin/map-players?offline=1'))['players'][0]
    133 
    134     # Main-page heartbeats remain responsive even if the game worker faults or blocks.
    135     assert message['instance'] == instance
    136     elapsed = time.time() - active['started']
    137     if message['error']:
    138         active.update(status='client-error', error=message['error'])
    139     elif elapsed >= 180:
    140         active['status'] = 'timeout'
    141     elif 'ready_time' in active and player['playfield'] != active['id']:
    142         active.update(status='zoned-during-movement', destination=player['playfield'])
    143     if active['status'] not in ['loading', 'ready', 'capturing']:
    144         return {'action': 'finish', 'id': active['id'], 'status': active['status']}
    145 
    146     if 'ready_time' not in active and player['connected'] and player['playfield'] == active['id']:
    147         with (fixture / 'logs/server.log').open('rb') as log:
    148             log.seek(active['server_log_start'])
    149             received = log.read()
    150         if re.search(rb'World C2S: dfdf000a[0-9a-f]{24}570c20390000c3500000004901', received):
    151             active.update(status='ready', ready_time=time.time(), ready_seconds=elapsed,
    152                 input_before=character_pose(), character_ready=True)
    153     if 'ready_time' in active:
    154         if message['frame_time'] / 1000 >= active['ready_time']:
    155             if 'first_frame' not in active:
    156                 active['first_frame'] = {'frames': message['frames'], 'time': message['frame_time'] / 1000}
    157             active['last_frame'] = {'frames': message['frames'], 'time': message['frame_time'] / 1000}
    158         if message['input'] is None:
    159             return {'action': 'input', 'id': active['id'], 'phase': active['phase']}
    160         if 'first_frame' in active:
    161             duration = active['last_frame']['time'] - active['first_frame']['time']
    162             frames = active['last_frame']['frames'] - active['first_frame']['frames']
    163             if duration >= 10 and frames >= 30:
    164                 if active['status'] != 'capturing':
    165                     active.update(status='capturing', capture_started=time.time(), frames=frames, fps=frames / duration)
    166                 if time.time() - active['capture_started'] > 10:
    167                     active['status'] = 'capture-timeout'
    168                     return {'action': 'finish', 'id': active['id'], 'status': active['status']}
    169                 return {'action': 'capture', 'id': active['id'], 'phase': active['phase']}
    170     return {'action': 'wait', 'id': active['id'], 'phase': active['phase'], 'elapsed': round(elapsed, 1)}
    171 
    172 
    173 def finish(message):
    174     global active, need_launch
    175     assert active is not None and message['instance'] == instance
    176     name = f'{active["phase"]}-{active["id"]}'
    177     if message['screenshot'] is not None:
    178         pixels = base64.b64decode(message['screenshot'], validate=True)
    179         assert pixels.startswith(b'\x89PNG\r\n\x1a\n')
    180         (output / (name + '.png')).write_bytes(pixels)
    181         active['screenshot'] = name + '.png'
    182         assert active['status'] == 'capturing'
    183         active['status'] = 'ready-and-rendering'
    184     active.update(elapsed_seconds=time.time() - active['started'], log=name + '.log')
    185     (output / active['log']).write_text(message['log'])
    186     if 'input_before' in active:
    187         active['input_after'] = character_pose()
    188         active['input_events'] = message['input']
    189         active['movement_observed'] = sum((active['input_before']['position'][axis]
    190             - active['input_after']['position'][axis]) ** 2 for axis in [0, 2]) > .01
    191         active['rotation_observed'] = abs(sum(a * b for a, b in zip(
    192             active['input_before']['rotation'], active['input_after']['rotation']))) < .999
    193     with (output / 'results.jsonl').open('a') as results:
    194         results.write(json.dumps(active) + '\n')
    195     print(json.dumps(active), flush=True)
    196     if active['status'] != 'ready-and-rendering':
    197         need_launch = True
    198         if active['phase'] == 'transition' and ('cold-repro', active['id']) not in completed:
    199             queue.insert(0, ('cold-repro', {'id': active['id'], 'name': active['name']}))
    200     result = active
    201     active = None
    202     return result
    203 
    204 
    205 class Controller(http.server.BaseHTTPRequestHandler):
    206     def log_message(self, format, *args):
    207         pass
    208 
    209     def do_OPTIONS(self):
    210         self.respond({})
    211 
    212     def do_POST(self):
    213         if self.headers.get('Origin') != 'http://127.0.0.1:8082':
    214             self.send_error(403)
    215             return
    216         size = int(self.headers['Content-Length'])
    217         assert 0 < size < 16 * 1024 * 1024
    218         message = json.loads(self.rfile.read(size))
    219         if self.path == '/tick':
    220             self.respond(tick(message))
    221         elif self.path == '/finish':
    222             self.respond(finish(message))
    223         else:
    224             self.send_error(404)
    225 
    226     def respond(self, result):
    227         body = json.dumps(result).encode()
    228         self.send_response(200)
    229         self.send_header('Access-Control-Allow-Origin', 'http://127.0.0.1:8082')
    230         self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
    231         self.send_header('Access-Control-Allow-Headers', 'Content-Type')
    232         self.send_header('Content-Type', 'application/json')
    233         self.send_header('Content-Length', str(len(body)))
    234         self.end_headers()
    235         self.wfile.write(body)
    236 
    237 
    238 with (output / 'server.log').open('a') as server_log:
    239     inhibitor = subprocess.Popen(['gnome-session-inhibit', '--reason', 'AO WASM playfield coverage', '--inhibit-only'], stdout=server_log, stderr=server_log)
    240     server = subprocess.Popen([str(work / 'server'), '-trace', '-login-port', '7520', '-world-port', '7521', '-http-port', '8082'], cwd=fixture, stdout=server_log, stderr=server_log)
    241     try:
    242         subprocess.run(['xset', 'dpms', 'force', 'on'], check=True)
    243         for attempt in range(60):
    244             assert server.poll() is None
    245             with socket.socket() as connection:
    246                 if connection.connect_ex(('127.0.0.1', 8082)) == 0:
    247                     break
    248             time.sleep(1)
    249         manifest = request('/browser-manifest').decode().splitlines()
    250         assert all(name in manifest for name in ['cd_image/', 'fonts/', 'version.id']), 'incomplete browser asset fixture'
    251         for name in ['cd_image', 'fonts', 'version.id']:
    252             request('/browser-assets/' + name)
    253         print(output, '\nOpen http://127.0.0.1:8082/wasm/sweep.html', flush=True)
    254         with http.server.HTTPServer(('127.0.0.1', 8083), Controller) as controller:
    255             controller.timeout = 1
    256             while True:
    257                 assert server.poll() is None
    258                 controller.handle_request()
    259     finally:
    260         server.terminate()
    261         server.wait(timeout=10)
    262         inhibitor.terminate()
    263         inhibitor.wait(timeout=10)