"""Store an event SFM downloaded from a unit -- the SDM side of POST /device/events/download. Both series end in the two writes every other ingest path makes: the waveform store (file + sidecar + .h5) and SeismoDb.insert_events(). The database matches rows on (serial, timestamp), so storing an event already there -- by an earlier download, or by THOR's watcher -- refreshes the row instead of duplicating it. """ from __future__ import annotations import datetime from pathlib import Path from typing import Any, Optional from sfm.device_access.models import DownloadedEvent, EventDownload class IngestError(Exception): """Downloaded from the unit, but could not be stored.""" def backfill_series3_event(ev: Any, cc: Any) -> None: """Compliance-config values that supersede what the 5A stream decoded. Some STRT fields have ambiguous semantics (STRT[20] is rectime, but STRT[8:10] / STRT[16:18] are device-specific scratch, not reliable sample or pre-trigger counts). Shared with GET /device/event/{i}/blastware_file. """ if not cc: return if ev.sample_rate is None and cc.sample_rate: ev.sample_rate = cc.sample_rate if cc.record_time: # Authoritative: the user-set value the unit followed when recording. ev.rectime_seconds = cc.record_time # Derive total_samples from sample_rate x rectime when we can; the # STRT-derived value can land at a buffer offset rather than a count. if ev.sample_rate and ev.rectime_seconds: derived = int(round(ev.sample_rate * ev.rectime_seconds)) if (ev.total_samples is None or ev.total_samples > derived * 2 or ev.total_samples < derived // 4): ev.total_samples = derived def _event_dt(ev: Any) -> Optional[datetime.datetime]: ts = getattr(ev, "timestamp", None) try: return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) except Exception: # noqa: BLE001 return None def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload: if dl.series == 4: ev, rec = store.save_imported_idf(dl.idf_bytes, source_path=Path(dl.filename), serial_hint=dl.serial) family = "series4" else: ev = dl.event backfill_series3_event(ev, dl.compliance) geo_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None rec = store.save(ev, serial=dl.serial, a5_frames=dl.a5_frames, geo_range=geo_range if geo_range is not None else "normal") family = "series3" if ev is None or ev._waveform_key is None: raise IngestError(f"{dl.filename}: stored the file but could not build a database row") inserted, _skipped = db.insert_events( [ev], serial=dl.serial, waveform_records={ev._waveform_key.hex(): rec}, device_family=family) row_id = None dt = _event_dt(ev) if dt is not None: rows = db.query_events(serial=dl.serial, from_dt=dt, to_dt=dt, limit=1) row_id = rows[0]["id"] if rows else None return EventDownload( event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row_id, stored_filename=rec["filename"], filesize=rec["filesize"], sha256=rec.get("sha256"), inserted=inserted > 0, verified=dl.verified, detail=dict(dl.detail), )