|
1
|
"""Callback implementations for pipeline progress reporting.""" |
|
2
|
|
|
3
|
import json |
|
4
|
import logging |
|
5
|
from typing import Optional |
|
6
|
|
|
7
|
logger = logging.getLogger(__name__) |
|
8
|
|
|
9
|
|
|
10
|
class WebhookCallback: |
|
11
|
"""Posts pipeline progress as JSON to a webhook URL.""" |
|
12
|
|
|
13
|
def __init__(self, url: str, timeout: float = 10.0, headers: Optional[dict] = None): |
|
14
|
self.url = url |
|
15
|
self.timeout = timeout |
|
16
|
self.headers = headers or {"Content-Type": "application/json"} |
|
17
|
|
|
18
|
def _post(self, payload: dict) -> None: |
|
19
|
"""POST JSON payload to the webhook URL. Failures are logged, not raised.""" |
|
20
|
try: |
|
21
|
import urllib.request |
|
22
|
|
|
23
|
data = json.dumps(payload).encode("utf-8") |
|
24
|
req = urllib.request.Request(self.url, data=data, headers=self.headers, method="POST") |
|
25
|
urllib.request.urlopen(req, timeout=self.timeout) |
|
26
|
except Exception as e: |
|
27
|
logger.warning(f"Webhook POST failed: {e}") |
|
28
|
|
|
29
|
def on_step_start(self, step: str, index: int, total: int) -> None: |
|
30
|
self._post( |
|
31
|
{ |
|
32
|
"event": "step_start", |
|
33
|
"step": step, |
|
34
|
"index": index, |
|
35
|
"total": total, |
|
36
|
} |
|
37
|
) |
|
38
|
|
|
39
|
def on_step_complete(self, step: str, index: int, total: int) -> None: |
|
40
|
self._post( |
|
41
|
{ |
|
42
|
"event": "step_complete", |
|
43
|
"step": step, |
|
44
|
"index": index, |
|
45
|
"total": total, |
|
46
|
} |
|
47
|
) |
|
48
|
|
|
49
|
def on_progress(self, step: str, percent: float, message: str = "") -> None: |
|
50
|
self._post( |
|
51
|
{ |
|
52
|
"event": "progress", |
|
53
|
"step": step, |
|
54
|
"percent": percent, |
|
55
|
"message": message, |
|
56
|
} |
|
57
|
) |
|
58
|
|