driftseer 0.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.
- driftseer/__init__.py +11 -0
- driftseer/cli.py +53 -0
- driftseer/cloud.py +191 -0
- driftseer/local.py +267 -0
- driftseer/otel/__init__.py +4 -0
- driftseer/otel/claude_code_tel.py +407 -0
- driftseer/tracer.py +602 -0
- driftseer-0.0.1.dist-info/METADATA +114 -0
- driftseer-0.0.1.dist-info/RECORD +12 -0
- driftseer-0.0.1.dist-info/WHEEL +5 -0
- driftseer-0.0.1.dist-info/entry_points.txt +3 -0
- driftseer-0.0.1.dist-info/top_level.txt +1 -0
driftseer/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""driftseer — capture a run's shape and economics, write it locally, and optionally upload it."""
|
|
2
|
+
|
|
3
|
+
from .local import default_runs_path
|
|
4
|
+
from .tracer import Lens, annotate, carry, outcome, record
|
|
5
|
+
|
|
6
|
+
__all__ = ["init", "Lens", "record", "annotate", "outcome", "carry", "default_runs_path"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def init(project: str, capture_content: bool = False) -> Lens:
|
|
10
|
+
"""The one entry point; capture_content=False keeps every file to shape and economics, never content."""
|
|
11
|
+
return Lens(project=project, capture_content=capture_content)
|
driftseer/cli.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cli.py — ``driftseer cloud on|off|status``, the only writer of settings.json.
|
|
3
|
+
|
|
4
|
+
The key never touches disk: it lives only in DRIFTSEER_CLOUD_KEY.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
from . import local
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _status() -> None:
|
|
14
|
+
"""Prints the switch, URL, whether the key is set (never its value), paths and upload counts."""
|
|
15
|
+
settings = local.read_settings()
|
|
16
|
+
key_set = "set" if os.getenv("DRIFTSEER_CLOUD_KEY") else "not set"
|
|
17
|
+
print(f"cloud upload: {'on' if settings.get('upload') else 'off'}")
|
|
18
|
+
print(f"url: {settings.get('url') or '(none saved)'}")
|
|
19
|
+
print(f"DRIFTSEER_CLOUD_KEY: {key_set}")
|
|
20
|
+
print(f"runs file: {local.default_runs_path()}")
|
|
21
|
+
print(f"waiting: {local.count_waiting()}")
|
|
22
|
+
print(f"rejected: {local.count_rejected()}")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main(argv: list[str] | None = None) -> None:
|
|
26
|
+
"""Console-script entry point for the cloud switch."""
|
|
27
|
+
parser = argparse.ArgumentParser(prog="driftseer")
|
|
28
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
29
|
+
cloud = sub.add_parser("cloud", help="Turn cloud upload on or off, or show its status")
|
|
30
|
+
action = cloud.add_subparsers(dest="action", required=True)
|
|
31
|
+
on = action.add_parser("on", help="Upload each finished run to the cloud ingest")
|
|
32
|
+
on.add_argument("--url", required=True, help="Cloud ingest URL")
|
|
33
|
+
action.add_parser("off", help="Stop uploading; the runs file keeps being written")
|
|
34
|
+
action.add_parser("status", help="Show the switch, URL, key presence and upload counts")
|
|
35
|
+
args = parser.parse_args(argv)
|
|
36
|
+
|
|
37
|
+
settings = local.read_settings()
|
|
38
|
+
if args.action == "on":
|
|
39
|
+
local.write_settings({**settings, "upload": True, "url": args.url})
|
|
40
|
+
print(f"cloud upload: on -> {args.url}")
|
|
41
|
+
if not os.getenv("DRIFTSEER_CLOUD_KEY"):
|
|
42
|
+
print("DRIFTSEER_CLOUD_KEY is not set: nothing uploads until it is.")
|
|
43
|
+
else:
|
|
44
|
+
print("DRIFTSEER_CLOUD_KEY is set.")
|
|
45
|
+
elif args.action == "off":
|
|
46
|
+
local.write_settings({**settings, "upload": False})
|
|
47
|
+
print("cloud upload: off")
|
|
48
|
+
else:
|
|
49
|
+
_status()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
main()
|
driftseer/cloud.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cloud.py — posts finished packets to the cloud ingest, off the caller's thread.
|
|
3
|
+
|
|
4
|
+
Upload happens only when all three hold: ``driftseer cloud on`` saved the switch,
|
|
5
|
+
a URL is saved with it, and ``DRIFTSEER_CLOUD_KEY`` is set in the environment.
|
|
6
|
+
|
|
7
|
+
A run's journal is deleted only when that same run gets its own 200. Progress is
|
|
8
|
+
never tracked by position, so a later success cannot hide an earlier failure, and
|
|
9
|
+
the first 200 after a failure resends every run still waiting (spec section 8b).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import atexit
|
|
13
|
+
import http.client
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import queue
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.request
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from . import local
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("driftseer")
|
|
26
|
+
|
|
27
|
+
_STOP = object()
|
|
28
|
+
_shippers: dict[tuple[str, str], "Shipper"] = {}
|
|
29
|
+
_registry_lock = threading.Lock()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_shipper() -> "Shipper | None":
|
|
33
|
+
"""Reads the switch once; returns this process's shipper, or None (no thread, no network)."""
|
|
34
|
+
settings = local.read_settings()
|
|
35
|
+
if not settings.get("upload"):
|
|
36
|
+
return None
|
|
37
|
+
url = settings.get("url")
|
|
38
|
+
if not url:
|
|
39
|
+
logger.warning("driftseer: cloud upload is on but no URL is saved; run "
|
|
40
|
+
"`driftseer cloud on --url <ingest url>`. Uploads are off.")
|
|
41
|
+
return None
|
|
42
|
+
key = os.getenv("DRIFTSEER_CLOUD_KEY")
|
|
43
|
+
if not key:
|
|
44
|
+
logger.warning("driftseer: cloud upload is on but DRIFTSEER_CLOUD_KEY is not set; "
|
|
45
|
+
"runs are written locally and nothing is uploaded.")
|
|
46
|
+
return None
|
|
47
|
+
with _registry_lock:
|
|
48
|
+
shipper = _shippers.get((url, key))
|
|
49
|
+
if shipper is None:
|
|
50
|
+
shipper = _shippers[(url, key)] = Shipper(url, key)
|
|
51
|
+
return shipper
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _wait_idle(timeout: float) -> bool:
|
|
55
|
+
"""Waits until every shipper in this process has answered its queue."""
|
|
56
|
+
end = time.monotonic() + timeout
|
|
57
|
+
return all(s.wait_idle(max(0.0, end - time.monotonic())) for s in list(_shippers.values()))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _close_all(timeout: float = 5.0) -> None:
|
|
61
|
+
"""Stops every shipper; anything unsent keeps its journal and waits for the next trigger."""
|
|
62
|
+
with _registry_lock:
|
|
63
|
+
shippers = list(_shippers.values())
|
|
64
|
+
_shippers.clear()
|
|
65
|
+
for s in shippers:
|
|
66
|
+
s.close(timeout)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
atexit.register(_close_all, 5.0)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Shipper:
|
|
73
|
+
"""One daemon thread per process that POSTs ready packets, so a slow endpoint never stalls the host."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, url: str, key: str, timeout: float = 15.0, max_queue: int = 1000):
|
|
76
|
+
"""Starts the drain thread; 15 s leaves room for a scaled-to-zero endpoint's cold start."""
|
|
77
|
+
self.endpoint = url.rstrip("/") + "/v1/runs"
|
|
78
|
+
self._key = key
|
|
79
|
+
self._timeout = timeout
|
|
80
|
+
self._queue: queue.Queue = queue.Queue(maxsize=max_queue)
|
|
81
|
+
self._pending: set[str] = set()
|
|
82
|
+
self._pending_lock = threading.Lock()
|
|
83
|
+
self._pass_lock = threading.Lock()
|
|
84
|
+
self._warned: set[str] = set()
|
|
85
|
+
self._thread = threading.Thread(target=self._drain, name="driftseer-cloud", daemon=True)
|
|
86
|
+
self._thread.start()
|
|
87
|
+
|
|
88
|
+
def _warn_once(self, key: str, msg: str, *args) -> None:
|
|
89
|
+
"""Keeps a recurring condition (full queue, bad key) to one warning per process."""
|
|
90
|
+
if key not in self._warned:
|
|
91
|
+
self._warned.add(key)
|
|
92
|
+
logger.warning(msg, *args)
|
|
93
|
+
|
|
94
|
+
def ship(self, run_id: str, body: bytes, journal_path: Path) -> None:
|
|
95
|
+
"""Queues one packet without blocking; a full queue leaves the run waiting, never dropped."""
|
|
96
|
+
with self._pending_lock:
|
|
97
|
+
if run_id in self._pending:
|
|
98
|
+
return
|
|
99
|
+
self._pending.add(run_id)
|
|
100
|
+
try:
|
|
101
|
+
self._queue.put_nowait((run_id, body, Path(journal_path)))
|
|
102
|
+
except queue.Full:
|
|
103
|
+
with self._pending_lock:
|
|
104
|
+
self._pending.discard(run_id)
|
|
105
|
+
self._warn_once("full", "driftseer: upload queue full; run %s waits for the next "
|
|
106
|
+
"resend (it is in the runs file).", run_id)
|
|
107
|
+
|
|
108
|
+
def resend_pass(self) -> None:
|
|
109
|
+
"""Queues every waiting run, oldest first; one pass at a time per process."""
|
|
110
|
+
if not self._pass_lock.acquire(blocking=False):
|
|
111
|
+
return
|
|
112
|
+
try:
|
|
113
|
+
for path in local.journals():
|
|
114
|
+
records = local.read_journal(path)
|
|
115
|
+
if local.journal_state(records) != "waiting":
|
|
116
|
+
continue
|
|
117
|
+
pid = records[0].get("pid") if records else None
|
|
118
|
+
if pid != os.getpid() and local.pid_alive(pid):
|
|
119
|
+
continue # its own process will send it
|
|
120
|
+
packet = next(r for r in records if r.get("t") == "packet")
|
|
121
|
+
self.ship(path.stem, packet["runs"].encode("utf-8"), path)
|
|
122
|
+
finally:
|
|
123
|
+
self._pass_lock.release()
|
|
124
|
+
|
|
125
|
+
def _post(self, body: bytes) -> "int | None":
|
|
126
|
+
"""POSTs one body; returns the HTTP status, or None when no response arrived."""
|
|
127
|
+
req = urllib.request.Request(
|
|
128
|
+
self.endpoint, data=body, method="POST",
|
|
129
|
+
headers={"Content-Type": "application/json", "Authorization": f"Bearer {self._key}"},
|
|
130
|
+
)
|
|
131
|
+
try:
|
|
132
|
+
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
|
133
|
+
resp.read()
|
|
134
|
+
return resp.status
|
|
135
|
+
except urllib.error.HTTPError as exc:
|
|
136
|
+
return exc.code
|
|
137
|
+
except (urllib.error.URLError, http.client.HTTPException, OSError, ValueError):
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
def _handle(self, run_id: str, status: "int | None", journal: local.Journal) -> None:
|
|
141
|
+
"""Applies the response rules: 200 deletes, 413/422 rejects, anything else keeps waiting."""
|
|
142
|
+
if status == 200:
|
|
143
|
+
journal.delete()
|
|
144
|
+
if local.count_waiting():
|
|
145
|
+
self.resend_pass()
|
|
146
|
+
elif status in (413, 422):
|
|
147
|
+
journal.reject()
|
|
148
|
+
logger.warning("driftseer: the cloud refused run %s (HTTP %s); kept in %s, never "
|
|
149
|
+
"retried.", run_id, status, local.rejected_dir())
|
|
150
|
+
elif status == 401:
|
|
151
|
+
self._warn_once("401", "driftseer: the cloud rejected DRIFTSEER_CLOUD_KEY (HTTP 401); "
|
|
152
|
+
"runs keep waiting until the key is fixed.")
|
|
153
|
+
else:
|
|
154
|
+
logger.warning("driftseer: upload of run %s failed (%s); it waits and is resent "
|
|
155
|
+
"at the next trigger.", run_id, status or "no response")
|
|
156
|
+
|
|
157
|
+
def _drain(self) -> None:
|
|
158
|
+
"""Posts queued packets one by one; nothing here may raise into the host."""
|
|
159
|
+
while True:
|
|
160
|
+
item = self._queue.get()
|
|
161
|
+
try:
|
|
162
|
+
if item is _STOP:
|
|
163
|
+
return
|
|
164
|
+
run_id, body, path = item
|
|
165
|
+
with self._pending_lock:
|
|
166
|
+
self._pending.discard(run_id)
|
|
167
|
+
self._handle(run_id, self._post(body), local.Journal(path))
|
|
168
|
+
except Exception as exc: # noqa: BLE001 - upload must never crash the host program
|
|
169
|
+
logger.warning("driftseer: upload error: %s", type(exc).__name__)
|
|
170
|
+
finally:
|
|
171
|
+
self._queue.task_done()
|
|
172
|
+
|
|
173
|
+
def wait_idle(self, timeout: float) -> bool:
|
|
174
|
+
"""Blocks until the queue is empty and answered, or the timeout passes."""
|
|
175
|
+
end = time.monotonic() + timeout
|
|
176
|
+
with self._queue.all_tasks_done:
|
|
177
|
+
while self._queue.unfinished_tasks:
|
|
178
|
+
remaining = end - time.monotonic()
|
|
179
|
+
if remaining <= 0:
|
|
180
|
+
return False
|
|
181
|
+
self._queue.all_tasks_done.wait(remaining)
|
|
182
|
+
return True
|
|
183
|
+
|
|
184
|
+
def close(self, timeout: float = 5.0) -> None:
|
|
185
|
+
"""Gives queued uploads up to `timeout`, then stops; unsent runs keep their journals."""
|
|
186
|
+
self.wait_idle(timeout)
|
|
187
|
+
try:
|
|
188
|
+
self._queue.put_nowait(_STOP)
|
|
189
|
+
except queue.Full:
|
|
190
|
+
pass
|
|
191
|
+
self._thread.join(timeout=1)
|
driftseer/local.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""
|
|
2
|
+
local.py — everything driftseer keeps on this machine.
|
|
3
|
+
|
|
4
|
+
One folder (``~/.driftseer``, or ``DRIFTSEER_HOME``) holds:
|
|
5
|
+
|
|
6
|
+
- ``runs.jsonl`` one packet per finished run, exactly what the cloud receives
|
|
7
|
+
- ``content.jsonl`` the same packet, plus content when ``capture_content`` is on
|
|
8
|
+
- ``settings.json`` the cloud switch, written only by ``driftseer cloud``
|
|
9
|
+
- ``inflight/`` one scratch journal per live or not-yet-delivered run
|
|
10
|
+
- ``rejected/`` journals the cloud refused for good (413/422), kept for the user
|
|
11
|
+
|
|
12
|
+
Stdlib only. Nothing here builds packets or talks to the network.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
import shutil
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("driftseer")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def home() -> Path:
|
|
26
|
+
"""One folder for every local file, so DRIFTSEER_HOME relocates them together."""
|
|
27
|
+
return Path(os.environ.get("DRIFTSEER_HOME") or Path.home() / ".driftseer")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def default_runs_path() -> str:
|
|
31
|
+
"""The runs file: the user's local copy of exactly what the cloud receives."""
|
|
32
|
+
return str(home() / "runs.jsonl")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def content_path() -> Path:
|
|
36
|
+
"""The content file: every run, with content only when capture_content is on."""
|
|
37
|
+
return home() / "content.jsonl"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def settings_path() -> Path:
|
|
41
|
+
"""The cloud switch's file, written only by the CLI."""
|
|
42
|
+
return home() / "settings.json"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def inflight_dir() -> Path:
|
|
46
|
+
"""Scratch journals for runs that are live or not yet delivered."""
|
|
47
|
+
return home() / "inflight"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def rejected_dir() -> Path:
|
|
51
|
+
"""Journals the cloud refused for good, kept so the user can see them."""
|
|
52
|
+
return home() / "rejected"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def now_iso() -> str:
|
|
56
|
+
"""One timestamp convention (UTC ISO 8601 with offset) for every record."""
|
|
57
|
+
return datetime.now(timezone.utc).isoformat()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ── settings ──────────────────────────────────────────────────────────────────
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def read_settings() -> dict:
|
|
64
|
+
"""Missing or unreadable means upload off; a corrupt file warns so it is not silent."""
|
|
65
|
+
path = settings_path()
|
|
66
|
+
try:
|
|
67
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
68
|
+
return data if isinstance(data, dict) else {}
|
|
69
|
+
except FileNotFoundError:
|
|
70
|
+
return {}
|
|
71
|
+
except (OSError, ValueError) as exc:
|
|
72
|
+
logger.warning("driftseer: cannot read settings %s (%s); cloud upload is off.", path, exc)
|
|
73
|
+
return {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def write_settings(data: dict) -> None:
|
|
77
|
+
"""Replaces the settings file atomically so a reader never sees half a file."""
|
|
78
|
+
path = settings_path()
|
|
79
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
tmp = path.with_suffix(".tmp")
|
|
81
|
+
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
|
82
|
+
os.replace(tmp, path)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ── locked append ─────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _lock(fd: int) -> None:
|
|
89
|
+
"""Blocks until this process holds the sidecar lock (msvcrt on Windows, flock elsewhere)."""
|
|
90
|
+
if os.name == "nt":
|
|
91
|
+
import msvcrt
|
|
92
|
+
|
|
93
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
94
|
+
while True:
|
|
95
|
+
try:
|
|
96
|
+
msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
|
|
97
|
+
return
|
|
98
|
+
except OSError:
|
|
99
|
+
continue # LK_LOCK gives up after ~10 s of contention; keep waiting
|
|
100
|
+
import fcntl
|
|
101
|
+
|
|
102
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _unlock(fd: int) -> None:
|
|
106
|
+
"""Releases the sidecar lock taken by _lock."""
|
|
107
|
+
if os.name == "nt":
|
|
108
|
+
import msvcrt
|
|
109
|
+
|
|
110
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
111
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
|
|
112
|
+
return
|
|
113
|
+
import fcntl
|
|
114
|
+
|
|
115
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def append_line(path, line: str) -> bool:
|
|
119
|
+
"""Appends one whole line under a cross-process lock, so lines never tear; False on failure, callers warn."""
|
|
120
|
+
path = Path(path)
|
|
121
|
+
try:
|
|
122
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
lock_fd = os.open(str(path) + ".lock", os.O_RDWR | os.O_CREAT, 0o644)
|
|
124
|
+
try:
|
|
125
|
+
_lock(lock_fd)
|
|
126
|
+
try:
|
|
127
|
+
with open(path, "ab") as f:
|
|
128
|
+
f.write(line.encode("utf-8") + b"\n")
|
|
129
|
+
f.flush()
|
|
130
|
+
os.fsync(f.fileno())
|
|
131
|
+
finally:
|
|
132
|
+
_unlock(lock_fd)
|
|
133
|
+
finally:
|
|
134
|
+
os.close(lock_fd)
|
|
135
|
+
return True
|
|
136
|
+
except OSError:
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ── process liveness ──────────────────────────────────────────────────────────
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def pid_alive(pid) -> bool:
|
|
144
|
+
"""Whether the process that owns a journal still runs; unknowable counts as alive (never steal)."""
|
|
145
|
+
if not isinstance(pid, int) or pid <= 0:
|
|
146
|
+
return True
|
|
147
|
+
if pid == os.getpid():
|
|
148
|
+
return True
|
|
149
|
+
if os.name == "nt":
|
|
150
|
+
import ctypes
|
|
151
|
+
|
|
152
|
+
kernel32 = ctypes.windll.kernel32
|
|
153
|
+
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
|
154
|
+
if not handle:
|
|
155
|
+
return kernel32.GetLastError() == 5 # access denied: it exists
|
|
156
|
+
try:
|
|
157
|
+
code = ctypes.c_ulong()
|
|
158
|
+
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
|
|
159
|
+
return True
|
|
160
|
+
return code.value == 259 # STILL_ACTIVE
|
|
161
|
+
finally:
|
|
162
|
+
kernel32.CloseHandle(handle)
|
|
163
|
+
try:
|
|
164
|
+
os.kill(pid, 0)
|
|
165
|
+
except ProcessLookupError:
|
|
166
|
+
return False
|
|
167
|
+
except PermissionError:
|
|
168
|
+
return True
|
|
169
|
+
return True
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# ── the crash journal ─────────────────────────────────────────────────────────
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class Journal:
|
|
176
|
+
"""One run's scratch file: each record is flushed to disk before capture continues."""
|
|
177
|
+
|
|
178
|
+
def __init__(self, path: Path):
|
|
179
|
+
"""Binds a journal path; nothing is opened until the first write."""
|
|
180
|
+
self.path = path
|
|
181
|
+
self.ok = True
|
|
182
|
+
|
|
183
|
+
@classmethod
|
|
184
|
+
def for_run(cls, run_id: str) -> "Journal":
|
|
185
|
+
"""The journal a new run writes to, under inflight/."""
|
|
186
|
+
return cls(inflight_dir() / f"{run_id}.jsonl")
|
|
187
|
+
|
|
188
|
+
def write(self, record: dict) -> None:
|
|
189
|
+
"""Appends one record and fsyncs it; a failure warns once and leaves the run in memory."""
|
|
190
|
+
if not self.ok:
|
|
191
|
+
return
|
|
192
|
+
try:
|
|
193
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
with open(self.path, "ab") as f:
|
|
195
|
+
f.write(json.dumps({**record, "ts": now_iso()}).encode("utf-8") + b"\n")
|
|
196
|
+
f.flush()
|
|
197
|
+
os.fsync(f.fileno())
|
|
198
|
+
except OSError as exc:
|
|
199
|
+
self.ok = False
|
|
200
|
+
logger.warning("driftseer: cannot write crash journal %s (%s); this run has no "
|
|
201
|
+
"crash protection.", self.path, exc)
|
|
202
|
+
|
|
203
|
+
def delete(self) -> None:
|
|
204
|
+
"""Drops the journal once its run is delivered."""
|
|
205
|
+
try:
|
|
206
|
+
self.path.unlink()
|
|
207
|
+
except FileNotFoundError:
|
|
208
|
+
pass
|
|
209
|
+
except OSError as exc:
|
|
210
|
+
logger.warning("driftseer: cannot delete journal %s (%s).", self.path, exc)
|
|
211
|
+
|
|
212
|
+
def reject(self) -> None:
|
|
213
|
+
"""Moves a journal the cloud can never accept into rejected/, kept and never retried."""
|
|
214
|
+
try:
|
|
215
|
+
rejected_dir().mkdir(parents=True, exist_ok=True)
|
|
216
|
+
shutil.move(str(self.path), str(rejected_dir() / self.path.name))
|
|
217
|
+
except OSError as exc:
|
|
218
|
+
logger.warning("driftseer: cannot move journal %s to rejected/ (%s).", self.path, exc)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def read_journal(path: Path) -> list[dict]:
|
|
222
|
+
"""Every whole record of a journal; a torn line (a write cut by a crash) is dropped with a warning."""
|
|
223
|
+
try:
|
|
224
|
+
text = path.read_text(encoding="utf-8")
|
|
225
|
+
except OSError:
|
|
226
|
+
return []
|
|
227
|
+
records = []
|
|
228
|
+
for raw in text.splitlines():
|
|
229
|
+
if not raw.strip():
|
|
230
|
+
continue
|
|
231
|
+
try:
|
|
232
|
+
records.append(json.loads(raw))
|
|
233
|
+
except ValueError:
|
|
234
|
+
logger.warning("driftseer: dropped a torn line in journal %s.", path.name)
|
|
235
|
+
return records
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def journals() -> list[Path]:
|
|
239
|
+
"""Every journal under inflight/, oldest first."""
|
|
240
|
+
try:
|
|
241
|
+
paths = list(inflight_dir().glob("*.jsonl"))
|
|
242
|
+
except OSError:
|
|
243
|
+
return []
|
|
244
|
+
return sorted(paths, key=lambda p: p.stat().st_mtime if p.exists() else 0)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def journal_state(records: list[dict]) -> str:
|
|
248
|
+
""""live" (no packet yet), "unwritten" (packet, files not done), "waiting" (needs a 200) or "done"."""
|
|
249
|
+
packet = next((r for r in records if r.get("t") == "packet"), None)
|
|
250
|
+
if packet is None:
|
|
251
|
+
return "live"
|
|
252
|
+
if not any(r.get("t") == "written" for r in records):
|
|
253
|
+
return "unwritten"
|
|
254
|
+
return "waiting" if packet.get("cloud") else "done"
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def count_waiting() -> int:
|
|
258
|
+
"""How many runs recorded with cloud on still lack their 200."""
|
|
259
|
+
return sum(1 for p in journals() if journal_state(read_journal(p)) == "waiting")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def count_rejected() -> int:
|
|
263
|
+
"""How many runs the cloud refused for good."""
|
|
264
|
+
try:
|
|
265
|
+
return len(list(rejected_dir().glob("*.jsonl")))
|
|
266
|
+
except OSError:
|
|
267
|
+
return 0
|