From 06cda8e5949dbafe628f798c76cbf0098bea60d9 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Wed, 18 Nov 2026 21:25:59 -0700 Subject: [PATCH] fix: keep usage reporting off once it is turned off Re-vendor trace-client-python 0.5.0 (every opt-out fails closed) and make patchwork's own switch fail closed too: - enabled is read with allows_reporting(), not bool(): "false"/"off" no longer report - "usage_reporting": false (not an object) is read as the switch and no longer overwritten with the default block (on) - a first run under TRACE_USAGE_REPORTING/DO_NOT_TRACK records enabled: false Co-Authored-By: Claude Opus 5.5 --- README.md | 26 +- tests/test_trace_client.py | 510 +++++++++++++++++++++++++++++++++- tests/test_usage_reporting.py | 60 +++- trace_client.py | 163 ++++++++--- usage_reporting.py | 28 +- 5 files changed, 707 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index a420b83..d00dd19 100644 --- a/README.md +++ b/README.md @@ -328,9 +328,9 @@ notice is not shown again: If `settings.json` already exists, the block is added alongside its other entries. If it exists but cannot be read, or does not hold a JSON object, a message saying so is printed, the file is left untouched, and nothing is reported for that run. When -`TRACE_USAGE_REPORTING` or `DO_NOT_TRACK` already opts out (see below), the block is still written, -but the notice instead reads `Usage reporting is off (environment). Details:` followed by the -details link. +`TRACE_USAGE_REPORTING` or `DO_NOT_TRACK` already opts out (see below), the block is written with +`"enabled": false`, so reporting stays off on later runs without the variable, and the notice says +reporting is off instead. The installation ID is a random UUID kept in a file named `trace-install-id` in the user data directory: `~/.local/share/patchwork/` on Linux (or `$XDG_DATA_HOME/patchwork/`), @@ -351,18 +351,18 @@ To turn reporting off, any one of these is enough: } ``` -- set the environment variable `TRACE_USAGE_REPORTING=off` (also `false`, `0`, `no`), which turns - off every program that reports to trace -- set the environment variable `DO_NOT_TRACK=1` (also `true`, `yes`; see [consoledonottrack.com](https://consoledonottrack.com)) +- set the environment variable `TRACE_USAGE_REPORTING=off`, which turns off every program that + reports to trace (any value other than blank, `true`, `on`, `yes` or `1` turns it off) +- set the environment variable `DO_NOT_TRACK=1` (any value other than blank, `0`, `false`, `off` or + `no` turns it off; see [consoledonottrack.com](https://consoledonottrack.com)) -For both variables, case and surrounding whitespace are ignored, and any other value (including an -empty one) leaves `settings.json` in charge. +For both variables, case and surrounding whitespace are ignored, and a blank value leaves +`settings.json` in charge. -In `settings.json`, `enabled` should be the JSON value `false`, not the string `"false"`: it is read -for its truthiness, so any non-empty string, including `"false"` and `"off"`, leaves reporting on, -while `0`, `""` and `null` turn it off. The `usage_reporting` entry itself must be an object. Any -other value, such as `false`, is overwritten with the default block above, with reporting on, and -the first-launch notice is shown again. +Every switch fails closed. In `settings.json`, only `true` (or the string `"true"`, `"on"`, `"yes"` +or `"1"`) reports; `false`, `"false"`, `"off"`, `0`, `""`, `null` or a typo all keep reporting off. +A `usage_reporting` entry that is not an object, such as `"usage_reporting": false`, is read as the +switch itself and is never overwritten. The environment variables win over `settings.json`. `endpoint` selects the trace server and `key` the key reports are sent with; the `PATCHWORK_USAGE_REPORTING_KEY` environment variable, when diff --git a/tests/test_trace_client.py b/tests/test_trace_client.py index 7763c31..696c4dd 100644 --- a/tests/test_trace_client.py +++ b/tests/test_trace_client.py @@ -1,19 +1,28 @@ """Drives the client against a real HTTP server on a loopback port -- the standard library's own, so the tests have no more dependencies than the client does.""" +import decimal +import fractions import json import logging import os +import pathlib +import re import shutil import tempfile import threading import time +import types import unittest +import urllib.error +import urllib.request import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest import mock -from trace_client import MAX_TAG_LENGTH, MAX_TAGS, TraceClient, environment_opts_out +from trace_client import (MAX_TAG_LENGTH, MAX_TAGS, TraceClient, __version__, allows_reporting, + environment_opts_out) +import trace_client as trace_client_module _ENV_VARS = ("TRACE_USAGE_REPORTING", "DO_NOT_TRACK") @@ -22,6 +31,7 @@ class _Capture: def __init__(self): self.requests = [] self.reply_status = 201 + self.location = None # sent as a Location header when set self.arrived = threading.Event() self.release = threading.Event() self.release.set() # by default answer at once @@ -34,6 +44,7 @@ def do_POST(self): body = self.rfile.read(length) capture.release.wait(10) capture.requests.append({ + "method": self.command, "path": self.path, "authorization": self.headers.get("Authorization"), "content_type": self.headers.get("Content-Type"), @@ -41,10 +52,14 @@ def do_POST(self): "body": body.decode("utf-8"), }) self.send_response(capture.reply_status) + if capture.location is not None: + self.send_header("Location", capture.location) self.send_header("Content-Length", "0") self.end_headers() capture.arrived.set() + do_GET = do_POST # a followed 301/302/303 arrives as a GET + def log_message(self, *args): # keep test output quiet pass @@ -87,6 +102,53 @@ def test_report_posts_the_event_to_the_metrics_endpoint_with_the_key(self): json.loads(request["body"])) client.close() + def test_constructor_trims_the_base_url_application_and_key(self): + client = TraceClient(" " + self.base_url + "/ ", " MyGame ", "1.2.3", key=" k-123 ") + client.report("startup") + self.assertTrue(self.capture.arrived.wait(5), "a padded base URL should still reach the server") + request = self.capture.requests[0] + self.assertEqual("/api/metrics", request["path"]) + self.assertEqual("Bearer k-123", request["authorization"], "the key is sent without its padding") + self.assertEqual("MyGame", json.loads(request["body"])["application"]) + self.assertTrue(request["user_agent"].endswith("(MyGame)"), request["user_agent"]) + client.close() + + def test_a_base_url_with_a_path_keeps_it_in_front_of_the_endpoint(self): + # A trace server behind a reverse proxy lives under a path prefix. + client = TraceClient(self.base_url + "/trace//", "MyGame", "1.2.3", key="k") + client.report("startup") + self.assertTrue(self.capture.arrived.wait(5), "the report should reach the server") + client.close() + self.assertEqual("/trace/api/metrics", self.capture.requests[0]["path"], + "the prefix is kept and every trailing slash is dropped before /api/metrics") + + def test_non_ascii_names_and_tags_arrive_intact_as_utf8_json(self): + client = TraceClient(self.base_url, "Spiel", "1.2.3", key="k") + client.report("défi", tags={"ville": "Zürich", "emoji": "\U0001F3B2"}) + self.assertTrue(self.capture.arrived.wait(5), "the report should reach the server") + client.close() + request = self.capture.requests[0] + self.assertEqual("application/json; charset=utf-8", request["content_type"]) + self.assertEqual({"application": "Spiel", "name": "défi", + "tags": {"ville": "Zürich", "emoji": "\U0001F3B2", "version": "1.2.3"}}, + json.loads(request["body"]), "text the program reports is what the server reads") + + def test_an_application_name_a_header_cannot_carry_still_delivers_its_events(self): + # The name goes in the User-Agent as well as the body, and a header + # refuses most of Unicode and any line break. + for application, shown in (("ゲーム", "???"), ("dice\U0001F3B2", "dice?"), ("two\nlines", "two?lines"), + ("Zürich", "Zürich")): + self.capture.requests.clear() + client = TraceClient(self.base_url, application, "1.2.3", key="k") + client.report("startup") + client.close() + self.assertEqual(1, len(self.capture.requests), "%r lost its event: %s" + % (application, [r.getMessage() for r in self.log])) + request = self.capture.requests[0] + self.assertEqual(application, json.loads(request["body"])["application"], + "the event keeps the exact name; only the header is approximate") + self.assertEqual("trace-client-python/%s (%s)" % (__version__, shown), request["user_agent"]) + def test_report_carries_value_and_tags_when_given(self): client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") client.report("world-load", 2.5, {"seed": "42", "size": 'the "big" one'}) @@ -128,6 +190,79 @@ def test_report_does_not_raise_when_the_server_rejects_the_key(self): client.close() self.assertTrue(any("answered 401" in r.getMessage() for r in self.log), [r.getMessage() for r in self.log]) + def test_a_201_is_delivered_without_logging_anything(self): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.report("startup") + self.assertTrue(self.capture.arrived.wait(5)) + client.close() + self.assertEqual([], [r.getMessage() for r in self.log], "success is silent") + + def test_a_success_status_other_than_201_is_logged_as_not_delivered(self): + for status in (200, 204): + self.log.clear() + self.capture.reply_status = status + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.report("startup") + client.close() # joins the sender, so its log line is written by now + self.assertTrue(any("answered %d" % status in r.getMessage() for r in self.log), + "only a 201 is success: %s" % [r.getMessage() for r in self.log]) + self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log)) + + def test_a_redirect_is_logged_and_dropped_never_followed_with_the_key(self): + target = _Capture() + target_server = _server(target) + self.addCleanup(target_server.shutdown) + # Another port and another host name: what a redirect elsewhere looks like. + self.capture.location = "http://localhost:%d/elsewhere" % target_server.server_address[1] + for status in (301, 302, 303, 307, 308): + self.log.clear() + self.capture.reply_status = status + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="secret-key") + client.report("startup") + client.close() # joins the sender, so its log line is written by now + self.assertEqual([], target.requests, + "a %d must not carry the key to the host it names" % status) + self.assertTrue(any("answered %d" % status in r.getMessage() for r in self.log), + "the log names the redirect that lost the event: %s" + % [r.getMessage() for r in self.log]) + self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log)) + + def test_an_error_answer_whose_body_cannot_be_read_still_logs_its_status(self): + class Unreadable(urllib.error.HTTPError): + def read(self, *args): + raise OSError("connection reset while reading the error body") + + answer = Unreadable(self.base_url + "/api/metrics", 503, "Service Unavailable", {}, None) + crashes = [] + with mock.patch.object(threading, "excepthook", crashes.append), \ + mock.patch.object(trace_client_module._OPENER, "open", side_effect=answer): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.report("startup") # must not raise + client.close() + self.assertEqual([], crashes, "the sender thread must not die with a traceback on stderr") + self.assertTrue(any("answered 503" in r.getMessage() for r in self.log), [r.getMessage() for r in self.log]) + self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log)) + + def test_a_server_that_never_answers_costs_one_report_not_the_sender(self): + # Each request is bounded by TIMEOUT_SECONDS (shortened here), so a + # server that accepts the connection and then hangs drops that report + # and the sender moves on to the next one. + self.capture.release.clear() # hold the first request unanswered + with mock.patch.object(TraceClient, "TIMEOUT_SECONDS", 0.5): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.report("first") + deadline = time.monotonic() + 10 + while time.monotonic() < deadline and not any("could not deliver" in r.getMessage() for r in self.log): + time.sleep(0.05) + self.assertTrue(any("could not deliver" in r.getMessage() for r in self.log), + "a hung request must time out: %s" % [r.getMessage() for r in self.log]) + self.capture.release.set() + client.report("second") + client.close() + self.assertIn("second", [json.loads(r["body"])["name"] for r in self.capture.requests], + "the sender is still alive after a request times out") + self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log)) + def test_disabled_client_sends_nothing(self): for client in (TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled=False), TraceClient(self.base_url, "MyGame", "1.2.3"), @@ -170,15 +305,36 @@ def test_TRACE_USAGE_REPORTING_off_disables_reporting_for_every_accepted_value(s for value in ("off", "false", "0", "no", "OFF", "False", "No", " off "): self._assert_environment_disables("TRACE_USAGE_REPORTING", value) + def test_TRACE_USAGE_REPORTING_set_to_anything_but_a_clear_on_disables(self): + # Fails closed: a typo or an unfamiliar word is an opt-out, never consent. + for value in ("disabled", "of", "nope", "2", "-1", "ture", "none", "never", '"true"'): + self._assert_environment_disables("TRACE_USAGE_REPORTING", value) + def test_DO_NOT_TRACK_disables_reporting_for_every_accepted_value(self): for value in ("1", "true", "yes", "TRUE", "Yes", " 1 "): self._assert_environment_disables("DO_NOT_TRACK", value) - def test_other_environment_values_leave_the_program_setting_in_charge(self): + def test_DO_NOT_TRACK_set_to_anything_but_a_clear_no_disables(self): + for value in ("on", "2", "y", "enabled", "please", "nein"): + self._assert_environment_disables("DO_NOT_TRACK", value) + + def test_an_environment_that_cannot_be_read_disables_and_does_not_raise(self): + class Unreadable(dict): + def get(self, *args, **kwargs): + raise PermissionError("no") + self.assertTrue(environment_opts_out(Unreadable())) + self.assertTrue(environment_opts_out({"DO_NOT_TRACK": 1}), "a value that is not a string opts out") + with mock.patch.object(os, "environ", Unreadable()): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + self.assertFalse(client.enabled) + self.assertEqual("environment", client.disabled_reason) + + def test_blank_or_clearly_on_environment_values_leave_the_program_setting_in_charge(self): for variable, value in (("TRACE_USAGE_REPORTING", "on"), ("TRACE_USAGE_REPORTING", ""), - ("TRACE_USAGE_REPORTING", "disabled"), ("TRACE_USAGE_REPORTING", "1"), + ("TRACE_USAGE_REPORTING", " "), ("TRACE_USAGE_REPORTING", "1"), + ("TRACE_USAGE_REPORTING", "TRUE"), ("TRACE_USAGE_REPORTING", " yes "), ("DO_NOT_TRACK", "0"), ("DO_NOT_TRACK", ""), ("DO_NOT_TRACK", "false"), - ("DO_NOT_TRACK", "off")): + ("DO_NOT_TRACK", "off"), ("DO_NOT_TRACK", " No ")): with mock.patch.dict(os.environ, {variable: value}): self.assertFalse(environment_opts_out(), "%s=%r is not an opt-out" % (variable, value)) client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") @@ -187,6 +343,23 @@ def test_other_environment_values_leave_the_program_setting_in_charge(self): client.close() self.assertFalse(environment_opts_out(), "an unset variable is not an opt-out") + def test_allows_reporting_is_true_only_for_True_or_a_clear_on_string(self): + for setting in (True, "true", "on", "yes", "1", "TRUE", " On ", "Yes\n"): + self.assertTrue(allows_reporting(setting), repr(setting)) + for setting in (False, None, "false", "off", "no", "0", "", " ", "ture", '"false"', '"true"', "disabled", + 1, 0, 1.0, [], ["true"], {"enabled": True}, object(), b"true"): + self.assertFalse(allows_reporting(setting), repr(setting)) + + def test_enabled_is_read_through_allows_reporting(self): + for setting in ("false", "off", "no", '"false"', "ture", None, 1, "0"): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled=setting) + self.assertFalse(client.enabled, "enabled=%r must not report" % (setting,)) + self.assertEqual("config", client.disabled_reason, repr(setting)) + for setting in (True, "true", " ON ", "yes", "1"): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled=setting) + self.assertTrue(client.enabled, "enabled=%r reports" % (setting,)) + client.close() + def test_environment_wins_over_the_config_flag_and_over_the_key(self): # enabled=True with a key, and the environment still says no. with mock.patch.dict(os.environ, {"TRACE_USAGE_REPORTING": "off"}): @@ -211,15 +384,47 @@ def test_environment_opts_out_accepts_an_explicit_mapping(self): self.assertTrue(environment_opts_out({"DO_NOT_TRACK": "yes"})) self.assertFalse(environment_opts_out({})) self.assertFalse(environment_opts_out({"DO_NOT_TRACK": "0", "TRACE_USAGE_REPORTING": "on"})) + self.assertTrue(environment_opts_out({"TRACE_USAGE_REPORTING": "disabled"})) + self.assertTrue(environment_opts_out({"DO_NOT_TRACK": "on"})) + + def test_environment_opts_out_reads_only_the_mapping_it_is_given(self): + with mock.patch.dict(os.environ, {"DO_NOT_TRACK": "1"}): + self.assertTrue(environment_opts_out(), "no mapping means the process environment") + self.assertTrue(environment_opts_out(None), "None means the process environment") + self.assertFalse(environment_opts_out({}), "an explicit mapping replaces the environment") + self.assertTrue(environment_opts_out({"DO_NOT_TRACK": " TRUE "}), + "a mapping's values are trimmed and compared without case, like the environment's") + self.assertTrue(environment_opts_out({"TRACE_USAGE_REPORTING": " No "})) def test_user_agent_names_the_client_version(self): from trace_client import __version__ - self.assertEqual("0.4.1", __version__) + self.assertEqual("0.5.0", __version__) client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") client.report("startup") self.assertTrue(self.capture.arrived.wait(5)) client.close() - self.assertEqual("trace-client-python/0.4.1 (MyGame)", self.capture.requests[0]["user_agent"]) + self.assertEqual("trace-client-python/0.5.0 (MyGame)", self.capture.requests[0]["user_agent"]) + + + + def test_disabled_reason_values_are_the_exported_constants(self): + from trace_client import REASON_CONFIG, REASON_ENVIRONMENT, REASON_NO_KEY + self.assertEqual(("environment", "config", "no key"), (REASON_ENVIRONMENT, REASON_CONFIG, REASON_NO_KEY), + "the strings the README documents, and the Java client sends the same") + self.assertEqual(REASON_CONFIG, TraceClient.disabled().disabled_reason) + self.assertEqual(REASON_NO_KEY, TraceClient(self.base_url, "MyGame", "1.2.3").disabled_reason) + with mock.patch.dict(os.environ, {"DO_NOT_TRACK": "1"}): + self.assertEqual(REASON_ENVIRONMENT, TraceClient(self.base_url, "MyGame", "1.2.3", key="k").disabled_reason) + + def test_report_does_not_raise_for_tags_that_are_not_a_mapping(self): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.report("startup", tags=["kind"]) # must not raise + client.report("command", tags=42) # must not raise + client.close() + self.assertFalse(self.capture.arrived.wait(0.3), "a report that could not be built is dropped") + self.assertEqual(["startup", "command"], + [r.args[0] for r in self.log if r.getMessage().startswith("[trace] could not queue")]) + self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log)) def test_report_ignores_a_blank_name(self): client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") @@ -289,6 +494,89 @@ def test_constructor_rejects_a_missing_blank_or_overlong_version(self): TraceClient(self.base_url, "MyGame", "9" * MAX_TAG_LENGTH, enabled=False) TraceClient(self.base_url, "MyGame", " " + "9" * MAX_TAG_LENGTH + " ", enabled=False) + def test_constructor_errors_name_the_argument_they_reject(self): + overlong = "x" * (MAX_TAG_LENGTH + 1) + cases = ( + ("base_url", lambda: TraceClient(" ", "MyGame", "1.2.3")), + ("application", lambda: TraceClient(self.base_url, "", "1.2.3")), + ("version", lambda: TraceClient(self.base_url, "MyGame", " ")), + ("version", lambda: TraceClient(self.base_url, "MyGame", overlong)), + ("install_id", lambda: TraceClient(self.base_url, "MyGame", "1.2.3", install_id=overlong)), + ) + for argument, construct in cases: + with self.assertRaises(ValueError) as raised: + construct() + self.assertTrue(str(raised.exception).startswith(argument + " "), + "the only raising path should say which argument was wrong: %s" % raised.exception) + with self.assertRaises(ValueError) as raised: + TraceClient(self.base_url, "MyGame", overlong) + self.assertIn(str(MAX_TAG_LENGTH), str(raised.exception), "an overlong value names the limit") + + def test_a_value_that_is_not_a_string_is_rejected_by_the_argument_it_was_given_for(self): + cases = ( + ("base_url", "int", lambda **kw: TraceClient(5, "MyGame", "1.2.3", **kw)), + ("application", "int", lambda **kw: TraceClient(self.base_url, 5, "1.2.3", **kw)), + ("application", "bytes", lambda **kw: TraceClient(self.base_url, b"MyGame", "1.2.3", **kw)), + ("version", "float", lambda **kw: TraceClient(self.base_url, "MyGame", 1.4, **kw)), + ("key", "int", lambda **kw: TraceClient(self.base_url, "MyGame", "1.2.3", key=123, **kw)), + ("install_id", "int", lambda **kw: TraceClient(self.base_url, "MyGame", "1.2.3", install_id=7, **kw)), + ) + for argument, type_name, construct in cases: + for options in ({}, {"enabled": False}): + with self.assertRaises(ValueError, msg=argument) as raised: + construct(**options) + self.assertEqual("%s must be a string, not %s" % (argument, type_name), str(raised.exception), + "the only raising path should say which argument was wrong") + + def test_arguments_are_checked_before_the_environment_opt_out(self): + with mock.patch.dict(os.environ, {"DO_NOT_TRACK": "1"}): + with self.assertRaises(ValueError, msg="a bad argument should not hide behind the opt-out") as raised: + TraceClient(self.base_url, "MyGame", 1.4, key="k") + self.assertEqual("version must be a string, not float", str(raised.exception)) + with self.assertRaises(ValueError, msg="a missing argument should not hide behind the opt-out"): + TraceClient(self.base_url, "", "1.2.3", key="k") + + def test_a_rejected_key_is_not_repeated_in_the_error(self): + with self.assertRaises(ValueError) as raised: + TraceClient(self.base_url, "MyGame", "1.2.3", key=123456789) + self.assertNotIn("123456789", str(raised.exception), "an error can end up in a log; a key should not") + + def test_an_empty_value_of_another_type_keeps_its_old_meaning(self): + # These never reached .strip(), so a program passing one already ran. + for empty in (0, False, []): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key=empty, enabled=False) + self.assertEqual("config", client.disabled_reason, repr(empty)) + self.assertEqual("no key", TraceClient(self.base_url, "MyGame", "1.2.3", key=empty).disabled_reason) + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id=empty) + self.assertIsNone(client.install_id, repr(empty)) + client.close() + with self.assertRaises(ValueError, msg=repr(empty)) as raised: + TraceClient(self.base_url, "MyGame", empty) + self.assertEqual("version is required", str(raised.exception)) + + def test_the_sender_is_one_daemon_thread_named_after_the_application(self): + before = set(threading.enumerate()) + client = TraceClient(self.base_url, " MyGame ", "1.2.3", key="k") + try: + started = [t for t in threading.enumerate() if t not in before] + self.assertEqual(1, len(started), "one sender thread per client") + sender = started[0] + self.assertTrue(sender.daemon, "a daemon thread never keeps the host program from exiting") + self.assertEqual("trace-client/MyGame", sender.name, "named after the trimmed application") + finally: + client.close() + self.assertFalse(sender.is_alive(), "close() stops it") + + def test_a_disabled_client_starts_no_thread(self): + before = set(threading.enumerate()) + clients = (TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled=False), + TraceClient(self.base_url, "MyGame", "1.2.3"), + TraceClient.disabled()) + started = [t for t in threading.enumerate() if t not in before] + self.assertEqual([], started, "a disabled client costs nothing") + for client in clients: + client.close() + def test_report_tags_a_command_with_the_program_version_trimmed(self): client = TraceClient(self.base_url, "MyGame", " 2.0.0-SNAPSHOT ", key="k") client.report("command", tags={"name": "home"}) @@ -318,6 +606,14 @@ def test_report_never_modifies_the_callers_tags(self): self.assertEqual({"name": "home", "version": "1.2.3"}, json.loads(self.capture.requests[0]["body"])["tags"]) + def test_report_drops_none_tags_and_stringifies_the_rest_before_adding_the_version(self): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.report("command", tags={"version": None, None: "orphan", "count": 7}) + self.assertTrue(self.capture.arrived.wait(5)) + self.assertEqual({"count": "7", "version": "1.2.3"}, json.loads(self.capture.requests[0]["body"])["tags"], + "a None version tag does not suppress the program's own version") + client.close() + def test_with_version_never_modifies_the_callers_mapping(self): from trace_client import _with_version tags = {"name": "home"} @@ -331,6 +627,45 @@ def test_json_drops_nan_and_none_tags(self): body = json.loads(_json("App", "n", float("nan"), {"ok": "line\nbreak", "none": None, None: "x"})) self.assertEqual({"application": "App", "name": "n", "tags": {"ok": "line\nbreak"}}, body) + def test_json_drops_infinite_values_but_keeps_zero(self): + from trace_client import _json + for infinite in (float("inf"), float("-inf")): + self.assertNotIn("value", json.loads(_json("App", "n", infinite, None)), + "JSON has no infinity; sending one would be rejected by the server") + self.assertEqual(0, json.loads(_json("App", "n", 0, None))["value"], "zero is a value, not a missing one") + + def test_json_leaves_out_a_value_that_is_not_a_real_number_but_keeps_the_event(self): + from trace_client import _json + for odd in ("3", "", True, False, b"3", [1], object(), 1j): + body = json.loads(_json("App", "n", odd, None)) + self.assertEqual({"application": "App", "name": "n"}, body, + "%r is not a number the server can take; the event goes without it" % (odd,)) + + def test_json_sends_other_real_numbers_as_floats(self): + from trace_client import _json + self.assertEqual(1.5, json.loads(_json("App", "n", decimal.Decimal("1.5"), None))["value"]) + self.assertEqual(0.25, json.loads(_json("App", "n", fractions.Fraction(1, 4), None))["value"]) + self.assertEqual(7, json.loads(_json("App", "n", 7, None))["value"]) + for unsendable in (decimal.Decimal("NaN"), decimal.Decimal("sNaN"), decimal.Decimal("1e400"), + fractions.Fraction(10 ** 400)): + self.assertNotIn("value", json.loads(_json("App", "n", unsendable, None)), + "%r has no finite float; it is left out rather than raising" % (unsendable,)) + + def test_report_with_a_decimal_value_still_delivers_the_event(self): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + try: + client.report("score", decimal.Decimal("2.5")) + self.assertTrue(self.capture.arrived.wait(5), "a Decimal must not cost the event its place") + finally: + client.close() + self.assertEqual(2.5, json.loads(self.capture.requests[0]["body"])["value"]) + + def test_json_omits_tags_that_are_empty_after_cleaning_and_stringifies_the_rest(self): + from trace_client import _json + self.assertNotIn("tags", json.loads(_json("App", "n", None, {"none": None}))) + self.assertNotIn("tags", json.loads(_json("App", "n", None, {}))) + self.assertEqual({"1": "2", "on": "True"}, json.loads(_json("App", "n", None, {1: 2, "on": True}))["tags"]) + def test_queue_is_bounded_and_drops_rather_than_grows(self): self.capture.release.clear() # hold the sender on the first report client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") @@ -343,6 +678,36 @@ def test_queue_is_bounded_and_drops_rather_than_grows(self): self.capture.release.set() client.close() + def test_a_dropped_report_is_logged_at_debug_with_its_name(self): + self.capture.release.clear() # hold the sender on the first report + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.report("filler") + # Wait for the sender to take it: if it woke up between the last filler + # and the overflow, the overflow would find a free slot and not be dropped. + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and not client._queue.empty(): + time.sleep(0.01) + self.assertTrue(client._queue.empty(), "the sender should have picked up the first report") + for _ in range(TraceClient.QUEUE_CAPACITY): + client.report("filler") + client.report("overflow-event") + dropped = [r for r in self.log if r.getMessage() == "[trace] queue full, dropped overflow-event"] + self.assertEqual(1, len(dropped), + "a drop names the event it dropped: %r" % [r.getMessage() for r in self.log]) + self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log), "drops are logged at DEBUG only") + self.capture.release.set() + client.close() + + def test_reports_are_delivered_in_the_order_they_were_made(self): + # One sender thread, one request at a time: the server sees events in + # the order the program reported them. + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + for i in range(20): + client.report("step", tags={"n": str(i)}) + client.close() + self.assertEqual([str(i) for i in range(20)], + [json.loads(r["body"])["tags"]["n"] for r in self.capture.requests]) + def test_close_sends_what_was_just_queued_before_stopping(self): # A CLI reports once and exits at once. Without draining, the event # races the sender thread and is lost a good fraction of the time; @@ -362,6 +727,20 @@ def test_close_still_returns_within_the_timeout_when_the_server_hangs(self): self.assertLess(time.monotonic() - before, 2.0, "draining must be bounded by the timeout") self.capture.release.set() + def test_reports_still_queued_at_the_timeout_are_sent_after_close_returns(self): + self.capture.release.clear() # hold the sender on the first report + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + thread = client._thread + client.report("seq", tags={"n": "0"}) + client.report("seq", tags={"n": "1"}) + client.close(timeout=0.5) + self.assertTrue(thread.is_alive(), "close() returned on its timeout with the sender still busy") + self.capture.release.set() + thread.join(30) + self.assertFalse(thread.is_alive(), "the sender stops once it reaches what close() queued behind them") + self.assertEqual(["0", "1"], [json.loads(r["body"])["tags"]["n"] for r in self.capture.requests], + "reports queued before close() are not discarded when its timeout runs out") + def test_close_is_prompt_and_idempotent(self): client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") client.report("startup") @@ -371,6 +750,58 @@ def test_close_is_prompt_and_idempotent(self): self.assertLess(time.monotonic() - before, TraceClient.TIMEOUT_SECONDS + 1) self.assertFalse(client.enabled) + def test_report_after_close_sends_nothing(self): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + client.close() + client.report("late") # must not raise + self.assertFalse(self.capture.arrived.wait(0.3), "a closed client should send nothing") + self.assertEqual([], self.capture.requests) + + def test_close_on_a_full_queue_drops_the_oldest_report_and_still_stops_the_sender(self): + self.capture.release.clear() # hold the sender on the first report + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + thread = client._thread + client.report("seq", tags={"n": "0"}) + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and not client._queue.empty(): + time.sleep(0.01) # until the sender has taken it and is waiting on the server + self.assertTrue(client._queue.empty(), "the sender should have picked up the first report") + for n in range(1, TraceClient.QUEUE_CAPACITY + 2): # one more than fits + client.report("seq", tags={"n": str(n)}) + before = time.monotonic() + client.close(timeout=0.5) + self.assertLess(time.monotonic() - before, 2.0, "close() must stay bounded with a full queue") + self.capture.release.set() + thread.join(30) + self.assertFalse(thread.is_alive(), "the sentinel must reach the sender even when the queue was full") + sent = [json.loads(r["body"])["tags"]["n"] for r in self.capture.requests] + self.assertEqual(TraceClient.QUEUE_CAPACITY, len(sent), "in flight + capacity - the displaced oldest") + self.assertNotIn("1", sent, "the oldest queued report makes room for the sentinel") + self.assertIn("0", sent) + self.assertIn(str(TraceClient.QUEUE_CAPACITY), sent) + + def test_the_report_close_drops_from_a_full_queue_is_logged_at_debug(self): + self.capture.release.clear() # hold the sender on the first report + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") + thread = client._thread + client.report("in-flight") + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and not client._queue.empty(): + time.sleep(0.01) # until the sender has taken it and is waiting on the server + self.assertTrue(client._queue.empty(), "the sender should have picked up the first report") + client.report("oldest-queued") + for _ in range(TraceClient.QUEUE_CAPACITY - 1): + client.report("filler") + client.close(timeout=0.5) + dropped = [r for r in self.log if r.getMessage().startswith("[trace] queue full at close, dropped ")] + self.assertEqual(1, len(dropped), + "the report close() displaces is logged, like every other drop: %r" + % [r.getMessage() for r in self.log]) + self.assertIn("oldest-queued", dropped[0].getMessage(), "the log names the report it dropped") + self.assertEqual(logging.DEBUG, dropped[0].levelno, "drops are logged at DEBUG only") + self.capture.release.set() + thread.join(30) + # -- the per-installation ID ------------------------------------------ def _tmpdir(self): @@ -415,6 +846,23 @@ def test_install_id_from_file_replaces_a_file_with_no_valid_line(self): made = TraceClient.install_id_from_file(path) self.assertEqual(made, TraceClient.install_id_from_file(path)) + def test_install_id_from_file_writes_an_id_into_an_existing_empty_file(self): + path = os.path.join(self._tmpdir(), "install-id") + open(path, "w", encoding="utf-8").close() + made = TraceClient.install_id_from_file(path) + self.assertEqual(str(uuid.UUID(made)), made) + with open(path, encoding="utf-8") as stored: + self.assertEqual(made + "\n", stored.read(), "an empty file holds no ID, so one is written") + + def test_install_id_file_accepts_a_path_object(self): + path = pathlib.Path(self._tmpdir()) / "nested" / "install-id" + made = TraceClient.install_id_from_file(path) + self.assertEqual(made + "\n", path.read_text(encoding="utf-8"), "os.PathLike is written like a str") + self.assertEqual(made, TraceClient.install_id_from_file(path), "and read back like one") + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id_file=path) + self.assertEqual(made, client.install_id, "the constructor takes the same os.PathLike") + self.assertEqual({"version": "1.2.3", "install": made}, self._sent_tags(client)) + def test_unwritable_install_id_file_yields_an_in_memory_id_and_never_raises(self): # A path under a regular file cannot be created, even as root. blocker = os.path.join(self._tmpdir(), "a-file") @@ -440,13 +888,42 @@ def test_install_id_from_file_never_raises_for_a_bad_path(self): made = TraceClient.install_id_from_file(path) self.assertEqual(str(uuid.UUID(made)), made, repr(path)) + def test_install_id_from_file_takes_an_id_of_exactly_the_tag_length_limit(self): + path = os.path.join(self._tmpdir(), "install-id") + longest = "x" * MAX_TAG_LENGTH + with open(path, "w", encoding="utf-8") as f: + f.write("has/a/slash\nhas a space\n" + longest + "\n") + self.assertEqual(longest, TraceClient.install_id_from_file(path), + "lines with other characters are skipped; %d characters is still an ID" % MAX_TAG_LENGTH) + with open(path, encoding="utf-8") as f: + self.assertTrue(f.read().startswith("has/a/slash\n"), "a file with an ID is never rewritten") + + def test_install_id_file_failures_are_logged_at_debug_only(self): + TraceClient.install_id_from_file(self._tmpdir()) # a directory cannot be read as a file + missing = os.path.join(self._tmpdir(), "install-id") # absent, so it is written -- and that fails + with mock.patch("trace_client.os.makedirs", side_effect=PermissionError("read-only")): + TraceClient.install_id_from_file(missing) + self.assertFalse(os.path.exists(missing)) + messages = [record.getMessage() for record in self.log] + self.assertEqual(2, len(messages), messages) + self.assertTrue(messages[0].startswith("[trace] could not read install ID file "), messages[0]) + self.assertTrue(messages[1].startswith("[trace] could not write install ID file "), messages[1]) + self.assertEqual({logging.DEBUG}, {record.levelno for record in self.log}, + "an ID problem is never louder than DEBUG") + + def test_explicit_install_id_is_sent_as_given_without_the_files_character_rule(self): + # The [A-Za-z0-9_.-] rule only picks an ID out of a file; an ID the + # program passes itself is only trimmed and length-checked. + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id=" mine/with spaces ") + self.assertEqual("mine/with spaces", client.install_id) + self.assertEqual({"version": "1.2.3", "install": "mine/with spaces"}, self._sent_tags(client)) + def test_a_disabled_client_never_makes_up_or_writes_an_install_id(self): directory = self._tmpdir() path = os.path.join(directory, "install-id") - os.environ["DO_NOT_TRACK"] = "1" - by_environment = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id_file=path, - install_id="explicit") - del os.environ["DO_NOT_TRACK"] + with mock.patch.dict(os.environ, {"DO_NOT_TRACK": "1"}): + by_environment = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id_file=path, + install_id="explicit") by_config = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled=False, install_id_file=path) by_no_key = TraceClient(self.base_url, "MyGame", "1.2.3", install_id_file=path) for client in (by_environment, by_config, by_no_key): @@ -464,7 +941,9 @@ def test_explicit_install_id_is_trimmed_sent_and_wins_over_the_file(self): def test_blank_install_id_is_none_and_an_overlong_one_is_rejected(self): for blank in (None, "", " "): - self.assertIsNone(TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id=blank).install_id) + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id=blank) + self.assertIsNone(client.install_id, repr(blank)) + client.close() with self.assertRaises(ValueError): TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id="x" * (MAX_TAG_LENGTH + 1)) with self.assertRaises(ValueError, msg="rejected even on a disabled client, like the version"): @@ -479,6 +958,15 @@ def test_an_events_own_install_tag_wins(self): self.assertEqual({"install": "theirs", "version": "1.2.3"}, self._sent_tags(client, tags=tags)) self.assertEqual({"install": "theirs"}, tags, "the caller's tags are never modified") + def test_a_none_install_tag_does_not_suppress_the_installation_id(self): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id="mine") + self.assertEqual({"version": "1.2.3", "install": "mine"}, self._sent_tags(client, tags={"install": None}), + "a None tag is left out, so the client's own ID takes its place, as with version") + self.capture.arrived.clear() + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id="mine") + self.assertEqual({"version": "1.2.3", "install": "7"}, self._sent_tags(client, tags={"install": 7}), + "any other value is the event's own, sent as a string, and wins") + def test_install_tag_never_pushes_an_event_past_the_tag_cap(self): client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", install_id="mine") full = {"t%d" % i: "v" for i in range(MAX_TAGS - 1)} # plus version = MAX_TAGS diff --git a/tests/test_usage_reporting.py b/tests/test_usage_reporting.py index 80a88ce..dc259bc 100644 --- a/tests/test_usage_reporting.py +++ b/tests/test_usage_reporting.py @@ -106,10 +106,21 @@ def test_first_run_under_an_environment_opt_out_says_reporting_is_off(self): self.assertEqual([FIRST_RUN_NOTICE_OFF_BY_ENVIRONMENT], self.logged) self.assertIn(DETAILS_URL, FIRST_RUN_NOTICE_OFF_BY_ENVIRONMENT) - # the environment never rewrites the settings: the block is still the default - self.assertEqual({"enabled": True, "endpoint": DEFAULT_ENDPOINT, "key": DEFAULT_KEY}, section) + # the first run records the environment's opt-out, so a later run without it stays off + self.assertEqual({"enabled": False, "endpoint": DEFAULT_ENDPOINT, "key": DEFAULT_KEY}, section) self.assertEqual({"usage_reporting": section}, self.readSettingsFile()) + def test_first_run_under_an_environment_opt_out_stays_off_without_the_variable(self): + with patch.dict(os.environ, {"TRACE_USAGE_REPORTING": "off"}): + loadSettings(self.settingsFile, self.log) + + client = buildClient(loadSettings(self.settingsFile, self.log), self.log) + try: + self.assertFalse(client.enabled) + self.assertEqual("config", client.disabled_reason) + finally: + client.close() + def test_existing_settings_without_the_block_are_preserved(self): with open(self.settingsFile, "w") as f: json.dump({"other": {"kept": 1}}, f) @@ -132,29 +143,48 @@ def test_opt_out_is_respected_and_not_rewritten(self): self.assertEqual([], self.logged) self.assertEqual({"usage_reporting": {"enabled": False}}, self.readSettingsFile()) - def test_a_block_that_is_not_an_object_is_replaced_by_the_defaults(self): - # Characterizes current behaviour: only an object counts as the block, so a value - # such as false is overwritten with reporting turned on and the notice shown again. + def test_a_block_that_is_not_an_object_is_read_as_the_switch_and_not_rewritten(self): + # "usage_reporting": false used to be overwritten with the default block (on) for name, value in (("false", False), ("string", "off"), ("list", []), ("null", None)): with self.subTest(name): self.logged.clear() + settings = {"usage_reporting": value, "other": {"kept": 1}} with open(self.settingsFile, "w") as f: - json.dump({"usage_reporting": value, "other": {"kept": 1}}, f) + json.dump(settings, f) section = loadSettings(self.settingsFile, self.log) + client = buildClient(section, self.log) + try: + self.assertFalse(client.enabled) + self.assertEqual("config", client.disabled_reason) + finally: + client.close() + self.assertEqual([], self.logged) + self.assertEqual(settings, self.readSettingsFile()) + + def test_a_block_that_is_not_an_object_can_still_turn_reporting_on(self): + with open(self.settingsFile, "w") as f: + json.dump({"usage_reporting": True}, f) - self.assertEqual({"enabled": True, "endpoint": DEFAULT_ENDPOINT, "key": DEFAULT_KEY}, section) - self.assertEqual([FIRST_RUN_NOTICE], self.logged) - self.assertEqual({"usage_reporting": section, "other": {"kept": 1}}, self.readSettingsFile()) + client = buildClient(loadSettings(self.settingsFile, self.log), self.log) + try: + self.assertTrue(client.enabled) + finally: + client.close() - def test_enabled_is_read_by_truthiness(self): - # Characterizes current behaviour: enabled is passed through bool(), so the string - # "false" turns reporting on, while 0, "" and null turn it off like false does. + def test_enabled_fails_closed(self): + # enabled used to go through bool(), so the string "false" turned reporting on; + # now only true or an "on" string does cases = ( ("missing", {}, True), - ("string false", {"enabled": "false"}, True), - ("string off", {"enabled": "off"}, True), - ("one", {"enabled": 1}, True), + ("true", {"enabled": True}, True), + ("string true", {"enabled": "true"}, True), + ("string on", {"enabled": " ON "}, True), + ("string false", {"enabled": "false"}, False), + ("string off", {"enabled": "off"}, False), + ("string no", {"enabled": "no"}, False), + ("typo", {"enabled": "ture"}, False), + ("one", {"enabled": 1}, False), ("zero", {"enabled": 0}, False), ("empty string", {"enabled": ""}, False), ("null", {"enabled": None}, False), diff --git a/trace_client.py b/trace_client.py index ddca37d..c24d598 100644 --- a/trace_client.py +++ b/trace_client.py @@ -1,4 +1,4 @@ -"""trace-client 0.4.1 -- https://github.com/Stephenson-Software/trace-client-python +"""trace-client 0.5.0 -- https://github.com/Stephenson-Software/trace-client-python One call to report that a program was used. Copy this file into a project as is, or vendor the package; either way there is nothing else to add. Standard @@ -10,8 +10,10 @@ """ from __future__ import annotations +import decimal import json import logging +import numbers import os import queue import re @@ -21,27 +23,31 @@ import uuid from typing import Dict, Mapping, Optional, Union -__version__ = "0.4.1" +__version__ = "0.5.0" _LOG = logging.getLogger("trace") #: Environment variables that turn reporting off for every program using a -#: trace client, checked before the program's own setting. Set -#: ``TRACE_USAGE_REPORTING=off`` (also ``false``, ``0``, ``no``; case does not -#: matter) or ``DO_NOT_TRACK=1`` (also ``true``, ``yes``; see -#: https://consoledonottrack.com). +#: trace client, checked before the program's own setting. Both fail closed: +#: ``TRACE_USAGE_REPORTING`` set to anything but blank, ``true``, ``on``, +#: ``yes`` or ``1`` turns reporting off (so ``off``, ``false``, ``0``, ``no``, +#: ``disabled``, a typo, ...), and so does ``DO_NOT_TRACK`` set to anything +#: but blank, ``0``, ``false``, ``off`` or ``no`` (so ``1``, ``true``, +#: ``yes``, ...; see https://consoledonottrack.com). Case and surrounding +#: space do not matter. ENV_TRACE_USAGE_REPORTING = "TRACE_USAGE_REPORTING" ENV_DO_NOT_TRACK = "DO_NOT_TRACK" -_OFF_VALUES = frozenset(("off", "false", "0", "no")) -_DO_NOT_TRACK_VALUES = frozenset(("1", "true", "yes")) +_ON_VALUES = frozenset(("true", "on", "yes", "1")) +_NEGATIVE_VALUES = frozenset(("false", "off", "no", "0")) #: The values :attr:`TraceClient.disabled_reason` can take. First match wins. REASON_ENVIRONMENT = "environment" REASON_CONFIG = "config" REASON_NO_KEY = "no key" -#: The longest a program version may be, after trimming: the trace server's -#: limit on a tag value. +#: The longest a tag value the client sets itself -- the program version, the +#: installation ID -- may be, after trimming: the trace server's limit on a +#: tag value. MAX_TAG_LENGTH = 255 #: The most tags one event carries: the trace server's limit. The ``install`` @@ -54,18 +60,58 @@ # What install_id_from_file accepts as an ID on a line of its file. _INSTALL_ID_LINE = re.compile(r"^[A-Za-z0-9_.-]{1,%d}$" % MAX_TAG_LENGTH) +# What the User-Agent header cannot carry: everything but printable Latin-1. +_NOT_IN_A_HEADER = re.compile(r"[^\x20-\x7e\xa0-\xff]") + + +class _RedirectsNotFollowed(urllib.request.HTTPRedirectHandler): + """Declines every redirect, so the redirect itself is the answer. Following + one would re-send the key to whatever host ``Location`` names, and a 301, + 302 or 303 would turn the POST into an empty GET that loses the event + anyway. trace-client-java does not follow redirects either.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +# Every report goes through this opener rather than urlopen: urlopen follows +# redirects, and install_opener would change the host program's urlopen too. +_OPENER = urllib.request.build_opener(_RedirectsNotFollowed) + def environment_opts_out(environ: Optional[Mapping[str, str]] = None) -> bool: - """Whether the environment asks for usage reporting to be off, via - ``TRACE_USAGE_REPORTING=off`` or ``DO_NOT_TRACK=1``. Only the listed - values count; anything else (including an empty value) leaves the - program's own setting in charge.""" - env = os.environ if environ is None else environ - if env.get(ENV_TRACE_USAGE_REPORTING, "").strip().lower() in _OFF_VALUES: + """Whether the environment asks for usage reporting to be off. Fails + closed: ``TRACE_USAGE_REPORTING`` set to anything but blank or a clear + "on" (``true``, ``on``, ``yes``, ``1``), or ``DO_NOT_TRACK`` set to + anything but blank or a clear "no" (``0``, ``false``, ``off``, ``no``), + opts out; case and surrounding space do not matter. An environment that + cannot be read -- or a value that is not a string -- opts out too: it may + hold ``DO_NOT_TRACK=1``. Never raises.""" + try: + env = os.environ if environ is None else environ + usage_reporting = (env.get(ENV_TRACE_USAGE_REPORTING) or "").strip().lower() + if usage_reporting and usage_reporting not in _ON_VALUES: + return True + do_not_track = (env.get(ENV_DO_NOT_TRACK) or "").strip().lower() + return bool(do_not_track) and do_not_track not in _NEGATIVE_VALUES + except Exception: # noqa: BLE001 - an environment that cannot be read counts as opting out return True - if env.get(ENV_DO_NOT_TRACK, "").strip().lower() in _DO_NOT_TRACK_VALUES: - return True - return False + + +def allows_reporting(setting: object) -> bool: + """Whether a program's own reporting setting, as read from its + configuration, allows reporting -- for ``enabled=``. Fails closed: only + ``True``, or a string reading ``true``, ``on``, ``yes`` or ``1`` (any + case, surrounding space ignored), allows it. Anything else turns + reporting off: ``False``, ``"false"``, ``"off"``, ``"no"``, a typo, a + number, ``None`` (a missing setting), a quoted ``'"false"'``. + + Pass the raw value, e.g. ``settings.get("usage_reporting")``, rather than + ``bool(...)`` of it: ``bool("false")`` is ``True``. The constructor reads + ``enabled=`` through this function too, so ``enabled="false"`` is off.""" + if isinstance(setting, bool): + return setting + return isinstance(setting, str) and setting.strip().lower() in _ON_VALUES class TraceClient: @@ -89,7 +135,10 @@ class TraceClient: does nothing and costs nothing. So does the environment: the constructor checks ``TRACE_USAGE_REPORTING=off`` and ``DO_NOT_TRACK=1`` before it looks at ``enabled``, so a user can switch off every trace-reporting - program at once. :attr:`disabled_reason` says which of those applied + program at once. Every switch fails closed: a value that does not clearly + mean "on" turns reporting off (see :func:`environment_opts_out` and + :func:`allows_reporting`), and nothing in this client turns a switch + back on. :attr:`disabled_reason` says which of those applied (``"environment"``, ``"config"`` or ``"no key"``; ``None`` when on) so the program can say so in its notice. Programs that run on other people's machines should expose that switch in their settings and say @@ -113,7 +162,8 @@ class TraceClient: :: trace = TraceClient("https://trace.example.org", "roam", __version__, - key=settings.usage_key, enabled=settings.usage_reporting) + key=settings.usage_key, + enabled=allows_reporting(settings.usage_reporting)) trace.report("startup") ... trace.close() # on shutdown @@ -123,7 +173,7 @@ class TraceClient: TIMEOUT_SECONDS = 5.0 def __init__(self, base_url: str, application: str, version: str, *, key: Optional[str] = None, - enabled: bool = True, install_id: Optional[str] = None, + enabled: Union[bool, str, None] = True, install_id: Optional[str] = None, install_id_file: Optional[Union[str, "os.PathLike[str]"]] = None) -> None: """A client for the program named ``application``, at ``version``, reporting to the trace server at ``base_url``. The version is sent as @@ -137,7 +187,18 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option longer than :data:`MAX_TAG_LENGTH` characters is a :class:`ValueError`. ``install_id_file`` is a path to load it from (or create it in) with :meth:`install_id_from_file`, only when the - client is enabled; an explicit ``install_id`` wins over it.""" + client is enabled; an explicit ``install_id`` wins over it. + + A value that is not a string for ``base_url``, ``application``, + ``version``, ``key`` or ``install_id`` is a :class:`ValueError` naming + the argument, even on a client that would be disabled: a settings + file that reads ``version: 1.4`` as a number should say so. An empty + one (``0``, ``False``, ``[]``) still means no value, as it did before + that check: no key, no ID, or " is required".""" + for argument, given in (("base_url", base_url), ("application", application), ("version", version), + ("key", key), ("install_id", install_id)): + if given and not isinstance(given, str): + raise ValueError("%s must be a string, not %s" % (argument, type(given).__name__)) if not base_url or not base_url.strip(): raise ValueError("base_url is required") if not application or not application.strip(): @@ -157,12 +218,13 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option self._thread: Optional[threading.Thread] = None #: Why this client reports nothing: ``"environment"`` (the #: ``TRACE_USAGE_REPORTING`` / ``DO_NOT_TRACK`` variables), - #: ``"config"`` (``enabled=False``) or ``"no key"``; ``None`` when it + #: ``"config"`` (``enabled`` not ``True`` or an "on" string -- see + #: :func:`allows_reporting`) or ``"no key"``; ``None`` when it #: reports. Decided once, here, in that order of precedence. self.disabled_reason: Optional[str] = None if environment_opts_out(): self.disabled_reason = REASON_ENVIRONMENT - elif not enabled: + elif not allows_reporting(enabled): self.disabled_reason = REASON_CONFIG elif not self._key: self.disabled_reason = REASON_NO_KEY @@ -245,7 +307,10 @@ def enabled(self) -> bool: def report(self, name: str, value: Optional[float] = None, tags: Optional[Mapping[str, str]] = None) -> None: """Report that ``name`` happened, with an optional numeric value and - optional string tags. Returns immediately; see the class docstring.""" + optional string tags. Returns immediately; see the class docstring. + A blank ``name`` sends nothing. A ``value`` that is NaN, infinite or + not a real number (a string, a bool), and any tag whose key or value + is ``None``, is left out of the event; the event is still sent.""" if self._queue is None: return try: @@ -265,8 +330,13 @@ def close(self, timeout: float = TIMEOUT_SECONDS) -> None: and then exits within milliseconds -- a CLI, a short script -- would otherwise lose its one event to the race between queueing it and the sender thread picking it up. The bound still holds: an unreachable - server costs at most ``timeout``, never a hang. Safe to call more than - once, and on a disabled client.""" + server costs at most ``timeout``, never a hang. Reports still queued + when ``timeout`` runs out are not discarded: the daemon thread keeps + sending them after ``close()`` returns, then stops, and whatever it + has not sent when the program exits is lost. On a full queue the + oldest queued report is dropped (logged at DEBUG) to make room for + the signal that stops the thread. Safe to call more than once, and + on a disabled client.""" if self._queue is None or self._thread is None: return q, thread = self._queue, self._thread @@ -278,7 +348,8 @@ def close(self, timeout: float = TIMEOUT_SECONDS) -> None: # the 257th. Drop the oldest to make room -- one lost report beats a # thread that never stops. try: - q.get_nowait() + dropped = q.get_nowait() + _LOG.debug("[trace] queue full at close, dropped %s", dropped) q.put_nowait(None) except (queue.Empty, queue.Full): pass @@ -307,9 +378,9 @@ def _send(self, body: bytes) -> None: headers={ "Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + self._key, - "User-Agent": "trace-client-python/%s (%s)" % (__version__, self._application), + "User-Agent": _user_agent(self._application), }) - with urllib.request.urlopen(request, timeout=self.TIMEOUT_SECONDS) as response: + with _OPENER.open(request, timeout=self.TIMEOUT_SECONDS) as response: status = response.status response.read() except urllib.error.HTTPError as answered: @@ -325,6 +396,14 @@ def _send(self, body: bytes) -> None: _LOG.debug("[trace] trace server answered %s for %s", status, body) +def _user_agent(application: str) -> str: + """The ``User-Agent`` for ``application``. A header carries printable + Latin-1 and nothing else, and one it cannot carry stops the request, so + any other character becomes ``?`` here. The event itself keeps the exact + name: what a program is called must not cost it every report.""" + return "trace-client-python/%s (%s)" % (__version__, _NOT_IN_A_HEADER.sub("?", application)) + + def _with_version(tags: Optional[Mapping[str, str]], version: str) -> Dict[str, str]: """The event's own tags plus ``version``, unless the event already carries one. A copy; the caller's mapping is never modified.""" @@ -348,10 +427,28 @@ def _with_install(tags: Dict[str, str], install_id: Optional[str]) -> Dict[str, return merged +def _number(value: object) -> Optional[float]: + """``value`` as a number JSON can carry, or ``None`` for one it cannot: + anything that is not a real number (a string, a bool), NaN and infinity. + A ``Decimal`` or ``Fraction`` becomes a float rather than costing the + event its place: ``json.dumps`` would refuse it, and the event with it.""" + if isinstance(value, bool) or not isinstance(value, (numbers.Real, decimal.Decimal)): + return None + if type(value) not in (int, float): + try: + value = float(value) + except (OverflowError, ValueError): + return None + if value != value or value in (float("inf"), float("-inf")): + return None + return value # type: ignore[return-value] + + def _json(application: str, name: str, value: Optional[float], tags: Optional[Mapping[str, str]]) -> bytes: payload: Dict[str, object] = {"application": application, "name": name} - if value is not None and value == value and value not in (float("inf"), float("-inf")): - payload["value"] = value + number = _number(value) + if number is not None: + payload["value"] = number if tags: clean = {str(k): str(v) for k, v in tags.items() if k is not None and v is not None} if clean: diff --git a/usage_reporting.py b/usage_reporting.py index 7ce2fa3..6d45f66 100644 --- a/usage_reporting.py +++ b/usage_reporting.py @@ -3,7 +3,7 @@ import os import sys -from trace_client import TraceClient, environment_opts_out +from trace_client import TraceClient, allows_reporting, environment_opts_out # @author Daniel McCoy Stephenson # @since September 11th, 2026 @@ -34,8 +34,12 @@ ) # Shown on the first run instead when TRACE_USAGE_REPORTING=off or DO_NOT_TRACK=1 is already -# set: settings.json still gets its block, but saying reporting is on would mislead. -FIRST_RUN_NOTICE_OFF_BY_ENVIRONMENT = "Usage reporting is off (environment). Details: " + DETAILS_URL +# set: settings.json gets its block with "enabled": false, so a later run without the variable +# does not report either. +FIRST_RUN_NOTICE_OFF_BY_ENVIRONMENT = ( + 'Usage reporting is off (environment), and "usage_reporting": {"enabled": false} was written ' + "to settings.json so it stays off. Details: " + DETAILS_URL +) def firstRunNotice(): @@ -45,9 +49,9 @@ def firstRunNotice(): return FIRST_RUN_NOTICE -def defaultSettings(): +def defaultSettings(enabled=True): """The usage_reporting block written to settings.json on first run.""" - return {"enabled": True, "endpoint": DEFAULT_ENDPOINT, "key": DEFAULT_KEY} + return {"enabled": enabled, "endpoint": DEFAULT_ENDPOINT, "key": DEFAULT_KEY} def installIdFile(): @@ -99,8 +103,14 @@ def loadSettings(settingsFile=SETTINGS_FILE, log=print): section = settings.get(SETTINGS_SECTION) if isinstance(section, dict): return section - - settings[SETTINGS_SECTION] = defaultSettings() + if SETTINGS_SECTION in settings: + # "usage_reporting": false (or "off", or anything else that is not a block) is the + # switch itself: read it as such, and never write the default block (on) over it. + return {"enabled": section} + + # Under an environment opt-out the first run records "off", so a later run without the + # variable does not quietly report. + settings[SETTINGS_SECTION] = defaultSettings(enabled=not environment_opts_out()) log(firstRunNotice()) try: with open(settingsFile, "w") as f: @@ -131,7 +141,9 @@ def buildClient(section, log=print): key = os.environ.get(KEY_ENV_VAR, "").strip() or str(section.get("key") or "").strip() or DEFAULT_KEY try: return TraceClient(endpoint, APPLICATION, readVersion() or UNKNOWN_VERSION, key=key, - enabled=bool(enabled), + # not bool(): bool("false") is True. Only true or an "on" string + # reports; "false", "off", 0, null or a typo do not. + enabled=allows_reporting(enabled), install_id=os.environ.get("TRACE_INSTALL_ID"), install_id_file=installIdFile()) except ValueError as e: