oracle7-deepspace / site /app /server.py
psiloceyeben's picture
Upload folder using huggingface_hub
3538060 verified
Raw History Blame Contribute Delete
29.3 kB
#!/usr/bin/env python3
"""oracle7-deepspace live mission server (stdlib only). Listens on 127.0.0.1; nginx is the only public door.
Every visitor gets a private MISSION: four spacecraft, each flown TWICE from the same seed and the same injected faults:
onboard - the oracle7-deepspace flight software (research code in ./deepspace, unmodified)
baseline - the paper's simplified limit-to-safe-mode baseline: any confirmed violation -> safe mode, then wait for
Earth. Not a model of real flight fault protection, which also has fault-specific responses.
Earth's fix is modelled as a LOWER BOUND: the correct remedy arrives exactly one round-trip light time
after the anomaly (zero diagnosis and planning time), which flatters the baseline craft.
The mission clock runs faster than real time (sim minutes per wall second, chosen by the visitor).
"""
from __future__ import annotations
import copy
import json
import math
import os
import random
import secrets
import sys
import threading
import time
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from deepspace.fdir import FDIR, Facts # noqa: E402
from deepspace.report import SelfReport, PLAIN, _fact, _safe # noqa: E402
from deepspace.runtime import PHYSICAL, scenario # noqa: E402
from deepspace.sim import CORRECT, HARMFUL, PROFILES, ZONES, Spacecraft # noqa: E402
import new_craft # noqa: E402,F401 profiles added after the flight code was frozen (registered from outside it)
# the live fleet: the paper's four craft plus three added after the freeze. Parker Solar Probe is evaluated in the paper
# but not flown here: in its hot environment the frozen facts layer misreads passive heating as a stuck heater.
SITE_CRAFT = ("voyager1", "voyager2", "new_horizons", "juno", "europa_clipper", "osiris_apex", "mro")
DATA = os.path.join(os.path.dirname(HERE), "static", "data")
PORT = int(os.environ.get("PORT", "8341"))
MAX_SESSIONS = int(os.environ.get("MAX_SESSIONS", "80"))
IDLE_S = 20 * 60
SPEEDS = (1, 4, 15, 60) # sim minutes per wall second
TURNAROUNDS = (0, 720, 4320) # Earth diagnosis + planning time options (min): lower bound, 12 h, 3 days
MAX_TICKS_PER_POLL = 90
AU_LIGHT_MIN = 8.316746 # light minutes per AU
FAULT_LABEL = {"heater_stuck_on": "Heater relay welded ON", "heater_stuck_off": "Heater element open (stuck OFF)",
"sensor_bias": "Temperature sensor drift (trap: the zone is fine)",
"seu_spike": "Radiation upset, single-tick spike (trap)", "wheel_friction": "Reaction wheel bearing friction",
"star_tracker_dropout": "Star tracker dropout", "solar_degradation": "Solar array string loss",
"battery_short": "Battery cell short", "thruster_degradation": "Attitude thrusters clogged (branch A)",
"rtg_decline": "RTG thermocouple string loss"}
FAULT_WHY = {"heater_stuck_on": "The zone keeps heating although its heater is commanded off.",
"heater_stuck_off": "The zone keeps cooling although its heater is commanded on.",
"sensor_bias": "One of two redundant sensors drifts ~20-28 C. The zone itself is fine: acting on the "
"reading (heater swap, safe mode) would be the WRONG response.",
"seu_spike": "A cosmic ray flips one reading for one tick. The right response is to do nothing.",
"wheel_friction": "A reaction wheel draws excess current; pointing degrades.",
"star_tracker_dropout": "Attitude knowledge is lost; the sun sensor is the backup.",
"solar_degradation": "Array output drops below what the pointing predicts; the battery begins to drain.",
"battery_short": "An unexplained multi-amp draw appears on the bus: a survival-class hazard.",
"thruster_degradation": "Branch-A thrusters lose authority; they fire far longer to hold attitude.",
"rtg_decline": "A thermocouple string opens; the power budget no longer covers every load."}
def light_minutes(ephem):
e = ephem["bodies"]["earth"]["now"]
return {k: round(math.dist(v["now"], e) * AU_LIGHT_MIN, 1) for k, v in ephem["craft"].items()}
EPHEM = json.load(open(os.path.join(DATA, "ephem.json")))
OWLT = light_minutes(EPHEM) # one-way light time in minutes, today's geometry
def load_rules():
try:
d = json.load(open(os.path.join(DATA, "rules.json")))
except Exception: # noqa: BLE001
return {}, None
rb = {}
for r in d["admitted"]:
rr = dict(r)
rr["bind"] = {k: tuple(v) for k, v in r["bind"].items()}
rb[tuple(r["signature"])] = rr
return rb, d
RULES, RULES_DOC = load_rules()
# the monitors each fault trips; after Earth fixes a fault it re-baselines these (as operators update limits)
FAULT_FACTS = {"heater_stuck_on": {"heater_on_uncommanded"}, "heater_stuck_off": {"heater_off_uncommanded"},
"sensor_bias": {"sensor_disagree"}, "wheel_friction": {"wheel_overcurrent"},
"star_tracker_dropout": {"attitude_knowledge_lost"}, "solar_degradation": {"solar_low", "load_excess"},
"battery_short": {"load_excess", "solar_low"}, "thruster_degradation": {"thruster_overuse"},
"rtg_decline": {"rtg_low"}, "seu_spike": set()}
class Threshold:
"""the paper's simplified limit-to-safe-mode baseline: any confirmed violation -> safe mode"""
def __init__(self, ignore=(), quiet_until=0):
self.facts, self.done = Facts(), False
self.ignore, self.quiet_until = set(ignore), quiet_until
def decide(self, tm):
facts = self.facts.update(tm)
live = [f for f in facts if f[0] != "transient_spike" and f[0] not in self.ignore
and not (f[0] == "zone_out_of_band" and tm["t"] < self.quiet_until)]
if not self.done and live:
self.done = True
return {"action": "safe_mode", "arg": {}, "t": tm["t"], "facts": [list(f) for f in facts]}
return None
class Rulebook:
"""what SelfReport._learned reads: the gate log"""
def __init__(self, log):
self.log = log
class Craft:
def __init__(self, name, seed, rules_on=False, vetoed=(), turnaround=0):
self.name, self.seed = name, seed
self.label = PROFILES[name]["label"]
self.owlt = OWLT[name]
self.turnaround = turnaround # Earth's diagnosis + planning time added to the round trip (minutes)
self.rules_on = rules_on
self.vetoed = set(vetoed)
rb = {k: v for k, v in RULES.items() if v["id"] not in self.vetoed} if rules_on else {}
self.on = Spacecraft(seed=seed, profile=name)
self.cl = Spacecraft(seed=seed, profile=name)
self.fdir = FDIR(rulebook=copy.deepcopy(rb))
self.rep = SelfReport(self.fdir, rulebook=Rulebook(RULES_DOC["log"]) if (RULES_DOC and rules_on) else None)
self.th = Threshold()
self.series = deque(maxlen=600)
self.events = []
self.faults = [] # {id, fault, t, params, verdict_on, verdict_cl, fixed_on, fixed_cl}
self.pending = []
self.ground = None # classic: tick at which Earth's correct fix arrives
self.sci = {"on": 0, "cl": 0}
self.safe_ticks = {"on": 0, "cl": 0}
self.tick_us = deque(maxlen=300)
self.worst_decision_ms = 0.0
self.last_decision_ms = None
self.damage_kinds = {"on": set(), "cl": set()}
self.n_inject = 0
self.ev_n = 0
# ---- events ----
def ev(self, kind, side, text, **kw):
self.ev_n += 1
e = {"i": self.ev_n, "t": self.on.t, "kind": kind, "side": side, "text": text}
e.update(kw)
self.events.append(e)
del self.events[:-400]
def inject(self, fault):
if fault not in PROFILES[self.name]["faults"] or fault == "nominal":
return "unknown fault for this craft"
if len([f for f in self.faults if not f["closed"]]) >= 2:
return "two faults already open on this craft; reset it or wait for them to resolve"
self.n_inject += 1
p = scenario(fault, self.seed * 1000 + self.n_inject, self.name)
used = {f["fault"] for f in self.faults} | {q["fault"] for q in self.pending}
if fault in ("heater_stuck_on", "heater_stuck_off", "sensor_bias"):
# a zone whose redundancy is already spent (heater on backup, a sensor marked invalid) cannot take this fault
busy = {f["params"]["zone"] for f in self.faults if f["fault"] in ("heater_stuck_on", "heater_stuck_off", "sensor_bias")}
busy |= {q["zone"] for q in self.pending}
free = [z for z in ZONES if z not in busy and (fault == "sensor_bias" or z != "avionics")]
if not free:
return "every zone's redundancy is already in use on this craft; reset the craft to fly it again"
if p["zone"] not in free:
p["zone"] = free[0]
elif fault != "seu_spike" and fault in used:
return "this craft has already flown that fault (its backup is in use); reset the craft to fly it again"
self.pending.append(p)
return None
def _apply_inject(self, p):
kw = dict(zone=p["zone"], wheel=p["wheel"], sensor=p["sensor"], magnitude=p["magnitude"])
self.on.inject(p["fault"], **kw)
self.cl.inject(p["fault"], **kw)
f = {"id": len(self.faults), "fault": p["fault"], "label": FAULT_LABEL[p["fault"]], "why": FAULT_WHY[p["fault"]],
"t": self.on.t, "params": p, "verdict_on": None, "verdict_cl": None, "t_on": None, "t_cl": None,
"closed": False, "trap": p["fault"] in ("sensor_bias", "seu_spike")}
where = {"heater_stuck_on": p["zone"], "heater_stuck_off": p["zone"], "sensor_bias": "%s sensor %s" % (p["zone"], p["sensor"]),
"wheel_friction": "wheel %d" % p["wheel"], "seu_spike": "%s sensor %s" % (p["zone"], p["sensor"])}.get(p["fault"])
f["where"] = where
self.faults.append(f)
self.ev("inject", "both", "%s%s injected" % (f["label"], (" (" + where + ")") if where else ""), fault=f["id"])
# ---- verdicts use the simulator's ground truth, which the flight software never sees ----
def _judge(self, side, action, arg):
key = "verdict_" + side
open_ = [f for f in self.faults if not f["closed"] and f[key] is None and f["fault"] != "seu_spike"]
for f in open_:
if action in CORRECT[f["fault"]] and _target_ok(f["params"], action, arg):
f[key], f["t_" + side] = "correct", self.on.t
return f
for f in self.faults:
if not f["closed"] and f[key] in (None, "correct") and action in HARMFUL.get(f["fault"], set()):
f[key], f["t_" + side] = "harmful", self.on.t
return f
if open_:
# neither the designed remedy nor a harmful act: for the classic craft this is safe mode (waits for Earth)
f = open_[0]
f[key], f["t_" + side] = ("safe_mode" if action == "safe_mode" else "other"), self.on.t
return f
return None
def step(self):
while self.pending and self.on.t >= 10: # the onboard monitors need a little history first
self._apply_inject(self.pending.pop(0))
# ---- onboard: oracle7-deepspace ----
t0 = time.perf_counter()
self.on.step()
tm = self.on.telemetry()
r = self.fdir.decide(tm)
dt = (time.perf_counter() - t0) * 1e6
self.tick_us.append(dt)
if r:
self.last_decision_ms = r["ms"]
self.worst_decision_ms = max(self.worst_decision_ms, r["ms"])
if r["action"] in PHYSICAL:
self.on.command(r["action"], **r["arg"])
f = self._judge("on", r["action"], r["arg"])
self.ev("decision", "on", _sentence(r), receipt=_slim(r), fault=f["id"] if f else None,
verdict=f and f["verdict_on"])
elif r["action"] == "collect_evidence":
self.ev("evidence", "on", _sentence(r), receipt=_slim(r))
# ---- classic: limit -> safe mode, then wait for Earth ----
self.cl.step()
tmc = self.cl.telemetry()
rc = self.th.decide(tmc)
if rc:
self.cl.command("safe_mode")
f = self._judge("cl", "safe_mode", {})
self.ground = self.cl.t + int(round(2 * self.owlt + self.turnaround))
self.ev("safe", "cl", "Limit violation -> SAFE MODE. Science stops; "
"the craft waits for Earth (round trip %s%s)." % (_dur(2 * self.owlt), (" + %s on the ground" % _dur(self.turnaround))
if self.turnaround else ""), fault=f["id"] if f else None,
verdict=f and f["verdict_cl"])
self.ev("downlink", "cl", "Anomaly telemetry is on its way to Earth: arrives in %s." % _dur(self.owlt))
if self.ground is not None and self.cl.t >= self.ground:
self._ground_fix()
# ---- bookkeeping ----
for side, sc in (("on", self.on), ("cl", self.cl)):
if not sc.science_on:
self.sci[side] += 1
if sc.safe:
self.safe_ticks[side] += 1
if sc.damage:
# the simulator logs damage every tick it persists; keep the first of each kind and drop the rest
kinds = {d[1] for d in sc.damage} - self.damage_kinds[side]
sc.damage.clear()
if kinds:
self.damage_kinds[side] |= kinds
self.ev("damage", side, "DAMAGE: %s" % ", ".join(sorted(k.replace("_", " ") for k in kinds)))
self._close_faults()
self.series.append(_sample(self.on, self.cl))
def _ground_fix(self):
"""Earth's command arrives: the correct remedy for every open fault, then exit safe mode (lower bound)"""
fixes = []
for f in self.faults:
if f["closed"] or f["fault"] in ("seu_spike",):
continue
p = f["params"]
for a in CORRECT[f["fault"]]:
if a in ("safe_mode", "no_action"):
continue
arg = {"switch_heater_backup": {"zone": p["zone"]}, "mark_sensor_invalid": {"zone": p["zone"], "sensor": p["sensor"]},
"switch_to_spare_wheel": {"wheel": p["wheel"]}}.get(a, {})
self.cl.command(a, **arg)
fixes.append(PLAIN[a] % _safe(arg))
f["ground_fixed"], f["t_ground"] = True, self.cl.t
keep_safe = any(not f["closed"] and f["fault"] == "battery_short" for f in self.faults)
if not keep_safe:
self.cl.safe = False
self.cl.science_on = not any(not f["closed"] and f["fault"] in ("solar_degradation", "rtg_decline") for f in self.faults)
self.ground = None
# Earth re-baselines the monitors of the faults it fixed and lets temperatures settle for 2 h
ignore = set(self.th.ignore)
for f in self.faults:
if f.get("ground_fixed"):
ignore |= FAULT_FACTS[f["fault"]]
self.th = Threshold(ignore=ignore, quiet_until=self.cl.t + 120)
self.ev("ground", "cl", "Earth's recovery command arrives (%s after the anomaly%s): %s."
% (_dur(2 * self.owlt + self.turnaround), ", assuming zero diagnosis time" if not self.turnaround else "",
"; ".join(fixes) or "exit safe mode"))
def _close_faults(self):
for f in self.faults:
if f["closed"]:
continue
age = self.on.t - f["t"]
if f["fault"] == "seu_spike" and age > 20:
f["verdict_on"] = f["verdict_on"] or "correct"
f["verdict_cl"] = f["verdict_cl"] or "correct"
done_on = f["verdict_on"] is not None
done_cl = f["verdict_cl"] in ("correct", "harmful") and f["fault"] in ("battery_short", "seu_spike") or bool(f.get("ground_fixed"))
if done_on and done_cl and age > 5:
f["closed"] = True
def ask(self, q):
a, cites = self.rep.answer(q)
return {"q": q, "a": a, "cites": cites, "t": self.on.t}
def state(self, since_tick, since_ev):
ser = [s for s in self.series if s[0] > since_tick]
us = sorted(self.tick_us)
return {"name": self.name, "label": self.label, "t": self.on.t, "owlt_min": self.owlt,
"series": ser, "events": [e for e in self.events if e["i"] >= since_ev],
"faults": [_fault_view(f) for f in self.faults[-12:]],
"on": _status(self.on, self.fdir.facts), "cl": _status(self.cl, self.th.facts),
"ground_eta": (self.ground - self.cl.t) if self.ground is not None else None,
"science_lost": self.sci, "safe_ticks": self.safe_ticks,
"damage": {k: sorted(v) for k, v in self.damage_kinds.items()},
"compute": {"tick_us_median": round(us[len(us) // 2], 1) if us else None,
"tick_us_p99": round(us[int(len(us) * 0.99)], 1) if us else None,
"worst_decision_ms": round(self.worst_decision_ms, 2), "last_decision_ms": self.last_decision_ms,
"twin_runs": self.fdir.twin_runs, "receipts": len(self.fdir.receipts)},
"rules_on": self.rules_on, "vetoed": sorted(self.vetoed), "turnaround_min": self.turnaround}
def _target_ok(p, action, arg):
if "zone" in arg and p["fault"] in ("heater_stuck_on", "heater_stuck_off", "sensor_bias") and arg["zone"] != p["zone"]:
return False
if p["fault"] == "sensor_bias" and arg.get("sensor") not in (None, p["sensor"]):
return False
if p["fault"] == "wheel_friction" and arg.get("wheel") not in (None, p["wheel"]):
return False
return True
def _fault_view(f):
return {k: f.get(k) for k in ("id", "fault", "label", "why", "where", "t", "verdict_on", "verdict_cl", "t_on", "t_cl",
"closed", "trap", "ground_fixed", "t_ground")}
def _status(sc, facts):
temps = {z: round(facts.zone_temp(facts.hist[-1], z), 1) if facts.hist else round(sc.temp[z], 1) for z in ZONES}
return {"mode": "SAFE" if sc.safe else ("SCIENCE" if sc.science_on else "LOADS SHED"), "soc": round(sc.soc, 3),
"src": round(sc.i_source, 2), "load": round(sc.i_load, 2), "point": round(sc.pointing_err, 2), "temps": temps,
"power": sc.power, "actuator": sc.actuator, "branch": sc.thruster_branch, "wheels": list(sc.wheels_active),
"att": sc.attitude_sensor, "invalid": sorted("%s.%s" % zs for zs in sc.sensor_invalid),
"heaters": {z: sc.heater_circuit[z] for z in ZONES}, "science": sc.science_on, "safe": sc.safe}
def _sample(on, cl):
return [on.t, round(on.soc, 4), round(on.i_source, 2), round(on.i_load, 2), round(on.pointing_err, 2),
round(on.temp["battery"], 1), round(on.temp["avionics"], 1), round(on.temp["tank"], 1),
round(cl.soc, 4), round(cl.i_source, 2), round(cl.i_load, 2), round(cl.pointing_err, 2),
round(cl.temp["battery"], 1), round(cl.temp["avionics"], 1), round(cl.temp["tank"], 1),
1 if on.science_on else 0, 1 if cl.science_on else 0, 1 if cl.safe else 0]
def _slim(r):
return {"id": r["id"], "t": r["t"], "facts": [_fact(tuple(f)) for f in r["facts"] if f[0] != "zone_out_of_band"],
"hypotheses": [h[0].replace("_", " ") for h in r["hypotheses"]], "action": r["action"], "arg": r["arg"],
"path": r["path"], "rule": r["rule"], "ms": r["ms"], "note": r["note"],
"alternatives": [{"action": a["action"], "arg": a["arg"], "score": a["worst_case"]} for a in r["alternatives"]]}
def _sentence(r):
act = PLAIN.get(r["action"], r["action"]) % _safe(r["arg"])
facts = "; ".join(_fact(tuple(f)) for f in r["facts"] if f[0] not in ("zone_out_of_band",)) or "facts recorded"
how = "admitted rule %s" % r["rule"] if r["path"] == "rule" else (
"simulated %d options on the onboard twin" % len(r["alternatives"]) if r["path"] == "lookahead" else "evidence rule")
return "%s: %s (%s, %.1f ms)" % (act[0].upper() + act[1:], facts, how, r["ms"])
def _dur(minutes):
m = int(round(minutes))
if m < 60:
return "%d min" % m
h, m = divmod(m, 60)
if h < 48:
return "%d h %02d min" % (h, m)
d, h = divmod(h, 24)
return "%d d %d h" % (d, h)
class Mission:
def __init__(self):
self.lock = threading.Lock()
self.seed = random.randrange(1, 10 ** 6)
self.rules_on = False
self.vetoed = set()
self.turnaround = 0
self.craft = {n: Craft(n, self.seed + i * 7919) for i, n in enumerate(SITE_CRAFT)}
self.speed = 4
self.last = time.time()
self.seen = time.time()
self.carry = 0.0
def advance(self):
now = time.time()
dt = min(now - self.last, 3.0)
self.last = now
self.seen = now
self.carry += dt * self.speed
n = min(int(self.carry), MAX_TICKS_PER_POLL)
self.carry -= int(self.carry)
for _ in range(n):
for c in self.craft.values():
c.step()
return n
def reset(self, name=None, rules_on=None):
if rules_on is not None:
self.rules_on = rules_on
for i, n in enumerate(SITE_CRAFT):
if name in (None, n):
self.craft[n] = Craft(n, self.seed + i * 7919 + random.randrange(1000), self.rules_on, self.vetoed, self.turnaround)
SESSIONS: dict[str, Mission] = {}
SLOCK = threading.Lock()
RATE: dict[str, list] = {}
def get_mission(sid, create=False):
with SLOCK:
now = time.time()
for k in [k for k, m in SESSIONS.items() if now - m.seen > IDLE_S]:
del SESSIONS[k]
m = SESSIONS.get(sid) if sid else None
if m or not create:
return sid, m
if len(SESSIONS) >= MAX_SESSIONS:
oldest = min(SESSIONS, key=lambda k: SESSIONS[k].seen)
del SESSIONS[oldest]
sid = secrets.token_urlsafe(12)
SESSIONS[sid] = Mission()
return sid, SESSIONS[sid]
def limited(key, n, per):
now = time.time()
q = [t for t in RATE.get(key, []) if now - t < per]
if len(q) >= n:
RATE[key] = q
return True
q.append(now)
RATE[key] = q
if len(RATE) > 5000:
RATE.clear()
return False
def code_sha256():
"""SHA-256 of the flight code actually running here (same recipe as eval/eval_final.py)"""
import hashlib
h = hashlib.sha256()
pkg = os.path.join(HERE, "deepspace")
for name in sorted(os.listdir(pkg)):
if name.endswith(".py"):
h.update(name.encode() + b"\0" + open(os.path.join(pkg, name), "rb").read() + b"\0")
return h.hexdigest()
def meta():
return {"craft": {n: {"label": p["label"], "power": p["power"], "actuator": p["actuator"], "owlt_min": OWLT[n],
"faults": [{"id": f, "label": FAULT_LABEL[f], "why": FAULT_WHY[f]} for f in p["faults"] if f != "nominal"]}
for n, p in ((n, PROFILES[n]) for n in SITE_CRAFT)},
"speeds": SPEEDS, "turnarounds": TURNAROUNDS, "rules": RULES_DOC, "code_sha256": code_sha256(), "epoch": EPHEM["epoch"]}
META = json.dumps(meta()).encode()
class H(BaseHTTPRequestHandler):
server_version = "o7ds"
sys_version = ""
def log_message(self, *a):
pass
def _json(self, code, obj):
b = obj if isinstance(obj, bytes) else json.dumps(obj, separators=(",", ":")).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def _ip(self):
return self.headers.get("X-Real-IP") or self.client_address[0]
def do_GET(self):
path, _, qs = self.path.partition("?")
q = dict(p.split("=", 1) for p in qs.split("&") if "=" in p)
if path == "/api/health":
return self._json(200, {"ok": True, "sessions": len(SESSIONS)})
if path == "/api/meta":
return self._json(200, META)
if path == "/api/state":
sid, m = get_mission(q.get("sid"))
if not m:
return self._json(404, {"error": "no session"})
try:
since = {k: int(v) for k, v in (x.split(":") for x in q.get("since", "").split(",") if ":" in x)}
ev = {k: int(v) for k, v in (x.split(":") for x in q.get("ev", "").split(",") if ":" in x)}
except ValueError:
return self._json(400, {"error": "bad query"})
with m.lock:
n = m.advance()
out = {"ticks": n, "speed": m.speed, "rules_on": m.rules_on,
"craft": {k: c.state(since.get(k, 0), ev.get(k, 0)) for k, c in m.craft.items()}}
return self._json(200, out)
return self._json(404, {"error": "not found"})
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
if n > 4096:
return self._json(413, {"error": "too large"})
try:
body = json.loads(self.rfile.read(n) or b"{}")
assert isinstance(body, dict)
except Exception: # noqa: BLE001
return self._json(400, {"error": "bad json"})
path = self.path.partition("?")[0]
if path == "/api/session":
if limited("s:" + self._ip(), 12, 60):
return self._json(429, {"error": "slow down"})
sid, m = get_mission(body.get("sid"), create=True)
return self._json(200, {"sid": sid})
sid, m = get_mission(body.get("sid"))
if not m:
return self._json(404, {"error": "no session"})
name = body.get("craft")
if path == "/api/inject":
if limited("i:" + sid, 6, 20):
return self._json(429, {"error": "one fault every few seconds, please"})
if name not in m.craft:
return self._json(400, {"error": "unknown craft"})
with m.lock:
err = m.craft[name].inject(str(body.get("fault", ""))[:40])
return self._json(400 if err else 200, {"error": err} if err else {"ok": True})
if path == "/api/ask":
if limited("a:" + sid, 20, 60):
return self._json(429, {"error": "slow down"})
if name not in m.craft:
return self._json(400, {"error": "unknown craft"})
qtext = str(body.get("q", ""))[:200]
with m.lock:
return self._json(200, m.craft[name].ask(qtext))
if path == "/api/speed":
try:
s = int(body.get("speed"))
except (TypeError, ValueError):
return self._json(400, {"error": "bad speed"})
if s not in SPEEDS:
return self._json(400, {"error": "bad speed"})
with m.lock:
m.advance()
m.speed = s
return self._json(200, {"ok": True})
if path == "/api/reset":
if limited("r:" + sid, 10, 60):
return self._json(429, {"error": "slow down"})
with m.lock:
rules = body.get("rules")
if body.get("turnaround") in TURNAROUNDS:
m.turnaround = body["turnaround"]
for c in m.craft.values():
c.turnaround = m.turnaround
return self._json(200, {"ok": True})
if isinstance(body.get("veto"), list):
m.vetoed = {str(v)[:120] for v in body["veto"]}
m.reset(name if name in m.craft else None, bool(rules) if rules is not None else None)
return self._json(200, {"ok": True})
return self._json(404, {"error": "not found"})
def main():
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H)
srv.daemon_threads = True
print("oracle7-deepspace mission server on 127.0.0.1:%d, OWLT %s" % (PORT, OWLT), flush=True)
srv.serve_forever()
if __name__ == "__main__":
main()