-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.py
More file actions
321 lines (278 loc) · 10.8 KB
/
Copy pathstate.py
File metadata and controls
321 lines (278 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
from __future__ import annotations
"""In-memory telemetry store used by the GUI and operator-facing diagnostics."""
import asyncio
import base64
import logging
import threading
import time
from collections import deque
from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any
from core.model import MessageEvent, PositionEvent
def _now_ts() -> float:
return time.time()
@dataclass(slots=True)
class ComponentStatus:
name: str
state: str = "unknown"
detail: str | None = None
updated_at: float = field(default_factory=_now_ts)
last_ok_at: float | None = None
class StateStore:
"""Keep recent events, logs and component status snapshots for the operator panel."""
def __init__(
self,
*,
max_events: int = 500,
max_logs: int = 500,
max_errors: int = 200,
) -> None:
self._lock = threading.RLock()
self._event_counter = 0
self._events: deque[dict[str, Any]] = deque(maxlen=max_events)
self._logs: deque[dict[str, Any]] = deque(maxlen=max_logs)
self._errors: deque[dict[str, Any]] = deque(maxlen=max_errors)
self._statuses: dict[str, ComponentStatus] = {}
self._counters: dict[str, int] = {
"events_total": 0,
"positions_total": 0,
"messages_total": 0,
"duplicates_total": 0,
"dispatch_failures_total": 0,
}
def update_status(self, name: str, state: str, detail: str | None = None) -> None:
with self._lock:
current = self._statuses.get(name) or ComponentStatus(name=name)
current.state = state
current.detail = detail
current.updated_at = _now_ts()
if state == "online":
current.last_ok_at = current.updated_at
self._statuses[name] = current
def increment(self, key: str, amount: int = 1) -> None:
with self._lock:
self._counters[key] = self._counters.get(key, 0) + amount
def record_event(
self,
event: PositionEvent | MessageEvent,
*,
stage: str,
adapter: str | None = None,
outcome: str | None = None,
detail: str | None = None,
) -> int:
with self._lock:
self._event_counter += 1
record = {
"event_id": self._event_counter,
"stage": stage,
"adapter": adapter,
"outcome": outcome,
"detail": detail,
"time": _now_ts(),
"kind": event.kind,
"source": event.source.value,
"id": event.id,
"target": getattr(event, "target", None),
"message": getattr(event, "message", None),
"lat": getattr(event, "lat", None),
"lon": getattr(event, "lon", None),
"entity_kind": getattr(event, "entity_kind", None),
"position_type": getattr(event, "type", None),
"object_name": getattr(event, "object_name", None),
"owner_id": getattr(event, "owner_id", None),
"symbol_table": getattr(event, "symbol_table", None),
"symbol_code": getattr(event, "symbol_code", None),
"tactical_name": getattr(event, "tactical_name", None),
"dedup_key": event.dedup_key,
"raw": _json_safe(deepcopy(event.raw)),
}
if isinstance(event.raw, dict):
canonical = event.raw.get("canonical")
if isinstance(canonical, dict):
meta = canonical.get("meta")
if isinstance(meta, dict):
record["event_subtype"] = meta.get("source_subtype")
custom = canonical.get("sartrack", {}).get("custom")
if isinstance(custom, dict):
record["object_timestamp_raw"] = custom.get("object_timestamp_raw")
record["object_timestamp_utc"] = custom.get("object_timestamp_utc")
record["display_type"] = _event_display_type(record)
record["display_label"] = _event_display_label(record)
self._events.append(record)
self._counters["events_total"] += 1
if event.kind == "position":
self._counters["positions_total"] += 1
elif event.kind == "message":
self._counters["messages_total"] += 1
return self._event_counter
def record_duplicate(self, event: PositionEvent | MessageEvent) -> None:
self.increment("duplicates_total")
self.record_event(event, stage="publish", outcome="duplicate", detail="dedup filtered event")
def record_dispatch_failure(
self,
adapter: str,
event: PositionEvent | MessageEvent,
exc: Exception,
) -> None:
self.increment("dispatch_failures_total")
self.record_event(
event,
stage="dispatch",
adapter=adapter,
outcome="error",
detail=str(exc),
)
self.record_error(adapter, str(exc))
def record_error(self, component: str, message: str) -> None:
with self._lock:
self._errors.appendleft(
{
"time": _now_ts(),
"component": component,
"message": message,
}
)
def add_log_record(self, record: logging.LogRecord, rendered: str) -> None:
level = record.levelname.upper()
entry = {
"time": record.created,
"level": level,
"logger": record.name,
"message": record.getMessage(),
"rendered": rendered,
}
with self._lock:
self._logs.appendleft(entry)
if level in {"WARNING", "ERROR", "CRITICAL"}:
self.record_error(record.name, record.getMessage())
def get_status_snapshot(self) -> dict[str, Any]:
with self._lock:
return {
"statuses": {
name: {
"state": status.state,
"detail": status.detail,
"updated_at": status.updated_at,
"last_ok_at": status.last_ok_at,
}
for name, status in sorted(self._statuses.items())
},
"counters": dict(self._counters),
}
def get_recent_events(self, limit: int = 50) -> list[dict[str, Any]]:
with self._lock:
return [deepcopy(item) for item in list(self._events)[-limit:]][::-1]
def get_event(self, event_id: int) -> dict[str, Any] | None:
with self._lock:
for item in self._events:
if item["event_id"] == event_id:
return deepcopy(item)
return None
def get_recent_logs(
self,
limit: int = 100,
*,
level: str | None = None,
logger_name: str | None = None,
exclude_logger_names: list[str] | None = None,
) -> list[dict[str, Any]]:
with self._lock:
logs = list(self._logs)
items: list[dict[str, Any]] = []
excludes = [item.lower() for item in (exclude_logger_names or []) if item]
for item in logs:
if level and item["level"] != level.upper():
continue
if logger_name and logger_name not in item["logger"]:
continue
if excludes and any(exclude in item["logger"].lower() for exclude in excludes):
continue
items.append(deepcopy(item))
if len(items) >= limit:
break
return items
def get_recent_errors(self, limit: int = 50) -> list[dict[str, Any]]:
with self._lock:
return [deepcopy(item) for item in list(self._errors)[:limit]]
class StateStoreLogHandler(logging.Handler):
def __init__(self, state_store: StateStore) -> None:
super().__init__()
self.state_store = state_store
def emit(self, record: logging.LogRecord) -> None:
try:
rendered = self.format(record)
self.state_store.add_log_record(record, rendered)
except Exception:
self.handleError(record)
def _json_safe(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, bytes):
return {
"__type__": "bytes",
"base64": base64.b64encode(value).decode("ascii"),
"size": len(value),
}
if isinstance(value, dict):
return {str(key): _json_safe(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set, deque)):
return [_json_safe(item) for item in value]
if hasattr(value, "isoformat"):
try:
return value.isoformat()
except Exception:
pass
if hasattr(value, "__dict__"):
try:
return _json_safe(vars(value))
except Exception:
pass
return repr(value)
def _event_display_type(record: dict[str, Any]) -> str:
subtype = str(record.get("event_subtype") or record.get("position_type") or "").strip().lower()
target = str(record.get("target") or "").strip().upper()
message = str(record.get("message") or "").strip().upper()
if subtype in {
"station",
"object",
"private_message",
"encrypted_message",
"group_message",
"bulletin",
"ack",
"ping",
"query",
"status_response",
"task",
"status",
}:
return subtype.replace("_", " ")
if record.get("entity_kind") == "object" or record.get("position_type") == "object":
return "object"
if record.get("kind") == "position":
return "station"
if record.get("kind") == "message":
if target.startswith("BLN"):
return "bulletin"
if target in {"GRUPA", "GROUP", "ALL"}:
return "group message"
if message.startswith("?"):
return "query"
if message.startswith("PING"):
return "ping"
if target:
return "private message"
return "message"
return str(record.get("kind") or "event")
def _event_display_label(record: dict[str, Any]) -> str:
display_type = _event_display_type(record)
is_object = display_type == "object"
if is_object:
return str(record.get("tactical_name") or record.get("object_name") or record.get("id") or "-")
if record.get("kind") == "message":
source_id = str(record.get("id") or "-")
target = str(record.get("target") or "").strip()
return f"{source_id} -> {target}" if target else source_id
return str(record.get("id") or "-")