driftseer 0.0.1__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.
- driftseer-0.0.1/PKG-INFO +114 -0
- driftseer-0.0.1/README.md +102 -0
- driftseer-0.0.1/pyproject.toml +27 -0
- driftseer-0.0.1/setup.cfg +4 -0
- driftseer-0.0.1/src/driftseer/__init__.py +11 -0
- driftseer-0.0.1/src/driftseer/cli.py +53 -0
- driftseer-0.0.1/src/driftseer/cloud.py +191 -0
- driftseer-0.0.1/src/driftseer/local.py +267 -0
- driftseer-0.0.1/src/driftseer/otel/__init__.py +4 -0
- driftseer-0.0.1/src/driftseer/otel/claude_code_tel.py +407 -0
- driftseer-0.0.1/src/driftseer/tracer.py +602 -0
- driftseer-0.0.1/src/driftseer.egg-info/PKG-INFO +114 -0
- driftseer-0.0.1/src/driftseer.egg-info/SOURCES.txt +14 -0
- driftseer-0.0.1/src/driftseer.egg-info/dependency_links.txt +1 -0
- driftseer-0.0.1/src/driftseer.egg-info/entry_points.txt +3 -0
- driftseer-0.0.1/src/driftseer.egg-info/top_level.txt +1 -0
driftseer-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: driftseer
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Capture an agent run's shape and economics into a local runs file, with an opt-in cloud upload
|
|
5
|
+
Author: Avtaar Labs
|
|
6
|
+
Project-URL: Homepage, https://driftseer.dev
|
|
7
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Topic :: System :: Monitoring
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# driftseer
|
|
14
|
+
|
|
15
|
+
> **Pre-launch release.** This early version is published ahead of the full launch. See https://driftseer.dev for status.
|
|
16
|
+
|
|
17
|
+
Capture the shape and economics of an agent run (tokens, latency, status,
|
|
18
|
+
structure), write it to a local file, and optionally upload it to the DriftSeer
|
|
19
|
+
cloud. Zero runtime dependencies.
|
|
20
|
+
|
|
21
|
+
**Your content never leaves the machine.** Each finished run is one JSON packet:
|
|
22
|
+
|
|
23
|
+
- `~/.driftseer/runs.jsonl` holds exactly what the cloud receives. Never content.
|
|
24
|
+
- `~/.driftseer/content.jsonl` holds the same packet, plus content when you turn
|
|
25
|
+
`capture_content` on. Build your own dashboard from it if you like.
|
|
26
|
+
|
|
27
|
+
Cloud upload is off until you turn it on. The line in the runs file, without its
|
|
28
|
+
newline, is byte for byte the body that is uploaded, so you can see what is sent.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install driftseer
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Use
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import driftseer
|
|
40
|
+
|
|
41
|
+
lens = driftseer.init(project="rag-agent") # capture_content=False by default
|
|
42
|
+
|
|
43
|
+
@lens.track(model="text-embedding-3-small")
|
|
44
|
+
def embed(query):
|
|
45
|
+
resp = client.embeddings.create(model="text-embedding-3-small", input=query)
|
|
46
|
+
driftseer.record(input_tokens=resp.usage.prompt_tokens)
|
|
47
|
+
return resp.data[0].embedding
|
|
48
|
+
|
|
49
|
+
@lens.track(model="gpt-4o-mini")
|
|
50
|
+
def answer(query, context):
|
|
51
|
+
resp = client.chat.completions.create(model="gpt-4o-mini", messages=[...])
|
|
52
|
+
driftseer.record(resp.usage.prompt_tokens, resp.usage.completion_tokens,
|
|
53
|
+
content={"answer": resp.choices[0].message.content})
|
|
54
|
+
return resp.choices[0].message.content
|
|
55
|
+
|
|
56
|
+
@lens.track
|
|
57
|
+
def ask(query): # the outermost tracked call is the run
|
|
58
|
+
driftseer.annotate(route="rag")
|
|
59
|
+
result = answer(query, embed(query))
|
|
60
|
+
driftseer.outcome(accepted=True)
|
|
61
|
+
return result
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
- `@lens.track(name=None, model=None)` works on functions, coroutines,
|
|
65
|
+
generators and async generators. A stream's step stays open until the stream
|
|
66
|
+
ends.
|
|
67
|
+
- `driftseer.record(input_tokens, output_tokens, content=None, model=None)`
|
|
68
|
+
reports usage for the current step. `model=` replaces a model chosen at
|
|
69
|
+
decoration time.
|
|
70
|
+
- `driftseer.annotate(**labels)` adds labels to the run's metadata. Labels are
|
|
71
|
+
uploaded, so keep personal data out of them.
|
|
72
|
+
- `driftseer.outcome(accepted, wasted=[step names])` labels the run explicitly.
|
|
73
|
+
- `driftseer.carry(fn)` keeps the run when work goes to a thread:
|
|
74
|
+
`pool.submit(driftseer.carry(worker), item)`.
|
|
75
|
+
- Misuse (for example `record()` outside any tracked function) warns and is
|
|
76
|
+
dropped. Capture never raises into your program.
|
|
77
|
+
|
|
78
|
+
Costs are not computed locally: every step carries `cost` null and the cloud
|
|
79
|
+
prices it from tokens and model. Errors upload as the exception type only; with
|
|
80
|
+
`capture_content` on, the message goes to the content file.
|
|
81
|
+
|
|
82
|
+
## Cloud upload
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
driftseer cloud on --url <ingest url> # also needs DRIFTSEER_CLOUD_KEY in the environment
|
|
86
|
+
driftseer cloud off
|
|
87
|
+
driftseer cloud status # switch, URL, key set or not, runs waiting/rejected
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Upload needs all three: the switch on, a saved URL, and `DRIFTSEER_CLOUD_KEY` set.
|
|
91
|
+
The key is never written to disk. A failed upload is resent at the next
|
|
92
|
+
`driftseer.init()`, or after the next successful upload; a run the cloud refuses
|
|
93
|
+
for good (HTTP 413 or 422) is kept in `~/.driftseer/rejected/`.
|
|
94
|
+
|
|
95
|
+
## Crash safety
|
|
96
|
+
|
|
97
|
+
While a run is live, each step is journaled in `~/.driftseer/inflight/`. If the
|
|
98
|
+
process dies, the next `driftseer.init()` on the machine delivers that run with
|
|
99
|
+
status `abandoned` and every step that finished.
|
|
100
|
+
|
|
101
|
+
## Files
|
|
102
|
+
|
|
103
|
+
`DRIFTSEER_HOME` relocates the whole folder: `runs.jsonl`, `content.jsonl`,
|
|
104
|
+
`settings.json`, `inflight/`, `rejected/`.
|
|
105
|
+
|
|
106
|
+
## Claude Code
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
python -m driftseer.otel.claude_code_tel --project claude-code --port 4318
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Each Claude Code turn becomes one run, with Claude Code's own `cost_usd` kept.
|
|
113
|
+
See the module docstring for the OTEL environment variables.
|
|
114
|
+
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# driftseer
|
|
2
|
+
|
|
3
|
+
> **Pre-launch release.** This early version is published ahead of the full launch. See https://driftseer.dev for status.
|
|
4
|
+
|
|
5
|
+
Capture the shape and economics of an agent run (tokens, latency, status,
|
|
6
|
+
structure), write it to a local file, and optionally upload it to the DriftSeer
|
|
7
|
+
cloud. Zero runtime dependencies.
|
|
8
|
+
|
|
9
|
+
**Your content never leaves the machine.** Each finished run is one JSON packet:
|
|
10
|
+
|
|
11
|
+
- `~/.driftseer/runs.jsonl` holds exactly what the cloud receives. Never content.
|
|
12
|
+
- `~/.driftseer/content.jsonl` holds the same packet, plus content when you turn
|
|
13
|
+
`capture_content` on. Build your own dashboard from it if you like.
|
|
14
|
+
|
|
15
|
+
Cloud upload is off until you turn it on. The line in the runs file, without its
|
|
16
|
+
newline, is byte for byte the body that is uploaded, so you can see what is sent.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install driftseer
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Use
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import driftseer
|
|
28
|
+
|
|
29
|
+
lens = driftseer.init(project="rag-agent") # capture_content=False by default
|
|
30
|
+
|
|
31
|
+
@lens.track(model="text-embedding-3-small")
|
|
32
|
+
def embed(query):
|
|
33
|
+
resp = client.embeddings.create(model="text-embedding-3-small", input=query)
|
|
34
|
+
driftseer.record(input_tokens=resp.usage.prompt_tokens)
|
|
35
|
+
return resp.data[0].embedding
|
|
36
|
+
|
|
37
|
+
@lens.track(model="gpt-4o-mini")
|
|
38
|
+
def answer(query, context):
|
|
39
|
+
resp = client.chat.completions.create(model="gpt-4o-mini", messages=[...])
|
|
40
|
+
driftseer.record(resp.usage.prompt_tokens, resp.usage.completion_tokens,
|
|
41
|
+
content={"answer": resp.choices[0].message.content})
|
|
42
|
+
return resp.choices[0].message.content
|
|
43
|
+
|
|
44
|
+
@lens.track
|
|
45
|
+
def ask(query): # the outermost tracked call is the run
|
|
46
|
+
driftseer.annotate(route="rag")
|
|
47
|
+
result = answer(query, embed(query))
|
|
48
|
+
driftseer.outcome(accepted=True)
|
|
49
|
+
return result
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- `@lens.track(name=None, model=None)` works on functions, coroutines,
|
|
53
|
+
generators and async generators. A stream's step stays open until the stream
|
|
54
|
+
ends.
|
|
55
|
+
- `driftseer.record(input_tokens, output_tokens, content=None, model=None)`
|
|
56
|
+
reports usage for the current step. `model=` replaces a model chosen at
|
|
57
|
+
decoration time.
|
|
58
|
+
- `driftseer.annotate(**labels)` adds labels to the run's metadata. Labels are
|
|
59
|
+
uploaded, so keep personal data out of them.
|
|
60
|
+
- `driftseer.outcome(accepted, wasted=[step names])` labels the run explicitly.
|
|
61
|
+
- `driftseer.carry(fn)` keeps the run when work goes to a thread:
|
|
62
|
+
`pool.submit(driftseer.carry(worker), item)`.
|
|
63
|
+
- Misuse (for example `record()` outside any tracked function) warns and is
|
|
64
|
+
dropped. Capture never raises into your program.
|
|
65
|
+
|
|
66
|
+
Costs are not computed locally: every step carries `cost` null and the cloud
|
|
67
|
+
prices it from tokens and model. Errors upload as the exception type only; with
|
|
68
|
+
`capture_content` on, the message goes to the content file.
|
|
69
|
+
|
|
70
|
+
## Cloud upload
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
driftseer cloud on --url <ingest url> # also needs DRIFTSEER_CLOUD_KEY in the environment
|
|
74
|
+
driftseer cloud off
|
|
75
|
+
driftseer cloud status # switch, URL, key set or not, runs waiting/rejected
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Upload needs all three: the switch on, a saved URL, and `DRIFTSEER_CLOUD_KEY` set.
|
|
79
|
+
The key is never written to disk. A failed upload is resent at the next
|
|
80
|
+
`driftseer.init()`, or after the next successful upload; a run the cloud refuses
|
|
81
|
+
for good (HTTP 413 or 422) is kept in `~/.driftseer/rejected/`.
|
|
82
|
+
|
|
83
|
+
## Crash safety
|
|
84
|
+
|
|
85
|
+
While a run is live, each step is journaled in `~/.driftseer/inflight/`. If the
|
|
86
|
+
process dies, the next `driftseer.init()` on the machine delivers that run with
|
|
87
|
+
status `abandoned` and every step that finished.
|
|
88
|
+
|
|
89
|
+
## Files
|
|
90
|
+
|
|
91
|
+
`DRIFTSEER_HOME` relocates the whole folder: `runs.jsonl`, `content.jsonl`,
|
|
92
|
+
`settings.json`, `inflight/`, `rejected/`.
|
|
93
|
+
|
|
94
|
+
## Claude Code
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
python -m driftseer.otel.claude_code_tel --project claude-code --port 4318
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Each Claude Code turn becomes one run, with Claude Code's own `cost_usd` kept.
|
|
101
|
+
See the module docstring for the OTEL environment variables.
|
|
102
|
+
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "driftseer"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "Capture an agent run's shape and economics into a local runs file, with an opt-in cloud upload"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
authors = [{ name = "Avtaar Labs" }]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Topic :: System :: Monitoring",
|
|
16
|
+
]
|
|
17
|
+
dependencies = []
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://driftseer.dev"
|
|
21
|
+
|
|
22
|
+
[project.scripts]
|
|
23
|
+
driftseer = "driftseer.cli:main"
|
|
24
|
+
driftseer-otel = "driftseer.otel.claude_code_tel:main"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
where = ["src"]
|
|
@@ -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)
|
|
@@ -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()
|
|
@@ -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)
|