feat(sfm): event models and event_id -- serial, key and timestamp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-21 16:54:53 -04:00
1 parent 83d1a98c1c
commit c85244e0fe
5 files changed
+180 -4

No files matched your search

+7 -3
View File
@@ -1,9 +1,13 @@
"""One door for every device request -- see the 2026-10-20 parity spec."""
from .errors import (
BadRequest, CallHomeInProgress, ConnectFailed, DeviceError, MalformedReply,
NoAnswer, NotSupported, UnitBusy, WrongUnit, translate,
BadRequest, CallHomeInProgress, ConnectFailed, DeviceError, EventNotFound,
MalformedReply, NoAnswer, NotSupported, StaleEvent, UnitBusy, WrongUnit,
translate,
)
from .models import (
DownloadedEvent, EventDownload, EventList, EventRef, UnitAddress, UnitInfo,
UnitSettings, UnitStatus,
)
from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .series import normalise_serial, series_for_serial
from .locks import UnitLocks
from .access import DeviceAccess
+10
View File
@@ -41,6 +41,16 @@ class MalformedReply(DeviceError):
http_status = 502
class EventNotFound(DeviceError):
http_status = 404
class StaleEvent(DeviceError):
"""The event at that key is not the one listed -- the unit was erased, or
its memory wrapped, since the list was read."""
http_status = 409
_TIMEOUTS = (_mm_proto.TimeoutError, _mmp_proto.TimeoutError)
_PROTOCOL = (_mm_proto.ProtocolError, _mmp_proto.ProtocolError)
+51
View File
@@ -0,0 +1,51 @@
"""Event identity. An `event_id` is `<serial>:<key hex>:<YYYYmmddHHMMSS>`.
The key alone is not enough: both series reuse keys (a MiniMate restarts at
01110000 after an erase; every Micromate's counter starts at the same value).
The timestamp turns a stale id into a loud StaleEvent instead of a download of
whatever now sits at that key. "-" stands in for an unknown timestamp.
"""
from __future__ import annotations
import datetime
from typing import Optional, Tuple
from .errors import BadRequest
from .series import normalise_serial
_NO_STAMP = "-"
_STAMP_FMT = "%Y%m%d%H%M%S"
def stamp_of(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.strftime(_STAMP_FMT) if dt is not None else None
def iso_of(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.isoformat() if dt is not None else None
def make_event_id(serial: str, key: bytes, stamp: Optional[str]) -> str:
return f"{normalise_serial(serial)}:{key.hex()}:{stamp or _NO_STAMP}"
def parse_event_id(event_id: str, serial: str) -> Tuple[bytes, Optional[str]]:
"""(key, stamp) for an id that belongs to `serial`; BadRequest otherwise."""
parts = (event_id or "").strip().split(":")
if len(parts) != 3:
raise BadRequest(f"not an event_id: {event_id!r} -- take it from GET /device/events")
id_serial, key_hex, stamp = parts
if normalise_serial(id_serial) != normalise_serial(serial):
raise BadRequest(f"event_id {event_id!r} belongs to {id_serial}, not {serial}")
try:
key = bytes.fromhex(key_hex)
except ValueError:
key = b""
if len(key) != 4:
raise BadRequest(f"event_id {event_id!r}: the key must be 8 hex digits")
if stamp != _NO_STAMP:
try:
datetime.datetime.strptime(stamp, _STAMP_FMT)
except ValueError:
raise BadRequest(f"event_id {event_id!r}: bad timestamp {stamp!r}") from None
return key, (None if stamp == _NO_STAMP else stamp)
+59 -1
View File
@@ -3,7 +3,7 @@ series; anything only one series has goes under `detail`."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, Optional
from typing import Any, Dict, List, Optional
from .errors import BadRequest
@@ -66,3 +66,61 @@ class UnitSettings:
geo_trigger_ips: Optional[float]
notes: Dict[str, str] = field(default_factory=dict)
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventRef:
"""One stored event, as listed. `event_id` is opaque: pass it back to
download the event. `index` is its position in the list right now; an
erase renumbers it, so it is for display, never identity."""
event_id: str
serial: str
series: int
index: int
timestamp: Optional[str] # ISO, the unit's own local time
record_type: Optional[str] # "waveform" | "histogram"
peak_vector_sum_ips: Optional[float]
peaks_ips: Dict[str, float] # geophones only: tran / vert / long
filename: Optional[str] # the name the vendor's software gives it
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventList:
serial: str
series: int
events: List[EventRef]
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventDownload:
"""What a download stored. The file and waveform are then served at
/db/events/{db_event_id}/... ."""
event_id: str
serial: str
series: int
db_event_id: Optional[str]
stored_filename: str
filesize: int
sha256: Optional[str]
inserted: bool # False: already stored; the row was refreshed
verified: Optional[bool] # True: decode self-check passed; None: no check exists
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class DownloadedEvent:
"""The device side's result, before SFM stores it. Not an HTTP shape: it
carries the payload -- a Series-3 Event + its 5A frames + the compliance
config, or a Series-4 file's bytes -- to sfm.event_ingest."""
event_id: str
serial: str
series: int
filename: str
verified: Optional[bool]
idf_bytes: Optional[bytes] = field(default=None, repr=False)
event: Any = field(default=None, repr=False)
a5_frames: Optional[list] = field(default=None, repr=False)
compliance: Any = field(default=None, repr=False)
detail: Dict[str, Any] = field(default_factory=dict)