From 51639391e445a6f9589841e7eef76097fc82ed2b Mon Sep 17 00:00:00 2001 From: tr00d Date: Thu, 26 Nov 2026 14:19:16 +0100 Subject: [PATCH] feat(observability): record http.client.request.duration and log under lowercase names in every client Auth, Storage and Functions now record the OpenTelemetry http.client.request.duration metric on their own meters, with the same HTTP client attributes Postgrest emits and no URL. The instrument and its attributes live once in Core. Every client builds the attributes only when something listens. Realtime logs under supabase.realtime, defined once. The Diagnostics docs no longer call the source names case-sensitive. --- .../HttpClientRequestDurationTests.cs | 123 +++++++++++ packages/Core/Core.Tests/Http/SdkLogTests.cs | 4 +- .../Diagnostics/HttpClientRequestDuration.cs | 70 +++++++ .../Core/Core/Diagnostics/Instrumentation.cs | 8 + .../ObservabilityContractTests.cs | 44 ++-- .../Functions/FunctionsDiagnostics.cs | 2 +- .../Functions/FunctionsInstrumentation.cs | 118 +++++------ packages/Functions/README.md | 5 +- .../ObservabilityContractTests.cs | 31 ++- packages/Gotrue/Gotrue/GotrueDiagnostics.cs | 2 +- .../Gotrue/Gotrue/GotrueInstrumentation.cs | 23 +-- packages/Gotrue/README.md | 4 +- .../Postgrest/PostgrestDiagnostics.cs | 2 +- .../Postgrest/PostgrestInstrumentation.cs | 30 +-- .../Observability/RealtimeLoggingTests.cs | 16 +- packages/Realtime/Realtime/Client.cs | 2 +- packages/Realtime/Realtime/Realtime.csproj | 1 + packages/Realtime/Realtime/RealtimeChannel.cs | 2 +- packages/Realtime/Realtime/RealtimeLogging.cs | 9 + packages/Realtime/Realtime/RealtimeSocket.cs | 11 +- packages/Storage/README.md | 4 +- .../ObservabilityContractTests.cs | 41 +++- .../Observability/TransferMetricsTests.cs | 85 ++++++++ .../Storage/Storage/StorageDiagnostics.cs | 2 +- .../Storage/Storage/StorageInstrumentation.cs | 193 +++++++++--------- .../DiagnosticLoggingWiringTests.cs | 2 +- .../Observability/SupabaseDiagnosticsTests.cs | 19 ++ packages/Supabase/Supabase/Client.cs | 2 +- .../Supabase/Supabase/SupabaseDiagnostics.cs | 43 ++-- packages/Supabase/Supabase/SupabaseOptions.cs | 4 +- 30 files changed, 619 insertions(+), 283 deletions(-) create mode 100644 packages/Core/Core.Tests/Diagnostics/HttpClientRequestDurationTests.cs create mode 100644 packages/Core/Core/Diagnostics/HttpClientRequestDuration.cs create mode 100644 packages/Realtime/Realtime/RealtimeLogging.cs create mode 100644 packages/Storage/Storage.Tests/Observability/TransferMetricsTests.cs create mode 100644 packages/Supabase/Supabase.Tests/Observability/SupabaseDiagnosticsTests.cs diff --git a/packages/Core/Core.Tests/Diagnostics/HttpClientRequestDurationTests.cs b/packages/Core/Core.Tests/Diagnostics/HttpClientRequestDurationTests.cs new file mode 100644 index 000000000..498ab75ca --- /dev/null +++ b/packages/Core/Core.Tests/Diagnostics/HttpClientRequestDurationTests.cs @@ -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; + +/// +/// Covers : the OpenTelemetry http.client.request.duration instrument +/// every Supabase client records on its own meter, and the HTTP client attributes it carries. +/// +[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 instruments = new(); + private readonly List 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((_, 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 + { + ["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 ToDictionary(TagList tags) + { + var values = new Dictionary(); + foreach (var tag in tags) + values[tag.Key] = tag.Value; + return values; + } +} diff --git a/packages/Core/Core.Tests/Http/SdkLogTests.cs b/packages/Core/Core.Tests/Http/SdkLogTests.cs index fd568e356..a75902e46 100644 --- a/packages/Core/Core.Tests/Http/SdkLogTests.cs +++ b/packages/Core/Core.Tests/Http/SdkLogTests.cs @@ -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"); } } diff --git a/packages/Core/Core/Diagnostics/HttpClientRequestDuration.cs b/packages/Core/Core/Diagnostics/HttpClientRequestDuration.cs new file mode 100644 index 000000000..99a7529b3 --- /dev/null +++ b/packages/Core/Core/Diagnostics/HttpClientRequestDuration.cs @@ -0,0 +1,70 @@ +using System; +using System.Diagnostics; +using System.Diagnostics.Metrics; +using System.Net.Http; + +namespace Supabase.Core.Diagnostics; + +/// +/// The OpenTelemetry http.client.request.duration histogram on a client library's . +/// 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. +/// +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 histogram; + + private HttpClientRequestDuration(Histogram histogram) => this.histogram = histogram; + + /// + /// Whether anything listens to the histogram. Callers build attributes only when it does, so recording + /// costs nothing without a listener. + /// + internal bool Enabled => this.histogram.Enabled; + + /// + /// Creates the histogram on the meter of the client library that sends the requests. + /// + /// The meter that names the client library. + internal static HttpClientRequestDuration On(Meter meter) => + new(meter.CreateHistogram(Name, Unit, Description)); + + /// + /// 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. + /// + /// The HTTP method of the request. + /// The request URI; only its scheme, host and port are recorded. + /// The HTTP response status code, or null if the request never got one. + /// The error classification, or null on success. + 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; + } + + /// + /// Records the time elapsed since the request started. + /// + /// The value captured before the request. + /// The attributes of the request outcome. + internal void Record(long startTimestamp, in TagList tags) => + this.histogram.Record(Instrumentation.SecondsSince(startTimestamp), tags); +} diff --git a/packages/Core/Core/Diagnostics/Instrumentation.cs b/packages/Core/Core/Diagnostics/Instrumentation.cs index d66c961d1..7636c39b0 100644 --- a/packages/Core/Core/Diagnostics/Instrumentation.cs +++ b/packages/Core/Core/Diagnostics/Instrumentation.cs @@ -30,6 +30,14 @@ public static class Instrumentation /// The meter name, e.g. supabase.gotrue. public static Meter CreateMeter(Assembly assembly, string name) => new(name, GetVersion(assembly)); + /// + /// The seconds elapsed since a value, the unit of every duration + /// histogram. + /// + /// The value captured at the start. + internal static double SecondsSince(long startTimestamp) => + (Stopwatch.GetTimestamp() - startTimestamp) / (double) Stopwatch.Frequency; + /// /// Resolves the version of an assembly, preferring the informational (package) version /// with any build metadata (+sha) stripped. diff --git a/packages/Functions/Functions.Tests/ObservabilityContractTests.cs b/packages/Functions/Functions.Tests/ObservabilityContractTests.cs index f35c9f58e..776d3aded 100644 --- a/packages/Functions/Functions.Tests/ObservabilityContractTests.cs +++ b/packages/Functions/Functions.Tests/ObservabilityContractTests.cs @@ -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 { - 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] diff --git a/packages/Functions/Functions/FunctionsDiagnostics.cs b/packages/Functions/Functions/FunctionsDiagnostics.cs index 9656faccc..4edf38226 100644 --- a/packages/Functions/Functions/FunctionsDiagnostics.cs +++ b/packages/Functions/Functions/FunctionsDiagnostics.cs @@ -2,7 +2,7 @@ namespace Supabase.Functions; /// /// 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: /// TracerProviderBuilder.AddSource(FunctionsDiagnostics.SourceName) and /// MeterProviderBuilder.AddMeter(FunctionsDiagnostics.SourceName). /// diff --git a/packages/Functions/Functions/FunctionsInstrumentation.cs b/packages/Functions/Functions/FunctionsInstrumentation.cs index 6e3571c12..d8ead662d 100644 --- a/packages/Functions/Functions/FunctionsInstrumentation.cs +++ b/packages/Functions/Functions/FunctionsInstrumentation.cs @@ -4,79 +4,65 @@ using System.Net.Http; using Supabase.Core.Diagnostics; -namespace Supabase.Functions -{ - /// - /// Diagnostics for the Functions client, exposed through so - /// consumers can subscribe with the OpenTelemetry SDK using - /// (AddSource(...) / AddMeter(...)). Emission is zero-cost when nothing is listening. - /// - /// Telemetry must never carry secrets or PII: URLs are recorded without their query string and - /// no tag may contain the request body, a token, or other sensitive value. The invoked function - /// name is recorded (it is part of the path), but never the payload. - /// - internal static class FunctionsInstrumentation - { - /// Tag key carrying the invoked function name (OpenTelemetry FaaS convention). - internal const string FunctionNameTag = "faas.invoked_name"; - - internal static readonly ActivitySource Source = - Instrumentation.CreateActivitySource(typeof(FunctionsInstrumentation).Assembly, FunctionsDiagnostics.SourceName); +namespace Supabase.Functions; - private static readonly Meter Meter = - Instrumentation.CreateMeter(typeof(FunctionsInstrumentation).Assembly, FunctionsDiagnostics.SourceName); - - private static readonly Histogram RequestDuration = Meter.CreateHistogram( - "supabase.functions.invoke.duration", "s", "Duration of function invocations sent by the Functions client."); - - /// - /// Starts the client span for a function invocation, tagged per OpenTelemetry HTTP - /// conventions with the sanitized (query-less) URL. Returns null when nothing is listening. - /// - /// The HTTP method of the request. - /// The request URI, sanitized before tagging. - /// The invoked function name. - internal static Activity? StartInvokeActivity(HttpMethod method, Uri uri, string functionName) - { - var activity = Source.StartActivity($"{method.Method} {uri.AbsolutePath}", ActivityKind.Client) - .SetHttpRequestTags(method.Method, uri); +/// +/// Diagnostics for the Functions client, exposed through so +/// consumers can subscribe with the OpenTelemetry SDK using +/// (AddSource(...) / AddMeter(...)). Emission is zero-cost when nothing is listening. +/// +/// Telemetry must never carry secrets or PII: URLs are recorded without their query string and +/// no tag may contain the request body, a token, or other sensitive value. The invoked function +/// name is recorded (it is part of the path), but never the payload. +/// +internal static class FunctionsInstrumentation +{ + /// Tag key carrying the invoked function name (OpenTelemetry FaaS convention). + internal const string FunctionNameTag = "faas.invoked_name"; - activity?.SetTag(FunctionNameTag, functionName); - return activity; - } + internal static readonly ActivitySource Source = + Instrumentation.CreateActivitySource(typeof(FunctionsInstrumentation).Assembly, FunctionsDiagnostics.SourceName); - /// - /// Records the invocation duration histogram for a request outcome. - /// - /// The HTTP method of the request. - /// The request URI; only its host and path are recorded. - /// The invoked function name. - /// The HTTP response status code, or null if the request never got one. - /// The error classification, or null on success. - /// The value captured before the request. - internal static void RecordInvoke(HttpMethod method, Uri uri, string functionName, int? statusCode, string? errorType, long startTimestamp) - { - if (!RequestDuration.Enabled) - return; + private static readonly Meter Meter = + Instrumentation.CreateMeter(typeof(FunctionsInstrumentation).Assembly, FunctionsDiagnostics.SourceName); - var tags = new TagList - { - { "http.request.method", method.Method }, - { "server.address", uri.Host }, - { "url.path", uri.AbsolutePath }, - { FunctionNameTag, functionName } - }; + private static readonly HttpClientRequestDuration RequestDuration = HttpClientRequestDuration.On(Meter); - if (statusCode.HasValue) - tags.Add("http.response.status_code", statusCode.Value); + /// + /// Starts the client span for a function invocation, tagged per OpenTelemetry HTTP + /// conventions with the sanitized (query-less) URL. Returns null when nothing is listening. + /// + /// The HTTP method of the request. + /// The request URI, sanitized before tagging. + /// The invoked function name. + internal static Activity? StartInvokeActivity(HttpMethod method, Uri uri, string functionName) + { + var activity = Source.StartActivity($"{method.Method} {uri.AbsolutePath}", ActivityKind.Client) + .SetHttpRequestTags(method.Method, uri); - if (errorType != null) - tags.Add("error.type", errorType); + activity?.SetTag(FunctionNameTag, functionName); + return activity; + } - RequestDuration.Record(GetElapsedSeconds(startTimestamp), tags); - } + /// + /// Records the invocation duration histogram for a request outcome. + /// + /// The HTTP method of the request. + /// The request URI; only its scheme, host and port are recorded. + /// The invoked function name. + /// The HTTP response status code, or null if the request never got one. + /// The error classification, or null on success. + /// The value captured before the request. + internal static void RecordInvoke(HttpMethod method, Uri uri, string functionName, int? statusCode, string? errorType, long startTimestamp) + { + if (RequestDuration.Enabled) + RequestDuration.Record(startTimestamp, InvokeTags(method, uri, functionName, statusCode, errorType)); + } - private static double GetElapsedSeconds(long startTimestamp) => - (Stopwatch.GetTimestamp() - startTimestamp) / (double)Stopwatch.Frequency; + private static TagList InvokeTags(HttpMethod method, Uri uri, string functionName, int? statusCode, string? errorType) + { + var tags = HttpClientRequestDuration.TagsOf(method, uri, statusCode, errorType); + tags.Add(FunctionNameTag, functionName); + return tags; } } diff --git a/packages/Functions/README.md b/packages/Functions/README.md index 19ff54eff..db2f8b582 100644 --- a/packages/Functions/README.md +++ b/packages/Functions/README.md @@ -112,8 +112,9 @@ Once subscribed you get: (method, status code, and a sanitized URL — the query string is never recorded, and neither is the request body). A `faas.invoked_name` tag carries the invoked function name. A relay error is reported as a failed span even when the HTTP status is a success. -- A `supabase.functions.invoke.duration` histogram (seconds), tagged with method, host, path, - function name, and status code. +- The standard `http.client.request.duration` histogram (seconds) on the `supabase.functions` meter, + tagged with method, server address and port, scheme, status code, error type and + `faas.invoked_name`. It carries no URL. If you are not using the OpenTelemetry SDK, a raw listener works too: diff --git a/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs b/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs index c441a4c6b..1666ff3b3 100644 --- a/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs +++ b/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs @@ -322,17 +322,36 @@ public async Task RequestDurationHistogram_ShouldRecordOncePerRequest() var measurement = this.measurements.Should().ContainSingle().Which; using (new AssertionScope()) { - measurement.Instrument.Should().Be("supabase.gotrue.http.request.duration"); measurement.Unit.Should().Be("s", "the histogram records a duration in seconds"); measurement.Value.Should().BeGreaterThan(0); - measurement.Tags.Should().Contain("http.request.method", "POST"); - measurement.Tags.Should().Contain("server.address", new Uri(this.server.Url).Host); - measurement.Tags.Should().Contain("http.response.status_code", 200); - measurement.Tags.Should().Contain("url.path", "/token"); - measurement.Tags.Should().NotContainKey("error.type", "a successful request carries no error tag"); } } + [TestMethod] + public async Task RequestDurationHistogram_ShouldBeTheStandardHttpClientInstrument() + { + this.MockTokenSuccess(); + await this.Refresh(); + this.measurements.Should().ContainSingle().Which.Instrument.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 RequestDurationHistogram_ShouldCarryTheHttpClientAttributes() + { + this.MockTokenSuccess(); + await this.Refresh(); + var serverUri = new Uri(this.server.Url); + this.measurements.Should().ContainSingle().Which.Tags.Should().BeEquivalentTo(new Dictionary + { + ["http.request.method"] = "POST", + ["server.address"] = serverUri.Host, + ["server.port"] = serverUri.Port, + ["url.scheme"] = serverUri.Scheme, + ["http.response.status_code"] = 200, + }, "the metric carries the OpenTelemetry HTTP client attributes and no URL path, which holds user and factor ids"); + } + [TestMethod] public async Task RequestDurationHistogram_ShouldTagErrorType_GivenFailedRequest() { diff --git a/packages/Gotrue/Gotrue/GotrueDiagnostics.cs b/packages/Gotrue/Gotrue/GotrueDiagnostics.cs index 814afb84c..68498658a 100644 --- a/packages/Gotrue/Gotrue/GotrueDiagnostics.cs +++ b/packages/Gotrue/Gotrue/GotrueDiagnostics.cs @@ -2,7 +2,7 @@ namespace Supabase.Gotrue; /// /// Names of the diagnostic sources the GoTrue 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: /// TracerProviderBuilder.AddSource(GotrueDiagnostics.SourceName) and /// MeterProviderBuilder.AddMeter(GotrueDiagnostics.SourceName). /// diff --git a/packages/Gotrue/Gotrue/GotrueInstrumentation.cs b/packages/Gotrue/Gotrue/GotrueInstrumentation.cs index bb53b2855..7de3afecc 100644 --- a/packages/Gotrue/Gotrue/GotrueInstrumentation.cs +++ b/packages/Gotrue/Gotrue/GotrueInstrumentation.cs @@ -27,8 +27,7 @@ internal static class GotrueInstrumentation private static readonly Meter Meter = Instrumentation.CreateMeter(typeof(GotrueInstrumentation).Assembly, GotrueDiagnostics.SourceName); - private static readonly Histogram RequestDuration = Meter.CreateHistogram( - "supabase.gotrue.http.request.duration", "s", "Duration of HTTP requests sent by the GoTrue client."); + private static readonly HttpClientRequestDuration RequestDuration = HttpClientRequestDuration.On(Meter); /// /// Starts the client span for an outgoing HTTP request, tagged per OpenTelemetry HTTP @@ -43,25 +42,9 @@ internal static class GotrueInstrumentation /// internal static void RecordRequest(HttpMethod method, Uri uri, int? statusCode, string? errorType, long startTimestamp) { - if (!RequestDuration.Enabled) - return; - - var tags = new TagList - { - { "http.request.method", method.Method }, - { "server.address", uri.Host }, - { "url.path", uri.AbsolutePath } - }; - - if (statusCode.HasValue) - tags.Add("http.response.status_code", statusCode.Value); - - if (errorType != null) - tags.Add("error.type", errorType); - - RequestDuration.Record(GetElapsedSeconds(startTimestamp), tags); + if (RequestDuration.Enabled) + RequestDuration.Record(startTimestamp, HttpClientRequestDuration.TagsOf(method, uri, statusCode, errorType)); } - private static double GetElapsedSeconds(long startTimestamp) => (Stopwatch.GetTimestamp() - startTimestamp) / (double) Stopwatch.Frequency; /// Names of the domain spans emitted for the public GoTrue operations. internal static class Spans diff --git a/packages/Gotrue/README.md b/packages/Gotrue/README.md index 570982bf1..c73863c44 100644 --- a/packages/Gotrue/README.md +++ b/packages/Gotrue/README.md @@ -193,8 +193,8 @@ Once subscribed you get: - A span per public operation (`gotrue.sign_in`, `gotrue.refresh_token`, …) with a child client span for the underlying HTTP call following OpenTelemetry HTTP conventions (method, status code, and a sanitized URL — the query string, which carries grant types and API keys, is never recorded). -- A `supabase.gotrue.http.request.duration` histogram (seconds), tagged with method, host, path, and - status code. +- The standard `http.client.request.duration` histogram (seconds) on the `supabase.gotrue` meter, + tagged with method, server address and port, scheme, status code and error type. It carries no URL. If you are not using the OpenTelemetry SDK, a raw listener works too: diff --git a/packages/Postgrest/Postgrest/PostgrestDiagnostics.cs b/packages/Postgrest/Postgrest/PostgrestDiagnostics.cs index 36cb705e0..52e1c40b6 100644 --- a/packages/Postgrest/Postgrest/PostgrestDiagnostics.cs +++ b/packages/Postgrest/Postgrest/PostgrestDiagnostics.cs @@ -2,7 +2,7 @@ namespace Supabase.Postgrest; /// /// Names of the diagnostic sources the Postgrest 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: /// TracerProviderBuilder.AddSource(PostgrestDiagnostics.SourceName) and /// MeterProviderBuilder.AddMeter(PostgrestDiagnostics.SourceName). /// diff --git a/packages/Postgrest/Postgrest/PostgrestInstrumentation.cs b/packages/Postgrest/Postgrest/PostgrestInstrumentation.cs index cfc582832..e34836af2 100644 --- a/packages/Postgrest/Postgrest/PostgrestInstrumentation.cs +++ b/packages/Postgrest/Postgrest/PostgrestInstrumentation.cs @@ -32,8 +32,7 @@ internal static class PostgrestInstrumentation private static readonly Meter Meter = Instrumentation.CreateMeter(typeof(PostgrestInstrumentation).Assembly, PostgrestDiagnostics.SourceName); - private static readonly Histogram RequestDuration = Meter.CreateHistogram( - "http.client.request.duration", "s", "Duration of HTTP client requests."); + private static readonly HttpClientRequestDuration RequestDuration = HttpClientRequestDuration.On(Meter); /// /// Maps an HTTP method and the request flags to the logical Postgrest operation name. @@ -87,14 +86,14 @@ internal static string ResolveOperation(HttpMethod method, bool isInsert, bool i /// The value captured before the request. internal static void RecordRequest(HttpMethod method, Uri uri, PostgrestCall call, int? statusCode, string? errorType, long startTimestamp) { - var tags = new TagList - { - { "http.request.method", method.Method }, - { "server.address", uri.Host }, - { "server.port", uri.Port }, - { "url.scheme", uri.Scheme }, - { OperationTag, call.Operation } - }; + if (RequestDuration.Enabled) + RequestDuration.Record(startTimestamp, RequestTags(method, uri, call, statusCode, errorType)); + } + + private static TagList RequestTags(HttpMethod method, Uri uri, PostgrestCall call, int? statusCode, string? errorType) + { + var tags = HttpClientRequestDuration.TagsOf(method, uri, statusCode, errorType); + tags.Add(OperationTag, call.Operation); if (call.Table != null) tags.Add(TableTag, call.Table); @@ -102,15 +101,6 @@ internal static void RecordRequest(HttpMethod method, Uri uri, PostgrestCall cal if (call.Function != null) tags.Add(FunctionTag, call.Function); - if (statusCode.HasValue) - tags.Add("http.response.status_code", statusCode.Value); - - if (errorType != null) - tags.Add("error.type", errorType); - - RequestDuration.Record(GetElapsedSeconds(startTimestamp), tags); + return tags; } - - private static double GetElapsedSeconds(long startTimestamp) => - (Stopwatch.GetTimestamp() - startTimestamp) / (double) Stopwatch.Frequency; } diff --git a/packages/Realtime/Realtime.Tests/Observability/RealtimeLoggingTests.cs b/packages/Realtime/Realtime.Tests/Observability/RealtimeLoggingTests.cs index 18f0093b4..330931dcf 100644 --- a/packages/Realtime/Realtime.Tests/Observability/RealtimeLoggingTests.cs +++ b/packages/Realtime/Realtime.Tests/Observability/RealtimeLoggingTests.cs @@ -42,7 +42,7 @@ private Client ClientOver(FakeWebsocketClient socket, Func>? retri public async Task ConnectAsync_ShouldLogTheConnectionAtDebug() { await this.ClientOver(new FakeWebsocketClient { OpenOnStart = true }).ConnectAsync(); - this.Messages().Should().Contain("Supabase.Realtime: connected"); + this.Messages().Should().Contain("supabase.realtime: connected"); } [TestMethod] @@ -51,7 +51,7 @@ public async Task Channel_ShouldLogItsStateAtDebug_GivenItJoined() var realtime = this.ClientOver(new FakeWebsocketClient { OpenOnStart = true, AnswerJoins = true }); await realtime.ConnectAsync(); await realtime.Channel("room").Subscribe(); - this.Messages().Should().Contain("Supabase.Realtime: channel realtime:room Joined", "a channel's state change is a lifecycle diagnostic"); + this.Messages().Should().Contain("supabase.realtime: channel realtime:room Joined", "a channel's state change is a lifecycle diagnostic"); } [TestMethod] @@ -71,9 +71,9 @@ public async Task Socket_ShouldLogTheDropAndTheReconnection_GivenALostConnection socket.RecoverFromLostConnection(); using (new AssertionScope()) { - this.Messages().Should().Contain(message => message.StartsWith("Supabase.Realtime: disconnected", StringComparison.Ordinal), "the drop is a lifecycle diagnostic"); - this.Messages().Should().Contain("Supabase.Realtime: reconnection attempt scheduled", "the next attempt is a lifecycle diagnostic"); - this.Messages().Should().Contain(message => message.StartsWith("Supabase.Realtime: reconnection ", StringComparison.Ordinal) && !message.EndsWith("scheduled", StringComparison.Ordinal), + this.Messages().Should().Contain(message => message.StartsWith("supabase.realtime: disconnected", StringComparison.Ordinal), "the drop is a lifecycle diagnostic"); + this.Messages().Should().Contain("supabase.realtime: reconnection attempt scheduled", "the next attempt is a lifecycle diagnostic"); + this.Messages().Should().Contain(message => message.StartsWith("supabase.realtime: reconnection ", StringComparison.Ordinal) && !message.EndsWith("scheduled", StringComparison.Ordinal), "the recovery is a lifecycle diagnostic"); } } @@ -82,8 +82,8 @@ public async Task Socket_ShouldLogTheDropAndTheReconnection_GivenALostConnection public async Task Socket_ShouldLogTheHeartbeatTimeoutAtDebug_GivenNoReply() { await this.ClientOver(new FakeWebsocketClient { OpenOnStart = true }).ConnectAsync(); - await WaitUntil(() => this.Messages().Contains("Supabase.Realtime: heartbeat timed out, reconnecting")); - this.Messages().Should().Contain("Supabase.Realtime: heartbeat timed out, reconnecting"); + await WaitUntil(() => this.Messages().Contains("supabase.realtime: heartbeat timed out, reconnecting")); + this.Messages().Should().Contain("supabase.realtime: heartbeat timed out, reconnecting"); } [TestMethod] @@ -94,7 +94,7 @@ await this.ClientOver(new FakeWebsocketClient { OpenOnStart = true, AnswerHeartb () => ++calls == 1 ? Task.FromResult("first") : throw new InvalidOperationException("secret-detail")).ConnectAsync(); await WaitUntil(() => this.capture.Records.Any(record => record.Level == LogLevel.Warning)); this.capture.Records.First(record => record.Level == LogLevel.Warning).Message.Should() - .Be("Supabase.Realtime: Access token refresh on heartbeat failed with InvalidOperationException", "a heartbeat has no caller to throw to"); + .Be("supabase.realtime: Access token refresh on heartbeat failed with InvalidOperationException", "a heartbeat has no caller to throw to"); } private static async Task WaitUntil(Func condition) diff --git a/packages/Realtime/Realtime/Client.cs b/packages/Realtime/Realtime/Client.cs index 76dd55191..a5305b8dc 100644 --- a/packages/Realtime/Realtime/Client.cs +++ b/packages/Realtime/Realtime/Client.cs @@ -345,7 +345,7 @@ private void LogRefreshFailure(Task refresh) { var failure = refresh.Exception!.InnerException!; Debugger.Instance.Log(this, failure.Message, failure); - this.Options.Logger.BackgroundWorkFailed("Supabase.Realtime", "Access token refresh on heartbeat", failure); + this.Options.Logger.BackgroundWorkFailed(RealtimeLogging.Category, "Access token refresh on heartbeat", failure); } private async Task RefreshAuthAsync() diff --git a/packages/Realtime/Realtime/Realtime.csproj b/packages/Realtime/Realtime/Realtime.csproj index 0ca837358..42016368e 100644 --- a/packages/Realtime/Realtime/Realtime.csproj +++ b/packages/Realtime/Realtime/Realtime.csproj @@ -32,6 +32,7 @@ + diff --git a/packages/Realtime/Realtime/RealtimeChannel.cs b/packages/Realtime/Realtime/RealtimeChannel.cs index f95bdaca4..d30a99fa0 100644 --- a/packages/Realtime/Realtime/RealtimeChannel.cs +++ b/packages/Realtime/Realtime/RealtimeChannel.cs @@ -308,7 +308,7 @@ public void ClearStateChangedHandlers() => private void NotifyStateChanged(ChannelState state, bool shouldRejoin = true) { this.State = state; - this.Options.ClientOptions.Logger.BackgroundWorkEvent("Supabase.Realtime", $"channel {this.Topic} {state}"); + this.Options.ClientOptions.Logger.BackgroundWorkEvent(RealtimeLogging.Category, $"channel {this.Topic} {state}"); this.isRejoining = shouldRejoin; if (shouldRejoin) diff --git a/packages/Realtime/Realtime/RealtimeLogging.cs b/packages/Realtime/Realtime/RealtimeLogging.cs new file mode 100644 index 000000000..91cde58de --- /dev/null +++ b/packages/Realtime/Realtime/RealtimeLogging.cs @@ -0,0 +1,9 @@ +namespace Supabase.Realtime; + +/// +/// The category the Realtime client logs under, lowercase like the other Supabase clients' categories. +/// +internal static class RealtimeLogging +{ + internal const string Category = "supabase.realtime"; +} diff --git a/packages/Realtime/Realtime/RealtimeSocket.cs b/packages/Realtime/Realtime/RealtimeSocket.cs index fb6c5971b..8255c78bf 100644 --- a/packages/Realtime/Realtime/RealtimeSocket.cs +++ b/packages/Realtime/Realtime/RealtimeSocket.cs @@ -72,7 +72,6 @@ private string EndpointUrl private readonly HandlerCollection errorEventHandlers = new(); private readonly string endpoint; - private const string LogComponent = "Supabase.Realtime"; private const long NotWaiting = long.MaxValue; private static readonly TimeSpan NetworkWakeSpacing = TimeSpan.FromSeconds(2); @@ -360,7 +359,7 @@ private void SendHeartbeat() this.hasPendingHeartbeat = false; Debugger.Instance.Log(this, "Socket Heartbeat Timeout: Attempting to re-establish a connection."); - this.options.Logger.BackgroundWorkEvent(LogComponent, "heartbeat timed out, reconnecting"); + this.options.Logger.BackgroundWorkEvent(RealtimeLogging.Category, "heartbeat timed out, reconnecting"); this.OnHeartbeat?.Invoke(HeartbeatStatus.Timeout, null); _ = this.connection.Reconnect(); return; @@ -395,7 +394,7 @@ private void HandleSocketOpened() this.isReconnecting = false; Debugger.Instance.Log(this, $"Socket Connected to: {this.EndpointUrl}"); - this.options.Logger.BackgroundWorkEvent(LogComponent, "connected"); + this.options.Logger.BackgroundWorkEvent(RealtimeLogging.Category, "connected"); this.StartHeartbeat(); @@ -469,7 +468,7 @@ private async Task ProbeAsync() private void HandleSocketReconnectionHappened(ReconnectionInfo reconnectionInfo) { Debugger.Instance.Log(this, $"Socket Reconnection: {reconnectionInfo.Type}"); - this.options.Logger.BackgroundWorkEvent(LogComponent, $"reconnection {reconnectionInfo.Type}"); + this.options.Logger.BackgroundWorkEvent(RealtimeLogging.Category, $"reconnection {reconnectionInfo.Type}"); if (this.disconnectRequested) { @@ -490,7 +489,7 @@ private void HandleSocketReconnectionHappened(ReconnectionInfo reconnectionInfo) private void HandleSocketDisconnectionHappened(DisconnectionInfo disconnectionInfo) { Debugger.Instance.Log(this, $"Socket Disconnection: {disconnectionInfo.Type}", disconnectionInfo.Exception); - this.options.Logger.BackgroundWorkEvent(LogComponent, $"disconnected ({disconnectionInfo.Type})"); + this.options.Logger.BackgroundWorkEvent(RealtimeLogging.Category, $"disconnected ({disconnectionInfo.Type})"); if (disconnectionInfo.Type != DisconnectionType.Error) this.MarkAttemptStarted(); @@ -561,7 +560,7 @@ private void HandleSocketError(DisconnectionInfo? disconnectionInfo = null) var nextInterval = DateTime.Now.Add(delay); Debugger.Instance.Log(this, $"Next reconnection attempt will occur at: {nextInterval}"); - this.options.Logger.BackgroundWorkEvent(LogComponent, "reconnection attempt scheduled"); + this.options.Logger.BackgroundWorkEvent(RealtimeLogging.Category, "reconnection attempt scheduled"); break; } case false when disconnectionInfo is { Exception: not RealtimeException }: diff --git a/packages/Storage/README.md b/packages/Storage/README.md index 07ae212a0..d4f058360 100644 --- a/packages/Storage/README.md +++ b/packages/Storage/README.md @@ -126,7 +126,9 @@ Once subscribed you get: `storage.transfer.direction` tag (`upload` / `download`). The resumable (TUS) upload is reported as a single operation span covering the whole transfer, rather than one span per underlying chunk request. -- `supabase.storage.http.request.duration` (seconds) for control-plane requests. +- The standard `http.client.request.duration` histogram (seconds) on the `supabase.storage` meter for + control-plane requests, tagged with method, server address and port, scheme, status code and error + type. It carries no URL. - `supabase.storage.transfer.duration` (seconds) and `supabase.storage.transfer.size` (bytes) for uploads and downloads, tagged by direction — because a duration alone does not describe a file transfer. diff --git a/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs b/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs index 20b0c450b..432f08330 100644 --- a/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs +++ b/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs @@ -84,10 +84,33 @@ public async Task ControlPlaneRequest_ShouldEmitAnHttpSpanWithoutTransferDirecti span.GetTagItem("http.request.method").Should().Be("POST"); span.GetTagItem("http.response.status_code").Should().Be(200); span.GetTagItem("storage.transfer.direction").Should().BeNull(); - this.measurements.Should().Contain(m => m.Name == "supabase.storage.http.request.duration"); } } + [TestMethod] + public async Task ControlPlaneRequest_ShouldRecordTheStandardHttpClientInstrument() + { + this.RespondJson($"/storage/v1/object/list/{Bucket}", "POST", 200, "[]"); + await this.client.From(Bucket).List(); + this.measurements.Should().ContainSingle().Which.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 ControlPlaneRequest_ShouldCarryTheHttpClientAttributes() + { + this.RespondJson($"/storage/v1/object/list/{Bucket}", "POST", 200, "[]"); + await this.client.From(Bucket).List(); + this.measurements.Should().ContainSingle().Which.Tags.Should().BeEquivalentTo(new Dictionary + { + ["http.request.method"] = "POST", + ["server.address"] = "localhost", + ["server.port"] = this.server.Port, + ["url.scheme"] = "http", + ["http.response.status_code"] = 200 + }, "the metric carries the OpenTelemetry HTTP client attributes and no URL path, which holds bucket and object names"); + } + [TestMethod] public async Task Download_ShouldTagTheSpanAndRecordTheTransferSize() { @@ -107,6 +130,22 @@ public async Task Download_ShouldTagTheSpanAndRecordTheTransferSize() } } + [TestMethod] + public async Task Download_ShouldCarryTheTransferAttributes() + { + this.server.Given(Request.Create().WithPath($"/storage/v1/object/{Bucket}/file.txt").UsingGet()) + .RespondWith(Response.Create().WithStatusCode(200).WithBody("payload")); + await this.client.From(Bucket).Download("file.txt", (EventHandler?) null); + this.measurements.Single(m => m.Name == "supabase.storage.transfer.duration").Tags.Should().BeEquivalentTo(new Dictionary + { + ["http.request.method"] = "GET", + ["server.address"] = "localhost", + ["url.path"] = $"/storage/v1/object/{Bucket}/file.txt", + ["storage.transfer.direction"] = "download", + ["http.response.status_code"] = 200 + }, "a transfer is a whole upload or download rather than one HTTP request, so it keeps its own metrics and attributes"); + } + [TestMethod] public async Task Upload_ShouldTagTheSpanAndRecordTheTransferSize() { diff --git a/packages/Storage/Storage.Tests/Observability/TransferMetricsTests.cs b/packages/Storage/Storage.Tests/Observability/TransferMetricsTests.cs new file mode 100644 index 000000000..bf33352cc --- /dev/null +++ b/packages/Storage/Storage.Tests/Observability/TransferMetricsTests.cs @@ -0,0 +1,85 @@ +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.Storage; + +namespace Storage.Tests.Observability; + +/// +/// Covers the transfer metrics on their own: each records as soon as something listens to it, whether or not the +/// other one is listened to, and a failed transfer carries its error type. +/// +[TestClass] +[TestCategory("Contract")] +public class TransferMetricsTests +{ + private const string TransferDuration = "supabase.storage.transfer.duration"; + private const string TransferSize = "supabase.storage.transfer.size"; + private const long TransferredBytes = 42; + private const int ServerError = 500; + private static readonly Uri ObjectUri = new("http://localhost/storage/v1/object/bucket/file.txt"); + + private readonly List<(string Name, Dictionary Tags)> measurements = new(); + private MeterListener listener = null!; + + [TestCleanup] + public void TearDown() => this.listener.Dispose(); + + [TestMethod] + public void RecordTransfer_ShouldRecordTheDuration_GivenOnlyTheDurationIsListenedTo() + { + this.ListenTo(TransferDuration); + RecordDownload(null); + this.measurements.Should().ContainSingle(m => m.Name == TransferDuration, + "the duration is recorded whenever it has a listener, even when the size has none"); + } + + [TestMethod] + public void RecordTransfer_ShouldRecordTheSize_GivenOnlyTheSizeIsListenedTo() + { + this.ListenTo(TransferSize); + RecordDownload(null); + this.measurements.Should().ContainSingle(m => m.Name == TransferSize, + "the size is recorded whenever it has a listener, even when the duration has none"); + } + + [TestMethod] + public void RecordTransfer_ShouldCarryTheErrorType_GivenAFailedTransfer() + { + this.ListenTo(TransferDuration); + RecordDownload(ServerError.ToString()); + this.measurements.Should().ContainSingle().Which.Tags.Should().Contain("error.type", ServerError.ToString(), + "a failed transfer says why it failed"); + } + + private static void RecordDownload(string? errorType) => + StorageInstrumentation.RecordTransfer(StorageInstrumentation.DirectionDownload, HttpMethod.Get, ObjectUri, + TransferredBytes, ServerError, errorType, Stopwatch.GetTimestamp()); + + private void ListenTo(string instrumentName) + { + this.listener = new MeterListener + { + InstrumentPublished = (instrument, meterListener) => + { + if (instrument.Meter.Name == StorageDiagnostics.SourceName && instrument.Name == instrumentName) + meterListener.EnableMeasurementEvents(instrument); + } + }; + this.listener.SetMeasurementEventCallback((instrument, _, tags, _) => this.Capture(instrument.Name, tags)); + this.listener.SetMeasurementEventCallback((instrument, _, tags, _) => this.Capture(instrument.Name, tags)); + this.listener.Start(); + } + + private void Capture(string name, ReadOnlySpan> tags) + { + var values = new Dictionary(); + foreach (var tag in tags) + values[tag.Key] = tag.Value; + this.measurements.Add((name, values)); + } +} diff --git a/packages/Storage/Storage/StorageDiagnostics.cs b/packages/Storage/Storage/StorageDiagnostics.cs index 17c89e3cb..b3c426d37 100644 --- a/packages/Storage/Storage/StorageDiagnostics.cs +++ b/packages/Storage/Storage/StorageDiagnostics.cs @@ -2,7 +2,7 @@ namespace Supabase.Storage; /// /// Names of the diagnostic sources the Storage 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: /// TracerProviderBuilder.AddSource(StorageDiagnostics.SourceName) and /// MeterProviderBuilder.AddMeter(StorageDiagnostics.SourceName). /// diff --git a/packages/Storage/Storage/StorageInstrumentation.cs b/packages/Storage/Storage/StorageInstrumentation.cs index 08db6a4e1..53e6c9228 100644 --- a/packages/Storage/Storage/StorageInstrumentation.cs +++ b/packages/Storage/Storage/StorageInstrumentation.cs @@ -4,122 +4,113 @@ using System.Net.Http; using Supabase.Core.Diagnostics; -namespace Supabase.Storage +namespace Supabase.Storage; + +/// +/// Diagnostics for the Storage client, exposed through so +/// consumers can subscribe with the OpenTelemetry SDK using +/// (AddSource(...) / AddMeter(...)). Emission is zero-cost when nothing is listening. +/// +/// Telemetry must never carry secrets or PII: URLs are recorded without their query string +/// (Storage signed URLs put a token there) and no tag may contain a token, credential, +/// or file contents. +/// +/// Storage covers three HTTP surfaces: the JSON control plane (bucket/file management), and the +/// upload and download transfer paths. Transfers additionally report the number of bytes moved, +/// since a duration alone does not describe a file transfer. +/// +internal static class StorageInstrumentation { - /// - /// Diagnostics for the Storage client, exposed through so - /// consumers can subscribe with the OpenTelemetry SDK using - /// (AddSource(...) / AddMeter(...)). Emission is zero-cost when nothing is listening. - /// - /// Telemetry must never carry secrets or PII: URLs are recorded without their query string - /// (Storage signed URLs put a token there) and no tag may contain a token, credential, - /// or file contents. - /// - /// Storage covers three HTTP surfaces: the JSON control plane (bucket/file management), and the - /// upload and download transfer paths. Transfers additionally report the number of bytes moved, - /// since a duration alone does not describe a file transfer. - /// - internal static class StorageInstrumentation - { - /// Tag key carrying the transfer direction (upload/download). - internal const string DirectionTag = "storage.transfer.direction"; + /// Tag key carrying the transfer direction (upload/download). + internal const string DirectionTag = "storage.transfer.direction"; - internal const string DirectionUpload = "upload"; - internal const string DirectionDownload = "download"; + internal const string DirectionUpload = "upload"; + internal const string DirectionDownload = "download"; - internal static readonly ActivitySource Source = - Instrumentation.CreateActivitySource(typeof(StorageInstrumentation).Assembly, StorageDiagnostics.SourceName); + internal static readonly ActivitySource Source = + Instrumentation.CreateActivitySource(typeof(StorageInstrumentation).Assembly, StorageDiagnostics.SourceName); - private static readonly Meter Meter = - Instrumentation.CreateMeter(typeof(StorageInstrumentation).Assembly, StorageDiagnostics.SourceName); + private static readonly Meter Meter = + Instrumentation.CreateMeter(typeof(StorageInstrumentation).Assembly, StorageDiagnostics.SourceName); - private static readonly Histogram RequestDuration = Meter.CreateHistogram( - "supabase.storage.http.request.duration", "s", "Duration of control-plane HTTP requests sent by the Storage client."); + private static readonly HttpClientRequestDuration RequestDuration = HttpClientRequestDuration.On(Meter); - private static readonly Histogram TransferDuration = Meter.CreateHistogram( - "supabase.storage.transfer.duration", "s", "Duration of file upload/download transfers."); + private static readonly Histogram TransferDuration = Meter.CreateHistogram( + "supabase.storage.transfer.duration", "s", "Duration of file upload/download transfers."); - private static readonly Histogram TransferSize = Meter.CreateHistogram( - "supabase.storage.transfer.size", "By", "Number of bytes moved by file upload/download transfers."); + private static readonly Histogram TransferSize = Meter.CreateHistogram( + "supabase.storage.transfer.size", "By", "Number of bytes moved by file upload/download transfers."); - /// - /// Starts a client span for a Storage HTTP request, tagged per OpenTelemetry HTTP - /// conventions with the sanitized (query-less) URL. Returns null when nothing is listening. - /// - /// The HTTP method of the request. - /// The request URI, sanitized before tagging. - /// The transfer direction, or null for control-plane requests. - internal static Activity? StartHttpActivity(HttpMethod method, Uri uri, string? direction = null) - { - var activity = Source.StartActivity($"{method.Method} {uri.AbsolutePath}", ActivityKind.Client) - .SetHttpRequestTags(method.Method, uri); - - if (direction != null) - activity?.SetTag(DirectionTag, direction); - - return activity; - } - - /// - /// Records the control-plane request duration histogram for an HTTP request outcome. - /// - /// The HTTP method of the request. - /// The request URI; only its host and path are recorded. - /// The HTTP response status code, or null if the request never got one. - /// The error classification, or null on success. - /// The value captured before the request. - internal static void RecordRequest(HttpMethod method, Uri uri, int? statusCode, string? errorType, long startTimestamp) - { - if (!RequestDuration.Enabled) - return; - - var tags = BaseTags(method.Method, uri, statusCode, errorType); - RequestDuration.Record(GetElapsedSeconds(startTimestamp), tags); - } - - /// - /// Records the transfer duration and (when known) size histograms for an upload/download outcome. - /// - /// The transfer direction ( / ). - /// The HTTP method of the request. - /// The request URI; only its host and path are recorded. - /// The number of bytes transferred, or null if it could not be determined. - /// The HTTP response status code, or null if the request never got one. - /// The error classification, or null on success. - /// The value captured before the request. - internal static void RecordTransfer(string direction, HttpMethod method, Uri uri, long? bytes, int? statusCode, string? errorType, long startTimestamp) - { - if (!TransferDuration.Enabled && !TransferSize.Enabled) - return; + /// + /// Starts a client span for a Storage HTTP request, tagged per OpenTelemetry HTTP + /// conventions with the sanitized (query-less) URL. Returns null when nothing is listening. + /// + /// The HTTP method of the request. + /// The request URI, sanitized before tagging. + /// The transfer direction, or null for control-plane requests. + internal static Activity? StartHttpActivity(HttpMethod method, Uri uri, string? direction = null) + { + var activity = Source.StartActivity($"{method.Method} {uri.AbsolutePath}", ActivityKind.Client) + .SetHttpRequestTags(method.Method, uri); - var tags = BaseTags(method.Method, uri, statusCode, errorType); - tags.Add(DirectionTag, direction); + if (direction != null) + activity?.SetTag(DirectionTag, direction); - TransferDuration.Record(GetElapsedSeconds(startTimestamp), tags); + return activity; + } - if (bytes.HasValue) - TransferSize.Record(bytes.Value, tags); - } + /// + /// Records the control-plane request duration histogram for an HTTP request outcome. + /// + /// The HTTP method of the request. + /// The request URI; only its scheme, host and port are recorded. + /// The HTTP response status code, or null if the request never got one. + /// The error classification, or null on success. + /// The value captured before the request. + internal static void RecordRequest(HttpMethod method, Uri uri, int? statusCode, string? errorType, long startTimestamp) + { + if (RequestDuration.Enabled) + RequestDuration.Record(startTimestamp, HttpClientRequestDuration.TagsOf(method, uri, statusCode, errorType)); + } - private static TagList BaseTags(string method, Uri uri, int? statusCode, string? errorType) - { - var tags = new TagList - { - { "http.request.method", method }, - { "server.address", uri.Host }, - { "url.path", uri.AbsolutePath } - }; + /// + /// Records the transfer duration and (when known) size histograms for an upload/download outcome. + /// + /// The transfer direction ( / ). + /// The HTTP method of the request. + /// The request URI; only its host and path are recorded. + /// The number of bytes transferred, or null if it could not be determined. + /// The HTTP response status code, or null if the request never got one. + /// The error classification, or null on success. + /// The value captured before the request. + internal static void RecordTransfer(string direction, HttpMethod method, Uri uri, long? bytes, int? statusCode, string? errorType, long startTimestamp) + { + if (!TransferDuration.Enabled && !TransferSize.Enabled) + return; - if (statusCode.HasValue) - tags.Add("http.response.status_code", statusCode.Value); + var tags = TransferTags(direction, method.Method, uri, statusCode, errorType); + TransferDuration.Record(Instrumentation.SecondsSince(startTimestamp), tags); + + if (bytes.HasValue) + TransferSize.Record(bytes.Value, tags); + } + + private static TagList TransferTags(string direction, string method, Uri uri, int? statusCode, string? errorType) + { + var tags = new TagList + { + { "http.request.method", method }, + { "server.address", uri.Host }, + { "url.path", uri.AbsolutePath }, + { DirectionTag, direction } + }; - if (errorType != null) - tags.Add("error.type", errorType); + if (statusCode.HasValue) + tags.Add("http.response.status_code", statusCode.Value); - return tags; - } + if (errorType != null) + tags.Add("error.type", errorType); - private static double GetElapsedSeconds(long startTimestamp) => - (Stopwatch.GetTimestamp() - startTimestamp) / (double)Stopwatch.Frequency; + return tags; } } diff --git a/packages/Supabase/Supabase.Tests/Observability/DiagnosticLoggingWiringTests.cs b/packages/Supabase/Supabase.Tests/Observability/DiagnosticLoggingWiringTests.cs index 83fa8883e..524d40e12 100644 --- a/packages/Supabase/Supabase.Tests/Observability/DiagnosticLoggingWiringTests.cs +++ b/packages/Supabase/Supabase.Tests/Observability/DiagnosticLoggingWiringTests.cs @@ -36,7 +36,7 @@ public void Client_ShouldHandEachSubClientALoggerOfItsOwnCategory_GivenALoggerFa factory.Received(1).CreateLogger("supabase.gotrue"); factory.Received(1).CreateLogger("supabase.postgrest"); factory.Received(1).CreateLogger("supabase.functions"); - factory.Received(1).CreateLogger("Supabase.Realtime"); + factory.Received(1).CreateLogger("supabase.realtime"); factory.Received(1).CreateLogger("supabase.storage"); } } diff --git a/packages/Supabase/Supabase.Tests/Observability/SupabaseDiagnosticsTests.cs b/packages/Supabase/Supabase.Tests/Observability/SupabaseDiagnosticsTests.cs new file mode 100644 index 000000000..57ed9e097 --- /dev/null +++ b/packages/Supabase/Supabase.Tests/Observability/SupabaseDiagnosticsTests.cs @@ -0,0 +1,19 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Supabase.Tests.Observability; + +/// +/// lists the source and meter name of every instrumented client, so one +/// registration covers them all. +/// +[TestClass] +[TestCategory("Unit")] +public class SupabaseDiagnosticsTests +{ + [TestMethod] + public void SourceNames_ShouldListEveryInstrumentedClient() => + SupabaseDiagnostics.SourceNames.Should().BeEquivalentTo( + new[] { "supabase.gotrue", "supabase.postgrest", "supabase.functions", "supabase.storage" }, + "Auth, Database, Functions and Storage each emit under their own lowercase name, and Realtime emits no spans or metrics"); +} diff --git a/packages/Supabase/Supabase/Client.cs b/packages/Supabase/Supabase/Client.cs index 572afead4..572e03c06 100644 --- a/packages/Supabase/Supabase/Client.cs +++ b/packages/Supabase/Supabase/Client.cs @@ -221,7 +221,7 @@ public Client(string supabaseUrl, string? supabaseKey, SupabaseOptions? options Parameters = { ApiKey = this.supabaseKey }, PostgrestClient = this.postgrest, WebSocketFactory = this.options.WebSocketFactory, - Logger = this.options.LoggerFor(SupabaseOptions.RealtimeLoggerCategory), + Logger = this.options.LoggerFor(Supabase.Realtime.RealtimeLogging.Category), TimeProvider = this.options.TimeProvider, RetrieveAccessToken = ThirdPartyAuthorization.RealtimeAccessToken(thirdPartyAccessToken, this.supabaseKey) }; diff --git a/packages/Supabase/Supabase/SupabaseDiagnostics.cs b/packages/Supabase/Supabase/SupabaseDiagnostics.cs index 8510b10ba..25d5247f3 100644 --- a/packages/Supabase/Supabase/SupabaseDiagnostics.cs +++ b/packages/Supabase/Supabase/SupabaseDiagnostics.cs @@ -4,30 +4,29 @@ using Supabase.Postgrest; using Supabase.Storage; -namespace Supabase +namespace Supabase; + +/// +/// Aggregates the diagnostic source names emitted by the Supabase clients so consumers of the +/// meta-package can register them all with OpenTelemetry in one place, without importing each +/// sub-package's namespace or repeating the names as string literals. +/// +/// Each client uses the same name for its and +/// its , so works for +/// both TracerProviderBuilder.AddSource(...) and MeterProviderBuilder.AddMeter(...). +/// Realtime is not yet instrumented and is therefore not included. +/// +public static class SupabaseDiagnostics { /// - /// Aggregates the diagnostic source names emitted by the Supabase clients so consumers of the - /// meta-package can register them all with OpenTelemetry in one place, without importing each - /// sub-package's namespace or hardcoding (case-sensitive) source names. - /// - /// Each client uses the same name for its and - /// its , so works for - /// both TracerProviderBuilder.AddSource(...) and MeterProviderBuilder.AddMeter(...). - /// Realtime is not yet instrumented and is therefore not included. + /// The names of every and + /// emitted by the Supabase clients. /// - public static class SupabaseDiagnostics + public static IReadOnlyList SourceNames { get; } = new[] { - /// - /// The names of every and - /// emitted by the Supabase clients. - /// - public static IReadOnlyList SourceNames { get; } = new[] - { - GotrueDiagnostics.SourceName, - PostgrestDiagnostics.SourceName, - FunctionsDiagnostics.SourceName, - StorageDiagnostics.SourceName, - }; - } + GotrueDiagnostics.SourceName, + PostgrestDiagnostics.SourceName, + FunctionsDiagnostics.SourceName, + StorageDiagnostics.SourceName, + }; } diff --git a/packages/Supabase/Supabase/SupabaseOptions.cs b/packages/Supabase/Supabase/SupabaseOptions.cs index 8949cab8c..65e47f7b1 100644 --- a/packages/Supabase/Supabase/SupabaseOptions.cs +++ b/packages/Supabase/Supabase/SupabaseOptions.cs @@ -193,7 +193,7 @@ public class SupabaseOptions /// Receives the diagnostics of every sub-client: request outcomes with timing and retry decisions at /// Debug, and failures of background work (token refresh, session persistence, Realtime reconnection) at /// Warning. Each sub-client logs under its own category (supabase.gotrue, supabase.postgrest, - /// supabase.storage, supabase.functions, Supabase.Realtime). Left null, the SDK logs nothing. + /// supabase.storage, supabase.functions, supabase.realtime). Left null, the SDK logs nothing. /// /// /// Credentials, tokens, request and response bodies, query strings and header values are never logged. A logger that @@ -207,8 +207,6 @@ public class SupabaseOptions [ImplementedCapability("client.observability.diagnostic_logging")] public Microsoft.Extensions.Logging.ILoggerFactory? LoggerFactory { get; set; } - internal const string RealtimeLoggerCategory = "Supabase.Realtime"; - internal Microsoft.Extensions.Logging.ILogger? LoggerFor(string category) => this.LoggerFactory?.CreateLogger(category); ///