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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ client never generates one, never writes one, and sends nothing.
| **Never throws** | A server that is down, slow, or rejecting the key is a dropped report, not an exception in your program — nor is a logger callback that throws. Drops go to the optional `log` callback, otherwise nowhere. |
| **Bounded** | At most 256 reports wait to be sent; past that, new ones are dropped. A trace server that is unreachable for a week costs a few kilobytes, not your memory. |
| **Within the server's limits** | A report the server would reject for its size — more than 32 tags, or an application, name, tag key or tag value longer than 255 characters — is dropped (and logged) instead of sent. Null or blank tag keys and null tag values are skipped. |
| **`Close()` / `Dispose()` drains** | Reports already queued get up to the client timeout (5 s total) to be sent before the thread stops, so a CLI that reports and exits at once does not lose its event. Still bounded: an unreachable server delays exit by at most the timeout plus half a second: at the timeout the in-flight request is cancelled, and the sending thread gets half a second to stop. |
| **`Close()` / `Dispose()` drains** | Reports already queued get up to the client timeout (5 s total) to be sent before the thread stops, so a CLI that reports and exits at once does not lose its event. Still bounded: an unreachable server delays exit by at most the timeout plus half a second: at the timeout the in-flight request is cancelled, and the sending thread gets half a second to stop. What is still queued then is dropped, and the `log` callback is told how many. |

Each request has a 5 s timeout.

Expand Down
23 changes: 18 additions & 5 deletions src/TraceClient/TraceClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ public void Report(string name, double? value = null, IEnumerable<KeyValuePair<s
string problem = Json(_application, name, value, WithInstall(WithVersion(tags, _version), InstallId), out body);
if (problem != null)
{
Log("dropped " + name + ": " + problem);
Log("dropped " + ForLog(name) + ": " + problem);
return;
}
if (!_queue.TryAdd(body))
Expand All @@ -402,18 +402,25 @@ public void Report(string name, double? value = null, IEnumerable<KeyValuePair<s
{
// InvalidOperationException when Close() raced us, or anything
// else: a usage report must never be the reason a program stops.
Log("could not queue " + name + ": " + failure.Message);
Log("could not queue " + ForLog(name) + ": " + failure.Message);
}
}

// A name past MaxLength is the very thing being dropped; its length is
// the program's to choose, so it does not reach the log uncut.
private static string ForLog(string name)
{
return name.Length > MaxLength ? name.Substring(0, MaxLength) + "..." : name;
}

/// <summary>
/// Stops the sending thread, giving reports already queued up to
/// <see cref="Timeout"/> in total to be sent first. A program that reports
/// and exits within milliseconds -- a CLI -- would otherwise lose its one
/// event. The bound still holds: an unreachable server delays exit by at
/// most the timeout plus half a second to cancel the in-flight request,
/// never a hang; whatever has not been sent by then is dropped. Safe to
/// call more than once, and on a disabled client.
/// never a hang; whatever has not been sent by then is dropped and logged.
/// Safe to call more than once, and on a disabled client.
/// </summary>
public void Close()
{
Expand Down Expand Up @@ -453,7 +460,13 @@ private void Drain()
}
catch (Exception)
{
// OperationCanceledException from Close() giving up; nothing to report.
// OperationCanceledException from Close() giving up. The queue is
// never disposed, so Count cannot throw on this thread.
int left = _queue.Count;
if (left > 0)
{
Log("close timed out, dropped " + left + " queued report(s)");
}
}
finally
{
Expand Down
102 changes: 102 additions & 0 deletions tests/TraceClient.Tests/TraceClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,66 @@ public void Report_DropsEveryEventOfAnApplicationNameLongerThanTheLimit()
log.ToArray());
}

