Skip to content
Merged
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
43 changes: 28 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ on the program side is meant to stay one call. The Java counterpart is
the two speak the same wire format and make the same promises.

```python
from trace_client import TraceClient
from trace_client import TraceClient, allows_reporting

trace = TraceClient("https://trace.danielstephenson.dev", "roam", __version__,
key=settings.usage_reporting_key,
enabled=settings.usage_reporting_enabled)
enabled=allows_reporting(settings.usage_reporting_enabled))
trace.report("startup")
trace.report("world-load", tags={"kind": "procedural"})

Expand Down Expand Up @@ -68,7 +68,7 @@ in is a file next to the program's own settings:
```python
trace = TraceClient("https://trace.danielstephenson.dev", "roam", __version__,
key=settings.usage_reporting_key,
enabled=settings.usage_reporting_enabled,
enabled=allows_reporting(settings.usage_reporting_enabled),
install_id_file=os.path.join(settings_dir, "trace-install-id"))
```

Expand Down Expand Up @@ -116,18 +116,31 @@ sends nothing.

## Turning it off

Reporting is **opt-out**. Any one of these yields a client that does nothing
and costs nothing; the first that applies is the reason:

- **Environment, for every trace-reporting program at once:**
`TRACE_USAGE_REPORTING=off` (also `false`, `0`, `no`; case-insensitive) or
`DO_NOT_TRACK=1` (also `true`, `yes`; the
[consoledonottrack.com](https://consoledonottrack.com) convention). The
constructor checks these before `enabled` and the key, so they win over the
program's own setting. (It checks its arguments before either, so a bad
argument still raises `ValueError` with reporting switched off.) Any other
value, or an unset variable, leaves that setting in charge.
- **The program's own setting:** `enabled=False`.
Reporting is **opt-out**, and the person running the program always has the
last word. **Every switch fails closed:** a value that does not clearly mean
"on" — a typo, `"false"` as a string, an empty value, `None` — turns
reporting off, and nothing in this client ever turns a switch back on. Any
one of these yields a client that does nothing and costs nothing; the first
that applies is the reason:

- **Environment, for every trace-reporting program at once** (case-insensitive,
surrounding space ignored): `TRACE_USAGE_REPORTING` set to anything but
blank, `true`, `on`, `yes` or `1` (so `off`, `false`, `0`, `no`,
`disabled`, …); or `DO_NOT_TRACK` set to anything but blank, `0`, `false`,
`off` or `no` (so `1`, `true`, `yes`, …; the
[consoledonottrack.com](https://consoledonottrack.com) convention). An
environment that cannot be read counts as opting out. The constructor
checks these before `enabled` and the key, so they win over the program's
own setting. (It checks its arguments before either, so a bad argument
still raises `ValueError` with reporting switched off.) An unset or blank
variable leaves that setting in charge. `environment_opts_out()` answers
the same question for the program.
- **The program's own setting:** `enabled=` anything but `True` or a string
`true`/`on`/`yes`/`1`. Read the setting with `allows_reporting(value)`,
which fails closed the same way: `False`, `"false"`, `"off"`, a typo, a
number and `None` (a missing setting) are all off. Pass the raw value, not
`bool(value)` — `bool("false")` is `True`. The constructor reads
`enabled=` through `allows_reporting` as well, so `enabled="false"` is off.
- **No key** (or a blank one).

`client.disabled_reason` says which one applied — `"environment"`, `"config"`
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "trace-client"
version = "0.4.2"
version = "0.5.0"
description = "One call to report that a program was used, to a trace server. Standard library only, Python 3.8+."
readme = "README.md"
license = {text = "MIT"}
Expand Down
53 changes: 47 additions & 6 deletions tests/test_trace_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest import mock

from trace_client import MAX_TAG_LENGTH, MAX_TAGS, TraceClient, __version__, environment_opts_out
from trace_client import (MAX_TAG_LENGTH, MAX_TAGS, TraceClient, __version__, allows_reporting,
environment_opts_out)
from trace_client import trace_client as trace_client_module

_ENV_VARS = ("TRACE_USAGE_REPORTING", "DO_NOT_TRACK")
Expand Down Expand Up @@ -304,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")
Expand All @@ -321,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"}):
Expand All @@ -345,6 +384,8 @@ 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"}):
Expand All @@ -357,12 +398,12 @@ def test_environment_opts_out_reads_only_the_mapping_it_is_given(self):

def test_user_agent_names_the_client_version(self):
from trace_client import __version__
self.assertEqual("0.4.2", __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.2 (MyGame)", self.capture.requests[0]["user_agent"])
self.assertEqual("trace-client-python/0.5.0 (MyGame)", self.capture.requests[0]["user_agent"])

def test_every_place_the_version_is_written_agrees_with_version(self):
# A vendored copy is identified by its header, an installed one by
Expand Down
6 changes: 3 additions & 3 deletions trace_client/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""trace-client 0.4.2 -- 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 ``trace_client.py`` (this
package's single module) into a project as is, or vendor the package; either
Expand All @@ -8,8 +8,8 @@
"""
from .trace_client import (ENV_DO_NOT_TRACK, ENV_TRACE_USAGE_REPORTING, INSTALL_TAG, MAX_TAG_LENGTH,
MAX_TAGS, REASON_CONFIG, REASON_ENVIRONMENT, REASON_NO_KEY, TraceClient,
__version__, environment_opts_out)
__version__, allows_reporting, environment_opts_out)

__all__ = ["TraceClient", "__version__", "environment_opts_out", "ENV_TRACE_USAGE_REPORTING",
__all__ = ["TraceClient", "__version__", "environment_opts_out", "allows_reporting", "ENV_TRACE_USAGE_REPORTING",
"ENV_DO_NOT_TRACK", "REASON_ENVIRONMENT", "REASON_CONFIG", "REASON_NO_KEY", "MAX_TAG_LENGTH",
"MAX_TAGS", "INSTALL_TAG"]
74 changes: 52 additions & 22 deletions trace_client/trace_client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""trace-client 0.4.2 -- 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
Expand All @@ -21,19 +21,22 @@
import uuid
from typing import Dict, Mapping, Optional, Union

__version__ = "0.4.2"
__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"
Expand Down Expand Up @@ -75,16 +78,38 @@ def redirect_request(self, req, fp, code, msg, headers, newurl):


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:
Expand All @@ -108,7 +133,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
Expand All @@ -132,7 +160,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
Expand All @@ -142,7 +171,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
Expand Down Expand Up @@ -187,12 +216,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
Expand Down
Loading