feat(mlg): store .MLG files and records, each record once
Two new tables, created on first start (no migration): mlg_files (one row per file received, deduped by name + sha256) and mlg_records (one row per log record, unique on serial, start, stop, flag word and trigger source; COALESCE on the stop, since an open record's NULL stop is distinct to a UNIQUE constraint). The text is not part of a record's identity: Blastware writes it, and two copies of the same records differ there. WaveformStore.save_mlg keeps the original file byte for byte under <serial>/mlg/. Operational consequence: two new tables on first start; no migration, no backfill. 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
a8adb03d23
commit
84d6cd05c3
3 files changed
+263
-3
No files matched your search
+152
-3
@@ -1,11 +1,15 @@
|
||||
"""
|
||||
sfm/database.py — SQLite persistence layer for seismo-relay.
|
||||
|
||||
Three tables, all keyed by unit serial number:
|
||||
Tables, all keyed by unit serial number:
|
||||
|
||||
ach_sessions — one row per inbound ACH call-home
|
||||
events — one row per triggered waveform event (deduped by serial+timestamp)
|
||||
monitor_log — one row per monitoring interval (deduped by serial+start_time)
|
||||
monitor_log — one row per monitoring interval (deduped by serial+start_time);
|
||||
live 0x0A reads by bridges/ach_server.py only
|
||||
mlg_files — one row per Blastware .MLG received (deduped by file name+sha256)
|
||||
mlg_records — one row per .MLG log record (deduped by serial, start, stop,
|
||||
flag word, trigger source — never the text, which Blastware writes)
|
||||
|
||||
The DB file lives at:
|
||||
<output_dir>/seismo_relay.db (default: bridges/captures/seismo_relay.db)
|
||||
@@ -43,7 +47,7 @@ from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from minimateplus.blastware_file import blastware_filename_time
|
||||
from minimateplus.models import Event, MonitorLogEntry
|
||||
from minimateplus.models import Event, MlgRecord, MonitorLogEntry
|
||||
|
||||
log = logging.getLogger("sfm.database")
|
||||
|
||||
@@ -150,6 +154,41 @@ CREATE TABLE IF NOT EXISTS device_commands (
|
||||
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
|
||||
|
||||
-- Blastware monitor logs (.MLG): spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
|
||||
-- Record times are the unit's own local clock (naive ISO); file_mtime is UTC (+00:00).
|
||||
CREATE TABLE IF NOT EXISTS mlg_files (
|
||||
id TEXT PRIMARY KEY,
|
||||
serial TEXT, -- NULL: an empty file whose unit is not known yet
|
||||
file_name TEXT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
record_count INTEGER NOT NULL, -- log records in the file (header excluded)
|
||||
empty INTEGER NOT NULL, -- 1: the 18-byte prefix alone
|
||||
call_in INTEGER NOT NULL DEFAULT 1, -- 0: a cable / direct download
|
||||
file_mtime TEXT, -- the file's modified time, when the sender gave it
|
||||
received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
stored_path TEXT, -- the original file, relative to the waveform store
|
||||
UNIQUE(file_name, sha256)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mlg_records (
|
||||
id TEXT PRIMARY KEY,
|
||||
serial TEXT NOT NULL,
|
||||
start_time TEXT NOT NULL,
|
||||
stop_time TEXT, -- NULL: "monitoring started", no stop yet
|
||||
flags INTEGER NOT NULL, -- monitor-log flag word; 65535 = started
|
||||
trigger_source INTEGER NOT NULL, -- 1-8 a channel, 1024 a histogram, 0 none
|
||||
text TEXT,
|
||||
trigger_level TEXT,
|
||||
event_time TEXT,
|
||||
file_id TEXT NOT NULL REFERENCES mlg_files(id), -- the file it first came in
|
||||
seq INTEGER NOT NULL -- its position in that file (1 = first log record)
|
||||
);
|
||||
-- NULL stops are distinct to a UNIQUE constraint, so the identity uses COALESCE.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity
|
||||
ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source);
|
||||
"""
|
||||
|
||||
|
||||
@@ -1259,6 +1298,116 @@ class SeismoDb:
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────
|
||||
|
||||
def mlg_file_exists(self, file_name: str, sha256: str) -> bool:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM mlg_files WHERE file_name = ? AND sha256 = ?",
|
||||
(file_name, sha256),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def insert_mlg(
|
||||
self,
|
||||
*,
|
||||
serial: Optional[str],
|
||||
file_name: str,
|
||||
sha256: str,
|
||||
size: int,
|
||||
empty: bool,
|
||||
call_in: bool,
|
||||
file_mtime: Optional[datetime.datetime],
|
||||
stored_path: Optional[str],
|
||||
records: list[MlgRecord],
|
||||
) -> tuple[Optional[str], int, int]:
|
||||
"""Store one .MLG file and its log records, in one transaction.
|
||||
|
||||
Returns (file_id, inserted, skipped); (None, 0, 0) when this file name
|
||||
with these bytes is already stored. A record already stored (from an
|
||||
earlier file) is skipped and keeps pointing at that file."""
|
||||
file_id = self._new_id()
|
||||
inserted = skipped = 0
|
||||
with self._connect() as conn:
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO mlg_files
|
||||
(id, serial, file_name, sha256, size, record_count, empty,
|
||||
call_in, file_mtime, stored_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(file_id, serial, file_name, sha256, size, len(records), int(empty),
|
||||
int(call_in), self._iso(file_mtime), stored_path),
|
||||
)
|
||||
except sqlite3.IntegrityError:
|
||||
return None, 0, 0
|
||||
for r in records:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO mlg_records
|
||||
(id, serial, start_time, stop_time, flags, trigger_source,
|
||||
text, trigger_level, event_time, file_id, seq)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(self._new_id(), serial, self._iso(r.start), self._iso(r.stop), r.flags,
|
||||
r.trigger_source, r.text, r.trigger_level, self._iso(r.event_time),
|
||||
file_id, r.index),
|
||||
)
|
||||
if cur.rowcount:
|
||||
inserted += 1
|
||||
else:
|
||||
skipped += 1
|
||||
log.debug("insert_mlg %s inserted=%d skipped=%d", file_name, inserted, skipped)
|
||||
return file_id, inserted, skipped
|
||||
|
||||
def query_mlg_records(
|
||||
self,
|
||||
serial: str,
|
||||
from_dt: Optional[datetime.datetime] = None,
|
||||
to_dt: Optional[datetime.datetime] = None,
|
||||
) -> list[dict]:
|
||||
"""A unit's .MLG records, oldest first (start time, then position in file)."""
|
||||
clauses, params = ["serial = ?"], [serial]
|
||||
if from_dt:
|
||||
clauses.append("start_time >= ?")
|
||||
params.append(from_dt.isoformat())
|
||||
if to_dt:
|
||||
clauses.append("start_time <= ?")
|
||||
params.append(to_dt.isoformat())
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(
|
||||
f"SELECT * FROM mlg_records WHERE {' AND '.join(clauses)} "
|
||||
f"ORDER BY start_time, seq",
|
||||
params,
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def query_mlg_files(self, serial: str) -> list[dict]:
|
||||
"""A unit's received .MLG files, oldest file time first."""
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM mlg_files WHERE serial = ? "
|
||||
"ORDER BY COALESCE(file_mtime, received_at), file_name",
|
||||
(serial,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def get_mlg_file(self, file_id: str) -> Optional[dict]:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute("SELECT * FROM mlg_files WHERE id = ?", (file_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def known_serials(self) -> set[str]:
|
||||
"""Every serial SFM holds data for: events, .MLG files and records."""
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT serial FROM events WHERE serial IS NOT NULL "
|
||||
"UNION SELECT serial FROM mlg_files WHERE serial IS NOT NULL "
|
||||
"UNION SELECT serial FROM mlg_records"
|
||||
).fetchall()
|
||||
return {r["serial"] for r in rows if r["serial"]}
|
||||
|
||||
# ── Fleet overview ────────────────────────────────────────────────────────
|
||||
|
||||
def query_units(self) -> list[dict]:
|
||||
|
||||
Reference in new issue
Block a user