mirror of
https://github.com/db9979/uconsole_asw_game.git
synced 2026-12-05 12:24:25 +01:00
Core split 6/6: Remote Crew transport into src/commander/v2 (wire, commands, routes)
server.py keeps CommanderServer and re-exports the rest; the grant table moves to wire.py so the routes never import the server module. The public logger name stays src.commander.server. tests/test_module_size.py holds every source module under 2500 lines. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
6e898c299f
commit
facd86e107
8 files changed
+2179
-1958
No files matched your search
+130
-1957
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
"""Remote Crew protocol v2 transport pieces (plan 1.3, phase 2, step 6):
|
||||
wire constants and helpers, the closed command registry and the HTTP/WebSocket
|
||||
routes. ``src.commander.server`` remains the facade that owns CommanderServer."""
|
||||
@@ -0,0 +1,593 @@
|
||||
"""The closed Remote Crew v2 command surface: per-action parameter validators,
|
||||
the action registry and the command envelope (verbatim from ``server.py``)."""
|
||||
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import math
|
||||
import unicodedata
|
||||
|
||||
from src.core import plot
|
||||
from src.core.config import (NATO_AFFILIATIONS, PLAYER_CLASSES,
|
||||
RADAR_RANGE_SCALES_NM, SHIP_SPEED_MAX_KN,
|
||||
HELO_DIP_DEPTH_MIN_M, HELO_DIP_DEPTH_MAX_M,
|
||||
DIFFICULTY_FIELDS, SAVE_SLOTS, SCENARIO_ORDER)
|
||||
from src.commander.v2.wire import (
|
||||
HOST_ROLE,
|
||||
ROLES,
|
||||
STATIONS,
|
||||
_V2_COMMAND_FIELDS)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class V2Action:
|
||||
"""Closed command metadata; M6/M7 add schemas and main-thread handlers here."""
|
||||
|
||||
stations: frozenset
|
||||
validate_params: object
|
||||
direct_fire: bool = False
|
||||
phases: frozenset = frozenset({"live"})
|
||||
# Only operator annotations of the shared picture are optimistic edits that
|
||||
# must match the crew assessment revision the browser saw. Every other
|
||||
# action resolves its opaque refs (if any) at apply time, so an unrelated
|
||||
# contact change must not reject it.
|
||||
revision_bound: bool = False
|
||||
|
||||
|
||||
def _no_params(params):
|
||||
return type(params) is dict and not params
|
||||
|
||||
|
||||
def _course_params(params):
|
||||
return (type(params) is dict and set(params) == {"course"}
|
||||
and type(params["course"]) in (int, float)
|
||||
and 0 <= params["course"] < 360)
|
||||
|
||||
|
||||
def _speed_params(params):
|
||||
return (type(params) is dict and set(params) == {"speed_kn"}
|
||||
and type(params["speed_kn"]) in (int, float)
|
||||
and 0 <= params["speed_kn"] <= SHIP_SPEED_MAX_KN)
|
||||
|
||||
|
||||
def _ref(value):
|
||||
return (type(value) is str and 1 <= len(value) <= 64
|
||||
and not any(unicodedata.category(char).startswith("C") for char in value))
|
||||
|
||||
|
||||
def _classification_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "classification"}
|
||||
and _ref(params["ref"])
|
||||
and (params["classification"] is None
|
||||
or params["classification"] in PLAYER_CLASSES))
|
||||
|
||||
|
||||
def _release_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "released"}
|
||||
and _ref(params["ref"]) and type(params["released"]) is bool)
|
||||
|
||||
|
||||
def _affiliation_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "affiliation"}
|
||||
and _ref(params["ref"])
|
||||
and params["affiliation"] in NATO_AFFILIATIONS)
|
||||
|
||||
|
||||
def _fusion_refs_params(params):
|
||||
refs = params.get("refs") if type(params) is dict and set(params) == {"refs"} else None
|
||||
return (type(refs) is list and 2 <= len(refs) <= 8
|
||||
and all(_ref(ref) for ref in refs) and len(set(refs)) == len(refs))
|
||||
|
||||
|
||||
def _single_ref_params(params):
|
||||
return type(params) is dict and set(params) == {"ref"} and _ref(params["ref"])
|
||||
|
||||
|
||||
def _track_label_params(params):
|
||||
if (type(params) is not dict or set(params) != {"ref", "label"}
|
||||
or not _ref(params["ref"]) or type(params["label"]) is not str):
|
||||
return False
|
||||
label = params["label"]
|
||||
return (1 <= len(label) <= 16 and label.isascii()
|
||||
and any(char.isalnum() for char in label)
|
||||
and all(char.isalnum() or char == "-" for char in label))
|
||||
|
||||
|
||||
def _torpedo_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "depth_m"}
|
||||
and _ref(params["ref"])
|
||||
and type(params["depth_m"]) in (int, float)
|
||||
and math.isfinite(params["depth_m"])
|
||||
and 10 <= params["depth_m"] <= 300)
|
||||
|
||||
|
||||
def _radar_params(params):
|
||||
return (type(params) is dict and set(params) == {"domain", "enabled"}
|
||||
and params["domain"] in ("surface", "air")
|
||||
and type(params["enabled"]) is bool)
|
||||
|
||||
|
||||
def _range_params(params):
|
||||
return (type(params) is dict and set(params) == {"range_nm"}
|
||||
and type(params["range_nm"]) in (int, float)
|
||||
and params["range_nm"] in RADAR_RANGE_SCALES_NM)
|
||||
|
||||
|
||||
# Rejections of the crewed submarine's own orders (their own vocabulary,
|
||||
# never the frigate's words).
|
||||
UBOOT_REASONS = frozenset((
|
||||
"uboot_no_torpedoes", "uboot_reloading", "uboot_out_of_arc", "uboot_no_decoys",
|
||||
"uboot_too_deep", "uboot_no_snorkel", "uboot_no_wire", "uboot_mast_depth"))
|
||||
|
||||
|
||||
def _bool_params(name):
|
||||
return lambda params: (type(params) is dict and set(params) == {name}
|
||||
and type(params[name]) is bool)
|
||||
|
||||
|
||||
def _enum_params(name, values):
|
||||
return lambda params: (type(params) is dict and set(params) == {name}
|
||||
and type(params[name]) is str
|
||||
and params[name] in values)
|
||||
|
||||
|
||||
def _bounded_number_params(name, minimum, maximum, *, nullable=False):
|
||||
def validate(params):
|
||||
if type(params) is not dict or set(params) != {name}:
|
||||
return False
|
||||
value = params[name]
|
||||
if nullable and value is None:
|
||||
return True
|
||||
return (type(value) in (int, float)
|
||||
and minimum <= value <= maximum and math.isfinite(value))
|
||||
return validate
|
||||
|
||||
|
||||
_COMPARTMENTS = frozenset(("bridge", "sonar", "weapons", "opz", "radio",
|
||||
"engine", "flightdeck", "hull_left", "hull_right"))
|
||||
|
||||
|
||||
def _sonar_cursor_params(params):
|
||||
return (type(params) is dict and set(params) == {"page", "frequency_hz"}
|
||||
and params["page"] in ("lofar", "demon")
|
||||
and type(params["frequency_hz"]) in (int, float)
|
||||
and math.isfinite(params["frequency_hz"])
|
||||
and 0.0 <= params["frequency_hz"] <= 300.0)
|
||||
|
||||
|
||||
def _sonar_band_params(params):
|
||||
return (type(params) is dict and set(params) == {"low_hz", "high_hz"}
|
||||
and all(type(params[name]) in (int, float) and math.isfinite(params[name])
|
||||
for name in ("low_hz", "high_hz"))
|
||||
and 0.0 <= params["low_hz"] < params["high_hz"] <= 300.0)
|
||||
|
||||
|
||||
def _tas_side_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "action"}
|
||||
and type(params["ref"]) is str and 0 < len(params["ref"]) <= 64
|
||||
and params["action"] in ("flip", "confirm"))
|
||||
|
||||
|
||||
def _demon_band_params(params):
|
||||
return (type(params) is dict and set(params) == {"low_hz", "high_hz"}
|
||||
and (params["low_hz"], params["high_hz"]) in ((200, 800), (400, 1400),
|
||||
(1000, 2000)))
|
||||
|
||||
|
||||
def _assign_profile_params(params):
|
||||
key = params.get("profile_key") if type(params) is dict else None
|
||||
return (type(params) is dict and set(params) == {"ref", "profile_key"}
|
||||
and type(params["ref"]) is str and 0 < len(params["ref"]) <= 64
|
||||
and (key is None or (type(key) is str and 0 < len(key) <= 64)))
|
||||
|
||||
|
||||
def _tma_hypothesis_params(params):
|
||||
return (type(params) is dict
|
||||
and set(params) == {"ref", "course", "speed_kn", "range_nm"}
|
||||
and type(params["ref"]) is str and 0 < len(params["ref"]) <= 64
|
||||
and all(type(params[name]) in (int, float) and math.isfinite(params[name])
|
||||
for name in ("course", "speed_kn", "range_nm"))
|
||||
and 0.0 <= params["course"] < 360.0 and 0.0 <= params["speed_kn"] <= 45.0
|
||||
and 0.2 <= params["range_nm"] <= 60.0)
|
||||
|
||||
|
||||
def _plot_add_params(params):
|
||||
shape = params.get("shape") if type(params) is dict else None
|
||||
if shape not in plot.KINDS:
|
||||
return False
|
||||
item = {("kind" if key == "shape" else key): value for key, value in params.items()}
|
||||
return (set(item) == plot.command_fields(shape)
|
||||
and plot.valid_object(dict(item, id=1, t=0.0)))
|
||||
|
||||
|
||||
def _plot_id(value):
|
||||
return type(value) is int and 1 <= value <= plot.MAX_ID
|
||||
|
||||
|
||||
def _plot_remove_params(params):
|
||||
return type(params) is dict and set(params) == {"id"} and _plot_id(params["id"])
|
||||
|
||||
|
||||
def _plot_relabel_params(params):
|
||||
return (type(params) is dict and set(params) == {"id", "label"}
|
||||
and _plot_id(params["id"]) and plot.valid_label(params["label"]))
|
||||
|
||||
|
||||
def _integration_params(params):
|
||||
return (type(params) is dict and set(params) == {"seconds"}
|
||||
and type(params["seconds"]) is int and params["seconds"] in (2, 8, 16, 64))
|
||||
|
||||
|
||||
def _team_compartment_params(params):
|
||||
return (type(params) is dict and set(params) == {"team", "compartment"}
|
||||
and type(params["team"]) is int and 1 <= params["team"] <= 3
|
||||
and type(params["compartment"]) is str
|
||||
and params["compartment"] in _COMPARTMENTS)
|
||||
|
||||
|
||||
def _annotation_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "candidate_ref"}
|
||||
and _ref(params["ref"]) and _ref(params["candidate_ref"]))
|
||||
|
||||
|
||||
def _ecm_technique_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "technique"}
|
||||
and _ref(params["ref"])
|
||||
and params["technique"] in (
|
||||
"noise", "rgpo", "vgpo", "false_targets"))
|
||||
|
||||
|
||||
def _waypoint_params(params):
|
||||
return (type(params) is dict and set(params) == {"x", "y"}
|
||||
and all(type(params[key]) in (int, float)
|
||||
and 0 <= params[key] <= 1000 and math.isfinite(params[key])
|
||||
for key in ("x", "y")))
|
||||
|
||||
|
||||
def _uboot_depth_params(params):
|
||||
return (type(params) is dict and set(params) == {"depth_m"}
|
||||
and type(params["depth_m"]) in (int, float)
|
||||
and math.isfinite(params["depth_m"])
|
||||
and 0 <= params["depth_m"] <= 1000)
|
||||
|
||||
|
||||
def _uboot_speed_params(params):
|
||||
return (type(params) is dict and set(params) == {"speed_kn"}
|
||||
and type(params["speed_kn"]) in (int, float)
|
||||
and math.isfinite(params["speed_kn"])
|
||||
and 0 <= params["speed_kn"] <= 40)
|
||||
|
||||
|
||||
def _uboot_wire_params(params):
|
||||
"""Steer a wired crew torpedo: its ref and the new datum from the boat."""
|
||||
return (type(params) is dict and set(params) == {"ref", "bearing", "range_nm"}
|
||||
and _ref(params["ref"])
|
||||
and all(type(params[key]) in (int, float) and math.isfinite(params[key])
|
||||
for key in ("bearing", "range_nm"))
|
||||
and 0 <= params["bearing"] < 360 and 0.05 <= params["range_nm"] <= 40)
|
||||
|
||||
|
||||
def _uboot_fire_params(params):
|
||||
"""A crew shot: a sonar contact ref, or a free bearing with optional range;
|
||||
run depth (optional) and one or two torpedoes."""
|
||||
if type(params) is not dict or set(params) != {"ref", "bearing", "range_nm",
|
||||
"depth_m", "salvo"}:
|
||||
return False
|
||||
ref, bearing, range_nm = params["ref"], params["bearing"], params["range_nm"]
|
||||
depth = params["depth_m"]
|
||||
if type(params["salvo"]) is not int or params["salvo"] not in (1, 2):
|
||||
return False
|
||||
if depth is not None and not (type(depth) in (int, float) and math.isfinite(depth)
|
||||
and 5 <= depth <= 300):
|
||||
return False
|
||||
if (ref is None) == (bearing is None):
|
||||
return False
|
||||
if ref is not None and not _ref(ref):
|
||||
return False
|
||||
if bearing is not None and not (type(bearing) in (int, float)
|
||||
and math.isfinite(bearing) and 0 <= bearing < 360):
|
||||
return False
|
||||
return range_nm is None or (type(range_nm) in (int, float)
|
||||
and math.isfinite(range_nm)
|
||||
and 0.05 <= range_nm <= 40)
|
||||
|
||||
|
||||
def _bearing_params(params):
|
||||
return (type(params) is dict and set(params) == {"bearing"}
|
||||
and type(params["bearing"]) in (int, float)
|
||||
and 0 <= params["bearing"] < 360
|
||||
and math.isfinite(params["bearing"]))
|
||||
|
||||
|
||||
def _navigation_proposal_params(params):
|
||||
if (type(params) is not dict or not params
|
||||
or not set(params) <= {"course", "speed_kn"}):
|
||||
return False
|
||||
course = params.get("course")
|
||||
speed = params.get("speed_kn")
|
||||
return ((course is None or type(course) in (int, float)
|
||||
and math.isfinite(course) and 0 <= course < 360)
|
||||
and (speed is None or type(speed) in (int, float)
|
||||
and math.isfinite(speed) and 0 <= speed <= SHIP_SPEED_MAX_KN)
|
||||
and (course is not None or speed is not None))
|
||||
|
||||
|
||||
def _ref_enabled_params(params):
|
||||
return (type(params) is dict and set(params) == {"ref", "enabled"}
|
||||
and _ref(params.get("ref"))
|
||||
and type(params.get("enabled")) is bool)
|
||||
|
||||
|
||||
def _slot_params(params):
|
||||
return (type(params) is dict and set(params) == {"slot"}
|
||||
and type(params["slot"]) is int and 1 <= params["slot"] <= SAVE_SLOTS)
|
||||
|
||||
|
||||
def _instructor_environment_params(params):
|
||||
return (type(params) is dict and set(params) == {"sea_state", "event"}
|
||||
and type(params["sea_state"]) is int
|
||||
and 0 <= params["sea_state"] <= 6
|
||||
and (params["event"] is None or params["event"] in (
|
||||
"targets_quiet", "targets_cruise", "targets_flank",
|
||||
"torpedo_transient")))
|
||||
|
||||
|
||||
def _new_game_params(params):
|
||||
required = {"scenario", "world_mode"}
|
||||
if (type(params) is not dict or not required <= set(params)
|
||||
or not set(params) <= required | {"difficulty", "seed"}):
|
||||
return False
|
||||
if not (type(params["scenario"]) is str and params["scenario"] in SCENARIO_ORDER
|
||||
and type(params["world_mode"]) is str
|
||||
and params["world_mode"] in ("fixed", "procedural", "real_fixed")
|
||||
and ("seed" not in params or type(params["seed"]) is int
|
||||
and 1 <= params["seed"] < 1_000_000_000)):
|
||||
return False
|
||||
if "difficulty" not in params:
|
||||
return True
|
||||
difficulty = params["difficulty"]
|
||||
if type(difficulty) is not dict or set(difficulty) != set(DIFFICULTY_FIELDS):
|
||||
return False
|
||||
for name, (kind, low, high, _step, _default) in DIFFICULTY_FIELDS.items():
|
||||
amount = difficulty[name]
|
||||
if kind is int:
|
||||
if type(amount) is not int or not low <= amount <= high:
|
||||
return False
|
||||
elif (type(amount) not in (int, float) or isinstance(amount, bool)
|
||||
or not math.isfinite(amount) or not low <= amount <= high):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
_HOST_ANY = frozenset({"live"})
|
||||
_HOST_REPLACING = frozenset({"live", "menu", "ended"})
|
||||
_HOST_STATIONS = frozenset({HOST_ROLE})
|
||||
# The boat's own plot: its commander and navigator draw on it.
|
||||
_UBOOT_PLOT = ("uboot", "uboot_nav")
|
||||
|
||||
V2_ACTION_REGISTRY = {
|
||||
"acknowledge": V2Action(frozenset(ROLES), _no_params),
|
||||
# Shared chart plot: every station may draw, relabel and erase.
|
||||
# The submarine commander's plot actions reach the boat's own plot.
|
||||
"plot_add": V2Action(frozenset((*STATIONS, *_UBOOT_PLOT)), _plot_add_params),
|
||||
"plot_remove": V2Action(frozenset((*STATIONS, *_UBOOT_PLOT)), _plot_remove_params),
|
||||
"plot_relabel": V2Action(frozenset((*STATIONS, *_UBOOT_PLOT)), _plot_relabel_params),
|
||||
"plot_clear": V2Action(frozenset((*STATIONS, *_UBOOT_PLOT)), _no_params),
|
||||
# Solo-only host controls: admitted only for a session carrying the host
|
||||
# surface, and each action states the exact phases it may run in.
|
||||
"host_save": V2Action(_HOST_STATIONS, _slot_params, phases=_HOST_ANY),
|
||||
"host_load": V2Action(_HOST_STATIONS, _slot_params, phases=_HOST_REPLACING),
|
||||
"host_new_game": V2Action(_HOST_STATIONS, _new_game_params,
|
||||
phases=_HOST_REPLACING),
|
||||
"host_instructor_environment": V2Action(
|
||||
_HOST_STATIONS, _instructor_environment_params, phases=_HOST_ANY),
|
||||
"bridge_set_course": V2Action(frozenset({"bridge"}), _course_params),
|
||||
"bridge_set_speed": V2Action(frozenset({"bridge"}), _speed_params),
|
||||
"propose_navigation": V2Action(frozenset({"bridge"}),
|
||||
_navigation_proposal_params),
|
||||
"sonar_classify": V2Action(frozenset({"sonar", "helicopter", "uboot_sonar"}), _classification_params,
|
||||
revision_bound=True),
|
||||
"sonar_set_release": V2Action(frozenset({"sonar", "helicopter"}), _release_params,
|
||||
revision_bound=True),
|
||||
"helicopter_qualify": V2Action(frozenset({"helicopter"}), _ref_enabled_params,
|
||||
revision_bound=True),
|
||||
"helicopter_buoy_release": V2Action(frozenset({"helicopter"}), _release_params,
|
||||
revision_bound=True),
|
||||
"propose_target": V2Action(frozenset({"sonar"}), _single_ref_params,
|
||||
revision_bound=True),
|
||||
"clear_target_proposal": V2Action(frozenset({"sonar"}), _no_params),
|
||||
"opz_classify": V2Action(frozenset({"opz"}), _classification_params,
|
||||
revision_bound=True),
|
||||
"opz_affiliate": V2Action(frozenset({"opz"}), _affiliation_params,
|
||||
revision_bound=True),
|
||||
"opz_set_track_id": V2Action(frozenset({"opz"}), _track_label_params,
|
||||
revision_bound=True),
|
||||
"opz_create_fusion": V2Action(frozenset({"opz"}), _fusion_refs_params,
|
||||
revision_bound=True),
|
||||
"opz_dissolve_fusion": V2Action(frozenset({"opz"}), _single_ref_params,
|
||||
revision_bound=True),
|
||||
"opz_set_radar": V2Action(frozenset({"opz"}), _radar_params),
|
||||
"opz_mark_blip": V2Action(frozenset({"opz"}), _single_ref_params),
|
||||
"opz_set_ciws": V2Action(frozenset({"opz"}), _bool_params("enabled")),
|
||||
"opz_set_range": V2Action(frozenset({"opz"}), _range_params),
|
||||
"opz_designate_target": V2Action(frozenset({"opz"}), _single_ref_params),
|
||||
"engine_set_telegraph": V2Action(frozenset({"engine"}), _enum_params(
|
||||
"order", ("ASTERN", "STOP", "SLOW", "HALF", "FULL", "FLANK"))),
|
||||
"engine_set_course": V2Action(frozenset({"engine"}), _course_params),
|
||||
"engine_set_speed": V2Action(frozenset({"engine"}), _speed_params),
|
||||
"engine_set_quiet_mode": V2Action(frozenset({"engine"}),
|
||||
_bool_params("enabled")),
|
||||
"damage_assign_team": V2Action(frozenset({"damage"}),
|
||||
_team_compartment_params),
|
||||
"damage_unassign_team": V2Action(frozenset({"damage"}),
|
||||
_team_compartment_params),
|
||||
"radio_capture_hfdf": V2Action(frozenset({"radio"}), _single_ref_params),
|
||||
"eloka_annotate": V2Action(frozenset({"eloka"}), _annotation_params,
|
||||
revision_bound=True),
|
||||
"eloka_clear_annotation": V2Action(frozenset({"eloka"}), _single_ref_params,
|
||||
revision_bound=True),
|
||||
"eloka_set_jamming": V2Action(frozenset({"eloka"}), _ref_enabled_params),
|
||||
"eloka_set_technique": V2Action(
|
||||
frozenset({"eloka"}), _ecm_technique_params),
|
||||
"eloka_set_auto": V2Action(frozenset({"eloka"}), _bool_params("enabled")),
|
||||
"sonar_set_listen_bearing": V2Action(frozenset({"sonar", "uboot_sonar"}), _bearing_params),
|
||||
"sonar_set_focus": V2Action(frozenset({"sonar", "uboot_sonar"}), _single_ref_params),
|
||||
"sonar_clear_focus": V2Action(frozenset({"sonar", "uboot_sonar"}), _no_params),
|
||||
"sonar_set_array_mode": V2Action(frozenset({"sonar"}),
|
||||
_enum_params("mode", ("BOW", "TOWED"))),
|
||||
"sonar_set_tas": V2Action(frozenset({"sonar"}), _bool_params("deployed")),
|
||||
"sonar_set_tow_depth": V2Action(frozenset({"sonar"}),
|
||||
_bounded_number_params("depth_m", 20, 260)),
|
||||
# The submarine commander may ping and take a BT without its sonar room.
|
||||
"sonar_measure_bt": V2Action(frozenset({"sonar", "uboot_sonar", "uboot"}), _no_params),
|
||||
"sonar_active_ping": V2Action(frozenset({"sonar", "uboot_sonar", "uboot"}), _no_params),
|
||||
"sonar_set_tma_enabled": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_bool_params("enabled")),
|
||||
"sonar_set_gain": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_bounded_number_params("gain_db", -12, 24)),
|
||||
"sonar_set_audition_mode": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_enum_params("mode", ("BROADBAND", "FILTERED", "HETERODYNE"))),
|
||||
"sonar_set_band_preset": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_enum_params("preset", ("FULL", "LOW", "SHAFT", "MID"))),
|
||||
"sonar_set_notch": V2Action(frozenset({"sonar", "uboot_sonar"}), _bool_params("enabled")),
|
||||
"sonar_set_cursor": V2Action(frozenset({"sonar", "uboot_sonar"}), _sonar_cursor_params),
|
||||
"sonar_mark_line": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_enum_params("page", ("lofar", "demon"))),
|
||||
"sonar_set_integration": V2Action(frozenset({"sonar", "uboot_sonar"}), _integration_params),
|
||||
"sonar_set_vernier": V2Action(frozenset({"sonar", "uboot_sonar"}), _bool_params("enabled")),
|
||||
"sonar_set_band": V2Action(frozenset({"sonar", "uboot_sonar"}), _sonar_band_params),
|
||||
"sonar_set_operator_notch": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_bounded_number_params("frequency_hz", 0.000001, 300, nullable=True)),
|
||||
"sonar_set_peak_hold": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_bool_params("enabled")),
|
||||
"sonar_set_harmonic": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_bounded_number_params("frequency_hz", 0.000001, 300, nullable=True)),
|
||||
"sonar_designate_target": V2Action(frozenset({"sonar", "uboot_sonar"}), _single_ref_params),
|
||||
"sonar_tma_set": V2Action(frozenset({"sonar", "uboot_sonar"}), _tma_hypothesis_params),
|
||||
"sonar_assign_profile": V2Action(frozenset({"sonar", "uboot_sonar"}), _assign_profile_params),
|
||||
"sonar_tas_side": V2Action(frozenset({"sonar"}), _tas_side_params),
|
||||
"sonar_set_demon_band": V2Action(frozenset({"sonar", "uboot_sonar"}), _demon_band_params),
|
||||
"sonar_set_heterodyne": V2Action(frozenset({"sonar", "uboot_sonar"}),
|
||||
_bounded_number_params("frequency_hz", 400, 1200)),
|
||||
"sonar_tma_accept": V2Action(frozenset({"sonar", "uboot_sonar"}), _single_ref_params),
|
||||
"sonar_tma_copy_proposal": V2Action(frozenset({"sonar", "uboot_sonar"}), _single_ref_params),
|
||||
"helicopter_launch": V2Action(frozenset({"helicopter"}), _no_params),
|
||||
"helicopter_return": V2Action(frozenset({"helicopter"}), _no_params),
|
||||
"helicopter_set_waypoint": V2Action(frozenset({"helicopter"}),
|
||||
_waypoint_params),
|
||||
"helicopter_deploy_buoy": V2Action(frozenset({"helicopter"}), _no_params),
|
||||
"helicopter_set_buoy_mode": V2Action(frozenset({"helicopter"}),
|
||||
_enum_params("mode", ("PASSIVE", "ACTIVE"))),
|
||||
"helicopter_set_listen_source": V2Action(frozenset({"helicopter"}),
|
||||
lambda params: (type(params) is dict and set(params) == {"source"}
|
||||
and type(params["source"]) is str
|
||||
and (params["source"] == "DIP" or
|
||||
params["source"].startswith("SB")
|
||||
and params["source"][2:].isdigit()
|
||||
and len(params["source"]) <= 5))),
|
||||
"helicopter_set_listen_bearing": V2Action(frozenset({"helicopter"}),
|
||||
_bounded_number_params("bearing", 0.0, 359.99999999999994)),
|
||||
"helicopter_clear_listen_bearing": V2Action(frozenset({"helicopter"}), _no_params),
|
||||
"helicopter_set_audio_mode": V2Action(frozenset({"helicopter"}),
|
||||
_enum_params("mode", ("BROADBAND", "FILTERED", "HETERODYNE"))),
|
||||
"helicopter_set_audio_band": V2Action(frozenset({"helicopter"}),
|
||||
_enum_params("preset", ("FULL", "LOW", "SHAFT", "MID"))),
|
||||
"helicopter_set_audio_gain": V2Action(frozenset({"helicopter"}),
|
||||
_bounded_number_params("gain_db", -12.0, 24.0)),
|
||||
"helicopter_set_audio_notch": V2Action(frozenset({"helicopter"}),
|
||||
_bool_params("enabled")),
|
||||
"helicopter_set_dipping": V2Action(frozenset({"helicopter"}),
|
||||
_bool_params("deployed")),
|
||||
"helicopter_set_dip_depth": V2Action(frozenset({"helicopter"}),
|
||||
_bounded_number_params("depth_m", HELO_DIP_DEPTH_MIN_M,
|
||||
HELO_DIP_DEPTH_MAX_M)),
|
||||
"helicopter_dipping_ping": V2Action(frozenset({"helicopter"}), _no_params),
|
||||
"weapons_launch_torpedo": V2Action(
|
||||
frozenset({"weapons"}), _torpedo_params, direct_fire=True),
|
||||
"helicopter_launch_torpedo": V2Action(
|
||||
frozenset({"weapons", "helicopter"}), _torpedo_params,
|
||||
direct_fire=True),
|
||||
"weapons_deploy_nixie": V2Action(
|
||||
frozenset({"weapons"}), _no_params, direct_fire=True),
|
||||
"opz_launch_essm": V2Action(
|
||||
frozenset({"opz"}), _single_ref_params, direct_fire=True),
|
||||
"opz_launch_chaff": V2Action(
|
||||
frozenset({"opz"}), _single_ref_params, direct_fire=True),
|
||||
# The crewed submarine's commander.
|
||||
# Each boat order belongs to the station that does it aboard; the commander
|
||||
# keeps course, speed and depth.
|
||||
"uboot_set_course": V2Action(frozenset({"uboot", "uboot_nav"}), _course_params),
|
||||
"uboot_set_speed": V2Action(frozenset({"uboot", "uboot_engine"}), _uboot_speed_params),
|
||||
"uboot_set_depth": V2Action(frozenset({"uboot", "uboot_nav"}), _uboot_depth_params),
|
||||
"uboot_fire": V2Action(frozenset({"uboot_weapons"}), _uboot_fire_params,
|
||||
direct_fire=True),
|
||||
"uboot_decoy": V2Action(frozenset({"uboot_weapons"}), _no_params),
|
||||
"uboot_blow": V2Action(frozenset({"uboot", "uboot_engine"}), _no_params),
|
||||
"uboot_snorkel": V2Action(frozenset({"uboot_engine"}), _bool_params("enabled")),
|
||||
"uboot_mast": V2Action(frozenset({"uboot_esm"}), _bool_params("enabled")),
|
||||
"uboot_wire_steer": V2Action(frozenset({"uboot_weapons"}), _uboot_wire_params),
|
||||
"uboot_wire_cut": V2Action(frozenset({"uboot_weapons"}), _single_ref_params),
|
||||
"uboot_silent": V2Action(frozenset({"uboot", "uboot_engine"}), _bool_params("enabled")),
|
||||
"uboot_bottom": V2Action(frozenset({"uboot", "uboot_nav"}), _bool_params("enabled")),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class V2CommandEnvelope:
|
||||
"""Detached transport record containing no session or simulation objects."""
|
||||
|
||||
session_digest: bytes
|
||||
client_id: str
|
||||
client_ordinal: int
|
||||
role: str
|
||||
lease_generation: int
|
||||
active_generation: int
|
||||
received_at: float
|
||||
body_bytes: bytes
|
||||
command_id: str
|
||||
seq: int
|
||||
|
||||
def body(self):
|
||||
return json.loads(self.body_bytes.decode("ascii"), object_pairs_hook=_object,
|
||||
parse_float=_number, parse_constant=_number)
|
||||
|
||||
|
||||
def _v2_command_valid(command):
|
||||
if (type(command) is not dict or set(command) != _V2_COMMAND_FIELDS
|
||||
or command.get("protocol") != 2):
|
||||
return False
|
||||
action = command.get("action")
|
||||
spec = V2_ACTION_REGISTRY.get(action) if type(action) is str else None
|
||||
if (spec is None or type(command.get("station")) is not str
|
||||
or command["station"] not in spec.stations):
|
||||
return False
|
||||
# The host surface has no station-activation context to bind to.
|
||||
if command["station"] == HOST_ROLE and command.get("active_generation") != 0:
|
||||
return False
|
||||
for field in ("id", "world_session"):
|
||||
value = command.get(field)
|
||||
if (type(value) is not str or not 1 <= len(value) <= 64
|
||||
or any(unicodedata.category(char).startswith("C") for char in value)):
|
||||
return False
|
||||
for field in ("seq", "station_generation", "active_generation", "world_epoch",
|
||||
"resource_revision"):
|
||||
maximum = 2**53 - 2 if field == "seq" else 2**53 - 1
|
||||
if type(command.get(field)) is not int or not 0 <= command[field] <= maximum:
|
||||
return False
|
||||
return spec.validate_params(command.get("params")) is True
|
||||
|
||||
|
||||
def _object(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError("duplicate key")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _number(text):
|
||||
value = float(text)
|
||||
if not math.isfinite(value):
|
||||
raise ValueError("nonfinite number")
|
||||
return value
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,187 @@
|
||||
"""Wire-level constants and helpers of Remote Crew v2: role tables, session and
|
||||
lease limits, JSON/audio payload encoders and WebSocket framing (verbatim
|
||||
from ``server.py``)."""
|
||||
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import struct
|
||||
import re
|
||||
|
||||
|
||||
|
||||
# The public logger name predates the split (tests and operators filter on it).
|
||||
_log = logging.getLogger("src.commander.server")
|
||||
_CONNECTION_DEADLINE_S = 3.0
|
||||
_CONTACT_ASSET_ROUTE = re.compile(
|
||||
r"/contact-analysis/[a-z0-9][a-z0-9_.-]{0,95}-(?:cruise|high|radar)\.png").fullmatch
|
||||
_MAX_PREBUILT_ROUTES = 512 # 3 PNG routes/profile + 1 JSON route; headroom above the current catalog size
|
||||
_MAX_PREBUILT_FILE_BYTES = 4 * 1024 * 1024
|
||||
_MAX_PREBUILT_BYTES = 32 * 1024 * 1024
|
||||
_V2_COOKIE = "ujagd_remote_v2"
|
||||
_WEB_REQUEST_ID = re.compile(
|
||||
r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}").fullmatch
|
||||
_V2_SESSION_IDLE_S = 8 * 60 * 60
|
||||
_V2_STATION_LEASE_S = 15.0
|
||||
_V2_SESSION_LIMIT = 12
|
||||
STATIONS = ("bridge", "sonar", "weapons", "damage", "opz", "radio",
|
||||
"engine", "helicopter", "eloka")
|
||||
# The crewed hostile submarine's six stations (command, sonar, weapons,
|
||||
# engine, mast/ESM, navigation). They are leased like the frigate's but never
|
||||
# belong to the frigate crew: a session holds roles of one side only.
|
||||
OPFOR_ROLES = ("uboot", "uboot_sonar", "uboot_weapons", "uboot_engine", "uboot_esm",
|
||||
"uboot_nav")
|
||||
# Boat stations served by the command projection (everything but its sonar room).
|
||||
UBOOT_COMMAND_ROLES = tuple(role for role in OPFOR_ROLES if role != "uboot_sonar")
|
||||
ROLES = STATIONS + OPFOR_ROLES
|
||||
# Roles with a sonar room (waterfall stream), and the gated capabilities.
|
||||
SONAR_ROLES = ("sonar", "uboot_sonar")
|
||||
DIRECT_FIRE_ROLES = ("weapons", "helicopter", "opz", "uboot_weapons")
|
||||
SONAR_AUDIO_ROLES = ("sonar", "helicopter", "uboot_sonar")
|
||||
# Pseudo-role of the solo host command surface. It is never a station lease:
|
||||
# only a solo session carries it, and STATIONS (and every projection) stays nine.
|
||||
HOST_ROLE = "host"
|
||||
|
||||
|
||||
def role_side(role):
|
||||
"""``"opfor"`` for the crewed submarine's roles, else ``"frigate"``."""
|
||||
return "opfor" if role in OPFOR_ROLES else "frigate"
|
||||
HOST_MAX_BYTES = 16 * 1024
|
||||
STATE_MAX_BYTES = 512 * 1024
|
||||
CHART_MAX_BYTES = 2 * 1024 * 1024
|
||||
_V2_STATION_CAPABILITIES = ("command", "direct_fire", "sonar_audio")
|
||||
SONAR_AUDIO_BYTES = 2048
|
||||
# Ten seconds of blocks: a client that stalls for a moment catches up in order
|
||||
# instead of losing audio; older blocks are dropped and reported as a discontinuity.
|
||||
SONAR_AUDIO_RING_BLOCKS = 40
|
||||
# A (re)connecting audio socket without a resume cursor receives at most this
|
||||
# many pending blocks (the browser's priming lead); older ones are skipped and
|
||||
# the skip shows up as a sequence gap.
|
||||
SONAR_AUDIO_RESUME_BLOCKS = 8
|
||||
# Inactivity timeout of an upgraded audio socket. A Wi-Fi stall shorter than
|
||||
# this keeps the stream; the request-phase timeout (1.5 s) does not apply.
|
||||
AUDIO_SOCKET_TIMEOUT_S = 6.0
|
||||
SONAR_AUDIO_FRAMES = 1024
|
||||
SONAR_AUDIO_RATE = 4096
|
||||
SONAR_STREAM_ROUTE = "/ws/v2/sonar"
|
||||
SONAR_AUDIO_STREAM_ROUTES = {"/ws/v2/sonar/audio": "sonar",
|
||||
"/ws/v2/helicopter/audio": "helicopter",
|
||||
"/ws/v2/uboot/audio": "uboot_sonar"}
|
||||
_AUDIO_POLL_ROUTES = {"/api/v2/sonar/audio": "sonar",
|
||||
"/api/v2/helicopter/audio": "helicopter",
|
||||
"/api/v2/uboot/audio": "uboot_sonar"}
|
||||
VOICE_STREAM_ROUTE = "/ws/v2/voice"
|
||||
_AUDIO_RESUME_QUERY = re.compile(r"after=(0|[1-9][0-9]{0,15})").fullmatch
|
||||
|
||||
|
||||
def _audio_resume_cursor(query: str):
|
||||
"""None (no cursor), an int cursor, or False for a malformed query."""
|
||||
if query == "":
|
||||
return None
|
||||
match = _AUDIO_RESUME_QUERY(query)
|
||||
if match is None:
|
||||
return False
|
||||
value = int(match.group(1))
|
||||
return value if value <= _SAFE_INTEGER_MAX else False
|
||||
SONAR_STREAM_MAGIC = b"UJS2"
|
||||
SONAR_STREAM_VERSION = 1
|
||||
SONAR_STREAM_HEADER_BYTES = 60
|
||||
SONAR_STREAM_MAX_BYTES = 4096
|
||||
SONAR_SCOPE_ROUTES = frozenset(
|
||||
f"/?scope={scope}" for scope in
|
||||
("broadband", "lofar", "demon", "tma", "environment", "active")
|
||||
)
|
||||
_WEBSOCKET_GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
_SAFE_INTEGER_MAX = 2**53 - 1
|
||||
_V2_SONAR_AUDIO_FIELDS = {"protocol", "after", "world_session", "world_epoch",
|
||||
"station_generation", "active_generation"}
|
||||
_V2_COMMAND_FIELDS = {"protocol", "id", "seq", "station", "station_generation",
|
||||
"active_generation", "world_session", "world_epoch", "resource_revision",
|
||||
"action", "params"}
|
||||
_V2_COMMAND_GLOBAL_LIMIT = 64
|
||||
_V2_COMMAND_CLIENT_LIMIT = 8
|
||||
_V2_COMMAND_HISTORY_LIMIT = 64
|
||||
_V2_COMMAND_MAX_AGE_S = 5.0
|
||||
_COOKIE_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+").fullmatch
|
||||
_COOKIE_VALUE = re.compile(r"[!#$%&'()*+\-./:<=>?@\[\]^_`{|}~0-9A-Za-z]*").fullmatch
|
||||
|
||||
|
||||
def _json_bytes(value):
|
||||
return json.dumps(value, allow_nan=False, ensure_ascii=True,
|
||||
separators=(",", ":")).encode("ascii")
|
||||
|
||||
|
||||
def _quantized(values, maximum):
|
||||
if not isinstance(values, (list, tuple)):
|
||||
return b""
|
||||
result = bytearray()
|
||||
for value in values[:maximum]:
|
||||
if type(value) not in (int, float) or not math.isfinite(value):
|
||||
return b""
|
||||
result.append(round(max(0.0, min(1.0, value)) * 255))
|
||||
return bytes(result)
|
||||
|
||||
|
||||
def _sonar_stream_payload(state, sequence, role="sonar"):
|
||||
"""Pack one detached projected sonar sample; never inspect simulation objects."""
|
||||
try:
|
||||
visual = state[role]["visualization"]
|
||||
broadband_rows = visual["broadband"]["history"]
|
||||
lofar_rows = visual["lofar"]["history"]
|
||||
demon_rows = visual["demon"]["history"]
|
||||
broadband = _quantized(broadband_rows[-1]["bins"], 180) if broadband_rows else b""
|
||||
lofar = _quantized(lofar_rows[-1]["bins"], 256) if lofar_rows else b""
|
||||
demon = _quantized(demon_rows[-1]["bins"], 80) if demon_rows else b""
|
||||
lofar_spectrum = _quantized(visual["lofar"]["spectrum"], 256)
|
||||
demon_spectrum = _quantized(visual["demon"]["spectrum"], 80)
|
||||
bearing = (float(lofar_rows[-1]["bearing"]) if lofar_rows else
|
||||
float(visual["receiver"]["listen_bearing"]))
|
||||
broadband_age = (float(broadband_rows[-1]["age_s"])
|
||||
if broadband_rows else 0.0)
|
||||
lofar_age = float(lofar_rows[-1]["age_s"]) if lofar_rows else 0.0
|
||||
demon_age = float(demon_rows[-1]["age_s"]) if demon_rows else 0.0
|
||||
epoch = int(state["epoch"])
|
||||
sim_time = float(state["clock"]["sim"])
|
||||
world_session = str(state["session"])
|
||||
except (KeyError, IndexError, TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
if (not all(math.isfinite(value) and value >= 0 for value in
|
||||
(sim_time, broadband_age, lofar_age, demon_age))
|
||||
or not math.isfinite(bearing)
|
||||
or not 0 <= epoch <= _SAFE_INTEGER_MAX
|
||||
or not 1 <= len(world_session) <= 64):
|
||||
return None
|
||||
header = struct.pack(
|
||||
"<4sBBHQQdfHHHHHHfff", SONAR_STREAM_MAGIC, SONAR_STREAM_VERSION, 0,
|
||||
SONAR_STREAM_HEADER_BYTES, sequence, epoch, sim_time, bearing,
|
||||
len(broadband), len(lofar), len(demon), len(lofar_spectrum),
|
||||
len(demon_spectrum), 0, broadband_age, lofar_age, demon_age)
|
||||
payload = header + broadband + lofar + demon + lofar_spectrum + demon_spectrum
|
||||
if len(header) != SONAR_STREAM_HEADER_BYTES or len(payload) > SONAR_STREAM_MAX_BYTES:
|
||||
return None
|
||||
return (world_session, epoch), payload
|
||||
|
||||
|
||||
def _websocket_frame(payload, opcode=2):
|
||||
length = len(payload)
|
||||
if length <= 125:
|
||||
return bytes((0x80 | opcode, length)) + payload
|
||||
if length <= 65535:
|
||||
return bytes((0x80 | opcode, 126)) + struct.pack("!H", length) + payload
|
||||
raise ValueError("websocket frame too large")
|
||||
|
||||
|
||||
SIMLOG_MAX_BYTES = 2 * 1024 * 1024
|
||||
EVENTS_MAX = 128
|
||||
SIMLOG_ENTRIES_MAX = 64
|
||||
|
||||
|
||||
def station_grants(station=None):
|
||||
"""A granted station always carries every right it can have; the host
|
||||
only ever takes rights away (``set_client_grant``) or the station."""
|
||||
return {
|
||||
"command": station in ROLES,
|
||||
"direct_fire": station in DIRECT_FIRE_ROLES,
|
||||
"sonar_audio": station in SONAR_AUDIO_ROLES,
|
||||
}
|
||||
@@ -1858,4 +1858,3 @@ def valid_save_document(data, runtime_catalog=None) -> bool:
|
||||
finite_number=finite_number, sim_t=save_sim_t):
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -14,6 +14,7 @@ from commander_web import top_level_files
|
||||
|
||||
from src.commander import CommanderServer
|
||||
from src.commander import server as transport
|
||||
from src.commander.v2 import routes
|
||||
from commander_fixtures import PLOT, WEATHER_STATION
|
||||
|
||||
|
||||
@@ -164,6 +165,7 @@ def test_multiple_pairings_reload_and_read_only_snapshots(server):
|
||||
def test_cookie_get_renews_eight_hour_idle_session(server, monkeypatch):
|
||||
clock = [float(int(time.monotonic()))]
|
||||
monkeypatch.setattr(transport, "time", SimpleNamespace(monotonic=lambda: clock[0]))
|
||||
monkeypatch.setattr(routes, "time", SimpleNamespace(monotonic=lambda: clock[0]))
|
||||
_, cookie, _, body = pair_v2(server, "Helm")
|
||||
clock[0] += 8 * 60 * 60 - 1
|
||||
resumed = request(server, "/api/v2/session", cookie=cookie)[2]
|
||||
@@ -201,6 +203,7 @@ def test_logout_requires_csrf_and_isolates_other_sessions(server):
|
||||
def test_twelve_session_limit_and_expiry_reopens_slot(server, monkeypatch):
|
||||
clock = [float(int(time.monotonic()))]
|
||||
monkeypatch.setattr(transport, "time", SimpleNamespace(monotonic=lambda: clock[0]))
|
||||
monkeypatch.setattr(routes, "time", SimpleNamespace(monotonic=lambda: clock[0]))
|
||||
cookies = [pair_v2(server, f"Client {index}")[1] for index in range(12)]
|
||||
code = server.pairing_code
|
||||
status, _, body = request(
|
||||
@@ -535,6 +538,7 @@ def test_capability_invariants_and_release(server):
|
||||
def test_presence_expiry_releases_role_but_session_reconnects(server, monkeypatch):
|
||||
clock = [float(int(time.monotonic()))]
|
||||
monkeypatch.setattr(transport, "time", SimpleNamespace(monotonic=lambda: clock[0]))
|
||||
monkeypatch.setattr(routes, "time", SimpleNamespace(monotonic=lambda: clock[0]))
|
||||
_, cookie, _, session = pair_v2(server, "Quiet")
|
||||
assert server.grant_station(session["client_id"], "radio")
|
||||
assert server.set_client_grant(session["client_id"], "command", True)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Plan 1.3, phase 2: no source module grows back into a monolith."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
LIMIT = 2500
|
||||
SRC = Path(__file__).resolve().parent.parent / "src"
|
||||
|
||||
|
||||
def test_no_source_module_exceeds_the_line_limit():
|
||||
oversized = {
|
||||
str(path.relative_to(SRC.parent)): count
|
||||
for path in SRC.rglob("*.py")
|
||||
if (count := sum(1 for _ in path.open(encoding="utf-8"))) > LIMIT
|
||||
}
|
||||
assert not oversized, oversized
|
||||
Reference in new issue
Block a user