Skip to content
Open
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
123 changes: 123 additions & 0 deletions packages/Core/Core.Tests/Diagnostics/HttpClientRequestDurationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Net.Http;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Core.Diagnostics;

namespace Core.Tests.Diagnostics;

/// <summary>
/// Covers <see cref="HttpClientRequestDuration"/>: the OpenTelemetry <c>http.client.request.duration</c> instrument
/// every Supabase client records on its own meter, and the HTTP client attributes it carries.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class HttpClientRequestDurationTests
{
private const int NotFound = 404;
private const double SecondsWithinATest = 1;
private static readonly Uri RequestUri = new("https://project.supabase.co:8443/rest/v1/todos?select=id#fragment");

private readonly List<Instrument> instruments = new();
private readonly List<double> durations = new();
private Meter meter = null!;
private MeterListener listener = null!;

[TestInitialize]
public void SetUp()
{
this.meter = new Meter($"supabase.test.{Guid.NewGuid():N}");
this.listener = new MeterListener
{
InstrumentPublished = (instrument, meterListener) =>
{
if (instrument.Meter != this.meter)
return;
this.instruments.Add(instrument);
meterListener.EnableMeasurementEvents(instrument);
}
};
this.listener.SetMeasurementEventCallback<double>((_, value, _, _) => this.durations.Add(value));
this.listener.Start();
}

[TestCleanup]
public void TearDown()
{
this.listener.Dispose();
this.meter.Dispose();
}

[TestMethod]
public void On_ShouldNameTheStandardHttpClientInstrument()
{
HttpClientRequestDuration.On(this.meter);
this.instruments.Should().ContainSingle().Which.Name.Should().Be("http.client.request.duration",
"the OpenTelemetry HTTP client semantic conventions name the request duration metric");
}

[TestMethod]
public void On_ShouldMeasureInSeconds()
{
HttpClientRequestDuration.On(this.meter);
this.instruments.Should().ContainSingle().Which.Unit.Should().Be("s",
"the OpenTelemetry HTTP client semantic conventions measure durations in seconds");
}

[TestMethod]
public void On_ShouldDescribeTheInstrument()
{
HttpClientRequestDuration.On(this.meter);
this.instruments.Should().ContainSingle().Which.Description.Should().Be("Duration of HTTP client requests.",
"every client shares one description for the shared instrument");
}

[TestMethod]
public void Enabled_ShouldBeTrue_GivenAListener() =>
HttpClientRequestDuration.On(this.meter).Enabled.Should().BeTrue("the listener enabled the instrument");

[TestMethod]
public void Enabled_ShouldBeFalse_GivenNoListener()
{
using var unobservedMeter = new Meter($"supabase.unobserved.{Guid.NewGuid():N}");
HttpClientRequestDuration.On(unobservedMeter).Enabled.Should().BeFalse("nothing listens to this meter");
}

[TestMethod]
public void Record_ShouldRecordTheElapsedSeconds()
{
HttpClientRequestDuration.On(this.meter).Record(Stopwatch.GetTimestamp(), new TagList());
this.durations.Should().ContainSingle().Which.Should().BeInRange(0, SecondsWithinATest,
"the value is the time since the start timestamp, in seconds rather than ticks");
}

[TestMethod]
public void TagsOf_ShouldCarryTheHttpClientAttributes_GivenAResponse() =>
ToDictionary(HttpClientRequestDuration.TagsOf(HttpMethod.Get, RequestUri, NotFound, "404")).Should().BeEquivalentTo(
new Dictionary<string, object?>
{
["http.request.method"] = "GET",
["server.address"] = "project.supabase.co",
["server.port"] = 8443,
["url.scheme"] = "https",
["http.response.status_code"] = NotFound,
["error.type"] = "404"
}, "the OpenTelemetry HTTP client attributes describe the request without its path, query, or fragment");

[TestMethod]
public void TagsOf_ShouldOmitTheStatusAndErrorType_GivenASuccessWithoutResponse() =>
ToDictionary(HttpClientRequestDuration.TagsOf(HttpMethod.Post, RequestUri, null, null)).Keys.Should().BeEquivalentTo(
new[] { "http.request.method", "server.address", "server.port", "url.scheme" },
"a status code and an error type are recorded only when the request has them");

private static Dictionary<string, object?> ToDictionary(TagList tags)
{
var values = new Dictionary<string, object?>();
foreach (var tag in tags)
values[tag.Key] = tag.Value;
return values;
}
}
4 changes: 2 additions & 2 deletions packages/Core/Core.Tests/Http/SdkLogTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ public class SdkLogTests
public void BackgroundWorkEvent_ShouldLogTheComponentAtDebug()
{
var capture = new LogCapture();
capture.Logger.BackgroundWorkEvent("Supabase.Realtime", "connected");
capture.Logger.BackgroundWorkEvent("supabase.realtime", "connected");
var record = capture.Records.Should().ContainSingle().Which;
using (new AssertionScope())
{
record.Level.Should().Be(LogLevel.Debug);
record.Message.Should().Be("Supabase.Realtime: connected");
record.Message.Should().Be("supabase.realtime: connected");
}
}

