Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion deadair/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -1438,7 +1438,7 @@ def _transition_evidence(condition: str, observation: Observation, *,
}


from .persistence import IncidentStore
from .persistence import IncidentStore, acknowledge_failed_delivery


def stream_fingerprint(stream: StreamConfig) -> str:
Expand Down Expand Up @@ -1952,6 +1952,15 @@ def _main(argv: Sequence[str] | None = None) -> int:
status_parser = commands.add_parser("status", help="read persisted health without network access or state writes")
status_parser.add_argument("--config", default=DEFAULT_CONFIG)
status_parser.add_argument("--json", action="store_true")
failures_parser = commands.add_parser("failures", help="list terminal notification failures without network access")
failures_parser.add_argument("--config", default=DEFAULT_CONFIG)
failures_parser.add_argument("--limit", type=int, default=50)
failures_parser.add_argument("--offset", type=int, default=0)
ack_parser = commands.add_parser("ack-delivery", help="acknowledge one terminal failed notification")
ack_parser.add_argument("--config", default=DEFAULT_CONFIG)
ack_parser.add_argument("--event-id", required=True)
ack_parser.add_argument("--destination-id", required=True)
ack_parser.add_argument("--operator", required=True)
check_parser = commands.add_parser("check", help="perform one bounded observation cycle")
check_parser.add_argument("--config", default=DEFAULT_CONFIG)
check_parser.add_argument("--json", action="store_true")
Expand Down Expand Up @@ -2010,6 +2019,29 @@ def _main(argv: Sequence[str] | None = None) -> int:
return 3
print(json.dumps(result, sort_keys=True) if args.json else format_status(result), flush=True)
return status_exit_code(result)
if args.command == "failures":
from .status import read_failed_deliveries
try:
failures = read_failed_deliveries(config, limit=args.limit, offset=args.offset)
except (PersistenceError, ValueError) as exc:
print(json.dumps({"ok": False, "error": str(exc)}, sort_keys=True), flush=True)
return 3
print(json.dumps({"ok": True, "failures": failures, "limit": args.limit, "offset": args.offset}, sort_keys=True), flush=True)
return 0
if args.command == "ack-delivery":
acknowledged_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
try:
result = acknowledge_failed_delivery(
config.watch.state_path, args.event_id, args.destination_id,
args.operator, acknowledged_at, time.time(), config.retention_days,
)
except (PersistenceError, ValueError) as exc:
print(json.dumps({"ok": False, "error": str(exc)}, sort_keys=True), flush=True)
return 3
ok = result in {"acknowledged", "already_acknowledged"}
print(json.dumps({"ok": ok, "result": result, "event_id": args.event_id,
"destination_id": args.destination_id}, sort_keys=True), flush=True)
return 0 if ok else 1
if args.command == "check":
try:
with IncidentStore(config.watch.state_path, config.retention_days) as store:
Expand Down
143 changes: 139 additions & 4 deletions deadair/persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,66 @@
from typing import Any, Mapping, Sequence
from .models import AppConfig, DestinationConfig, Observation, PersistenceError, StreamConfig


