repodna-engine 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- repodna/__init__.py +3 -0
- repodna/__main__.py +10 -0
- repodna/advisor/__init__.py +17 -0
- repodna/advisor/engine.py +502 -0
- repodna/advisor/models.py +101 -0
- repodna/agent/__init__.py +87 -0
- repodna/agent/context.py +558 -0
- repodna/agent/deltas.py +198 -0
- repodna/agent/evidence.py +134 -0
- repodna/agent/expansion.py +447 -0
- repodna/agent/localization.py +518 -0
- repodna/agent/models.py +695 -0
- repodna/agent/patch.py +378 -0
- repodna/agent/postflight.py +278 -0
- repodna/agent/preflight.py +336 -0
- repodna/agent/ranking.py +318 -0
- repodna/agent/repo_map.py +392 -0
- repodna/agent/safety.py +111 -0
- repodna/agent/service.py +574 -0
- repodna/agent/sessions.py +264 -0
- repodna/agent/task.py +660 -0
- repodna/agent/telemetry.py +101 -0
- repodna/agent/token_budget.py +231 -0
- repodna/api/__init__.py +1 -0
- repodna/api/agent_routes.py +248 -0
- repodna/api/app.py +2904 -0
- repodna/benchmarks/__init__.py +29 -0
- repodna/benchmarks/baselines.py +126 -0
- repodna/benchmarks/budget_bench.py +162 -0
- repodna/benchmarks/engine.py +418 -0
- repodna/benchmarks/evaluator.py +310 -0
- repodna/benchmarks/metrics.py +206 -0
- repodna/benchmarks/models.py +194 -0
- repodna/benchmarks/scalability.py +166 -0
- repodna/brain/__init__.py +46 -0
- repodna/brain/evidence.py +276 -0
- repodna/brain/extractor.py +1207 -0
- repodna/brain/indexer.py +766 -0
- repodna/brain/models.py +275 -0
- repodna/brain/multilang_extractors.py +889 -0
- repodna/brain/retrieval.py +469 -0
- repodna/brain/tracer.py +203 -0
- repodna/cli/__init__.py +1 -0
- repodna/cli/__main__.py +10 -0
- repodna/cli/agent_cmd.py +228 -0
- repodna/cli/installer.py +590 -0
- repodna/cli/main.py +2173 -0
- repodna/cli/plugin_cmd.py +130 -0
- repodna/cli/workspace_cmd.py +211 -0
- repodna/context/__init__.py +9 -0
- repodna/context/builder.py +379 -0
- repodna/context/models.py +133 -0
- repodna/contract/__init__.py +39 -0
- repodna/contract/evaluator.py +318 -0
- repodna/contract/loader.py +260 -0
- repodna/contract/models.py +185 -0
- repodna/core/__init__.py +1 -0
- repodna/core/analyzer.py +1424 -0
- repodna/diff/__init__.py +35 -0
- repodna/diff/engine.py +332 -0
- repodna/diff/models.py +117 -0
- repodna/diff/snapshot.py +248 -0
- repodna/ecosystem/__init__.py +27 -0
- repodna/ecosystem/contracts.py +129 -0
- repodna/ecosystem/doctor.py +253 -0
- repodna/git_insights/__init__.py +1 -0
- repodna/git_insights/analyzer.py +273 -0
- repodna/graph/__init__.py +1 -0
- repodna/graph/engine.py +562 -0
- repodna/guardian/__init__.py +17 -0
- repodna/guardian/engine.py +369 -0
- repodna/guardian/models.py +104 -0
- repodna/history/__init__.py +40 -0
- repodna/history/cache.py +240 -0
- repodna/history/diff.py +394 -0
- repodna/history/engine.py +557 -0
- repodna/history/evidence.py +160 -0
- repodna/history/models.py +258 -0
- repodna/history/timeline.py +164 -0
- repodna/intelligence/__init__.py +33 -0
- repodna/intelligence/models.py +165 -0
- repodna/intelligence/service.py +570 -0
- repodna/live/__init__.py +94 -0
- repodna/live/alerts.py +443 -0
- repodna/live/coordinator.py +351 -0
- repodna/live/diff.py +444 -0
- repodna/live/events.py +471 -0
- repodna/live/filtering.py +329 -0
- repodna/live/history.py +637 -0
- repodna/live/models.py +505 -0
- repodna/live/observer.py +653 -0
- repodna/live/reconciliation.py +253 -0
- repodna/live/session.py +1547 -0
- repodna/mcp/__init__.py +5 -0
- repodna/mcp/__main__.py +6 -0
- repodna/mcp/agent_tools.py +258 -0
- repodna/mcp/server.py +3283 -0
- repodna/mcp/workspace_tools.py +200 -0
- repodna/parsers/__init__.py +13 -0
- repodna/parsers/base.py +126 -0
- repodna/parsers/capabilities.py +361 -0
- repodna/parsers/project_metadata.py +232 -0
- repodna/parsers/resolver.py +621 -0
- repodna/parsers/treesitter_parser.py +830 -0
- repodna/passport/__init__.py +64 -0
- repodna/passport/generator.py +546 -0
- repodna/passport/migrator.py +139 -0
- repodna/passport/models.py +224 -0
- repodna/passport/validator.py +143 -0
- repodna/performance/__init__.py +89 -0
- repodna/performance/cache.py +1584 -0
- repodna/performance/identity.py +341 -0
- repodna/performance/incremental.py +317 -0
- repodna/performance/models.py +157 -0
- repodna/performance/parallel.py +291 -0
- repodna/plugins/__init__.py +47 -0
- repodna/plugins/evaluator.py +334 -0
- repodna/plugins/models.py +113 -0
- repodna/plugins/validator.py +256 -0
- repodna/quality/__init__.py +91 -0
- repodna/quality/complexity.py +352 -0
- repodna/quality/config.py +159 -0
- repodna/quality/debt.py +73 -0
- repodna/quality/duplicates.py +330 -0
- repodna/quality/engine.py +282 -0
- repodna/quality/impact.py +198 -0
- repodna/quality/models.py +427 -0
- repodna/quality/rules.py +364 -0
- repodna/quality/sarif.py +107 -0
- repodna/quality/security_signals.py +278 -0
- repodna/quality/test_mapping.py +271 -0
- repodna/quality/unused.py +201 -0
- repodna/reports/__init__.py +1 -0
- repodna/reports/exporter.py +374 -0
- repodna/rules/__init__.py +1 -0
- repodna/rules/health.py +436 -0
- repodna/schemas/__init__.py +1 -0
- repodna/schemas/models.py +348 -0
- repodna/security/__init__.py +1 -0
- repodna/security/safe_yaml.py +81 -0
- repodna/security/validators.py +583 -0
- repodna/skills/__init__.py +0 -0
- repodna/skills/repodna/SKILL.md +59 -0
- repodna/skills/repodna/__init__.py +0 -0
- repodna/skills/repodna/examples/workflows.md +85 -0
- repodna/skills/repodna/references/architecture-rules.md +26 -0
- repodna/storage/__init__.py +1 -0
- repodna/storage/workspace.py +199 -0
- repodna/webui/__init__.py +1 -0
- repodna/webui/assets/DependencyGraph-km_Qo-nG.js +43 -0
- repodna/webui/assets/HealthReportView-WVL39aNO.js +1 -0
- repodna/webui/assets/index-ByZ5e5pe.js +506 -0
- repodna/webui/assets/index-CDj3e8hw.css +1 -0
- repodna/webui/index.html +21 -0
- repodna/workspace/__init__.py +131 -0
- repodna/workspace/compatibility.py +317 -0
- repodna/workspace/context.py +175 -0
- repodna/workspace/contracts.py +369 -0
- repodna/workspace/federation.py +411 -0
- repodna/workspace/identity.py +202 -0
- repodna/workspace/impact.py +111 -0
- repodna/workspace/manifest.py +266 -0
- repodna/workspace/models.py +461 -0
- repodna/workspace/packages.py +494 -0
- repodna/workspace/policies.py +142 -0
- repodna/workspace/services.py +238 -0
- repodna/workspace/topology.py +316 -0
- repodna_engine-1.0.1.dist-info/METADATA +129 -0
- repodna_engine-1.0.1.dist-info/RECORD +173 -0
- repodna_engine-1.0.1.dist-info/WHEEL +5 -0
- repodna_engine-1.0.1.dist-info/entry_points.txt +2 -0
- repodna_engine-1.0.1.dist-info/licenses/LICENSE +21 -0
- repodna_engine-1.0.1.dist-info/top_level.txt +1 -0
repodna/live/events.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"""Typed Live Event Bus with generation-scoped sequences, bounded replay buffer, and slow-client protection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import queue
|
|
8
|
+
import threading
|
|
9
|
+
import uuid
|
|
10
|
+
from collections import deque
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from repodna.live.models import (
|
|
16
|
+
LIVE_EVENT_SCHEMA_VERSION,
|
|
17
|
+
LiveEventEnvelope,
|
|
18
|
+
LiveEventType,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
# Keys that must NEVER be emitted in SSE / JSONL event streams (raw source code / secrets)
|
|
22
|
+
_FORBIDDEN_PAYLOAD_KEYS = frozenset(
|
|
23
|
+
{
|
|
24
|
+
"raw_source",
|
|
25
|
+
"source_code",
|
|
26
|
+
"file_content",
|
|
27
|
+
"content",
|
|
28
|
+
"secret",
|
|
29
|
+
"token",
|
|
30
|
+
"password",
|
|
31
|
+
"api_key",
|
|
32
|
+
"private_key",
|
|
33
|
+
"authorization",
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse_last_event_id(last_event_id: str | None) -> tuple[int | None, int | None]:
|
|
39
|
+
"""
|
|
40
|
+
Parse SSE `Last-Event-ID` formatted as `<session_generation>:<sequence>` or `<sequence>`.
|
|
41
|
+
Returns `(generation_or_none, sequence_or_none)`.
|
|
42
|
+
"""
|
|
43
|
+
if not last_event_id:
|
|
44
|
+
return None, None
|
|
45
|
+
cleaned = last_event_id.strip()
|
|
46
|
+
if not cleaned:
|
|
47
|
+
return None, None
|
|
48
|
+
if ":" in cleaned:
|
|
49
|
+
parts = cleaned.split(":", 1)
|
|
50
|
+
try:
|
|
51
|
+
return int(parts[0]), int(parts[1])
|
|
52
|
+
except ValueError:
|
|
53
|
+
return None, None
|
|
54
|
+
try:
|
|
55
|
+
return None, int(cleaned)
|
|
56
|
+
except ValueError:
|
|
57
|
+
return None, None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def sanitize_and_bound_payload(
|
|
61
|
+
payload: dict[str, Any],
|
|
62
|
+
*,
|
|
63
|
+
max_bytes: int = 64 * 1024,
|
|
64
|
+
) -> dict[str, Any]:
|
|
65
|
+
"""
|
|
66
|
+
Strip forbidden raw-source/secret keys and enforce an upper serialized byte bound
|
|
67
|
+
on event payloads without crashing or corrupting JSON structure.
|
|
68
|
+
"""
|
|
69
|
+
cleaned = _strip_forbidden(payload)
|
|
70
|
+
encoded = json.dumps(cleaned, default=str).encode("utf-8")
|
|
71
|
+
if len(encoded) <= max_bytes:
|
|
72
|
+
return cleaned
|
|
73
|
+
|
|
74
|
+
# Progressively truncate large lists/strings inside top-level payload
|
|
75
|
+
bounded: dict[str, Any] = {}
|
|
76
|
+
for k, v in cleaned.items():
|
|
77
|
+
if isinstance(v, list) and len(v) > 25:
|
|
78
|
+
bounded[k] = v[:25]
|
|
79
|
+
bounded[f"{k}_truncated"] = True
|
|
80
|
+
bounded[f"{k}_total_count"] = len(v)
|
|
81
|
+
elif isinstance(v, str) and len(v) > 2048:
|
|
82
|
+
bounded[k] = v[:2048] + "...[truncated]"
|
|
83
|
+
bounded["payload_truncated"] = True
|
|
84
|
+
else:
|
|
85
|
+
bounded[k] = v
|
|
86
|
+
|
|
87
|
+
encoded2 = json.dumps(bounded, default=str).encode("utf-8")
|
|
88
|
+
if len(encoded2) <= max_bytes:
|
|
89
|
+
bounded["payload_truncated"] = True
|
|
90
|
+
return bounded
|
|
91
|
+
|
|
92
|
+
# Last-resort minimal safe summary preserving core scalar fields
|
|
93
|
+
minimal: dict[str, Any] = {"payload_truncated": True}
|
|
94
|
+
for k, v in bounded.items():
|
|
95
|
+
if isinstance(v, (str, int, float, bool)) or v is None:
|
|
96
|
+
if isinstance(v, str) and len(v) > 512:
|
|
97
|
+
minimal[k] = v[:512]
|
|
98
|
+
else:
|
|
99
|
+
minimal[k] = v
|
|
100
|
+
return minimal
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _strip_forbidden(obj: Any) -> Any:
|
|
104
|
+
if isinstance(obj, dict):
|
|
105
|
+
return {
|
|
106
|
+
str(k): _strip_forbidden(v)
|
|
107
|
+
for k, v in obj.items()
|
|
108
|
+
if str(k).lower() not in _FORBIDDEN_PAYLOAD_KEYS
|
|
109
|
+
}
|
|
110
|
+
if isinstance(obj, list):
|
|
111
|
+
return [_strip_forbidden(item) for item in obj]
|
|
112
|
+
return obj
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def format_sse_event(envelope: LiveEventEnvelope) -> str:
|
|
116
|
+
"""Format a `LiveEventEnvelope` as a standards-compliant SSE frame."""
|
|
117
|
+
data_json = envelope.model_dump_json()
|
|
118
|
+
return f"id: {envelope.event_id}\nevent: {envelope.event_type.value}\ndata: {data_json}\n\n"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def format_sse_heartbeat() -> str:
|
|
122
|
+
"""Comment heartbeat frame per WHATWG SSE spec (does not advance Last-Event-ID)."""
|
|
123
|
+
return f": heartbeat {datetime.now(UTC).isoformat()}\n\n"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass
|
|
127
|
+
class _AsyncSubscriber:
|
|
128
|
+
subscriber_id: str
|
|
129
|
+
loop: asyncio.AbstractEventLoop
|
|
130
|
+
queue: asyncio.Queue[LiveEventEnvelope | None]
|
|
131
|
+
overflowed: bool = False
|
|
132
|
+
closed: bool = False
|
|
133
|
+
created_at: float = field(default_factory=lambda: datetime.now(UTC).timestamp())
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class _SyncSubscriber:
|
|
138
|
+
subscriber_id: str
|
|
139
|
+
queue: queue.Queue[LiveEventEnvelope | None]
|
|
140
|
+
overflowed: bool = False
|
|
141
|
+
closed: bool = False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class LiveEventBus:
|
|
145
|
+
"""
|
|
146
|
+
Thread-safe live event broker supporting both AsyncIO (FastAPI SSE) and synchronous (CLI)
|
|
147
|
+
subscribers with:
|
|
148
|
+
- Generation-scoped monotonic sequence numbers (`<generation>:<sequence>`)
|
|
149
|
+
- Bounded replay ring buffer (`max_replay_events`)
|
|
150
|
+
- `Last-Event-ID` replay and explicit `stream_reset` signaling on replay gap
|
|
151
|
+
- Bounded per-subscriber queues with non-blocking slow-client protection
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(
|
|
155
|
+
self,
|
|
156
|
+
*,
|
|
157
|
+
session_id: str,
|
|
158
|
+
session_generation: int = 1,
|
|
159
|
+
max_replay_events: int = 500,
|
|
160
|
+
max_subscriber_queue: int = 256,
|
|
161
|
+
max_payload_bytes: int = 64 * 1024,
|
|
162
|
+
) -> None:
|
|
163
|
+
self.session_id = session_id
|
|
164
|
+
self.session_generation = session_generation
|
|
165
|
+
self.max_replay_events = max(16, int(max_replay_events))
|
|
166
|
+
self.max_subscriber_queue = max(4, int(max_subscriber_queue))
|
|
167
|
+
self.max_payload_bytes = max(4096, int(max_payload_bytes))
|
|
168
|
+
|
|
169
|
+
self._lock = threading.Lock()
|
|
170
|
+
self._sequence = 0
|
|
171
|
+
self._replay: deque[LiveEventEnvelope] = deque(maxlen=self.max_replay_events)
|
|
172
|
+
self._async_subs: dict[str, _AsyncSubscriber] = {}
|
|
173
|
+
self._sync_subs: dict[str, _SyncSubscriber] = {}
|
|
174
|
+
self._slow_resets = 0
|
|
175
|
+
self._closed = False
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def current_sequence(self) -> int:
|
|
179
|
+
with self._lock:
|
|
180
|
+
return self._sequence
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def active_subscriber_count(self) -> int:
|
|
184
|
+
with self._lock:
|
|
185
|
+
return len(self._async_subs) + len(self._sync_subs)
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def slow_subscriber_resets(self) -> int:
|
|
189
|
+
with self._lock:
|
|
190
|
+
return self._slow_resets
|
|
191
|
+
|
|
192
|
+
def publish(
|
|
193
|
+
self,
|
|
194
|
+
event_type: LiveEventType,
|
|
195
|
+
payload: dict[str, Any] | None = None,
|
|
196
|
+
*,
|
|
197
|
+
snapshot_identity: str | None = None,
|
|
198
|
+
) -> LiveEventEnvelope:
|
|
199
|
+
"""
|
|
200
|
+
Publish a typed event to the replay ring and all active subscribers without blocking.
|
|
201
|
+
Slow subscribers whose bounded queue is full are signaled with `stream_reset` rather
|
|
202
|
+
than blocking the publisher or dropping events silently.
|
|
203
|
+
"""
|
|
204
|
+
safe_payload = sanitize_and_bound_payload(
|
|
205
|
+
payload or {}, max_bytes=self.max_payload_bytes
|
|
206
|
+
)
|
|
207
|
+
with self._lock:
|
|
208
|
+
self._sequence += 1
|
|
209
|
+
seq = self._sequence
|
|
210
|
+
envelope = LiveEventEnvelope(
|
|
211
|
+
schema_version=LIVE_EVENT_SCHEMA_VERSION,
|
|
212
|
+
session_id=self.session_id,
|
|
213
|
+
session_generation=self.session_generation,
|
|
214
|
+
event_id=f"{self.session_generation}:{seq}",
|
|
215
|
+
sequence=seq,
|
|
216
|
+
event_type=event_type,
|
|
217
|
+
timestamp=datetime.now(UTC),
|
|
218
|
+
snapshot_identity=snapshot_identity,
|
|
219
|
+
payload=safe_payload,
|
|
220
|
+
)
|
|
221
|
+
self._replay.append(envelope)
|
|
222
|
+
async_subs = list(self._async_subs.values())
|
|
223
|
+
sync_subs = list(self._sync_subs.values())
|
|
224
|
+
|
|
225
|
+
for sub in async_subs:
|
|
226
|
+
self._deliver_async(sub, envelope)
|
|
227
|
+
for ssub in sync_subs:
|
|
228
|
+
self._deliver_sync(ssub, envelope)
|
|
229
|
+
|
|
230
|
+
return envelope
|
|
231
|
+
|
|
232
|
+
def build_stream_reset_envelope(
|
|
233
|
+
self,
|
|
234
|
+
*,
|
|
235
|
+
reason: str,
|
|
236
|
+
authoritative_state: dict[str, Any],
|
|
237
|
+
snapshot_identity: str | None = None,
|
|
238
|
+
) -> LiveEventEnvelope:
|
|
239
|
+
"""Construct a non-buffered `stream_reset` envelope carrying authoritative resync state."""
|
|
240
|
+
with self._lock:
|
|
241
|
+
seq = self._sequence
|
|
242
|
+
safe_payload = sanitize_and_bound_payload(
|
|
243
|
+
{
|
|
244
|
+
"reason": reason,
|
|
245
|
+
"latest_sequence": seq,
|
|
246
|
+
"session": authoritative_state,
|
|
247
|
+
},
|
|
248
|
+
max_bytes=self.max_payload_bytes,
|
|
249
|
+
)
|
|
250
|
+
return LiveEventEnvelope(
|
|
251
|
+
schema_version=LIVE_EVENT_SCHEMA_VERSION,
|
|
252
|
+
session_id=self.session_id,
|
|
253
|
+
session_generation=self.session_generation,
|
|
254
|
+
event_id=f"{self.session_generation}:{seq}",
|
|
255
|
+
sequence=seq,
|
|
256
|
+
event_type=LiveEventType.STREAM_RESET,
|
|
257
|
+
timestamp=datetime.now(UTC),
|
|
258
|
+
snapshot_identity=snapshot_identity,
|
|
259
|
+
payload=safe_payload,
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
def _deliver_async(self, sub: _AsyncSubscriber, envelope: LiveEventEnvelope) -> None:
|
|
263
|
+
if sub.closed or sub.loop.is_closed():
|
|
264
|
+
return
|
|
265
|
+
|
|
266
|
+
def _enqueue() -> None:
|
|
267
|
+
if sub.closed:
|
|
268
|
+
return
|
|
269
|
+
try:
|
|
270
|
+
sub.queue.put_nowait(envelope)
|
|
271
|
+
except asyncio.QueueFull:
|
|
272
|
+
# Slow subscriber protection: drain backlog and emit stream_reset marker
|
|
273
|
+
sub.overflowed = True
|
|
274
|
+
with self._lock:
|
|
275
|
+
self._slow_resets += 1
|
|
276
|
+
while not sub.queue.empty():
|
|
277
|
+
try:
|
|
278
|
+
sub.queue.get_nowait()
|
|
279
|
+
except asyncio.QueueEmpty:
|
|
280
|
+
break
|
|
281
|
+
reset_ev = LiveEventEnvelope(
|
|
282
|
+
schema_version=LIVE_EVENT_SCHEMA_VERSION,
|
|
283
|
+
session_id=self.session_id,
|
|
284
|
+
session_generation=self.session_generation,
|
|
285
|
+
event_id=envelope.event_id,
|
|
286
|
+
sequence=envelope.sequence,
|
|
287
|
+
event_type=LiveEventType.STREAM_RESET,
|
|
288
|
+
timestamp=datetime.now(UTC),
|
|
289
|
+
snapshot_identity=envelope.snapshot_identity,
|
|
290
|
+
payload={
|
|
291
|
+
"reason": "slow_subscriber_queue_overflow",
|
|
292
|
+
"latest_sequence": envelope.sequence,
|
|
293
|
+
"resync_required": True,
|
|
294
|
+
},
|
|
295
|
+
)
|
|
296
|
+
try:
|
|
297
|
+
sub.queue.put_nowait(reset_ev)
|
|
298
|
+
except asyncio.QueueFull:
|
|
299
|
+
pass
|
|
300
|
+
|
|
301
|
+
try:
|
|
302
|
+
sub.loop.call_soon_threadsafe(_enqueue)
|
|
303
|
+
except RuntimeError:
|
|
304
|
+
pass
|
|
305
|
+
|
|
306
|
+
def _deliver_sync(self, sub: _SyncSubscriber, envelope: LiveEventEnvelope) -> None:
|
|
307
|
+
if sub.closed:
|
|
308
|
+
return
|
|
309
|
+
try:
|
|
310
|
+
sub.queue.put_nowait(envelope)
|
|
311
|
+
except queue.Full:
|
|
312
|
+
sub.overflowed = True
|
|
313
|
+
with self._lock:
|
|
314
|
+
self._slow_resets += 1
|
|
315
|
+
while True:
|
|
316
|
+
try:
|
|
317
|
+
sub.queue.get_nowait()
|
|
318
|
+
except queue.Empty:
|
|
319
|
+
break
|
|
320
|
+
reset_ev = LiveEventEnvelope(
|
|
321
|
+
schema_version=LIVE_EVENT_SCHEMA_VERSION,
|
|
322
|
+
session_id=self.session_id,
|
|
323
|
+
session_generation=self.session_generation,
|
|
324
|
+
event_id=envelope.event_id,
|
|
325
|
+
sequence=envelope.sequence,
|
|
326
|
+
event_type=LiveEventType.STREAM_RESET,
|
|
327
|
+
timestamp=datetime.now(UTC),
|
|
328
|
+
snapshot_identity=envelope.snapshot_identity,
|
|
329
|
+
payload={
|
|
330
|
+
"reason": "slow_subscriber_queue_overflow",
|
|
331
|
+
"latest_sequence": envelope.sequence,
|
|
332
|
+
"resync_required": True,
|
|
333
|
+
},
|
|
334
|
+
)
|
|
335
|
+
try:
|
|
336
|
+
sub.queue.put_nowait(reset_ev)
|
|
337
|
+
except queue.Full:
|
|
338
|
+
pass
|
|
339
|
+
|
|
340
|
+
def get_replay_since(
|
|
341
|
+
self, last_event_id: str | None
|
|
342
|
+
) -> tuple[list[LiveEventEnvelope], bool, str | None]:
|
|
343
|
+
"""
|
|
344
|
+
Compute events to replay for a reconnecting subscriber given `Last-Event-ID`.
|
|
345
|
+
|
|
346
|
+
Returns `(events_to_replay, needs_stream_reset, reset_reason)`.
|
|
347
|
+
"""
|
|
348
|
+
if not last_event_id:
|
|
349
|
+
return [], False, None
|
|
350
|
+
|
|
351
|
+
req_gen, req_seq = parse_last_event_id(last_event_id)
|
|
352
|
+
if req_seq is None:
|
|
353
|
+
return [], True, "invalid_last_event_id"
|
|
354
|
+
|
|
355
|
+
with self._lock:
|
|
356
|
+
if req_gen is not None and req_gen != self.session_generation:
|
|
357
|
+
return [], True, "session_generation_mismatch"
|
|
358
|
+
|
|
359
|
+
if req_seq >= self._sequence:
|
|
360
|
+
return [], False, None
|
|
361
|
+
|
|
362
|
+
if not self._replay:
|
|
363
|
+
return [], True, "replay_buffer_empty"
|
|
364
|
+
|
|
365
|
+
oldest_seq = self._replay[0].sequence
|
|
366
|
+
if req_seq < oldest_seq - 1:
|
|
367
|
+
return [], True, f"replay_buffer_gap (requested={req_seq}, oldest={oldest_seq})"
|
|
368
|
+
|
|
369
|
+
missed = [ev for ev in self._replay if ev.sequence > req_seq]
|
|
370
|
+
return missed, False, None
|
|
371
|
+
|
|
372
|
+
def subscribe_async(
|
|
373
|
+
self,
|
|
374
|
+
loop: asyncio.AbstractEventLoop,
|
|
375
|
+
*,
|
|
376
|
+
last_event_id: str | None = None,
|
|
377
|
+
) -> tuple[str, asyncio.Queue[LiveEventEnvelope | None], list[LiveEventEnvelope], bool, str | None]:
|
|
378
|
+
"""Register an AsyncIO subscriber (FastAPI SSE) and atomically fetch replay state."""
|
|
379
|
+
sub_id = f"sub_{uuid.uuid4().hex[:10]}"
|
|
380
|
+
q: asyncio.Queue[LiveEventEnvelope | None] = asyncio.Queue(maxsize=self.max_subscriber_queue)
|
|
381
|
+
sub = _AsyncSubscriber(subscriber_id=sub_id, loop=loop, queue=q)
|
|
382
|
+
|
|
383
|
+
with self._lock:
|
|
384
|
+
missed, needs_reset, reset_reason = self._compute_replay_locked(last_event_id)
|
|
385
|
+
if not self._closed:
|
|
386
|
+
self._async_subs[sub_id] = sub
|
|
387
|
+
else:
|
|
388
|
+
q.put_nowait(None)
|
|
389
|
+
|
|
390
|
+
return sub_id, q, missed, needs_reset, reset_reason
|
|
391
|
+
|
|
392
|
+
def _compute_replay_locked(
|
|
393
|
+
self, last_event_id: str | None
|
|
394
|
+
) -> tuple[list[LiveEventEnvelope], bool, str | None]:
|
|
395
|
+
if not last_event_id:
|
|
396
|
+
return [], False, None
|
|
397
|
+
req_gen, req_seq = parse_last_event_id(last_event_id)
|
|
398
|
+
if req_seq is None:
|
|
399
|
+
return [], True, "invalid_last_event_id"
|
|
400
|
+
if req_gen is not None and req_gen != self.session_generation:
|
|
401
|
+
return [], True, "session_generation_mismatch"
|
|
402
|
+
if req_seq >= self._sequence:
|
|
403
|
+
return [], False, None
|
|
404
|
+
if not self._replay:
|
|
405
|
+
return [], True, "replay_buffer_empty"
|
|
406
|
+
oldest_seq = self._replay[0].sequence
|
|
407
|
+
if req_seq < oldest_seq - 1:
|
|
408
|
+
return [], True, f"replay_buffer_gap (requested={req_seq}, oldest={oldest_seq})"
|
|
409
|
+
return [ev for ev in self._replay if ev.sequence > req_seq], False, None
|
|
410
|
+
|
|
411
|
+
def unsubscribe_async(self, subscriber_id: str) -> None:
|
|
412
|
+
with self._lock:
|
|
413
|
+
sub = self._async_subs.pop(subscriber_id, None)
|
|
414
|
+
if sub is not None:
|
|
415
|
+
sub.closed = True
|
|
416
|
+
|
|
417
|
+
def subscribe_sync(self) -> tuple[str, queue.Queue[LiveEventEnvelope | None]]:
|
|
418
|
+
"""Register a thread-safe synchronous subscriber (CLI watch mode)."""
|
|
419
|
+
sub_id = f"sync_{uuid.uuid4().hex[:10]}"
|
|
420
|
+
q: queue.Queue[LiveEventEnvelope | None] = queue.Queue(maxsize=self.max_subscriber_queue)
|
|
421
|
+
sub = _SyncSubscriber(subscriber_id=sub_id, queue=q)
|
|
422
|
+
with self._lock:
|
|
423
|
+
if not self._closed:
|
|
424
|
+
self._sync_subs[sub_id] = sub
|
|
425
|
+
else:
|
|
426
|
+
q.put_nowait(None)
|
|
427
|
+
return sub_id, q
|
|
428
|
+
|
|
429
|
+
def unsubscribe_sync(self, subscriber_id: str) -> None:
|
|
430
|
+
with self._lock:
|
|
431
|
+
sub = self._sync_subs.pop(subscriber_id, None)
|
|
432
|
+
if sub is not None:
|
|
433
|
+
sub.closed = True
|
|
434
|
+
|
|
435
|
+
def close_all(self) -> None:
|
|
436
|
+
"""Close all subscriber streams cleanly on session stop or server shutdown."""
|
|
437
|
+
with self._lock:
|
|
438
|
+
self._closed = True
|
|
439
|
+
async_subs = list(self._async_subs.values())
|
|
440
|
+
sync_subs = list(self._sync_subs.values())
|
|
441
|
+
self._async_subs.clear()
|
|
442
|
+
self._sync_subs.clear()
|
|
443
|
+
|
|
444
|
+
for sub in async_subs:
|
|
445
|
+
sub.closed = True
|
|
446
|
+
if not sub.loop.is_closed():
|
|
447
|
+
def _signal_close(target_q: asyncio.Queue[LiveEventEnvelope | None] = sub.queue) -> None:
|
|
448
|
+
try:
|
|
449
|
+
target_q.put_nowait(None)
|
|
450
|
+
except asyncio.QueueFull:
|
|
451
|
+
try:
|
|
452
|
+
target_q.get_nowait()
|
|
453
|
+
target_q.put_nowait(None)
|
|
454
|
+
except Exception:
|
|
455
|
+
pass
|
|
456
|
+
|
|
457
|
+
try:
|
|
458
|
+
sub.loop.call_soon_threadsafe(_signal_close)
|
|
459
|
+
except RuntimeError:
|
|
460
|
+
pass
|
|
461
|
+
|
|
462
|
+
for ssub in sync_subs:
|
|
463
|
+
ssub.closed = True
|
|
464
|
+
try:
|
|
465
|
+
ssub.queue.put_nowait(None)
|
|
466
|
+
except queue.Full:
|
|
467
|
+
try:
|
|
468
|
+
ssub.queue.get_nowait()
|
|
469
|
+
ssub.queue.put_nowait(None)
|
|
470
|
+
except Exception:
|
|
471
|
+
pass
|