diff --git a/README.md b/README.md index 98c60c1..93d1ed3 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/TraceClient/TraceClient.cs b/src/TraceClient/TraceClient.cs index bfc381e..bbf7dec 100644 --- a/src/TraceClient/TraceClient.cs +++ b/src/TraceClient/TraceClient.cs @@ -390,7 +390,7 @@ public void Report(string name, double? value = null, IEnumerable MaxLength ? name.Substring(0, MaxLength) + "..." : name; + } + /// /// Stops the sending thread, giving reports already queued up to /// 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. /// public void Close() { @@ -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 { diff --git a/tests/TraceClient.Tests/TraceClientTest.cs b/tests/TraceClient.Tests/TraceClientTest.cs index 66355a9..357efac 100644 --- a/tests/TraceClient.Tests/TraceClientTest.cs +++ b/tests/TraceClient.Tests/TraceClientTest.cs @@ -811,6 +811,66 @@ public void Report_DropsEveryEventOfAnApplicationNameLongerThanTheLimit() log.ToArray()); } + [Fact] + public void Report_LogsAnOverlongNameCutAtTheLimit() + { + var log = new ConcurrentQueue(); + 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(); + 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("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(); + 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> ThrowingTags() + { + yield return new KeyValuePair("ok", "v"); + throw new InvalidOperationException("tags failed"); + } + [Fact] public void Queue_IsBoundedAndDropsRatherThanGrows() { @@ -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(); + 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(); + 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() {