diff --git a/.env.example b/.env.example index 7bb46af..88c31ae 100644 --- a/.env.example +++ b/.env.example @@ -15,15 +15,18 @@ BACKUP_INTERVAL_MS= # event, each tagged with the program version and a random installation ID # (nothing else), to the maintainers' trace service. Nothing about the users or # repositories being backed up is sent. -# Set to false to turn it off. See CONFIG.md and +# Set to false to turn it off. It fails closed: anything but true, on, yes or 1 +# (blank or a typo included) turns it off. See CONFIG.md and # https://danielstephenson.dev/usage-reporting USAGE_REPORTING_ENABLED=true # The switch every trace client honours, checked before USAGE_REPORTING_ENABLED: -# off (or false, 0, no) turns reporting off. Leave empty for "not set". +# off (or false, 0, no -- anything but true, on, yes or 1) turns reporting off. +# Leave empty for "not set". TRACE_USAGE_REPORTING= -# The https://consoledonottrack.com convention: 1 (or true, yes) turns it off too. +# The https://consoledonottrack.com convention: 1 (or true, yes -- anything but +# 0, false, off or no) turns it off too. DO_NOT_TRACK= # Pins the installation ID sent as the 'install' tag. Leave empty to have one diff --git a/CHANGELOG.md b/CHANGELOG.md index 98b981b..6c28294 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] +### Fixed + +- Usage reporting now stays off once it is turned off. `usage.reporting.enabled` / `USAGE_REPORTING_ENABLED` used to turn reporting off only for `false`: `off`, `no`, `0`, a blank value or a typo all left it on. It now fails closed and is read through the trace client's `allowsReporting` helper: only `true`, `on`, `yes` or `1` (any case) keeps reporting on, and anything else turns it off. `docker-compose.yml` now passes a blank `USAGE_REPORTING_ENABLED` through as blank (off) instead of replacing it with `true`. The vendored `TraceClient` is now trace-client-java 0.8.0, whose `TRACE_USAGE_REPORTING` and `DO_NOT_TRACK` checks fail closed too: `TRACE_USAGE_REPORTING` set to anything but blank or `true`/`on`/`yes`/`1`, `DO_NOT_TRACK` set to anything but blank or `0`/`false`/`off`/`no`, or an environment that cannot be read, turns reporting off + ### Added - Usage reporting to the maintainers' trace service: a `startup` event once per process and a `backup-completed` event when a backup run finishes, each tagged with the program version and a random installation ID (`TRACE_INSTALL_ID`, or a UUID kept in `~/.config/gh-backup/trace-install-id`) and nothing else, sent from a background thread that never delays a backup or holds up exit by more than the client's 5-second timeout. Nothing about the users, organizations or repositories being backed up is sent. On by default; a one-line notice is logged the first time it runs on a machine (recorded in `~/.config/gh-backup/usage-reporting-notice-shown`), and it is turned off with `-Dusage.reporting.enabled=false` or `USAGE_REPORTING_ENABLED=false` (`usage.reporting.endpoint` and `usage.reporting.key` are documented in `CONFIG.md`; the Docker daemon takes `USAGE_REPORTING_ENABLED` from `.env`) @@ -20,7 +24,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - Unit tests for `POST /api/backups` request validation: a missing or blank `userOrOrg`, a leading, trailing or doubled hyphen, characters outside letters, digits and hyphens, and a name longer than 39 characters each return `400 Bad Request` without starting a backup or reporting a completed one, while a 39-character name and a single inner hyphen are accepted; a successful backup reports exactly one `backup-completed` event and a failed one reports none. Before these, the `400` behavior documented in `COMMANDS.md` was untested. - Unit tests for the clone/fetch progress monitor's `backup.progress.overwrite` handling and update edge cases: overwrite mode is the default when the property is unset, `false` (or any value other than `true`) selects one line per update, progress reported before any task has begun is ignored, an update reaching or overshooting the task's total leaves the `100%` line to the end of the task, and in overwrite mode each update rewrites the current line. Before these, the system property documented in `COMMANDS.md` and `CONFIG.md` was not read by any test. - Unit tests for two `BackupService` paths that had no assertions: a repository whose directory already exists but is not a Git repository is reported as a failed update (`✗ Failed to update`, then named in the failure summary) without being cloned over or having its contents touched, while the other repositories are still backed up; and a relative `backup.directory` is resolved against the working directory and normalized, as the path printed by `status` shows. Before these, the update-failure branch was never run by a test and the relative-path test only checked that nothing was thrown. -- Unit tests for `UsageReportingService`'s value handling and no-home path: only `false` (in any case, with surrounding spaces) turns reporting off, while values such as `no`, `0` and `off` leave it on, as `COMMANDS.md` documents for `USAGE_REPORTING_ENABLED`; the version is trimmed and a missing or blank one is sent as `unknown`; the installation ID file sits next to the notice marker; and without a usable home directory there is no notice marker and no installation ID, while the `startup` event is still sent. Before these, only the `false`/blank cases and the unfiltered `@project.version@` placeholder were tested. +- Unit tests for `UsageReportingService`'s value handling and no-home path: only `true`, `on`, `yes` or `1` (in any case, with surrounding spaces) keeps reporting on, while `false`, `no`, `0`, `off`, a blank value and typos turn it off, as `COMMANDS.md` documents for `USAGE_REPORTING_ENABLED` (see Fixed); the version is trimmed and a missing or blank one is sent as `unknown`; the installation ID file sits next to the notice marker; and without a usable home directory there is no notice marker and no installation ID, while the `startup` event is still sent. Before these, only the `false`/blank cases and the unfiltered `@project.version@` placeholder were tested. ### Changed diff --git a/COMMANDS.md b/COMMANDS.md index fcf5582..ede8fe9 100644 --- a/COMMANDS.md +++ b/COMMANDS.md @@ -135,7 +135,7 @@ java -Dspring.profiles.active=web -Dserver.port=9000 -jar target/gh-backup-2.0.0 ### `-Dusage.reporting.enabled=` -**Description:** Turn usage reporting off with `false`. When on, a `startup` event and a `backup-completed` event, carrying only the program version and a random installation ID, are sent to the maintainers' trace service; see [`usage.reporting.enabled`](CONFIG.md#usagereportingenabled) for exactly what is sent and the other ways to opt out. +**Description:** Turn usage reporting off with `false` (or anything but `true`, `on`, `yes` or `1`). When on, a `startup` event and a `backup-completed` event, carrying only the program version and a random installation ID, are sent to the maintainers' trace service; see [`usage.reporting.enabled`](CONFIG.md#usagereportingenabled) for exactly what is sent and the other ways to opt out. **Default:** `true` **Example:** ```bash @@ -156,7 +156,7 @@ java -jar target/gh-backup-2.0.0-SNAPSHOT-8-8-2026.jar octocat ### `USAGE_REPORTING_ENABLED` -**Description:** Set to `false` to turn usage reporting off, the same as `-Dusage.reporting.enabled=false`. Any other value, or leaving it unset or empty, leaves reporting on. +**Description:** Set to `false` to turn usage reporting off, the same as `-Dusage.reporting.enabled=false`. It fails closed: only `true`, `on`, `yes` or `1` (any case) keeps reporting on, and any other value — `off`, `no`, `0`, empty, a typo — turns it off. Leaving it unset leaves reporting on. **Required:** No **Example:** ```bash @@ -166,7 +166,7 @@ java -jar target/gh-backup-2.0.0-SNAPSHOT-8-8-2026.jar octocat ### `TRACE_USAGE_REPORTING` and `DO_NOT_TRACK` -**Description:** The opt-outs every trace client honours, checked before gh-backup's own setting. `TRACE_USAGE_REPORTING=off` (also `false`, `0`, `no`) or `DO_NOT_TRACK=1` (also `true`, `yes`) turns usage reporting off regardless of `usage.reporting.enabled`. +**Description:** The opt-outs every trace client honours, checked before gh-backup's own setting. `TRACE_USAGE_REPORTING=off` (or any value but blank, `true`, `on`, `yes` or `1`) or `DO_NOT_TRACK=1` (or any value but blank, `0`, `false`, `off` or `no`) turns usage reporting off regardless of `usage.reporting.enabled`. **Required:** No **Example:** ```bash diff --git a/CONFIG.md b/CONFIG.md index ac66048..026adb1 100644 --- a/CONFIG.md +++ b/CONFIG.md @@ -129,7 +129,7 @@ java -Dlogging.level.root=INFO -jar target/gh-backup-2.0.0-SNAPSHOT-8-8-2026.jar **Type:** boolean **Default:** `true` -**Description:** Whether gh-backup reports that it was used to the maintainers' trace service. When on, two events are sent, both from a background thread that never blocks or delays a backup: `startup` once per process and `backup-completed` when a backup run finishes. Both carry the same two tags and nothing else: `version`, the program version, and `install`, a random installation ID that lets installations be counted rather than events. The installation ID is the value of the `TRACE_INSTALL_ID` environment variable when that is set and not blank; otherwise it is a random UUID written the first time reporting runs to `~/.config/gh-backup/trace-install-id` and reused after that (delete the file to get a new one). Nothing about the users, organizations or repositories being backed up is sent, and no usernames, hostnames, IP addresses or paths. The first time reporting runs on a machine, one `INFO` line saying so is logged, and a marker file (`~/.config/gh-backup/usage-reporting-notice-shown`) keeps it from repeating; delete that file to see the notice again. gh-backup has no settings file of its own, which is why the marker and the installation ID file live there. If the JVM has no usable home directory (`user.home` unset or blank), there is nowhere to keep the marker or the installation ID, so the notice is logged on every run and events carry no `install` tag unless `TRACE_INSTALL_ID` is set. Setting the property to `false` sends nothing, logs no notice, writes no marker, and neither reads nor writes the installation ID file. As with every other property, it can also be set in an `application.properties` next to the JAR, and it is read from a `USAGE_REPORTING_ENABLED` environment variable, which is how the Docker image is configured. Independently of this property, the environment variables every trace client honours also turn reporting off and are checked first: `TRACE_USAGE_REPORTING=off` (also `false`, `0`, `no`) and `DO_NOT_TRACK=1` (also `true`, `yes`; see https://consoledonottrack.com). Details on what trace collects and why: https://danielstephenson.dev/usage-reporting +**Description:** Whether gh-backup reports that it was used to the maintainers' trace service. When on, two events are sent, both from a background thread that never blocks or delays a backup: `startup` once per process and `backup-completed` when a backup run finishes. Both carry the same two tags and nothing else: `version`, the program version, and `install`, a random installation ID that lets installations be counted rather than events. The installation ID is the value of the `TRACE_INSTALL_ID` environment variable when that is set and not blank; otherwise it is a random UUID written the first time reporting runs to `~/.config/gh-backup/trace-install-id` and reused after that (delete the file to get a new one). Nothing about the users, organizations or repositories being backed up is sent, and no usernames, hostnames, IP addresses or paths. The first time reporting runs on a machine, one `INFO` line saying so is logged, and a marker file (`~/.config/gh-backup/usage-reporting-notice-shown`) keeps it from repeating; delete that file to see the notice again. gh-backup has no settings file of its own, which is why the marker and the installation ID file live there. If the JVM has no usable home directory (`user.home` unset or blank), there is nowhere to keep the marker or the installation ID, so the notice is logged on every run and events carry no `install` tag unless `TRACE_INSTALL_ID` is set. Setting the property to `false` — or to anything but `true`, `on`, `yes` or `1` (any case), blank or a typo included, since it fails closed — sends nothing, logs no notice, writes no marker, and neither reads nor writes the installation ID file. As with every other property, it can also be set in an `application.properties` next to the JAR, and it is read from a `USAGE_REPORTING_ENABLED` environment variable, which is how the Docker image is configured. Independently of this property, the environment variables every trace client honours also turn reporting off and are checked first: `TRACE_USAGE_REPORTING=off` (or any value but blank, `true`, `on`, `yes` or `1`) and `DO_NOT_TRACK=1` (or any value but blank, `0`, `false`, `off` or `no`; see https://consoledonottrack.com). Details on what trace collects and why: https://danielstephenson.dev/usage-reporting **Override at runtime:** ```bash @@ -189,9 +189,9 @@ When the image built from the included `Dockerfile` is used, the container alway | `BACKUP_INTERVAL_MS` | `backup.scheduled.interval.ms` | *(empty)* | Delay between scheduled backups, in milliseconds. Passed to the application only when non-empty; when empty, the default of `86400000` (24 hours) from `application-daemon.properties` applies. | | `BACKUP_DIRECTORY` | `backup.directory` | `/backups` | Backup directory inside the container. | | `GITHUB_TOKEN` | *(read directly by the application)* | *(unset)* | GitHub personal access token, as described above. | -| `USAGE_REPORTING_ENABLED` | `usage.reporting.enabled` *(read directly by the application)* | *(unset)* | When unset, the application's default of `true` applies; `docker-compose.yml` passes `true` unless `.env` gives it a non-empty value. Set to `false` to stop the daemon reporting `startup` and `backup-completed` events to the trace service, as described above. | -| `TRACE_USAGE_REPORTING` | *(read directly by the vendored trace client)* | *(unset)* | `off` (or `false`, `0`, `no`) stops reporting regardless of `USAGE_REPORTING_ENABLED`. | -| `DO_NOT_TRACK` | *(read directly by the vendored trace client)* | *(unset)* | `1` (or `true`, `yes`) stops reporting too, per https://consoledonottrack.com. | +| `USAGE_REPORTING_ENABLED` | `usage.reporting.enabled` *(read directly by the application)* | *(unset)* | When unset, the application's default of `true` applies; `docker-compose.yml` passes `true` only when `.env` does not set it, and passes an empty value through as empty, which is off. Set to `false` (or anything but `true`/`on`/`yes`/`1`) to stop the daemon reporting `startup` and `backup-completed` events to the trace service, as described above. | +| `TRACE_USAGE_REPORTING` | *(read directly by the vendored trace client)* | *(unset)* | `off` (or any value but blank, `true`, `on`, `yes` or `1`) stops reporting regardless of `USAGE_REPORTING_ENABLED`. | +| `DO_NOT_TRACK` | *(read directly by the vendored trace client)* | *(unset)* | `1` (or any value but blank, `0`, `false`, `off` or `no`) stops reporting too, per https://consoledonottrack.com. | | `TRACE_INSTALL_ID` | *(read directly by the application)* | *(unset)* | Pins the installation ID sent as the `install` tag. When unset, the ID file is kept inside the container, so a recreated container counts as a new installation. | Of these, `GITHUB_TOKEN`, `SCHEDULED_USERS`, `BACKUP_INTERVAL_MS`, `USAGE_REPORTING_ENABLED`, `TRACE_USAGE_REPORTING`, `DO_NOT_TRACK` and `TRACE_INSTALL_ID` are wired through to a `.env` file by the included `docker-compose.yml` (see `.env.example`); that file pins `BACKUP_DIRECTORY` to `/backups` and mounts the host's `./backups` directory there so backups persist outside the container. diff --git a/README.md b/README.md index 3b8c60b..426397e 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ To turn it off, any one of these is enough: - `TRACE_USAGE_REPORTING=off` (also `false`, `0`, `no`) in the environment — the switch every trace client honours, checked before gh-backup's own setting - `DO_NOT_TRACK=1` (also `true`, `yes`) in the environment, per [consoledonottrack.com](https://consoledonottrack.com) +Every switch fails closed, so an opt-out is never read as "on": `usage.reporting.enabled` / `USAGE_REPORTING_ENABLED` keeps reporting on only for `true`, `on`, `yes` or `1` (any case) and turns it off for anything else, blank or a typo included; `TRACE_USAGE_REPORTING` set to anything but blank or one of those values turns it off; `DO_NOT_TRACK` set to anything but blank, `0`, `false`, `off` or `no` turns it off. + See [`usage.reporting.enabled`](CONFIG.md#usagereportingenabled) in the Configuration Guide, and for what trace collects and why: https://danielstephenson.dev/usage-reporting ## Contributing diff --git a/docker-compose.yml b/docker-compose.yml index a650fbb..6b131c1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -22,9 +22,11 @@ services: # Usage reporting to the maintainers' trace service (startup and # backup-completed events, nothing about what is backed up). # Set USAGE_REPORTING_ENABLED=false or TRACE_USAGE_REPORTING=off to turn - # it off (DO_NOT_TRACK=1 too); see CONFIG.md and + # it off (DO_NOT_TRACK=1 too). A blank USAGE_REPORTING_ENABLED is passed + # through as blank (not replaced by true), and anything but true/on/yes/1 + # is read as off; see CONFIG.md and # https://danielstephenson.dev/usage-reporting - - USAGE_REPORTING_ENABLED=${USAGE_REPORTING_ENABLED:-true} + - USAGE_REPORTING_ENABLED=${USAGE_REPORTING_ENABLED-true} - TRACE_USAGE_REPORTING=${TRACE_USAGE_REPORTING:-} - DO_NOT_TRACK=${DO_NOT_TRACK:-} diff --git a/src/main/java/com/github/backup/UsageReportingService.java b/src/main/java/com/github/backup/UsageReportingService.java index a351e9b..456e9f7 100644 --- a/src/main/java/com/github/backup/UsageReportingService.java +++ b/src/main/java/com/github/backup/UsageReportingService.java @@ -32,7 +32,10 @@ * {@code application.properties}, or as {@code USAGE_REPORTING_ENABLED=false} * in the environment), or with the environment variables every trace client * honours, {@code TRACE_USAGE_REPORTING=off} and {@code DO_NOT_TRACK=1}, which - * the client checks before anything this service passes it. The first time + * the client checks before anything this service passes it. Every switch fails + * closed: {@code usage.reporting.enabled} keeps reporting on only for + * {@code true}, {@code on}, {@code yes} or {@code 1}, and anything else -- + * {@code off}, {@code no}, {@code 0}, blank, a typo -- turns it off. The first time * reporting runs on a machine, one notice is logged saying so; a marker file * under the user's config directory ({@code ~/.config/gh-backup/}) keeps it * from being repeated. Without a usable home directory there is nowhere to keep @@ -95,8 +98,9 @@ static File installIdFile(Path noticeMarker) { private static TraceClient buildClient(String enabled, String endpoint, String key, String version, File installIdFile) { - // A blank value (an empty environment variable, say) means "default", i.e. on. - boolean on = enabled == null || enabled.isBlank() || !"false".equalsIgnoreCase(enabled.trim()); + // Fails closed: only true, on, yes or 1 (any case) keeps reporting on. Anything else -- + // false, off, no, 0, blank, a typo -- turns it off, so an opt-out is never read as on. + boolean on = TraceClient.allowsReporting(enabled); try { return TraceClient.builder(endpoint, APPLICATION, version) .key(key) diff --git a/src/main/java/com/github/backup/trace/TraceClient.java b/src/main/java/com/github/backup/trace/TraceClient.java index 5d3b279..3bde654 100644 --- a/src/main/java/com/github/backup/trace/TraceClient.java +++ b/src/main/java/com/github/backup/trace/TraceClient.java @@ -1,5 +1,5 @@ /* - * trace-client 0.7.0 -- https://github.com/Stephenson-Software/trace-client-java + * trace-client 0.8.0 -- https://github.com/Stephenson-Software/trace-client-java * * One call to report that a program was used. Copy this file into a project as * is, or depend on the artifact; either way there is nothing else to add. @@ -14,7 +14,9 @@ import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; @@ -23,6 +25,7 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.UUID; @@ -40,7 +43,7 @@ * Reports usage events to a trace server, and never gets in the way of the * program doing the reporting. * - *

