Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ using StephensonSoftware.Trace;

var trace = new TraceClient("https://trace.danielstephenson.dev", "my-game", "1.4.0",
key: settings.UsageReportingKey,
enabled: settings.UsageReportingEnabled,
enabled: TraceClient.AllowsReporting(settings.UsageReportingEnabled),
log: message => Debug.WriteLine(message)); // optional

if (trace.IsEnabled)
Expand Down Expand Up @@ -76,7 +76,7 @@ nothing is written. The simplest way is a file the program chooses:
```csharp
var trace = new TraceClient(url, "my-game", "1.4.0",
key: settings.UsageReportingKey,
enabled: settings.UsageReportingEnabled,
enabled: TraceClient.AllowsReporting(settings.UsageReportingEnabled),
installIdFile: Path.Combine(settings.DataDirectory, "trace-install-id"));
```

Expand Down Expand Up @@ -139,13 +139,15 @@ the client does not write the key into any message.
## Turning it off

Reporting is **opt-out**, and the person running the program always has the
last word. The constructor checks these in order; the first that applies is
last word. **Every switch fails closed:** a value that does not clearly mean
"on" — a typo, a quoted `"false"`, an empty value — turns reporting off, and
nothing in this client ever turns a switch back on. The constructor checks these in order; the first that applies is
what `DisabledReason` returns, verbatim, so the program can log it:

