diff --git a/deploy/TRACING.md b/deploy/TRACING.md index c64aa279..b8e1c0b5 100644 --- a/deploy/TRACING.md +++ b/deploy/TRACING.md @@ -39,6 +39,13 @@ Docker healthcheck удерживает запускающийся контей на время диагностики. HTTP connection setup — отдельная трасса, связанная с исходящим HTTP-спаном через ссылку, а не обычный дочерний спан. +Для замеров чтения ответа включить +`AppConfiguration__Tracing__DialogflowResponseTimingEnabled=true` вместе с +трассировкой. В спане `Dialogflow DetectIntent` событие `dialogflow.response.read` +отмечает получение заголовков. Поля `first_data_ms`, `last_data_ms` и +`stream_end_ms` показывают время от заголовков до чтения данных и конца потока. +При прерванном чтении доступны только достигнутые этапы. + Интерфейс доступен через SSH-туннель: ```bash diff --git a/deploy/app-env.example b/deploy/app-env.example index c725e2ad..851ea2d7 100644 --- a/deploy/app-env.example +++ b/deploy/app-env.example @@ -33,6 +33,8 @@ AppConfiguration__Tracing__Host= AppConfiguration__Tracing__Port=4317 # Низкоуровневые сетевые spans включаются отдельно, только при Enabled=true. AppConfiguration__Tracing__NetworkEnabled=false +# Тайминги чтения ответа DetectIntent в спанах. +AppConfiguration__Tracing__DialogflowResponseTimingEnabled=false # Плавная остановка; значения по умолчанию подходят # AppConfiguration__Shutdown__DrainDelaySeconds=10 diff --git a/src/FillInTheTextBot.Api/DI/ExternalServicesRegistration.cs b/src/FillInTheTextBot.Api/DI/ExternalServicesRegistration.cs index 2bffa22f..7ca0bd8b 100644 --- a/src/FillInTheTextBot.Api/DI/ExternalServicesRegistration.cs +++ b/src/FillInTheTextBot.Api/DI/ExternalServicesRegistration.cs @@ -1,7 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; +using FillInTheTextBot.Services; using FillInTheTextBot.Services.Configuration; +using Google.Api.Gax.Grpc; using Google.Apis.Auth.OAuth2; using Google.Cloud.Dialogflow.V2; using GranSteL.Helpers.Redis; @@ -49,19 +52,30 @@ private static ScopesSelector RegisterSessionsClientScopes(IServ var scopeContexts = GetScopesContexts(configuration); - var selector = new ScopesSelector(scopeContexts, CreateDialogflowSessionsClient); + var tracing = provider.GetRequiredService(); + var adapter = tracing is { Enabled: true, DialogflowResponseTimingEnabled: true } + ? GrpcNetClientAdapter.Default.WithAdditionalOptions(options => + { + options.HttpHandler = new DialogflowResponseTimingHandler(options.HttpHandler ?? + new SocketsHttpHandler { EnableMultipleHttp2Connections = true }); + options.DisposeHttpClient = true; + }) + : null; + var selector = new ScopesSelector(scopeContexts, + context => CreateDialogflowSessionsClient(context, adapter)); return selector; } - private static SessionsClient CreateDialogflowSessionsClient(ScopeContext context) + private static SessionsClient CreateDialogflowSessionsClient(ScopeContext context, GrpcAdapter adapter) { if (TryGetEmulatorEndpoint(context, out var emulatorEndpoint)) { var emulatorClientBuilder = new SessionsClientBuilder { Endpoint = emulatorEndpoint, - ChannelCredentials = ChannelCredentials.Insecure + ChannelCredentials = ChannelCredentials.Insecure, + GrpcAdapter = adapter }; return emulatorClientBuilder.Build(); @@ -75,7 +89,8 @@ private static SessionsClient CreateDialogflowSessionsClient(ScopeContext contex var clientBuilder = new SessionsClientBuilder { ChannelCredentials = credential.ToChannelCredentials(), - Endpoint = endpoint + Endpoint = endpoint, + GrpcAdapter = adapter }; var client = clientBuilder.Build(); diff --git a/src/FillInTheTextBot.Services.Tests/DialogflowResponseTimingTests.cs b/src/FillInTheTextBot.Services.Tests/DialogflowResponseTimingTests.cs new file mode 100644 index 00000000..f27a8924 --- /dev/null +++ b/src/FillInTheTextBot.Services.Tests/DialogflowResponseTimingTests.cs @@ -0,0 +1,82 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using NUnit.Framework; + +namespace FillInTheTextBot.Services.Tests; + +public class DialogflowResponseTimingTests +{ + [TestCase(true, true)] + [TestCase(true, false)] + [TestCase(false, true)] + public async Task ResponseTiming_RecordsOnlyReachedStagesOnSampledSpans(bool recorded, bool readToEnd) + { + using var source = new ActivitySource(Tracing.ActivitySourceName); + using var listener = new ActivityListener + { + ShouldListenTo = candidate => ReferenceEquals(candidate, source), + Sample = (ref ActivityCreationOptions _) => recorded + ? ActivitySamplingResult.AllDataAndRecorded + : ActivitySamplingResult.AllData + }; + ActivitySource.AddActivityListener(listener); + using var activity = source.StartActivity("Dialogflow DetectIntent", ActivityKind.Internal, + default(ActivityContext)); + + using var content = new StreamContent(new MemoryStream(new byte[] { 42 })); + content.Headers.ContentType = new("application/grpc"); + using var client = new HttpMessageInvoker(new DialogflowResponseTimingHandler(new ResponseHandler(content))); + using var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/synthetic"); + using var response = await client.SendAsync(request, CancellationToken.None); + Assert.That(response.Content.Headers.ContentType?.MediaType, Is.EqualTo("application/grpc")); + Assert.That(ReferenceEquals(response.Content, content), Is.EqualTo(!recorded)); + + using var stream = await response.Content.ReadAsStreamAsync(); + Assert.That(await stream.ReadAsync(Memory.Empty), Is.Zero); + var buffer = new byte[1]; + Assert.That(await stream.ReadAsync(buffer.AsMemory()), Is.EqualTo(1)); + Assert.That(buffer[0], Is.EqualTo(42)); + Assert.That(activity.Events, Is.Empty); + + if (readToEnd) + { + Assert.That(await stream.ReadAsync(buffer.AsMemory()), Is.Zero); + } + + response.Dispose(); + if (!recorded) + { + Assert.That(activity.Events, Is.Empty); + return; + } + + var timing = activity.Events.Single(); + var tags = timing.Tags.ToDictionary(tag => tag.Key, tag => tag.Value); + Assert.Multiple(() => + { + Assert.That(timing.Name, Is.EqualTo("dialogflow.response.read")); + Assert.That(tags.Keys, Is.EquivalentTo(readToEnd + ? new[] { "first_data_ms", "last_data_ms", "stream_end_ms" } + : new[] { "first_data_ms", "last_data_ms" })); + Assert.That((double)tags["first_data_ms"], Is.GreaterThanOrEqualTo(0)); + Assert.That(tags["last_data_ms"], Is.EqualTo(tags["first_data_ms"])); + if (readToEnd) + { + Assert.That((double)tags["stream_end_ms"], Is.GreaterThanOrEqualTo((double)tags["last_data_ms"])); + } + }); + } + + private sealed class ResponseHandler(HttpContent content) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, + CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); + } +} diff --git a/src/FillInTheTextBot.Services/Configuration/TracingConfiguration.cs b/src/FillInTheTextBot.Services/Configuration/TracingConfiguration.cs index b6d0d04a..e0f53b91 100644 --- a/src/FillInTheTextBot.Services/Configuration/TracingConfiguration.cs +++ b/src/FillInTheTextBot.Services/Configuration/TracingConfiguration.cs @@ -6,6 +6,8 @@ public class TracingConfiguration : Configuration public bool NetworkEnabled { get; set; } + public bool DialogflowResponseTimingEnabled { get; set; } + public string Host { get; set; } public int? Port { get; set; } diff --git a/src/FillInTheTextBot.Services/DialogflowResponseTimingHandler.cs b/src/FillInTheTextBot.Services/DialogflowResponseTimingHandler.cs new file mode 100644 index 00000000..d9462703 --- /dev/null +++ b/src/FillInTheTextBot.Services/DialogflowResponseTimingHandler.cs @@ -0,0 +1,179 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace FillInTheTextBot.Services; + +public sealed class DialogflowResponseTimingHandler(HttpMessageHandler innerHandler) : DelegatingHandler(innerHandler) +{ + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + for (var activity = Activity.Current; activity is not null; activity = activity.Parent) + { + if (activity.Source.Name == Tracing.ActivitySourceName && + activity.OperationName == DialogflowService.DetectIntentActivityName) + { + if (activity.Recorded) + { + return SendWithTimingAsync(activity, request, cancellationToken); + } + + break; + } + } + + return base.SendAsync(request, cancellationToken); + } + + private async Task SendWithTimingAsync(Activity activity, HttpRequestMessage request, + CancellationToken cancellationToken) + { + var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + response.Content = new TimedContent(response.Content, activity); + return response; + } + + private sealed class TimedContent : HttpContent + { + private readonly HttpContent _content; + private readonly Activity _activity; + private readonly long _headers = Stopwatch.GetTimestamp(); + private readonly DateTimeOffset _headersAt = DateTimeOffset.UtcNow; + private long _firstData; + private long _lastData; + private long _streamEnd; + private int _published; + + public TimedContent(HttpContent content, Activity activity) + { + _content = content; + _activity = activity; + foreach (var header in content.Headers.NonValidated) + { + Headers.TryAddWithoutValidation(header.Key, header.Value); + } + } + + protected override async Task CreateContentReadStreamAsync() => + new TimedStream(await _content.ReadAsStreamAsync().ConfigureAwait(false), this); + + protected override async Task CreateContentReadStreamAsync(CancellationToken cancellationToken) => + new TimedStream(await _content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), this); + + protected override Stream CreateContentReadStream(CancellationToken cancellationToken) => + new TimedStream(_content.ReadAsStream(cancellationToken), this); + + protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) => + _content.CopyToAsync(stream, context); + + protected override Task SerializeToStreamAsync(Stream stream, TransportContext context, + CancellationToken cancellationToken) => _content.CopyToAsync(stream, context, cancellationToken); + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + + private void Publish() + { + if (Interlocked.Exchange(ref _published, 1) != 0) + { + return; + } + + var tags = new ActivityTagsCollection(); + AddTiming(tags, "first_data_ms", Volatile.Read(ref _firstData)); + AddTiming(tags, "last_data_ms", Volatile.Read(ref _lastData)); + AddTiming(tags, "stream_end_ms", Volatile.Read(ref _streamEnd)); + _activity.AddEvent(new ActivityEvent("dialogflow.response.read", _headersAt, tags)); + } + + private void AddTiming(ActivityTagsCollection tags, string name, long timestamp) + { + if (timestamp != 0) + { + tags.Add(name, Stopwatch.GetElapsedTime(_headers, timestamp).TotalMilliseconds); + } + } + + public int Observe(int count, int requested) + { + if (count > 0) + { + var timestamp = Stopwatch.GetTimestamp(); + if (_firstData == 0) + { + Volatile.Write(ref _firstData, timestamp); + } + + Volatile.Write(ref _lastData, timestamp); + } + else if (requested > 0) + { + Volatile.Write(ref _streamEnd, Stopwatch.GetTimestamp()); + Publish(); + } + + return count; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + Publish(); + _content.Dispose(); + } + + base.Dispose(disposing); + } + } + + private sealed class TimedStream(Stream inner, TimedContent timing) : Stream + { + public override bool CanRead => inner.CanRead; + public override bool CanSeek => inner.CanSeek; + public override bool CanWrite => false; + public override long Length => inner.Length; + public override long Position { get => inner.Position; set => inner.Position = value; } + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + + public override int Read(byte[] buffer, int offset, int count) => + timing.Observe(inner.Read(buffer, offset, count), count); + + public override int Read(Span buffer) => timing.Observe(inner.Read(buffer), buffer.Length); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = inner.ReadAsync(buffer, cancellationToken); + return read.IsCompletedSuccessfully + ? ValueTask.FromResult(timing.Observe(read.Result, buffer.Length)) + : ObserveReadAsync(read, buffer.Length); + } + + private async ValueTask ObserveReadAsync(ValueTask read, int requested) => + timing.Observe(await read.ConfigureAwait(false), requested); + + public override void Flush() => inner.Flush(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/src/FillInTheTextBot.Services/DialogflowService.cs b/src/FillInTheTextBot.Services/DialogflowService.cs index ab29b360..360f8d79 100644 --- a/src/FillInTheTextBot.Services/DialogflowService.cs +++ b/src/FillInTheTextBot.Services/DialogflowService.cs @@ -14,6 +14,8 @@ namespace FillInTheTextBot.Services { public class DialogflowService : IDialogflowService { + internal const string DetectIntentActivityName = "Dialogflow DetectIntent"; + private const string EventKey = "event:"; private const string StartCommand = "/start"; private const string ErrorCommand = "/error"; @@ -110,7 +112,7 @@ await _contextsClientSelector.Invoke((client, context) => .SetTag(nameof(context.ScopeId), context.ScopeId) .SetTag("rpc.system", "grpc") .SetTag("rpc.service", "google.cloud.dialogflow.v2.Sessions") - .SetTag("rpc.method", "DetectIntent"), "Dialogflow DetectIntent")) + .SetTag("rpc.method", "DetectIntent"), DetectIntentActivityName)) { try {