codecraftai-integration-runtime 1.3.0__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.
- ccai/integrationruntime/__init__.py +27 -0
- ccai/integrationruntime/entrypoints.py +59 -0
- ccai/integrationruntime/initialize.py +100 -0
- ccai/integrationruntime/integratedtestjob.py +100 -0
- ccai/integrationruntime/integrationruntimedefaulttypefactory.py +51 -0
- ccai/integrationruntime/py.typed +0 -0
- ccai/integrationruntime/results/__init__.py +13 -0
- ccai/integrationruntime/results/concentrators/__init__.py +13 -0
- ccai/integrationruntime/results/concentrators/progressconcentratorservice.py +526 -0
- ccai/integrationruntime/results/recorders/__init__.py +22 -0
- ccai/integrationruntime/results/recorders/integrationjsonresultrecorder.py +126 -0
- ccai/integrationruntime/results/recorders/streamingresultrecorder.py +271 -0
- ccai/integrationruntime/results/streaming/__init__.py +25 -0
- ccai/integrationruntime/results/streaming/resultstreamer.py +581 -0
- ccai/integrationruntime/runtimeoutputcontext.py +68 -0
- ccai/integrationruntime/runtimerunmetadata.py +165 -0
- ccai/integrationruntime/templates/v2/static/images/test-report-banner-background-image.png +0 -0
- ccai/integrationruntime/templates/v2/static/javascript/d3.v7.js +20625 -0
- ccai/integrationruntime/templates/v2/static/javascript/icon-components.js +510 -0
- ccai/integrationruntime/templates/v2/static/javascript/mojo-components.js +1417 -0
- ccai/integrationruntime/templates/v2/static/javascript/prism.js +1789 -0
- ccai/integrationruntime/templates/v2/static/javascript/testsummary-accessibility.js +704 -0
- ccai/integrationruntime/templates/v2/static/javascript/testsummary-comparison.js +1287 -0
- ccai/integrationruntime/templates/v2/static/javascript/testsummary-components.js +3499 -0
- ccai/integrationruntime/templates/v2/static/javascript/testsummary-helpers.js +426 -0
- ccai/integrationruntime/templates/v2/static/javascript/testsummary-responsive.js +493 -0
- ccai/integrationruntime/templates/v2/static/javascript/testsummary.js +1128 -0
- ccai/integrationruntime/templates/v2/static/javascript/webcomponent-helpers.js +112 -0
- ccai/integrationruntime/templates/v2/static/styles/branding-theme.css +144 -0
- ccai/integrationruntime/templates/v2/static/styles/icon-styles.css +9 -0
- ccai/integrationruntime/templates/v2/static/styles/mojo-components.css +384 -0
- ccai/integrationruntime/templates/v2/static/styles/prism.css +143 -0
- ccai/integrationruntime/templates/v2/static/styles/tabs-responsive.css +186 -0
- ccai/integrationruntime/templates/v2/static/styles/testsummary-accessibility.css +413 -0
- ccai/integrationruntime/templates/v2/static/styles/testsummary-comparison.css +746 -0
- ccai/integrationruntime/templates/v2/static/styles/testsummary-responsive.css +679 -0
- ccai/integrationruntime/templates/v2/static/styles/testsummary.css +1631 -0
- ccai/integrationruntime/templates/v2/tabs/tab-data.html +870 -0
- ccai/integrationruntime/templates/v2/tabs/tab-images.html +110 -0
- ccai/integrationruntime/templates/v2/tabs/tab-logs.html +594 -0
- ccai/integrationruntime/templates/v2/tabs/tab-sounds.html +112 -0
- ccai/integrationruntime/templates/v2/tabs/tab-timeseries.html +368 -0
- ccai/integrationruntime/templates/v2/tabs/tab-videos.html +372 -0
- ccai/integrationruntime/templates/v2/testsummary.html +81 -0
- codecraftai_integration_runtime-1.3.0.dist-info/METADATA +73 -0
- codecraftai_integration_runtime-1.3.0.dist-info/RECORD +48 -0
- codecraftai_integration_runtime-1.3.0.dist-info/WHEEL +4 -0
- codecraftai_integration_runtime-1.3.0.dist-info/licenses/LICENSE.md +204 -0
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: ccai.integrationruntime.results.concentrators.progressconcentratorservice
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Module for progressconcentratorservice.
|
|
5
|
+
|
|
6
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
__author__ = "Myron Walker"
|
|
12
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
13
|
+
__credits__ = []
|
|
14
|
+
|
|
15
|
+
from typing import Any, Optional, Tuple
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import requests
|
|
19
|
+
import os
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
import traceback
|
|
23
|
+
|
|
24
|
+
from datetime import datetime
|
|
25
|
+
from socketserver import ThreadingMixIn
|
|
26
|
+
from http.server import HTTPServer, SimpleHTTPRequestHandler
|
|
27
|
+
|
|
28
|
+
# Type alias for server address - compatible with all Python versions
|
|
29
|
+
ServerAddress = Tuple[str, int]
|
|
30
|
+
|
|
31
|
+
# Bound the summary-forwarding POST so an unresponsive monitoring endpoint cannot
|
|
32
|
+
# wedge the forwarder daemon thread indefinitely.
|
|
33
|
+
FORWARDING_POST_TIMEOUT_SECONDS = 30
|
|
34
|
+
|
|
35
|
+
from ccai.xmodules.xlogging.enhancedloggers import getEnhancedLogger
|
|
36
|
+
|
|
37
|
+
from ccai.testbase.results.model.forwardinginfo import ForwardingInfo
|
|
38
|
+
from ccai.testbase.results.model.progressinfo import ProgressInfo
|
|
39
|
+
from ccai.testbase.results.recorders.resultrecorder import ResultRecorder
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SummaryJsonEncoder(json.JSONEncoder):
|
|
43
|
+
"""
|
|
44
|
+
A custom JSON encoder that extends :class:`json.JSONEncoder` to handle datetime
|
|
45
|
+
serialization for summary forwarding operations.
|
|
46
|
+
|
|
47
|
+
This encoder converts datetime objects to ISO 8601 formatted strings, enabling
|
|
48
|
+
proper JSON serialization of summary data that contains timestamp fields.
|
|
49
|
+
|
|
50
|
+
The encoder is used internally by the :class:`ProgressConcentratorServer` when
|
|
51
|
+
forwarding aggregated summaries to external monitoring services.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def default(self, obj) -> Any:
|
|
55
|
+
"""
|
|
56
|
+
Converts non-serializable objects to JSON-compatible representations.
|
|
57
|
+
|
|
58
|
+
This method overrides the base :class:`json.JSONEncoder.default` method to
|
|
59
|
+
provide custom serialization for datetime objects. All other object types
|
|
60
|
+
are delegated to the parent class implementation.
|
|
61
|
+
|
|
62
|
+
:param obj: The object to serialize to a JSON-compatible format.
|
|
63
|
+
|
|
64
|
+
:returns: An ISO 8601 formatted string if obj is a datetime, otherwise
|
|
65
|
+
delegates to the parent class default method.
|
|
66
|
+
|
|
67
|
+
:raises: TypeError if the object is not serializable and the parent
|
|
68
|
+
class cannot handle it.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
cval = None
|
|
72
|
+
|
|
73
|
+
if isinstance(obj, datetime):
|
|
74
|
+
cval = obj.isoformat()
|
|
75
|
+
else:
|
|
76
|
+
cval = json.JSONEncoder.default(self, obj)
|
|
77
|
+
|
|
78
|
+
return cval
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ProgressCallbackHandler(SimpleHTTPRequestHandler):
|
|
82
|
+
"""
|
|
83
|
+
An HTTP request handler that processes incoming POST requests containing progress
|
|
84
|
+
information from remote test workers.
|
|
85
|
+
|
|
86
|
+
The :class:`ProgressCallbackHandler` inherits from :class:`SimpleHTTPRequestHandler`
|
|
87
|
+
and implements the do_POST method to receive JSON-encoded progress updates. Each
|
|
88
|
+
progress update is deserialized into a :class:`ProgressInfo` object and forwarded
|
|
89
|
+
to the parent :class:`ProgressConcentratorServer` for aggregation.
|
|
90
|
+
|
|
91
|
+
This handler is designed to be used with the :class:`ProgressConcentratorServer`
|
|
92
|
+
which provides concurrent request handling through the :class:`ThreadingMixIn`.
|
|
93
|
+
Multiple workers can submit progress updates simultaneously, with each request
|
|
94
|
+
being processed in a separate thread.
|
|
95
|
+
|
|
96
|
+
Response Codes:
|
|
97
|
+
- 200 OK: Progress update was successfully processed or no content was provided
|
|
98
|
+
- 500 Internal Server Error: An exception occurred during processing
|
|
99
|
+
|
|
100
|
+
Expected JSON Payload Format::
|
|
101
|
+
|
|
102
|
+
{
|
|
103
|
+
"id": "task-uuid-123",
|
|
104
|
+
"category": "test-execution",
|
|
105
|
+
"moniker": "test_module.test_function",
|
|
106
|
+
"ptype": "Sequential",
|
|
107
|
+
"range_min": "0",
|
|
108
|
+
"range_max": "10",
|
|
109
|
+
"position": "5",
|
|
110
|
+
"status": "Running",
|
|
111
|
+
"when": "2025-02-20T10:30:00.000000",
|
|
112
|
+
"data": {...}
|
|
113
|
+
}
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def do_POST(self):
|
|
117
|
+
"""
|
|
118
|
+
Handles incoming HTTP POST requests containing progress update data.
|
|
119
|
+
|
|
120
|
+
This method reads the request body when a content-length header is present,
|
|
121
|
+
parses the JSON payload, creates a :class:`ProgressInfo` object from the
|
|
122
|
+
data, and delegates the progress update to the server's update_task_progress
|
|
123
|
+
method.
|
|
124
|
+
|
|
125
|
+
The method implements robust error handling to ensure the server remains
|
|
126
|
+
stable even when receiving malformed requests. All exceptions during
|
|
127
|
+
processing are caught and returned as 500 error responses with detailed
|
|
128
|
+
traceback information.
|
|
129
|
+
|
|
130
|
+
Response Behavior:
|
|
131
|
+
- If content-length is missing: Returns 200 OK without processing
|
|
132
|
+
- If JSON parsing succeeds: Returns 200 OK after updating progress
|
|
133
|
+
- If any exception occurs: Returns 500 with error message and traceback
|
|
134
|
+
|
|
135
|
+
:returns: None. Response is sent directly to the client via inherited methods.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
# ERROR HANDLING PATTERN:
|
|
139
|
+
# We use a sentinel variable (errmsg) to track error state throughout processing.
|
|
140
|
+
# This allows us to attempt all processing steps and collect error information
|
|
141
|
+
# before deciding on the response code. If errmsg remains None, processing succeeded.
|
|
142
|
+
errmsg = None
|
|
143
|
+
|
|
144
|
+
# Only process requests that have a content-length header.
|
|
145
|
+
# Requests without content-length are treated as no-ops and return 200 OK.
|
|
146
|
+
# This handles edge cases like health checks or empty POST requests gracefully.
|
|
147
|
+
if 'content-length' in self.headers:
|
|
148
|
+
|
|
149
|
+
content_length = self.headers["content-length"]
|
|
150
|
+
length = int(content_length) if content_length else 0
|
|
151
|
+
|
|
152
|
+
if length:
|
|
153
|
+
# ERROR HANDLING: Wrap all processing in try/except to ensure server stability.
|
|
154
|
+
# Any exception during JSON parsing, ProgressInfo creation, or progress update
|
|
155
|
+
# is caught and converted to a 500 error response with full traceback.
|
|
156
|
+
# This prevents malformed requests from crashing the server thread.
|
|
157
|
+
try:
|
|
158
|
+
# Step 1: Read raw bytes from request body
|
|
159
|
+
content = self.rfile.read(length)
|
|
160
|
+
|
|
161
|
+
# Step 2: Parse JSON - may raise json.JSONDecodeError for malformed JSON
|
|
162
|
+
data = json.loads(content)
|
|
163
|
+
|
|
164
|
+
# Step 3: Deserialize to ProgressInfo - may raise if required fields missing
|
|
165
|
+
progress = ProgressInfo.from_dict(data)
|
|
166
|
+
|
|
167
|
+
# Step 4: Delegate to server for thread-safe aggregation
|
|
168
|
+
# The server's update_task_progress method handles concurrent access
|
|
169
|
+
server: ProgressConcentratorServer = self.server
|
|
170
|
+
server.update_task_progress(progress)
|
|
171
|
+
|
|
172
|
+
except Exception as perr:
|
|
173
|
+
# ERROR HANDLING: Capture full exception context for debugging.
|
|
174
|
+
# Include a human-readable prefix and the complete traceback
|
|
175
|
+
# to help diagnose issues with malformed progress payloads.
|
|
176
|
+
errmsg_msg_lines = [
|
|
177
|
+
"Error processing progress postback.",
|
|
178
|
+
"EXCEPTION:",
|
|
179
|
+
traceback.format_exc()
|
|
180
|
+
]
|
|
181
|
+
errmsg = os.linesep.join(errmsg_msg_lines)
|
|
182
|
+
|
|
183
|
+
# RESPONSE HANDLING: Send appropriate HTTP response based on processing outcome.
|
|
184
|
+
# Success (errmsg is None) returns 200 OK; failure returns 500 with error details.
|
|
185
|
+
if not errmsg:
|
|
186
|
+
self.send_response(200, message=None)
|
|
187
|
+
self.send_header("Content-Type", "text/html")
|
|
188
|
+
self.end_headers()
|
|
189
|
+
else:
|
|
190
|
+
# Include error message in 500 response for client-side debugging.
|
|
191
|
+
# Only use the first line of the error message to avoid HTTP header injection
|
|
192
|
+
# Make sure it only contains latin-1 characters or encode it safely
|
|
193
|
+
safe_msg = errmsg_msg_lines[0].encode('latin-1', 'replace').decode('latin-1')
|
|
194
|
+
self.send_response(500, message=safe_msg)
|
|
195
|
+
self.send_header("Content-Type", "text/plain")
|
|
196
|
+
|
|
197
|
+
# Send the full error message in the response body
|
|
198
|
+
body_bytes = errmsg.encode('utf-8')
|
|
199
|
+
self.send_header("Content-Length", str(len(body_bytes)))
|
|
200
|
+
self.end_headers()
|
|
201
|
+
self.wfile.write(body_bytes)
|
|
202
|
+
|
|
203
|
+
return
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class ProgressConcentratorServer(ThreadingMixIn, HTTPServer):
|
|
207
|
+
"""
|
|
208
|
+
A threaded HTTP server that receives progress callbacks from remote test workers
|
|
209
|
+
and aggregates them into a central :class:`ResultRecorder`.
|
|
210
|
+
|
|
211
|
+
The :class:`ProgressConcentratorServer` combines :class:`ThreadingMixIn` with
|
|
212
|
+
:class:`HTTPServer` to provide concurrent request handling capabilities. This
|
|
213
|
+
allows multiple remote workers to submit progress updates simultaneously without
|
|
214
|
+
blocking each other.
|
|
215
|
+
|
|
216
|
+
The server provides two main functions:
|
|
217
|
+
|
|
218
|
+
1. **Progress Collection**: Accepts HTTP POST requests containing JSON-encoded
|
|
219
|
+
progress updates from remote workers and routes them to the ResultRecorder
|
|
220
|
+
for aggregation.
|
|
221
|
+
|
|
222
|
+
2. **Summary Forwarding**: Optionally runs a background thread that periodically
|
|
223
|
+
retrieves the aggregated summary from the ResultRecorder and forwards it to
|
|
224
|
+
external monitoring services via HTTP POST.
|
|
225
|
+
|
|
226
|
+
Thread Architecture:
|
|
227
|
+
- Server Thread ('prog-concentrator'): Daemon thread running serve_forever()
|
|
228
|
+
to accept incoming connections
|
|
229
|
+
- Forwarding Thread ('prog-forwarder'): Optional daemon thread that periodically
|
|
230
|
+
forwards summaries to external services
|
|
231
|
+
- Request Threads: Spawned by ThreadingMixIn for each incoming request
|
|
232
|
+
|
|
233
|
+
The server uses gate events for thread synchronization to ensure the start()
|
|
234
|
+
method does not return until all threads are ready to process requests.
|
|
235
|
+
|
|
236
|
+
Example Usage::
|
|
237
|
+
|
|
238
|
+
from ccai.testbase.results.model.forwardinginfo import ForwardingInfo
|
|
239
|
+
from ccai.testbase.results.concentrators.progressconcentratorservice import (
|
|
240
|
+
ProgressConcentratorServer
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
# Configure forwarding (optional)
|
|
244
|
+
forwarding_info = ForwardingInfo(
|
|
245
|
+
forwarding_interval=5.0,
|
|
246
|
+
forwarding_url="https://monitoring.example.com/api/progress",
|
|
247
|
+
forwarding_headers={"Authorization": "Bearer token123"}
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
# Create and start concentrator
|
|
251
|
+
server = ProgressConcentratorServer(
|
|
252
|
+
recorder=result_recorder,
|
|
253
|
+
server_address=("0.0.0.0", 8080),
|
|
254
|
+
forwarding_info=forwarding_info
|
|
255
|
+
)
|
|
256
|
+
server.start()
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
# Increase the listen backlog to handle high concurrency and prevent 'Connection reset by peer'
|
|
260
|
+
request_queue_size = 128
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def __init__(self, recorder: ResultRecorder, server_address: ServerAddress, forwarding_info: Optional[ForwardingInfo] = None,
|
|
264
|
+
bind_and_activate: bool = True) -> None:
|
|
265
|
+
"""
|
|
266
|
+
Initializes a new ProgressConcentratorServer instance.
|
|
267
|
+
|
|
268
|
+
:param recorder: The :class:`ResultRecorder` instance to aggregate progress into.
|
|
269
|
+
All progress updates received by this server will be forwarded
|
|
270
|
+
to this recorder's post_task_progress method.
|
|
271
|
+
:param server_address: A tuple of (host, port) specifying the address to bind to.
|
|
272
|
+
Use "0.0.0.0" to listen on all interfaces or "127.0.0.1"
|
|
273
|
+
for loopback only.
|
|
274
|
+
:param forwarding_info: Optional :class:`ForwardingInfo` configuration for periodic
|
|
275
|
+
summary forwarding. If provided, a forwarding thread will
|
|
276
|
+
be started when start() is called.
|
|
277
|
+
:param bind_and_activate: If True (default), the server will bind to the address
|
|
278
|
+
and activate immediately upon construction.
|
|
279
|
+
|
|
280
|
+
:returns: None
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
self._recorder = recorder
|
|
284
|
+
self._forwarding_info = forwarding_info
|
|
285
|
+
|
|
286
|
+
super().__init__(server_address, ProgressCallbackHandler, bind_and_activate)
|
|
287
|
+
|
|
288
|
+
self._forward_thread = None
|
|
289
|
+
self._forwarding_running = False
|
|
290
|
+
|
|
291
|
+
self._server_thread = None
|
|
292
|
+
self._server_running = False
|
|
293
|
+
|
|
294
|
+
self._logger = getEnhancedLogger()
|
|
295
|
+
|
|
296
|
+
return
|
|
297
|
+
|
|
298
|
+
def start(self):
|
|
299
|
+
"""
|
|
300
|
+
Starts the server and optional forwarding threads.
|
|
301
|
+
|
|
302
|
+
This method initiates the server's request handling thread and, if forwarding
|
|
303
|
+
configuration was provided, also starts the summary forwarding thread. The
|
|
304
|
+
method uses gate events to synchronize thread startup and does not return
|
|
305
|
+
until all threads signal readiness.
|
|
306
|
+
|
|
307
|
+
Thread Startup Order:
|
|
308
|
+
1. If forwarding_info is configured, start the forwarding thread first
|
|
309
|
+
and wait for it to signal readiness via its gate event
|
|
310
|
+
2. Start the server thread and wait for it to signal readiness
|
|
311
|
+
3. Return to caller once all threads are running
|
|
312
|
+
|
|
313
|
+
Both threads are created as daemon threads, meaning they will be automatically
|
|
314
|
+
terminated when the main process exits.
|
|
315
|
+
|
|
316
|
+
:returns: None
|
|
317
|
+
"""
|
|
318
|
+
|
|
319
|
+
# THREAD SYNCHRONIZATION - GATE PATTERN:
|
|
320
|
+
# We use threading.Event objects as "gates" to synchronize thread startup.
|
|
321
|
+
# The pattern ensures the start() method does not return until child threads
|
|
322
|
+
# are fully initialized and ready to process work. This prevents race conditions
|
|
323
|
+
# where callers might try to use the server before it's ready.
|
|
324
|
+
#
|
|
325
|
+
# Gate Pattern Flow:
|
|
326
|
+
# 1. Create Event and clear it (gate is "closed")
|
|
327
|
+
# 2. Pass gate to child thread
|
|
328
|
+
# 3. Child thread performs initialization
|
|
329
|
+
# 4. Child thread calls gate.set() to "open" the gate
|
|
330
|
+
# 5. Parent thread's gate.wait() returns, confirming child is ready
|
|
331
|
+
|
|
332
|
+
# Start forwarding thread first if forwarding is configured.
|
|
333
|
+
# This ensures summary forwarding is operational before we start accepting
|
|
334
|
+
# progress updates from workers.
|
|
335
|
+
if self._forwarding_info is not None:
|
|
336
|
+
# Create gate event for forwarding thread synchronization
|
|
337
|
+
fwd_gate = threading.Event()
|
|
338
|
+
fwd_gate.clear() # Ensure gate starts in "closed" state
|
|
339
|
+
|
|
340
|
+
# Create forwarding thread as daemon so it auto-terminates on process exit.
|
|
341
|
+
# Thread name 'prog-forwarder' aids in debugging and thread identification.
|
|
342
|
+
self._forward_thread = threading.Thread(target=self._forwarding_thread_entry, name='prog-forwarder', args=(fwd_gate,), daemon=True)
|
|
343
|
+
self._forward_thread.start()
|
|
344
|
+
|
|
345
|
+
# SYNCHRONIZATION POINT: Block until forwarding thread signals ready.
|
|
346
|
+
# This ensures the forwarding loop is running before we proceed.
|
|
347
|
+
fwd_gate.wait()
|
|
348
|
+
|
|
349
|
+
# Create gate event for server thread synchronization
|
|
350
|
+
svr_gate = threading.Event()
|
|
351
|
+
svr_gate.clear() # Ensure gate starts in "closed" state
|
|
352
|
+
|
|
353
|
+
# Set running flag before starting thread to indicate intent to run
|
|
354
|
+
self._server_running = True
|
|
355
|
+
|
|
356
|
+
# Create server thread as daemon so it auto-terminates on process exit.
|
|
357
|
+
# Thread name 'prog-concentrator' aids in debugging and thread identification.
|
|
358
|
+
self._server_thread = threading.Thread(target=self._service_thread_entry, name='prog-concentrator', args=(svr_gate,), daemon=True)
|
|
359
|
+
self._server_thread.start()
|
|
360
|
+
|
|
361
|
+
# SYNCHRONIZATION POINT: Block until server thread signals ready.
|
|
362
|
+
# This ensures serve_forever() is running and accepting connections
|
|
363
|
+
# before we return to the caller.
|
|
364
|
+
svr_gate.wait()
|
|
365
|
+
|
|
366
|
+
return
|
|
367
|
+
|
|
368
|
+
def _forwarding_thread_entry(self, start_gate: threading.Event):
|
|
369
|
+
"""
|
|
370
|
+
Entry point for the summary forwarding thread.
|
|
371
|
+
|
|
372
|
+
This method runs the forwarding loop that periodically retrieves the summary
|
|
373
|
+
from the recorder and POSTs it to the configured forwarding URL. The loop
|
|
374
|
+
continues while _forwarding_running is True.
|
|
375
|
+
|
|
376
|
+
The method handles exceptions gracefully to ensure the forwarding thread
|
|
377
|
+
continues operating even when network errors or HTTP failures occur. All
|
|
378
|
+
exceptions are logged but do not terminate the thread.
|
|
379
|
+
|
|
380
|
+
:param start_gate: A :class:`threading.Event` used to signal to the caller
|
|
381
|
+
that the forwarding thread has started and is ready.
|
|
382
|
+
|
|
383
|
+
:returns: None
|
|
384
|
+
"""
|
|
385
|
+
|
|
386
|
+
# FORWARDING LOOP INITIALIZATION:
|
|
387
|
+
# Set the running flag to True to enable the forwarding loop.
|
|
388
|
+
# This flag can be set to False externally to gracefully stop forwarding.
|
|
389
|
+
self._forwarding_running = True
|
|
390
|
+
|
|
391
|
+
# HEADER CONFIGURATION:
|
|
392
|
+
# Build the HTTP headers for forwarding requests. Start with the required
|
|
393
|
+
# Content-Type header for JSON payloads, then merge any custom headers
|
|
394
|
+
# provided in the forwarding configuration (e.g., Authorization tokens).
|
|
395
|
+
headers = {
|
|
396
|
+
"Content-Type": "application/json"
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
# Extract forwarding configuration for use in the loop.
|
|
400
|
+
# These values are read once at startup for efficiency.
|
|
401
|
+
forwarding_interval = self._forwarding_info.forwarding_interval
|
|
402
|
+
forwarding_url = self._forwarding_info.forwarding_url
|
|
403
|
+
forwarding_headers = self._forwarding_info.forwarding_headers
|
|
404
|
+
|
|
405
|
+
# Merge custom headers if provided. This allows callers to add
|
|
406
|
+
# authentication headers, correlation IDs, or other custom headers.
|
|
407
|
+
if forwarding_headers is not None:
|
|
408
|
+
headers.update(forwarding_headers)
|
|
409
|
+
|
|
410
|
+
# GATE PATTERN - SIGNAL READY:
|
|
411
|
+
# Signal to the parent thread (start() method) that initialization is complete
|
|
412
|
+
# and the forwarding loop is about to begin. This allows start() to return
|
|
413
|
+
# knowing that forwarding is operational.
|
|
414
|
+
start_gate.set()
|
|
415
|
+
|
|
416
|
+
# FORWARDING LOOP:
|
|
417
|
+
# Continuously forward summaries to the external service at the configured interval.
|
|
418
|
+
# The loop runs until _forwarding_running is set to False (e.g., during shutdown).
|
|
419
|
+
while self._forwarding_running:
|
|
420
|
+
|
|
421
|
+
# ERROR HANDLING - RESILIENT LOOP:
|
|
422
|
+
# Wrap the entire loop iteration in try/except to ensure the forwarding
|
|
423
|
+
# thread never terminates due to transient errors. Network failures,
|
|
424
|
+
# HTTP errors, or serialization issues are logged but don't stop forwarding.
|
|
425
|
+
# This is critical for maintaining monitoring connectivity during test runs.
|
|
426
|
+
try:
|
|
427
|
+
# THREAD-SAFE SUMMARY ACCESS:
|
|
428
|
+
# Retrieve a deep copy of the current summary from the recorder.
|
|
429
|
+
# The recorder's summary property uses locking to ensure we get
|
|
430
|
+
# a consistent snapshot even while other threads update progress.
|
|
431
|
+
summary = self._recorder.summary
|
|
432
|
+
|
|
433
|
+
# SERIALIZATION AND FORWARDING:
|
|
434
|
+
# Serialize the summary to JSON using our custom encoder that handles
|
|
435
|
+
# datetime objects, then POST to the configured monitoring endpoint.
|
|
436
|
+
summary_json = json.dumps(summary, cls=SummaryJsonEncoder)
|
|
437
|
+
requests.post(forwarding_url, data=summary_json, headers=headers, timeout=FORWARDING_POST_TIMEOUT_SECONDS)
|
|
438
|
+
|
|
439
|
+
except (requests.exceptions.ConnectionError, requests.exceptions.RetryError) as err:
|
|
440
|
+
# ERROR HANDLING - LOG AND CONTINUE:
|
|
441
|
+
# Log connection errors as warnings without full tracebacks to avoid spamming
|
|
442
|
+
# the console, particularly during integration tests that simulate failures.
|
|
443
|
+
self._logger.warning(f"Connection error while forwarding progress: {err}")
|
|
444
|
+
|
|
445
|
+
except Exception:
|
|
446
|
+
# ERROR HANDLING - LOG AND CONTINUE:
|
|
447
|
+
# Log the full exception traceback for debugging other types of errors, but don't re-raise.
|
|
448
|
+
# The loop continues to the next iteration, ensuring forwarding
|
|
449
|
+
# resumes after transient failures (network issues, service outages, etc.).
|
|
450
|
+
errmsg = traceback.format_exc()
|
|
451
|
+
self._logger.error(errmsg)
|
|
452
|
+
|
|
453
|
+
finally:
|
|
454
|
+
# INTERVAL SLEEP:
|
|
455
|
+
# Wait for the configured interval before the next forward.
|
|
456
|
+
# This controls the frequency of summary updates to external services.
|
|
457
|
+
if self._forwarding_running:
|
|
458
|
+
time.sleep(forwarding_interval)
|
|
459
|
+
|
|
460
|
+
return
|
|
461
|
+
|
|
462
|
+
def _service_thread_entry(self, start_gate: threading.Event):
|
|
463
|
+
"""
|
|
464
|
+
Entry point for the HTTP server thread.
|
|
465
|
+
|
|
466
|
+
This method sets the server_running flag, signals readiness via the gate
|
|
467
|
+
event, and then enters the serve_forever loop to accept and handle incoming
|
|
468
|
+
HTTP connections.
|
|
469
|
+
|
|
470
|
+
:param start_gate: A :class:`threading.Event` used to signal to the caller
|
|
471
|
+
that the server thread has started and is ready to accept
|
|
472
|
+
connections.
|
|
473
|
+
|
|
474
|
+
:returns: None
|
|
475
|
+
"""
|
|
476
|
+
|
|
477
|
+
# SERVER THREAD INITIALIZATION:
|
|
478
|
+
# Set the running flag to indicate the server is operational.
|
|
479
|
+
# This flag can be checked by other components to verify server status.
|
|
480
|
+
self._server_running = True
|
|
481
|
+
|
|
482
|
+
# GATE PATTERN - SIGNAL READY:
|
|
483
|
+
# Signal to the parent thread (start() method) that the server thread
|
|
484
|
+
# has initialized and is about to enter serve_forever(). This allows
|
|
485
|
+
# start() to return knowing the server is ready to accept connections.
|
|
486
|
+
# Note: We signal BEFORE serve_forever() because serve_forever() blocks.
|
|
487
|
+
start_gate.set()
|
|
488
|
+
|
|
489
|
+
# HTTP SERVER LOOP:
|
|
490
|
+
# Enter the blocking serve_forever() loop provided by HTTPServer.
|
|
491
|
+
# This method handles incoming connections and spawns handler threads
|
|
492
|
+
# (via ThreadingMixIn) for each request. The loop runs until
|
|
493
|
+
# shutdown() is called on the server.
|
|
494
|
+
self.serve_forever()
|
|
495
|
+
|
|
496
|
+
return
|
|
497
|
+
|
|
498
|
+
def update_task_progress(self, progress: ProgressInfo):
|
|
499
|
+
"""
|
|
500
|
+
Updates the task progress in the associated ResultRecorder.
|
|
501
|
+
|
|
502
|
+
This method is called by :class:`ProgressCallbackHandler` instances when
|
|
503
|
+
they receive valid progress updates from remote workers. The method
|
|
504
|
+
delegates to the recorder's post_task_progress method, which handles
|
|
505
|
+
thread-safe updates to the running tasks dictionary.
|
|
506
|
+
|
|
507
|
+
This method is thread-safe and can be called concurrently from multiple
|
|
508
|
+
request handler threads.
|
|
509
|
+
|
|
510
|
+
:param progress: A :class:`ProgressInfo` object containing the progress
|
|
511
|
+
update data received from a remote worker.
|
|
512
|
+
|
|
513
|
+
:returns: None
|
|
514
|
+
"""
|
|
515
|
+
# THREAD-SAFE DELEGATION:
|
|
516
|
+
# Delegate to the recorder's post_task_progress method, which uses
|
|
517
|
+
# internal locking to ensure thread-safe updates to the running_tasks
|
|
518
|
+
# dictionary. Multiple request handler threads can call this method
|
|
519
|
+
# concurrently without data corruption.
|
|
520
|
+
#
|
|
521
|
+
# The progress is wrapped in a list because post_task_progress accepts
|
|
522
|
+
# a list of ProgressInfo objects for batch processing efficiency.
|
|
523
|
+
self._recorder.post_task_progress([progress])
|
|
524
|
+
return
|
|
525
|
+
|
|
526
|
+
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: ccai.integrationruntime.results.recorders
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Integration-tier result recorders relocated from ``codecraftai-testbase``. These extend
|
|
5
|
+
testbase's JSOS/JSON ``JsonResultRecorder`` with streaming and (HTML-summary) rendering
|
|
6
|
+
behaviour that the near-standalone framework deliberately omits.
|
|
7
|
+
|
|
8
|
+
.. moduleauthor:: CodeCraftX
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__author__ = "CodeCraftX"
|
|
12
|
+
__copyright__ = "Copyright 2026, Code Craft AI LLC"
|
|
13
|
+
__credits__ = []
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
from ccai.integrationruntime.results.recorders.integrationjsonresultrecorder import IntegrationJsonResultRecorder
|
|
17
|
+
from ccai.integrationruntime.results.recorders.streamingresultrecorder import StreamingResultRecorder
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"IntegrationJsonResultRecorder",
|
|
21
|
+
"StreamingResultRecorder"
|
|
22
|
+
]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: ccai.integrationruntime.results.recorders.integrationjsonresultrecorder
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: :class:`IntegrationJsonResultRecorder` — extends testbase's JSOS/JSON
|
|
5
|
+
:class:`JsonResultRecorder` with the HTML-summary presentation behaviour relocated out
|
|
6
|
+
of the near-standalone testbase framework in the Phase 3 results split.
|
|
7
|
+
|
|
8
|
+
The near-standalone ``codecraftai-testbase`` :class:`ResultRecorder` base now only generates the
|
|
9
|
+
output-directory catalog; it no longer publishes static render resources or copies the HTML
|
|
10
|
+
summary template. This recorder re-supplies that behaviour for integration runs by overriding
|
|
11
|
+
``update_render_environment`` (static-resource publishing) and ``initialize_report`` (which
|
|
12
|
+
publishes the resources, copies the HTML summary template, then delegates to the base for the
|
|
13
|
+
catalog).
|
|
14
|
+
|
|
15
|
+
.. moduleauthor:: CodeCraftX
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
__author__ = "CodeCraftX"
|
|
19
|
+
__copyright__ = "Copyright 2026, Code Craft AI LLC"
|
|
20
|
+
__credits__ = []
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
import os
|
|
24
|
+
import shutil
|
|
25
|
+
|
|
26
|
+
from ccai.testbase.results.exceptions import ResultRecordingError
|
|
27
|
+
from ccai.testbase.results.recorders.jsonresultrecorder import JsonResultRecorder
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class IntegrationJsonResultRecorder(JsonResultRecorder):
|
|
31
|
+
"""
|
|
32
|
+
A JSOS/JSON result recorder that additionally renders the HTML summary report.
|
|
33
|
+
|
|
34
|
+
This recorder extends :class:`ccai.testbase.results.recorders.jsonresultrecorder.JsonResultRecorder`
|
|
35
|
+
(JSOS/JSON serialization plus the output-directory catalog) with the HTML presentation
|
|
36
|
+
behaviour that the near-standalone testbase framework deliberately omits. It is the recorder
|
|
37
|
+
installed by :class:`ccai.integrationruntime.integratedtestjob.IntegratedTestJob`.
|
|
38
|
+
|
|
39
|
+
It adds no instance state, so the :class:`JsonResultRecorder` constructor is inherited
|
|
40
|
+
unchanged.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def update_render_environment(self) -> None:
|
|
44
|
+
"""
|
|
45
|
+
Publishes the static render resources required by the HTML presentation.
|
|
46
|
+
|
|
47
|
+
Copies the CSS / JavaScript / image resources from
|
|
48
|
+
``render_info.static_resource_source`` into ``render_info.static_resource_destination``.
|
|
49
|
+
Files are copied only when they do not already exist at the destination, so the method is
|
|
50
|
+
safe to call repeatedly (e.g. for shared-resource deployments).
|
|
51
|
+
|
|
52
|
+
:returns: None
|
|
53
|
+
|
|
54
|
+
:raises: ResultRecordingError if a destination directory cannot be created or a resource
|
|
55
|
+
cannot be copied.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
if self._render_info.static_resource_source is not None:
|
|
59
|
+
static_resource_dest_dir = self._render_info.static_resource_destination
|
|
60
|
+
static_resource_src_dir = self._render_info.static_resource_source
|
|
61
|
+
|
|
62
|
+
for nxt_root, _, nxt_files in os.walk(static_resource_src_dir):
|
|
63
|
+
for nf in nxt_files:
|
|
64
|
+
res_src_full = os.path.join(nxt_root, nf)
|
|
65
|
+
res_src_leaf = res_src_full[len(static_resource_src_dir):].lstrip(os.sep)
|
|
66
|
+
res_dest_full = os.path.join(static_resource_dest_dir, res_src_leaf)
|
|
67
|
+
if not os.path.exists(res_dest_full):
|
|
68
|
+
dest_dir = os.path.dirname(res_dest_full)
|
|
69
|
+
if not os.path.exists(dest_dir):
|
|
70
|
+
try:
|
|
71
|
+
os.makedirs(dest_dir)
|
|
72
|
+
except OSError as err:
|
|
73
|
+
errmsg = f"Failed to create directory '{dest_dir}' for static resources."
|
|
74
|
+
raise ResultRecordingError(
|
|
75
|
+
errmsg,
|
|
76
|
+
file_path=dest_dir,
|
|
77
|
+
operation="creating static resource directory",
|
|
78
|
+
original_error=err
|
|
79
|
+
) from err
|
|
80
|
+
try:
|
|
81
|
+
shutil.copy2(res_src_full, res_dest_full)
|
|
82
|
+
except OSError as err:
|
|
83
|
+
errmsg = f"Failed to copy static resource from '{res_src_full}' to '{res_dest_full}'."
|
|
84
|
+
raise ResultRecordingError(
|
|
85
|
+
errmsg,
|
|
86
|
+
file_path=res_dest_full,
|
|
87
|
+
operation="copying static resource",
|
|
88
|
+
original_error=err
|
|
89
|
+
) from err
|
|
90
|
+
|
|
91
|
+
return
|
|
92
|
+
|
|
93
|
+
def initialize_report(self) -> None:
|
|
94
|
+
"""
|
|
95
|
+
Initializes the HTML report output environment, then performs the base catalog step.
|
|
96
|
+
|
|
97
|
+
Publishes the static render resources, copies the HTML summary template into the results
|
|
98
|
+
directory, then delegates to :meth:`JsonResultRecorder.initialize_report` (the base
|
|
99
|
+
output-directory catalog). This preserves the original ordering (static resources, then
|
|
100
|
+
template, then catalog) so the catalog includes the published HTML resources.
|
|
101
|
+
|
|
102
|
+
:returns: None
|
|
103
|
+
|
|
104
|
+
:raises: ResultRecordingError if the summary template cannot be copied.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
self.update_render_environment()
|
|
108
|
+
|
|
109
|
+
summary_html_source = self._render_info.summary_template
|
|
110
|
+
summary_render_html_base = self.get_summary_render_file_basename()
|
|
111
|
+
summary_render_html_dest = os.path.join(self._output_dir, summary_render_html_base)
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
shutil.copy2(summary_html_source, summary_render_html_dest)
|
|
115
|
+
except OSError as err:
|
|
116
|
+
errmsg = f"Failed to copy summary template from '{summary_html_source}' to '{summary_render_html_dest}'."
|
|
117
|
+
raise ResultRecordingError(
|
|
118
|
+
errmsg,
|
|
119
|
+
file_path=summary_render_html_dest,
|
|
120
|
+
operation="copying summary template",
|
|
121
|
+
original_error=err
|
|
122
|
+
) from err
|
|
123
|
+
|
|
124
|
+
super().initialize_report()
|
|
125
|
+
|
|
126
|
+
return
|