[Fact]
public void Report_LogsAnOverlongNameCutAtTheLimit()
{
var log = new ConcurrentQueue<string>();
var client = new TraceClient(_server.BaseUrl, "MyGame", "1.2.3", key: "k", log: log.Enqueue);

client.Report(new string('n', TraceClient.MaxLength * 4));
client.Close();

Assert.Equal("[trace] dropped " + new string('n', TraceClient.MaxLength) + "...: name longer than "
+ TraceClient.MaxLength + " characters",
Assert.Single(log));
Assert.Empty(_server.Received);
}

[Fact]
public void Report_LogsANameAtTheLimitWhole()
{
// The limit is where the cut starts: a name the server would accept
// is dropped for some other reason, and reads in full in the log.
string longest = new string('n', TraceClient.MaxLength);
var log = new ConcurrentQueue<string>();
var client = new TraceClient(_server.BaseUrl, "MyGame", "1.2.3", key: "k", log: log.Enqueue);
var tooMany = Enumerable.Range(0, TraceClient.MaxTags + 1)
.Select(i => new KeyValuePair<string, string>("t" + i, "v")).ToList();

client.Report(longest, tags: tooMany);
client.Close();

Assert.Equal("[trace] dropped " + longest + ": more than " + TraceClient.MaxTags + " tags",
Assert.Single(log));
}

[Fact]
public void Report_NeverThrowsWhenTheTagsDoAndLogsAnOverlongNameCut()
{
// The tags are read before the name's length is checked, so this is
// the one way an overlong name reaches "could not queue".
var log = new ConcurrentQueue<string>();
var client = new TraceClient(_server.BaseUrl, "MyGame", "1.2.3", key: "k", log: log.Enqueue);

client.Report("startup", tags: ThrowingTags());
client.Report(new string('n', TraceClient.MaxLength + 1), tags: ThrowingTags());
client.Close();

Assert.Equal(new[]
{
"[trace] could not queue startup: tags failed",
"[trace] could not queue " + new string('n', TraceClient.MaxLength) + "...: tags failed",
},
log.ToArray());
Assert.Empty(_server.Received);
}

private static IEnumerable<KeyValuePair<string, string>> ThrowingTags()
{
yield return new KeyValuePair<string, string>("ok", "v");
throw new InvalidOperationException("tags failed");
}

[Fact]
public void Queue_IsBoundedAndDropsRatherThanGrows()
{
Expand Down Expand Up @@ -1003,6 +1063,48 @@ public void Close_StillReturnsWithinTheTimeoutWhenTheServerHangs()
}
}

[Fact]
public void Close_LogsHowManyReportsItGaveUpOn()
{
// One or two requests are in flight when Close gives up, and each is
// logged as undelivered. The rest never leave the queue, and they
// must be accounted for too: every report is delivered or logged.
const int reports = 6;
var release = new ManualResetEventSlim(false);
using (var slow = new StubServer(beforeReply: () => release.Wait(TimeSpan.FromSeconds(15))))
{
var log = new ConcurrentQueue<string>();
var client = new TraceClient(slow.BaseUrl, "MyCli", "1.2.3", key: "k", log: log.Enqueue);
for (int i = 0; i < reports; i++)
{
client.Report("startup");
}

client.Close();
bool logged = SpinWait.SpinUntil(() => log.Any(m => m.Contains("close timed out")), TimeSpan.FromSeconds(5));
release.Set();

Assert.True(logged, "logged: " + string.Join(" | ", log));
int undelivered = log.Count(m => m.StartsWith("[trace] could not deliver ", StringComparison.Ordinal));
Assert.Equal("[trace] close timed out, dropped " + (reports - undelivered) + " queued report(s)",
log.Single(m => m.Contains("close timed out")));
}
}

[Fact]
public void Close_LogsNoDropWhenEverythingWasDelivered()
{
var log = new ConcurrentQueue<string>();
var client = new TraceClient(_server.BaseUrl, "MyCli", "1.2.3", key: "k", log: log.Enqueue);

client.Report("startup");
client.Report("command");
client.Close();

Assert.Equal(2, _server.Received.Count);
Assert.Empty(log);
}

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