def _acknowledge_failed_delivery(db: sqlite3.Connection, event_id: str, destination_id: str,
operator: str, acknowledged_at: str, now_wall: float) -> str:
if (not isinstance(event_id, str) or not event_id or len(event_id) > 64
or not event_id.isascii() or not event_id.isalnum()):
raise ValueError("event_id must be a bounded ASCII identifier")
if (not isinstance(destination_id, str) or not destination_id
or len(destination_id) > 64
or any(char not in "abcdefghijklmnopqrstuvwxyz0123456789_-" for char in destination_id)):
raise ValueError("destination_id must be a bounded lowercase identifier")
if (not isinstance(operator, str) or not operator.strip()
or len(operator) > 80 or not operator.isprintable()):
raise ValueError("operator must be a printable label of 1 to 80 characters")
if not isinstance(acknowledged_at, str) or len(acknowledged_at) > 40:
raise ValueError("acknowledged_at must be an ISO timestamp")
try:
parsed_at = datetime.fromisoformat(acknowledged_at.replace("Z", "+00:00"))
except ValueError:
raise ValueError("acknowledged_at must be an ISO timestamp") from None
try:
finite_now = (isinstance(now_wall, (int, float)) and not isinstance(now_wall, bool)
and math.isfinite(now_wall))
except OverflowError:
finite_now = False
if parsed_at.tzinfo is None or not finite_now:
raise ValueError("acknowledgment time must include a timezone and finite epoch")
try:
db.execute("BEGIN IMMEDIATE")
row = db.execute(
"SELECT status,acknowledged_at FROM deliveries WHERE event_id=? AND destination_id=?",
(event_id, destination_id),
).fetchone()
if row is None:
db.execute("COMMIT")
return "not_found"
if row[0] != "failed":
db.execute("COMMIT")
return "not_failed"
if row[1] is not None:
db.execute("COMMIT")
return "already_acknowledged"
db.execute(
"UPDATE deliveries SET acknowledged_at=?,acknowledged_wall=?,acknowledged_by=? "
"WHERE event_id=? AND destination_id=? AND status='failed' AND acknowledged_at IS NULL",
(acknowledged_at, now_wall, operator.strip(), event_id, destination_id),
)
if db.execute("SELECT changes()").fetchone()[0] != 1:
raise sqlite3.DatabaseError("delivery changed during acknowledgment")
db.execute("COMMIT")
return "acknowledged"
except sqlite3.DatabaseError:
try:
db.execute("ROLLBACK")
except sqlite3.DatabaseError:
pass
raise PersistenceError("PERSISTENCE_WRITE_FAILED") from None


class IncidentStore:
SCHEMA = 1
SCHEMA = 2
LEGACY_GUARD = b"DEAD_AIR_OS_LOCK_V2\n"