Expand Down
70 changes: 70 additions & 0 deletions packages/Core/Core/Diagnostics/HttpClientRequestDuration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Net.Http;

namespace Supabase.Core.Diagnostics;

/// <summary>
/// The OpenTelemetry <c>http.client.request.duration</c> histogram on a client library's <see cref="Meter"/>.
/// The meter names the product, so every Supabase client records the same instrument with the same HTTP
/// attributes and adds its own on top. The attributes carry no URL, query string, or credential.
/// </summary>
internal sealed class HttpClientRequestDuration
{
private const string Name = "http.client.request.duration";
private const string Unit = "s";
private const string Description = "Duration of HTTP client requests.";

private readonly Histogram<double> histogram;

private HttpClientRequestDuration(Histogram<double> histogram) => this.histogram = histogram;

/// <summary>
/// Whether anything listens to the histogram. Callers build attributes only when it does, so recording
/// costs nothing without a listener.
/// </summary>
internal bool Enabled => this.histogram.Enabled;

/// <summary>
/// Creates the histogram on the meter of the client library that sends the requests.
/// </summary>
/// <param name="meter">The meter that names the client library.</param>
internal static HttpClientRequestDuration On(Meter meter) =>
new(meter.CreateHistogram<double>(Name, Unit, Description));

/// <summary>
/// The OpenTelemetry HTTP client attributes of a request outcome: method, server address and port, scheme,
/// and the status code and error type when there is one.
/// </summary>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="uri">The request URI; only its scheme, host and port are recorded.</param>
/// <param name="statusCode">The HTTP response status code, or null if the request never got one.</param>
/// <param name="errorType">The error classification, or null on success.</param>
internal static TagList TagsOf(HttpMethod method, Uri uri, int? statusCode, string? errorType)
{
var tags = new TagList
{
{ "http.request.method", method.Method },
{ "server.address", uri.Host },
{ "server.port", uri.Port },
{ "url.scheme", uri.Scheme }
};

if (statusCode.HasValue)
tags.Add("http.response.status_code", statusCode.Value);

if (errorType != null)
tags.Add("error.type", errorType);

return tags;
}

/// <summary>
/// Records the time elapsed since the request started.
/// </summary>
/// <param name="startTimestamp">The <see cref="Stopwatch.GetTimestamp"/> value captured before the request.</param>
/// <param name="tags">The attributes of the request outcome.</param>
internal void Record(long startTimestamp, in TagList tags) =>
this.histogram.Record(Instrumentation.SecondsSince(startTimestamp), tags);
}
8 changes: 8 additions & 0 deletions packages/Core/Core/Diagnostics/Instrumentation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ public static class Instrumentation
/// <param name="name">The meter name, e.g. <c>supabase.gotrue</c>.</param>
public static Meter CreateMeter(Assembly assembly, string name) => new(name, GetVersion(assembly));

