feat(mlg): /db routes: import .MLG, a unit's timeline, monitoring at T
POST /db/import/mlg_file (per-file status; good files stored even when
another in the request is refused; each file's modified time as a JSON
form field), GET /db/units/{serial}/timeline (optionally windowed),
GET /db/units/{serial}/monitoring_at, GET /db/mlg_records, and
GET /db/mlg_files/{id} (the original, byte for byte, for printing).
Tested by calling the route functions directly: httpx is not in this
venv, so TestClient tests would skip silently.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
This commit is contained in:
1 parent
faa371a73b
commit
c0cdf58527
4 files changed
+265
-1
No files matched your search
@@ -201,6 +201,40 @@ def build_timeline(records: list[dict], files: list[dict]) -> dict:
|
||||
"call_ins": _call_ins(records, files)}
|
||||
|
||||
|
||||
def window(timeline: dict, from_dt: Optional[datetime.datetime],
|
||||
to_dt: Optional[datetime.datetime]) -> dict:
|
||||
"""The parts of a timeline that overlap [from_dt, to_dt] (the unit's clock).
|
||||
|
||||
Sessions, gaps and clock steps are on the unit's clock and filter exactly.
|
||||
A call-in with a unit time filters by it. A nothing_new call-in has only
|
||||
the PC's file time (UTC); it is kept when within a day of the window, since
|
||||
the unit's local clock and UTC differ by hours and cannot be compared
|
||||
exactly."""
|
||||
lo = from_dt or datetime.datetime.min
|
||||
hi = to_dt or datetime.datetime.max
|
||||
|
||||
def overlaps(start: Optional[str], end: Optional[str]) -> bool:
|
||||
s = _dt(start) or datetime.datetime.min
|
||||
e = _dt(end) or datetime.datetime.max
|
||||
return s <= hi and e >= lo
|
||||
|
||||
def call_in_kept(c: dict) -> bool:
|
||||
if c["unit_time"]:
|
||||
return lo <= _dt(c["unit_time"]) <= hi
|
||||
t = _dt(c["file_time"]).replace(tzinfo=None)
|
||||
day = datetime.timedelta(days=1)
|
||||
return (lo == datetime.datetime.min or t >= lo - day) and (hi == datetime.datetime.max or t <= hi + day)
|
||||
|
||||
return {
|
||||
"sessions": [s for s in timeline["sessions"]
|
||||
if overlaps(s["start"], None if s["running_at_last_report"]
|
||||
else s["stop"] or s["end_before"])],
|
||||
"gaps": [g for g in timeline["gaps"] if overlaps(g["start"], g["stop"])],
|
||||
"clock_steps": [c for c in timeline["clock_steps"] if overlaps(c["next_start"], c["previous_stop"])],
|
||||
"call_ins": [c for c in timeline["call_ins"] if call_in_kept(c)],
|
||||
}
|
||||
|
||||
|
||||
def monitoring_at(timeline: dict, at: datetime.datetime) -> dict:
|
||||
"""Was the unit monitoring at `at` (its own clock)?
|
||||
|
||||
|
||||
+110
-1
@@ -43,6 +43,7 @@ or:
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
@@ -54,7 +55,7 @@ from typing import Any, Dict, Mapping, Optional
|
||||
|
||||
# FastAPI / Pydantic
|
||||
try:
|
||||
from fastapi import Body, FastAPI, File, HTTPException, Query, Response, UploadFile
|
||||
from fastapi import Body, FastAPI, File, Form, HTTPException, Query, Response, UploadFile
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -84,6 +85,8 @@ from sfm.live_cache import LiveCache as _LiveCache
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from sfm import db_snapshot
|
||||
from sfm.event_ingest import backfill_series3_event, persist_download
|
||||
from sfm.mlg_ingest import ingest_mlg
|
||||
from sfm.mlg_timeline import build_timeline, monitoring_at as mlg_monitoring_at, window as mlg_window
|
||||
import dataclasses
|
||||
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
|
||||
from sfm.device_access.errors import BadRequest, ChangeUnconfirmed
|
||||
@@ -3067,6 +3070,112 @@ async def db_import_idf_file(
|
||||
return {"count": len(results), "results": results}
|
||||
|
||||
|
||||
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────────
|
||||
# Spec: docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §5.
|
||||
# Record and timeline times are the unit's own local clock; file times are UTC.
|
||||
|
||||
|
||||
def _parse_unit_time(value: Optional[str], name: str) -> Optional[datetime.datetime]:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return datetime.datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
raise HTTPException(400, f"{name} is not an ISO-8601 time: {value!r}")
|
||||
|
||||
|
||||
def _mlg_timeline(serial: str) -> dict:
|
||||
db = _get_db()
|
||||
return build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
|
||||
|
||||
|
||||
@app.post("/db/import/mlg_file")
|
||||
async def db_import_mlg_file(
|
||||
files: list[UploadFile] = File(...),
|
||||
serial: Optional[str] = Query(None, description="Serial hint, used only for a file with no serial inside (an empty one)"),
|
||||
call_in: bool = Query(True, description="False for a cable / direct download: its records are kept, but it is not a call-in"),
|
||||
mtimes: Optional[str] = Form(None, description='Each file\'s modified time: JSON {"<file name>": <unix seconds, UTC>}'),
|
||||
) -> dict:
|
||||
"""
|
||||
Multipart upload of one or more Blastware .MLG monitor logs.
|
||||
|
||||
Each file gets its own status ("ok" / "duplicate" / "error"); good files
|
||||
are stored even when another in the same request is not. A file that is
|
||||
not whole, or any of whose records fails its checksum, stores nothing.
|
||||
The original is kept byte for byte in the waveform store.
|
||||
"""
|
||||
try:
|
||||
file_times = json.loads(mtimes) if mtimes else {}
|
||||
if not isinstance(file_times, dict):
|
||||
raise ValueError("not an object")
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, f"mtimes must be a JSON object of file name -> unix seconds: {exc}")
|
||||
db, store = _get_db(), _get_store()
|
||||
results: list[dict] = []
|
||||
for upload in files:
|
||||
name = upload.filename or "unnamed.MLG"
|
||||
try:
|
||||
data = await upload.read()
|
||||
except Exception as exc:
|
||||
results.append({"filename": name, "status": "error", "detail": f"read failed: {exc}"})
|
||||
continue
|
||||
stamp = file_times.get(name)
|
||||
file_mtime = (datetime.datetime.fromtimestamp(float(stamp), datetime.timezone.utc)
|
||||
if stamp is not None else None)
|
||||
results.append(ingest_mlg(db, store, name, data, serial_hint=serial,
|
||||
file_mtime=file_mtime, call_in=call_in))
|
||||
return {"count": len(results), "results": results}
|
||||
|
||||
|
||||
@app.get("/db/units/{serial}/timeline")
|
||||
def db_unit_timeline(
|
||||
serial: str,
|
||||
from_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
|
||||
to_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
|
||||
) -> dict:
|
||||
"""A unit's monitoring timeline from its .MLGs: sessions (how each ended,
|
||||
its events, its trigger level), gaps and what each means, clock steps, and
|
||||
call-ins (delivered / no_file / nothing_new)."""
|
||||
lo, hi = _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt")
|
||||
timeline = _mlg_timeline(serial)
|
||||
if lo or hi:
|
||||
timeline = mlg_window(timeline, lo, hi)
|
||||
return {"serial": serial, **timeline}
|
||||
|
||||
|
||||
@app.get("/db/units/{serial}/monitoring_at")
|
||||
def db_unit_monitoring_at(
|
||||
serial: str,
|
||||
at: str = Query(..., description="ISO-8601, the unit's clock"),
|
||||
) -> dict:
|
||||
"""Was the unit monitoring at `at`? monitoring / not_monitoring / unknown,
|
||||
with the session or gap that says so and the trigger level as logged."""
|
||||
when = _parse_unit_time(at, "at")
|
||||
return {"serial": serial, "at": at, **mlg_monitoring_at(_mlg_timeline(serial), when)}
|
||||
|
||||
|
||||
@app.get("/db/mlg_records")
|
||||
def db_mlg_records(
|
||||
serial: str = Query(..., description="Unit serial"),
|
||||
from_dt: Optional[str] = Query(None, description="ISO-8601 start (record start, inclusive)"),
|
||||
to_dt: Optional[str] = Query(None, description="ISO-8601 end (record start, inclusive)"),
|
||||
) -> dict:
|
||||
"""A unit's raw .MLG records, oldest first."""
|
||||
rows = _get_db().query_mlg_records(
|
||||
serial, _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt"))
|
||||
return {"count": len(rows), "records": rows}
|
||||
|
||||
|
||||
@app.get("/db/mlg_files/{file_id}")
|
||||
def db_mlg_file(file_id: str):
|
||||
"""The original .MLG, byte for byte, for printing or opening in Blastware."""
|
||||
row = _get_db().get_mlg_file(file_id)
|
||||
path = _get_store().root / row["stored_path"] if row and row["stored_path"] else None
|
||||
if path is None or not path.is_file():
|
||||
raise HTTPException(404, f"no stored .MLG with id {file_id}")
|
||||
return FileResponse(path, filename=row["file_name"], media_type="application/octet-stream")
|
||||
|
||||
|
||||
@app.get("/db/units/{serial}/waveforms.zip")
|
||||
def db_unit_waveforms_zip(
|
||||
serial: str,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
Tests for the .MLG routes in sfm/server.py (spec §5).
|
||||
|
||||
httpx is not installed in this venv, so starlette's TestClient tests skip; these
|
||||
call the route functions directly, passing every parameter (a FastAPI Query()
|
||||
default is not a value).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from fastapi import HTTPException, UploadFile
|
||||
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
|
||||
|
||||
|
||||
def _env(tmp_path, monkeypatch):
|
||||
import sfm.server as srv
|
||||
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "waveforms")
|
||||
monkeypatch.setattr(srv, "_db", db, raising=False)
|
||||
monkeypatch.setattr(srv, "_store", store, raising=False)
|
||||
return srv, db, store
|
||||
|
||||
|
||||
def _import(srv, uploads, *, serial=None, call_in=True, mtimes=None):
|
||||
files = [UploadFile(file=io.BytesIO(data), filename=name) for name, data in uploads]
|
||||
return asyncio.run(srv.db_import_mlg_file(files=files, serial=serial, call_in=call_in, mtimes=mtimes))
|
||||
|
||||
|
||||
def _fixture(name):
|
||||
return name, (FIX / name).read_bytes()
|
||||
|
||||
|
||||
def test_import_route_stores_good_file_and_refuses_bad_one(tmp_path, monkeypatch):
|
||||
srv, db, store = _env(tmp_path, monkeypatch)
|
||||
name, good = _fixture("BE128443065.MLG")
|
||||
bad = bytearray(good)
|
||||
bad[18 + 292 + 40] ^= 0xFF
|
||||
out = _import(srv, [(name, good), ("BE128443099.MLG", bytes(bad))])
|
||||
assert out["count"] == 2
|
||||
assert [r["status"] for r in out["results"]] == ["ok", "error"]
|
||||
assert "record 1" in out["results"][1]["detail"]
|
||||
assert [f["file_name"] for f in db.query_mlg_files("BE12844")] == ["BE128443065.MLG"]
|
||||
assert sorted(p.name for p in store.root.rglob("*.MLG")) == ["BE128443065.MLG"]
|
||||
|
||||
|
||||
def test_import_route_reads_mtimes(tmp_path, monkeypatch):
|
||||
srv, db, _ = _env(tmp_path, monkeypatch)
|
||||
out = _import(srv, [_fixture("BE128443065.MLG")], mtimes='{"BE128443065.MLG": 1788734760}')
|
||||
f = db.get_mlg_file(out["results"][0]["file_id"])
|
||||
assert f["file_mtime"] == "2026-09-06T22:46:00+00:00"
|
||||
|
||||
|
||||
def test_import_route_rejects_bad_mtimes(tmp_path, monkeypatch):
|
||||
srv, _, _ = _env(tmp_path, monkeypatch)
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
_import(srv, [_fixture("BE128443065.MLG")], mtimes="not json")
|
||||
assert exc.value.status_code == 400
|
||||
|
||||
|
||||
def test_timeline_and_monitoring_at_routes(tmp_path, monkeypatch):
|
||||
srv, _, _ = _env(tmp_path, monkeypatch)
|
||||
_import(srv, [_fixture("BE8081321.MLG")])
|
||||
tl = srv.db_unit_timeline(serial="BE8081", from_dt=None, to_dt=None)
|
||||
assert tl["serial"] == "BE8081" and len(tl["sessions"]) == 4
|
||||
windowed = srv.db_unit_timeline(serial="BE8081", from_dt="2019-04-13T00:00:00", to_dt=None)
|
||||
assert [s["start"] for s in windowed["sessions"]] == [
|
||||
"2019-04-12T18:38:14", "2019-04-13T07:05:15", "2019-04-15T12:47:05"]
|
||||
assert [g["meaning"] for g in windowed["gaps"]] == ["call-in", "lost power"]
|
||||
m = srv.db_unit_monitoring_at(serial="BE8081", at="2019-04-14T12:00:00")
|
||||
assert m["serial"] == "BE8081" and m["status"] == "not_monitoring"
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
srv.db_unit_monitoring_at(serial="BE8081", at="yesterday")
|
||||
assert exc.value.status_code == 400
|
||||
|
||||
|
||||
def test_timeline_routes_for_unknown_serial(tmp_path, monkeypatch):
|
||||
srv, _, _ = _env(tmp_path, monkeypatch)
|
||||
tl = srv.db_unit_timeline(serial="BE0000", from_dt=None, to_dt=None)
|
||||
assert (tl["sessions"], tl["gaps"], tl["call_ins"], tl["clock_steps"]) == ([], [], [], [])
|
||||
assert srv.db_unit_monitoring_at(serial="BE0000", at="2026-09-08T10:00:00")["status"] == "unknown"
|
||||
|
||||
|
||||
def test_mlg_records_route(tmp_path, monkeypatch):
|
||||
srv, _, _ = _env(tmp_path, monkeypatch)
|
||||
_import(srv, [_fixture("BE8081321.MLG")])
|
||||
out = srv.db_mlg_records(serial="BE8081", from_dt=None, to_dt=None)
|
||||
assert out["count"] == 6 and out["records"][0]["start_time"] == "2019-04-12T17:17:59"
|
||||
|
||||
|
||||
def test_mlg_file_route_returns_original_bytes(tmp_path, monkeypatch):
|
||||
srv, _, _ = _env(tmp_path, monkeypatch)
|
||||
name, data = _fixture("BE8081321.MLG")
|
||||
file_id = _import(srv, [(name, data)])["results"][0]["file_id"]
|
||||
resp = srv.db_mlg_file(file_id=file_id)
|
||||
assert Path(resp.path).read_bytes() == data and resp.filename == name
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
srv.db_mlg_file(file_id="no-such-id")
|
||||
assert exc.value.status_code == 404
|
||||
@@ -148,3 +148,13 @@ def test_no_data_gives_an_empty_timeline():
|
||||
tl = build_timeline([], [])
|
||||
assert tl == {"sessions": [], "gaps": [], "clock_steps": [], "call_ins": []}
|
||||
assert monitoring_at(tl, dt(2026, 9, 8))["status"] == "unknown"
|
||||
|
||||
|
||||
def test_window_filters_call_ins_by_unit_time_and_empty_files_by_file_time(tmp_path):
|
||||
from sfm.mlg_timeline import window
|
||||
tl = _timeline(tmp_path, "BE6907", "BE6907750.MLG", "BE6907751.MLG") # files at BASE, BASE+1h (UTC)
|
||||
late = window(tl, dt(2026, 8, 23), None)
|
||||
assert [(c["kind"], c["unit_time"]) for c in late["call_ins"]] == [("delivered", "2026-08-23T18:30:00")]
|
||||
around_file = window(tl, dt(2025, 12, 31), dt(2026, 1, 2))
|
||||
assert [c["kind"] for c in around_file["call_ins"]] == ["nothing_new"]
|
||||
assert window(tl, None, None)["call_ins"] == tl["call_ins"]
|
||||
Reference in new issue
Block a user