Merge main into feat/server-levels
game/lan.rs: #586's movement-check rules are set before the per-level passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+31
-5
@@ -44,6 +44,7 @@ import json
|
||||
import math
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import statistics
|
||||
@@ -185,19 +186,35 @@ def summary(values):
|
||||
return {"n": n, "mean": rnd(mean), "stdev": sd, "min": rnd(min(values)), "max": rnd(max(values)), "ci95": ci}
|
||||
|
||||
|
||||
def phys_footprint(pid):
|
||||
"""macOS: the bytes the kernel charges the process (`footprint`), without
|
||||
the freed pages the allocator marked reusable, which `ps` still counts as
|
||||
resident until memory runs short. None elsewhere."""
|
||||
if sys.platform != "darwin":
|
||||
return None
|
||||
out = subprocess.run(["footprint", "-f", "bytes", str(pid)], capture_output=True, text=True)
|
||||
m = re.search(r"phys_footprint:\s*(\d+)", out.stdout)
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
"""Samples a process's resident memory every quarter second (ps, so the
|
||||
same reading for every game and OS)."""
|
||||
same reading for every game and OS) and, on macOS, its physical footprint
|
||||
every two seconds."""
|
||||
|
||||
def __init__(self, pid):
|
||||
super().__init__(daemon=True)
|
||||
self.pid, self.samples, self.stop = pid, [], threading.Event()
|
||||
self.pid, self.samples, self.footprints, self.stop = pid, [], [], threading.Event()
|
||||
|
||||
def run(self):
|
||||
tick = 0
|
||||
while not self.stop.is_set():
|
||||
out = subprocess.run(["ps", "-o", "rss=", "-p", str(self.pid)], capture_output=True, text=True)
|
||||
if out.stdout.strip():
|
||||
self.samples.append((time.time(), int(out.stdout.split()[0]) * 1024))
|
||||
if tick % 8 == 0 and (fp := phys_footprint(self.pid)) is not None:
|
||||
self.footprints.append((time.time(), fp))
|
||||
tick += 1
|
||||
self.stop.wait(0.25)
|
||||
|
||||
def summary(self, windows):
|
||||
@@ -205,11 +222,16 @@ class Sampler(threading.Thread):
|
||||
if not self.samples:
|
||||
return {}
|
||||
during = [rss for t, rss in self.samples if any(a <= t <= b for a, b in windows)]
|
||||
return {
|
||||
out = {
|
||||
"rss_peak_mb": max(rss for _, rss in self.samples) / 2**20,
|
||||
"rss_steady_mb": statistics.median(during) / 2**20 if during else None,
|
||||
"rss_samples": len(self.samples),
|
||||
}
|
||||
if self.footprints:
|
||||
steady = [fp for t, fp in self.footprints if any(a <= t <= b for a, b in windows)]
|
||||
out["footprint_peak_mb"] = max(fp for _, fp in self.footprints) / 2**20
|
||||
out["footprint_steady_mb"] = statistics.median(steady) / 2**20 if steady else None
|
||||
return out
|
||||
|
||||
|
||||
def nvidia_memory_mb(pid):
|
||||
@@ -685,6 +707,8 @@ def report(args, distance, runs, app):
|
||||
metric(f"memory.{name}.gpu_mb", [s.get("gpu_mb") for s in scenes])
|
||||
metric("memory.rss_peak_mb", [r["memory"].get("rss_peak_mb") for r in runs])
|
||||
metric("memory.rss_steady_mb", [r["memory"].get("rss_steady_mb") for r in runs])
|
||||
metric("memory.footprint_peak_mb", [r["memory"].get("footprint_peak_mb") for r in runs])
|
||||
metric("memory.footprint_steady_mb", [r["memory"].get("footprint_steady_mb") for r in runs])
|
||||
return {"format": REPORT_FORMAT, "version": REPORT_VERSION, "kind": "game",
|
||||
"created": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"app": app, "hardware": hw, "conditions": conditions, "metrics": metrics, "frames": entries,
|
||||
@@ -711,7 +735,7 @@ def table(labels):
|
||||
cells.append(" / ".join(cell(m.get(f"fps.{scene}.{k}")) for k in ("avg_fps", "low_1pct_fps", "low_01pct_fps")))
|
||||
print(f"| {d} | {scene} | " + " | ".join(cells) + " |")
|
||||
print()
|
||||
print("| RD | " + " | ".join(f"{l}: title / world s, mean scene load s, RSS steady / peak MB, load avg" for l in labels) + " |")
|
||||
print("| RD | " + " | ".join(f"{l}: title / world s, mean scene load s, RSS steady / peak MB, footprint steady / peak MB, load avg" for l in labels) + " |")
|
||||
print("| --- |" + " --- |" * len(labels))
|
||||
for d in distances:
|
||||
cells = []
|
||||
@@ -726,7 +750,9 @@ def table(labels):
|
||||
mb = lambda k: f"{m[k]['mean']:.0f}" if k in m else "–"
|
||||
cells.append(f"{sec('startup.title_ms')} / {sec('startup.world_ms')}, "
|
||||
f"{statistics.mean(loads) / 1000 if loads else 0:.1f}, "
|
||||
f"{mb('memory.rss_steady_mb')} / {mb('memory.rss_peak_mb')}, {r['conditions'].get('load_avg_1m')}")
|
||||
f"{mb('memory.rss_steady_mb')} / {mb('memory.rss_peak_mb')}, "
|
||||
f"{mb('memory.footprint_steady_mb')} / {mb('memory.footprint_peak_mb')}, "
|
||||
f"{r['conditions'].get('load_avg_1m')}")
|
||||
print(f"| {d} | " + " | ".join(cells) + " |")
|
||||
|
||||
|
||||
|
||||
+11
-1
@@ -39,7 +39,17 @@ EXPORTERS = "mods/horizon/src/test/java/dev/horizonlab/parity/"
|
||||
|
||||
# What players run. Documentation (*.md), tests, benchmarks and harness probes (examples/) never count.
|
||||
GAME_PATHS = ["crates/", "xtask/", "packaging/", "Cargo.toml", "Cargo.lock", "research-lock.json"]
|
||||
LAUNCHER_PATHS = ["launcher/", "crates/horizon-prepare/", "crates/horizon-theme/", "crates/horizon-telemetry/"]
|
||||
# Every crate the launcher builds in (cargo metadata --manifest-path launcher/Cargo.toml: the path packages).
|
||||
LAUNCHER_PATHS = [
|
||||
"launcher/",
|
||||
"crates/horizon-bench/",
|
||||
"crates/horizon-friends/",
|
||||
"crates/horizon-mods/",
|
||||
"crates/horizon-port-pack/",
|
||||
"crates/horizon-prepare/",
|
||||
"crates/horizon-telemetry/",
|
||||
"crates/horizon-theme/",
|
||||
]
|
||||
LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"]
|
||||
|
||||
FOOTER = {
|
||||
|
||||
+91
-24
@@ -8,10 +8,18 @@ then measures for a while:
|
||||
- MSPT (average, P50, P95, P99) from each server's own `/tick query`, asked every 5 seconds on the console:
|
||||
vanilla's ServerTickRateManager numbers, which Horizon reproduces, so both measure themselves the same way;
|
||||
- RSS and CPU of the server's whole process tree, once a second;
|
||||
- chunks the bots receive per second (new terrain while the `explore` bots fly outwards);
|
||||
- chunks the bots receive per second (new terrain while the `explore` bots fly outwards), chunks sent again
|
||||
while a bot still held them, and the moves the server refused (pull-backs; "moved too quickly" and
|
||||
"moved wrongly" lines);
|
||||
- the start time to `Done`, and every bot that failed to join or was dropped.
|
||||
|
||||
python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --seconds 120
|
||||
python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --behaviour walk,explore
|
||||
|
||||
The bots can run on another machine, so they don't take the server's CPU: `--bots-via 'ssh macmini'` with
|
||||
`--bots-bin` naming horizon-bots there and `--connect` the address it reaches this machine at. `--nice 19`
|
||||
runs every server at the lowest priority (a shared machine). The explore bots fly as fast as each server
|
||||
sends them chunks, so a faster server gets more terrain to generate; `--explore-speed` slows them to a rate
|
||||
both servers keep up with, for equal work.
|
||||
|
||||
The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The
|
||||
Horizon side runs target/release/horizon-server with the engine beside it; build both first:
|
||||
@@ -186,8 +194,16 @@ def server_command(kind, directory, args):
|
||||
return [server, '--dir', directory, 'run']
|
||||
|
||||
|
||||
def run_once(kind, bots, args, out):
|
||||
directory = out / f'{kind}-{bots}'
|
||||
def bots_command(args):
|
||||
"""horizon-bots here, or through `--bots-via` (for example `ssh macmini`) on another machine."""
|
||||
if args.bots_via:
|
||||
return [*args.bots_via.split(), args.bots_bin or 'horizon-bots']
|
||||
return [args.bots_bin or BIN / f'horizon-bots{EXE}']
|
||||
|
||||
|
||||
def run_once(kind, bots, behaviour, args, out):
|
||||
name = f'{kind}-{behaviour}-{bots}'
|
||||
directory = out / name
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True)
|
||||
port = free_port()
|
||||
@@ -195,19 +211,27 @@ def run_once(kind, bots, args, out):
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
command = server_command(kind, directory, args)
|
||||
if args.nice:
|
||||
command = ['nice', '-n', str(args.nice), *command]
|
||||
started = time.time()
|
||||
server = Server(command, directory, out / f'{kind}-{bots}.log')
|
||||
result = {'server': kind, 'bots': bots}
|
||||
server = Server(command, directory, out / f'{name}.log')
|
||||
result = {'server': kind, 'bots': bots, 'behaviour': behaviour}
|
||||
try:
|
||||
server.wait_for(r'/INFO\]: Done \(', 600)
|
||||
result['start_seconds'] = round(time.time() - started, 2)
|
||||
# Every bot appears on the world spawn itself, not spread around it, so both servers see the same paths.
|
||||
server.console('gamerule respawn_radius 0')
|
||||
for rule in filter(None, args.gamerule.split(',')):
|
||||
server.console('gamerule ' + rule.replace('=', ' '))
|
||||
time.sleep(5)
|
||||
report = out / f'{kind}-{bots}-bots.json'
|
||||
report = out / f'{name}-bots.json'
|
||||
total = bots * args.join_every + args.warmup + args.seconds
|
||||
# The summary comes back on stdout after the per-second lines, so it works over ssh too.
|
||||
bot_process = subprocess.Popen(
|
||||
[BIN / f'horizon-bots{EXE}', '--server', f'127.0.0.1:{port}', '--bots', str(bots),
|
||||
'--behaviour', args.behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)),
|
||||
'--seed', str(args.seed), '--report', report],
|
||||
[*bots_command(args), '--server', f'{args.connect}:{port}', '--bots', str(bots),
|
||||
'--behaviour', behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)),
|
||||
'--seed', str(args.seed), '--report', '-',
|
||||
*(['--explore-speed', str(args.explore_speed)] if args.explore_speed else [])],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
bot_lines = []
|
||||
threading.Thread(target=lambda: bot_lines.extend(bot_process.stdout), daemon=True).start()
|
||||
@@ -229,11 +253,27 @@ def run_once(kind, bots, args, out):
|
||||
if (t := tick_query(server)) is not None:
|
||||
ticks.append(t)
|
||||
next_query = now + 5
|
||||
measured = [json.loads(l) for l in list(bot_lines) if l.startswith('{')]
|
||||
window = [l for l in measured if l['t'] >= measured[-1]['t'] - args.seconds] if measured else []
|
||||
bot_process.wait(timeout=total + 120)
|
||||
summary = json.loads(report.read_text()) if report.exists() else {}
|
||||
time.sleep(0.5)
|
||||
measured, rest = [], []
|
||||
for line in list(bot_lines):
|
||||
try:
|
||||
sample = json.loads(line)
|
||||
except ValueError:
|
||||
sample = None
|
||||
if isinstance(sample, dict) and 't' in sample:
|
||||
measured.append(sample)
|
||||
else:
|
||||
rest.append(line)
|
||||
window = [l for l in measured if l['t'] >= measured[-1]['t'] - args.seconds] if measured else []
|
||||
summary_text = ''.join(rest)
|
||||
summary = json.loads(summary_text) if summary_text.strip() else {}
|
||||
report.write_text(json.dumps(summary, indent=2) + '\n')
|
||||
mean = lambda xs: round(statistics.fmean(xs), 2) if xs else None
|
||||
per_bot = summary.get('per_bot', [])
|
||||
by_behaviour = {}
|
||||
for b in per_bot:
|
||||
by_behaviour.setdefault(b['behaviour'], []).append(b)
|
||||
result.update({
|
||||
'mspt': {k: mean([t[k] for t in ticks]) for k in ('average', 'p50', 'p95', 'p99')},
|
||||
'mspt_worst_p99': max((t['p99'] for t in ticks), default=None),
|
||||
@@ -242,6 +282,19 @@ def run_once(kind, bots, args, out):
|
||||
'rss_mb': {'mean': mean([r / 1e6 for r in rss]), 'max': round(max(rss) / 1e6, 1) if rss else None},
|
||||
'cpu_percent': mean(cpu),
|
||||
'chunks_per_second': mean([l['chunks_per_second'] for l in window]),
|
||||
# Over the measured window: different chunks reaching the bots, chunks they had dropped and got
|
||||
# again (walking back), and ticks the bots stood still waiting for their own chunk.
|
||||
**({k + '_per_second': round((window[-1][k] - window[0][k]) / max(len(window) - 1, 1), 2)
|
||||
for k in ('unique', 'forgotten', 'waited_ticks')} if len(window) > 1 else {}),
|
||||
'chunks_total': summary.get('chunks'),
|
||||
# Per bot over the whole run: every chunk received, the different ones, and those sent again
|
||||
# while the bot still held them.
|
||||
'chunks_per_bot': {k: mean([b['chunks'] for b in v]) for k, v in by_behaviour.items()},
|
||||
'unique_chunks_per_bot': {k: mean([b['unique_chunks'] for b in v]) for k, v in by_behaviour.items()},
|
||||
'resent': summary.get('resent'),
|
||||
'pulled_back': summary.get('pulled_back'),
|
||||
'moved_too_quickly': sum('moved too quickly!' in l for l in server.since(0)),
|
||||
'moved_wrongly': sum('moved wrongly!' in l for l in server.since(0)),
|
||||
'bots_joined': summary.get('joined'),
|
||||
'bots_failed': [b for b in summary.get('per_bot', []) if b.get('error')],
|
||||
'tick_queries': len(ticks),
|
||||
@@ -257,23 +310,34 @@ def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
|
||||
parser.add_argument('--servers', default='horizon,vanilla')
|
||||
parser.add_argument('--bots', default='1,10,25,50')
|
||||
parser.add_argument('--behaviour', default='mixed')
|
||||
parser.add_argument('--behaviour', default='walk,explore', help='one pass per behaviour (comma-separated)')
|
||||
parser.add_argument('--join-every', type=float, default=1.0)
|
||||
parser.add_argument('--warmup', type=int, default=60)
|
||||
parser.add_argument('--seconds', type=int, default=300)
|
||||
parser.add_argument('--seed', type=int, default=12345)
|
||||
parser.add_argument('--explore-speed', type=float, default=0,
|
||||
help='blocks a second the explore bots fly (default: the bots\' 22, as fast as chunks '
|
||||
'come); a speed both servers keep up with makes the explore pass equal work')
|
||||
parser.add_argument('--gamerule', default='',
|
||||
help="more game rules for both servers, 'name=value,...' (locator_bar=false: Horizon has "
|
||||
"no locator bar yet)")
|
||||
parser.add_argument('--heap', default='4g', help='the Java heap, -Xms and -Xmx (vanilla)')
|
||||
parser.add_argument('--out', type=Path, default=None, help='the report (JSON)')
|
||||
parser.add_argument('--nice', type=int, default=0, help='run the servers under nice -n N')
|
||||
parser.add_argument('--bots-via', default='', help="a command prefix to run the bots elsewhere ('ssh host')")
|
||||
parser.add_argument('--bots-bin', default='', help='horizon-bots (on the --bots-via machine)')
|
||||
parser.add_argument('--connect', default='127.0.0.1', help='the address the bots reach the server at')
|
||||
args = parser.parse_args()
|
||||
out = lab.LOCAL / 'server-bench'
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
runs = []
|
||||
for bots in [int(b) for b in args.bots.split(',')]:
|
||||
for kind in args.servers.split(','):
|
||||
print(f'{kind}, {bots} bots...', flush=True)
|
||||
result = run_once(kind, bots, args, out)
|
||||
runs.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
for behaviour in args.behaviour.split(','):
|
||||
for bots in [int(b) for b in args.bots.split(',')]:
|
||||
for kind in args.servers.split(','):
|
||||
print(f'{kind}, {bots} {behaviour} bots...', flush=True)
|
||||
result = run_once(kind, bots, behaviour, args, out)
|
||||
runs.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
report = {
|
||||
'kind': 'horizon-server-benchmark',
|
||||
'date': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'),
|
||||
@@ -286,13 +350,16 @@ def main():
|
||||
path = args.out or out / 'report.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(f'\n{"server":8} {"bots":>4} {"start s":>8} {"MSPT":>6} {"P95":>6} {"P99":>6} {"RSS MB":>7} {"CPU %":>6} {"chunks/s":>8} {"joined":>6}')
|
||||
print(f'\n{"server":8} {"pass":8} {"bots":>4} {"start s":>8} {"MSPT":>6} {"P95":>6} {"P99":>6} {"RSS MB":>7} '
|
||||
f'{"CPU %":>6} {"chunks/s":>8} {"/bot":>6} {"resent":>6} {"pulled":>6} {"joined":>6}')
|
||||
for r in runs:
|
||||
if 'error' in r:
|
||||
print(f'{r["server"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}')
|
||||
print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}')
|
||||
continue
|
||||
print(f'{r["server"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} {r["mspt"]["p95"]!s:>6} '
|
||||
f'{r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} {r["chunks_per_second"]!s:>8} '
|
||||
per_bot = r['chunks_per_bot'].get(r['behaviour'])
|
||||
print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} '
|
||||
f'{r["mspt"]["p95"]!s:>6} {r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} '
|
||||
f'{r["chunks_per_second"]!s:>8} {per_bot!s:>6} {r["resent"]!s:>6} {r["pulled_back"]!s:>6} '
|
||||
f'{r["bots_joined"]!s:>6}')
|
||||
print(f'\nWrote {path}')
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ the same files), chats, runs /list and commands that fail (`/random value
|
||||
7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by
|
||||
the console, runs /kill, respawns (as vanilla's LevelLoadTracker waits: until the "level
|
||||
chunks load start" event and the chunk under the player), sets a furnace
|
||||
beside itself, gives itself raw iron and coal, opens the furnace, shift-clicks
|
||||
beside itself, gives itself raw iron and coal, sets and asks its own score
|
||||
(`@s`), opens the furnace, shift-clicks
|
||||
the ore and the coal in and the ingot out, and leaves. The
|
||||
console then runs `list` and `say` and `stop`. Compared, all of them
|
||||
exactly:
|
||||
@@ -33,9 +34,12 @@ exactly:
|
||||
player respawned (guests' death messages aren't Horizon's yet: left out);
|
||||
- the furnace menu: its type and title, its contents, the slots each
|
||||
shift-click changes and its lit and cooking totals;
|
||||
- the console lines about the player, the chat, `list`, `say` and `stop`;
|
||||
- the console lines about the player (an operator's command feedback, which
|
||||
vanilla broadcasts to the console, included), the chat, `list`, `say` and
|
||||
`stop`;
|
||||
- the files the servers leave: server.properties (but the date line),
|
||||
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json.
|
||||
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json,
|
||||
usercache.json (but the date the player's entry expires).
|
||||
|
||||
Online mode needs Mojang's session servers and is not tested.
|
||||
"""
|
||||
@@ -208,10 +212,9 @@ CONSOLE_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*)$')
|
||||
KEPT = re.compile(r'Tester|\[Server\]|\[Not Secure\]|There are|Stopping|Saving|ThreadedAnvilChunkStorage|All dimensions|Unknown or incomplete')
|
||||
|
||||
|
||||
# Guests' death messages, the op's command feedback broadcast to the console and guests'
|
||||
# advancement announcements aren't Horizon's yet (the client's own transcript leaves the
|
||||
# death message out as well).
|
||||
NOT_YET = re.compile(r'Tester was killed|Killed Tester|System chat: \[Tester: |Tester has made the advancement')
|
||||
# Guests' death messages and advancement announcements aren't Horizon's yet (the client's
|
||||
# own transcript leaves the death message out as well).
|
||||
NOT_YET = re.compile(r'Tester was killed|Tester has made the advancement')
|
||||
|
||||
|
||||
def console_lines(lines):
|
||||
@@ -238,7 +241,8 @@ def console_lines(lines):
|
||||
|
||||
def server_files(directory):
|
||||
out = []
|
||||
for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json']:
|
||||
for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json',
|
||||
'usercache.json']:
|
||||
path = directory / name
|
||||
if not path.exists():
|
||||
out.append(f'{name}: missing')
|
||||
@@ -249,6 +253,9 @@ def server_files(directory):
|
||||
text = re.sub(r'^(#[^\n]*\n)#[^\n]*\n', r'\1#<date>\n', text)
|
||||
# Random per server, and each side has its own port.
|
||||
text = re.sub(r'\n(management-server-secret|server-port)=[^\n]*', r'\n\1=<varies>', text)
|
||||
if name == 'usercache.json':
|
||||
# A month from when the player joined.
|
||||
text = re.sub(r'"expiresOn":"[^"]*"', '"expiresOn":"<a month on>"', text)
|
||||
out.append(f'{name}: {text!r}')
|
||||
return out
|
||||
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The locator bar on a dedicated server, against vanilla's, seen by vanilla clients.
|
||||
|
||||
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat
|
||||
world vanilla generated first (players appear at its spawn), with the same server.properties (offline,
|
||||
creative, view distance 4) and two operators. LocatorBarClient, two
|
||||
players made of vanilla's protocol code (any byte vanilla would not read is an error), joins Alice and then
|
||||
Bob, who fly as creative players do (a player floating without flying falls on the server every tick), and
|
||||
records every ClientboundTrackedWaypointPacket each of them receives. Bob then:
|
||||
|
||||
- teleports one block, three blocks, out of Alice's view, one chunk on, really far (an azimuth) and turns
|
||||
around her, and back;
|
||||
- turns invisible and visible, joins a red team (by the console), has it turned blue, leaves it;
|
||||
- crouches and stands up, wears a carved pumpkin and takes it off;
|
||||
- turns spectator and moves, then creative again;
|
||||
|
||||
the console turns the `locator_bar` game rule off and on, and Bob leaves. The waypoint packets each player
|
||||
received in each step are compared exactly: operation, player, style, colour and the block, chunk or angle.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server, free_port
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
|
||||
NAME = 'locator-bar-parity'
|
||||
PROPERTIES = {
|
||||
'online-mode': 'false',
|
||||
'white-list': 'false',
|
||||
'level-seed': '12345',
|
||||
'level-type': 'minecraft\\:flat',
|
||||
'generate-structures': 'false',
|
||||
'gamemode': 'creative',
|
||||
'force-gamemode': 'true',
|
||||
'view-distance': '4',
|
||||
'simulation-distance': '4',
|
||||
'spawn-protection': '0',
|
||||
'max-players': '5',
|
||||
'pause-when-empty-seconds': '-1',
|
||||
}
|
||||
PLAYERS = ['Alice', 'Bob']
|
||||
|
||||
# (label, [what the console does], [what the players do]); every step then waits for its packets.
|
||||
SCRIPT = [
|
||||
('alice-joins', [], ['join Alice', 'fly Alice on', 'cmd Alice tp @s 0.5 100 0.5']),
|
||||
('bob-joins', [], ['join Bob', 'fly Bob on', 'cmd Bob tp @s 2.5 100 0.5']),
|
||||
('near', [], ['cmd Bob tp @s 5.5 100 0.5']),
|
||||
('one-block', [], ['cmd Bob tp @s 6.5 100 0.5']),
|
||||
('three-blocks', [], ['cmd Bob tp @s 9.5 100 0.5']),
|
||||
('out-of-view', [], ['cmd Bob tp @s 100.5 100 0.5']),
|
||||
('next-chunk', [], ['cmd Bob tp @s 116.5 100 0.5']),
|
||||
('really-far', [], ['cmd Bob tp @s 1000.5 100 0.5']),
|
||||
('turn-around', [], ['cmd Bob tp @s 1000.5 100 300.5']),
|
||||
('half-degree', [], ['cmd Bob tp @s 1000.5 100 302.5']),
|
||||
('invisible', [], ['cmd Bob effect give @s minecraft:invisibility infinite 0 true']),
|
||||
('visible', [], ['cmd Bob effect clear @s']),
|
||||
('back-near', [], ['cmd Bob tp @s 3.5 100 0.5']),
|
||||
('red-team', ['team add red', 'team modify red color red', 'team join red Bob'], []),
|
||||
('blue-team', ['team modify red color blue'], []),
|
||||
('no-team', ['team leave Bob'], []),
|
||||
# Crouching needs the ground: a flying player who holds shift goes down instead.
|
||||
('landed', [], ['cmd Bob tp @s 3.5 -60 0.5', 'fly Bob off']),
|
||||
('crouch', [], ['shift Bob on']),
|
||||
('stand', [], ['shift Bob off']),
|
||||
('flying-again', [], ['fly Bob on', 'cmd Bob tp @s 3.5 100 0.5']),
|
||||
('pumpkin', [], ['cmd Bob item replace entity @s armor.head with minecraft:carved_pumpkin']),
|
||||
('no-pumpkin', [], ['cmd Bob item replace entity @s armor.head with minecraft:air']),
|
||||
('rule-off', ['gamerule locator_bar false'], []),
|
||||
('moves-without', [], ['cmd Bob tp @s 4.5 100 0.5']),
|
||||
('rule-on', ['gamerule locator_bar true'], []),
|
||||
('spectator', [], ['cmd Bob gamemode spectator', 'cmd Bob tp @s 5.5 100 0.5']),
|
||||
('creative', [], ['cmd Bob gamemode creative', 'cmd Bob tp @s 6.5 100 0.5']),
|
||||
('bob-leaves', [], ['quit Bob']),
|
||||
]
|
||||
STEP_SECONDS = 2.0
|
||||
# Vanilla's server moves a player who just joined on their own first ticks (a tiny step and back), which tracks
|
||||
# them where they spawned; Horizon does not simulate its guests. These steps compare what the bar shows at
|
||||
# their end (Bob has moved by then) rather than every packet.
|
||||
SETTLING_STEPS = {'alice-joins', 'bob-joins'}
|
||||
|
||||
|
||||
def shown(lines):
|
||||
"""The transcript with each settling step reduced to what each player's bar shows at its end."""
|
||||
out, state = [], {}
|
||||
|
||||
def flush(step):
|
||||
for (receiver, source), rest in sorted(state.items()):
|
||||
out.append(f'{receiver} step={step} shows {source} {rest}')
|
||||
state.clear()
|
||||
|
||||
current = None
|
||||
for line in lines:
|
||||
receiver, step, *packet = line.split(' ')
|
||||
step = step.removeprefix('step=')
|
||||
if current in SETTLING_STEPS and step != current:
|
||||
flush(current)
|
||||
current = step
|
||||
if step not in SETTLING_STEPS or len(packet) < 3:
|
||||
out.append(line)
|
||||
elif packet[0] == 'untrack':
|
||||
state.pop((receiver, packet[1]), None)
|
||||
else:
|
||||
state[(receiver, packet[1])] = ' '.join(packet[2:])
|
||||
if current in SETTLING_STEPS:
|
||||
flush(current)
|
||||
return out
|
||||
|
||||
|
||||
def ops_json():
|
||||
"""Both players at level 4, by their offline UUIDs."""
|
||||
import hashlib
|
||||
import json
|
||||
import uuid as uuidlib
|
||||
entries = []
|
||||
for name in PLAYERS:
|
||||
digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest())
|
||||
digest[6] = (digest[6] & 0x0F) | 0x30
|
||||
digest[8] = (digest[8] & 0x3F) | 0x80
|
||||
entries.append({'uuid': str(uuidlib.UUID(bytes=bytes(digest))), 'name': name, 'level': 4,
|
||||
'bypassesPlayerLimit': False})
|
||||
return json.dumps(entries, indent=2)
|
||||
|
||||
|
||||
def server_dir(directory, world=None):
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
directory.mkdir(parents=True)
|
||||
port = free_port()
|
||||
props = dict(PROPERTIES, **{'server-port': str(port)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
|
||||
encoding='iso-8859-1')
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
(directory / 'ops.json').write_text(ops_json())
|
||||
if world is not None:
|
||||
shutil.copytree(world, directory / 'world')
|
||||
(directory / 'world' / 'session.lock').unlink(missing_ok=True)
|
||||
return port
|
||||
|
||||
|
||||
def generate_world(server_command, build):
|
||||
"""The flat world both servers load, made once by vanilla: players appear at its spawn itself
|
||||
(respawn_radius 0), on the ground at 0 -60 0, and the chunks around it are saved."""
|
||||
directory = build / 'generate'
|
||||
server_dir(directory)
|
||||
server = Server(server_command, directory, 'generate')
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
for command, reply in [('gamerule respawn_radius 0', 'respawn_radius'),
|
||||
('setworldspawn 0 -60 0', 'Set the world spawn'),
|
||||
('forceload add -96 -96 96 96', 'force loaded'),
|
||||
('save-all flush', 'Saved the game')]:
|
||||
server.console(command)
|
||||
server.wait_for(reply, timeout=120)
|
||||
server.console('forceload remove all')
|
||||
finally:
|
||||
server.stop()
|
||||
return directory / 'world'
|
||||
|
||||
|
||||
def run_side(label, server_command, client_command, build, world):
|
||||
directory = build / label
|
||||
port = server_dir(directory, world)
|
||||
out = build / f'{label}.txt'
|
||||
out.unlink(missing_ok=True)
|
||||
server = Server(server_command, directory, label)
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
with (build / f'{label}-client.log').open('w') as log:
|
||||
client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
|
||||
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
|
||||
text=True)
|
||||
try:
|
||||
for step, console, actions in SCRIPT:
|
||||
client.stdin.write(f'step {step}\n')
|
||||
client.stdin.flush()
|
||||
for command in console:
|
||||
server.console(command)
|
||||
for action in actions:
|
||||
client.stdin.write(action + '\n')
|
||||
client.stdin.flush()
|
||||
if action.startswith('join'):
|
||||
# Joining takes the world's first chunks: wait for the server to place the player.
|
||||
server.wait_for(rf'{action.split()[1]} joined the game', timeout=120)
|
||||
time.sleep(STEP_SECONDS)
|
||||
client.stdin.write('end\n')
|
||||
client.stdin.flush()
|
||||
client.wait(timeout=60)
|
||||
finally:
|
||||
if client.poll() is None:
|
||||
client.kill()
|
||||
finally:
|
||||
server.stop()
|
||||
if not out.exists():
|
||||
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
|
||||
return out.read_text(encoding='utf-8').splitlines()
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java'
|
||||
classes = build / 'classes'
|
||||
shutil.rmtree(classes, ignore_errors=True)
|
||||
classes.mkdir()
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
cwd=lab.ROOT, check=True, capture_output=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
|
||||
|
||||
world = generate_world(vanilla_server, build)
|
||||
vanilla = run_side('vanilla', vanilla_server, client, build, world)
|
||||
horizon = run_side('horizon', horizon_server, client, build, world)
|
||||
errors = [l for l in vanilla + horizon if ' error ' in f' {l} ' or 'disconnected' in l]
|
||||
vanilla, horizon = shown(vanilla), shown(horizon)
|
||||
# Each player's packets in their order; which player's line comes first in a step doesn't matter.
|
||||
if errors or vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
|
||||
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
|
||||
+ '\n'.join(errors[:10]) + '\n' + diff[:6000])
|
||||
if len(vanilla) < 20:
|
||||
raise AssertionError(f'only {len(vanilla)} waypoint packets: the script did not run (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
packets=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Locator bar waypoints (ClientboundTrackedWaypointPacket) two vanilla-codec players receive on a '
|
||||
'dedicated server: block, chunk and azimuth connections as one moves, invisibility, team colours, '
|
||||
'crouching, a carved pumpkin, the locator_bar game rule, spectator mode and leaving.'))
|
||||
print(f'locator bar: {len(vanilla)} waypoint packets identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
@@ -262,6 +262,12 @@ def scenarios():
|
||||
add('bee_hive_rain', 300, [HIVE, 'mob minecraft:bee 0.5 -58 0.5 0 162 persistent'], 'rain')
|
||||
add('bee_hive_morning', 1000, [HIVE, 'mob minecraft:bee 0.5 -58 0.5 0 163 persistent'], 'time=22900 daycycle')
|
||||
add('bee_hive_honey', 2600, [HIVE, 'mob minecraft:bee 0.5 -58 0.5 0 164 persistent nectar'])
|
||||
# Mobs dropped into deep water (#542): FloatGoal users float at the surface (their navigation
|
||||
# can float, so Mob.jumpInLiquid adds 0.04 a tick), zombies sink.
|
||||
for species, seed in [('pig', 171), ('cow', 172), ('wolf', 173), ('cat', 174), ('horse', 175),
|
||||
('witch', 176), ('vindicator', 177), ('zombie', 178)]:
|
||||
add(f'{species}_deep_water', 160, ['fill -4 -64 -4 4 -61 4 minecraft:water',
|
||||
f'mob minecraft:{species} 0.5 -62 0.5 0 {seed} persistent'])
|
||||
return s
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,10 @@ Also checked, with vanilla's messages:
|
||||
- a token the session service rejects ("Failed to log in: Invalid session");
|
||||
- a join the session service forgets (the server: "Failed to verify username!");
|
||||
- no account at all (the client refuses before joining);
|
||||
- a verified player the whitelist refuses.
|
||||
- a verified player the whitelist refuses;
|
||||
- `whitelist add` in online mode: a player who joined before is known by name
|
||||
and let in; another name is looked up through the services' profile lookup,
|
||||
and one with no account is refused ("That player does not exist").
|
||||
|
||||
Horizon's dedicated server then runs the same steps in online mode
|
||||
(`HORIZON_API_DISCOVERY` points it at the mock too): it must give the client
|
||||
@@ -100,6 +103,14 @@ class Services:
|
||||
query = dict(urllib.parse.parse_qsl(url.query))
|
||||
if url.path == '/minecraft/client':
|
||||
return self.reply(200, services.discovery())
|
||||
if url.path.startswith('/users/profiles/minecraft/'):
|
||||
# profiles/getByName: the account with that name, ignoring case.
|
||||
name = urllib.parse.unquote(url.path.rsplit('/', 1)[1])
|
||||
with services.lock:
|
||||
services.log.append(('lookup', name))
|
||||
if name.lower() == PLAYER.lower():
|
||||
return self.reply(200, {'id': PLAYER_UUID, 'name': PLAYER})
|
||||
return self.reply(404, {'error': 'NOT_FOUND', 'errorMessage': f'Couldn\'t find any profile with name {name}'})
|
||||
if url.path == '/session/minecraft/hasJoined':
|
||||
with services.lock:
|
||||
ok = services.joined.get(query.get('username')) == query.get('serverId')
|
||||
@@ -107,11 +118,15 @@ class Services:
|
||||
if ok:
|
||||
return self.reply(200, {'id': PLAYER_UUID, 'name': query['username'], 'properties': []})
|
||||
return self.reply(204)
|
||||
with services.lock:
|
||||
services.log.append(('unknown', url.path))
|
||||
self.reply(404, {'error': 'NotFound', 'path': url.path})
|
||||
|
||||
def do_POST(self):
|
||||
body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))) or b'{}')
|
||||
if self.path != '/session/minecraft/join':
|
||||
with services.lock:
|
||||
services.log.append(('unknown', self.path))
|
||||
return self.reply(404, {'error': 'NotFound'})
|
||||
token, profile, server_id = body.get('accessToken'), body.get('selectedProfile'), body.get('serverId')
|
||||
accepted = token in (GOOD, FORGET) and profile == PLAYER_UUID
|
||||
@@ -135,7 +150,8 @@ class Services:
|
||||
'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined',
|
||||
getProfileById='/session/minecraft/profile/{profileId}'),
|
||||
'player': {'endpoints': {}},
|
||||
'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}}},
|
||||
'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']},
|
||||
'getByName': {'uri': self.url + '/users/profiles/minecraft/{name}'}}},
|
||||
'telemetry': {'endpoints': {}},
|
||||
}}
|
||||
|
||||
@@ -189,8 +205,19 @@ def player_lines(lines):
|
||||
return out
|
||||
|
||||
|
||||
def wait_after(server, mark, pattern, timeout=30):
|
||||
"""A line matching `pattern` among those the server printed after `mark`."""
|
||||
regex = re.compile(pattern)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if any(regex.search(l) for l in server.lines[mark:]):
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise AssertionError(f'no {pattern!r} after line {mark} of {server.log_path.name}')
|
||||
|
||||
|
||||
def run_side(label, command, binary, build, services, discovery):
|
||||
"""The five logins against one server; its checks and its log about the player."""
|
||||
"""The six logins against one server; its checks and its log about the player."""
|
||||
port = free_port()
|
||||
directory = build / label
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
@@ -261,6 +288,24 @@ def run_side(label, command, binary, build, services, discovery):
|
||||
check('not whitelisted: client message', got['error'], 'disconnected: You are not white-listed on this server!')
|
||||
check('not whitelisted: verified first', [(e[0], e[3]) for e in services.take_log()],
|
||||
[('join', True), ('verify', True)])
|
||||
|
||||
# 6. Whitelisted by name: the server knows the player from their first join (its name cache), so it
|
||||
# asks the services nothing, and lets them in.
|
||||
mark = len(server.lines)
|
||||
server.console('whitelist add tester')
|
||||
wait_after(server, mark, r'Added Tester to the whitelist')
|
||||
check('whitelist add: known player, no lookup', services.take_log(), [])
|
||||
got = run_client(binary, build, port, f'{label}-whitelisted', GOOD, discovery)
|
||||
wait_after(server, mark, r'Tester left the game')
|
||||
check('whitelisted: connected throughout', got['error'], None)
|
||||
services.take_log()
|
||||
# A name nobody joined with: the server looks the account up, and there is none.
|
||||
mark = len(server.lines)
|
||||
server.console('whitelist add Nobody')
|
||||
wait_after(server, mark, r'That player does not exist')
|
||||
check('whitelist add: lookup failure logged',
|
||||
any("Couldn't find profile with name: nobody" in l for l in server.lines[mark:]), True)
|
||||
check('whitelist add: no such account', services.take_log(), [('lookup', 'nobody')])
|
||||
time.sleep(1)
|
||||
finally:
|
||||
server.stop()
|
||||
@@ -310,7 +355,7 @@ def main():
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], checks=len(checks),
|
||||
scope='Online-mode login against vanilla\'s dedicated server and Horizon\'s, with a mock session service: '
|
||||
'server hash, RSA key packet, AES/CFB8, session join and verify, play; rejected token, forgotten '
|
||||
'join, no account, whitelist; the servers\' log lines about the player.'))
|
||||
'join, no account, whitelist, whitelist add by account name; the servers\' log lines about the player.'))
|
||||
print(f'online mode: {len(checks)} checks ok')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A new world's generator settings from server.properties, against vanilla's dedicated server.
|
||||
|
||||
DedicatedServerProperties.WorldDimensionData makes a world that doesn't exist yet from `level-type` (a world
|
||||
preset: `flat`, `minecraft:normal`, or a name it can't find, which it warns about and replaces with
|
||||
`minecraft:normal`), a flat world's `generator-settings` (FlatLevelGeneratorSettings: its layers, biome,
|
||||
lakes and features; a layer that doesn't parse is left out and logged, and settings without layers fall back
|
||||
to the preset's classic ones) and `generate-structures`.
|
||||
|
||||
Each case starts vanilla's server and Horizon's (`horizon-client --dedicated --nogui`) in a new folder, waits
|
||||
for `Done` and stops them. Compared exactly: the world's `data/minecraft/world_gen_settings.dat`, tag types
|
||||
included, and the warnings and errors logged while the world's settings are read (the `Worker-Main` lines;
|
||||
the worker's number is left out).
|
||||
|
||||
Horizon generates the normal and flat presets only: `large_biomes`, `amplified`, `single_biome_surface` and
|
||||
`debug_all_block_states` aren't tested.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import anvil_dump, lab, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server, free_port
|
||||
except ImportError:
|
||||
import anvil_dump
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
|
||||
NAME = 'server-world-gen-parity'
|
||||
PROPERTIES = {
|
||||
'online-mode': 'false',
|
||||
'view-distance': '2',
|
||||
'simulation-distance': '2',
|
||||
'spawn-protection': '0',
|
||||
}
|
||||
CASES = {
|
||||
# server.properties' default generator-settings ({}) has no layers: the preset's classic ones.
|
||||
'flat': {'level-type': 'flat', 'level-seed': '1'},
|
||||
'flat-layers': {
|
||||
'level-type': 'minecraft:flat',
|
||||
'level-seed': '-7',
|
||||
'generator-settings': json.dumps({
|
||||
'layers': [{'block': 'minecraft:bedrock', 'height': 1}, {'block': 'stone', 'height': 10},
|
||||
{'block': 'minecraft:no_such_block', 'height': 2}, {'block': 'sand', 'height': 3}],
|
||||
'biome': 'minecraft:desert', 'lakes': True, 'features': True}, separators=(',', ':')),
|
||||
},
|
||||
'flat-biome': {
|
||||
'level-type': 'FLAT',
|
||||
'level-seed': 'flat',
|
||||
'generator-settings': '{"layers":[{"block":"minecraft:glass","height":5}],"biome":"nowhere"}',
|
||||
},
|
||||
'normal': {'level-type': 'minecraft:normal', 'level-seed': 'abc', 'generate-structures': 'false'},
|
||||
'unknown': {'level-type': 'Some Type', 'level-seed': '42'},
|
||||
}
|
||||
WORKER = re.compile(r'\[Worker-Main-\d+/(WARN|ERROR)\]: (.*)')
|
||||
|
||||
|
||||
def escape(value):
|
||||
"""java.util.Properties.store's escaping of a value."""
|
||||
return value.replace('\\', '\\\\').replace(':', '\\:').replace('=', '\\=').replace('#', '\\#')
|
||||
|
||||
|
||||
def run_case(label, command, build, case):
|
||||
directory = build / label / case
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
directory.mkdir(parents=True)
|
||||
props = dict(PROPERTIES, **CASES[case], **{'server-port': str(free_port())})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={escape(v)}\n' for k, v in props.items()),
|
||||
encoding='iso-8859-1')
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
server = Server(command, directory, f'{label}-{case}')
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
finally:
|
||||
server.stop()
|
||||
out = [f'# {case}']
|
||||
out += [f'{m.group(1)}: {m.group(2)}' for l in server.lines if (m := WORKER.search(l))]
|
||||
settings = anvil_dump.plain(anvil_dump.read_dat(directory / 'world/data/minecraft/world_gen_settings.dat'),
|
||||
True, typed=True)
|
||||
out += json.dumps(settings, indent=1, sort_keys=True).splitlines()
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main',
|
||||
'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
vanilla, horizon = [], []
|
||||
for case in CASES:
|
||||
vanilla += run_case('vanilla', vanilla_server, build, case)
|
||||
horizon += run_case('horizon', horizon_server, build, case)
|
||||
(build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8')
|
||||
(build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8')
|
||||
if vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=2, lineterm=''))
|
||||
raise AssertionError(f'world settings differ (see {build}/vanilla.txt and horizon.txt):\n' + diff[:6000])
|
||||
if not any('minecraft:flat' in l for l in vanilla) or not any(l.startswith('ERROR: ') for l in vanilla):
|
||||
raise AssertionError(f'vanilla made no flat world or logged no error (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
cases=list(CASES), lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='a new dedicated-server world: level-type (flat, normal, unknown), a flat world\'s '
|
||||
'generator-settings, generate-structures, as world_gen_settings.dat and the lines logged.'))
|
||||
print(f'server world gen: {len(CASES)} cases, {len(vanilla)} lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
"""usercache.json and the console's player names, against vanilla's dedicated server.
|
||||
|
||||
The console finds a player by name through the user cache (CachedUserNameToIdResolver): a name it holds
|
||||
in any case, else the profile service's `getByName` (asked with the lower-case name), else, in offline
|
||||
mode, the offline player of that lower-case name; what it finds is cached for a month and the file
|
||||
rewritten, most recently used first. A small mock of the Minecraft services (dev only: the discovery
|
||||
document and `getByName`, which knows one account) stands in for Mojang's; vanilla finds it through
|
||||
`-Dminecraft.api.discovery.host`, Horizon through `HORIZON_API_DISCOVERY`.
|
||||
|
||||
Each server starts in offline mode in a folder holding a usercache.json with a live entry, an expired
|
||||
one, entries without a date, with a bad date, without an id, and not an object. The console then
|
||||
whitelists, ops, deops and bans players: the cached one in another case, the expired one, the account the
|
||||
service knows, names it doesn't know, a name too long to ask about. The server restarts in online mode,
|
||||
where a name nobody knows is no player at all, and stops. Compared exactly: the console's replies, the
|
||||
names asked of the service in order, and usercache.json, whitelist.json, ops.json and
|
||||
banned-players.json after each run (the dates the servers wrote are placeholders).
|
||||
|
||||
Players who join are added by the dedicated-server harness, which compares usercache.json too.
|
||||
"""
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server, free_port
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
|
||||
NAME = 'user-cache-parity'
|
||||
PROPERTIES = {
|
||||
'online-mode': 'false',
|
||||
'level-seed': '12345',
|
||||
'generate-structures': 'false',
|
||||
'view-distance': '2',
|
||||
'simulation-distance': '2',
|
||||
'spawn-protection': '0',
|
||||
'pause-when-empty-seconds': '-1',
|
||||
}
|
||||
NOTCH = '069a79f444e94726a5befca90e38aaf5'
|
||||
SEEDED = [
|
||||
{'uuid': '853c80ef-3c37-49fd-aa49-938b674adae6', 'name': 'Seeded', 'expiresOn': '2099-01-01 00:00:00 +0000'},
|
||||
{'uuid': '61699b2e-d327-4a01-9f1e-0ea8c3f06bc6', 'name': 'Expired', 'expiresOn': '2001-02-03 04:05:06 +0000'},
|
||||
{'uuid': '00000000-0000-0000-0000-000000000001', 'name': 'NoDate'},
|
||||
{'uuid': '00000000-0000-0000-0000-000000000002', 'name': 'BadDate', 'expiresOn': 'tomorrow'},
|
||||
{'name': 'NoId', 'expiresOn': '2099-01-01 00:00:00 +0000'},
|
||||
'not an object',
|
||||
{'uuid': '00000000-0000-0000-0000-000000000003', 'name': 'Later', 'expiresOn': '2098-05-06 07:08:09 +0100'},
|
||||
]
|
||||
# (console command, the reply it waits for)
|
||||
OFFLINE = [
|
||||
('whitelist add SEEDED', r'System chat: (Added|Player is already)'),
|
||||
('whitelist add Notch', r'System chat: (Added|Player is already)'),
|
||||
('op expired', r'System chat: (Made|Nothing changed)'),
|
||||
('ban Nobody_Here', r'System chat: (Banned|Nothing changed)'),
|
||||
('whitelist add NameMuchTooLongForMinecraft', r'System chat: (Added|Player is already)'),
|
||||
('deop NOTCH', r'System chat: (Made|Nothing changed)'),
|
||||
('whitelist add later', r'System chat: (Added|Player is already)'),
|
||||
('whitelist remove notch', r'System chat: (Removed|Player is not)'),
|
||||
]
|
||||
ONLINE = [
|
||||
('whitelist add Somebody_Else', r'System chat: (Added|That player does not exist)'),
|
||||
('whitelist add nobody_here', r'System chat: (Added|Player is already)'),
|
||||
]
|
||||
FILES = ['usercache.json', 'whitelist.json', 'ops.json', 'banned-players.json']
|
||||
|
||||
|
||||
class Services:
|
||||
"""The mock discovery document and profile lookup by name."""
|
||||
|
||||
def __init__(self):
|
||||
self.asked = []
|
||||
self.lock = threading.Lock()
|
||||
services = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def reply(self, status, body):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
url = urllib.parse.urlparse(self.path)
|
||||
if url.path == '/minecraft/client':
|
||||
return self.reply(200, services.discovery())
|
||||
if url.path.startswith('/profiles/name/'):
|
||||
name = urllib.parse.unquote(url.path.removeprefix('/profiles/name/'))
|
||||
with services.lock:
|
||||
services.asked.append(name)
|
||||
if name.lower() == 'notch':
|
||||
return self.reply(200, {'id': NOTCH, 'name': 'Notch'})
|
||||
return self.reply(404, {'path': url.path, 'errorMessage': f"Couldn't find any profile with name {name}"})
|
||||
self.reply(404, {'error': 'NotFound', 'path': url.path})
|
||||
|
||||
self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
self.url = f'http://127.0.0.1:{self.server.server_address[1]}'
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
|
||||
def discovery(self):
|
||||
def endpoints(**names):
|
||||
return {'endpoints': {k: {'uri': self.url + v} for k, v in names.items()}}
|
||||
return {'environment': 'mock', 'product': 'minecraft', 'discovery': {
|
||||
'authentication': endpoints(getPublicKeys='/publickeys'),
|
||||
'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined',
|
||||
getProfileById='/session/minecraft/profile/{profileId}'),
|
||||
'player': endpoints(),
|
||||
'profiles': endpoints(getByName='/profiles/name/{name}'),
|
||||
'telemetry': endpoints(),
|
||||
}}
|
||||
|
||||
def take(self):
|
||||
with self.lock:
|
||||
asked, self.asked = self.asked, []
|
||||
return asked
|
||||
|
||||
def stop(self):
|
||||
self.server.shutdown()
|
||||
|
||||
|
||||
def write_properties(directory, online):
|
||||
props = dict(PROPERTIES, **{'server-port': str(free_port()), 'online-mode': str(online).lower()})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
|
||||
encoding='iso-8859-1')
|
||||
|
||||
|
||||
def files(directory):
|
||||
out = []
|
||||
for name in FILES:
|
||||
path = directory / name
|
||||
if not path.exists():
|
||||
out.append(f'{name}: missing')
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8')
|
||||
# The dates written now: a month on for the cache, the ban's creation.
|
||||
text = re.sub(r'"(expiresOn|created)": ?"20[2-3]\d-[^"]*"', r'"\1":"<now>"', text)
|
||||
out.append(f'{name}: {text}')
|
||||
return out
|
||||
|
||||
|
||||
def wait_after(server, seen, pattern, timeout=60):
|
||||
"""Waits for a line matching `pattern` after the first `seen` lines."""
|
||||
deadline = time.time() + timeout
|
||||
regex = re.compile(pattern)
|
||||
while not any(regex.search(l) for l in server.lines[seen:]):
|
||||
if time.time() > deadline or server.process.poll() is not None:
|
||||
raise AssertionError(f'{server.log_path.name}: no reply matching {pattern!r}:\n'
|
||||
+ '\n'.join(server.lines[-20:]))
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
def run(label, command, build, services, steps, online, transcript):
|
||||
directory = build / label
|
||||
write_properties(directory, online)
|
||||
server = Server(command, directory, f'{label}-{"online" if online else "offline"}')
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
services.take()
|
||||
for line, reply in steps:
|
||||
seen = len(server.lines)
|
||||
server.console(line)
|
||||
wait_after(server, seen, reply)
|
||||
replies = [l for l in server.lines[seen:] if 'System chat:' in l]
|
||||
transcript.append(f'> {line}')
|
||||
transcript += [re.sub(r'^\[[^]]*\] ', '', l) for l in replies]
|
||||
transcript.append(f'asked: {services.take()}')
|
||||
finally:
|
||||
server.stop()
|
||||
transcript += files(directory)
|
||||
|
||||
|
||||
def run_side(label, command, build, services):
|
||||
directory = build / label
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
directory.mkdir(parents=True)
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
(directory / 'usercache.json').write_text(json.dumps(SEEDED), encoding='utf-8')
|
||||
transcript = []
|
||||
run(label, command, build, services, OFFLINE, False, transcript)
|
||||
run(label, command, build, services, ONLINE, True, transcript)
|
||||
return transcript
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
services = Services()
|
||||
discovery = services.url + '/minecraft/client'
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}',
|
||||
'-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
os.environ['HORIZON_API_DISCOVERY'] = discovery
|
||||
try:
|
||||
vanilla = run_side('vanilla', vanilla_server, build, services)
|
||||
horizon = run_side('horizon', horizon_server, build, services)
|
||||
finally:
|
||||
services.stop()
|
||||
(build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8')
|
||||
(build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8')
|
||||
if vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
|
||||
raise AssertionError(f'transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + diff[:6000])
|
||||
if not any('Notch' in l for l in vanilla if l.startswith('usercache.json')):
|
||||
raise AssertionError(f'the cache never held the looked-up account (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='usercache.json (load, expiry, most recently used order, Gson output) and the console finding '
|
||||
'players by name through it and the profile service, offline and online.'))
|
||||
print(f'user cache: {len(vanilla)} lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
Reference in New Issue
Block a user