|
| 1 | +"""Emergency Mode — the "balloon went up" orchestrator (v7.5.0). |
| 2 | +
|
| 3 | +NOMAD has every component you need in an active crisis (SITREP, watch |
| 4 | +rotation, incidents, contacts, AI, Situation Room alerts, proximity, |
| 5 | +etc.) but nothing that *orchestrates* them for a live event. The user |
| 6 | +shouldn't have to remember to start a watch schedule, log an incident, |
| 7 | +and generate a SITREP separately. Emergency Mode does it for you. |
| 8 | +
|
| 9 | +Entering Emergency Mode: |
| 10 | + 1. Writes a persistent state flag to settings (emergency_active=true, |
| 11 | + emergency_started_at, emergency_reason). |
| 12 | + 2. Auto-creates an incident log entry with severity=critical and the |
| 13 | + user-supplied reason. |
| 14 | + 3. Broadcasts an SSE event so every open tab can enter red-mode UI |
| 15 | + without polling. |
| 16 | +
|
| 17 | +Exiting Emergency Mode: |
| 18 | + 1. Clears the state flags. |
| 19 | + 2. Appends a close-out incident log entry with total duration. |
| 20 | + 3. Broadcasts an SSE event so UI drops out of red mode. |
| 21 | +
|
| 22 | +All operations are idempotent — entering while already active is a |
| 23 | +no-op (returns the existing state); exiting while inactive is a no-op. |
| 24 | +This matters because a page reload during active emergency mode must |
| 25 | +restore the banner without double-entering. |
| 26 | +""" |
| 27 | + |
| 28 | +import logging |
| 29 | +from datetime import datetime, timezone |
| 30 | + |
| 31 | +from flask import Blueprint, request, jsonify, current_app |
| 32 | + |
| 33 | +from db import db_session, log_activity |
| 34 | + |
| 35 | +emergency_bp = Blueprint('emergency', __name__) |
| 36 | +log = logging.getLogger('nomad.emergency') |
| 37 | + |
| 38 | +_STATE_KEYS = { |
| 39 | + 'emergency_active': 'False', |
| 40 | + 'emergency_started_at': '', |
| 41 | + 'emergency_reason': '', |
| 42 | + 'emergency_incident_id': '', |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +def _read_state(db): |
| 47 | + """Load the emergency state dict from settings. Missing keys default.""" |
| 48 | + keys = tuple(_STATE_KEYS.keys()) |
| 49 | + placeholders = ','.join('?' * len(keys)) |
| 50 | + rows = db.execute( |
| 51 | + f'SELECT key, value FROM settings WHERE key IN ({placeholders})', |
| 52 | + keys, |
| 53 | + ).fetchall() |
| 54 | + got = {r['key']: r['value'] for r in rows} |
| 55 | + return { |
| 56 | + 'active': (got.get('emergency_active', 'False') or '').lower() == 'true', |
| 57 | + 'started_at': got.get('emergency_started_at') or None, |
| 58 | + 'reason': got.get('emergency_reason') or '', |
| 59 | + 'incident_id': _parse_int(got.get('emergency_incident_id')), |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | +def _write_state(db, **kwargs): |
| 64 | + """Upsert any subset of the emergency_* settings keys.""" |
| 65 | + for key, val in kwargs.items(): |
| 66 | + full_key = f'emergency_{key}' |
| 67 | + if full_key not in _STATE_KEYS: |
| 68 | + continue |
| 69 | + db.execute( |
| 70 | + 'INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)', |
| 71 | + (full_key, str(val) if val is not None else ''), |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +def _parse_int(v): |
| 76 | + try: return int(v) if v not in (None, '') else None |
| 77 | + except (TypeError, ValueError): return None |
| 78 | + |
| 79 | + |
| 80 | +def _duration_hours(started_iso): |
| 81 | + """Hours (float) between started_iso and now. None on bad input.""" |
| 82 | + if not started_iso: |
| 83 | + return None |
| 84 | + try: |
| 85 | + started = datetime.fromisoformat(started_iso.replace('Z', '+00:00')) |
| 86 | + except (TypeError, ValueError): |
| 87 | + return None |
| 88 | + if started.tzinfo is None: |
| 89 | + started = started.replace(tzinfo=timezone.utc) |
| 90 | + return round((datetime.now(timezone.utc) - started).total_seconds() / 3600, 2) |
| 91 | + |
| 92 | + |
| 93 | +def _broadcast(event_type, payload): |
| 94 | + """Fire an SSE event so every open tab syncs without polling.""" |
| 95 | + try: |
| 96 | + from web.app import _broadcast_event # circular-safe: only imported at call-time |
| 97 | + _broadcast_event(event_type, payload) |
| 98 | + except Exception: |
| 99 | + # SSE is a nice-to-have; never let a broadcast error block state change |
| 100 | + pass |
| 101 | + |
| 102 | + |
| 103 | +# ─── Routes ───────────────────────────────────────────────────────── |
| 104 | + |
| 105 | +@emergency_bp.route('/api/emergency/status') |
| 106 | +def api_emergency_status(): |
| 107 | + """Return the current emergency state + derived duration. |
| 108 | +
|
| 109 | + Also used on page load so every tab can pick up the banner after |
| 110 | + a reload without separately querying settings. |
| 111 | + """ |
| 112 | + with db_session() as db: |
| 113 | + state = _read_state(db) |
| 114 | + state['duration_hours'] = _duration_hours(state['started_at']) |
| 115 | + return jsonify(state) |
| 116 | + |
| 117 | + |
| 118 | +@emergency_bp.route('/api/emergency/enter', methods=['POST']) |
| 119 | +def api_emergency_enter(): |
| 120 | + """Enter emergency mode. Idempotent — returns current state if |
| 121 | + already active. Body: ``{reason}`` (optional, default 'Emergency'). |
| 122 | + """ |
| 123 | + data = request.get_json() or {} |
| 124 | + reason = (data.get('reason') or 'Emergency').strip()[:500] |
| 125 | + now_iso = datetime.now(timezone.utc).isoformat() |
| 126 | + |
| 127 | + with db_session() as db: |
| 128 | + state = _read_state(db) |
| 129 | + if state['active']: |
| 130 | + # Already active — return current state without mutation |
| 131 | + state['duration_hours'] = _duration_hours(state['started_at']) |
| 132 | + return jsonify({**state, 'already_active': True}) |
| 133 | + |
| 134 | + # Create a critical incident for the timeline |
| 135 | + incident_id = None |
| 136 | + try: |
| 137 | + cur = db.execute( |
| 138 | + 'INSERT INTO incidents (severity, category, description) VALUES (?, ?, ?)', |
| 139 | + ('critical', 'emergency', f'Emergency mode entered: {reason}'), |
| 140 | + ) |
| 141 | + incident_id = cur.lastrowid |
| 142 | + except Exception as e: |
| 143 | + log.warning(f'Could not create incident on emergency enter: {e}') |
| 144 | + |
| 145 | + _write_state(db, |
| 146 | + active='True', |
| 147 | + started_at=now_iso, |
| 148 | + reason=reason, |
| 149 | + incident_id=incident_id if incident_id is not None else '', |
| 150 | + ) |
| 151 | + db.commit() |
| 152 | + try: |
| 153 | + log_activity('emergency_enter', f'Emergency mode activated: {reason}') |
| 154 | + except Exception: |
| 155 | + pass |
| 156 | + |
| 157 | + _broadcast('emergency_enter', {'reason': reason, 'started_at': now_iso}) |
| 158 | + return jsonify({ |
| 159 | + 'active': True, |
| 160 | + 'started_at': now_iso, |
| 161 | + 'reason': reason, |
| 162 | + 'incident_id': incident_id, |
| 163 | + 'duration_hours': 0.0, |
| 164 | + }), 201 |
| 165 | + |
| 166 | + |
| 167 | +@emergency_bp.route('/api/emergency/exit', methods=['POST']) |
| 168 | +def api_emergency_exit(): |
| 169 | + """Exit emergency mode. Idempotent — no-op if not currently active. |
| 170 | + Body: ``{closeout_note}`` (optional) gets logged to the incident. |
| 171 | + """ |
| 172 | + data = request.get_json() or {} |
| 173 | + closeout = (data.get('closeout_note') or '').strip()[:2000] |
| 174 | + |
| 175 | + with db_session() as db: |
| 176 | + state = _read_state(db) |
| 177 | + if not state['active']: |
| 178 | + return jsonify({**state, 'already_inactive': True}) |
| 179 | + |
| 180 | + duration = _duration_hours(state['started_at']) |
| 181 | + duration_str = f'{duration}h' if duration is not None else 'unknown duration' |
| 182 | + exit_reason = state['reason'] or 'Emergency' |
| 183 | + |
| 184 | + # Log the closeout as a second incident entry for the timeline |
| 185 | + try: |
| 186 | + msg = f'Emergency mode exited ({duration_str}): {exit_reason}' |
| 187 | + if closeout: |
| 188 | + msg += f' — {closeout}' |
| 189 | + db.execute( |
| 190 | + 'INSERT INTO incidents (severity, category, description) VALUES (?, ?, ?)', |
| 191 | + ('info', 'emergency', msg), |
| 192 | + ) |
| 193 | + except Exception as e: |
| 194 | + log.warning(f'Could not create incident on emergency exit: {e}') |
| 195 | + |
| 196 | + _write_state(db, active='False', started_at='', reason='', incident_id='') |
| 197 | + db.commit() |
| 198 | + try: |
| 199 | + log_activity('emergency_exit', f'Emergency mode deactivated ({duration_str})') |
| 200 | + except Exception: |
| 201 | + pass |
| 202 | + |
| 203 | + _broadcast('emergency_exit', {'duration_hours': duration}) |
| 204 | + return jsonify({ |
| 205 | + 'active': False, |
| 206 | + 'duration_hours': duration, |
| 207 | + 'reason': exit_reason, |
| 208 | + }) |
0 commit comments