using System.Collections.Concurrent;
using System.Data;
using System.Diagnostics;
using System.Text.Json;
using Microsoft.Data.SqlClient;
namespace PlotLine.Data;
/// Opt-in, value-free SqlClient timings. Reader timings end at ExecuteReader, not final consumption.
public sealed class DevelopmentSqlDiagnostics(IHostEnvironment environment, IConfiguration configuration,
ILogger logger) : IHostedService, IObserver, IObserver>
{
private readonly ConcurrentDictionary pending = new();
private readonly List subscriptions = [];
private readonly AsyncLocal current = new();
private IDisposable? allListeners;
private int records;
private readonly long captureStarted = Stopwatch.GetTimestamp();
private bool CaptureActive => Enabled && records < 50000 && Stopwatch.GetElapsedTime(captureStarted) < TimeSpan.FromMinutes(30);
public bool Enabled => environment.IsDevelopment() && configuration.GetValue("SqlDiagnostics:Enabled");
private sealed record Pending(long Start, string Procedure, Frame? Frame, string Correlation, string Operation);
public sealed class Frame(string correlation)
{
public string Correlation { get; } = correlation;
public int Count;
public double SqlMilliseconds;
public int Errors;
public readonly Dictionary Procedures = new(StringComparer.Ordinal);
}
public Task StartAsync(CancellationToken cancellationToken)
{
if (Enabled) allListeners = DiagnosticListener.AllListeners.Subscribe(this);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
allListeners?.Dispose();
lock (subscriptions) foreach (var subscription in subscriptions) subscription.Dispose();
pending.Clear();
return Task.CompletedTask;
}
public Frame BeginRequest(string correlation) => current.Value = new Frame(correlation);
public void EndRequest(Frame frame, string route, double elapsed, int status, string outcome = "complete")
{
current.Value = null;
if (!CaptureActive) return;
Interlocked.Increment(ref records);
lock (frame)
logger.LogInformation("SQL_REQUEST {Summary}", JsonSerializer.Serialize(new { frame.Correlation, Route = route,
DurationMs = elapsed, Status = status, Outcome = outcome, Commands = frame.Count, SqlMs = frame.SqlMilliseconds,
frame.Errors, Procedures = frame.Procedures }));
}
public void OnNext(DiagnosticListener listener)
{
if (listener.Name == "SqlClientDiagnosticListener")
lock (subscriptions) subscriptions.Add(listener.Subscribe(this, name => CaptureActive && name.StartsWith("Microsoft.Data.SqlClient.WriteCommand", StringComparison.Ordinal)));
}
public void OnNext(KeyValuePair item)
{
// Diagnostics must never change application behaviour or emit exception/SQL parameter contents.
try
{
var value = item.Value;
if (value is null) return;
var type = value.GetType();
if (type.GetProperty("OperationId")?.GetValue(value) is not Guid id) return;
if (item.Key.EndsWith("Before", StringComparison.Ordinal))
{
if (!CaptureActive || pending.Count >= 2048) return;
var command = type.GetProperty("Command")?.GetValue(value) as SqlCommand;
var procedure = command?.CommandType == CommandType.StoredProcedure ? command.CommandText : "[text omitted]";
// Only retain identifiers, never dynamically constructed text, arguments or connection metadata.
if (procedure.Length > 160 || procedure.Any(c => !char.IsLetterOrDigit(c) && c is not '_' and not '.' and not '[' and not ']' and not ' ')) procedure = "[identifier omitted]";
var frame = current.Value;
pending.TryAdd(id, new(Stopwatch.GetTimestamp(), procedure, frame,
frame?.Correlation ?? Activity.Current?.TraceId.ToString() ?? id.ToString("N"),
frame is null && Activity.Current?.OperationName == "StoryIntelligence.Poll" ? "StoryIntelligence.Poll" : frame is null ? "background" : "http"));
return;
}
if (!pending.TryRemove(id, out var start)) return;
var ms = Stopwatch.GetElapsedTime(start.Start).TotalMilliseconds;
var error = item.Key.EndsWith("Error", StringComparison.Ordinal);
var exception = type.GetProperty("Exception")?.GetValue(value) as Exception;
var outcome = !error ? "ok" : exception is OperationCanceledException ? "cancelled" : exception is SqlException { Number: -2 } ? "timeout" : "error";
if (start.Frame is { } frameResult)
lock (frameResult)
{
frameResult.Count++; frameResult.SqlMilliseconds += ms;
if (error) frameResult.Errors++;
if (frameResult.Procedures.Count < 128 || frameResult.Procedures.ContainsKey(start.Procedure))
frameResult.Procedures[start.Procedure] = frameResult.Procedures.GetValueOrDefault(start.Procedure) + 1;
}
if (!CaptureActive) return;
Interlocked.Increment(ref records);
logger.LogInformation("SQL_COMMAND {Summary}", JsonSerializer.Serialize(new { start.Correlation,
start.Procedure, start.Operation, DurationMs = ms, Outcome = outcome, ErrorNumber = (exception as SqlException)?.Number, Background = start.Frame is null }));
}
catch { /* Observability must not break data access. */ }
}
public void OnCompleted() { }
public void OnError(Exception error) { }
}