| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Diagnostics.Metrics; |
| | | 3 | | using System.Runtime.CompilerServices; |
| | | 4 | | |
| | | 5 | | namespace NGql.Core.Observability; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Centralized telemetry provider for NGql using .NET's built-in observability primitives. |
| | | 9 | | /// Provides OpenTelemetry-compatible traces and metrics using only BCL components (zero dependencies). |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class NGqlTelemetry |
| | | 12 | | { |
| | | 13 | | // OpenTelemetry-standard naming convention: {company}.{product} |
| | | 14 | | private const string ActivitySourceName = "NGql.Core"; |
| | | 15 | | private const string MeterName = "NGql.Core"; |
| | | 16 | | private const string Version = "1.0.0"; // Should match assembly version |
| | | 17 | | |
| | | 18 | | // Activity source for distributed tracing (OpenTelemetry-compatible) |
| | 3 | 19 | | private static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version); |
| | | 20 | | |
| | | 21 | | // Meter for metrics collection (OpenTelemetry-compatible) |
| | 3 | 22 | | private static readonly Meter Meter = new(MeterName, Version); |
| | | 23 | | |
| | | 24 | | #region Traces (Activities) |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Starts a new activity for query building operations |
| | | 28 | | /// </summary> |
| | | 29 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 30 | | internal static Activity? StartQueryBuildingActivity(string operationName) |
| | | 31 | | { |
| | 279 | 32 | | return ActivitySource.StartActivity($"ngql.query.{operationName}"); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Starts a new activity for field operations |
| | | 37 | | /// </summary> |
| | | 38 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 39 | | internal static Activity? StartFieldActivity(string operationName) |
| | | 40 | | { |
| | 36 | 41 | | return ActivitySource.StartActivity($"ngql.field.{operationName}"); |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Starts a new activity for pooling operations |
| | | 46 | | /// </summary> |
| | | 47 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 48 | | internal static Activity? StartPoolingActivity(string poolType, string operation) |
| | | 49 | | { |
| | 10695 | 50 | | return ActivitySource.StartActivity($"ngql.pool.{poolType}.{operation}"); |
| | | 51 | | } |
| | | 52 | | |
| | | 53 | | /// <summary> |
| | | 54 | | /// Adds standard tags to an activity for query operations |
| | | 55 | | /// </summary> |
| | | 56 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 57 | | internal static void TagQueryActivity(Activity? activity, string? queryName, int fieldCount) |
| | | 58 | | { |
| | 81 | 59 | | if (activity == null) return; |
| | | 60 | | |
| | 3 | 61 | | activity.SetTag("ngql.query.name", queryName); |
| | 3 | 62 | | activity.SetTag("ngql.query.field_count", fieldCount); |
| | 3 | 63 | | activity.SetTag("ngql.operation.type", "query_building"); |
| | 3 | 64 | | } |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// Adds standard tags to an activity for field operations |
| | | 68 | | /// </summary> |
| | | 69 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 70 | | internal static void TagFieldActivity(Activity? activity, string fieldPath, bool hasArguments, bool hasMetadata) |
| | | 71 | | { |
| | 81 | 72 | | if (activity == null) return; |
| | | 73 | | |
| | 3 | 74 | | activity.SetTag("ngql.field.path", fieldPath); |
| | 3 | 75 | | activity.SetTag("ngql.field.has_arguments", hasArguments); |
| | 3 | 76 | | activity.SetTag("ngql.field.has_metadata", hasMetadata); |
| | 3 | 77 | | activity.SetTag("ngql.operation.type", "field_building"); |
| | 3 | 78 | | } |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Adds standard tags to an activity for pooling operations |
| | | 82 | | /// </summary> |
| | | 83 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 84 | | internal static void TagPoolingActivity(Activity? activity, string poolType, string cacheHit, int poolSize) |
| | | 85 | | { |
| | 21369 | 86 | | if (activity == null) return; |
| | | 87 | | |
| | 3 | 88 | | activity.SetTag("ngql.pool.type", poolType); |
| | 3 | 89 | | activity.SetTag("ngql.pool.cache_hit", cacheHit); |
| | 3 | 90 | | activity.SetTag("ngql.pool.size", poolSize); |
| | 3 | 91 | | activity.SetTag("ngql.operation.type", "pooling"); |
| | 3 | 92 | | } |
| | | 93 | | |
| | | 94 | | #endregion |
| | | 95 | | |
| | | 96 | | #region Metrics |
| | | 97 | | |
| | | 98 | | // Counters (monotonic increasing values) |
| | 3 | 99 | | private static readonly Counter<long> QueryBuiltCounter = Meter.CreateCounter<long>( |
| | 3 | 100 | | "ngql_queries_built_total", |
| | 3 | 101 | | description: "Total number of GraphQL queries built"); |
| | | 102 | | |
| | 3 | 103 | | private static readonly Counter<long> FieldsAddedCounter = Meter.CreateCounter<long>( |
| | 3 | 104 | | "ngql_fields_added_total", |
| | 3 | 105 | | description: "Total number of fields added to queries"); |
| | | 106 | | |
| | 3 | 107 | | private static readonly Counter<long> PoolOperationsCounter = Meter.CreateCounter<long>( |
| | 3 | 108 | | "ngql_pool_operations_total", |
| | 3 | 109 | | description: "Total number of pooling operations"); |
| | | 110 | | |
| | | 111 | | // Histograms (value distributions) |
| | 3 | 112 | | private static readonly Histogram<double> QueryBuildDuration = Meter.CreateHistogram<double>( |
| | 3 | 113 | | "ngql_query_build_duration_seconds", |
| | 3 | 114 | | unit: "s", |
| | 3 | 115 | | description: "Duration of query building operations"); |
| | | 116 | | |
| | 3 | 117 | | private static readonly Histogram<double> SerializationDuration = Meter.CreateHistogram<double>( |
| | 3 | 118 | | "ngql_serialization_duration_seconds", |
| | 3 | 119 | | unit: "s", |
| | 3 | 120 | | description: "Duration of query serialization to string"); |
| | | 121 | | |
| | 3 | 122 | | private static readonly Histogram<long> QueryFieldCount = Meter.CreateHistogram<long>( |
| | 3 | 123 | | "ngql_query_field_count", |
| | 3 | 124 | | description: "Number of fields in built queries"); |
| | | 125 | | |
| | | 126 | | #if NET7_0_OR_GREATER |
| | | 127 | | // UpDownCounters (can increase or decrease) - Available in .NET 7+ |
| | 3 | 128 | | private static readonly UpDownCounter<long> ActiveQueriesGauge = Meter.CreateUpDownCounter<long>( |
| | 3 | 129 | | "ngql_active_queries", |
| | 3 | 130 | | description: "Number of queries currently being built"); |
| | | 131 | | |
| | 3 | 132 | | private static readonly UpDownCounter<long> PoolSizeGauge = Meter.CreateUpDownCounter<long>( |
| | 3 | 133 | | "ngql_pool_size", |
| | 3 | 134 | | description: "Current size of object pools"); |
| | | 135 | | #else |
| | | 136 | | // For .NET 6, we'll use regular counters and manage state manually |
| | | 137 | | private static readonly Counter<long> ActiveQueriesChangeCounter = Meter.CreateCounter<long>( |
| | | 138 | | "ngql_active_queries_changes_total", |
| | | 139 | | description: "Total changes to active query count"); |
| | | 140 | | |
| | | 141 | | private static readonly Counter<long> PoolSizeChangeCounter = Meter.CreateCounter<long>( |
| | | 142 | | "ngql_pool_size_changes_total", |
| | | 143 | | description: "Total changes to pool sizes"); |
| | | 144 | | |
| | | 145 | | // Manual state tracking for .NET 6 compatibility |
| | | 146 | | private static long _currentActiveQueries = 0; |
| | | 147 | | #endif |
| | | 148 | | |
| | | 149 | | #region Metric Recording Methods |
| | | 150 | | |
| | | 151 | | /// <summary> |
| | | 152 | | /// Records a query built event with contextual tags |
| | | 153 | | /// </summary> |
| | | 154 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 155 | | internal static void RecordQueryBuilt(string? queryName, int fieldCount, double durationSeconds) |
| | | 156 | | { |
| | 96 | 157 | | var tags = new TagList |
| | 96 | 158 | | { |
| | 96 | 159 | | { "query.name", queryName }, |
| | 96 | 160 | | { "operation", "build" } |
| | 96 | 161 | | }; |
| | | 162 | | |
| | 96 | 163 | | QueryBuiltCounter.Add(1, tags); |
| | 96 | 164 | | QueryBuildDuration.Record(durationSeconds, tags); |
| | 96 | 165 | | QueryFieldCount.Record(fieldCount, tags); |
| | 96 | 166 | | } |
| | | 167 | | |
| | | 168 | | /// <summary> |
| | | 169 | | /// Records a field added event |
| | | 170 | | /// </summary> |
| | | 171 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 172 | | internal static void RecordFieldAdded(string fieldPath, bool hasArguments, bool hasMetadata) |
| | | 173 | | { |
| | 78 | 174 | | var tags = new TagList |
| | 78 | 175 | | { |
| | 78 | 176 | | { "field.has_arguments", hasArguments }, |
| | 78 | 177 | | { "field.has_metadata", hasMetadata }, |
| | 78 | 178 | | { "field.is_nested", fieldPath.Contains('.') } |
| | 78 | 179 | | }; |
| | | 180 | | |
| | 78 | 181 | | FieldsAddedCounter.Add(1, tags); |
| | 78 | 182 | | } |
| | | 183 | | |
| | | 184 | | /// <summary> |
| | | 185 | | /// Records query serialization metrics |
| | | 186 | | /// </summary> |
| | | 187 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 188 | | internal static void RecordSerialization(double durationSeconds, int outputLength) |
| | | 189 | | { |
| | 42 | 190 | | var tags = new TagList |
| | 42 | 191 | | { |
| | 42 | 192 | | { "operation", "serialize" }, |
| | 42 | 193 | | { "output.size_category", GetSizeCategory(outputLength) } |
| | 42 | 194 | | }; |
| | | 195 | | |
| | 42 | 196 | | SerializationDuration.Record(durationSeconds, tags); |
| | 42 | 197 | | } |
| | | 198 | | |
| | | 199 | | /// <summary> |
| | | 200 | | /// Records pool operation metrics |
| | | 201 | | /// </summary> |
| | | 202 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 203 | | internal static void RecordPoolOperation(string poolType, string operation, string cacheLevel, int poolSize) |
| | | 204 | | { |
| | 10668 | 205 | | var tags = new TagList |
| | 10668 | 206 | | { |
| | 10668 | 207 | | { "pool.type", poolType }, |
| | 10668 | 208 | | { "pool.operation", operation }, |
| | 10668 | 209 | | { "pool.cache_level", cacheLevel } |
| | 10668 | 210 | | }; |
| | | 211 | | |
| | 10668 | 212 | | PoolOperationsCounter.Add(1, tags); |
| | | 213 | | |
| | | 214 | | #if NET7_0_OR_GREATER |
| | 10668 | 215 | | PoolSizeGauge.Add(poolSize, new TagList { { "pool.type", poolType } }); |
| | | 216 | | #else |
| | | 217 | | // For .NET 6, record as counter change |
| | | 218 | | PoolSizeChangeCounter.Add(Math.Abs(poolSize), new TagList { { "pool.type", poolType } }); |
| | | 219 | | #endif |
| | 10668 | 220 | | } |
| | | 221 | | |
| | | 222 | | /// <summary> |
| | | 223 | | /// Records active query count changes |
| | | 224 | | /// </summary> |
| | | 225 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 226 | | internal static void RecordActiveQueryChange(int delta) |
| | | 227 | | { |
| | | 228 | | #if NET7_0_OR_GREATER |
| | 45 | 229 | | ActiveQueriesGauge.Add(delta); |
| | | 230 | | #else |
| | | 231 | | // For .NET 6, track manually and record as counter changes |
| | | 232 | | var newCount = Interlocked.Add(ref _currentActiveQueries, delta); |
| | | 233 | | ActiveQueriesChangeCounter.Add(Math.Abs(delta), new TagList { { "operation", "active_query_change" } }); |
| | | 234 | | |
| | | 235 | | // Optionally record the current value in activities for observability |
| | | 236 | | using var activity = ActivitySource.StartActivity("ngql.metrics.active_queries"); |
| | | 237 | | activity?.SetTag("current_count", newCount); |
| | | 238 | | activity?.SetTag("delta", delta); |
| | | 239 | | #endif |
| | 45 | 240 | | } |
| | | 241 | | |
| | | 242 | | #endregion |
| | | 243 | | |
| | | 244 | | #endregion |
| | | 245 | | |
| | | 246 | | #region Utility Methods |
| | | 247 | | |
| | | 248 | | /// <summary> |
| | | 249 | | /// Categorizes output size for better metric cardinality control |
| | | 250 | | /// </summary> |
| | | 251 | | private static string GetSizeCategory(int size) |
| | | 252 | | { |
| | 42 | 253 | | return size switch |
| | 42 | 254 | | { |
| | 15 | 255 | | < 1024 => "small", // < 1KB |
| | 15 | 256 | | < 10240 => "medium", // < 10KB |
| | 6 | 257 | | < 102400 => "large", // < 100KB |
| | 6 | 258 | | _ => "very_large" // >= 100KB |
| | 42 | 259 | | }; |
| | | 260 | | } |
| | | 261 | | |
| | | 262 | | /// <summary> |
| | | 263 | | /// Creates a scoped measurement for timing operations |
| | | 264 | | /// </summary> |
| | | 265 | | internal static IDisposable CreateTimedScope(string operationName, TagList tags) |
| | | 266 | | { |
| | 12 | 267 | | return new TimedScope(operationName, tags); |
| | | 268 | | } |
| | | 269 | | |
| | | 270 | | #endregion |
| | | 271 | | |
| | | 272 | | #region Timed Scope Helper |
| | | 273 | | |
| | | 274 | | /// <summary> |
| | | 275 | | /// RAII helper for automatic timing measurements |
| | | 276 | | /// </summary> |
| | | 277 | | private readonly struct TimedScope : IDisposable |
| | | 278 | | { |
| | | 279 | | private readonly string _operationName; |
| | | 280 | | private readonly TagList _tags; |
| | | 281 | | private readonly long _startTicks; |
| | | 282 | | |
| | | 283 | | public TimedScope(string operationName, TagList tags) |
| | | 284 | | { |
| | 12 | 285 | | _operationName = operationName; |
| | 12 | 286 | | _tags = tags; |
| | 12 | 287 | | _startTicks = Stopwatch.GetTimestamp(); |
| | 12 | 288 | | } |
| | | 289 | | |
| | | 290 | | public void Dispose() |
| | | 291 | | { |
| | 12 | 292 | | var elapsed = GetElapsedSeconds(_startTicks); |
| | | 293 | | |
| | | 294 | | // Record to appropriate histogram based on operation |
| | 12 | 295 | | if (_operationName.Contains("serialize")) |
| | | 296 | | { |
| | 3 | 297 | | SerializationDuration.Record(elapsed, _tags); |
| | | 298 | | } |
| | | 299 | | else |
| | | 300 | | { |
| | 9 | 301 | | QueryBuildDuration.Record(elapsed, _tags); |
| | | 302 | | } |
| | | 303 | | |
| | | 304 | | |
| | | 305 | | // <summary> |
| | | 306 | | // Gets elapsed seconds since the given timestamp (cross-.NET version compatible) |
| | | 307 | | // </summary> |
| | | 308 | | static double GetElapsedSeconds(long startTimestamp) |
| | | 309 | | { |
| | | 310 | | #if NET7_0_OR_GREATER |
| | 12 | 311 | | return Stopwatch.GetElapsedTime(startTimestamp).TotalSeconds; |
| | | 312 | | #else |
| | | 313 | | var elapsed = Stopwatch.GetTimestamp() - startTimestamp; |
| | | 314 | | return (double)elapsed / Stopwatch.Frequency; |
| | | 315 | | #endif |
| | | 316 | | } |
| | 9 | 317 | | } |
| | | 318 | | } |
| | | 319 | | |
| | | 320 | | #endregion |
| | | 321 | | |
| | | 322 | | } |