Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<ItemGroup Label="Testing and benchmarks">
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.14" />
<PackageVersion Include="TUnit" Version="1.77.0" />
<PackageVersion Include="BenchmarkDotNet" Version="0.15.8" />
</ItemGroup>
Expand Down
14 changes: 14 additions & 0 deletions benchmarks/Relayer.Benchmarks/FailurePipelineBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class FailurePipelineBenchmarks
private IServiceScopeFactory _scopes = null!;
private ConsumePipeline _consumer = null!;
private ConsumePipeline _failures = null!;
private ConsumePipeline _instrumentedFailures = null!;
private HandlerDescriptor<Payload> _descriptor = null!;
private readonly DirectContext _direct = new();
private readonly Serializer _serializer = new();
Expand Down Expand Up @@ -44,6 +45,12 @@ public void Setup()
static (_, error, _) => ValueTask.FromException(error)).Handler(_descriptor).Build(1);
_failures = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService<MessageTypeRegistry>(), _serializer,
policy).Handler(_descriptor).Build(1);
var telemetry = _provider.GetRequiredService<RelayerInstrumentation>().CreateEndpoint(new()
{
System = "relayer.inmemory", Destination = "source",
});
_instrumentedFailures = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService<MessageTypeRegistry>(), _serializer,
policy).Handler(_descriptor).Telemetry(telemetry).Build(1);
_message = new() { MessageId = "benchmark", MessageType = new("benchmark.failure", 1), Body = default };
}

Expand Down Expand Up @@ -74,6 +81,13 @@ public async ValueTask ExecutableFailurePipeline()
await _failures.ProcessAsync(context).ConfigureAwait(false);
}

[Benchmark]
public async ValueTask ExecutableFailurePipelineWithTelemetry()
{
using var context = _instrumentedFailures.RentContext(_message);
await _instrumentedFailures.ProcessAsync(context).ConfigureAwait(false);
}

[GlobalCleanup]
public async Task Cleanup() => await _provider.DisposeAsync();

Expand Down
1 change: 1 addition & 0 deletions benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.Extensions.Logging" />
</ItemGroup>

<ItemGroup>
Expand Down
142 changes: 142 additions & 0 deletions benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
#pragma warning disable RLY001 // The benchmark explicitly registers its cached payload and serializer.
using System.Buffers;
using System.Diagnostics.Metrics;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Relayer.Serialization;

namespace Relayer.Benchmarks;

