Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ __pycache__/
dist/
build/
*.egg-info/
.darkroom/
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,57 @@ trace.report("world-load", tags={"kind": "procedural"})
trace.close()
```

![Terminal output of examples/demo.py: three events reach a stand-in trace server as POST /api/metrics with a Bearer key, each tagged with version and install; then DO_NOT_TRACK=1, enabled="false" and an empty key each give a client that sends nothing](docs/screenshots/demo-output.png)

*The real output of [`python examples/demo.py`](examples/demo.py), which runs the
client against a stand-in trace server on a loopback port. Nothing leaves the
machine.*

## How a report travels

`report()` only builds the JSON body and puts it on a bounded queue; one daemon
thread the client owns does the HTTP. The opt-outs are decided once, in the
constructor, and a disabled client never starts that thread.

```mermaid
sequenceDiagram
participant P as Program
participant C as TraceClient
participant Q as Queue (max 256)
participant S as Sender thread
participant T as trace server

P->>C: TraceClient(base_url, application, version, key=..., enabled=...)
Note over C: opt-outs, first match wins:<br/>environment, then enabled=, then key<br/>disabled: no thread, no install ID, nothing sent
C->>S: start daemon thread (enabled only)
P->>C: report("startup", value, tags)
Note over C: add tags version and install,<br/>drop None tags and non-real values
C->>Q: put_nowait(JSON body)
C-->>P: returns at once (full queue: dropped, logged at DEBUG)
Q->>S: get()
S->>T: POST /api/metrics<br/>Authorization: Bearer key
alt 201
T-->>S: 201 Created
else any other status (redirects not followed)
T-->>S: 3xx / 4xx / 5xx
end
Note over S: anything but 201, or no answer in 5 s:<br/>logged at DEBUG, report dropped
P->>C: close(timeout=5)
C->>Q: put stop signal behind queued reports
Q->>S: remaining reports, then stop
C-->>P: returns when drained or after timeout
```

## Screenshots

| | |
|---|---|
| ![Terminal output of examples/demo.py showing the three events the stand-in server received and the three opt-outs](docs/screenshots/demo-output.png) | **`python examples/demo.py`.** The client reports `startup`, `world-load` and `level-complete`; every event arrives at `POST /api/metrics` with the key as a Bearer token, the `trace-client-python/<version>` User-Agent, and the `version` and `install` tags added by the client. Then `DO_NOT_TRACK=1`, `enabled="false"` and an empty key each give a client with `enabled=False` and the matching `disabled_reason`. (The install ID is a fresh random UUID each run; the example prints its first eight characters.) |

**Regenerating screenshots:** `darkroom shoot docs/screenshots/media.json` (the
[darkroom](https://github.com/Preponderous-Software/darkroom) shot list runs the
example and screenshots its output).

## Every event carries the program's version

The third argument to `TraceClient` is the program's own version, and it is
Expand Down Expand Up @@ -205,6 +256,10 @@ Pyodide has no real threads and no outbound sockets, so build the client with
python -m unittest -v
```

To see the client work end to end without a trace server, run
`python examples/demo.py`: it starts a stand-in server on a loopback port and
prints what it receives.

Tests run the client against the standard library's own `ThreadingHTTPServer`
on a loopback port. CI runs them on Python 3.8, 3.10 and 3.12.

Expand Down
Binary file added docs/screenshots/demo-output.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions docs/screenshots/media.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"out": ".",
"shots": [
{
"name": "demo-page", "kind": "prep", "backend": "command",
"argv": ["python3", "render_terminal.py", "build/demo.html"],
"inputs": ["render_terminal.py", "../../examples/demo.py", "../../trace_client/trace_client.py"],
"outputs": ["build/demo.html"]
},
{
"name": "demo-output", "kind": "still", "format": "png", "device": "desktop",
"depends": ["demo-page"],
"url": "file://{manifest_dir}/build/demo.html",
"crop": { "of": "#term", "pad": 0 },
"caption": "examples/demo.py: three events reach a stand-in trace server, then each opt-out yields a client that sends nothing.",
"alt": "Terminal output of python examples/demo.py: the stand-in server receives three POST /api/metrics events with a Bearer key, the trace-client-python User-Agent, and version and install tags on every event; then DO_NOT_TRACK=1, enabled=\"false\" and an empty key each give enabled=False with disabled_reason environment, config and no key."
}
]
}
41 changes: 41 additions & 0 deletions docs/screenshots/render_terminal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Runs examples/demo.py and writes its real output as a terminal-styled
HTML page, which media.json then screenshots. Usage:

