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
7 changes: 7 additions & 0 deletions deploy/TRACING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions deploy/app-env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 19 additions & 4 deletions src/FillInTheTextBot.Api/DI/ExternalServicesRegistration.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -49,19 +52,30 @@ private static ScopesSelector<SessionsClient> RegisterSessionsClientScopes(IServ

var scopeContexts = GetScopesContexts(configuration);

var selector = new ScopesSelector<SessionsClient>(scopeContexts, CreateDialogflowSessionsClient);
var tracing = provider.GetRequiredService<TracingConfiguration>();
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<SessionsClient>(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();
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
@@ -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<ActivityContext> _) => 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<byte>.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<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken) =>
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = content });
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
179 changes: 179 additions & 0 deletions src/FillInTheTextBot.Services/DialogflowResponseTimingHandler.cs
Original file line number Diff line number Diff line change
@@ -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<HttpResponseMessage> 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<HttpResponseMessage> 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<Stream> CreateContentReadStreamAsync() =>
new TimedStream(await _content.ReadAsStreamAsync().ConfigureAwait(false), this);

protected override async Task<Stream> 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<byte> buffer) => timing.Observe(inner.Read(buffer), buffer.Length);

public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();

public override ValueTask<int> ReadAsync(Memory<byte> 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<int> ObserveReadAsync(ValueTask<int> 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);
}
}
}
4 changes: 3 additions & 1 deletion src/FillInTheTextBot.Services/DialogflowService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
{
Expand Down