/// <summary>Measures telemetry's incremental CPU and allocation cost with identical DI/serializer work in each case.</summary>
[MemoryDiagnoser]
public class TelemetryBenchmarks
{
private ServiceProvider _provider = null!;
private ConsumePipeline _baseline = null!;
private ConsumePipeline _instrumented = null!;
private ReceivePipeline<Incoming, Binding> _receive = null!;
private Incoming _incoming = null!;
private MeterListener? _listener;
private EndpointTelemetry _endpoint = null!;
private ConsumeMessage _message;

[Params(false, true)]
public bool ListenerAttached { get; set; }

[Params(false, true)]
public bool ErrorLoggingEnabled { get; set; }

[GlobalSetup]
public void Setup()
{
var services = new ServiceCollection();
services.AddSingleton<Handler>();
services.AddLogging(logging => logging
.SetMinimumLevel(ErrorLoggingEnabled ? LogLevel.Error : LogLevel.None)
.AddProvider(new ScopeProvider()));
services.AddRelayer(r => { r.MessageTypes.Add<Payload>("benchmark.payload"); r.Handler<Handler>(); });
_provider = services.BuildServiceProvider();
var instrumentation = _provider.GetRequiredService<RelayerInstrumentation>();
_endpoint = instrumentation.CreateEndpoint(new()
{
System = "kafka", Destination = "orders", ConsumerGroup = "billing", Subscription = "subscription",
ServerAddress = "localhost", ServerPort = 9092,
});
if (ListenerAttached)
{
_listener = new MeterListener
{
InstrumentPublished = (instrument, listener) =>
{
if (ReferenceEquals(instrument.Meter.Scope, instrumentation)) listener.EnableMeasurementEvents(instrument);
},
};
_listener.SetMeasurementEventCallback<double>(static (_, _, _, _) => { });
_listener.SetMeasurementEventCallback<long>(static (_, _, _, _) => { });
_listener.Start();
}
_baseline = Builder().Build(1);
_instrumented = Builder().Telemetry(_endpoint).Build(1);
_receive = new(_instrumented, new HeaderNames(), 1);
_incoming = new();
_message = new() { MessageId = "benchmark", MessageType = new("benchmark.payload", 1), Body = default };
}

private ConsumePipelineBuilder Builder() => new ConsumePipelineBuilder(_provider.GetRequiredService<IServiceScopeFactory>(),
_provider.GetRequiredService<MessageTypeRegistry>(), new Serializer(), static (_, error, _) => ValueTask.FromException(error))
.Handler(_provider.GetRequiredService<HandlerRegistry>().GetHandler<Payload, Handler>());

[Benchmark(Baseline = true)]
public async ValueTask ConsumerWithoutTelemetry()
{
using var context = _baseline.RentContext(_message);
await _baseline.ProcessAsync(context).ConfigureAwait(false);
}

[Benchmark]
public async ValueTask ConsumerWithTelemetry()
{
using var context = _instrumented.RentContext(_message);
await _instrumented.ProcessAsync(context).ConfigureAwait(false);
}

[Benchmark]
public ValueTask<Disposition> NativeConsumerWithTelemetry() => _receive.ProcessAsync(_incoming);

[Benchmark]
public void FailureMeasurement() => _endpoint.RecordDuration(TimeSpan.FromMilliseconds(1), failed: true);

[GlobalCleanup]
public void Cleanup()
{
_listener?.Dispose();
_provider.Dispose();
}

// LoggerFactory supplies real external scopes; output is disabled to isolate pipeline overhead.
private sealed class ScopeProvider : ILoggerProvider, ISupportExternalScope, ILogger
{
public ILogger CreateLogger(string categoryName) => this;
public bool IsEnabled(LogLevel level) => level >= LogLevel.Error;
public void SetScopeProvider(IExternalScopeProvider scopeProvider) { }
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => throw new NotSupportedException();
public void Log<TState>(LogLevel level, EventId id, TState state, Exception? error, Func<TState, Exception?, string> formatter) { }
public void Dispose() { }
}
private sealed class Incoming
{
internal byte[] Id { get; } = "benchmark"u8.ToArray();
internal byte[] Type { get; } = "benchmark.payload;v=1"u8.ToArray();
internal byte[] Correlation { get; } = "conversation"u8.ToArray();
}
private readonly struct Binding : IMessageBinding<Incoming>
{
public static ReadOnlySequence<byte> GetBody(Incoming message) => default;
public static int? GetDeliveryCount(Incoming message) => 1;
public static bool TryGetHeader(Incoming message, string name, out WireString value)
{
value = name switch
{
"ce_id" => new(message.Id),
"ce_type" => new(message.Type),
"ce_correlationid" => new(message.Correlation),
_ => default,
};
return !value.IsEmpty;
}
}

public sealed class Payload;
public sealed class Handler : IHandler<Payload>
{
public ValueTask HandleAsync(Payload message, MessageContext context, CancellationToken cancellationToken) => default;
}
private sealed class Serializer : IMessageSerializer
{
private readonly Payload _payload = new();
public string ContentType => "benchmark/cached";
public T Deserialize<T>(ReadOnlySequence<byte> source) => (T)(object)_payload;
public void Serialize<T>(T message, IBufferWriter<byte> destination) => throw new NotSupportedException();
}
}
2 changes: 2 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ Superseded by [D24](#d24-capabilities-are-valued-and-declared-per-endpoint).
- W3C trace context is propagated in native headers.
- The outbox captures trace context at enqueue time.
- Processing duration is measured after settlement.
- Immediate retries share one delivery duration. A retry that completes handling, scope disposal and buffered send flushing clears earlier failures from the duration's `error.type`; each failed attempt is still logged. Unrecovered failures retain the tag, including after durable dead-letter handling or subsequent delivery-token cancellation. A settlement error marks the duration as failed; delivery-token cancellation alone does not.
- Generated failure logs open an identity scope only around the log call. `LoggerFactory` allocates when it pushes an external scope, so successful deliveries must not open a Relayer scope. Failure scopes contain read-only snapshots rather than pooled context references, allowing providers to retain them for asynchronous export. Logging provider failures must not replace the delivery error or bypass durable failure handling.
- Enrichers are supported.

## D16. Topology is declared; default mode is Validate
Expand Down
4 changes: 3 additions & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,8 @@ Attributes that only Relayer defines use the `relayer.` prefix and never the `me

### 8.4 Metrics

See [metrics and logging integration](telemetry.md) for the implemented transport-author call site and recording contracts.

Instruments from the semantic conventions, with the conventions' recommended histogram buckets given as instrument advice:

| Instrument | Type | Unit | Measures |
Expand Down Expand Up @@ -635,7 +637,7 @@ Relayer-specific instruments, for which the conventions define nothing:

### 8.6 Logging and health

- Logging uses `LoggerMessage` source generation (zero allocations when disabled) and scopes that carry the message ID, type, and correlation ID.
- Logging uses `LoggerMessage` source generation and scopes that carry the message ID, type, and correlation ID around generated failure logs. Successful deliveries open no logging scope, preserving zero incremental allocations with Error logging enabled. Failure scopes hold read-only identity snapshots that providers can retain after processing.
- Health checks: transport connectivity, consumer liveness (each consumer has made progress or is idle), and outbox backlog thresholds.

---
Expand Down
48 changes: 48 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Metrics and logging

`AddRelayer` registers a single DI-owned `RelayerInstrumentation`. Its meter is named `Relayer`; subscribe with your OpenTelemetry provider's `AddMeter(RelayerTelemetry.MeterName)`. `RelayerTelemetry.SchemaUrl` pins the semantic conventions version. No OpenTelemetry SDK dependency is needed in the library.

Transport authors compose endpoint telemetry at startup, alongside generated dispatch. For example, after registering and freezing handlers:

```csharp
var instrumentation = provider.GetRequiredService<RelayerInstrumentation>();
var process = instrumentation.CreateEndpoint(new EndpointTelemetryOptions
{
System = "servicebus",
Destination = "orders",
Subscription = "billing",
ServerAddress = "example.servicebus.windows.net",
});

var consumer = new ConsumePipelineBuilder(
provider.GetRequiredService<IServiceScopeFactory>(),
provider.GetRequiredService<MessageTypeRegistry>(),
provider.GetRequiredService<IMessageSerializer>(),
HandleFailureDurablyAsync)
.Handler(orderHandlerDescriptor)
.Telemetry(process)
.Settle(SettleNativeMessageAsync)
.Build();
```

The settlement callback reads the transport's native feature and its disposition. It runs only after durable processing, failure handling and async scope disposal succeed. It must honor `SettledByHandler`, use the broker's native semantics, and record its native operation with a separate endpoint recorder (`OperationName = "complete"`, `"ack"`, `"commit"`, etc.). `context.Services` is unavailable after scope disposal. A settlement error propagates to the receive loop without re-entering failure handling. If settlement runs outside this callback, its duration cannot be included in the process metric. Amortized commits stay outside per-message processing, as design §8.2 requires.

Both consumer constructors support telemetry and settlement. With an executable `FailurePipeline`, the native feature receives the resolved failure disposition before the settlement callback runs. Immediate retries share one delivery count and duration, including all attempt scopes, send flushes, durable failure work and settlement. A successful retry clears earlier failures from the duration's `error.type` only after its scope disposal and buffered send flush succeed. Each failed attempt is still logged. A later settlement error marks the duration as failed.

The consumer records one `messaging.client.consumed.messages` measurement per delivery and a `messaging.process.duration` measurement after settlement. Unrecovered processing failures, including ones durably dead-lettered or otherwise handled by the failure pipeline, mark the duration with `error.type = "_OTHER"`. Actual exception objects are retained in logs. This bounded fallback avoids runtime type lookups and message-derived metric dimensions. Delivery-token cancellation still counts as a delivery and records duration, but does not add `error.type`. If handling already failed and no retry recovered before cancellation, the duration retains that earlier failure. Cancellation before receive adaptation starts is not a delivery.

Other execution components use the same recorder methods: `RecordSent` counts messages attempted at the broker, including failed attempts, but never an outbox enqueue. `RecordDuration` selects the process histogram only for `OperationName = "process"`; other operations use the client-operation histogram. Durations and dispatch lag use seconds. Outbox dispatch, retry, inbox, circuit and transport implementations call the corresponding recorder only when the actual action occurs. The current core exposes those recording seams; it does not infer retries or dead-letter success from a classifier decision. `RecordConsumerLag` accepts the native client's lag calculation. Circuit values are 0 closed, 1 open and 2 half-open.

Each recorder retains precomputed `TagList` values, including its failure tags. Tags include only declared system, operation, destination, group, subscription and broker address/port. Do not create recorders per message or use dynamic destination names, message IDs or keys. Both convention histograms publish the [pinned conventions' recommended bucket advice](https://github.com/open-telemetry/semantic-conventions/blob/v1.44.0/docs/messaging/messaging-metrics.md).

The consumer reads the transport binding's CloudEvents time header only when `relayer.critical_time` has a listener. Invalid or missing timestamps produce no critical-time measurement. With logging and metrics disabled, optional headers remain unread and telemetry adds no per-delivery allocations.

Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, each generated failure log opens a scope carrying `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional CloudEvents `correlationid` extension (`ce_correlationid` or `cloudEvents:correlationid`, resolved through `HeaderNames.CorrelationId`). Failures in handling, failure handling, disposal and settlement receive this scope. It surrounds only the generated log call; application and failure-handler logs retain the application's ambient scopes. Successful deliveries open no Relayer logging scope, because `LoggerFactory` allocates when pushing an external scope. Cancellation with the delivery token canceled propagates without an Error log, while unrelated cancellation failures are logged normally. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Producers opt into correlation by writing the extension through their native header writer using `names.CorrelationId`; the envelope writer does not invent a correlation ID. Native adapters expose that header through their lazy binding, including messages from non-Relayer producers. For example, after writing the envelope:

```csharp
NativeHeaderWriter.SetHeader(nativeMessage, names.CorrelationId, correlationId);
```

Scope identities are captured in a read-only snapshot only when a generated failure log is emitted. Successful deliveries do not format identities or read optional correlation headers merely because Error logging is enabled. Typed deliveries reuse the precomputed wire type string; native malformed fields remain available without envelope parsing. A provider can retain the scope snapshot for asynchronous export after the context is cleared or reused. Snapshot, scope-push and enumeration allocations occur only on the failure path. Exceptions from logging providers are contained so they cannot replace the delivery error or bypass durable failure handling.

Health integration is tracked separately in #85; tracing in #13. See [design §8](design.md#8-observability) for their contracts.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public static IServiceCollection AddRelayer(this IServiceCollection services, Ac
}

var builder = new RelayerBuilder(services);
services.TryAddSingleton<RelayerInstrumentation>();
configure(builder);
builder.MessageTypes.Freeze();
builder.Handlers.Freeze();
Expand Down
3 changes: 3 additions & 0 deletions src/Relayer/Envelope/HeaderNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public HeaderNames(string prefix = "ce_")
Source = prefix + "source";
Time = prefix + "time";
SpecVersion = prefix + "specversion";
CorrelationId = prefix + "correlationid";
}

/// <summary>The event ID header.</summary>
Expand All @@ -24,6 +25,8 @@ public HeaderNames(string prefix = "ce_")
public string Time { get; }
/// <summary>The CloudEvents version header.</summary>
public string SpecVersion { get; }
/// <summary>The optional CloudEvents correlationid extension header.</summary>
public string CorrelationId { get; }
/// <summary>The W3C trace parent header.</summary>
public string TraceParent => "traceparent";
/// <summary>The W3C trace state header.</summary>
Expand Down
Loading
Loading