| Switch | `DisabledReason` |
|---|---|
| Environment, for every trace-reporting program at once: `TRACE_USAGE_REPORTING=off` (also `false`, `0`, `no`) or `DO_NOT_TRACK=1` (also `true`, `yes`; the [consoledonottrack.com](https://consoledonottrack.com) convention), case-insensitive. Always checked first; any other value leaves the program's setting in charge. | `environment` |
| The program's own setting: `enabled: false`. | `config` |
| Environment, for every trace-reporting program at once, case-insensitive and trimmed, always checked first: `TRACE_USAGE_REPORTING` set to anything but blank, `true`, `on`, `yes` or `1` (so `off`, `false`, `0`, `no`, `disabled`, a typo, …); or `DO_NOT_TRACK` set to anything but blank, `0`, `false`, `off` or `no` (so `1`, `true`, `yes`, …; the [consoledonottrack.com](https://consoledonottrack.com) convention). An environment that cannot be read (e.g. a `SecurityException` in a sandbox) counts as opting out. | `environment` |
| The program's own setting: `enabled: false`. Read it with `TraceClient.AllowsReporting(value)`, which fails closed the same way: only `true`, or a string `true`/`on`/`yes`/`1` (any case, trimmed), allows reporting; `null`, `false`, a quoted `"false"`, a number or a typo turns it off. | `config` |
| No key, or a blank one. | `no key` |

`DisabledReason` is `null` when the client reports. A disabled client does
Expand Down Expand Up @@ -173,7 +175,7 @@ distribution.
## The wire format

`POST {baseUrl}/api/metrics` with `Authorization: Bearer <key>`,
`User-Agent: trace-client/0.3.0 (<application>)` and a body of
`User-Agent: trace-client/0.4.0 (<application>)` and a body of

```json
{"application":"my-game","name":"level-complete","value":42,"tags":{"version":"1.4.0","install":"0f8b6c1e-3a52-4c8e-9a0d-6e2f1b7c4d90"}}
Expand Down
88 changes: 64 additions & 24 deletions src/TraceClient/TraceClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* trace-client 0.3.0 -- https://github.com/Stephenson-Software/trace-client-csharp
* trace-client 0.4.0 -- https://github.com/Stephenson-Software/trace-client-csharp
*
* One call to report that a program was used. Copy this file into a project as
* is, or reference the project; either way there is nothing else to add.
Expand Down Expand Up @@ -38,11 +38,18 @@ namespace StephensonSoftware.Trace
/// accumulated.</item>
/// </list>
/// <para>Reporting is opt-out, and the person running the program has the
/// last word. The constructor checks, in this order, and the first match is
/// what <see cref="DisabledReason"/> says: the environment
/// (<c>TRACE_USAGE_REPORTING=off</c> or <c>DO_NOT_TRACK=1</c>) -- reason
/// <c>environment</c>; the program's own setting, <c>enabled: false</c> --
/// reason <c>config</c>; no key -- reason <c>no key</c>.</para>
/// last word. Every switch fails closed: a value that does not clearly mean
/// "on" -- a typo, a quoted <c>"false"</c>, an empty value -- turns reporting
/// off, and nothing in this client ever turns a switch back on. The
/// constructor checks, in this order, and the first match is what
/// <see cref="DisabledReason"/> says: the environment
/// (<c>TRACE_USAGE_REPORTING</c> set to anything but blank, <c>true</c>,
/// <c>on</c>, <c>yes</c> or <c>1</c>; or <c>DO_NOT_TRACK</c> set to anything
/// but blank, <c>0</c>, <c>false</c>, <c>off</c> or <c>no</c>; or an
/// environment that cannot be read) -- reason <c>environment</c>; the
/// program's own setting, <c>enabled: false</c> -- reason <c>config</c>,
/// read it with <see cref="AllowsReporting"/> so it fails closed too; no key
/// -- reason <c>no key</c>.</para>
/// <para>Every event carries the program's own version as the tag
/// <c>version</c> -- the third constructor argument, required, so a
/// <c>command</c> event can be tied to a release as well as a
Expand All @@ -56,7 +63,7 @@ namespace StephensonSoftware.Trace
/// <code>
/// var trace = new TraceClient("https://trace.example.org", "my-game", ProgramVersion,
/// key: settings.UsageReportingKey,
/// enabled: settings.UsageReportingEnabled);
/// enabled: TraceClient.AllowsReporting(settings.UsageReportingEnabled));
/// trace.Report("startup");
/// ...
/// trace.Dispose(); // on shutdown: sends what is queued, bounded by the timeout
Expand All @@ -65,7 +72,7 @@ namespace StephensonSoftware.Trace
public sealed class TraceClient : IDisposable
{
/// <summary>The client version, as sent in the User-Agent header.</summary>
public const string Version = "0.3.0";
public const string Version = "0.4.0";

/// <summary>How many reports may wait to be sent before new ones are dropped.</summary>
public const int QueueCapacity = 256;
Expand All @@ -83,10 +90,14 @@ public sealed class TraceClient : IDisposable
/// The program's version and installation ID are tag values too, so the constructor rejects either past it.</summary>
public const int MaxLength = 255;

/// <summary>Environment variable that turns reporting off: <c>off</c>, <c>false</c>, <c>0</c>, <c>no</c>.</summary>
/// <summary>Environment variable that turns reporting off when set to anything but blank,
/// <c>true</c>, <c>on</c>, <c>yes</c> or <c>1</c> (case-insensitive): <c>off</c>, <c>false</c>,
/// <c>0</c>, <c>no</c>, a typo, ...</summary>
public const string EnvUsageReporting = "TRACE_USAGE_REPORTING";

/// <summary>Environment variable that turns reporting off: <c>1</c>, <c>true</c>, <c>yes</c>. See https://consoledonottrack.com.</summary>
/// <summary>Environment variable that turns reporting off when set to anything but blank,
/// <c>0</c>, <c>false</c>, <c>off</c> or <c>no</c> (case-insensitive): <c>1</c>, <c>true</c>,
/// <c>yes</c>, ... See https://consoledonottrack.com.</summary>
public const string EnvDoNotTrack = "DO_NOT_TRACK";

/// <summary>Reason given when an environment variable turned reporting off.</summary>
Expand Down Expand Up @@ -140,7 +151,9 @@ public sealed class TraceClient : IDisposable
/// <param name="version">The program's own version, trimmed. Sent as the tag <c>version</c>
/// on every event unless the event carries its own.</param>
/// <param name="key">The program's write key. Without one the client is a no-op.</param>
/// <param name="enabled">The program's own opt-out. <c>false</c> yields a client that reports nothing.</param>
/// <param name="enabled">The program's own opt-out. <c>false</c> yields a client that reports nothing.
/// When the setting comes from a file or other loosely typed source, pass it through
/// <see cref="AllowsReporting"/> so that anything but a clear "on" turns reporting off.</param>
/// <param name="log">Where dropped reports and installation ID file failures are mentioned.
/// Optional; treat as debug-level.
/// Called on the caller's thread or on the client's background thread, so it must be
Expand Down Expand Up @@ -343,41 +356,68 @@ public bool IsEnabled
}

/// <summary>
/// Whether the environment asks for usage reporting to be off, via
/// <see cref="EnvUsageReporting"/> or <see cref="EnvDoNotTrack"/> set to one of
/// the values listed there, case-insensitive. Anything else (including empty), or
/// an environment that cannot be read, leaves the program's own setting in charge.
/// Whether the environment asks for usage reporting to be off. Fails closed:
/// <see cref="EnvUsageReporting"/> set to anything but blank, <c>true</c>, <c>on</c>,
/// <c>yes</c> or <c>1</c>, or <see cref="EnvDoNotTrack"/> set to anything but blank,
/// <c>0</c>, <c>false</c>, <c>off</c> or <c>no</c> (case-insensitive, trimmed), turns
/// reporting off. An environment that cannot be read (e.g. a
/// <see cref="System.Security.SecurityException"/> in a sandbox) may hold
/// <c>DO_NOT_TRACK=1</c>, so it counts as opting out too. Never throws.
/// </summary>
public static bool EnvironmentDisables()
{
try
{
return IsOff(EnvironmentSource(EnvUsageReporting)) || IsYes(EnvironmentSource(EnvDoNotTrack));
string usageReporting = EnvironmentSource(EnvUsageReporting);
if (!string.IsNullOrWhiteSpace(usageReporting) && !IsOn(usageReporting))
{
return true;
}
string doNotTrack = EnvironmentSource(EnvDoNotTrack);
return !string.IsNullOrWhiteSpace(doNotTrack) && !IsNegative(doNotTrack);
}
catch (Exception)
{
return false; // e.g. a SecurityException in a sandbox; the program's setting stays in charge
return true; // an environment that cannot be read may say DO_NOT_TRACK=1
}
}

private static bool IsOff(string value)
/// <summary>
/// Whether a program's own reporting setting, as read from its configuration,
/// allows reporting -- for the constructor's <c>enabled</c>. Fails closed: only
/// <c>true</c>, or a string reading <c>true</c>, <c>on</c>, <c>yes</c> or <c>1</c>
/// (any case, surrounding space ignored), allows it. Anything else turns reporting
/// off: <c>false</c>, a quoted <c>"false"</c>, <c>off</c>, <c>no</c>, a typo, a
/// number, or <c>null</c>. Never throws.
/// </summary>
/// <param name="setting">The raw value: a <see cref="bool"/>, a <see cref="string"/>,
/// <c>null</c> or anything else.</param>
public static bool AllowsReporting(object setting)
{
if (value == null)
if (setting is bool)
{
return false;
return (bool)setting;
}
string v = value.Trim().ToLowerInvariant();
return v == "off" || v == "false" || v == "0" || v == "no";
string text = setting as string;
return text != null && IsOn(text);
}

private static bool IsYes(string value)
// true, on, yes or 1, ignoring case and surrounding space.
private static bool IsOn(string value)
{
if (value == null)
{
return false;
}
string v = value.Trim().ToLowerInvariant();
return v == "1" || v == "true" || v == "yes";
return v == "true" || v == "on" || v == "yes" || v == "1";
}

// false, off, no or 0, ignoring case and surrounding space.
private static bool IsNegative(string value)
{
string v = value.Trim().ToLowerInvariant();
return v == "false" || v == "off" || v == "no" || v == "0";
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/TraceClient/TraceClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<LangVersion>7.3</LangVersion>
<AssemblyName>StephensonSoftware.Trace</AssemblyName>
<RootNamespace>StephensonSoftware.Trace</RootNamespace>
<Version>0.3.0</Version>
<Version>0.4.0</Version>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
Expand Down
72 changes: 64 additions & 8 deletions tests/TraceClient.Tests/TraceClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,11 @@ public void DisabledReason_TreatsABlankKeyAsNoKey(string key)
[InlineData("0")]
[InlineData("no")]
[InlineData(" No ")]
public void TraceUsageReporting_DisablesReportingForEveryAcceptedValue(string value)
[InlineData("disabled")]
[InlineData("of")]
[InlineData("\"on\"")]
[InlineData("2")]
public void TraceUsageReporting_DisablesReportingForAnythingButAClearOn(string value)
{
_environment[TraceClient.EnvUsageReporting] = value;

Expand All @@ -429,7 +433,11 @@ public void TraceUsageReporting_DisablesReportingForEveryAcceptedValue(string va
[InlineData("TRUE")]
[InlineData("yes")]
[InlineData(" Yes ")]
public void DoNotTrack_DisablesReportingForEveryAcceptedValue(string value)
[InlineData("on")]
[InlineData("y")]
[InlineData("2")]
[InlineData("nope")]
public void DoNotTrack_DisablesReportingForAnythingButAClearNo(string value)
{
_environment[TraceClient.EnvDoNotTrack] = value;

Expand All @@ -442,11 +450,16 @@ public void DoNotTrack_DisablesReportingForEveryAcceptedValue(string value)
[Theory]
[InlineData("TRACE_USAGE_REPORTING", "on")]
[InlineData("TRACE_USAGE_REPORTING", "")]
[InlineData("TRACE_USAGE_REPORTING", " ")]
[InlineData("TRACE_USAGE_REPORTING", "1")]
[InlineData("TRACE_USAGE_REPORTING", " TRUE ")]
[InlineData("TRACE_USAGE_REPORTING", "Yes")]
[InlineData("DO_NOT_TRACK", "0")]
[InlineData("DO_NOT_TRACK", "")]
[InlineData("DO_NOT_TRACK", "false")]
public void OtherEnvironmentValues_LeaveTheProgramSettingInCharge(string variable, string value)
[InlineData("DO_NOT_TRACK", " OFF ")]
[InlineData("DO_NOT_TRACK", "No")]
public void BlankOrClearlyOnEnvironmentValues_LeaveTheProgramSettingInCharge(string variable, string value)
{
_environment[variable] = value;

Expand Down Expand Up @@ -988,19 +1001,62 @@ public void Report_SendsTheNameAndTagsUntrimmed()
}

[Fact]
public void EnvironmentDisables_IsFalseWhenTheEnvironmentCannotBeRead()
public void EnvironmentDisables_IsTrueWhenTheEnvironmentCannotBeRead()
{
// A sandbox that forbids reading the environment must not stop the
// program from starting, nor silently decide for it: its own setting rules.
// program from starting. It may hold DO_NOT_TRACK=1, so it fails closed.
TraceClient.EnvironmentSource = name => throw new System.Security.SecurityException("sandboxed");

Assert.False(TraceClient.EnvironmentDisables());
Assert.True(TraceClient.EnvironmentDisables());
var client = new TraceClient(_server.BaseUrl, "MyGame", "1.2.3", key: "k");
Assert.True(client.IsEnabled);
Assert.Null(client.DisabledReason);
Assert.False(client.IsEnabled);
Assert.Equal(TraceClient.ReasonEnvironment, client.DisabledReason);
client.Close();
}

[Theory]
[InlineData(true)]
[InlineData("true")]
[InlineData("TRUE")]
[InlineData(" on ")]
[InlineData("Yes")]
[InlineData("1")]
public void AllowsReporting_IsTrueOnlyForAClearOn(object setting)
{
Assert.True(TraceClient.AllowsReporting(setting));
}

[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData("false")]
[InlineData("\"false\"")]
[InlineData("\"true\"")]
[InlineData("off")]
[InlineData("no")]
[InlineData("0")]
[InlineData("")]
[InlineData(" ")]
[InlineData("ture")]
[InlineData("enabled")]
[InlineData(1)]
[InlineData(0)]
[InlineData(1.0)]
public void AllowsReporting_FailsClosedForEverythingElse(object setting)
{
Assert.False(TraceClient.AllowsReporting(setting));
}

[Fact]
public void AllowsReporting_FeedsTheConfigSwitch()
{
var client = new TraceClient(_server.BaseUrl, "MyGame", "1.2.3", key: "k",
enabled: TraceClient.AllowsReporting("\"false\""));

Assert.False(client.IsEnabled);
Assert.Equal(TraceClient.ReasonConfig, client.DisabledReason);
}

[Fact]
public void Report_DropsWhatTheServerWouldRejectForItsSize()
{
Expand Down
Loading