NEXJAST: add production OTLP observability pipeline
This commit is contained in:
1 parent
b50a2959a7
commit
ef98ab2b0b
11 files changed
+1472
-23
No files matched your search
@@ -109,7 +109,7 @@ jobs:
|
||||
shell: bash
|
||||
run: dotnet run --configuration Release --project tools/ci/NexBusRegression/NexBusRegression.csproj
|
||||
|
||||
- name: Verify NexMetrics foundation
|
||||
- name: Verify NexMetrics OTLP pipeline
|
||||
shell: bash
|
||||
run: dotnet run --configuration Release --project tools/ci/NexMetricsRegression/NexMetricsRegression.csproj
|
||||
|
||||
|
||||
@@ -15,6 +15,43 @@ namespace NexVerse.Core.Observability
|
||||
Gauge
|
||||
}
|
||||
|
||||
public sealed class NexMetricSampleSnapshot
|
||||
{
|
||||
public IReadOnlyDictionary<string, string> Labels { get; }
|
||||
public double Value { get; }
|
||||
|
||||
public NexMetricSampleSnapshot(
|
||||
IReadOnlyDictionary<string, string> labels,
|
||||
double value)
|
||||
{
|
||||
Labels = labels ??
|
||||
new Dictionary<string, string>(
|
||||
StringComparer.Ordinal);
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class NexMetricSnapshot
|
||||
{
|
||||
public string Name { get; }
|
||||
public string Help { get; }
|
||||
public NexMetricType Type { get; }
|
||||
public IReadOnlyList<NexMetricSampleSnapshot> Samples { get; }
|
||||
|
||||
public NexMetricSnapshot(
|
||||
string name,
|
||||
string help,
|
||||
NexMetricType type,
|
||||
IReadOnlyList<NexMetricSampleSnapshot> samples)
|
||||
{
|
||||
Name = name ?? string.Empty;
|
||||
Help = help ?? string.Empty;
|
||||
Type = type;
|
||||
Samples = samples ??
|
||||
Array.Empty<NexMetricSampleSnapshot>();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class NexMetricsRegistry
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, MetricFamily> m_Families =
|
||||
@@ -48,6 +85,29 @@ namespace NexVerse.Core.Observability
|
||||
family.GetSample(labels).Set(value);
|
||||
}
|
||||
|
||||
public IReadOnlyList<NexMetricSnapshot> Snapshot()
|
||||
{
|
||||
return m_Families.Values
|
||||
.OrderBy(x => x.Name, StringComparer.Ordinal)
|
||||
.Select(family =>
|
||||
new NexMetricSnapshot(
|
||||
family.Name,
|
||||
family.Help,
|
||||
family.Type,
|
||||
family.Samples
|
||||
.OrderBy(
|
||||
x => x.Key,
|
||||
StringComparer.Ordinal)
|
||||
.Select(sample =>
|
||||
new NexMetricSampleSnapshot(
|
||||
new Dictionary<string, string>(
|
||||
sample.Labels,
|
||||
StringComparer.Ordinal),
|
||||
sample.Value))
|
||||
.ToArray()))
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
public string RenderPrometheus()
|
||||
{
|
||||
StringBuilder output = new StringBuilder(4096);
|
||||
|
||||
@@ -0,0 +1,836 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using NexVerse.Core;
|
||||
using NexVerse.Core.Observability;
|
||||
|
||||
namespace NexVerse.Server.Api
|
||||
{
|
||||
internal sealed class NexOtlpHttpOptions
|
||||
{
|
||||
public Uri Endpoint { get; set; }
|
||||
public Uri TracesEndpoint { get; set; }
|
||||
public Uri MetricsEndpoint { get; set; }
|
||||
public string ServiceName { get; set; } = "NexVerse.Robust";
|
||||
public string ServiceInstanceId { get; set; } = Environment.MachineName;
|
||||
public IReadOnlyDictionary<string, string> Headers { get; set; } =
|
||||
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
public int ExportIntervalSeconds { get; set; } = 10;
|
||||
public int BatchSize { get; set; } = 256;
|
||||
public int QueueCapacity { get; set; } = 4096;
|
||||
public int TimeoutMilliseconds { get; set; } = 10000;
|
||||
public int MaxRetries { get; set; } = 3;
|
||||
public bool AllowInsecure { get; set; }
|
||||
public bool AutoStart { get; set; } = true;
|
||||
}
|
||||
|
||||
internal sealed class NexOtlpHttpExporter : IDisposable
|
||||
{
|
||||
private readonly NexMetricsRegistry m_Metrics;
|
||||
private readonly NexOtlpHttpOptions m_Options;
|
||||
private readonly Uri m_TracesEndpoint;
|
||||
private readonly Uri m_MetricsEndpoint;
|
||||
private readonly BlockingCollection<Dictionary<string, object>> m_Spans;
|
||||
private readonly CancellationTokenSource m_Stop = new CancellationTokenSource();
|
||||
private readonly HttpClient m_Client;
|
||||
private readonly ActivityListener m_Listener;
|
||||
private readonly Task m_Worker;
|
||||
private readonly object m_FlushSync = new object();
|
||||
private readonly long m_StartUnixNano;
|
||||
private int m_Disposed;
|
||||
|
||||
public NexOtlpHttpExporter(
|
||||
NexMetricsRegistry metrics,
|
||||
NexOtlpHttpOptions options,
|
||||
HttpMessageHandler handler = null)
|
||||
{
|
||||
m_Metrics = metrics ??
|
||||
throw new ArgumentNullException(nameof(metrics));
|
||||
m_Options = options ??
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
|
||||
ValidateOptions(options);
|
||||
|
||||
m_TracesEndpoint =
|
||||
ResolveEndpoint(
|
||||
options.TracesEndpoint,
|
||||
options.Endpoint,
|
||||
"v1/traces");
|
||||
m_MetricsEndpoint =
|
||||
ResolveEndpoint(
|
||||
options.MetricsEndpoint,
|
||||
options.Endpoint,
|
||||
"v1/metrics");
|
||||
|
||||
ValidateTransport(m_TracesEndpoint, options.AllowInsecure);
|
||||
ValidateTransport(m_MetricsEndpoint, options.AllowInsecure);
|
||||
|
||||
m_Spans =
|
||||
new BlockingCollection<Dictionary<string, object>>(
|
||||
new ConcurrentQueue<Dictionary<string, object>>(),
|
||||
Math.Max(128, options.QueueCapacity));
|
||||
|
||||
m_Client = handler == null
|
||||
? new HttpClient()
|
||||
: new HttpClient(handler, false);
|
||||
m_Client.Timeout =
|
||||
TimeSpan.FromMilliseconds(
|
||||
Math.Max(250, options.TimeoutMilliseconds));
|
||||
|
||||
m_StartUnixNano =
|
||||
UnixNanoseconds(DateTime.UtcNow);
|
||||
|
||||
m_Listener = new ActivityListener
|
||||
{
|
||||
ShouldListenTo =
|
||||
source =>
|
||||
string.Equals(
|
||||
source.Name,
|
||||
NexTelemetry.ActivitySourceName,
|
||||
StringComparison.Ordinal),
|
||||
Sample =
|
||||
(ref ActivityCreationOptions<ActivityContext> _) =>
|
||||
ActivitySamplingResult.AllDataAndRecorded,
|
||||
SampleUsingParentId =
|
||||
(ref ActivityCreationOptions<string> _) =>
|
||||
ActivitySamplingResult.AllDataAndRecorded,
|
||||
ActivityStopped = OnActivityStopped
|
||||
};
|
||||
|
||||
ActivitySource.AddActivityListener(m_Listener);
|
||||
|
||||
if (options.AutoStart)
|
||||
m_Worker = Task.Run(WorkerLoop);
|
||||
}
|
||||
|
||||
public void Flush()
|
||||
{
|
||||
if (Volatile.Read(ref m_Disposed) != 0)
|
||||
return;
|
||||
|
||||
lock (m_FlushSync)
|
||||
{
|
||||
ExportQueuedSpans();
|
||||
ExportMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref m_Disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
m_Listener.Dispose();
|
||||
m_Spans.CompleteAdding();
|
||||
m_Stop.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
m_Worker?.Wait(
|
||||
TimeSpan.FromMilliseconds(
|
||||
Math.Max(
|
||||
1000,
|
||||
m_Options.TimeoutMilliseconds + 1000)));
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
lock (m_FlushSync)
|
||||
{
|
||||
ExportQueuedSpans();
|
||||
ExportMetrics();
|
||||
}
|
||||
|
||||
m_Client.Dispose();
|
||||
m_Stop.Dispose();
|
||||
m_Spans.Dispose();
|
||||
}
|
||||
|
||||
private void OnActivityStopped(Activity activity)
|
||||
{
|
||||
if (activity == null ||
|
||||
Volatile.Read(ref m_Disposed) != 0)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
if (!m_Spans.TryAdd(BuildSpan(activity)))
|
||||
{
|
||||
m_Metrics.IncrementCounter(
|
||||
"nexverse_otlp_spans_dropped_total",
|
||||
"NexVerse trace spans dropped because the OTLP export queue is full.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
m_Metrics.SetGauge(
|
||||
"nexverse_otlp_queue_depth",
|
||||
"Current NexVerse OTLP trace export queue depth.",
|
||||
m_Spans.Count);
|
||||
}
|
||||
|
||||
private void WorkerLoop()
|
||||
{
|
||||
TimeSpan interval =
|
||||
TimeSpan.FromSeconds(
|
||||
Math.Max(1, m_Options.ExportIntervalSeconds));
|
||||
|
||||
try
|
||||
{
|
||||
while (!m_Stop.IsCancellationRequested)
|
||||
{
|
||||
if (m_Spans.Count >= Math.Max(1, m_Options.BatchSize))
|
||||
{
|
||||
lock (m_FlushSync)
|
||||
ExportQueuedSpans();
|
||||
}
|
||||
|
||||
if (m_Stop.Token.WaitHandle.WaitOne(interval))
|
||||
break;
|
||||
|
||||
lock (m_FlushSync)
|
||||
{
|
||||
ExportQueuedSpans();
|
||||
ExportMetrics();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
m_Metrics.IncrementCounter(
|
||||
"nexverse_otlp_worker_failures_total",
|
||||
"Unexpected NexVerse OTLP exporter worker failures.");
|
||||
}
|
||||
}
|
||||
|
||||
private void ExportQueuedSpans()
|
||||
{
|
||||
int batchSize = Math.Max(1, m_Options.BatchSize);
|
||||
|
||||
while (m_Spans.Count > 0)
|
||||
{
|
||||
List<Dictionary<string, object>> batch =
|
||||
new List<Dictionary<string, object>>(batchSize);
|
||||
|
||||
while (batch.Count < batchSize &&
|
||||
m_Spans.TryTake(out Dictionary<string, object> span))
|
||||
batch.Add(span);
|
||||
|
||||
if (batch.Count == 0)
|
||||
break;
|
||||
|
||||
m_Metrics.SetGauge(
|
||||
"nexverse_otlp_queue_depth",
|
||||
"Current NexVerse OTLP trace export queue depth.",
|
||||
m_Spans.Count);
|
||||
|
||||
Send(
|
||||
m_TracesEndpoint,
|
||||
JsonSerializer.SerializeToUtf8Bytes(
|
||||
BuildTracePayload(batch)),
|
||||
"traces",
|
||||
batch.Count);
|
||||
}
|
||||
}
|
||||
|
||||
private void ExportMetrics()
|
||||
{
|
||||
IReadOnlyList<NexMetricSnapshot> snapshots =
|
||||
m_Metrics.Snapshot();
|
||||
|
||||
if (snapshots.Count == 0)
|
||||
return;
|
||||
|
||||
long now = UnixNanoseconds(DateTime.UtcNow);
|
||||
List<object> metricPayloads =
|
||||
new List<object>(snapshots.Count);
|
||||
int dataPointCount = 0;
|
||||
|
||||
foreach (NexMetricSnapshot metric in snapshots)
|
||||
{
|
||||
object[] points =
|
||||
metric.Samples
|
||||
.Select(sample =>
|
||||
BuildMetricPoint(
|
||||
sample,
|
||||
now,
|
||||
metric.Type == NexMetricType.Counter))
|
||||
.ToArray();
|
||||
|
||||
dataPointCount += points.Length;
|
||||
|
||||
Dictionary<string, object> item =
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["name"] = metric.Name,
|
||||
["description"] = metric.Help
|
||||
};
|
||||
|
||||
if (metric.Type == NexMetricType.Counter)
|
||||
{
|
||||
item["sum"] =
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["aggregationTemporality"] = 2,
|
||||
["isMonotonic"] = true,
|
||||
["dataPoints"] = points
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
item["gauge"] =
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["dataPoints"] = points
|
||||
};
|
||||
}
|
||||
|
||||
metricPayloads.Add(item);
|
||||
}
|
||||
|
||||
object payload =
|
||||
new
|
||||
{
|
||||
resourceMetrics =
|
||||
new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
resource =
|
||||
new
|
||||
{
|
||||
attributes =
|
||||
ResourceAttributes()
|
||||
},
|
||||
scopeMetrics =
|
||||
new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
scope =
|
||||
InstrumentationScope(),
|
||||
metrics =
|
||||
metricPayloads
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Send(
|
||||
m_MetricsEndpoint,
|
||||
JsonSerializer.SerializeToUtf8Bytes(payload),
|
||||
"metrics",
|
||||
dataPointCount);
|
||||
}
|
||||
|
||||
private object BuildTracePayload(
|
||||
IReadOnlyList<Dictionary<string, object>> spans)
|
||||
{
|
||||
return new
|
||||
{
|
||||
resourceSpans =
|
||||
new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
resource =
|
||||
new
|
||||
{
|
||||
attributes =
|
||||
ResourceAttributes()
|
||||
},
|
||||
scopeSpans =
|
||||
new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
scope =
|
||||
InstrumentationScope(),
|
||||
spans
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static Dictionary<string, object> BuildSpan(
|
||||
Activity activity)
|
||||
{
|
||||
long start = UnixNanoseconds(activity.StartTimeUtc);
|
||||
long end =
|
||||
UnixNanoseconds(
|
||||
activity.StartTimeUtc +
|
||||
activity.Duration);
|
||||
|
||||
Dictionary<string, object> span =
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["traceId"] = activity.TraceId.ToHexString(),
|
||||
["spanId"] = activity.SpanId.ToHexString(),
|
||||
["name"] =
|
||||
activity.DisplayName ??
|
||||
activity.OperationName ??
|
||||
"nexverse.activity",
|
||||
["kind"] = (int)activity.Kind + 1,
|
||||
["startTimeUnixNano"] =
|
||||
start.ToString(
|
||||
CultureInfo.InvariantCulture),
|
||||
["endTimeUnixNano"] =
|
||||
end.ToString(
|
||||
CultureInfo.InvariantCulture),
|
||||
["attributes"] =
|
||||
Attributes(activity.TagObjects),
|
||||
["status"] = BuildStatus(activity)
|
||||
};
|
||||
|
||||
if (activity.ParentSpanId != default)
|
||||
span["parentSpanId"] =
|
||||
activity.ParentSpanId.ToHexString();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(activity.TraceStateString))
|
||||
span["traceState"] = activity.TraceStateString;
|
||||
|
||||
object[] events =
|
||||
activity.Events
|
||||
.Select(e =>
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["timeUnixNano"] =
|
||||
UnixNanoseconds(e.Timestamp.UtcDateTime)
|
||||
.ToString(
|
||||
CultureInfo.InvariantCulture),
|
||||
["name"] = e.Name,
|
||||
["attributes"] =
|
||||
Attributes(e.Tags)
|
||||
})
|
||||
.Cast<object>()
|
||||
.ToArray();
|
||||
|
||||
if (events.Length > 0)
|
||||
span["events"] = events;
|
||||
|
||||
return span;
|
||||
}
|
||||
|
||||
private object BuildMetricPoint(
|
||||
NexMetricSampleSnapshot sample,
|
||||
long timeUnixNano,
|
||||
bool cumulative)
|
||||
{
|
||||
Dictionary<string, object> point =
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["attributes"] =
|
||||
Attributes(
|
||||
sample.Labels.Select(
|
||||
x =>
|
||||
new KeyValuePair<string, object>(
|
||||
x.Key,
|
||||
x.Value))),
|
||||
["timeUnixNano"] =
|
||||
timeUnixNano.ToString(
|
||||
CultureInfo.InvariantCulture),
|
||||
["asDouble"] = sample.Value
|
||||
};
|
||||
|
||||
if (cumulative)
|
||||
{
|
||||
point["startTimeUnixNano"] =
|
||||
m_StartUnixNano.ToString(
|
||||
CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return point;
|
||||
}
|
||||
|
||||
private object[] ResourceAttributes()
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
KeyValue("service.name", m_Options.ServiceName),
|
||||
KeyValue("service.instance.id", m_Options.ServiceInstanceId),
|
||||
KeyValue("service.version", NexVersePlatform.ApiVersion),
|
||||
KeyValue("nexverse.milestone", NexVersePlatform.MilestoneCodename)
|
||||
};
|
||||
}
|
||||
|
||||
private static object InstrumentationScope()
|
||||
{
|
||||
return new
|
||||
{
|
||||
name = NexTelemetry.ActivitySourceName,
|
||||
version = NexVersePlatform.ApiVersion
|
||||
};
|
||||
}
|
||||
|
||||
private static object BuildStatus(Activity activity)
|
||||
{
|
||||
int code =
|
||||
activity.Status switch
|
||||
{
|
||||
ActivityStatusCode.Ok => 1,
|
||||
ActivityStatusCode.Error => 2,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
if (string.IsNullOrWhiteSpace(activity.StatusDescription))
|
||||
return new { code };
|
||||
|
||||
return new
|
||||
{
|
||||
code,
|
||||
message = activity.StatusDescription
|
||||
};
|
||||
}
|
||||
|
||||
private static object[] Attributes(
|
||||
IEnumerable<KeyValuePair<string, object>> values)
|
||||
{
|
||||
if (values == null)
|
||||
return Array.Empty<object>();
|
||||
|
||||
return values
|
||||
.Where(x =>
|
||||
!string.IsNullOrWhiteSpace(x.Key) &&
|
||||
x.Value != null)
|
||||
.Select(x => KeyValue(x.Key, x.Value))
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static object KeyValue(
|
||||
string key,
|
||||
object value)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["key"] = key ?? string.Empty,
|
||||
["value"] = AnyValue(value)
|
||||
};
|
||||
}
|
||||
|
||||
private static object AnyValue(object value)
|
||||
{
|
||||
if (value is bool boolean)
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["boolValue"] = boolean
|
||||
};
|
||||
|
||||
if (value is byte ||
|
||||
value is sbyte ||
|
||||
value is short ||
|
||||
value is ushort ||
|
||||
value is int ||
|
||||
value is uint ||
|
||||
value is long ||
|
||||
value is ulong)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["intValue"] =
|
||||
Convert.ToString(
|
||||
value,
|
||||
CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
|
||||
if (value is float ||
|
||||
value is double ||
|
||||
value is decimal)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["doubleValue"] =
|
||||
Convert.ToDouble(
|
||||
value,
|
||||
CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["stringValue"] =
|
||||
Convert.ToString(
|
||||
value,
|
||||
CultureInfo.InvariantCulture) ??
|
||||
string.Empty
|
||||
};
|
||||
}
|
||||
|
||||
private void Send(
|
||||
Uri endpoint,
|
||||
byte[] payload,
|
||||
string signal,
|
||||
int recordCount)
|
||||
{
|
||||
int maxAttempts =
|
||||
Math.Max(1, m_Options.MaxRetries + 1);
|
||||
|
||||
for (int attempt = 1;
|
||||
attempt <= maxAttempts;
|
||||
attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using HttpRequestMessage request =
|
||||
new HttpRequestMessage(
|
||||
HttpMethod.Post,
|
||||
endpoint);
|
||||
|
||||
request.Content =
|
||||
new ByteArrayContent(payload);
|
||||
request.Content.Headers.ContentType =
|
||||
new MediaTypeHeaderValue("application/json");
|
||||
|
||||
foreach (KeyValuePair<string, string> header
|
||||
in m_Options.Headers ??
|
||||
new Dictionary<string, string>())
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(header.Key))
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation(
|
||||
header.Key,
|
||||
header.Value ?? string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
using HttpResponseMessage response =
|
||||
m_Client.Send(
|
||||
request,
|
||||
HttpCompletionOption.ResponseHeadersRead);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
RecordExport(
|
||||
signal,
|
||||
"success",
|
||||
recordCount);
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsRetryable(response.StatusCode) &&
|
||||
attempt < maxAttempts)
|
||||
{
|
||||
RecordExport(
|
||||
signal,
|
||||
"retry",
|
||||
recordCount);
|
||||
SleepBeforeRetry(response, attempt);
|
||||
continue;
|
||||
}
|
||||
|
||||
RecordExport(
|
||||
signal,
|
||||
"failed",
|
||||
recordCount);
|
||||
return;
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
if (attempt < maxAttempts)
|
||||
{
|
||||
RecordExport(
|
||||
signal,
|
||||
"retry",
|
||||
recordCount);
|
||||
SleepBeforeRetry(null, attempt);
|
||||
continue;
|
||||
}
|
||||
|
||||
RecordExport(
|
||||
signal,
|
||||
"failed",
|
||||
recordCount);
|
||||
return;
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
if (attempt < maxAttempts)
|
||||
{
|
||||
RecordExport(
|
||||
signal,
|
||||
"retry",
|
||||
recordCount);
|
||||
SleepBeforeRetry(null, attempt);
|
||||
continue;
|
||||
}
|
||||
|
||||
RecordExport(
|
||||
signal,
|
||||
"failed",
|
||||
recordCount);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RecordExport(
|
||||
string signal,
|
||||
string result,
|
||||
int recordCount)
|
||||
{
|
||||
Dictionary<string, string> labels =
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["signal"] = signal,
|
||||
["result"] = result
|
||||
};
|
||||
|
||||
m_Metrics.IncrementCounter(
|
||||
"nexverse_otlp_export_requests_total",
|
||||
"NexVerse OTLP/HTTP export requests by signal and result.",
|
||||
1,
|
||||
labels);
|
||||
|
||||
m_Metrics.IncrementCounter(
|
||||
"nexverse_otlp_export_records_total",
|
||||
"NexVerse OTLP records included in export requests by signal and result.",
|
||||
Math.Max(0, recordCount),
|
||||
labels);
|
||||
}
|
||||
|
||||
private static bool IsRetryable(HttpStatusCode statusCode)
|
||||
{
|
||||
int code = (int)statusCode;
|
||||
return code == 408 ||
|
||||
code == 429 ||
|
||||
code == 502 ||
|
||||
code == 503 ||
|
||||
code == 504;
|
||||
}
|
||||
|
||||
private static void SleepBeforeRetry(
|
||||
HttpResponseMessage response,
|
||||
int attempt)
|
||||
{
|
||||
TimeSpan delay =
|
||||
TimeSpan.FromMilliseconds(
|
||||
Math.Min(
|
||||
5000,
|
||||
200 *
|
||||
(1 << Math.Min(
|
||||
4,
|
||||
Math.Max(0, attempt - 1))) +
|
||||
Random.Shared.Next(25, 176)));
|
||||
|
||||
if (response?.Headers?.RetryAfter?.Delta
|
||||
is TimeSpan retryAfter &&
|
||||
retryAfter > TimeSpan.Zero)
|
||||
{
|
||||
delay =
|
||||
retryAfter > TimeSpan.FromSeconds(30)
|
||||
? TimeSpan.FromSeconds(30)
|
||||
: retryAfter;
|
||||
}
|
||||
|
||||
Thread.Sleep(delay);
|
||||
}
|
||||
|
||||
private static Uri ResolveEndpoint(
|
||||
Uri specific,
|
||||
Uri common,
|
||||
string signalPath)
|
||||
{
|
||||
if (specific != null)
|
||||
return specific;
|
||||
|
||||
if (common == null)
|
||||
throw new ArgumentException(
|
||||
"An OTLP endpoint is required.");
|
||||
|
||||
string value = common.AbsoluteUri;
|
||||
if (!value.EndsWith("/", StringComparison.Ordinal))
|
||||
value += "/";
|
||||
|
||||
return new Uri(
|
||||
value + signalPath,
|
||||
UriKind.Absolute);
|
||||
}
|
||||
|
||||
private static void ValidateTransport(
|
||||
Uri endpoint,
|
||||
bool allowInsecure)
|
||||
{
|
||||
if (endpoint == null || !endpoint.IsAbsoluteUri)
|
||||
throw new ArgumentException(
|
||||
"OTLP endpoints must be absolute URLs.");
|
||||
|
||||
if (!string.Equals(
|
||||
endpoint.Scheme,
|
||||
Uri.UriSchemeHttp,
|
||||
StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(
|
||||
endpoint.Scheme,
|
||||
Uri.UriSchemeHttps,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"OTLP/HTTP endpoints must use http or https.");
|
||||
}
|
||||
|
||||
if (!allowInsecure &&
|
||||
string.Equals(
|
||||
endpoint.Scheme,
|
||||
Uri.UriSchemeHttp,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Plain HTTP OTLP export is disabled. Use HTTPS or set AllowInsecure=true only on a trusted private transport.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateOptions(
|
||||
NexOtlpHttpOptions options)
|
||||
{
|
||||
if (options.Endpoint == null &&
|
||||
options.TracesEndpoint == null &&
|
||||
options.MetricsEndpoint == null)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"At least one OTLP endpoint must be configured.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(options.ServiceName))
|
||||
throw new ArgumentException(
|
||||
"OTLP service name is required.");
|
||||
|
||||
if (options.ExportIntervalSeconds < 1 ||
|
||||
options.BatchSize < 1 ||
|
||||
options.QueueCapacity < 128 ||
|
||||
options.TimeoutMilliseconds < 250 ||
|
||||
options.MaxRetries < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(options),
|
||||
"OTLP timing, batching, queue and retry settings are outside supported bounds.");
|
||||
}
|
||||
}
|
||||
|
||||
private static long UnixNanoseconds(DateTime utc)
|
||||
{
|
||||
long ticks =
|
||||
utc.ToUniversalTime().Ticks -
|
||||
DateTime.UnixEpoch.Ticks;
|
||||
|
||||
return checked(ticks * 100L);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using log4net;
|
||||
using Nini.Config;
|
||||
using NexVerse.Core.Audit;
|
||||
@@ -17,6 +18,8 @@ namespace NexVerse.Server.Api
|
||||
public sealed class NexVerseWorldApiConnector : ServiceConnector
|
||||
{
|
||||
private static readonly ILog m_Log = LogManager.GetLogger(typeof(NexVerseWorldApiConnector));
|
||||
private static readonly object s_TelemetrySync = new object();
|
||||
private static NexOtlpHttpExporter s_OtlpExporter;
|
||||
|
||||
public NexVerseWorldApiConnector(IConfigSource config, IHttpServer server, string configName)
|
||||
: base(config, server, configName)
|
||||
@@ -58,6 +61,113 @@ namespace NexVerse.Server.Api
|
||||
m_Log.WarnFormat("[NEX-METRICS]: Metrics endpoint enabled at {0}. Restrict access with firewall/TLS policy.", metricsPath);
|
||||
}
|
||||
|
||||
IConfig telemetryConfig = config.Configs["NexTelemetry"];
|
||||
if (telemetryConfig != null &&
|
||||
telemetryConfig.GetBoolean("Enabled", false))
|
||||
{
|
||||
string protocol =
|
||||
telemetryConfig.GetString(
|
||||
"Protocol",
|
||||
"http/json").Trim();
|
||||
|
||||
if (!string.Equals(
|
||||
protocol,
|
||||
"http/json",
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"NexVerse currently supports OTLP protocol http/json.");
|
||||
}
|
||||
|
||||
lock (s_TelemetrySync)
|
||||
{
|
||||
if (s_OtlpExporter == null)
|
||||
{
|
||||
string instanceId =
|
||||
telemetryConfig.GetString(
|
||||
"ServiceInstanceId",
|
||||
string.Empty);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(instanceId))
|
||||
instanceId = Environment.MachineName;
|
||||
|
||||
NexOtlpHttpOptions options =
|
||||
new NexOtlpHttpOptions
|
||||
{
|
||||
Endpoint =
|
||||
ParseOptionalAbsoluteUri(
|
||||
telemetryConfig.GetString(
|
||||
"Endpoint",
|
||||
"http://127.0.0.1:4318")),
|
||||
TracesEndpoint =
|
||||
ParseOptionalAbsoluteUri(
|
||||
telemetryConfig.GetString(
|
||||
"TracesEndpoint",
|
||||
string.Empty)),
|
||||
MetricsEndpoint =
|
||||
ParseOptionalAbsoluteUri(
|
||||
telemetryConfig.GetString(
|
||||
"MetricsEndpoint",
|
||||
string.Empty)),
|
||||
ServiceName =
|
||||
telemetryConfig.GetString(
|
||||
"ServiceName",
|
||||
"NexVerse.Robust").Trim(),
|
||||
ServiceInstanceId =
|
||||
instanceId.Trim(),
|
||||
Headers =
|
||||
ParseOtlpHeaders(
|
||||
telemetryConfig.GetString(
|
||||
"Headers",
|
||||
string.Empty)),
|
||||
ExportIntervalSeconds =
|
||||
telemetryConfig.GetInt(
|
||||
"ExportIntervalSeconds",
|
||||
10),
|
||||
BatchSize =
|
||||
telemetryConfig.GetInt(
|
||||
"BatchSize",
|
||||
256),
|
||||
QueueCapacity =
|
||||
telemetryConfig.GetInt(
|
||||
"QueueCapacity",
|
||||
4096),
|
||||
TimeoutMilliseconds =
|
||||
telemetryConfig.GetInt(
|
||||
"TimeoutMilliseconds",
|
||||
10000),
|
||||
MaxRetries =
|
||||
telemetryConfig.GetInt(
|
||||
"MaxRetries",
|
||||
3),
|
||||
AllowInsecure =
|
||||
telemetryConfig.GetBoolean(
|
||||
"AllowInsecure",
|
||||
false)
|
||||
};
|
||||
|
||||
s_OtlpExporter =
|
||||
new NexOtlpHttpExporter(
|
||||
metrics,
|
||||
options);
|
||||
|
||||
AppDomain.CurrentDomain.ProcessExit +=
|
||||
(_, __) =>
|
||||
{
|
||||
lock (s_TelemetrySync)
|
||||
{
|
||||
s_OtlpExporter?.Dispose();
|
||||
s_OtlpExporter = null;
|
||||
}
|
||||
};
|
||||
|
||||
m_Log.InfoFormat(
|
||||
"[NEX-OTLP]: OTLP/HTTP JSON export enabled for service {0}.",
|
||||
options.ServiceName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
INexEventBus eventBus = CreateEventBus(config, server);
|
||||
INexAuditSink publicAuditSink = new LogNexAuditSink();
|
||||
INexAuthorizationService authorization = new NexAuthorizationService();
|
||||
@@ -318,6 +428,69 @@ namespace NexVerse.Server.Api
|
||||
return distributed;
|
||||
}
|
||||
|
||||
private static Uri ParseOptionalAbsoluteUri(
|
||||
string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return null;
|
||||
|
||||
if (!Uri.TryCreate(
|
||||
value.Trim(),
|
||||
UriKind.Absolute,
|
||||
out Uri parsed))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Invalid NexTelemetry endpoint URL: " +
|
||||
value);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<string, string> ParseOtlpHeaders(
|
||||
string value)
|
||||
{
|
||||
Dictionary<string, string> headers =
|
||||
new Dictionary<string, string>(
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return headers;
|
||||
|
||||
foreach (string rawPair in value.Split(
|
||||
',',
|
||||
StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
int separator = rawPair.IndexOf('=');
|
||||
if (separator <= 0)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"NexTelemetry Headers must use comma-separated key=value pairs.");
|
||||
}
|
||||
|
||||
string key =
|
||||
Uri.UnescapeDataString(
|
||||
rawPair.Substring(
|
||||
0,
|
||||
separator).Trim());
|
||||
|
||||
string headerValue =
|
||||
Uri.UnescapeDataString(
|
||||
rawPair.Substring(
|
||||
separator + 1).Trim());
|
||||
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"NexTelemetry header names must not be empty.");
|
||||
}
|
||||
|
||||
headers[key] = headerValue;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
private static T LoadOptionalService<T>(IConfigSource config, string sectionName)
|
||||
where T : class
|
||||
{
|
||||
|
||||
@@ -585,6 +585,25 @@
|
||||
Enabled = false
|
||||
Path = "/internal/metrics"
|
||||
|
||||
[NexTelemetry]
|
||||
; Optional production OpenTelemetry export via OTLP/HTTP JSON.
|
||||
; Disabled by default. Prefer HTTPS. AllowInsecure=true is intended only
|
||||
; for a trusted private collector network.
|
||||
Enabled = false
|
||||
Protocol = "http/json"
|
||||
Endpoint = "http://127.0.0.1:4318"
|
||||
TracesEndpoint = ""
|
||||
MetricsEndpoint = ""
|
||||
ServiceName = "NexVerse.Robust"
|
||||
ServiceInstanceId = ""
|
||||
Headers = ""
|
||||
ExportIntervalSeconds = 10
|
||||
BatchSize = 256
|
||||
QueueCapacity = 4096
|
||||
TimeoutMilliseconds = 10000
|
||||
MaxRetries = 3
|
||||
AllowInsecure = false
|
||||
|
||||
[NexBus]
|
||||
; Distributed NexBus peer transport. Keep disabled while internal traffic is
|
||||
; not protected by TLS/private networking. SharedKey must be >= 32 bytes.
|
||||
|
||||
@@ -584,6 +584,25 @@
|
||||
Enabled = false
|
||||
Path = "/internal/metrics"
|
||||
|
||||
[NexTelemetry]
|
||||
; Optional production OpenTelemetry export via OTLP/HTTP JSON.
|
||||
; Disabled by default. Prefer HTTPS. AllowInsecure=true is intended only
|
||||
; for a trusted private collector network.
|
||||
Enabled = false
|
||||
Protocol = "http/json"
|
||||
Endpoint = "http://127.0.0.1:4318"
|
||||
TracesEndpoint = ""
|
||||
MetricsEndpoint = ""
|
||||
ServiceName = "NexVerse.Robust"
|
||||
ServiceInstanceId = ""
|
||||
Headers = ""
|
||||
ExportIntervalSeconds = 10
|
||||
BatchSize = 256
|
||||
QueueCapacity = 4096
|
||||
TimeoutMilliseconds = 10000
|
||||
MaxRetries = 3
|
||||
AllowInsecure = false
|
||||
|
||||
[NexBus]
|
||||
; Distributed NexBus peer transport. Keep disabled while internal traffic is
|
||||
; not protected by TLS/private networking. SharedKey must be >= 32 bytes.
|
||||
|
||||
@@ -504,6 +504,25 @@
|
||||
Enabled = false
|
||||
Path = "/internal/metrics"
|
||||
|
||||
[NexTelemetry]
|
||||
; Optional production OpenTelemetry export via OTLP/HTTP JSON.
|
||||
; Disabled by default. Prefer HTTPS. AllowInsecure=true is intended only
|
||||
; for a trusted private collector network.
|
||||
Enabled = false
|
||||
Protocol = "http/json"
|
||||
Endpoint = "http://127.0.0.1:4318"
|
||||
TracesEndpoint = ""
|
||||
MetricsEndpoint = ""
|
||||
ServiceName = "NexVerse.Robust"
|
||||
ServiceInstanceId = ""
|
||||
Headers = ""
|
||||
ExportIntervalSeconds = 10
|
||||
BatchSize = 256
|
||||
QueueCapacity = 4096
|
||||
TimeoutMilliseconds = 10000
|
||||
MaxRetries = 3
|
||||
AllowInsecure = false
|
||||
|
||||
[NexBus]
|
||||
; Distributed NexBus peer transport. Keep disabled while internal traffic is
|
||||
; not protected by TLS/private networking. SharedKey must be >= 32 bytes.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# NexVerse Observability
|
||||
|
||||
NexVerse exposes two complementary production observability paths:
|
||||
|
||||
- Prometheus-compatible pull metrics through the optional `[NexMetrics]` endpoint.
|
||||
- OpenTelemetry Protocol export through the optional `[NexTelemetry]` OTLP/HTTP JSON pipeline.
|
||||
|
||||
Both are disabled by default.
|
||||
|
||||
## Prometheus metrics
|
||||
|
||||
```ini
|
||||
[NexMetrics]
|
||||
Enabled = true
|
||||
Path = "/internal/metrics"
|
||||
```
|
||||
|
||||
The metrics endpoint is intended for a trusted monitoring network. Restrict it with firewall, reverse-proxy and TLS policy when it is reachable outside localhost/private infrastructure.
|
||||
|
||||
## OTLP/HTTP JSON collector export
|
||||
|
||||
```ini
|
||||
[NexTelemetry]
|
||||
Enabled = true
|
||||
Protocol = "http/json"
|
||||
Endpoint = "https://otel-collector.example:4318"
|
||||
TracesEndpoint = ""
|
||||
MetricsEndpoint = ""
|
||||
ServiceName = "NexVerse.Robust"
|
||||
ServiceInstanceId = "robust-main"
|
||||
Headers = ""
|
||||
ExportIntervalSeconds = 10
|
||||
BatchSize = 256
|
||||
QueueCapacity = 4096
|
||||
TimeoutMilliseconds = 10000
|
||||
MaxRetries = 3
|
||||
AllowInsecure = false
|
||||
```
|
||||
|
||||
With the common `Endpoint`, NexVerse sends traces to `/v1/traces` and metrics to `/v1/metrics`. `TracesEndpoint` and `MetricsEndpoint` override those URLs independently and are used exactly as configured.
|
||||
|
||||
The built-in exporter intentionally supports `http/json`. It emits OTLP JSON using lower-camel-case protobuf field names, hexadecimal trace/span IDs, integer enum values and decimal-string 64-bit nanosecond timestamps.
|
||||
|
||||
`AllowInsecure=false` rejects plaintext HTTP collectors. Set it to `true` only when the collector path is protected by a trusted private network or equivalent transport security.
|
||||
|
||||
`Headers` accepts comma-separated `key=value` pairs for collector authentication or metadata. Percent-encoding may be used when a value contains a comma. Header values are not written to audit records.
|
||||
|
||||
## Reliability and backpressure
|
||||
|
||||
Trace export is decoupled from request processing through a bounded in-memory queue. The queue is flushed in batches and on the configured interval. A full queue drops new spans instead of blocking the World API and increments `nexverse_otlp_spans_dropped_total`.
|
||||
|
||||
HTTP 408, 429, 502, 503 and 504 responses and connection/timeout failures are retried with bounded exponential backoff and jitter. `Retry-After` is honored when supplied, capped at 30 seconds.
|
||||
|
||||
Exporter health is visible through NexMetrics:
|
||||
|
||||
- `nexverse_otlp_queue_depth`
|
||||
- `nexverse_otlp_spans_dropped_total`
|
||||
- `nexverse_otlp_export_requests_total{signal,result}`
|
||||
- `nexverse_otlp_export_records_total{signal,result}`
|
||||
- `nexverse_otlp_worker_failures_total`
|
||||
|
||||
## Resource identity
|
||||
|
||||
Each OTLP resource carries `service.name`, `service.instance.id`, `service.version` and `nexverse.milestone`. The instrumentation scope is `NexVerse`.
|
||||
|
||||
## Security
|
||||
|
||||
Do not place resident passwords, access tokens, refresh tokens, OAuth client secrets, API keys or other credentials in Activity tags or metric labels.
|
||||
|
||||
Collector authentication belongs in the protected `Headers` configuration. Prefer HTTPS and restrict the collector to trusted NexVerse infrastructure.
|
||||
@@ -247,8 +247,8 @@ Implemented during NEXJAST:
|
||||
- [x] distributed NexBus transport connected end-to-end between Robust and simulator nodes.
|
||||
- [x] distributed NexBus core plus authenticated HTTP/HMAC peer transport foundation implemented with relay-loop deduplication and bounded outbound queue.
|
||||
- [x] NexVerse NodeAgent region module publishes node/region lifecycle and health heartbeats and exposes local/inbound NexBus pub/sub to simulator modules.
|
||||
- [ ] production metrics/OpenTelemetry implemented end-to-end.
|
||||
- [x] NexMetrics Prometheus-compatible registry/export endpoint and OpenTelemetry-compatible ActivitySource foundation implemented; external collector/export pipeline remains pending.
|
||||
- [x] production metrics/OpenTelemetry implemented end-to-end through Prometheus export plus a bounded OTLP/HTTP JSON trace/metrics collector pipeline.
|
||||
- [x] NexMetrics Prometheus-compatible registry/export endpoint, OpenTelemetry-compatible ActivitySource, OTLP batching/retry/TLS controls and external collector export are implemented and CI-regression tested.
|
||||
|
||||
### 5.8 NEXJAST definition of done
|
||||
|
||||
|
||||
@@ -10,5 +10,6 @@
|
||||
<Compile Include="../../../NexVerse/Core/NexVersePlatform.cs" Link="NexVersePlatform.cs" />
|
||||
<Compile Include="../../../NexVerse/Core/Observability/NexMetrics.cs" Link="NexMetrics.cs" />
|
||||
<Compile Include="../../../NexVerse/Core/Observability/NexTelemetry.cs" Link="NexTelemetry.cs" />
|
||||
<Compile Include="../../../NexVerse/Server/Api/NexOtlpHttpExporter.cs" Link="NexOtlpHttpExporter.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,11 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using NexVerse.Core.Observability;
|
||||
using NexVerse.Server.Api;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static void Require(bool condition, string message)
|
||||
private sealed class CaptureHandler : HttpMessageHandler
|
||||
{
|
||||
public sealed class Capture
|
||||
{
|
||||
public Uri Uri { get; set; }
|
||||
public string MediaType { get; set; }
|
||||
public string Body { get; set; }
|
||||
}
|
||||
|
||||
public List<Capture> Requests { get; } =
|
||||
new List<Capture>();
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
string body =
|
||||
request.Content == null
|
||||
? string.Empty
|
||||
: await request.Content.ReadAsStringAsync(
|
||||
cancellationToken);
|
||||
|
||||
Requests.Add(
|
||||
new Capture
|
||||
{
|
||||
Uri = request.RequestUri,
|
||||
MediaType =
|
||||
request.Content?.Headers?.ContentType?.MediaType,
|
||||
Body = body
|
||||
});
|
||||
|
||||
return new HttpResponseMessage(
|
||||
HttpStatusCode.OK)
|
||||
{
|
||||
Content =
|
||||
new StringContent("{}")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static void Require(
|
||||
bool condition,
|
||||
string message)
|
||||
{
|
||||
if (!condition)
|
||||
throw new InvalidOperationException(message);
|
||||
@@ -13,47 +62,250 @@ internal static class Program
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
NexMetricsRegistry metrics = new NexMetricsRegistry();
|
||||
NexMetricsRegistry metrics =
|
||||
new NexMetricsRegistry();
|
||||
|
||||
metrics.IncrementCounter(
|
||||
"nexverse_requests_total",
|
||||
"Regression requests.",
|
||||
2,
|
||||
new Dictionary<string, string> { ["route"] = "/api/v1" });
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["route"] = "/api/v1"
|
||||
});
|
||||
|
||||
metrics.IncrementCounter(
|
||||
"nexverse_requests_total",
|
||||
"Regression requests.",
|
||||
3,
|
||||
new Dictionary<string, string> { ["route"] = "/api/v1" });
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["route"] = "/api/v1"
|
||||
});
|
||||
|
||||
metrics.SetGauge(
|
||||
"nexverse_queue_depth",
|
||||
"Regression queue depth.",
|
||||
7);
|
||||
|
||||
string rendered = metrics.RenderPrometheus();
|
||||
string rendered =
|
||||
metrics.RenderPrometheus();
|
||||
|
||||
Require(rendered.Contains("# TYPE nexverse_requests_total counter"), "counter type missing");
|
||||
Require(rendered.Contains("nexverse_requests_total{route=\"/api/v1\"} 5"), "counter aggregation failed");
|
||||
Require(rendered.Contains("# TYPE nexverse_queue_depth gauge"), "gauge type missing");
|
||||
Require(rendered.Contains("nexverse_queue_depth 7"), "gauge value missing");
|
||||
Require(
|
||||
rendered.Contains(
|
||||
"# TYPE nexverse_requests_total counter"),
|
||||
"counter type missing");
|
||||
|
||||
Require(
|
||||
rendered.Contains(
|
||||
"nexverse_requests_total{route=\"/api/v1\"} 5"),
|
||||
"counter aggregation failed");
|
||||
|
||||
Require(
|
||||
rendered.Contains(
|
||||
"# TYPE nexverse_queue_depth gauge"),
|
||||
"gauge type missing");
|
||||
|
||||
Require(
|
||||
rendered.Contains(
|
||||
"nexverse_queue_depth 7"),
|
||||
"gauge value missing");
|
||||
|
||||
IReadOnlyList<NexMetricSnapshot> snapshot =
|
||||
metrics.Snapshot();
|
||||
|
||||
Require(
|
||||
snapshot.Any(x =>
|
||||
x.Name ==
|
||||
"nexverse_requests_total" &&
|
||||
x.Samples.Any(s =>
|
||||
Math.Abs(s.Value - 5) < 0.0001)),
|
||||
"metric snapshot missing counter value");
|
||||
|
||||
bool observed = false;
|
||||
using ActivityListener listener = new ActivityListener
|
||||
{
|
||||
ShouldListenTo = source => source.Name == NexTelemetry.ActivitySourceName,
|
||||
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllData,
|
||||
ActivityStarted = _ => observed = true
|
||||
};
|
||||
|
||||
using ActivityListener listener =
|
||||
new ActivityListener
|
||||
{
|
||||
ShouldListenTo =
|
||||
source =>
|
||||
source.Name ==
|
||||
NexTelemetry.ActivitySourceName,
|
||||
Sample =
|
||||
(ref ActivityCreationOptions<ActivityContext> _) =>
|
||||
ActivitySamplingResult.AllData,
|
||||
ActivityStarted =
|
||||
_ => observed = true
|
||||
};
|
||||
|
||||
ActivitySource.AddActivityListener(listener);
|
||||
using (Activity activity = NexTelemetry.ActivitySource.StartActivity("regression"))
|
||||
|
||||
using (Activity activity =
|
||||
NexTelemetry.ActivitySource.StartActivity(
|
||||
"regression"))
|
||||
{
|
||||
Require(activity != null, "ActivitySource did not create an activity");
|
||||
activity.SetTag("nexverse.test", true);
|
||||
Require(
|
||||
activity != null,
|
||||
"ActivitySource did not create an activity");
|
||||
|
||||
activity.SetTag(
|
||||
"nexverse.test",
|
||||
true);
|
||||
}
|
||||
|
||||
Require(observed, "Activity listener did not observe NexVerse activity");
|
||||
Require(
|
||||
observed,
|
||||
"Activity listener did not observe NexVerse activity");
|
||||
|
||||
CaptureHandler capture =
|
||||
new CaptureHandler();
|
||||
|
||||
NexOtlpHttpOptions options =
|
||||
new NexOtlpHttpOptions
|
||||
{
|
||||
Endpoint =
|
||||
new Uri(
|
||||
"http://collector.example:4318",
|
||||
UriKind.Absolute),
|
||||
ServiceName =
|
||||
"NexVerse.Regression",
|
||||
ServiceInstanceId =
|
||||
"ci",
|
||||
ExportIntervalSeconds = 3600,
|
||||
BatchSize = 16,
|
||||
QueueCapacity = 128,
|
||||
TimeoutMilliseconds = 1000,
|
||||
MaxRetries = 0,
|
||||
AllowInsecure = true,
|
||||
AutoStart = false
|
||||
};
|
||||
|
||||
using (NexOtlpHttpExporter exporter =
|
||||
new NexOtlpHttpExporter(
|
||||
metrics,
|
||||
options,
|
||||
capture))
|
||||
{
|
||||
using (Activity activity =
|
||||
NexTelemetry.ActivitySource.StartActivity(
|
||||
"otlp.regression",
|
||||
ActivityKind.Server))
|
||||
{
|
||||
Require(
|
||||
activity != null,
|
||||
"OTLP listener did not sample activity");
|
||||
|
||||
activity.SetTag(
|
||||
"http.request.method",
|
||||
"GET");
|
||||
|
||||
activity.SetTag(
|
||||
"nexverse.regression",
|
||||
1L);
|
||||
|
||||
activity.SetStatus(
|
||||
ActivityStatusCode.Ok);
|
||||
}
|
||||
|
||||
exporter.Flush();
|
||||
|
||||
Require(
|
||||
capture.Requests.Count == 2,
|
||||
"expected one trace and one metric export");
|
||||
|
||||
CaptureHandler.Capture trace =
|
||||
capture.Requests.Single(x =>
|
||||
x.Uri.AbsolutePath.EndsWith(
|
||||
"/v1/traces",
|
||||
StringComparison.Ordinal));
|
||||
|
||||
CaptureHandler.Capture metric =
|
||||
capture.Requests.Single(x =>
|
||||
x.Uri.AbsolutePath.EndsWith(
|
||||
"/v1/metrics",
|
||||
StringComparison.Ordinal));
|
||||
|
||||
Require(
|
||||
trace.MediaType == "application/json" &&
|
||||
metric.MediaType == "application/json",
|
||||
"OTLP HTTP JSON content type missing");
|
||||
|
||||
using JsonDocument traceJson =
|
||||
JsonDocument.Parse(trace.Body);
|
||||
|
||||
JsonElement span =
|
||||
traceJson.RootElement
|
||||
.GetProperty("resourceSpans")[0]
|
||||
.GetProperty("scopeSpans")[0]
|
||||
.GetProperty("spans")[0];
|
||||
|
||||
Require(
|
||||
span.GetProperty("traceId")
|
||||
.GetString()?.Length == 32,
|
||||
"OTLP traceId is not 32 hex characters");
|
||||
|
||||
Require(
|
||||
span.GetProperty("spanId")
|
||||
.GetString()?.Length == 16,
|
||||
"OTLP spanId is not 16 hex characters");
|
||||
|
||||
Require(
|
||||
span.GetProperty("kind")
|
||||
.GetInt32() == 2,
|
||||
"server activity was not mapped to OTLP SPAN_KIND_SERVER");
|
||||
|
||||
Require(
|
||||
span.GetProperty("startTimeUnixNano")
|
||||
.ValueKind == JsonValueKind.String,
|
||||
"OTLP nanosecond timestamp must be a decimal string");
|
||||
|
||||
using JsonDocument metricJson =
|
||||
JsonDocument.Parse(metric.Body);
|
||||
|
||||
JsonElement exportedMetrics =
|
||||
metricJson.RootElement
|
||||
.GetProperty("resourceMetrics")[0]
|
||||
.GetProperty("scopeMetrics")[0]
|
||||
.GetProperty("metrics");
|
||||
|
||||
Require(
|
||||
exportedMetrics
|
||||
.EnumerateArray()
|
||||
.Any(x =>
|
||||
x.GetProperty("name").GetString() ==
|
||||
"nexverse_requests_total"),
|
||||
"OTLP metric payload missing regression counter");
|
||||
}
|
||||
|
||||
bool blockedInsecure = false;
|
||||
|
||||
try
|
||||
{
|
||||
using NexOtlpHttpExporter unused =
|
||||
new NexOtlpHttpExporter(
|
||||
metrics,
|
||||
new NexOtlpHttpOptions
|
||||
{
|
||||
Endpoint =
|
||||
new Uri(
|
||||
"http://collector.example:4318"),
|
||||
AllowInsecure = false,
|
||||
AutoStart = false
|
||||
},
|
||||
new CaptureHandler());
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
blockedInsecure = true;
|
||||
}
|
||||
|
||||
Require(
|
||||
blockedInsecure,
|
||||
"plain HTTP OTLP transport was not blocked by default");
|
||||
|
||||
Console.WriteLine(
|
||||
"NexMetrics/OpenTelemetry OTLP regression: OK");
|
||||
|
||||
Console.WriteLine("NexMetrics/OpenTelemetry foundation regression: OK");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user