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
19 changes: 14 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,22 @@ full run of the program with a 15-line fixture on stdin.
## Usage reporting

Usage reporting is on by default: Collide sends its name (`Collide`), its version and the events
`startup` (when the program starts) and `ideas-written` (when a session's ideas have been saved)
to [trace](https://github.com/Stephenson-Software/trace) at `https://trace.danielstephenson.dev`.
Nothing about you, your machine, your IP address, the keywords or the ideas is sent. The report
is made from a background thread, never blocks the program, and is dropped silently if the
service is unreachable.
`startup` (when the program starts) and `ideas-written` (when a session's ideas have been saved) to
[trace](https://github.com/Stephenson-Software/trace) at `https://trace.danielstephenson.dev`.
Every event also carries a random installation ID (the tag `install`) so installations can be
counted rather than events. Nothing about you, your machine, your IP address, the keywords or the
ideas is sent. The report is made from a background thread, never blocks the program, and is
dropped silently if the service is unreachable.

The first launch writes a `settings.json` at the repository root and prints a one-line notice.

The installation ID is a random UUID kept in a file named `trace-install-id` in the user data
directory: `~/.local/share/collide/` on Linux (or `$XDG_DATA_HOME/collide/`),
`~/Library/Application Support/collide/` on macOS and `%APPDATA%\collide\` on Windows. It
identifies no person, account or address; delete the file to get a new one. Setting the environment
variable `TRACE_INSTALL_ID` sends that value instead and leaves the file alone. The file is only
created while reporting is on, so every opt-out below also stops it.

To turn reporting off, any one of these is enough:

- `"usage_reporting": {"enabled": false}` in `settings.json`:
Expand Down
121 changes: 114 additions & 7 deletions src/trace_client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""trace-client 0.3.0 -- https://github.com/Stephenson-Software/trace-client-python
"""trace-client 0.4.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 @@ -14,12 +14,14 @@
import logging
import os
import queue
import re
import threading
import urllib.error
import urllib.request
from typing import Dict, Mapping, Optional
import uuid
from typing import Dict, Mapping, Optional, Union

__version__ = "0.3.0"
__version__ = "0.4.0"

_LOG = logging.getLogger("trace")

Expand All @@ -42,6 +44,16 @@
#: limit on a tag value.
MAX_TAG_LENGTH = 255

#: The most tags one event carries: the trace server's limit. The ``install``
#: tag is only added while an event has fewer than this.
MAX_TAGS = 32

#: The tag every event carries the installation's ID as.
INSTALL_TAG = "install"

# 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)


def environment_opts_out(environ: Optional[Mapping[str, str]] = None) -> bool:
"""Whether the environment asks for usage reporting to be off, via
Expand Down Expand Up @@ -89,6 +101,16 @@ class TraceClient:
release as well as a ``startup`` one. An event's own ``version`` tag wins
over it.

Every event also carries a random per-installation ID as the tag
``install``, so the trace server can count distinct installations rather
than raw events -- when the program supplies one: ``install_id=`` (an ID
it stores itself) or ``install_id_file=`` (a path the client loads the ID
from, or writes a new random one to; see :meth:`install_id_from_file`).
Without either, no ``install`` tag is sent and nothing is written
anywhere. Both are resolved only after the opt-outs, so a disabled client
never makes up an ID and never writes one. An event's own ``install`` tag
wins over it.

::

trace = TraceClient("https://trace.example.org", "roam", __version__,
Expand All @@ -102,11 +124,21 @@ class TraceClient:
TIMEOUT_SECONDS = 5.0

def __init__(self, base_url: str, application: str, version: str, *, key: Optional[str] = None,
enabled: bool = True) -> None:
enabled: bool = 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
the tag ``version`` on every event; a blank one, or one longer than
:data:`MAX_TAG_LENGTH` characters, is a :class:`ValueError`."""
:data:`MAX_TAG_LENGTH` characters, is a :class:`ValueError`.

``install_id`` is the installation's ID, sent as the tag ``install``
on every event. It should be random -- e.g. a :func:`uuid.uuid4` the
program stores in its own settings -- and never derived from a
person, account or address. Trimmed; ``None`` or blank means none;
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."""
if not base_url or not base_url.strip():
raise ValueError("base_url is required")
if not application or not application.strip():
Expand All @@ -115,6 +147,9 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option
raise ValueError("version is required")
if len(version.strip()) > MAX_TAG_LENGTH:
raise ValueError("version is longer than %d characters" % MAX_TAG_LENGTH)
explicit_install_id = (install_id or "").strip() or None
if explicit_install_id is not None and len(explicit_install_id) > MAX_TAG_LENGTH:
raise ValueError("install_id is longer than %d characters" % MAX_TAG_LENGTH)
self._endpoint = base_url.strip().rstrip("/") + "/api/metrics"
self._application = application.strip()
self._version = version.strip()
Expand All @@ -132,7 +167,14 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option
self.disabled_reason = REASON_CONFIG
elif not self._key:
self.disabled_reason = REASON_NO_KEY
self._install_id: Optional[str] = None
if self.disabled_reason is None:
# After the opt-outs, never before: a disabled client neither
# makes up an ID nor writes one to disk.
if explicit_install_id is not None:
self._install_id = explicit_install_id
elif install_id_file is not None:
self._install_id = TraceClient.install_id_from_file(install_id_file)
self._queue = queue.Queue(maxsize=self.QUEUE_CAPACITY)
self._thread = threading.Thread(target=self._drain, name="trace-client/" + self._application,
daemon=True)
Expand All @@ -143,6 +185,57 @@ def disabled(cls) -> "TraceClient":
"""A client that reports nothing. Useful as a default before settings are read."""
return cls("http://disabled.invalid", "disabled", "disabled", enabled=False)

@property
def install_id(self) -> Optional[str]:
"""The per-installation ID every event carries as the tag ``install``,
or ``None`` when the client is disabled or was given none (no
``install_id`` and no ``install_id_file``)."""
return self._install_id

@staticmethod
def install_id_from_file(path: Union[str, "os.PathLike[str]"]) -> str:
"""The installation's ID kept in the file at ``path``, which the
program chooses -- there is no default location. The first line that
is an ID (``[A-Za-z0-9_.-]``, at most :data:`MAX_TAG_LENGTH`
characters, surrounding whitespace ignored) is returned. If the file
does not exist or holds no such line, a new random :func:`uuid.uuid4`
is written to it (parent directories created) and returned. Delete
the file to get a new one.

Never raises: if the file exists but cannot be read, or cannot be
written, a fresh random ID is returned for this process only, and an
unreadable file is left as it is.

Called directly, this writes whatever the opt-outs say. Pass the path
as ``install_id_file=`` instead to keep the guarantee that a disabled
client writes nothing."""
fresh = str(uuid.uuid4())
try:
target = os.fspath(path)
if not target or not str(target).strip():
return fresh
try:
with open(target, "r", encoding="utf-8") as existing:
for line in existing:
candidate = line.strip()
if _INSTALL_ID_LINE.match(candidate):
return candidate
except FileNotFoundError:
pass
except Exception as failure: # noqa: BLE001 - unreadable: never overwrite it
_LOG.debug("[trace] could not read install ID file %s, using an in-memory one: %s",
target, failure)
return fresh
parent = os.path.dirname(os.path.abspath(target))
os.makedirs(parent, exist_ok=True)
with open(target, "w", encoding="utf-8") as written:
written.write(fresh + "\n")
return fresh
except Exception as failure: # noqa: BLE001 - an ID must never be the reason a program stops
_LOG.debug("[trace] could not write install ID file %s, using an in-memory one: %s",
path, failure)
return fresh

@property
def enabled(self) -> bool:
"""Whether :meth:`report` will actually send anything. ``False`` after
Expand All @@ -159,7 +252,8 @@ def report(self, name: str, value: Optional[float] = None,
try:
if not name or not name.strip():
return
body = _json(self._application, name, value, _with_version(tags, self._version))
tags = _with_install(_with_version(tags, self._version), self._install_id)
body = _json(self._application, name, value, tags)
self._queue.put_nowait(body)
except queue.Full:
_LOG.debug("[trace] queue full, dropped %s", name)
Expand Down Expand Up @@ -200,7 +294,10 @@ def _drain(self) -> None:
body = q.get()
if body is None:
return
self._send(body)
try:
self._send(body)
except Exception as failure: # noqa: BLE001 - a dead sender would leave the queue filling forever
_LOG.debug("[trace] sender failed on %s: %s", body, failure)

def _send(self, body: bytes) -> None:
try:
Expand Down Expand Up @@ -242,6 +339,16 @@ def _with_version(tags: Optional[Mapping[str, str]], version: str) -> Dict[str,
return merged


def _with_install(tags: Dict[str, str], install_id: Optional[str]) -> Dict[str, str]:
"""The tags plus ``install``, unless they already carry one, there is no
ID, or adding it would pass :data:`MAX_TAGS`. A copy when it adds."""
if install_id is None or INSTALL_TAG in tags or len(tags) >= MAX_TAGS:
return tags
merged = dict(tags)
merged[INSTALL_TAG] = install_id
return merged


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")):
Expand Down
29 changes: 26 additions & 3 deletions src/usage_reporting.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Reports that Collide was used to the trace service, and nothing else.

What is sent: the program's name (``Collide``) and version with every event -- a
``startup`` event, and an ideas-written event when a session's ideas are saved. Nothing about you, your machine, the keywords or the ideas.
``startup`` event, and an ideas-written event when a session's ideas are saved. Every event also carries a random installation ID
(tag ``install``, see ``installIdFile``) so installations can be counted rather than
events. Nothing about you, the keywords or the ideas.

Reporting is on by default. The first launch writes a ``usage_reporting``
block to ``settings.json`` and prints a one-line notice saying so and how to
Expand All @@ -15,6 +17,7 @@
import atexit
import json
import os
import sys

from trace_client import TraceClient, environment_opts_out

Expand All @@ -36,7 +39,7 @@

FIRST_RUN_NOTICE = (
"Usage reporting is on: Collide sends its name and version at startup and an ideas-written event when a session is saved to "
"https://trace.danielstephenson.dev - nothing about you, your machine, the keywords or the ideas. "
"https://trace.danielstephenson.dev, with a random installation ID - nothing about you, the keywords or the ideas. "
'Turn it off with "usage_reporting": {"enabled": false} in settings.json, or for every '
"trace-reporting program with the environment variable TRACE_USAGE_REPORTING=off. "
"Details: " + DETAILS_URL
Expand All @@ -59,6 +62,21 @@ def defaultSettings():
return {"enabled": True, "endpoint": DEFAULT_ENDPOINT, "key": DEFAULT_KEY}


def installIdFile():
"""Where this installation's random ID (the tag ``install`` on every event) is kept:
``<user data dir>/collide/trace-install-id``, the user data dir being %APPDATA% on Windows,
~/Library/Application Support on macOS and $XDG_DATA_HOME (or ~/.local/share) elsewhere.
The client only reads or creates it when reporting is on; deleting it resets the ID."""
home = os.path.expanduser("~")
if sys.platform == "win32":
base = os.environ.get("APPDATA", "").strip() or os.path.join(home, "AppData", "Roaming")
elif sys.platform == "darwin":
base = os.path.join(home, "Library", "Application Support")
else:
base = os.environ.get("XDG_DATA_HOME", "").strip() or os.path.join(home, ".local", "share")
return os.path.join(base, APPLICATION.lower(), "trace-install-id")


def loadSettings(settingsFile=SETTINGS_FILE, log=print):
"""Read the usage_reporting block from the settings file, writing the default block
(and printing the one-time notice) when the file does not have one yet.
Expand Down Expand Up @@ -97,7 +115,10 @@ def buildClient(section):

Always built through the client's constructor otherwise, which puts
TRACE_USAGE_REPORTING / DO_NOT_TRACK ahead of ``enabled`` and records why it is off in
``disabled_reason``. A missing endpoint or key falls back to the shipped default.
``disabled_reason``. A missing endpoint or key falls back to the shipped default. Every
event carries a random installation ID as ``install``: TRACE_INSTALL_ID when set, else the
one kept in installIdFile(); the client resolves both only after its opt-out checks, so a
disabled client never creates the file.
"""
if section is None:
return TraceClient.disabled()
Expand All @@ -108,6 +129,8 @@ def buildClient(section):
VERSION,
key=str(section.get("key") or DEFAULT_KEY),
enabled=bool(section.get("enabled", True)),
install_id=os.environ.get("TRACE_INSTALL_ID"),
install_id_file=installIdFile(),
)
except Exception:
return TraceClient.disabled()
Expand Down
Loading
Loading