forum_runtime.py
11 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
322
323
324
325
326
327
"""Forum engine runtime helpers and object-oriented adapter."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable
from loguru import logger
from apps.web_api.runtime.log_stream import read_log_from_file
from apps.web_api.runtime.process_registry import PROCESS_RUNTIME_REGISTRY, ProcessRuntimeRegistry
from services.shared.models import EngineExecutionError, EngineResult
ForumEmitOutput = Callable[[str, dict[str, Any]], None]
ForumMonitorStarter = Callable[[], bool]
ForumMonitorStopper = Callable[[], None]
ForumLogReader = Callable[[Path, str, int | None], list[str]]
_FORUM_ENGINE_NAME = "forum"
_FORUM_LOG_FILE_NAME = "forum.log"
def _default_start_forum_monitoring() -> bool:
from services.engines.forum.monitor import start_forum_monitoring
return start_forum_monitoring()
def _default_stop_forum_monitoring() -> None:
from services.engines.forum.monitor import stop_forum_monitoring
stop_forum_monitoring()
class ForumRuntime:
"""Object-oriented wrapper around forum runtime operations."""
def __init__(
self,
*,
process_registry: ProcessRuntimeRegistry | None = None,
read_log: ForumLogReader = read_log_from_file,
start_monitoring: ForumMonitorStarter = _default_start_forum_monitoring,
stop_monitoring: ForumMonitorStopper = _default_stop_forum_monitoring,
) -> None:
self._process_registry = process_registry
self._read_log = read_log
self._start_monitoring = start_monitoring
self._stop_monitoring = stop_monitoring
@property
def process_registry(self) -> ProcessRuntimeRegistry:
return self._process_registry if self._process_registry is not None else PROCESS_RUNTIME_REGISTRY
def start_engine(self, *, emit_output: ForumEmitOutput | None = None) -> bool:
try:
logger.info("ForumEngine: starting forum monitoring")
success = self._start_monitoring()
if not success:
raise RuntimeError("ForumEngine failed to start")
self.process_registry.set_status(_FORUM_ENGINE_NAME, "running")
if emit_output is not None:
emit_output(
"console_output",
{
"app": _FORUM_ENGINE_NAME,
"line": "[SYSTEM] ForumEngine started",
},
)
return True
except Exception as exc:
self.process_registry.set_status(_FORUM_ENGINE_NAME, "error")
logger.exception(f"ForumEngine failed to start: {exc}")
raise
def stop_engine(self, *, emit_output: ForumEmitOutput | None = None) -> None:
try:
logger.info("ForumEngine: stopping forum monitoring")
self._stop_monitoring()
self.process_registry.set_status(_FORUM_ENGINE_NAME, "stopped")
if emit_output is not None:
emit_output(
"console_output",
{
"app": _FORUM_ENGINE_NAME,
"line": "[SYSTEM] ForumEngine stopped",
},
)
logger.info("ForumEngine: forum monitoring stopped")
except Exception as exc:
self.process_registry.set_status(_FORUM_ENGINE_NAME, "error")
logger.exception(f"ForumEngine failed to stop: {exc}")
raise
def get_output(self, *, log_dir: Path) -> dict[str, Any]:
lines = self._read_log(log_dir, _FORUM_ENGINE_NAME)
parsed_messages = self._parse_lines(lines)
return {
"success": True,
"output": lines,
"total_lines": len(lines),
"engine_result": self._build_engine_result(
log_dir=log_dir,
lines=lines,
parsed_messages=parsed_messages,
),
}
def get_log_payload(self, *, log_dir: Path) -> dict[str, Any]:
lines = self._read_log(log_dir, _FORUM_ENGINE_NAME)
parsed_messages = self._parse_lines(lines)
return {
"success": True,
"log_lines": lines,
"parsed_messages": parsed_messages,
"total_lines": len(lines),
"engine_result": self._build_engine_result(
log_dir=log_dir,
lines=lines,
parsed_messages=parsed_messages,
),
}
def get_log_history(
self,
*,
log_dir: Path,
start_position: int = 0,
max_lines: int = 1000,
) -> dict[str, Any]:
forum_log_file = log_dir / _FORUM_LOG_FILE_NAME
if not forum_log_file.exists():
return {
"success": True,
"log_lines": [],
"position": 0,
"has_more": False,
"engine_result": self._build_engine_result(log_dir=log_dir, lines=[]),
}
with open(forum_log_file, "r", encoding="utf-8", errors="ignore") as file:
file.seek(start_position)
lines: list[str] = []
line_count = 0
while line_count < max_lines:
line = file.readline()
if not line:
break
normalized = line.rstrip("\n\r")
if normalized.strip():
lines.append(normalized)
line_count += 1
current_position = file.tell()
file.seek(0, 2)
end_position = file.tell()
parsed_messages = self._parse_lines(lines)
return {
"success": True,
"log_lines": lines,
"position": current_position,
"has_more": current_position < end_position,
"engine_result": self._build_engine_result(
log_dir=log_dir,
lines=lines,
parsed_messages=parsed_messages,
),
}
def _parse_lines(self, lines: list[str]) -> list[dict[str, str]]:
return [parsed for parsed in (parse_forum_log_line(line) for line in lines) if parsed is not None]
def _build_engine_result(
self,
*,
log_dir: Path,
lines: list[str],
parsed_messages: list[dict[str, str]] | None = None,
) -> dict[str, Any]:
parsed = list(parsed_messages) if parsed_messages is not None else self._parse_lines(lines)
host_summary = self._extract_host_summary(parsed)
runtime_status = self.process_registry.get_status(_FORUM_ENGINE_NAME).strip().lower()
status = self._resolve_engine_status(runtime_status=runtime_status, host_summary=host_summary, parsed_messages=parsed)
success = status != "failed"
summary = self._resolve_engine_summary(
status=status,
parsed_messages=parsed,
host_summary=host_summary,
)
participants = sorted({message["source"] for message in parsed if message.get("source")})
artifacts: dict[str, Any] = {
"parsed_messages": parsed,
"participants": participants,
}
if host_summary:
artifacts["host_summary"] = host_summary
metrics = {
"log_line_count": len(lines),
"parsed_message_count": len(parsed),
"participant_count": len(participants),
"host_summary_count": 1 if host_summary else 0,
}
error = None
if not success:
error = EngineExecutionError(
code="forum_runtime_error",
message=summary,
retryable=False,
details={"runtime_status": runtime_status or "unknown"},
)
return EngineResult(
engine_name=_FORUM_ENGINE_NAME,
status=status,
success=success,
summary=summary,
artifacts=artifacts,
metrics=metrics,
logs_ref=str(log_dir / _FORUM_LOG_FILE_NAME),
error=error,
).to_runtime_payload()
@staticmethod
def _extract_host_summary(parsed_messages: list[dict[str, str]]) -> str:
for message in reversed(parsed_messages):
if message.get("source", "").strip().upper() != "HOST":
continue
content = str(message.get("content") or "").strip()
if content:
return content
return ""
@staticmethod
def _resolve_engine_status(
*,
runtime_status: str,
host_summary: str,
parsed_messages: list[dict[str, str]],
) -> str:
if runtime_status == "error":
return "failed"
if host_summary:
return "completed"
if runtime_status == "running":
return "running"
if runtime_status in {"stopped", "idle", "pending"}:
return runtime_status
if parsed_messages:
return "running"
return "idle"
@staticmethod
def _resolve_engine_summary(
*,
status: str,
parsed_messages: list[dict[str, str]],
host_summary: str,
) -> str:
if host_summary:
return host_summary
if parsed_messages:
latest_content = str(parsed_messages[-1].get("content") or "").strip()
if latest_content:
return latest_content
if status == "running":
return "Forum discussion is running"
if status == "failed":
return "Forum runtime reported an error"
if status == "stopped":
return "Forum discussion is stopped"
return "Forum discussion has no log output yet"
def parse_forum_log_line(line: str) -> dict[str, str] | None:
normalized = line.strip()
if not normalized:
return None
if normalized.startswith("["):
try:
timestamp_end = normalized.index("]")
timestamp = normalized[1:timestamp_end]
remaining = normalized[timestamp_end + 1 :].strip()
if remaining.startswith("["):
source_end = remaining.index("]")
source = remaining[1:source_end]
content = remaining[source_end + 1 :].strip()
return {
"timestamp": timestamp,
"source": source,
"content": content.replace("\\n", "\n").replace("\\r", "\r"),
}
return {
"timestamp": timestamp,
"source": "SYSTEM",
"content": remaining.replace("\\n", "\n").replace("\\r", "\r"),
}
except ValueError:
pass
return {
"timestamp": "",
"source": "UNKNOWN",
"content": normalized.replace("\\n", "\n").replace("\\r", "\r"),
}
def build_forum_runtime(
*,
process_registry: ProcessRuntimeRegistry | None = None,
) -> ForumRuntime:
"""Build a forum runtime bound to the provided process registry."""
return ForumRuntime(process_registry=process_registry)
__all__ = [
"ForumRuntime",
"build_forum_runtime",
"parse_forum_log_line",
]