hadoku-execlog 0.1.0__tar.gz
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.
- hadoku_execlog-0.1.0/PKG-INFO +58 -0
- hadoku_execlog-0.1.0/README.md +35 -0
- hadoku_execlog-0.1.0/execlog/__init__.py +37 -0
- hadoku_execlog-0.1.0/execlog/reporter.py +188 -0
- hadoku_execlog-0.1.0/hadoku_execlog.egg-info/PKG-INFO +58 -0
- hadoku_execlog-0.1.0/hadoku_execlog.egg-info/SOURCES.txt +10 -0
- hadoku_execlog-0.1.0/hadoku_execlog.egg-info/dependency_links.txt +1 -0
- hadoku_execlog-0.1.0/hadoku_execlog.egg-info/requires.txt +3 -0
- hadoku_execlog-0.1.0/hadoku_execlog.egg-info/top_level.txt +1 -0
- hadoku_execlog-0.1.0/setup.cfg +4 -0
- hadoku_execlog-0.1.0/setup.py +27 -0
- hadoku_execlog-0.1.0/tests/test_reporter.py +140 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hadoku-execlog
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Execution-log reporter — self-report scheduled-job runs to hadoku monitoring-api (unified contract).
|
|
5
|
+
Home-page: https://github.com/WolffM/hadoku_site
|
|
6
|
+
Author: WolffM
|
|
7
|
+
License: ISC
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: ISC License (ISCL)
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
14
|
+
Dynamic: author
|
|
15
|
+
Dynamic: classifier
|
|
16
|
+
Dynamic: description
|
|
17
|
+
Dynamic: description-content-type
|
|
18
|
+
Dynamic: home-page
|
|
19
|
+
Dynamic: license
|
|
20
|
+
Dynamic: provides-extra
|
|
21
|
+
Dynamic: requires-python
|
|
22
|
+
Dynamic: summary
|
|
23
|
+
|
|
24
|
+
# hadoku-execlog
|
|
25
|
+
|
|
26
|
+
The Python execution-log reporter — the twin of `@wolffm/logger/jobs`. One client
|
|
27
|
+
that posts the unified execution-log contract to monitoring-api's
|
|
28
|
+
`POST /health/api/jobs`, so every scheduled job (Python or TypeScript) self-reports
|
|
29
|
+
a single truthful run record.
|
|
30
|
+
|
|
31
|
+
Part of the execution-log unification —
|
|
32
|
+
`docs/planning/execution-log-unification-2026-07-21.md` in hadoku_site.
|
|
33
|
+
|
|
34
|
+
- **Zero runtime dependencies** (stdlib `urllib` only) — a run-and-exit systemd job
|
|
35
|
+
can adopt it without pulling a dependency tree.
|
|
36
|
+
- **Fail-soft** — a monitoring outage never poisons the job. The exception is
|
|
37
|
+
`tracked()`, where the wrapped work's own error always propagates.
|
|
38
|
+
- **Unified 5-state vocabulary**: `started` / `succeeded` / `failed` / `killed` / `skipped`.
|
|
39
|
+
|
|
40
|
+
## Use
|
|
41
|
+
|
|
42
|
+
Run-and-exit job (the common case for dataplatform / writeOutPrompts):
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from execlog import create_job_reporter
|
|
46
|
+
|
|
47
|
+
reporter = create_job_reporter(url="https://hadoku.me/health/api/jobs", user_key=SERVICE_KEY)
|
|
48
|
+
with reporter.tracked("dataplatform:daily-pipeline"):
|
|
49
|
+
run_daily_pipeline() # raises on failure -> recorded `failed`; else `succeeded`
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Manual start/finish (e.g. a fire-and-forget job that mints its run_id for a 202 body):
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
run_id = reporter.start("scraper:oss-recon") # posts a `started` row
|
|
56
|
+
... # background work
|
|
57
|
+
reporter.finish(run_id, "scraper:oss-recon", "succeeded", duration_ms=elapsed_ms)
|
|
58
|
+
```
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# hadoku-execlog
|
|
2
|
+
|
|
3
|
+
The Python execution-log reporter — the twin of `@wolffm/logger/jobs`. One client
|
|
4
|
+
that posts the unified execution-log contract to monitoring-api's
|
|
5
|
+
`POST /health/api/jobs`, so every scheduled job (Python or TypeScript) self-reports
|
|
6
|
+
a single truthful run record.
|
|
7
|
+
|
|
8
|
+
Part of the execution-log unification —
|
|
9
|
+
`docs/planning/execution-log-unification-2026-07-21.md` in hadoku_site.
|
|
10
|
+
|
|
11
|
+
- **Zero runtime dependencies** (stdlib `urllib` only) — a run-and-exit systemd job
|
|
12
|
+
can adopt it without pulling a dependency tree.
|
|
13
|
+
- **Fail-soft** — a monitoring outage never poisons the job. The exception is
|
|
14
|
+
`tracked()`, where the wrapped work's own error always propagates.
|
|
15
|
+
- **Unified 5-state vocabulary**: `started` / `succeeded` / `failed` / `killed` / `skipped`.
|
|
16
|
+
|
|
17
|
+
## Use
|
|
18
|
+
|
|
19
|
+
Run-and-exit job (the common case for dataplatform / writeOutPrompts):
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from execlog import create_job_reporter
|
|
23
|
+
|
|
24
|
+
reporter = create_job_reporter(url="https://hadoku.me/health/api/jobs", user_key=SERVICE_KEY)
|
|
25
|
+
with reporter.tracked("dataplatform:daily-pipeline"):
|
|
26
|
+
run_daily_pipeline() # raises on failure -> recorded `failed`; else `succeeded`
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Manual start/finish (e.g. a fire-and-forget job that mints its run_id for a 202 body):
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
run_id = reporter.start("scraper:oss-recon") # posts a `started` row
|
|
33
|
+
... # background work
|
|
34
|
+
reporter.finish(run_id, "scraper:oss-recon", "succeeded", duration_ms=elapsed_ms)
|
|
35
|
+
```
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""hadoku-execlog — the Python execution-log reporter.
|
|
2
|
+
|
|
3
|
+
The Python twin of ``@wolffm/logger/jobs``: one client that posts the unified
|
|
4
|
+
execution-log contract to monitoring-api's ``POST /health/api/jobs`` so every
|
|
5
|
+
scheduled job — Python or TypeScript — self-reports a single truthful run record
|
|
6
|
+
(docs/planning/execution-log-unification-2026-07-21.md in hadoku_site).
|
|
7
|
+
|
|
8
|
+
Zero third-party dependencies (stdlib ``urllib`` only) so a run-and-exit systemd
|
|
9
|
+
job can adopt it without pulling a dependency tree. Fail-soft by design: a
|
|
10
|
+
monitoring outage never poisons the job.
|
|
11
|
+
|
|
12
|
+
Typical use for a run-and-exit job::
|
|
13
|
+
|
|
14
|
+
from execlog import create_job_reporter
|
|
15
|
+
|
|
16
|
+
reporter = create_job_reporter(url=..., user_key=...)
|
|
17
|
+
with reporter.tracked("dataplatform:daily-pipeline"):
|
|
18
|
+
run_daily_pipeline() # raises on failure -> recorded `failed`
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from .reporter import (
|
|
22
|
+
JobReporter,
|
|
23
|
+
JobStatus,
|
|
24
|
+
TERMINAL_STATUSES,
|
|
25
|
+
create_job_reporter,
|
|
26
|
+
generate_run_id,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"JobReporter",
|
|
31
|
+
"JobStatus",
|
|
32
|
+
"TERMINAL_STATUSES",
|
|
33
|
+
"create_job_reporter",
|
|
34
|
+
"generate_run_id",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""The execution-log reporter — posts the unified contract to monitoring-api.
|
|
2
|
+
|
|
3
|
+
Mirrors the TypeScript ``createJobReporter`` (@wolffm/logger/jobs): a run posts a
|
|
4
|
+
``started`` row, then UPDATEs it to a terminal outcome keyed by ``run_id``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import time
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
import uuid
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
from typing import Any, Callable, Iterator, Optional
|
|
16
|
+
|
|
17
|
+
# The unified 5-state execution-log vocabulary. ``started`` is in-flight.
|
|
18
|
+
JobStatus = str # one of: started | succeeded | failed | killed | skipped
|
|
19
|
+
TERMINAL_STATUSES = frozenset({"succeeded", "failed", "killed", "skipped"})
|
|
20
|
+
|
|
21
|
+
# Public so callers can log/inspect; not raised (the client is fail-soft).
|
|
22
|
+
OnError = Callable[[BaseException, str], None]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def generate_run_id(kind: str = "run") -> str:
|
|
26
|
+
"""``{kind}_{uuid12}`` — the ecosystem-wide run_id convention."""
|
|
27
|
+
return f"{kind}_{uuid.uuid4().hex[:12]}"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class JobReporter:
|
|
31
|
+
"""Posts job-run records to monitoring-api's ``/health/api/jobs``.
|
|
32
|
+
|
|
33
|
+
All network errors are swallowed (logged via ``on_error``) — a monitoring
|
|
34
|
+
outage must never poison the job. The exception is :meth:`tracked`, where the
|
|
35
|
+
wrapped work's own exception always propagates; only the reporting is
|
|
36
|
+
fail-soft.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
url: str,
|
|
42
|
+
user_key: str,
|
|
43
|
+
*,
|
|
44
|
+
cron: Optional[str] = None,
|
|
45
|
+
timeout: float = 8.0,
|
|
46
|
+
on_error: Optional[OnError] = None,
|
|
47
|
+
_opener: Optional[Callable[[urllib.request.Request, float], Any]] = None,
|
|
48
|
+
) -> None:
|
|
49
|
+
self._url = url
|
|
50
|
+
self._user_key = user_key
|
|
51
|
+
self._cron = cron
|
|
52
|
+
self._timeout = timeout
|
|
53
|
+
self._on_error = on_error or _default_on_error
|
|
54
|
+
# Injection seam for tests — defaults to urllib.request.urlopen.
|
|
55
|
+
self._opener = _opener or (lambda req, timeout: urllib.request.urlopen(req, timeout=timeout))
|
|
56
|
+
|
|
57
|
+
def _post(self, body: dict[str, Any], phase: str) -> None:
|
|
58
|
+
payload = json.dumps({k: v for k, v in body.items() if v is not None}).encode("utf-8")
|
|
59
|
+
req = urllib.request.Request(
|
|
60
|
+
self._url,
|
|
61
|
+
data=payload,
|
|
62
|
+
method="POST",
|
|
63
|
+
headers={"Content-Type": "application/json", "X-User-Key": self._user_key},
|
|
64
|
+
)
|
|
65
|
+
try:
|
|
66
|
+
resp = self._opener(req, self._timeout)
|
|
67
|
+
# urlopen raises HTTPError for non-2xx, so reaching here is 2xx; still
|
|
68
|
+
# read/close defensively for connection reuse.
|
|
69
|
+
status = getattr(resp, "status", None) or getattr(resp, "code", 200)
|
|
70
|
+
close = getattr(resp, "close", None)
|
|
71
|
+
if callable(close):
|
|
72
|
+
close()
|
|
73
|
+
if status is not None and not (200 <= int(status) < 300):
|
|
74
|
+
self._on_error(RuntimeError(f"HTTP {status}"), phase)
|
|
75
|
+
except urllib.error.HTTPError as e: # non-2xx — the 403-outage shape
|
|
76
|
+
self._on_error(RuntimeError(f"HTTP {e.code}"), phase)
|
|
77
|
+
except Exception as e: # noqa: BLE001 — fail-soft; never poison the job
|
|
78
|
+
self._on_error(e, phase)
|
|
79
|
+
|
|
80
|
+
def start(
|
|
81
|
+
self,
|
|
82
|
+
job_name: str,
|
|
83
|
+
*,
|
|
84
|
+
run_id: Optional[str] = None,
|
|
85
|
+
kind: str = "run",
|
|
86
|
+
cron: Optional[str] = None,
|
|
87
|
+
metadata: Optional[dict[str, Any]] = None,
|
|
88
|
+
) -> str:
|
|
89
|
+
"""Post a ``started`` row; returns the run_id (generated if not supplied)."""
|
|
90
|
+
rid = run_id or generate_run_id(kind)
|
|
91
|
+
self._post(
|
|
92
|
+
{
|
|
93
|
+
"job_name": job_name,
|
|
94
|
+
"status": "started",
|
|
95
|
+
"run_id": rid,
|
|
96
|
+
"cron": cron or self._cron,
|
|
97
|
+
"data": metadata,
|
|
98
|
+
},
|
|
99
|
+
"start",
|
|
100
|
+
)
|
|
101
|
+
return rid
|
|
102
|
+
|
|
103
|
+
def finish(
|
|
104
|
+
self,
|
|
105
|
+
run_id: str,
|
|
106
|
+
job_name: str,
|
|
107
|
+
status: JobStatus,
|
|
108
|
+
*,
|
|
109
|
+
duration_ms: int,
|
|
110
|
+
error: Optional[str] = None,
|
|
111
|
+
cron: Optional[str] = None,
|
|
112
|
+
metadata: Optional[dict[str, Any]] = None,
|
|
113
|
+
) -> None:
|
|
114
|
+
"""Post the terminal outcome for ``run_id`` (UPDATEs the started row)."""
|
|
115
|
+
if status not in TERMINAL_STATUSES:
|
|
116
|
+
raise ValueError(f"finish() status must be terminal, got {status!r}")
|
|
117
|
+
self._post(
|
|
118
|
+
{
|
|
119
|
+
"job_name": job_name,
|
|
120
|
+
"status": status,
|
|
121
|
+
"run_id": run_id,
|
|
122
|
+
"duration_ms": duration_ms,
|
|
123
|
+
"error": error,
|
|
124
|
+
"cron": cron or self._cron,
|
|
125
|
+
"data": metadata,
|
|
126
|
+
},
|
|
127
|
+
"finish",
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
@contextmanager
|
|
131
|
+
def tracked(
|
|
132
|
+
self,
|
|
133
|
+
job_name: str,
|
|
134
|
+
*,
|
|
135
|
+
kind: str = "run",
|
|
136
|
+
cron: Optional[str] = None,
|
|
137
|
+
metadata: Optional[dict[str, Any]] = None,
|
|
138
|
+
) -> Iterator[str]:
|
|
139
|
+
"""start -> run body -> finish. Maps an exception to ``failed`` and re-raises.
|
|
140
|
+
|
|
141
|
+
``with reporter.tracked("x:y") as run_id: do_work()``
|
|
142
|
+
"""
|
|
143
|
+
run_id = self.start(job_name, kind=kind, cron=cron, metadata=metadata)
|
|
144
|
+
started = time.monotonic()
|
|
145
|
+
try:
|
|
146
|
+
yield run_id
|
|
147
|
+
except BaseException as e:
|
|
148
|
+
self.finish(
|
|
149
|
+
run_id,
|
|
150
|
+
job_name,
|
|
151
|
+
"failed",
|
|
152
|
+
duration_ms=int((time.monotonic() - started) * 1000),
|
|
153
|
+
error=str(e),
|
|
154
|
+
cron=cron,
|
|
155
|
+
metadata=metadata,
|
|
156
|
+
)
|
|
157
|
+
raise
|
|
158
|
+
else:
|
|
159
|
+
self.finish(
|
|
160
|
+
run_id,
|
|
161
|
+
job_name,
|
|
162
|
+
"succeeded",
|
|
163
|
+
duration_ms=int((time.monotonic() - started) * 1000),
|
|
164
|
+
cron=cron,
|
|
165
|
+
metadata=metadata,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _default_on_error(err: BaseException, phase: str) -> None:
|
|
170
|
+
# Deliberately stderr-only + best-effort; the reporter must never raise.
|
|
171
|
+
try:
|
|
172
|
+
import sys
|
|
173
|
+
|
|
174
|
+
print(f"[execlog] {phase} report failed: {err}", file=sys.stderr)
|
|
175
|
+
except Exception: # noqa: BLE001
|
|
176
|
+
pass
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def create_job_reporter(
|
|
180
|
+
url: str,
|
|
181
|
+
user_key: str,
|
|
182
|
+
*,
|
|
183
|
+
cron: Optional[str] = None,
|
|
184
|
+
timeout: float = 8.0,
|
|
185
|
+
on_error: Optional[OnError] = None,
|
|
186
|
+
) -> JobReporter:
|
|
187
|
+
"""Construct a :class:`JobReporter`. Mirrors TS ``createJobReporter``."""
|
|
188
|
+
return JobReporter(url, user_key, cron=cron, timeout=timeout, on_error=on_error)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hadoku-execlog
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Execution-log reporter — self-report scheduled-job runs to hadoku monitoring-api (unified contract).
|
|
5
|
+
Home-page: https://github.com/WolffM/hadoku_site
|
|
6
|
+
Author: WolffM
|
|
7
|
+
License: ISC
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: ISC License (ISCL)
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
14
|
+
Dynamic: author
|
|
15
|
+
Dynamic: classifier
|
|
16
|
+
Dynamic: description
|
|
17
|
+
Dynamic: description-content-type
|
|
18
|
+
Dynamic: home-page
|
|
19
|
+
Dynamic: license
|
|
20
|
+
Dynamic: provides-extra
|
|
21
|
+
Dynamic: requires-python
|
|
22
|
+
Dynamic: summary
|
|
23
|
+
|
|
24
|
+
# hadoku-execlog
|
|
25
|
+
|
|
26
|
+
The Python execution-log reporter — the twin of `@wolffm/logger/jobs`. One client
|
|
27
|
+
that posts the unified execution-log contract to monitoring-api's
|
|
28
|
+
`POST /health/api/jobs`, so every scheduled job (Python or TypeScript) self-reports
|
|
29
|
+
a single truthful run record.
|
|
30
|
+
|
|
31
|
+
Part of the execution-log unification —
|
|
32
|
+
`docs/planning/execution-log-unification-2026-07-21.md` in hadoku_site.
|
|
33
|
+
|
|
34
|
+
- **Zero runtime dependencies** (stdlib `urllib` only) — a run-and-exit systemd job
|
|
35
|
+
can adopt it without pulling a dependency tree.
|
|
36
|
+
- **Fail-soft** — a monitoring outage never poisons the job. The exception is
|
|
37
|
+
`tracked()`, where the wrapped work's own error always propagates.
|
|
38
|
+
- **Unified 5-state vocabulary**: `started` / `succeeded` / `failed` / `killed` / `skipped`.
|
|
39
|
+
|
|
40
|
+
## Use
|
|
41
|
+
|
|
42
|
+
Run-and-exit job (the common case for dataplatform / writeOutPrompts):
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from execlog import create_job_reporter
|
|
46
|
+
|
|
47
|
+
reporter = create_job_reporter(url="https://hadoku.me/health/api/jobs", user_key=SERVICE_KEY)
|
|
48
|
+
with reporter.tracked("dataplatform:daily-pipeline"):
|
|
49
|
+
run_daily_pipeline() # raises on failure -> recorded `failed`; else `succeeded`
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Manual start/finish (e.g. a fire-and-forget job that mints its run_id for a 202 body):
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
run_id = reporter.start("scraper:oss-recon") # posts a `started` row
|
|
56
|
+
... # background work
|
|
57
|
+
reporter.finish(run_id, "scraper:oss-recon", "succeeded", duration_ms=elapsed_ms)
|
|
58
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
setup.py
|
|
3
|
+
execlog/__init__.py
|
|
4
|
+
execlog/reporter.py
|
|
5
|
+
hadoku_execlog.egg-info/PKG-INFO
|
|
6
|
+
hadoku_execlog.egg-info/SOURCES.txt
|
|
7
|
+
hadoku_execlog.egg-info/dependency_links.txt
|
|
8
|
+
hadoku_execlog.egg-info/requires.txt
|
|
9
|
+
hadoku_execlog.egg-info/top_level.txt
|
|
10
|
+
tests/test_reporter.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
execlog
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""hadoku-execlog — Python execution-log reporter.
|
|
2
|
+
|
|
3
|
+
Packaging mirrors the ecosystem's proven PyPI trusted-publishing pattern
|
|
4
|
+
(see fidelity-api): a plain setup.py, built with `python -m build` and published
|
|
5
|
+
by a GitHub Actions workflow via OIDC (no tokens). Zero runtime dependencies.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from setuptools import setup, find_packages
|
|
9
|
+
|
|
10
|
+
setup(
|
|
11
|
+
name="hadoku-execlog",
|
|
12
|
+
version="0.1.0",
|
|
13
|
+
description="Execution-log reporter — self-report scheduled-job runs to hadoku monitoring-api (unified contract).",
|
|
14
|
+
long_description=open("README.md", encoding="utf-8").read(),
|
|
15
|
+
long_description_content_type="text/markdown",
|
|
16
|
+
author="WolffM",
|
|
17
|
+
url="https://github.com/WolffM/hadoku_site",
|
|
18
|
+
packages=find_packages(exclude=("tests", "tests.*")),
|
|
19
|
+
python_requires=">=3.9",
|
|
20
|
+
install_requires=[], # stdlib only — deliberately dependency-free
|
|
21
|
+
extras_require={"dev": ["pytest>=7"]},
|
|
22
|
+
classifiers=[
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"License :: OSI Approved :: ISC License (ISCL)",
|
|
25
|
+
],
|
|
26
|
+
license="ISC",
|
|
27
|
+
)
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Tests for the execution-log reporter (the Python twin of @wolffm/logger/jobs)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import urllib.error
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from execlog import JobReporter, create_job_reporter, generate_run_id
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _FakeResp:
|
|
15
|
+
def __init__(self, status: int = 200) -> None:
|
|
16
|
+
self.status = status
|
|
17
|
+
|
|
18
|
+
def close(self) -> None:
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def make_reporter(*, fail: bool = False, http_status: int = 200):
|
|
23
|
+
calls: list[dict] = []
|
|
24
|
+
errors: list[tuple[str, str]] = []
|
|
25
|
+
|
|
26
|
+
def opener(req, timeout): # noqa: ANN001
|
|
27
|
+
calls.append(
|
|
28
|
+
{
|
|
29
|
+
"url": req.full_url,
|
|
30
|
+
"headers": {k.lower(): v for k, v in req.headers.items()},
|
|
31
|
+
"body": json.loads(req.data.decode()),
|
|
32
|
+
}
|
|
33
|
+
)
|
|
34
|
+
if fail:
|
|
35
|
+
raise urllib.error.URLError("network down")
|
|
36
|
+
if http_status >= 400:
|
|
37
|
+
raise urllib.error.HTTPError(req.full_url, http_status, "err", {}, None) # type: ignore[arg-type]
|
|
38
|
+
return _FakeResp(http_status)
|
|
39
|
+
|
|
40
|
+
reporter = JobReporter(
|
|
41
|
+
"https://hadoku.me/health/api/jobs",
|
|
42
|
+
"test-key",
|
|
43
|
+
on_error=lambda e, phase: errors.append((phase, str(e))),
|
|
44
|
+
_opener=opener,
|
|
45
|
+
)
|
|
46
|
+
return reporter, calls, errors
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_generate_run_id_format():
|
|
50
|
+
assert re.match(r"^daily_[0-9a-f]{12}$", generate_run_id("daily"))
|
|
51
|
+
assert re.match(r"^run_[0-9a-f]{12}$", generate_run_id())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_start_posts_started_and_returns_run_id():
|
|
55
|
+
reporter, calls, _ = make_reporter()
|
|
56
|
+
run_id = reporter.start("scraper:oss-recon", kind="daily", cron="0 11 * * *")
|
|
57
|
+
assert re.match(r"^daily_[0-9a-f]{12}$", run_id)
|
|
58
|
+
assert len(calls) == 1
|
|
59
|
+
assert calls[0]["headers"]["x-user-key"] == "test-key"
|
|
60
|
+
assert calls[0]["body"] == {
|
|
61
|
+
"job_name": "scraper:oss-recon",
|
|
62
|
+
"status": "started",
|
|
63
|
+
"run_id": run_id,
|
|
64
|
+
"cron": "0 11 * * *",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_start_honors_supplied_run_id():
|
|
69
|
+
reporter, calls, _ = make_reporter()
|
|
70
|
+
run_id = reporter.start("a:b", run_id="pre_minted01")
|
|
71
|
+
assert run_id == "pre_minted01"
|
|
72
|
+
assert calls[0]["body"]["run_id"] == "pre_minted01"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_finish_posts_terminal_keyed_by_run_id():
|
|
76
|
+
reporter, calls, _ = make_reporter()
|
|
77
|
+
reporter.finish("run_abc123456789", "a:b", "failed", duration_ms=4200, error="boom", metadata={"rows": 3})
|
|
78
|
+
body = calls[0]["body"]
|
|
79
|
+
assert body["job_name"] == "a:b"
|
|
80
|
+
assert body["status"] == "failed"
|
|
81
|
+
assert body["run_id"] == "run_abc123456789"
|
|
82
|
+
assert body["duration_ms"] == 4200
|
|
83
|
+
assert body["error"] == "boom"
|
|
84
|
+
assert body["data"] == {"rows": 3}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_finish_rejects_non_terminal_status():
|
|
88
|
+
reporter, _, _ = make_reporter()
|
|
89
|
+
with pytest.raises(ValueError):
|
|
90
|
+
reporter.finish("run_x", "a:b", "started", duration_ms=1)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_tracked_success_start_then_succeeded():
|
|
94
|
+
reporter, calls, _ = make_reporter()
|
|
95
|
+
with reporter.tracked("a:b") as run_id:
|
|
96
|
+
assert run_id
|
|
97
|
+
statuses = [c["body"]["status"] for c in calls]
|
|
98
|
+
assert statuses == ["started", "succeeded"]
|
|
99
|
+
assert calls[0]["body"]["run_id"] == calls[1]["body"]["run_id"]
|
|
100
|
+
assert isinstance(calls[1]["body"]["duration_ms"], int)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_tracked_exception_start_then_failed_and_reraises():
|
|
104
|
+
reporter, calls, _ = make_reporter()
|
|
105
|
+
with pytest.raises(RuntimeError, match="work blew up"):
|
|
106
|
+
with reporter.tracked("a:b"):
|
|
107
|
+
raise RuntimeError("work blew up")
|
|
108
|
+
statuses = [c["body"]["status"] for c in calls]
|
|
109
|
+
assert statuses == ["started", "failed"]
|
|
110
|
+
assert calls[1]["body"]["error"] == "work blew up"
|
|
111
|
+
assert calls[0]["body"]["run_id"] == calls[1]["body"]["run_id"]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_fail_soft_network_error_never_raises():
|
|
115
|
+
reporter, _, errors = make_reporter(fail=True)
|
|
116
|
+
# start still returns a run_id even when the POST fails
|
|
117
|
+
run_id = reporter.start("a:b")
|
|
118
|
+
assert run_id.startswith("run_")
|
|
119
|
+
reporter.finish("run_x", "a:b", "succeeded", duration_ms=1)
|
|
120
|
+
assert [p for p, _ in errors] == ["start", "finish"]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def test_tracked_propagates_work_error_even_when_reporting_fails():
|
|
124
|
+
reporter, _, _ = make_reporter(fail=True)
|
|
125
|
+
with pytest.raises(RuntimeError, match="work error"):
|
|
126
|
+
with reporter.tracked("a:b"):
|
|
127
|
+
raise RuntimeError("work error")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def test_non_2xx_surfaced_to_on_error():
|
|
131
|
+
reporter, _, errors = make_reporter(http_status=403)
|
|
132
|
+
reporter.finish("run_x", "a:b", "succeeded", duration_ms=1)
|
|
133
|
+
assert len(errors) == 1
|
|
134
|
+
assert errors[0][0] == "finish"
|
|
135
|
+
assert "HTTP 403" in errors[0][1]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_create_job_reporter_helper():
|
|
139
|
+
r = create_job_reporter("https://x/jobs", "k")
|
|
140
|
+
assert isinstance(r, JobReporter)
|