341aa98a96
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
330 lines
14 KiB
Python
330 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Play with friends end to end, without the internet.
|
|
|
|
A relay (`horizon-relay`) on a free local port; a host Horizon that opens a
|
|
world and shares it behind an invite code (`friends host`); a guest Horizon
|
|
that joins with the code (`connect friend:CODE`). The guest joins twice:
|
|
first on the direct path, then started with HORIZON_FRIENDS_PATH=relay so
|
|
the session goes through the relay. Each time both sides must see the
|
|
other's chat line, the other moving, a block the host places and the block
|
|
the guest breaks; the host's counts say which path each session took, and
|
|
the relay's relayed bytes must stay small for the direct session and grow
|
|
with the relayed one. Last, the host stops sharing and a guest using the
|
|
old code is told the invite has ended.
|
|
|
|
python3 tools/test_friends.py --client target/fast/horizon-client --relay target/fast/horizon-relay
|
|
|
|
`--relay-url HOST:PORT` uses a relay already running elsewhere (two
|
|
machines); `--role host|guest` then runs one side only and prints or takes
|
|
the code (`--code`). Needs a display on Linux (xvfb-run -a).
|
|
"""
|
|
import argparse
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import socket
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
import urllib.request
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def command(endpoint, line, check=True):
|
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
|
connection.settimeout(60)
|
|
connection.connect(str(endpoint))
|
|
connection.sendall((line + '\n').encode())
|
|
with connection.makefile('r') as reply:
|
|
result = json.loads(reply.readline())
|
|
if check:
|
|
assert 'error' not in result, (line, result)
|
|
return result
|
|
|
|
|
|
def wait_for(endpoint, line, predicate, timeout=60, what=None):
|
|
deadline = time.monotonic() + timeout
|
|
last = None
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
last = command(endpoint, line, check=False)
|
|
except (FileNotFoundError, ConnectionRefusedError):
|
|
time.sleep(0.1)
|
|
continue
|
|
try:
|
|
if predicate(last):
|
|
return last
|
|
except (KeyError, TypeError, IndexError):
|
|
pass
|
|
time.sleep(0.1)
|
|
raise AssertionError(f'timed out waiting for {what or line}: {last}')
|
|
|
|
|
|
def free_port():
|
|
with socket.socket() as s:
|
|
s.bind(('127.0.0.1', 0))
|
|
return s.getsockname()[1]
|
|
|
|
|
|
def health(relay_url):
|
|
with urllib.request.urlopen(f'http://{relay_url}/health', timeout=5) as r:
|
|
return json.loads(r.read())
|
|
|
|
|
|
class Game:
|
|
"""A Horizon client with a control socket in its own home."""
|
|
|
|
def __init__(self, client, resources, work, name, env):
|
|
self.home = work / name
|
|
self.home.mkdir()
|
|
self.endpoint = self.home / 'c.sock'
|
|
self.log = (self.home / 'client.log').open('w+')
|
|
self.process = subprocess.Popen([
|
|
str(client), '--resources', str(resources), '--render-distance', '2', '--test-terrain',
|
|
'--control-socket', str(self.endpoint), '--timeout-seconds', '600',
|
|
], cwd=self.home, env=dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_NO_AUDIO='1', **env),
|
|
stdout=self.log, stderr=subprocess.STDOUT)
|
|
wait_for(self.endpoint, 'screen', lambda v: v['screen'] == 'title', 120, f'{name} title')
|
|
|
|
def __call__(self, line, check=True):
|
|
return command(self.endpoint, line, check)
|
|
|
|
def wait(self, line, predicate, timeout=60, what=None):
|
|
return wait_for(self.endpoint, line, predicate, timeout, what)
|
|
|
|
def stop(self):
|
|
if self.process.poll() is None:
|
|
try:
|
|
self('quit', check=False)
|
|
self.process.wait(timeout=20)
|
|
except Exception:
|
|
self.process.terminate()
|
|
try:
|
|
self.process.wait(timeout=10)
|
|
except subprocess.TimeoutExpired:
|
|
self.process.kill()
|
|
self.log.seek(0)
|
|
return self.log.read()
|
|
|
|
|
|
def host_world(host):
|
|
host('open Friends 0 creative')
|
|
host.wait('status', lambda v: v['player'] is not None and v['pending_chunks'] == 0, 120, 'host world')
|
|
assert host('friends status')['available'], 'HORIZON_RELAY_URL did not reach the host'
|
|
host('friends host')
|
|
return host.wait('friends status', lambda v: v['code'], 30, 'invite code')['code']
|
|
|
|
|
|
def guest_pos(host, name):
|
|
guests = host('lan status')['guests']
|
|
return next(g['position'] for g in guests if g['name'] == name)
|
|
|
|
|
|
def play_together(host, guest, name, round_index):
|
|
"""Chat, movement and blocks seen from both sides."""
|
|
host.wait('lan status', lambda v: any(g['name'] == name and g['placed'] for g in v['guests']), 60,
|
|
'the guest in the host world')
|
|
guest.wait('status', lambda v: v['server']['joined'] and v['player'] is not None, 60, 'guest joined')
|
|
# Chat both ways.
|
|
guest(f'chat hello from {name} {round_index}')
|
|
host.wait('chat-log 20', lambda v: any(f'hello from {name} {round_index}' in l for l in v['chat']), 30,
|
|
'guest chat on the host')
|
|
host(f'chat hello from the host {round_index}')
|
|
guest.wait('status', lambda v: any(f'hello from the host {round_index}' in l for l in v['server']['chat']), 30,
|
|
'host chat on the guest')
|
|
# The guest walks; the host sees it move.
|
|
before = guest_pos(host, name)
|
|
guest('look 0 0')
|
|
guest('key w down')
|
|
time.sleep(1.5)
|
|
guest('key w up')
|
|
host.wait('lan status', lambda v: math.dist(before, next(g['position'] for g in v['guests'] if g['name'] == name)) > 1.0,
|
|
20, 'guest movement on the host')
|
|
# The host moves; the guest sees the host's player there.
|
|
hp = host('status')['player']['position']
|
|
target = [hp[0] + 3.0, hp[1], hp[2] + 1.0]
|
|
host(f'tp {target[0]} {target[1]} {target[2]}')
|
|
guest.wait('status', lambda v: any(math.dist(p, target) < 0.6 for p in v['server']['player_positions']), 20,
|
|
'host movement on the guest')
|
|
# A block the host places, which the guest sees and then breaks.
|
|
gp = guest('status')['player']['position']
|
|
feet = [math.floor(gp[0]), math.floor(gp[1]), math.floor(gp[2])]
|
|
block = [feet[0] + 2, feet[1] + 1, feet[2]]
|
|
# Clear the line of sight (the test terrain has hills), then the block at eye level.
|
|
host(f'fill {feet[0] + 1} {feet[1]} {feet[2]} {feet[0] + 1} {feet[1] + 2} {feet[2]} minecraft:air')
|
|
host(f'setblock {block[0]} {block[1]} {block[2]} minecraft:gold_block')
|
|
guest.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:gold_block', 20,
|
|
'the host block on the guest')
|
|
eye = [gp[0], gp[1] + 1.62, gp[2]]
|
|
dx, dy, dz = block[0] + 0.5 - eye[0], block[1] + 0.5 - eye[1], block[2] + 0.5 - eye[2]
|
|
yaw = math.degrees(math.atan2(-dx, dz))
|
|
pitch = -math.degrees(math.atan2(dy, math.hypot(dx, dz)))
|
|
guest(f'look {yaw:.3f} {pitch:.3f}')
|
|
guest.wait('status', lambda v: v['target']['pos'] == block, 10, 'the guest aiming at the block')
|
|
# Held for a few ticks, as a player clicks (creative breaks at once).
|
|
guest('mouse left down')
|
|
time.sleep(0.25)
|
|
guest('mouse left up')
|
|
host.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:air', 20,
|
|
'the guest breaking the block, on the host')
|
|
guest.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:air', 20,
|
|
'the broken block on the guest')
|
|
|
|
|
|
def join(guest, code, name):
|
|
guest(f'connect friend:{code} {name}')
|
|
|
|
|
|
def leave(host, guest, name):
|
|
guest('disconnect')
|
|
host.wait('lan status', lambda v: all(g['name'] != name for g in v['guests']), 30, 'the guest leaving')
|
|
|
|
|
|
def full(args, work, relay_url):
|
|
env = {'HORIZON_RELAY_URL': relay_url}
|
|
host = Game(args.client, args.resources, work, 'host', env)
|
|
games = [host]
|
|
try:
|
|
code = host_world(host)
|
|
print(f'host shares the world: {code[:4]}-****')
|
|
if args.baseline:
|
|
# The same checks over plain LAN, without the tunnel: the behaviour
|
|
# the tunnel must reproduce.
|
|
guest = Game(args.client, args.resources, work, 'guest-lan', env)
|
|
games.append(guest)
|
|
guest(f'connect 127.0.0.1:{host("lan status")["port"]} Plain')
|
|
play_together(host, guest, 'Plain', 0)
|
|
print('plain LAN: chat, movement and blocks both ways')
|
|
leave(host, guest, 'Plain')
|
|
guest.stop()
|
|
# Direct path.
|
|
guest = Game(args.client, args.resources, work, 'guest-direct', env)
|
|
games.append(guest)
|
|
before = health(relay_url)['relayed_bytes']
|
|
join(guest, code, 'Guest')
|
|
play_together(host, guest, 'Guest', 1)
|
|
direct_bytes = health(relay_url)['relayed_bytes'] - before
|
|
assert host('friends status')['direct'] == 1, host('friends status')
|
|
assert direct_bytes < 64 * 1024, f'the direct session went through the relay ({direct_bytes} bytes)'
|
|
print(f'direct path: chat, movement and blocks both ways; relay carried {direct_bytes} bytes')
|
|
leave(host, guest, 'Guest')
|
|
guest.stop()
|
|
# Forced relay path.
|
|
guest = Game(args.client, args.resources, work, 'guest-relay',
|
|
dict(env, HORIZON_FRIENDS_PATH='relay'))
|
|
games.append(guest)
|
|
before = health(relay_url)['relayed_bytes']
|
|
join(guest, code, 'Relayed')
|
|
play_together(host, guest, 'Relayed', 2)
|
|
relayed_bytes = health(relay_url)['relayed_bytes'] - before
|
|
status = host('friends status')
|
|
assert status['relayed'] == 1, status
|
|
# Render distance 2: the join is some tens of kB of compressed chunks.
|
|
assert relayed_bytes > max(32 * 1024, 4 * direct_bytes), \
|
|
f'the relayed session carried only {relayed_bytes} bytes (direct: {direct_bytes})'
|
|
print(f'relay path: chat, movement and blocks both ways; relay carried {relayed_bytes} bytes')
|
|
leave(host, guest, 'Relayed')
|
|
# The code ends with sharing.
|
|
host('friends stop')
|
|
assert host('friends status')['code'] is None
|
|
join(guest, code, 'Late')
|
|
reason = guest.wait('screen', lambda v: v['menu']['disconnected'], 30, 'the ended invite')['menu']['disconnected']
|
|
assert 'invite has ended' in reason, reason
|
|
print(f'after stopping: "{reason}"')
|
|
assert host('lan status') == {'open': False}, 'sharing opened LAN, so stopping closes it'
|
|
return code
|
|
except Exception:
|
|
for g in games:
|
|
print(f'--- {g.home.name} log tail ---')
|
|
print('\n'.join(g.stop().splitlines()[-25:]))
|
|
raise
|
|
finally:
|
|
for g in games:
|
|
g.stop()
|
|
|
|
|
|
def one_side(args, work):
|
|
env = {'HORIZON_RELAY_URL': args.relay_url}
|
|
if args.path:
|
|
env['HORIZON_FRIENDS_PATH'] = args.path
|
|
game = Game(args.client, args.resources, work, args.role, env)
|
|
try:
|
|
if args.role == 'host':
|
|
code = host_world(game)
|
|
print(f'CODE {code}', flush=True)
|
|
game.wait('lan status', lambda v: v['guests'], args.wait, 'a guest')
|
|
game.wait('lan status', lambda v: not v['guests'], args.wait, 'the guest leaving')
|
|
print(f'host: {game("friends status")}')
|
|
else:
|
|
join(game, args.code, 'Remote')
|
|
game.wait('status', lambda v: v['server']['joined'] and v['player'] is not None, 60, 'joined')
|
|
game('chat hello across machines')
|
|
v = game.wait('status', lambda v: v['server']['chunks'] > 0, 30, 'chunks')
|
|
print(f'guest joined: {v["server"]["address"]}, {v["server"]["chunks"]} chunks')
|
|
game('key w down')
|
|
time.sleep(1.0)
|
|
game('key w up')
|
|
time.sleep(args.hold)
|
|
game('disconnect')
|
|
finally:
|
|
game.stop()
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument('--client', type=Path, required=True)
|
|
parser.add_argument('--relay', type=Path, help='horizon-relay binary (started on a free local port)')
|
|
parser.add_argument('--relay-url', help='an already running relay, HOST:PORT')
|
|
parser.add_argument('--resources', type=Path, default=ROOT / '.local/horizon-client/26.3')
|
|
parser.add_argument('--role', choices=['host', 'guest'])
|
|
parser.add_argument('--code')
|
|
parser.add_argument('--path', choices=['relay', 'direct'])
|
|
parser.add_argument('--wait', type=float, default=600)
|
|
parser.add_argument('--hold', type=float, default=0, help='guest: stay this many seconds before leaving')
|
|
parser.add_argument('--baseline', action='store_true', help='first run the same checks over plain LAN')
|
|
args = parser.parse_args()
|
|
args.client, args.resources = args.client.resolve(), args.resources.resolve()
|
|
# Short: Unix socket paths are limited to about 100 bytes.
|
|
with tempfile.TemporaryDirectory(prefix='hzf-', dir='/tmp') as directory:
|
|
work = Path(directory)
|
|
if args.role:
|
|
assert args.relay_url, '--role needs --relay-url'
|
|
return one_side(args, work)
|
|
relay = None
|
|
relay_url = args.relay_url
|
|
if not relay_url:
|
|
assert args.relay, 'give --relay or --relay-url'
|
|
port = free_port()
|
|
relay_url = f'127.0.0.1:{port}'
|
|
relay_log = (work / 'relay.log').open('w+')
|
|
relay = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)),
|
|
stdout=relay_log, stderr=subprocess.STDOUT)
|
|
deadline = time.monotonic() + 10
|
|
while True:
|
|
try:
|
|
health(relay_url)
|
|
break
|
|
except OSError:
|
|
assert time.monotonic() < deadline, 'the relay did not start'
|
|
time.sleep(0.1)
|
|
try:
|
|
code = full(args, work, relay_url)
|
|
finally:
|
|
if relay:
|
|
relay.terminate()
|
|
relay.wait(timeout=10)
|
|
relay_log.seek(0)
|
|
text = relay_log.read()
|
|
print(f'relay log: {text.splitlines()}')
|
|
if relay:
|
|
# Counts only: no code, no address, no name.
|
|
for secret in [code[:4], '127.0.0.1', 'Guest', 'Relayed']:
|
|
assert secret not in text, f'the relay logged {secret!r}'
|
|
print('Play with friends passed: direct and relayed sessions, chat, movement and blocks both ways')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|