Three properties hold for every call to {@link #report}: + *

Four properties hold for every call to {@link #report}: * *

* *

Reporting is opt-out, and the person running the program always has the - * last word. {@link Builder#build()} checks, in this order, and the first - * match is what {@link #disabledReason()} reports: + * last word. Every switch fails closed: a value that does not clearly mean + * "on" -- a typo, a quoted {@code "false"}, an empty value -- turns reporting + * off, and nothing in this client ever turns a switch back on. + * {@link Builder#build()} checks, in this order, and the first match is what + * {@link #disabledReason()} reports: * *

    - *
  1. the environment: {@code TRACE_USAGE_REPORTING=off} (or {@code false}, - * {@code 0}, {@code no}) or {@code DO_NOT_TRACK=1} (or {@code true}, - * {@code yes}), case-insensitive -- reason {@code environment};
  2. + *
  3. the environment: {@code TRACE_USAGE_REPORTING} set to anything but + * blank, {@code true}, {@code on}, {@code yes} or {@code 1}; or + * {@code DO_NOT_TRACK} set to anything but blank, {@code 0}, + * {@code false}, {@code off} or {@code no}; case-insensitive -- reason + * {@code environment};
  4. *
  5. the server-wide switch, when {@link Builder#serverWideConfig(File)} - * was given: {@code enabled: false} in {@code plugins/trace/config.yml} - * -- reason {@code server-wide config: plugins/trace/config.yml};
  6. + * was given: any {@code enabled:} line in {@code plugins/trace/config.yml} + * whose value, bare or quoted, is not {@code true}, {@code on}, + * {@code yes} or {@code 1} (case-insensitive); or that file existing but + * being unreadable -- reason + * {@code server-wide config: plugins/trace/config.yml}; *
  7. the program's own setting, {@link Builder#enabled(boolean) - * enabled(false)} -- reason {@code config.yml};
  8. + * enabled(false)} -- reason {@code config.yml}. Read it with + * {@link #allowsReporting(Object)} so it fails closed too; *
  9. no key -- reason {@code no key}.
  10. *
* @@ -104,7 +117,8 @@ * server-wide {@code server-id:}; with none of them, no {@code install} tag * is sent. The ID is random: it names no person, account or address. A * disabled client never generates, reads or writes one. An event's own - * {@code install} tag wins over it. + * {@code install} tag wins over it, and an event already at + * {@value #MAX_TAGS} tags with {@code version} goes out without it. * *

A disabled client is a no-op that costs nothing. Programs that run on * other people's machines should expose their own switch in their @@ -114,7 +128,7 @@ * TraceClient trace = TraceClient.builder("https://trace.example.org", "MyPlugin", * getDescription().getVersion()) * .key(config.getString("usage-reporting.key")) - * .enabled(config.getBoolean("usage-reporting.enabled", true)) + * .enabled(TraceClient.allowsReporting(config.get("usage-reporting.enabled"))) * .serverWideConfig(getDataFolder().getParentFile()) // plugins/ * .logger(getLogger()) * .build(); @@ -135,7 +149,7 @@ public final class TraceClient { /** This client's version, as sent in the User-Agent. */ - public static final String VERSION = "0.7.0"; + public static final String VERSION = "0.8.0"; /** How many reports may wait to be sent before new ones are dropped. */ public static final int QUEUE_CAPACITY = 256; @@ -216,7 +230,7 @@ public final class TraceClient { /** What {@link #installIdFromFile(File)} accepts as an ID on a line of its file. */ private static final Pattern INSTALL_ID_LINE = Pattern.compile("[A-Za-z0-9_.\\-]{1,255}"); - private static final Pattern ENABLED_LINE = Pattern.compile("^\\s*enabled\\s*:\\s*(\\S+)"); + private static final Pattern ENABLED_LINE = Pattern.compile("^\\s*enabled\\s*:(.*)$"); private static final Pattern TAGS_LINE = Pattern.compile("^tags\\s*:\\s*(#.*)?$"); private static final Pattern SERVER_ID_LINE = Pattern.compile("^server-id\\s*:(.*)$"); @@ -392,7 +406,8 @@ private String resolveInstallId(Builder builder, ServerWideConfig serverWide) { * *

Never throws: 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. + * unreadable file is left as it is. The same goes for a {@code null} + * file or a blank path, which nothing is written to. * *

Called directly, this writes whatever the opt-outs say. Pass * the file to {@link Builder#installIdFile(File)} instead to keep the @@ -454,30 +469,71 @@ private static String disabledReason(Builder builder, ServerWideConfig serverWid return null; } + // Both variables fail closed: once set to anything but blank, only a value + // that clearly means "keep reporting" keeps it on. private static boolean environmentDisables() { - return isOff(environment.apply(ENV_USAGE_REPORTING)) || isYes(environment.apply(ENV_DO_NOT_TRACK)); + try { + return environmentSaysOff(); + } catch (RuntimeException unreadable) { + // e.g. a SecurityManager denying getenv: an environment that cannot + // be read may hold DO_NOT_TRACK=1, so it counts as opting out. + return true; + } } - private static boolean isOff(String value) { - if (value == null) { - return false; + private static boolean environmentSaysOff() { + String usageReporting = environment.apply(ENV_USAGE_REPORTING); + if (usageReporting != null && !usageReporting.trim().isEmpty() && !isOn(usageReporting)) { + return true; } - String v = value.trim().toLowerCase(); - return v.equals("off") || v.equals("false") || v.equals("0") || v.equals("no"); + String doNotTrack = environment.apply(ENV_DO_NOT_TRACK); + return doNotTrack != null && !doNotTrack.trim().isEmpty() && !isNegative(doNotTrack); } - private static boolean isYes(String value) { + /** {@code true}, {@code on}, {@code yes} or {@code 1}, ignoring case and surrounding space. */ + private static boolean isOn(String value) { if (value == null) { return false; } - String v = value.trim().toLowerCase(); - return v.equals("1") || v.equals("true") || v.equals("yes"); + String v = value.trim().toLowerCase(Locale.ROOT); + return v.equals("true") || v.equals("on") || v.equals("yes") || v.equals("1"); + } + + /** {@code false}, {@code off}, {@code no} or {@code 0}, ignoring case and surrounding space. */ + private static boolean isNegative(String value) { + String v = value.trim().toLowerCase(Locale.ROOT); + return v.equals("false") || v.equals("off") || v.equals("no") || v.equals("0"); + } + + /** + * Whether a program's own reporting setting, as read from its + * configuration, allows reporting -- for {@link Builder#enabled(boolean)}. + * Fails closed: only {@link Boolean#TRUE}, or a string reading + * {@code true}, {@code on}, {@code yes} or {@code 1} (any case), allows it. + * Anything else turns reporting off: {@code false}, a quoted + * {@code "false"}, {@code off}, {@code no}, a typo, a number, or + * {@code null}. + * + *

Prefer this over {@code getBoolean(path, true)}: Bukkit's + * {@code getBoolean} returns its default for a value that is not a YAML + * boolean, so an operator's {@code enabled: "false"} would read as on. + * Pass the raw value -- on Bukkit, {@code getConfig().get(path)}, which + * still falls through to the defaults bundled in the jar when the + * operator's file has no such key. + */ + public static boolean allowsReporting(Object setting) { + if (setting instanceof Boolean) { + return (Boolean) setting; + } + return setting instanceof String && isOn((String) setting); } /** What {@code plugins/trace/config.yml} says: the switch, the server-wide tags and the server-id. */ static final class ServerWideConfig { /** No file was read: none was asked for, or it could not be read. */ static final ServerWideConfig NONE = new ServerWideConfig(false, Collections.emptyMap(), null); + /** The file is there but could not be read: whatever it says, it may say off. */ + static final ServerWideConfig UNREADABLE = new ServerWideConfig(true, Collections.emptyMap(), null); final boolean disables; final Map tags; @@ -504,39 +560,71 @@ ServerWideConfig readFromDisk(boolean created) { /** * Ensures {@code /trace/config.yml} exists and reads its - * {@code enabled:} line and {@code tags:} block. No YAML library: the file - * is ours, shallow, and a line scan is enough. Anything going wrong on - * disk is logged at FINE and counts as enabled with no tags -- a - * read-only plugins directory must not silently switch reporting off, - * nor stop the host program. + * {@code enabled:} line, {@code tags:} block and {@code server-id:} line. + * Not called when the environment opts out. No YAML library: the file + * is ours, shallow, and a line scan is enough. Nothing here throws. + * A file that is missing and cannot be created counts as enabled with no + * tags: the operator has said nothing, and a read-only plugins directory + * must not silently switch reporting off. A file that is there but cannot + * be read counts as disabled: it may say {@code enabled: false}. A file + * that is not valid UTF-8 is read as ISO-8859-1. */ private ServerWideConfig readServerWideConfig(File pluginsDirectory) { File location = new File(pluginsDirectory, SERVER_WIDE_CONFIG_PATH); + Path file; + try { + // toPath() throws InvalidPathException for a path the file system + // cannot represent. No file can be there, so the operator has said + // nothing; and build() never throws. + file = location.toPath(); + } catch (RuntimeException unrepresentable) { + log("could not read server-wide config " + location + ": " + unrepresentable); + return ServerWideConfig.NONE; + } try { - // Inside the try: toPath() throws InvalidPathException for a path - // the file system cannot represent, and build() never throws. - Path file = location.toPath(); boolean created = false; if (!Files.exists(file)) { - Files.createDirectories(file.getParent()); - Files.write(file, SERVER_WIDE_CONFIG_CONTENT.getBytes(StandardCharsets.UTF_8)); - // just written: enabled: true, and the tags example commented out - created = true; + try { + Files.createDirectories(file.getParent()); + Files.write(file, SERVER_WIDE_CONFIG_CONTENT.getBytes(StandardCharsets.UTF_8), + StandardOpenOption.CREATE_NEW); + // just written: enabled: true, and the tags example commented out + created = true; + } catch (FileAlreadyExistsException raced) { + // another plugin wrote it first: read theirs + } catch (IOException | RuntimeException failure) { + // No file, and none can be made: the operator has said nothing. + log("could not create server-wide config " + location + ": " + failure); + return ServerWideConfig.NONE; + } + } + try { + return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.UTF_8)).readFromDisk(created); + } catch (CharacterCodingException notUtf8) { + // Saved in another encoding, e.g. with an accented comment. The + // switch is still read; nothing is appended to the file, so the + // install ID lives in memory for this process. + log("server-wide config " + location + " is not UTF-8; reading it as ISO-8859-1"); + return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.ISO_8859_1)); } - return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.UTF_8)).readFromDisk(created); } catch (IOException | RuntimeException failure) { - log("could not read server-wide config " + location + ": " + failure); - return ServerWideConfig.NONE; + // The file is there but cannot be read. It may say enabled: false, + // so reporting stays off rather than guessing. + log("could not read server-wide config " + location + ", so reporting is off: " + failure); + return ServerWideConfig.UNREADABLE; } } + /** * Reads the switch and the tags from the lines of the server-wide file. - * The first {@code enabled:} line outside a {@code tags:} block is the - * switch. A {@code tags:} line at column 0 opens a block of indented - * {@code key: value} lines, which ends at the next non-blank line that is - * not indented; blank and {@code #} lines inside it are skipped, as are - * lines indented differently from its first entry. Values may be bare, + * Every {@code enabled:} line outside a {@code tags:} block is a switch, + * and reporting stays on only if each one reads, bare or quoted, + * {@code true}, {@code on}, {@code yes} or {@code 1}. A {@code tags:} line at column 0 opens a block of indented + * {@code key: value} lines, which ends at the next line that is not + * blank, a comment or indented; blank and {@code #} lines inside it are + * skipped, at any indent, as are lines indented differently from its + * first entry. Values may be bare, * double- or single-quoted. Entries the trace server would reject -- and * anything this reader does not understand -- are dropped, one by one, * and at most {@link #MAX_TAGS} are kept. The first {@code server-id:} @@ -587,10 +675,15 @@ static ServerWideConfig parseServerWideConfig(List lines) { continue; } } - if (disables == null) { - Matcher matcher = ENABLED_LINE.matcher(line); - if (matcher.find()) { - disables = isOff(matcher.group(1)); + Matcher enabled = ENABLED_LINE.matcher(line); + if (enabled.matches()) { + // Fails closed: every enabled: line counts, and only a value + // that clearly means "on" keeps reporting on. + String value = scalar(enabled.group(1).trim()); + if (value == null || !isOn(value)) { + disables = true; + } else if (disables == null) { + disables = false; } } } @@ -757,7 +850,9 @@ public void report(String name) { /** * Reports that {@code name} happened, with an optional numeric value and * optional string tags. Returns immediately; see the class comment. A - * {@code null} or blank name sends nothing. + * {@code null} or blank name sends nothing, and so does a {@code tags} + * map that fails while being read -- changed by another thread during + * the call, or holding a non-{@code String} through an unchecked cast. * *

Repeats are coalesced. The first report of an event -- its name, * value and tags, once {@code version}, {@code install} and the @@ -772,9 +867,16 @@ public void report(String name) { * counted nothing ends. {@link #close()} sends every count still open. * *

So the number of times an event happened is the sum, over the - * events the server stored, of {@code value} where the - * {@value #COALESCED_TAG} tag is present and 1 where it is not -- for - * a valueless event, simply {@code COALESCE(value, 1)}. + * events the server stored, of the {@value #COALESCED_TAG} tag where it + * is present and 1 where it is not -- for an event reported without a + * value, simply {@code COALESCE(value, 1)}; an event reported with one + * keeps it, so only the tag holds the count. Two exceptions: a count is + * not tagged when the event already carries {@value #MAX_TAGS} tags, so + * it reads as a single report; and an event with its own + * {@value #COALESCED_TAG} tag keeps it, so that tag is not a count. + * + *

A count goes through the same queue as any report: one that finds + * it full is dropped, without a log line, and what it counted is lost. * *

{@code startup} is never coalesced, nor held back: every one is * sent at once. @@ -786,9 +888,17 @@ public void report(String name, Double value, Map tags) { // json() leaves out a value that is NaN or infinite, so they are the // same event as no value at all. Double finite = value == null || value.isNaN() || value.isInfinite() ? null : value; - Map merged = - withServerWideTags(withInstall(withVersion(tags, version), installId), serverWideTags); - String body = json(application, name, finite, merged); + Map merged; + String body; + try { + merged = withServerWideTags(withInstall(withVersion(tags, version), installId), serverWideTags); + body = json(application, name, finite, merged); + } catch (RuntimeException unreadable) { + // The caller's map, read on the caller's thread: another thread + // changing it, or a raw map holding a non-String, fails here. Not + // logged, like the other drops on this thread: a handler may do IO. + return; + } synchronized (lock) { if (closed) { return; @@ -920,12 +1030,12 @@ int coalescing() { * Sends every count still being coalesced (see {@link #report(String, * Double, Map)}), then stops the sending thread, giving reports already * queued up to {@value #READ_TIMEOUT_MS} ms in total to be sent first. - * A program that - * reports and then exits within milliseconds -- a CLI -- would otherwise - * lose its one event to the race between queueing it and the thread - * picking it up. The bound still holds: an unreachable server delays exit + * A program that reports and then exits within milliseconds -- a CLI -- + * would otherwise lose its one event to the race between queueing it + * and the thread picking it up. The bound still holds: an unreachable server delays exit * by at most the timeout, never a hang; whatever has not been sent by - * then is dropped. Safe to call more than once, and on a disabled client. + * then is dropped. A report made after this is dropped too. Safe to call + * more than once, and on a disabled client. */ public void close() { if (executor == null) { @@ -1106,7 +1216,8 @@ public Builder enabled(boolean enabled) { * in a Bukkit plugin), {@link #build()} makes sure * {@code plugins/trace/config.yml} exists -- creating it with * {@code enabled: true} if it is missing -- and honours - * {@code enabled: false} in it. Its optional {@code tags:} block is + * {@code enabled: false} (or {@code off}, {@code 0}, {@code no}, + * case-insensitive) in it. Its optional {@code tags:} block is * added to every event this client reports, below the event's own * tags. Its {@code server-id:} line is sent as the tag * {@code install}; when an enabled client finds none, it appends one @@ -1121,8 +1232,9 @@ public Builder enabled(boolean enabled) { * server-id: 0f8b6c1e-... * * - *

Both are read once, here. Optional; programs that are not - * plugins leave it unset. + *

All three are read once, here. When an environment variable has + * already turned reporting off, the file is neither read nor created. + * Optional; programs that are not plugins leave it unset. */ public Builder serverWideConfig(File pluginsDirectory) { this.pluginsDirectory = pluginsDirectory; @@ -1176,8 +1288,10 @@ public Builder installIdFile(File installIdFile) { * {@code [trace]}: a report the server did not answer {@code 201} * to or that could not be delivered, and a server-wide config or * install ID file that could not be read or written in - * {@link #build()}. A report dropped because the queue is full is - * not mentioned. Optional; without one, nothing is logged. + * {@link #build()}. A report dropped because the queue is full, because + * {@value TraceClient#MAX_COALESCED_EVENTS} other events are already + * being counted, or because its tags map could not be read, is not + * mentioned. Optional; without one, nothing is logged. */ public Builder logger(Logger logger) { this.logger = logger; diff --git a/src/test/java/com/github/backup/DockerComposeEnvironmentTest.java b/src/test/java/com/github/backup/DockerComposeEnvironmentTest.java index 297ab06..3b59170 100644 --- a/src/test/java/com/github/backup/DockerComposeEnvironmentTest.java +++ b/src/test/java/com/github/backup/DockerComposeEnvironmentTest.java @@ -32,7 +32,11 @@ void testEnvExampleVariables_ForwardedByDockerCompose() throws Exception { if (matcher.find()) { String name = matcher.group(1); variables.add(name); - if (!compose.contains("- " + name + "=${" + name + ":-")) { + // ${NAME:-default} or ${NAME-default}; the latter passes an empty value through + // rather than replacing it, as USAGE_REPORTING_ENABLED does so that a blank + // value is read as off. + if (!compose.contains("- " + name + "=${" + name + ":-") + && !compose.contains("- " + name + "=${" + name + "-")) { missing.add(name); } } diff --git a/src/test/java/com/github/backup/UsageReportingServiceTest.java b/src/test/java/com/github/backup/UsageReportingServiceTest.java index fc36cd1..7088c61 100644 --- a/src/test/java/com/github/backup/UsageReportingServiceTest.java +++ b/src/test/java/com/github/backup/UsageReportingServiceTest.java @@ -167,10 +167,13 @@ void disabledSendsNothingAndShowsNoNotice() throws Exception { } @Test - void blankEnabledValueMeansOnAndMissingKeyMeansOff() { - assertTrue(new UsageReportingService("", endpoint(), "test-key", "1", marker()).isEnabled(), - "an empty USAGE_REPORTING_ENABLED must not turn reporting off or crash"); - assertTrue(new UsageReportingService(null, endpoint(), "test-key", "1", marker()).isEnabled()); + void blankOrMissingEnabledValueMeansOffAndMissingKeyMeansOff() { + // Fails closed: an empty USAGE_REPORTING_ENABLED (the property itself defaults to true when + // the variable is unset) is not a clear "on", so it turns reporting off -- without crashing. + assertFalse(new UsageReportingService("", endpoint(), "test-key", "1", marker()).isEnabled(), + "an empty USAGE_REPORTING_ENABLED must turn reporting off, not crash"); + assertFalse(new UsageReportingService(" ", endpoint(), "test-key", "1", marker()).isEnabled()); + assertFalse(new UsageReportingService(null, endpoint(), "test-key", "1", marker()).isEnabled()); assertFalse(new UsageReportingService("true", endpoint(), "", "1", marker()).isEnabled(), "no key means nothing can be reported"); assertFalse(new UsageReportingService("FALSE", endpoint(), "test-key", "1", marker()).isEnabled()); @@ -201,12 +204,17 @@ void defaultMarkerLivesUnderTheUsersConfigDirectory() { } @Test - void onlyFalseTurnsReportingOffWhateverItsCaseOrSurroundingSpace() { - assertFalse(new UsageReportingService(" False ", endpoint(), "test-key", "1", marker()).isEnabled()); - // COMMANDS.md: any value of USAGE_REPORTING_ENABLED other than false leaves reporting on - for (String other : new String[] {"no", "0", "off", "disabled", "true"}) { - assertTrue(new UsageReportingService(other, endpoint(), "test-key", "1", marker()).isEnabled(), - "'" + other + "' should leave reporting on"); + void onlyAClearOnValueKeepsReportingOnWhateverItsCaseOrSurroundingSpace() { + // COMMANDS.md: USAGE_REPORTING_ENABLED keeps reporting on only for true, on, yes or 1; + // anything else turns it off. Before, only "false" did, and "off", "no" and "0" left it on. + for (String off : new String[] {" False ", "false", "no", "0", "off", "OFF", "disabled", "flase", "\"false\""}) { + assertFalse(new UsageReportingService(off, endpoint(), "test-key", "1", marker()).isEnabled(), + "'" + off + "' should turn reporting off"); + } + for (String on : new String[] {"true", " TRUE ", "on", "yes", "1"}) { + UsageReportingService service = new UsageReportingService(on, endpoint(), "test-key", "1", marker()); + assertTrue(service.isEnabled(), "'" + on + "' should leave reporting on"); + service.close(); } } diff --git a/src/test/java/com/github/backup/trace/TraceClientTest.java b/src/test/java/com/github/backup/trace/TraceClientTest.java index 0b7811e..831d198 100644 --- a/src/test/java/com/github/backup/trace/TraceClientTest.java +++ b/src/test/java/com/github/backup/trace/TraceClientTest.java @@ -13,23 +13,31 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.AbstractMap; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; +import java.util.function.IntConsumer; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Drives the client against a real HTTP server on a loopback port -- the @@ -222,6 +230,58 @@ void report_doesNotThrowWhenTheServerRejectsTheKey() throws Exception { client.close(); } + @Test + void report_aTagsMapChangedMidReadIsDroppedWithoutThrowing() throws Exception { + // Arrange + // What a HashMap does when another thread changes it during the + // copy, without needing to win that race. + Map beingChanged = new AbstractMap() { + @Override + public Set> entrySet() { + throw new ConcurrentModificationException(); + } + }; + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.unreadableTags"); + logger.setLevel(Level.ALL); + logger.addHandler(log); + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").logger(logger).build(); + + // Act + assertDoesNotThrow(() -> client.report("command", 1.0, beingChanged)); + client.report("after", null, null); + + // Assert + assertTrue(arrived.await(5, TimeUnit.SECONDS), "the client should keep working"); + assertEquals(1, client.coalescing(), "only the good report opened a window"); + client.close(); + assertEquals(1, received.size(), "the unreadable report is dropped"); + assertTrue(received.get(0).body.contains("\"name\":\"after\""), received.get(0).body); + assertTrue(log.records.isEmpty(), "nothing is logged on the caller's thread: " + log.records); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void report_aNonStringTagSmuggledInByARawMapIsDroppedWithoutThrowing() throws Exception { + // Arrange + // A Bukkit getValues(false) is a Map; one unchecked + // cast puts an Integer where json() needs a String. + Map raw = new HashMap(); + raw.put("count", 5); + Map tags = raw; + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + + // Act + assertDoesNotThrow(() -> client.report("command", null, tags)); + client.report("after", null, null); + + // Assert + assertTrue(arrived.await(5, TimeUnit.SECONDS), "the client should keep working"); + client.close(); + assertEquals(1, received.size(), "the unreadable report is dropped"); + assertTrue(received.get(0).body.contains("\"name\":\"after\""), received.get(0).body); + } + @Test void disabledClient_sendsNothing() throws Exception { // Arrange @@ -276,6 +336,47 @@ void builder_rejectsAMissingOrOverlongVersion() { assertThrows(IllegalArgumentException.class, () -> TraceClient.builder("http://x", "MyPlugin", overlong.toString())); } + @Test + void builder_namesWhatIsMissingInItsMessage() { + // Act + IllegalArgumentException noBaseUrl = assertThrows(IllegalArgumentException.class, + () -> TraceClient.builder(" ", "MyPlugin", "1.2.3")); + IllegalArgumentException noApplication = assertThrows(IllegalArgumentException.class, + () -> TraceClient.builder("http://x", null, "1.2.3")); + IllegalArgumentException noVersion = assertThrows(IllegalArgumentException.class, + () -> TraceClient.builder("http://x", "MyPlugin", "")); + IllegalArgumentException allMissing = assertThrows(IllegalArgumentException.class, + () -> TraceClient.builder(null, null, null)); + + // Assert + assertEquals("baseUrl is required", noBaseUrl.getMessage()); + assertEquals("application is required", noApplication.getMessage()); + assertEquals("version is required", noVersion.getMessage()); + assertEquals("baseUrl is required", allMissing.getMessage(), "checked in argument order"); + } + + @Test + void builder_rejectsAnOverlongVersionAndAcceptsOneAtTheLimit() throws Exception { + // Arrange + StringBuilder max = new StringBuilder(); + for (int i = 0; i < TraceClient.MAX_TAG_LENGTH; i++) { + max.append('9'); + } + + // Act + IllegalArgumentException tooLong = assertThrows(IllegalArgumentException.class, + () -> TraceClient.builder(baseUrl(), "MyPlugin", max + "9")); + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", " " + max + " ").key("k").build(); + client.report("startup"); + + // Assert + assertEquals("version is longer than " + TraceClient.MAX_TAG_LENGTH + " characters", tooLong.getMessage()); + assertTrue(arrived.await(5, TimeUnit.SECONDS), "a version at the limit is accepted"); + assertTrue(received.get(0).body.contains("\"version\":\"" + max + "\""), + "surrounding whitespace does not count and is not sent: " + received.get(0).body); + client.close(); + } + @Test void report_tagsACommandWithTheProgramVersionTrimmed() throws Exception { // Arrange @@ -321,6 +422,92 @@ void withVersion_neverModifiesTheCallersMap() { assertEquals("1.2.3", TraceClient.withVersion(null, "1.2.3").get("version")); } + @Test + void withVersion_dropsNullKeysAndValuesAndKeepsTheEventsOwnVersion() { + // Arrange + Map tags = new LinkedHashMap<>(); + tags.put("name", "home"); + tags.put("nullValue", null); + tags.put(null, "nullKey"); + tags.put("version", "own"); + + // Act + Map merged = TraceClient.withVersion(tags, "1.2.3"); + + // Assert + Map expected = new LinkedHashMap<>(); + expected.put("name", "home"); + expected.put("version", "own"); + assertEquals(expected, merged); + assertEquals(4, tags.size(), "the caller's map is not modified"); + } + + @Test + void withVersion_addsTheVersionEvenToAnEventAlreadyAtMaxTags() { + // Characterizes current behaviour, which issue #13 questions: unlike + // install and the server-wide tags, version is not held to MAX_TAGS, + // so an event with MAX_TAGS tags of its own goes out with one more. + // Arrange + Map tags = new LinkedHashMap<>(); + for (int i = 0; i < TraceClient.MAX_TAGS; i++) { + tags.put("e" + i, "v"); + } + + // Act + Map merged = TraceClient.withVersion(tags, "1.2.3"); + + // Assert + assertEquals(TraceClient.MAX_TAGS + 1, merged.size()); + assertEquals("1.2.3", merged.get("version")); + } + + @Test + void withInstall_addsTheIdOnlyWhenThereIsOneAndRoomAndNoneAlready() { + // Arrange + Map tags = new LinkedHashMap<>(); + tags.put("version", "1.2.3"); + Map own = Collections.singletonMap("install", "the-events-own"); + Map full = new LinkedHashMap<>(); + for (int i = 0; i < TraceClient.MAX_TAGS; i++) { + full.put("e" + i, "v"); + } + + // Act + Map added = TraceClient.withInstall(tags, "abc"); + + // Assert + Map expected = new LinkedHashMap<>(); + expected.put("version", "1.2.3"); + expected.put("install", "abc"); + assertEquals(expected, added); + assertEquals(Collections.singletonMap("version", "1.2.3"), tags, "the caller's map is not modified"); + assertSame(tags, TraceClient.withInstall(tags, null), "no ID, nothing added"); + assertSame(own, TraceClient.withInstall(own, "abc"), "the event's own install tag wins"); + assertSame(full, TraceClient.withInstall(full, "abc"), "never pushed past MAX_TAGS"); + } + + @Test + void serverWideConfig_anyEnabledLineThatIsNotOnDisables() { + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true", "enabled: false")).disables, + "a later off wins over an earlier on"); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: false", "enabled: true")).disables, + "and an earlier off wins over a later on"); + assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true", "enabled: yes")).disables); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("# enabled: true", "enabled: false")).disables, + "a commented-out line is not a switch"); + } + + @Test + void serverWideConfig_aValuelessEnabledLineDisables() { + // Fails closed (issue #27): an enabled: line with no value, or only a + // comment, does not clearly mean "on", so it turns reporting off. + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled:")).disables); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: ")).disables); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: # set below", "enabled: true")).disables); + assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true # on")).disables, + "a trailing comment after a value is not part of it"); + } + @Test void json_escapesControlCharactersAndSkipsNullTags() { Map tags = new LinkedHashMap<>(); @@ -348,6 +535,23 @@ void json_dropsInfiniteValuesAndKeepsFiniteOnes() { assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":-0.5}", finite); } + @Test + void json_writesValuesAsDoubleToStringDoesWhichIsStillValidJson() { + // A value goes out as Double.toString: always with a fraction, and in + // exponent form below 1e-3 and from 1e7 up. JSON allows "1.0E20" and + // "1.0E-5" (an upper-case E and a signed exponent), so the server + // must parse both forms. + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0}", TraceClient.json("App", "n", 1.0, null)); + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1234567.0}", TraceClient.json("App", "n", 1234567.0, null)); + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0E7}", TraceClient.json("App", "n", 1e7, null)); + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0E20}", TraceClient.json("App", "n", 1e20, null)); + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":0.001}", TraceClient.json("App", "n", 0.001, null)); + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0E-5}", TraceClient.json("App", "n", 1e-5, null)); + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":-0.0}", TraceClient.json("App", "n", -0.0, null)); + assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.7976931348623157E308}", + TraceClient.json("App", "n", Double.MAX_VALUE, null)); + } + @Test void json_omitsTagsWhenNullOrEmpty() { // Arrange + Act @@ -411,13 +615,19 @@ void queue_isBoundedAndDropsRatherThanGrows() throws Exception { exchange.close(); }); slow.start(); + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.flood"); + logger.setLevel(Level.ALL); + logger.addHandler(log); TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "MyPlugin", "1.2.3") - .key("k").build(); + .key("k").logger(logger).build(); int flood = TraceClient.QUEUE_CAPACITY * 3; // Act + // startup, because it is never coalesced: every one of these goes + // to the queue, so the queue is all that bounds them. for (int i = 0; i < flood; i++) { - client.report("flood"); + client.report("startup"); } release.countDown(); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20); @@ -437,6 +647,17 @@ void queue_isBoundedAndDropsRatherThanGrows() throws Exception { "delivered " + delivered.get() + " of " + flood + "; at most the in-flight one plus a full queue may survive"); assertTrue(delivered.get() < flood, "an unbounded queue would have delivered all " + flood); client.close(); + // The README says drops are silent. The server only answers 201, so + // the one other line the send path can write is "could not deliver", + // for a loopback connection that failed -- one stray line was seen + // once on Java 8 CI. Allow a few of those, far fewer than there were + // drops: logging each drop would be hundreds of lines. + List messages = log.records.stream().map(LogRecord::getMessage).collect(Collectors.toList()); + int dropped = flood - (TraceClient.QUEUE_CAPACITY + 1); + assertTrue(messages.stream().allMatch(m -> m.startsWith("[trace] could not deliver ")), + "only a failed send may be logged, but logged: " + messages); + assertTrue(messages.size() < dropped / 10, + "a full queue drops without logging, but logged " + messages.size() + " lines: " + messages); slow.stop(0); } @@ -475,6 +696,75 @@ void close_stillReturnsWithinTheTimeoutWhenTheServerHangs() throws Exception { slow.stop(0); } + @Test + void close_whenInterruptedReturnsAtOnceAndKeepsTheInterruptFlag() throws Exception { + // Arrange + // A server holding a request, so close() would otherwise wait out + // the whole drain timeout. A host shutting down on an interrupt must + // not wait that long, and must still see that it was interrupted. + CountDownLatch inFlight = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + slow.createContext("/", exchange -> { + inFlight.countDown(); + try { release.await(15, TimeUnit.SECONDS); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } + exchange.sendResponseHeaders(201, -1); + exchange.close(); + }); + slow.start(); + TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "MyCli", "1.2.3").key("k").build(); + client.report("startup"); + assertTrue(inFlight.await(5, TimeUnit.SECONDS), "the report should reach the server"); + + // Act + Thread.currentThread().interrupt(); + long before = System.nanoTime(); + client.close(); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - before); + boolean stillInterrupted = Thread.interrupted(); // clears it, so later tests run uninterrupted + + // Assert + assertTrue(stillInterrupted, "close() must restore the interrupt it swallowed"); + assertTrue(elapsedMs < 2_000, "close() took " + elapsedMs + " ms; an interrupt must cut the drain short"); + release.countDown(); + slow.stop(0); + } + + @Test + void report_sendsFromOneDaemonThreadNamedForTheApplication() throws Exception { + // Arrange + // A server holding the first request, so the sender thread is alive + // and busy while the rest queue behind it. + CountDownLatch inFlight = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + slow.createContext("/", exchange -> { + inFlight.countDown(); + try { release.await(15, TimeUnit.SECONDS); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } + exchange.sendResponseHeaders(201, -1); + exchange.close(); + }); + slow.start(); + TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "ThreadProbe", "1.2.3") + .key("k").build(); + + // Act + for (int i = 0; i < 5; i++) { + client.report("startup"); + } + assertTrue(inFlight.await(5, TimeUnit.SECONDS), "the first report should reach the server"); + List senders = Thread.getAllStackTraces().keySet().stream() + .filter(thread -> thread.getName().equals("trace-client/ThreadProbe")) + .collect(Collectors.toList()); + + // Assert + assertEquals(1, senders.size(), "one sender thread, however many reports wait"); + assertTrue(senders.get(0).isDaemon(), "a daemon thread never keeps the host's JVM from exiting"); + release.countDown(); + client.close(); + slow.stop(0); + } + @Test void close_isSafeToCallTwice() throws Exception { // Arrange @@ -519,6 +809,83 @@ void report_sendsAUserAgentNamingTheClientAndTheApplication() throws Exception { client.close(); } + /** What reached a server, as bytes, with the two headers that say how to read them. */ + private static final class RawRequest { + final byte[] body; + final String contentType; + final String contentLength; + + RawRequest(byte[] body, String contentType, String contentLength) { + this.body = body; + this.contentType = contentType; + this.contentLength = contentLength; + } + } + + /** Reports {@code name} with {@code tags} to a server of its own and returns the one request it received. */ + private static RawRequest reportAndCaptureRawRequest(String name, Map tags) throws Exception { + List raw = new CopyOnWriteArrayList<>(); + CountDownLatch got = new CountDownLatch(1); + HttpServer capturing = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + capturing.createContext("/", exchange -> { + raw.add(new RawRequest(readAll(exchange.getRequestBody()), + exchange.getRequestHeaders().getFirst("Content-Type"), + exchange.getRequestHeaders().getFirst("Content-Length"))); + exchange.sendResponseHeaders(201, -1); + exchange.close(); + got.countDown(); + }); + capturing.start(); + try { + TraceClient client = TraceClient.builder("http://127.0.0.1:" + capturing.getAddress().getPort(), "MyPlugin", "1.2.3") + .key("k").build(); + client.report(name, null, tags); + assertTrue(got.await(5, TimeUnit.SECONDS), "the report should reach the server"); + client.close(); + return raw.get(0); + } finally { + capturing.stop(0); + } + } + + @Test + void report_sendsNonAsciiTextAsUtf8WithALengthCountedInBytes() throws Exception { + // Arrange + // A two-byte, a three-byte and a four-byte (surrogate pair) character. + // The body is streamed with a fixed length: counted in chars rather + // than bytes, every such report would fail to send. + Map tags = Collections.singletonMap("place", "€ 🏠"); + String expected = "{\"application\":\"MyPlugin\",\"name\":\"démarrage\"," + + "\"tags\":{\"place\":\"€ 🏠\",\"version\":\"1.2.3\"}}"; + + // Act + RawRequest request = reportAndCaptureRawRequest("démarrage", tags); + + // Assert + assertArrayEquals(expected.getBytes(StandardCharsets.UTF_8), request.body, "the body is the JSON in UTF-8"); + assertTrue(request.body.length > expected.length(), "the multi-byte characters must have been sent as such"); + assertEquals(String.valueOf(request.body.length), request.contentLength, "the length is counted in bytes"); + assertEquals("application/json; charset=utf-8", request.contentType); + } + + @Test + void report_aLoneSurrogateIsSentAsAQuestionMarkRatherThanDroppingTheReport() throws Exception { + // Arrange + // Half of a surrogate pair is not text UTF-8 can encode. quote() + // passes it through, and String.getBytes(UTF_8) then writes its + // replacement byte -- so the report still goes out, with '?' there. + Map tags = Collections.singletonMap("broken", "a\uD83Cb"); + + // Act + RawRequest request = reportAndCaptureRawRequest("command", tags); + + // Assert + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\"," + + "\"tags\":{\"broken\":\"a?b\",\"version\":\"1.2.3\"}}", + new String(request.body, StandardCharsets.UTF_8)); + assertEquals(String.valueOf(request.body.length), request.contentLength); + } + @Test void report_logsASuccessStatusOtherThan201() throws Exception { // Arrange @@ -543,6 +910,137 @@ void report_logsASuccessStatusOtherThan201() throws Exception { client.close(); } + @Test + void report_aBaseUrlThatIsNotHttpIsLoggedFineAndNeverThrows() throws Exception { + // Arrange + // build() takes the base URL as a string and never parses it, so a + // typo only shows up in send(): "no protocol" is an IOException, and a + // file: URL opens a connection that is not an HttpURLConnection -- a + // ClassCastException, which is why send() catches RuntimeException too. + String[][] cases = { + {"not a url", "java.net.MalformedURLException"}, + {"file:///trace-client-test", "java.lang.ClassCastException"}, + }; + for (String[] misconfigured : cases) { + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.misconfigured." + misconfigured[1]); + logger.setLevel(Level.ALL); + logger.addHandler(log); + TraceClient client = assertDoesNotThrow(() -> + TraceClient.builder(misconfigured[0], "MyPlugin", "1.2.3").key("k").logger(logger).build()); + assertTrue(client.isEnabled(), "a bad URL is not an opt-out"); + + // Act + assertDoesNotThrow(() -> client.report("startup")); + client.close(); + + // Assert + assertTrue(log.await(5, TimeUnit.SECONDS), misconfigured[0] + " should be mentioned at FINE"); + LogRecord record = log.records.get(0); + assertEquals(Level.FINE, record.getLevel()); + assertTrue(record.getMessage().startsWith("[trace] could not deliver {\"application\":\"MyPlugin\""), + record.getMessage()); + assertTrue(record.getMessage().contains(misconfigured[1]), record.getMessage()); + } + } + + @Test + void report_drainsAResponseBodyAndKeepsSendingAfterAnError() throws Exception { + // Arrange + // Unlike the shared server, this one answers with a body: an error page + // first, then a 201 with content. send() reads either to its end and + // the next report still goes out. + List bodies = new CopyOnWriteArrayList<>(); + CountDownLatch both = new CountDownLatch(2); + HttpServer chatty = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + chatty.createContext("/", exchange -> { + bodies.add(new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8)); + byte[] reply = new byte[4096]; // more than drain()'s 512-byte buffer + Arrays.fill(reply, (byte) 'x'); + exchange.sendResponseHeaders(bodies.size() == 1 ? 500 : 201, reply.length); + exchange.getResponseBody().write(reply); + exchange.close(); + both.countDown(); + }); + chatty.start(); + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.chatty"); + logger.setLevel(Level.ALL); + logger.addHandler(log); + TraceClient client = TraceClient.builder("http://127.0.0.1:" + chatty.getAddress().getPort(), "MyPlugin", "1.2.3") + .key("k").logger(logger).build(); + + // Act + client.report("first"); + client.report("second"); + client.close(); + + // Assert + assertTrue(both.await(5, TimeUnit.SECONDS), "both reports should reach the server"); + assertEquals(2, bodies.size()); + assertTrue(bodies.get(1).contains("\"name\":\"second\""), bodies.get(1)); + assertEquals(1, log.records.size(), "only the 500 is worth a line: " + log.records); + assertEquals("[trace] trace server answered 500 for " + + "{\"application\":\"MyPlugin\",\"name\":\"first\",\"tags\":{\"version\":\"1.2.3\"}}", + log.records.get(0).getMessage()); + chatty.stop(0); + } + + @Test + void report_keepsAPathInTheBaseUrlInFrontOfApiMetrics() throws Exception { + // Arrange + // A trace server behind a reverse proxy under a sub-path: only the + // trailing slashes go, the path itself stays. + TraceClient client = TraceClient.builder(baseUrl() + "/trace/", "MyPlugin", "1.2.3").key("k").build(); + + // Act + client.report("startup"); + + // Assert + assertTrue(arrived.await(5, TimeUnit.SECONDS)); + assertEquals("/trace/api/metrics", received.get(0).path); + client.close(); + } + + @Test + void report_aRedirectIsNotFollowedAndIsLoggedFine() throws Exception { + // Arrange + // Characterizes current behaviour: the body is streamed with a fixed + // length, so HttpURLConnection cannot replay it to a redirect target. + // It throws HttpRetryException instead, so a base URL that redirects + // (http to https, say) drops every report, and the only trace of it + // is a FINE "could not deliver" line. + List paths = new CopyOnWriteArrayList<>(); + HttpServer redirecting = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + redirecting.createContext("/", exchange -> { + paths.add(exchange.getRequestURI().getPath()); + readAll(exchange.getRequestBody()); + exchange.getResponseHeaders().add("Location", "/moved/api/metrics"); + exchange.sendResponseHeaders(301, -1); + exchange.close(); + }); + redirecting.start(); + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.redirect"); + logger.setLevel(Level.ALL); + logger.addHandler(log); + TraceClient client = TraceClient.builder("http://127.0.0.1:" + redirecting.getAddress().getPort(), "MyPlugin", "1.2.3") + .key("k").logger(logger).build(); + + // Act + assertDoesNotThrow(() -> client.report("startup")); + + // Assert + assertTrue(log.await(5, TimeUnit.SECONDS), "the redirect should be mentioned at FINE"); + client.close(); + assertEquals(Collections.singletonList("/api/metrics"), paths, "the redirect target is never asked"); + assertEquals(Level.FINE, log.records.get(0).getLevel()); + String message = log.records.get(0).getMessage(); + assertTrue(message.startsWith("[trace] could not deliver {\"application\":\"MyPlugin\",\"name\":\"startup\""), message); + assertTrue(message.contains("java.net.HttpRetryException"), message); + redirecting.stop(0); + } + @Test void builder_trimsTheBaseUrlAndApplicationAndDropsEveryTrailingSlash() throws Exception { // Arrange @@ -628,16 +1126,17 @@ void serverWideConfig_enabledFalseDisablesWithTheServerWideReason(@TempDir Path } @Test - void serverWideConfig_acceptsEverySpellingOfOff(@TempDir Path plugins) throws Exception { + void serverWideConfig_onlyClearSpellingsOfOnLeaveReportingOn(@TempDir Path plugins) throws Exception { Path file = plugins.resolve("trace").resolve("config.yml"); Files.createDirectories(file.getParent()); - for (String off : new String[] {"false", "no", "0", "off", "OFF", "No"}) { + for (String off : new String[] {"false", "no", "0", "off", "OFF", "No", "\"false\"", "'off'", + "flase", "disabled", "anything-else"}) { Files.write(file, ("enabled: " + off + "\n").getBytes(StandardCharsets.UTF_8)); assertEquals(TraceClient.REASON_SERVER_WIDE, TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build().disabledReason(), "enabled: " + off + " should disable"); } - for (String on : new String[] {"true", "yes", "1", "on", "anything-else"}) { + for (String on : new String[] {"true", "yes", "1", "on", "ON", "\"true\""}) { Files.write(file, ("enabled: " + on + "\n").getBytes(StandardCharsets.UTF_8)); assertNull(TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build().disabledReason(), "enabled: " + on + " should not disable"); @@ -648,40 +1147,218 @@ void serverWideConfig_acceptsEverySpellingOfOff(@TempDir Path plugins) throws Ex } @Test - void environment_disablesAndWinsOverTheServerWideFile(@TempDir Path plugins) throws Exception { - // Arrange - // The file says on; the environment says off. The environment wins, - // and is the reason given. - TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build().close(); - assertTrue(Files.readAllLines(plugins.resolve("trace").resolve("config.yml"), StandardCharsets.UTF_8).contains("enabled: true")); + void serverWideConfig_theSwitchIgnoresATrailingCommentAndLeadingIndent() { + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: false # off for now")).disables); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList(" enabled: false")).disables, + "indented, but outside a tags: block, it is still the switch"); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled :\tFALSE")).disables); + } - for (String off : new String[] {"off", "OFF", "false", "0", "no", " No "}) { - environment.clear(); - environment.put("TRACE_USAGE_REPORTING", off); - TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); - assertFalse(client.isEnabled(), "TRACE_USAGE_REPORTING=" + off + " should disable"); - assertEquals("environment", client.disabledReason()); - client.report("startup"); - client.close(); + @Test + void serverWideConfig_aQuotedOffDisables() { + // Issue #15: the value used to be compared with its quotes on. + for (String quoted : new String[] {"\"false\"", "'false'", "\"off\"", "'no'"}) { + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: " + quoted)).disables, + "enabled: " + quoted); } - for (String yes : new String[] {"1", "true", "TRUE", "yes"}) { - environment.clear(); - environment.put("DO_NOT_TRACK", yes); - TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); - assertFalse(client.isEnabled(), "DO_NOT_TRACK=" + yes + " should disable"); - assertEquals("environment", client.disabledReason()); - client.report("startup"); - client.close(); + assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: \"true\"")).disables); + } + + @Test + void environment_thatCannotBeReadOptsOut() { + java.util.function.Function saved = TraceClient.environment; + TraceClient.environment = name -> { throw new SecurityException("getenv." + name); }; + try { + TraceClient client = assertDoesNotThrow(() -> TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build()); + assertEquals(TraceClient.REASON_ENVIRONMENT, client.disabledReason()); + assertDoesNotThrow(() -> TraceClient.disabled()); + } finally { + TraceClient.environment = saved; } - assertFalse(arrived.await(300, TimeUnit.MILLISECONDS), "nothing should have been sent"); + } - // Values that are not an opt-out leave the client alone. - environment.clear(); + @Test + void allowsReporting_failsClosed() { + assertTrue(TraceClient.allowsReporting(true)); + assertTrue(TraceClient.allowsReporting("true")); + assertTrue(TraceClient.allowsReporting(" ON ")); + assertTrue(TraceClient.allowsReporting("yes")); + assertTrue(TraceClient.allowsReporting("1")); + assertFalse(TraceClient.allowsReporting(false)); + assertFalse(TraceClient.allowsReporting("false")); + assertFalse(TraceClient.allowsReporting("off")); + assertFalse(TraceClient.allowsReporting("flase")); + assertFalse(TraceClient.allowsReporting("")); + assertFalse(TraceClient.allowsReporting(1)); + assertFalse(TraceClient.allowsReporting(null)); + } + + @Test + void serverWideConfig_aFileThatIsNotUtf8IsStillObeyed(@TempDir Path plugins) throws Exception { + // Issue #40: one byte of another encoding used to fail the whole read, + // so the enabled: false below it was never seen. + Path file = plugins.resolve("trace").resolve("config.yml"); + Files.createDirectories(file.getParent()); + byte[] latin1 = "# café\nenabled: false\n".getBytes(StandardCharsets.ISO_8859_1); + Files.write(file, latin1); + + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .serverWideConfig(plugins.toFile()).build(); + + assertEquals(TraceClient.REASON_SERVER_WIDE, client.disabledReason()); + assertArrayEquals(latin1, Files.readAllBytes(file), "the file is left as it is"); + client.close(); + } + + @Test + void serverWideConfig_aFileThatIsThereButUnreadableDisables(@TempDir Path plugins) throws Exception { + // A directory where the file should be cannot be read, and may be + // hiding an opt-out: reporting stays off. + Files.createDirectories(plugins.resolve("trace").resolve("config.yml")); + + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .serverWideConfig(plugins.toFile()).build(); + + assertEquals(TraceClient.REASON_SERVER_WIDE, client.disabledReason()); + } + + @Test + void serverWideConfig_aByteOrderMarkHidesAFirstLineEnabledFalseYet(@TempDir Path plugins) throws Exception { + // Characterizes current behaviour, which issue #40 questions: the + // mark is not whitespace to ENABLED_LINE, so the line does not match. + // Arrange + Path file = plugins.resolve("trace").resolve("config.yml"); + Files.createDirectories(file.getParent()); + Files.write(file, "enabled: false\n".getBytes(StandardCharsets.UTF_8)); + + // Act + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .serverWideConfig(plugins.toFile()).build(); + + // Assert + assertTrue(client.isEnabled(), "the switch was not recognised"); + client.close(); + } + + @Test + void environment_disablesAndWinsOverTheServerWideFile(@TempDir Path plugins) throws Exception { + // Arrange + // The file says on; the environment says off. The environment wins, + // and is the reason given. + TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build().close(); + assertTrue(Files.readAllLines(plugins.resolve("trace").resolve("config.yml"), StandardCharsets.UTF_8).contains("enabled: true")); + + for (String off : new String[] {"off", "OFF", "false", "0", "no", " No "}) { + environment.clear(); + environment.put("TRACE_USAGE_REPORTING", off); + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); + assertFalse(client.isEnabled(), "TRACE_USAGE_REPORTING=" + off + " should disable"); + assertEquals("environment", client.disabledReason()); + client.report("startup"); + client.close(); + } + for (String yes : new String[] {"1", "true", "TRUE", "yes"}) { + environment.clear(); + environment.put("DO_NOT_TRACK", yes); + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); + assertFalse(client.isEnabled(), "DO_NOT_TRACK=" + yes + " should disable"); + assertEquals("environment", client.disabledReason()); + client.report("startup"); + client.close(); + } + assertFalse(arrived.await(300, TimeUnit.MILLISECONDS), "nothing should have been sent"); + + // Values that are not an opt-out leave the client alone. + environment.clear(); environment.put("TRACE_USAGE_REPORTING", "on"); environment.put("DO_NOT_TRACK", "0"); assertNull(TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build().disabledReason()); } + @Test + void environment_eitherVariableAloneTurnsReportingOffWhateverTheOtherSays() { + // Arrange: one variable opts out, the other says something that is + // not an opt-out. Neither can cancel the other. + String[][] pairs = { + {"on", "1"}, + {"true", " Yes "}, + {"off", "0"}, + {"No", "false"}, + }; + + for (String[] pair : pairs) { + environment.clear(); + environment.put("TRACE_USAGE_REPORTING", pair[0]); + environment.put("DO_NOT_TRACK", pair[1]); + + // Act + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + + // Assert + assertEquals(TraceClient.REASON_ENVIRONMENT, client.disabledReason(), + "TRACE_USAGE_REPORTING=" + pair[0] + ", DO_NOT_TRACK=" + pair[1]); + assertFalse(client.isEnabled()); + } + } + + @Test + void environment_onlyBlankOrAClearOnLeavesReportingOn() { + // Fails closed: once a variable is set to anything but blank, only a + // value that clearly means "keep reporting" leaves it on. + for (String value : new String[] {"", " ", "on", "true", "yes", "1", "TRUE"}) { + environment.clear(); + environment.put("TRACE_USAGE_REPORTING", value); + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + assertNull(client.disabledReason(), "TRACE_USAGE_REPORTING=\"" + value + "\""); + client.close(); + } + for (String value : new String[] {"disabled", "offline", "nope", "2"}) { + environment.clear(); + environment.put("TRACE_USAGE_REPORTING", value); + assertEquals(TraceClient.REASON_ENVIRONMENT, + TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build().disabledReason(), + "TRACE_USAGE_REPORTING=\"" + value + "\""); + } + for (String value : new String[] {"", " ", "0", "false", "no", "off"}) { + environment.clear(); + environment.put("DO_NOT_TRACK", value); + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + assertNull(client.disabledReason(), "DO_NOT_TRACK=\"" + value + "\""); + client.close(); + } + for (String value : new String[] {"2", "y", "please"}) { + environment.clear(); + environment.put("DO_NOT_TRACK", value); + assertEquals(TraceClient.REASON_ENVIRONMENT, + TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build().disabledReason(), + "DO_NOT_TRACK=\"" + value + "\""); + } + } + + @Test + void disabled_isOffForTheConfigReasonUnlessTheEnvironmentSaysSoFirst() { + // Act + TraceClient byDefault = TraceClient.disabled(); + + // Assert + assertFalse(byDefault.isEnabled()); + assertEquals(TraceClient.REASON_CONFIG, byDefault.disabledReason()); + assertNull(byDefault.installId(), "a disabled client has no install ID"); + + // Arrange: the environment is checked before the client's own switch, + // so it is the reason even here. + environment.put("DO_NOT_TRACK", "1"); + + // Act + TraceClient byEnvironment = TraceClient.disabled(); + + // Assert + assertFalse(byEnvironment.isEnabled()); + assertEquals(TraceClient.REASON_ENVIRONMENT, byEnvironment.disabledReason()); + byDefault.close(); + byEnvironment.close(); + } + @Test void disabledReason_followsThePrecedenceEnvironmentThenServerWideThenConfigThenKey(@TempDir Path plugins) throws Exception { // Arrange: everything says off at once. @@ -806,6 +1483,45 @@ void serverWideTags_blockEndsAtTheNextUnindentedLineOrEndOfFile() { assertTrue(tagsOf("tags:\nenabled: true\n").isEmpty()); } + @Test + void serverWideTags_aSecondTagsBlockAddsToTheFirstAndTheFirstEntryOfAKeyWins() { + // Arrange + // Two blocks, as an operator might leave after pasting an example + // below their own; the second is indented differently from the first. + String content = "tags:\n" + + " ci: \"true\"\n" + + " env: staging\n" + + "enabled: true\n" + + "tags:\n" + + " env: prod\n" + + " region: eu\n"; + + // Act + TraceClient.ServerWideConfig config = TraceClient.parseServerWideConfig(Arrays.asList(content.split("\n", -1))); + + // Assert + Map expected = new LinkedHashMap<>(); + expected.put("ci", "true"); + expected.put("env", "staging"); + expected.put("region", "eu"); + assertEquals(expected, config.tags, "each block takes its own indent; a key already read is not replaced"); + assertFalse(config.disables); + } + + @Test + void serverWideTags_theTagsLineIsCaseSensitiveAndAllowsSpaceBeforeTheColon() { + // Arrange, Act and Assert + assertEquals(Collections.singletonMap("ci", "true"), tagsOf("tags :\n ci: \"true\"\n")); + assertTrue(tagsOf("Tags:\n ci: \"true\"\n").isEmpty(), "Tags: is not tags:"); + assertTrue(tagsOf("tags: ci\n env: prod\n").isEmpty(), "a value on the tags: line is not a block"); + + // Under a line that does not open a block, an indented enabled: is + // outside any tags: block, so it is the switch. + TraceClient.ServerWideConfig config = TraceClient.parseServerWideConfig(Arrays.asList("Tags:", " enabled: false")); + assertTrue(config.disables); + assertTrue(config.tags.isEmpty()); + } + @Test void serverWideTags_dropEntriesTheServerWouldRejectOrThatAreNotUnderstood() { StringBuilder longText = new StringBuilder(); @@ -839,6 +1555,67 @@ void serverWideTags_dropEntriesTheServerWouldRejectOrThatAreNotUnderstood() { assertEquals(expected, tags); } + @Test + void serverWideTags_doubleQuotedValuesUnescapeNewlineTabCarriageReturnAndBackslash() { + Map tags = tagsOf("tags:\n" + + " a: \"line\\nbreak\\ttab\\rreturn\"\n" + + " b: \"back\\\\slash\\/solidus\\qother\"\n" + + " c: 'single \\n stays'\n"); + Map expected = new LinkedHashMap<>(); + expected.put("a", "line\nbreak\ttab\rreturn"); + expected.put("b", "back\\slash/solidusqother"); + expected.put("c", "single \\n stays"); + assertEquals(expected, tags); + } + + @Test + void serverWideTags_dropKeysAndValuesWhoseQuoteIsNeverClosed() { + Map tags = tagsOf("tags:\n" + + " \"open-double: x\n" + + " 'open-single: x\n" + + " \"mismatched': x\n" + + " \": lone-quote\n" + + " value: \"ends in a backslash\\\n" + + " ok: fine\n"); + assertEquals(Collections.singletonMap("ok", "fine"), tags); + } + + @Test + void serverWideTags_aSingleQuotedValueTakesACommentButNothingElseAfterIt() { + Map tags = tagsOf("tags:\n" + + " a: 'x' # comment after a quote\n" + + " b: 'x' junk\n"); + assertEquals(Collections.singletonMap("a", "x"), tags); + } + + @Test + void serverWideTags_dropValuesThatOpenAnAnchorAliasTagOrFoldedScalar() { + Map tags = tagsOf("tags:\n" + + " anchor: &a x\n" + + " alias: *a\n" + + " tag: !!str x\n" + + " directive: %x\n" + + " at: @x\n" + + " backtick: `x\n" + + " folded: >\n" + + " ok: fine\n"); + assertEquals(Collections.singletonMap("ok", "fine"), tags); + } + + @Test + void serverWideTags_aHashIsACommentOnlyAfterWhitespace() { + Map tags = tagsOf("tags:\n" + + " a: issue#13\n" + + " b: x\t# tab before the hash\n" + + "\tc: tab-separated\n" + + " d:\tafter-a-tab\n"); + Map expected = new LinkedHashMap<>(); + expected.put("a", "issue#13"); + expected.put("b", "x"); + expected.put("d", "after-a-tab"); + assertEquals(expected, tags, "c is indented differently from the block's first entry"); + } + @Test void serverWideTags_areCappedSoTheEventStaysWithinTheServersTagLimit(@TempDir Path plugins) throws Exception { // Arrange: 40 server-wide tags, 29 event tags. @@ -935,8 +1712,8 @@ void serverWideTags_malformedFileNeverThrowsAndReportingStillWorks(@TempDir Path byte[] notUtf8 = Files.readAllBytes(file); String body = reportedBody(plugins, "startup", null); assertTrue(body.matches("\\{\"application\":\"MyPlugin\",\"name\":\"startup\",\"tags\":" - + "\\{\"version\":\"1\\.2\\.3\",\"install\":\"" + UUID_PATTERN + "\"}}"), - "a file that is not UTF-8 counts as enabled with no tags, and an in-memory install ID: " + body); + + "\\{\"version\":\"1\\.2\\.3\",\"install\":\"" + UUID_PATTERN + "\",\"ci\":\"\u00c3\\(\"}}"), + "a file that is not UTF-8 is read as ISO-8859-1, with an in-memory install ID: " + body); assertArrayEquals(notUtf8, Files.readAllBytes(file), "a file that cannot be read is never appended to"); } @@ -947,6 +1724,56 @@ void withServerWideTags_leavesTheEventAloneWhenThereAreNone() { assertNull(TraceClient.withServerWideTags(null, Collections.emptyMap())); } + @Test + void withServerWideTags_dropsNullTagsLetsTheEventWinAndNeverModifiesTheCallersMap() { + // Arrange + Map tags = new LinkedHashMap<>(); + tags.put("name", "home"); + tags.put("nullValue", null); + tags.put(null, "nullKey"); + tags.put("ci", "the-events-own"); + Map serverWide = new LinkedHashMap<>(); + serverWide.put("ci", "true"); + serverWide.put("env", "staging"); + + // Act + Map merged = TraceClient.withServerWideTags(tags, serverWide); + + // Assert + Map expected = new LinkedHashMap<>(); + expected.put("name", "home"); + expected.put("ci", "the-events-own"); + expected.put("env", "staging"); + assertEquals(expected, merged); + assertEquals(new ArrayList<>(expected.keySet()), new ArrayList<>(merged.keySet()), "event tags first, then server-wide"); + assertEquals(4, tags.size(), "the caller's map is not modified"); + assertEquals(serverWide, TraceClient.withServerWideTags(null, serverWide), "an event with no tags gets the server-wide ones"); + } + + @Test + void withServerWideTags_addsNoneToAnEventAlreadyAtOrOverMaxTags() { + // Arrange + Map atMax = new LinkedHashMap<>(); + for (int i = 0; i < TraceClient.MAX_TAGS; i++) { + atMax.put("e" + i, "v"); + } + Map overMax = new LinkedHashMap<>(atMax); + overMax.put("version", "1.2.3"); // what withVersion does today, see issue #13 + Map oneShort = new LinkedHashMap<>(atMax); + oneShort.remove("e0"); + Map serverWide = new LinkedHashMap<>(); + serverWide.put("ci", "true"); + serverWide.put("env", "staging"); + + // Act + Assert + assertEquals(atMax, TraceClient.withServerWideTags(atMax, serverWide)); + assertEquals(overMax, TraceClient.withServerWideTags(overMax, serverWide), "the cap adds nothing, and drops nothing either"); + Map filled = TraceClient.withServerWideTags(oneShort, serverWide); + assertEquals(TraceClient.MAX_TAGS, filled.size()); + assertEquals("true", filled.get("ci")); + assertFalse(filled.containsKey("env"), "only the first server-wide tag fits"); + } + @Test void serverWideConfig_ioFailureIsLoggedFineAndTreatedAsEnabled(@TempDir Path scratch) throws Exception { // Arrange @@ -1051,6 +1878,14 @@ void installId_anExistingServerIdIsUsedAndAnUnusableOneIsIgnored() { assertEquals("abc-123", TraceClient.parseServerWideConfig(Arrays.asList("server-id: \"abc-123\" # mine")).serverId); assertEquals("first", TraceClient.parseServerWideConfig(Arrays.asList("server-id: first", "server-id: second")).serverId); assertEquals("good", TraceClient.parseServerWideConfig(Arrays.asList("server-id:", "server-id: has space", "server-id: good")).serverId); + assertNull(TraceClient.parseServerWideConfig(Arrays.asList("server-id: _mine")).serverId, "starts with a letter or digit"); + assertEquals("good", TraceClient.parseServerWideConfig(Arrays.asList("server-id: -mine", "server-id: good")).serverId); + StringBuilder overlong = new StringBuilder(); + for (int i = 0; i <= TraceClient.MAX_TAG_LENGTH; i++) { + overlong.append('a'); + } + assertNull(TraceClient.parseServerWideConfig(Arrays.asList("server-id: " + overlong)).serverId, + "at most MAX_TAG_LENGTH characters"); assertNull(TraceClient.parseServerWideConfig(Arrays.asList(" server-id: indented")).serverId, "column 0 only"); assertNull(TraceClient.parseServerWideConfig(Arrays.asList("# server-id: commented")).serverId); TraceClient.ServerWideConfig inTags = TraceClient.parseServerWideConfig(Arrays.asList("tags:", " server-id: x")); @@ -1058,6 +1893,21 @@ void installId_anExistingServerIdIsUsedAndAnUnusableOneIsIgnored() { assertEquals(Collections.singletonMap("server-id", "x"), inTags.tags); } + @Test + void installId_theServerIdLineNeedsNoSpaceAroundItsColonAndIsCaseSensitive() { + // Unlike a tags: entry, where "a:b" is a string and not a pair, the + // server-id: line takes its value straight after the colon, and + // allows space before the colon. + assertEquals("abc", TraceClient.parseServerWideConfig(Arrays.asList("server-id:abc")).serverId); + assertEquals("abc", TraceClient.parseServerWideConfig(Arrays.asList("server-id : abc")).serverId); + assertEquals("abc", TraceClient.parseServerWideConfig(Arrays.asList("server-id:\tabc\t")).serverId); + + // The name itself is matched exactly. + assertNull(TraceClient.parseServerWideConfig(Arrays.asList("Server-Id: abc")).serverId); + assertNull(TraceClient.parseServerWideConfig(Arrays.asList("server_id: abc")).serverId); + assertNull(TraceClient.parseServerWideConfig(Arrays.asList("server-ids: abc")).serverId); + } + @Test void installId_unwritableConfigFallsBackToAnInMemoryIdWithoutThrowing(@TempDir Path scratch) throws Exception { // Arrange: a "plugins directory" that is a regular file, so nothing @@ -1082,6 +1932,114 @@ void installId_unwritableConfigFallsBackToAnInMemoryIdWithoutThrowing(@TempDir P assertEquals("not a directory", new String(Files.readAllBytes(notADirectory), StandardCharsets.UTF_8)); } + @Test + void installId_aConfigThatCannotBeAppendedToFallsBackToAnInMemoryIdAndIsLoggedFine(@TempDir Path plugins) throws Exception { + // Arrange + // The test above fails at the read. To fail at the append, the file + // has to read fine and refuse a write, even as root: /proc/version + // does, and has no enabled: or server-id: line in it. + Path readOnly = Paths.get("/proc/version"); + assumeTrue(Files.isReadable(readOnly), "needs Linux's /proc"); + Path config = Files.createDirectory(plugins.resolve("trace")).resolve("config.yml"); + Files.createSymbolicLink(config, readOnly); + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.serverIdAppend"); + logger.setLevel(Level.ALL); + logger.addHandler(log); + + // Act + TraceClient first = assertDoesNotThrow(() -> TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .serverWideConfig(plugins.toFile()).logger(logger).build()); + TraceClient second = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); + first.report("startup"); + + // Assert + assertTrue(arrived.await(5, TimeUnit.SECONDS)); + first.close(); + second.close(); + assertTrue(first.isEnabled()); + assertTrue(first.installId().matches(UUID_PATTERN), first.installId()); + assertNotEquals(first.installId(), second.installId(), "nothing persisted: each process gets its own"); + assertTrue(received.get(0).body.contains("\"install\":\"" + first.installId() + "\""), received.get(0).body); + assertTrue(log.await(1, TimeUnit.SECONDS), "the fallback should be mentioned at FINE"); + assertEquals(Level.FINE, log.records.get(0).getLevel()); + assertTrue(log.records.get(0).getMessage().contains("could not write server-id"), log.records.get(0).getMessage()); + } + + @Test + void installId_anUnreadableConfigIsLoggedFineAndNotAppendedTo(@TempDir Path scratch) throws Exception { + // Arrange: as above, a "plugins directory" that is a regular file. + Path notADirectory = scratch.resolve("plugins"); + Files.write(notADirectory, "not a directory".getBytes(StandardCharsets.UTF_8)); + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.unreadableServerId"); + logger.setLevel(Level.ALL); + logger.addHandler(log); + + // Act + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .serverWideConfig(notADirectory.toFile()).logger(logger).build(); + client.close(); + + // Assert: both happen on the building thread, so they are already logged. + assertEquals(2, log.records.size(), log.records.toString()); + assertEquals(Level.FINE, log.records.get(0).getLevel()); + assertTrue(log.records.get(0).getMessage().startsWith("[trace] could not create server-wide config "), + log.records.get(0).getMessage()); + assertEquals(Level.FINE, log.records.get(1).getLevel()); + assertEquals("[trace] using an in-memory server-id for this process: server-wide config was not readable", + log.records.get(1).getMessage()); + } + + @Test + void installId_isAppendedToAnEmptyConfigWithoutALeadingBlankLine(@TempDir Path plugins) throws Exception { + // Arrange: the file exists but is empty, so build() does not create it. + Path file = writeServerWideConfigExactly(plugins, ""); + + // Act + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); + client.close(); + + // Assert + assertTrue(client.isEnabled(), "no enabled: line counts as enabled"); + assertEquals(TraceClient.SERVER_ID_COMMENT + "server-id: " + client.installId() + "\n", + new String(Files.readAllBytes(file), StandardCharsets.UTF_8)); + } + + @Test + void installId_isAppendedDirectlyBelowAConfigThatEndsInANewline(@TempDir Path plugins) throws Exception { + // Arrange + Path file = writeServerWideConfigExactly(plugins, "enabled: true\n"); + + // Act + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); + client.close(); + + // Assert + assertEquals("enabled: true\n" + TraceClient.SERVER_ID_COMMENT + "server-id: " + client.installId() + "\n", + new String(Files.readAllBytes(file), StandardCharsets.UTF_8)); + } + + @Test + void installId_anUnusableServerIdLineGetsAUsableOneAppendedAndKept(@TempDir Path plugins) throws Exception { + // Arrange: an operator's hand-typed ID with a space in it. + Path file = writeServerWideConfigExactly(plugins, "enabled: true\nserver-id: has space\n"); + + // Act + TraceClient first = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); + String afterFirst = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); + TraceClient second = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build(); + first.close(); + second.close(); + + // Assert + assertTrue(first.installId().matches(UUID_PATTERN), first.installId()); + assertEquals("enabled: true\nserver-id: has space\n" + TraceClient.SERVER_ID_COMMENT + "server-id: " + first.installId() + "\n", + afterFirst, "the unusable line is left alone, not rewritten"); + assertEquals(first.installId(), second.installId(), "the appended line is the one read from then on"); + assertEquals(afterFirst, new String(Files.readAllBytes(file), StandardCharsets.UTF_8), "and nothing more is appended"); + } + @Test void installId_aDisabledClientNeitherGeneratesNorWritesOne(@TempDir Path plugins) throws Exception { Path file = plugins.resolve("trace").resolve("config.yml"); @@ -1152,6 +2110,27 @@ void installId_canBeGivenExplicitlyByAProgramThatIsNotAPlugin(@TempDir Path plug new String(Files.readAllBytes(plugins.resolve("trace").resolve("config.yml")), StandardCharsets.UTF_8)); } + @Test + void builder_rejectsAnOverlongInstallIdAndAcceptsOneAtTheLimit() { + // Arrange + StringBuilder max = new StringBuilder(); + for (int i = 0; i < TraceClient.MAX_TAG_LENGTH; i++) { + max.append('i'); + } + TraceClient.Builder builder = TraceClient.builder(baseUrl(), "MyCli", "1.2.3"); + + // Act + IllegalArgumentException tooLong = assertThrows(IllegalArgumentException.class, + () -> builder.installId(max + "i")); + builder.installId(" " + max + " "); + + // Assert + assertEquals("installId is longer than " + TraceClient.MAX_TAG_LENGTH + " characters", tooLong.getMessage()); + TraceClient client = builder.key("k").build(); + assertEquals(max.toString(), client.installId(), "surrounding whitespace does not count"); + client.close(); + } + @Test void installId_anEventsOwnInstallTagWins(@TempDir Path plugins) throws Exception { // Arrange @@ -1250,6 +2229,36 @@ void installIdFile_unwritableYieldsAnInMemoryIdWithoutThrowing(@TempDir Path scr "the fallback is logged at FINE"); } + @Test + void installIdFile_aWriteThatFailsYieldsAnInMemoryIdAndIsLoggedFine(@TempDir Path scratch) throws Exception { + // Arrange + // The test above fails at the read. A link into a directory that does + // not exist reads as "no such file", so the client goes on to write, + // and that fails too, even as root. + assumeTrue(File.separatorChar == '/', "needs POSIX symbolic links"); + Path target = scratch.resolve("missing").resolve("trace-install-id"); + Path link = Files.createSymbolicLink(scratch.resolve("trace-install-id"), target); + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.installIdFileWrite"); + logger.setLevel(Level.ALL); + logger.addHandler(log); + + // Act + TraceClient client = assertDoesNotThrow(() -> TraceClient.builder(baseUrl(), "MyCli", "1.2.3").key("k") + .installIdFile(link.toFile()).logger(logger).build()); + client.report("startup"); + + // Assert + assertTrue(arrived.await(5, TimeUnit.SECONDS)); + client.close(); + assertTrue(client.installId().matches(UUID_PATTERN), client.installId()); + assertTrue(received.get(0).body.contains("\"install\":\"" + client.installId() + "\""), received.get(0).body); + assertFalse(Files.exists(target)); + assertTrue(log.await(1, TimeUnit.SECONDS), "the fallback should be mentioned at FINE"); + assertEquals(Level.FINE, log.records.get(0).getLevel()); + assertTrue(log.records.get(0).getMessage().contains("could not write install ID file"), log.records.get(0).getMessage()); + } + @Test void installIdFromFile_leavesAnUnreadableFileAlone(@TempDir Path scratch) throws Exception { // A directory cannot be read as a file. @@ -1264,6 +2273,34 @@ void installIdFromFile_leavesAnUnreadableFileAlone(@TempDir Path scratch) throws } } + @Test + void installIdFile_aFileThatIsNotUtf8IsLeftAloneAndAnInMemoryIdIsUsed(@TempDir Path scratch) throws Exception { + // Arrange + // An ID line below a comment saved in ISO-8859-1: the 0xE9 byte is + // not UTF-8, so the whole file fails to read, valid line and all. + Path file = scratch.resolve("trace-install-id"); + byte[] content = "# café\nmy-own-id\n".getBytes(StandardCharsets.ISO_8859_1); + Files.write(file, content); + RecordingHandler log = new RecordingHandler(); + Logger logger = Logger.getLogger("TraceClientTest.installIdFileNotUtf8"); + logger.setLevel(Level.ALL); + logger.addHandler(log); + + // Act + TraceClient client = assertDoesNotThrow(() -> TraceClient.builder(baseUrl(), "MyCli", "1.2.3").key("k") + .installIdFile(file.toFile()).logger(logger).build()); + client.close(); + + // Assert + assertTrue(client.isEnabled()); + assertTrue(client.installId().matches(UUID_PATTERN), client.installId()); + assertArrayEquals(content, Files.readAllBytes(file), "a file that cannot be read is never overwritten"); + assertNotEquals(client.installId(), TraceClient.installIdFromFile(file.toFile()), "in memory: a new one each process"); + assertTrue(log.await(1, TimeUnit.SECONDS), "the fallback should be mentioned at FINE"); + assertEquals(Level.FINE, log.records.get(0).getLevel()); + assertTrue(log.records.get(0).getMessage().contains("could not read install ID file"), log.records.get(0).getMessage()); + } + @Test void installIdFromFile_neverThrowsForABadPath() { for (File file : new File[] {null, new File(""), new File(" "), new File("bad\u0000name")}) { @@ -1358,6 +2395,459 @@ private static Map tagsOf(String content) { return TraceClient.parseServerWideConfig(Arrays.asList(content.split("\n", -1))).tags; } + /** Waits until the shared server has received {@code count} reports, or 5 s pass. */ + private void awaitReceived(int count) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (received.size() < count && System.nanoTime() < deadline) { + Thread.sleep(20); + } + } + + @Test + void coalesce_sendsTheFirstAtOnceAndTheRepeatsAsOneCountedEventWhenTheWindowCloses() throws Exception { + // Arrange + // The flood that prompted this: another plugin dispatching /power + // every 100 ms, each one a command event. + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .coalesceWindowMillis(1_000).build(); + Map power = Collections.singletonMap("name", "power"); + + // Act + for (int i = 0; i < 50; i++) { + client.report("command", null, power); + } + + // Assert + assertTrue(arrived.await(5, TimeUnit.SECONDS), "the first report goes out at once"); + Thread.sleep(200); + assertEquals(1, received.size(), "the repeats wait for the window to close"); + awaitReceived(2); + assertEquals(2, received.size(), "one event for all 49 repeats"); + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"tags\":{\"name\":\"power\",\"version\":\"1.2.3\"}}", + received.get(0).body); + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":49.0," + + "\"tags\":{\"name\":\"power\",\"version\":\"1.2.3\",\"coalesced\":\"49\"}}", + received.get(1).body); + client.close(); + assertEquals(2, received.size(), "nothing was left to flush"); + } + + @Test + void coalesce_aSteadyFloodIsOneEventPerWindowAndAQuietWindowEnds() throws Exception { + // Arrange + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .coalesceWindowMillis(300).build(); + + // Act + // About four windows of a report every 10 ms, then quiet. + long until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1_200); + int reports = 0; + while (System.nanoTime() < until) { + client.report("command", null, Collections.singletonMap("name", "power")); + reports++; + Thread.sleep(10); + } + long quiet = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (client.coalescing() > 0 && System.nanoTime() < quiet) { + Thread.sleep(20); + } + + // Assert + assertEquals(0, client.coalescing(), "a window that counted nothing ends"); + int sent = received.size(); + assertTrue(sent >= 3 && sent <= 7, "about one event per 300 ms window, but sent " + sent + " for " + reports); + long total = 1; + for (Received request : received.subList(1, sent)) { + java.util.regex.Matcher count = java.util.regex.Pattern.compile("\"coalesced\":\"(\\d+)\"").matcher(request.body); + assertTrue(count.find(), "every event after the first is a count: " + request.body); + total += Long.parseLong(count.group(1)); + } + assertEquals(reports, total, "the counts add up to every report"); + client.close(); + assertEquals(sent, received.size(), "nothing was left to flush"); + } + + @Test + void coalesce_aWindowThatClosesLeavesOneOpenedLaterToItsOwnDeadline() throws Exception { + // Arrange + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .coalesceWindowMillis(2_000).build(); + Map early = Collections.singletonMap("name", "early"); + Map late = Collections.singletonMap("name", "late"); + + // Act + // Half a window apart, so the flush that closes the first finds the + // second still open. + client.report("command", null, early); + client.report("command", null, early); + Thread.sleep(1_000); + client.report("command", null, late); + client.report("command", null, late); + awaitReceived(3); + + // Assert + assertEquals(3, received.size(), "two first reports and the early count"); + assertTrue(received.get(2).body.contains("\"name\":\"early\"") && received.get(2).body.contains("\"coalesced\":\"1\""), + received.get(2).body); + Thread.sleep(200); + assertEquals(3, received.size(), "the late window has not closed yet"); + awaitReceived(4); + assertEquals(4, received.size(), "it gets a flush of its own"); + assertTrue(received.get(3).body.contains("\"name\":\"late\"") && received.get(3).body.contains("\"coalesced\":\"1\""), + received.get(3).body); + client.close(); + } + + @Test + void close_sendsEveryCountStillOpen() throws Exception { + // Arrange + // The real window, a minute: only close() can send these counts. + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + for (int i = 0; i < 10; i++) { + client.report("command", null, Collections.singletonMap("name", "home")); + } + for (int i = 0; i < 3; i++) { + client.report("command", null, Collections.singletonMap("name", "spawn")); + } + client.report("command", null, Collections.singletonMap("name", "once")); + + // Act + long before = System.nanoTime(); + client.close(); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - before); + + // Assert + assertTrue(elapsedMs < 5_000, "close() must not wait for the window: took " + elapsedMs + " ms"); + List bodies = received.stream().map(r -> r.body).collect(Collectors.toList()); + assertEquals(5, bodies.size(), "three first reports and two counts: " + bodies); + assertTrue(bodies.contains("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":9.0," + + "\"tags\":{\"name\":\"home\",\"version\":\"1.2.3\",\"coalesced\":\"9\"}}"), bodies.toString()); + assertTrue(bodies.contains("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":2.0," + + "\"tags\":{\"name\":\"spawn\",\"version\":\"1.2.3\",\"coalesced\":\"2\"}}"), bodies.toString()); + assertEquals(1, bodies.stream().filter(b -> b.contains("\"once\"")).count(), "nothing to count, nothing more sent"); + } + + @Test + void close_aCountThatFindsTheQueueFullIsDropped() throws Exception { + // Arrange + // Hold the sending thread on the first report, so nothing behind it + // leaves the queue until close() has tried to queue the count. + CountDownLatch holding = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + List bodies = new CopyOnWriteArrayList<>(); + HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + slow.createContext("/", exchange -> { + bodies.add(new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8)); + holding.countDown(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + exchange.sendResponseHeaders(201, -1); + exchange.close(); + }); + slow.start(); + TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "MyPlugin", "1.2.3") + .key("k").build(); + client.report("command"); + client.report("command"); // counted, so close() has a count to send + assertTrue(holding.await(5, TimeUnit.SECONDS), "the first report is in flight"); + for (int i = 0; i < TraceClient.QUEUE_CAPACITY; i++) { + client.report("startup"); // never coalesced: every one takes a place in the queue + } + + // Act + Thread closing = new Thread(client::close); + closing.start(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (client.coalescing() > 0 && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertEquals(0, client.coalescing(), "close() has flushed"); + release.countDown(); + closing.join(10_000); + + // Assert + assertFalse(closing.isAlive(), "close() returned"); + assertTrue(bodies.size() > 1, "the queue behind the first report drained"); + assertTrue(bodies.stream().noneMatch(b -> b.contains(TraceClient.COALESCED_TAG)), bodies.toString()); + slow.stop(0); + } + + @Test + void coalesce_keysOnNameValueAndTagsButNotTagOrder() throws Exception { + // Arrange + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + Map ab = new LinkedHashMap<>(); + ab.put("a", "1"); + ab.put("b", "2"); + Map ba = new LinkedHashMap<>(); + ba.put("b", "2"); + ba.put("a", "1"); + + // Act + client.report("command", null, ab); + client.report("command", null, ba); // the same event + client.report("command", 2.5, ab); // a different value: a different event + client.report("command", 2.5, ab); + client.report("command", 2.5, ab); + client.report("other", null, ab); // a different name + client.report("command", null, Collections.singletonMap("a", "1")); // different tags + client.report("command", Double.NaN, ab); // NaN is sent as no value: the first event again + awaitReceived(4); + Thread.sleep(200); + int sentAtOnce = received.size(); + client.close(); + + // Assert + assertEquals(4, sentAtOnce, "one first report per distinct event"); + List bodies = received.stream().map(r -> r.body).collect(Collectors.toList()); + assertEquals(6, bodies.size(), bodies.toString()); + assertTrue(bodies.contains("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":2.0," + + "\"tags\":{\"a\":\"1\",\"b\":\"2\",\"version\":\"1.2.3\",\"coalesced\":\"2\"}}"), bodies.toString()); + assertTrue(bodies.contains("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":2.5," + + "\"tags\":{\"a\":\"1\",\"b\":\"2\",\"version\":\"1.2.3\",\"coalesced\":\"2\"}}"), + "an event with a value keeps it; the count is the tag: " + bodies); + } + + /** Starts {@code threads} threads that each run {@code work} with their index, all at once, and waits for them. */ + private static void runAtOnce(int threads, IntConsumer work) throws InterruptedException { + CountDownLatch start = new CountDownLatch(1); + List started = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + final int index = t; + Thread thread = new Thread(() -> { + try { + start.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return; + } + work.accept(index); + }); + thread.start(); + started.add(thread); + } + start.countDown(); + for (Thread thread : started) { + thread.join(10_000); + assertFalse(thread.isAlive(), "a reporting thread did not finish"); + } + } + + @Test + void coalesce_reportsFromManyThreadsAtOnceAreEachCountedExactlyOnce() throws Exception { + // Arrange + // report() runs on the host's threads -- a plugin's async tasks + // beside the main thread -- so the window it shares must neither lose + // a repeat nor count one twice. + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + Map power = Collections.singletonMap("name", "power"); + int threads = 8; + int each = 500; + + // Act + // The real window, a minute: everything after the first report is + // counted until close() sends the count. + runAtOnce(threads, index -> { + for (int i = 0; i < each; i++) { + client.report("command", null, power); + } + }); + client.close(); + + // Assert + List bodies = received.stream().map(r -> r.body).collect(Collectors.toList()); + assertEquals(2, bodies.size(), "one first report and one count: " + bodies); + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"tags\":{\"name\":\"power\",\"version\":\"1.2.3\"}}", + bodies.get(0)); + int repeats = threads * each - 1; + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":" + (double) repeats + "," + + "\"tags\":{\"name\":\"power\",\"version\":\"1.2.3\",\"coalesced\":\"" + repeats + "\"}}", + bodies.get(1)); + } + + @Test + void coalesce_distinctEventsFromManyThreadsAtOnceAreEachSentOnceAndCountedOnce() throws Exception { + // Arrange + // Every thread opens windows of its own at the same moment, so the + // windows map and the queue count are changed from all of them at + // once. Well under QUEUE_CAPACITY and MAX_COALESCED_EVENTS, so + // nothing may be dropped. + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + int threads = 8; + int events = 5; + assertTrue(2 * threads * events <= TraceClient.QUEUE_CAPACITY); + assertTrue(threads * events <= TraceClient.MAX_COALESCED_EVENTS); + + // Act + runAtOnce(threads, index -> { + for (int repeat = 0; repeat < 3; repeat++) { + for (int e = 0; e < events; e++) { + client.report("command", null, Collections.singletonMap("name", index + "-" + e)); + } + } + }); + client.close(); + + // Assert + List bodies = received.stream().map(r -> r.body).collect(Collectors.toList()); + assertEquals(2 * threads * events, bodies.size(), "a first report and a count per event: " + bodies); + for (int t = 0; t < threads; t++) { + for (int e = 0; e < events; e++) { + String tags = "\"tags\":{\"name\":\"" + t + "-" + e + "\",\"version\":\"1.2.3\""; + assertEquals(1, bodies.stream().filter(b -> b.equals( + "{\"application\":\"MyPlugin\",\"name\":\"command\"," + tags + "}}")).count(), + "one first report of " + t + "-" + e + ": " + bodies); + assertEquals(1, bodies.stream().filter(b -> b.equals( + "{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":2.0," + tags + ",\"coalesced\":\"2\"}}")).count(), + "one count of 2 for " + t + "-" + e + ": " + bodies); + } + } + } + + @Test + void coalesce_neverHoldsBackStartup() throws Exception { + // Arrange + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + + // Act + for (int i = 0; i < 5; i++) { + client.report("startup"); + } + awaitReceived(5); + + // Assert + assertEquals(5, received.size(), "every startup goes out at once"); + assertEquals(0, client.coalescing(), "startup is never counted"); + client.close(); + assertEquals(5, received.size()); + } + + @Test + void coalesce_countsAtMostMaxCoalescedEventsAndDropsNewOnesBeyond() throws Exception { + // Arrange + // Nothing listening, so the sends fail fast and the test is about + // memory alone: a new name every call must not grow without bound. + TraceClient client = TraceClient.builder("http://127.0.0.1:1", "MyPlugin", "1.2.3").key("k").build(); + + // Act + for (int i = 0; i < TraceClient.MAX_COALESCED_EVENTS * 4; i++) { + client.report("command", null, Collections.singletonMap("name", "c" + i)); + client.report("command", null, Collections.singletonMap("name", "c" + i)); + } + + // Assert + assertEquals(TraceClient.MAX_COALESCED_EVENTS, client.coalescing()); + assertDoesNotThrow(() -> client.report("startup"), "startup still goes to the queue"); + client.close(); + assertEquals(0, client.coalescing(), "close() lets go of every count"); + } + + @Test + void coalesce_afterCloseNothingIsCountedOrSent() throws Exception { + // Arrange + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + client.close(); + + // Act + client.report("command"); + client.report("command"); + + // Assert + assertEquals(0, client.coalescing()); + assertFalse(arrived.await(300, TimeUnit.MILLISECONDS), "nothing should be sent after close()"); + } + + @Test + void coalesce_infiniteValuesAreTheSameEventAsNoValue() throws Exception { + // Arrange + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + + // Act + client.report("command"); + client.report("command", Double.POSITIVE_INFINITY, null); + client.report("command", Double.NEGATIVE_INFINITY, null); + assertTrue(arrived.await(5, TimeUnit.SECONDS), "the first report goes out at once"); + Thread.sleep(200); + int sentAtOnce = received.size(); + int counting = client.coalescing(); + client.close(); + + // Assert + assertEquals(1, sentAtOnce, "json() sends an infinite value as no value, so these are one event"); + assertEquals(1, counting); + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":2.0," + + "\"tags\":{\"version\":\"1.2.3\",\"coalesced\":\"2\"}}", received.get(1).body); + } + + @Test + void coalesce_aTagWithANullKeyOrValueIsLeftOutOfTheEventAndNeverThrows() throws Exception { + // Arrange + // The key is built from a TreeMap, which throws on a null key: this + // is only safe because withVersion() drops such tags first. + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); + Map withNulls = new HashMap<>(); + withNulls.put("name", "home"); + withNulls.put("nullValue", null); + withNulls.put(null, "nullKey"); + + // Act + assertDoesNotThrow(() -> client.report("command", null, withNulls)); + assertDoesNotThrow(() -> client.report("command", null, withNulls)); + client.report("command", null, Collections.singletonMap("name", "home")); + assertTrue(arrived.await(5, TimeUnit.SECONDS), "the first report goes out at once"); + Thread.sleep(200); + int sentAtOnce = received.size(); + client.close(); + + // Assert + assertEquals(1, sentAtOnce, "the same event as one without the null tags"); + assertEquals(2, received.size(), "and one count for both repeats"); + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"tags\":{\"name\":\"home\",\"version\":\"1.2.3\"}}", + received.get(0).body); + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":2.0," + + "\"tags\":{\"name\":\"home\",\"version\":\"1.2.3\",\"coalesced\":\"2\"}}", received.get(1).body); + } + + @Test + void coalesce_aCountCarriesTheInstallAndServerWideTagsBeforeItsOwn(@TempDir Path plugins) throws Exception { + // Arrange + writeServerWideConfig(plugins, "tags:\n ci: \"true\"\n"); + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .serverWideConfig(plugins.toFile()).build(); + + // Act + for (int i = 0; i < 4; i++) { + client.report("command", null, Collections.singletonMap("name", "home")); + } + client.close(); + + // Assert + assertEquals(2, received.size(), "the first report and one count"); + assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":3.0," + + "\"tags\":{\"name\":\"home\",\"version\":\"1.2.3\",\"install\":\"test-server\",\"ci\":\"true\",\"coalesced\":\"3\"}}", + received.get(1).body); + } + + @Test + void withCount_addsTheCountOnlyWhenThereIsRoomAndNoneAlready() { + Map tags = new LinkedHashMap<>(); + tags.put("version", "1"); + assertEquals("7", TraceClient.withCount(tags, 7).get(TraceClient.COALESCED_TAG)); + assertFalse(tags.containsKey(TraceClient.COALESCED_TAG), "the caller's map is never modified"); + + Map own = Collections.singletonMap(TraceClient.COALESCED_TAG, "mine"); + assertEquals("mine", TraceClient.withCount(own, 7).get(TraceClient.COALESCED_TAG)); + + Map full = new LinkedHashMap<>(); + for (int i = 0; i < TraceClient.MAX_TAGS; i++) { + full.put("t" + i, "v"); + } + assertEquals(TraceClient.MAX_TAGS, TraceClient.withCount(full, 7).size(), "never past the server's tag limit"); + } + private static byte[] readAll(InputStream in) throws java.io.IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; diff --git a/src/test/java/com/github/backup/trace/UsageReportingEnvironmentTest.java b/src/test/java/com/github/backup/trace/UsageReportingEnvironmentTest.java index d240fb2..58dcd56 100644 --- a/src/test/java/com/github/backup/trace/UsageReportingEnvironmentTest.java +++ b/src/test/java/com/github/backup/trace/UsageReportingEnvironmentTest.java @@ -63,6 +63,34 @@ void withoutEitherVariableThePropertyStands() { service.close(); } + @Test + void traceUsageReportingFailsClosedForAnyValueButAnOnValue() { + for (String value : new String[] {"false", "0", "no", "disabled", "nope"}) { + environment.put("TRACE_USAGE_REPORTING", value); + UsageReportingService service = newService(); + assertFalse(service.isEnabled(), "TRACE_USAGE_REPORTING=" + value + " must switch reporting off"); + service.close(); + } + } + + @Test + void doNotTrackFailsClosedForAnyValueButANegativeOne() { + for (String value : new String[] {"1", "true", "yes", "anything"}) { + environment.put("DO_NOT_TRACK", value); + UsageReportingService service = newService(); + assertFalse(service.isEnabled(), "DO_NOT_TRACK=" + value + " must switch reporting off"); + service.close(); + } + } + + @Test + void anOnTraceUsageReportingDoesNotOverrideTheProgramsOwnOff() { + environment.put("TRACE_USAGE_REPORTING", "on"); + UsageReportingService service = new UsageReportingService("off", "http://127.0.0.1:9", "test-key", "1.0"); + assertFalse(service.isEnabled(), "USAGE_REPORTING_ENABLED=off must still win over TRACE_USAGE_REPORTING=on"); + service.close(); + } + private static UsageReportingService newService() { // Enabled, with a key, pointed at a port nothing listens on: nothing is sent either way. return new UsageReportingService("true", "http://127.0.0.1:9", "test-key", "1.0");