def __init__(self, path: str | os.PathLike[str], retention_days: int = 90):
Expand All @@ -39,6 +97,8 @@ def __init__(self, path: str | os.PathLike[str], retention_days: int = 90):
version = int(self._db.execute("PRAGMA user_version").fetchone()[0])
if not existed:
self._create_schema()
elif version == 1:
self._migrate_schema_1()
elif version != self.SCHEMA:
raise PersistenceError("STATE_SCHEMA_UNSUPPORTED")
if self._db.execute("PRAGMA quick_check").fetchone()[0] != "ok":
Expand Down Expand Up @@ -90,12 +150,30 @@ def _create_schema(self) -> None:
destination_id TEXT NOT NULL, status TEXT NOT NULL, attempts INTEGER NOT NULL,
created_wall REAL NOT NULL, next_attempt_wall REAL, last_error TEXT,
last_http_status INTEGER, updated_wall REAL NOT NULL,
acknowledged_at TEXT, acknowledged_wall REAL, acknowledged_by TEXT,
PRIMARY KEY(event_id, destination_id)
);
PRAGMA user_version=1;
PRAGMA user_version=2;
COMMIT;
""")

def _migrate_schema_1(self) -> None:
"""Add delivery acknowledgments without deleting or rewriting delivery rows."""
assert self._db is not None
try:
self._db.execute("BEGIN EXCLUSIVE")
self._db.execute("ALTER TABLE deliveries ADD COLUMN acknowledged_at TEXT")
self._db.execute("ALTER TABLE deliveries ADD COLUMN acknowledged_wall REAL")
self._db.execute("ALTER TABLE deliveries ADD COLUMN acknowledged_by TEXT")
self._db.execute("PRAGMA user_version=2")
self._db.execute("COMMIT")
except sqlite3.DatabaseError:
try:
self._db.execute("ROLLBACK")
except sqlite3.DatabaseError:
pass
raise PersistenceError("STATE_MIGRATION_FAILED") from None

def _close_db(self) -> None:
if self._db is not None:
try:
Expand Down Expand Up @@ -197,7 +275,8 @@ def _insert_event(self, stream: StreamConfig, incident_id: str, condition: str,
)
for destination in destinations:
self._db.execute(
"INSERT INTO deliveries VALUES(?,?, 'pending',0,?,?,NULL,NULL,?)",
"INSERT INTO deliveries(event_id,destination_id,status,attempts,created_wall,next_attempt_wall,last_error,last_http_status,updated_wall) "
"VALUES(?,?,'pending',0,?,?,NULL,NULL,?)",
(event_id, destination.id, now_wall, now_wall, now_wall),
)

Expand Down Expand Up @@ -332,7 +411,8 @@ def _prune(self, now_wall: float) -> None:
self._db.execute("""
DELETE FROM events WHERE created_wall < ?
AND incident_id IN (SELECT incident_id FROM incidents WHERE closed_wall IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.event_id=events.event_id AND d.status!='sent')
AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.event_id=events.event_id
AND d.status!='sent' AND d.acknowledged_at IS NULL)
""", (cutoff,))
self._db.execute("""
DELETE FROM incidents WHERE closed_wall IS NOT NULL AND closed_wall < ?
Expand Down Expand Up @@ -376,6 +456,15 @@ def record_delivery(self, event_id: str, destination_id: str, success: bool,
except sqlite3.DatabaseError:
raise PersistenceError("PERSISTENCE_WRITE_FAILED") from None

def acknowledge_failed_delivery(self, event_id: str, destination_id: str,
operator: str, acknowledged_at: str,
now_wall: float) -> str:
"""Record who acknowledged a terminal failure while retaining its delivery row."""
assert self._db is not None
return _acknowledge_failed_delivery(
self._db, event_id, destination_id, operator, acknowledged_at, now_wall,
)

def open_incidents(self) -> list[tuple[Any, ...]]:
assert self._db is not None
return self._db.execute("SELECT stream_id,condition,opened_at FROM incidents WHERE closed_wall IS NULL ORDER BY condition").fetchall()
Expand All @@ -400,3 +489,49 @@ def diagnostics(self) -> dict[str, Any]:
raise PersistenceError("PERSISTENCE_READ_FAILED") from None


def acknowledge_failed_delivery(path: str | os.PathLike[str], event_id: str,
destination_id: str, operator: str,
acknowledged_at: str, now_wall: float,
retention_days: int = 90) -> str:
"""Acknowledge one terminal failure without resetting a running watcher's counters."""
state_path = Path(path).absolute()
if state_path.is_symlink() or state_path.parent.is_symlink():
raise PersistenceError("STATE_PATH_UNSAFE")
try:
state_size = state_path.stat().st_size
except FileNotFoundError:
return "not_found"
except OSError:
raise PersistenceError("STATE_UNAVAILABLE") from None
if state_size == 0:
raise PersistenceError("STATE_CORRUPT")
connection = None
try:
connection = sqlite3.connect(
state_path.as_uri() + "?mode=rw", uri=True, timeout=5, isolation_level=None,
)
connection.execute("PRAGMA busy_timeout=5000")
version = connection.execute("PRAGMA user_version").fetchone()[0]
if version == 1:
connection.close()
connection = None
# An old active writer cannot safely see the new columns. The normal
# writer lock makes migration wait until it stops before upgrading.
with IncidentStore(state_path, retention_days) as store:
return store.acknowledge_failed_delivery(
event_id, destination_id, operator, acknowledged_at, now_wall,
)
if version != IncidentStore.SCHEMA:
raise PersistenceError("STATE_SCHEMA_UNSUPPORTED")
# Schema-2 watch cycles remain the sole owner of stream and incident state.
# SQLite serializes this bounded acknowledgment update with those cycles.
return _acknowledge_failed_delivery(
connection, event_id, destination_id, operator, acknowledged_at, now_wall,
)
except sqlite3.DatabaseError:
raise PersistenceError("PERSISTENCE_READ_FAILED") from None
finally:
if connection is not None:
connection.close()


Loading
Loading