python docs/screenshots/render_terminal.py OUT.html
"""
import html
import os
import subprocess
import sys

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
COMMAND = ["python", "examples/demo.py"]

PAGE = """<!doctype html><meta charset="utf-8"><title>demo</title>
<style>
body {{ margin: 0; background: #e8eaed; font: 15px/1.5 "DejaVu Sans Mono", monospace; }}
#term {{ display: inline-block; margin: 24px; background: #0d1117; color: #c9d1d9;
border-radius: 10px; box-shadow: 0 4px 18px #0004; min-width: 1000px; }}
.bar {{ padding: 9px 14px; background: #161b22; border-radius: 10px 10px 0 0; }}
.bar i {{ display: inline-block; width: 12px; height: 12px; border-radius: 50%; margin-right: 6px; }}
pre {{ margin: 0; padding: 14px 20px 18px; font: inherit; white-space: pre; }}
.p {{ color: #7ee787; }}
</style>
<div id="term"><div class="bar"><i style="background:#ff5f56"></i><i style="background:#ffbd2e"></i><i style="background:#27c93f"></i></div>
<pre><span class="p">$</span> {command}
{output}</pre></div>
"""


def main(out):
env = {k: v for k, v in os.environ.items() if k not in ("TRACE_USAGE_REPORTING", "DO_NOT_TRACK")}
result = subprocess.run([sys.executable] + COMMAND[1:], cwd=ROOT, env=env, check=True,
capture_output=True, text=True)
os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
with open(out, "w", encoding="utf-8") as page:
page.write(PAGE.format(command=html.escape(" ".join(COMMAND)),
output=html.escape(result.stdout.rstrip("\n"))))


if __name__ == "__main__":
main(sys.argv[1])
84 changes: 84 additions & 0 deletions examples/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""A self-contained run of trace-client against a stand-in trace server.

Starts a tiny HTTP server on a free loopback port that answers
``POST /api/metrics`` the way a trace server does (``201``), points a
``TraceClient`` at it, reports a few events, and prints what reached the
server. Then shows the opt-outs: the same constructor with
``DO_NOT_TRACK=1``, with ``enabled="false"`` and with no key.

Nothing leaves the machine. Run from the repository root:

python examples/demo.py
"""
import json
import os
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

from trace_client import TraceClient, __version__, allows_reporting # noqa: E402

received = []


class StandIn(BaseHTTPRequestHandler):
"""Answers like a trace server: 201 for every POST to /api/metrics."""

def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
received.append((self.path, self.headers.get("Authorization"),
self.headers.get("User-Agent"), json.loads(body)))
self.send_response(201 if self.path == "/api/metrics" else 404)
self.send_header("Content-Length", "0")
self.end_headers()

def log_message(self, *args):
pass


def main():
for name in ("TRACE_USAGE_REPORTING", "DO_NOT_TRACK"):
os.environ.pop(name, None)
server = ThreadingHTTPServer(("127.0.0.1", 0), StandIn)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d" % server.server_address[1]

print("trace-client-python %s, stand-in trace server on a loopback port\n" % __version__)
with tempfile.TemporaryDirectory() as settings_dir:
trace = TraceClient(url, "demo-game", "1.4.0", key="demo-key",
enabled=allows_reporting("true"),
install_id_file=os.path.join(settings_dir, "trace-install-id"))
print("enabled=%s disabled_reason=%s" % (trace.enabled, trace.disabled_reason))
trace.report("startup")
trace.report("world-load", tags={"kind": "procedural"})
trace.report("level-complete", value=42.5, tags={"level": "3"})
trace.close() # drains the queue before returning

print("\nThe server received %d events:" % len(received))
path, authorization, user_agent, _ = received[0]
print(" POST %s" % path)
print(" Authorization: %s" % authorization)
print(" User-Agent: %s" % user_agent)
for _, _, _, event in received:
install = event.get("tags", {}).get("install")
if install: # a fresh random UUID each run; shortened for the screen
event["tags"]["install"] = install[:8] + "..."
print(" " + json.dumps(event, separators=(",", ":")))
server.shutdown()

print("\nEvery opt-out yields a client that sends nothing:")
os.environ["DO_NOT_TRACK"] = "1"
off = TraceClient(url, "demo-game", "1.4.0", key="demo-key")
print(" DO_NOT_TRACK=1 -> enabled=%s disabled_reason=%r" % (off.enabled, off.disabled_reason))
del os.environ["DO_NOT_TRACK"]
off = TraceClient(url, "demo-game", "1.4.0", key="demo-key", enabled="false")
print(" enabled=\"false\" -> enabled=%s disabled_reason=%r" % (off.enabled, off.disabled_reason))
off = TraceClient(url, "demo-game", "1.4.0", key="")
print(" key=\"\" -> enabled=%s disabled_reason=%r" % (off.enabled, off.disabled_reason))


if __name__ == "__main__":
main()
Loading