diff --git a/.gitignore b/.gitignore
index a0dc30c..8092f7c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,4 @@ __pycache__/
dist/
build/
*.egg-info/
+.darkroom/
diff --git a/README.md b/README.md
index 0690422..fb82f36 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,57 @@ trace.report("world-load", tags={"kind": "procedural"})
trace.close()
```
+
+
+*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:
environment, then enabled=, then key
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,
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
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:
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
+
+| | |
+|---|---|
+|  | **`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/` 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
@@ -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.
diff --git a/docs/screenshots/demo-output.png b/docs/screenshots/demo-output.png
new file mode 100644
index 0000000..a57d839
Binary files /dev/null and b/docs/screenshots/demo-output.png differ
diff --git a/docs/screenshots/media.json b/docs/screenshots/media.json
new file mode 100644
index 0000000..20de794
--- /dev/null
+++ b/docs/screenshots/media.json
@@ -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."
+ }
+ ]
+}
diff --git a/docs/screenshots/render_terminal.py b/docs/screenshots/render_terminal.py
new file mode 100644
index 0000000..f7a94ac
--- /dev/null
+++ b/docs/screenshots/render_terminal.py
@@ -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 = """demo
+
+
+"""
+
+
+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])
diff --git a/examples/demo.py b/examples/demo.py
new file mode 100644
index 0000000..39d502a
--- /dev/null
+++ b/examples/demo.py
@@ -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()