Files
WoW-Hybrid-gateway/ops/launcher_trace_journal.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

260 lines
11 KiB
Python

"""Private bounded opcode metadata journal; never stores packet bytes or identities.
Uses only snapshots the supervisor already reads. Direct writes survive a client
crash independently of Lua SavedVariables; the32-row source ring can still lose
bursts and the final unsampled interval. This is not lossless packet recording.
"""
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import time
REVISION = re.compile(r"[0-9a-f]{40}\Z")
STATUS_FIELDS = ("error", "closed", "world_auth")
WORLD_STATUS_FIELDS = ("login_sent", "self_create", "received", "queued", "ignored")
WORLD_FAILURE_FIELDS = ("phase", "result", "source_opcode", "source_bytes",
"modern_opcode", "modern_bytes", "required", "capacity", "count", "index")
def uint(value, maximum=0xffffffff):
return type(value) is int and 0 <= value <= maximum
class DisabledJournal:
active = False
def sample(self, _pipe):
return False
def close(self):
pass
class TraceJournal:
def __init__(self, runtime, revision, pid, *, manifest_sha256=None,
max_bytes=262144, keep_files=4):
if not isinstance(revision, str) or not REVISION.fullmatch(revision):
raise ValueError("Exact build revision required")
if not uint(pid, 0x7fffffff) or not pid:
raise ValueError("Positive native PID required")
if not uint(max_bytes, 1048576) or max_bytes < 4096 or not uint(keep_files, 8) or keep_files < 1:
raise ValueError("Bounded journal retention required")
if manifest_sha256 is not None and (not isinstance(manifest_sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", manifest_sha256)):
raise ValueError("Release manifest digest differs")
self.revision, self.pid = revision, pid
self.manifest_sha256 = manifest_sha256
self.max_bytes, self.keep_files = max_bytes, keep_files
self.directory, self.fd = None, None
self.active = False
self.last = None
self.epoch = self.segment = self.size = 0
self.sampled = self.lost = self.invalid = self.invalid_rows = self.rotations = 0
self.last_status = None
self.session_started_ns = time.time_ns()
self.prefix = "trace-" + revision
runtime = Path(runtime)
parent = os.open(runtime, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
st = os.fstat(parent)
if st.st_uid != os.getuid() or st.st_mode & 0o022:
raise ValueError("Owned runtime directory required")
try:
os.mkdir("launcher-traces", 0o700, dir_fd=parent)
except FileExistsError:
pass
self.directory = os.open("launcher-traces", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
st = os.fstat(self.directory)
if st.st_uid != os.getuid() or st.st_mode & 0o077:
raise ValueError("Private owned journal directory required")
self.active = True
if self._safe_existing(self._name(0)):
self._rotate()
else:
self._open()
except Exception:
self._disable()
raise
finally:
os.close(parent)
@classmethod
def from_release(cls, root, pid, *, log=None):
"""Unpackaged/unsafe/unwritable capture fails soft, never fails gameplay."""
try:
root = Path(root)
path = root / "linux-release.json"
st = path.lstat()
if not stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid() or not 1 <= st.st_size <= 1048576:
raise ValueError("Owned bounded release manifest required")
with path.open("rb") as stream:
raw = stream.read(1048577)
if len(raw) != st.st_size:
raise ValueError("Release manifest changed")
manifest = json.loads(raw)
if manifest.get("kind") != "linux-forever-client-folder-package-v1":
raise ValueError("Release manifest kind differs")
return cls(root / "runtime", manifest.get("source_git_revision"), pid,
manifest_sha256=hashlib.sha256(raw).hexdigest())
except Exception as error:
if log is not None:
try:
print("Numeric trace journal unavailable (" + type(error).__name__ + "); gameplay preserved.", file=log)
except Exception:
pass
return DisabledJournal()
def _name(self, index):
return self.prefix + "." + str(index) + ".jsonl"
def _safe_existing(self, name):
try:
st = os.stat(name, dir_fd=self.directory, follow_symlinks=False)
except FileNotFoundError:
return False
if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid()
or stat.S_IMODE(st.st_mode) != 0o600 or st.st_nlink != 1 or st.st_size > self.max_bytes):
raise ValueError("Unsafe journal segment preserved")
return True
def _open(self):
self.fd = os.open(self._name(0), os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
0o600, dir_fd=self.directory)
os.fchmod(self.fd, 0o600)
self.size = 0
header = dict(schema=1, event="segment", build_revision=self.revision,
native_pid=self.pid, segment=self.segment, epoch=self.epoch,
session_started_unix_ns=self.session_started_ns,
observed_monotonic_ns=time.monotonic_ns(), max_segment_bytes=self.max_bytes,
retained_segments=self.keep_files)
if self.manifest_sha256 is not None:
header["release_manifest_sha256"] = self.manifest_sha256
self._write(header, rotate=False)
def _rotate(self):
if self.fd is not None:
os.close(self.fd)
self.fd = None
for index in range(self.keep_files):
self._safe_existing(self._name(index))
oldest = self._name(self.keep_files - 1)
if self._safe_existing(oldest):
os.unlink(oldest, dir_fd=self.directory)
for index in range(self.keep_files - 2, -1, -1):
if self._safe_existing(self._name(index)):
os.replace(self._name(index), self._name(index + 1),
src_dir_fd=self.directory, dst_dir_fd=self.directory)
self.segment += 1
self.rotations += 1
self._open()
def _write(self, record, *, rotate=True):
data = (json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii")
if len(data) > self.max_bytes:
raise ValueError("Journal record exceeds segment bound")
if rotate and self.size + len(data) > self.max_bytes:
self._rotate()
offset = 0
while offset < len(data):
written = os.write(self.fd, data[offset:])
if written <= 0:
raise OSError("Short journal write")
offset += written
self.size += len(data)
def _status(self, pipe, world):
status = {}
for key in STATUS_FIELDS:
value = pipe.get(key)
if type(value) is bool:
value = int(value)
if uint(value):
status[key] = value
for key in WORLD_STATUS_FIELDS:
value = world.get(key)
if type(value) is bool:
value = int(value)
if uint(value):
status["world_" + key] = value
# Reuse the public ABI1 drain diagnostic already decoded by the pipe
# observer. Retain only a complete numeric record, never arbitrary fields.
failure = pipe.get("world_failure")
if isinstance(failure, dict) and all(
type(failure.get(key)) is int and
(-0x80000000 <= failure[key] <= 0x7fffffff if key == "result" else
uint(failure[key], 11 if key == "phase" else 0xffffffff))
for key in WORLD_FAILURE_FIELDS):
status.update(("world_failure_" + key, failure[key]) for key in WORLD_FAILURE_FIELDS)
if status != self.last_status:
self._write(dict(event="status", epoch=self.epoch,
observed_monotonic_ns=time.monotonic_ns(), **status))
self.last_status = status
def sample(self, pipe):
if not self.active:
return False
try:
if not isinstance(pipe, dict) or not isinstance(pipe.get("world"), dict):
self.invalid += 1
return False
world = pipe["world"]
self._status(pipe, world)
count, rows = world.get("trace_count"), world.get("trace")
if not uint(count) or not isinstance(rows, list) or len(rows) > 32 or count < len(rows):
self.invalid += 1
return False
start = count - len(rows)
if self.last is not None and count < self.last:
self.epoch += 1
self._write(dict(event="counter_reset", epoch=self.epoch, previous_count=self.last, trace_count=count))
self.last = None
before = 0 if self.last is None else self.last
lost = max(0, start - before)
if lost:
self.lost += lost
self._write(dict(event="ring_gap", epoch=self.epoch, first_missing_sequence=before,
missing_rows=lost, cumulative_missing_rows=self.lost))
sampled_at = time.monotonic_ns()
for sequence, row in enumerate(rows, start):
if sequence < before:
continue
if (not isinstance(row, dict) or not uint(row.get("direction"), 4)
or row["direction"] == 0 or not uint(row.get("opcode")) or not uint(row.get("bytes"))):
self.invalid_rows += 1
self._write(dict(event="invalid_row", epoch=self.epoch, sequence=sequence))
continue
self._write(dict(event="packet_metadata", epoch=self.epoch, sequence=sequence,
observed_monotonic_ns=sampled_at,
direction=row["direction"], opcode=row["opcode"], bytes=row["bytes"]))
self.sampled += 1
self.last = count
return True
except Exception:
self._disable()
return False
def _disable(self):
self.active = False
if self.fd is not None:
try:
os.close(self.fd)
except OSError:
pass
self.fd = None
if self.directory is not None:
try:
os.close(self.directory)
except OSError:
pass
self.directory = None
def close(self):
if self.active:
try:
self._write(dict(event="finished", epoch=self.epoch, sampled_rows=self.sampled,
missing_ring_rows=self.lost, invalid_snapshots=self.invalid,
invalid_rows=self.invalid_rows, rotated_segments=self.rotations))
except Exception:
pass
self._disable()