""" sfm/mlg_ingest.py — take in one Blastware .MLG: verify it, work out its unit, keep the original, store its records once. Shared by POST /db/import/mlg_file and scripts/import_mlg_dir.py. Spec: docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3, §5, §6. """ from __future__ import annotations import datetime import hashlib import logging import re from pathlib import Path from typing import Optional from minimateplus.mlg_file import MlgFormatError, parse_mlg log = logging.getLogger("sfm.mlg_ingest") _MODEM_EXIT = 0x0020 # A serial becomes a directory in the waveform store, and a header serial comes # from the file's own bytes: only plain serials (BE6907, UM20147) are used. _SERIAL_RE = re.compile(r"[A-Za-z0-9]{1,16}") def usable_serial(serial: Optional[str]) -> bool: return bool(serial) and _SERIAL_RE.fullmatch(serial) is not None def resolve_serial( file_name: str, header_serial: Optional[str], hint: Optional[str], known: set[str], ) -> Optional[str]: """The unit a .MLG belongs to. The serial inside the file wins; then the caller's hint. An empty file carries none, and its name is with nothing between, so take the longest serial SFM already knows that the name starts with, followed only by digits (or nothing: DL2's first file was BE8081.MLG). None when nothing fits.""" if header_serial: return header_serial if hint: return hint stem = Path(file_name).name if stem.upper().endswith(".MLG"): stem = stem[:-4] def fits(serial: str) -> bool: counter = stem[len(serial):] return stem.upper().startswith(serial.upper()) and (counter == "" or counter.isdigit()) candidates = [s for s in known if fits(s)] return max(candidates, key=len) if candidates else None def ingest_mlg( db, store, file_name: str, data: bytes, *, serial_hint: Optional[str] = None, file_mtime: Optional[datetime.datetime] = None, call_in: bool = True, ) -> dict: """Ingest one .MLG. Never raises for a bad file: the result says what happened. status "error": not a whole .MLG, or any record fails its checksum — nothing of it is stored. status "duplicate": this name with these bytes is already stored. status "ok": the original is kept and its new records stored.""" result = { "filename": file_name, "status": "error", "detail": None, "serial": None, "serial_unresolved": False, "empty": False, "records": 0, "inserted": 0, "skipped": 0, "file_id": None, } try: mlg = parse_mlg(data) except MlgFormatError as exc: result["detail"] = str(exc) return result result["records"] = len(mlg.records) result["empty"] = mlg.empty if mlg.crc_failures: result["detail"] = ", ".join(f"record {i}" for i in mlg.crc_failures) + " fails its checksum" return result header = mlg.serial or None for label, value in (("the file's serial", header), ("the serial hint", serial_hint)): if value is not None and not usable_serial(value): result["detail"] = f"{label} {value!r} is not a plain serial" return result known = db.known_serials() if not (header or serial_hint) else set() serial = resolve_serial(file_name, header, serial_hint, known) if mlg.records and serial is None: result["detail"] = "no serial: the file's header carries none and no hint was given" return result result["serial"] = serial result["serial_unresolved"] = serial is None # What this file says about calls, kept per file: a record stored once may # have arrived first in another file (a cable download). The file was sent # by the call that ended its last record; every earlier Modem Exit in it was # a call that left no file. last_stop = mlg.records[-1].stop if mlg.records else None no_file_stops = [r.stop for r in mlg.records[:-1] if not r.is_start and r.flags & _MODEM_EXIT and r.stop] sha256 = hashlib.sha256(data).hexdigest() if db.mlg_file_exists(file_name, sha256): result["status"] = "duplicate" result["detail"] = "this file is already stored" return result stored_path = store.save_mlg(serial, file_name, data) file_id, inserted, skipped = db.insert_mlg( serial=serial, file_name=file_name, sha256=sha256, size=len(data), empty=mlg.empty, call_in=call_in, file_mtime=file_mtime, stored_path=stored_path, records=mlg.records, last_stop=last_stop, no_file_stops=no_file_stops, ) if file_id is None: # stored between the check and the insert result["status"] = "duplicate" result["detail"] = "this file is already stored" return result result.update(status="ok", file_id=file_id, inserted=inserted, skipped=skipped) log.info("mlg %s serial=%s inserted=%d skipped=%d", file_name, serial, inserted, skipped) return result