/// <summary>
/// The seconds elapsed since a <see cref="Stopwatch.GetTimestamp"/> value, the unit of every duration
/// histogram.
/// </summary>
/// <param name="startTimestamp">The <see cref="Stopwatch.GetTimestamp"/> value captured at the start.</param>
internal static double SecondsSince(long startTimestamp) =>
(Stopwatch.GetTimestamp() - startTimestamp) / (double) Stopwatch.Frequency;

/// <summary>
/// Resolves the version of an assembly, preferring the informational (package) version
/// with any build metadata (<c>+sha</c>) stripped.
Expand Down
44 changes: 29 additions & 15 deletions packages/Functions/Functions.Tests/ObservabilityContractTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,31 +141,45 @@ public async Task InvokeDuration_ShouldRecordPositiveDurationPerRequest()
}

[TestMethod]
public async Task InvokeDuration_ShouldBeNamedAndMeasuredInSeconds()
public async Task InvokeDuration_ShouldBeTheStandardHttpClientInstrument()
{
this.MockInvokeOk();
await this.Invoke();
using (new AssertionScope())
{
this.durationInstrument!.Name.Should().Be("supabase.functions.invoke.duration");
this.durationInstrument!.Unit.Should().Be("s");
}
this.durationInstrument!.Name.Should().Be("http.client.request.duration",
"every Supabase client records the OpenTelemetry HTTP client metric on its own meter, as Postgrest does");
}

[TestMethod]
public async Task InvokeDuration_ShouldTagRequestDimensions()
public async Task InvokeDuration_ShouldMeasureInSeconds()
{
this.MockInvokeOk();
await this.Invoke();
var dimensions = this.measurements.Should().ContainSingle().Which.Value;
using (new AssertionScope())
this.durationInstrument!.Unit.Should().Be("s", "OpenTelemetry measures HTTP client durations in seconds");
}

[TestMethod]
public async Task InvokeDuration_ShouldBeDescribed()
{
this.MockInvokeOk();
await this.Invoke();
this.durationInstrument!.Description.Should().Be("Duration of HTTP client requests.",
"the instrument shares the description of the OpenTelemetry HTTP client metric");
}

[TestMethod]
public async Task InvokeDuration_ShouldCarryTheHttpClientAndFunctionAttributes()
{
this.MockInvokeOk();
await this.Invoke();
this.measurements.Should().ContainSingle().Which.Value.Should().BeEquivalentTo(new Dictionary<string, object?>
{
dimensions["http.request.method"].Should().Be("POST");
dimensions["http.response.status_code"].Should().Be(200);
dimensions["server.address"].Should().Be(new System.Uri(this.server.Url!).Host);
dimensions["url.path"].Should().Be($"/functions/v1/{FunctionName}");
dimensions["faas.invoked_name"].Should().Be(FunctionName);
}
["http.request.method"] = "POST",
["server.address"] = "localhost",
["server.port"] = this.server.Port,
["url.scheme"] = "http",
["http.response.status_code"] = 200,
["faas.invoked_name"] = FunctionName
}, "the metric carries the OpenTelemetry HTTP client attributes and the invoked function, and no URL path");
}

[TestMethod]
Expand Down
2 changes: 1 addition & 1 deletion packages/Functions/Functions/FunctionsDiagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace Supabase.Functions;

/// <summary>
/// Names of the diagnostic sources the Functions client emits to. Pass these when wiring up
/// OpenTelemetry so you don't have to hardcode (case-sensitive) source names:
/// OpenTelemetry rather than repeating the name as a string literal:
/// <c>TracerProviderBuilder.AddSource(FunctionsDiagnostics.SourceName)</c> and
/// <c>MeterProviderBuilder.AddMeter(FunctionsDiagnostics.SourceName)</c>.
/// </summary>
Expand Down
Loading
Loading