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
107 changes: 107 additions & 0 deletions benchmarks/Relayer.Benchmarks/BatchBufferedSendBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
using System.Buffers;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
using Relayer.Serialization;
using Relayer.Transports;

namespace Relayer.Benchmarks;

/// <summary>Buffered batch sends with shared or distinct cancellable delivery tokens. Results are per batch.</summary>
[MemoryDiagnoser]
public class BatchBufferedSendBenchmarks
{
private ServiceProvider _provider = null!;
private ConsumePipeline _pipeline = null!;
private DefaultMessageContext[] _contexts = null!;
private CancellationTokenSource[] _deliveries = null!;
private readonly CancellationTokenSource _batch = new();
private readonly ConsumeMessage _message = new()
{
MessageId = "benchmark", MessageType = new("benchmark.buffered-batch", 1), Body = ReadOnlySequence<byte>.Empty
};

[Params(1, 10, 100)]
public int BatchSize { get; set; }

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

[GlobalSetup]
public void Setup()
{
var services = new ServiceCollection();
services.AddSingleton<IMessageSerializer, Serializer>();
services.AddSingleton<ITransport, Transport>();
services.AddSingleton<Handler>();
services.AddRelayer(builder =>
{
builder.MessageTypes.Add<Payload>("benchmark.buffered-batch");
builder.AddTransport<Options, Options, Options>("benchmark", transport =>
{
transport.Send<Payload>("destination");
transport.Consume("source", consumer => consumer.Handler<Handler>().Batch(BatchSize, TimeSpan.FromSeconds(1)));
});
});
_provider = services.BuildServiceProvider();
_pipeline = new ConsumePipelineBuilder(_provider.GetRequiredService<IServiceScopeFactory>(),
_provider.GetRequiredService<MessageTypeRegistry>(), _provider.GetRequiredService<IMessageSerializer>(),
static (_, error, _) => ValueTask.FromException(error))
.BuildBatch(_provider.GetRequiredService<HandlerRegistry>().GetBatchHandler<Payload, Handler>(),
_provider.GetRequiredService<RelayerConfiguration>().Transports[0].Consumers[0]);
_contexts = new DefaultMessageContext[BatchSize];
_deliveries = new CancellationTokenSource[DistinctDeliveryTokens ? BatchSize : 1];
for (var i = 0; i < _deliveries.Length; i++) _deliveries[i] = new();
}

[Benchmark]
public async ValueTask BufferedBatch()
{
for (var i = 0; i < BatchSize; i++)
_contexts[i] = _pipeline.RentContext(_message, _deliveries[DistinctDeliveryTokens ? i : 0].Token);
try { await _pipeline.ProcessBatchAsync(_contexts, _batch.Token).ConfigureAwait(false); }
finally
{
for (var i = 0; i < BatchSize; i++) { _contexts[i].Dispose(); _contexts[i] = null!; }
}
}

[GlobalCleanup]
public async ValueTask Cleanup()
{
foreach (var delivery in _deliveries) delivery.Dispose();
_batch.Dispose();
await _provider.DisposeAsync().ConfigureAwait(false);
}

public sealed class Options;
[Message("benchmark.buffered-batch")]
public sealed class Payload;
public sealed class Handler : IBatchHandler<Payload>
{
public async ValueTask<BatchResult> HandleAsync(Batch<Payload> batch, CancellationToken cancellationToken)
{
var sender = batch.Items[0].Context.Services.GetRequiredService<ISender>();
for (var i = 0; i < batch.Count; i++)
await sender.SendNowAsync(batch.Items[i].Message, cancellationToken).ConfigureAwait(false);
return BatchResult.Success;
}
}
private sealed class Serializer : IMessageSerializer
{
private readonly Payload _payload = new();
public string ContentType => "benchmark/cached";
public TMessage Deserialize<TMessage>(ReadOnlySequence<byte> source) => (TMessage)(object)_payload;
public void Serialize<TMessage>(TMessage message, IBufferWriter<byte> destination) { destination.GetSpan(1)[0] = 1; destination.Advance(1); }
}
private sealed class Transport : ITransport
{
public string Name => "benchmark";
public TransportCapabilities GetCapabilities(string endpoint) => new();
public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) => default;
public ValueTask SendBatchAsync(ReadOnlyMemory<OutgoingMessage> messages, CancellationToken cancellationToken) => throw new NotSupportedException();
public ValueTask<TopologyReport> ApplyTopologyAsync(TopologyMode mode, CancellationToken cancellationToken) => new(new TopologyReport([]));
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public ValueTask DisposeAsync() => default;
}
}
172 changes: 172 additions & 0 deletions benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
using System.Buffers;
using System.Diagnostics;
using System.Text;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
using Relayer.Serialization;

namespace Relayer.Benchmarks;

/// <summary>Batch composition versus the same scoped sender, serializer and generated handler dispatch.</summary>
/// <remarks>Results are per batch. DI scope allocations are shared by both paths; payload instances are cached.</remarks>
[MemoryDiagnoser]
public class BatchConsumePipelineBenchmarks
{
private ServiceProvider _provider = null!;
private IServiceScopeFactory _scopes = null!;
private ConsumePipeline _pipeline = null!;
private BatchHandlerDescriptor<Payload> _descriptor = null!;
private readonly Serializer _serializer = new();
private readonly DirectContext _directContext = new();
private Batch<Payload> _directBatch = null!;
private ConsumeMessage _message;
private DefaultMessageContext[] _contexts = null!;
private ActivitySource _source = null!;
private ActivityListener _listener = null!;
private Activity _ambient = null!;
private ActivityLink[] _links = null!;
private KeyValuePair<string, object?>[] _tags = null!;
private readonly HeaderNames _headerNames = new();

[Params(1, 10, 100)]
public int BatchSize { get; set; }

[Params(TracingMode.None, TracingMode.Text, TracingMode.Utf8)]
public TracingMode Tracing { get; set; }

[GlobalSetup]
public void Setup()
{
var services = new ServiceCollection();
services.AddSingleton<IMessageSerializer>(_serializer);
services.AddSingleton<Handler>();
services.AddRelayer(builder =>
{
builder.MessageTypes.Add<Payload>("benchmark.batch");
builder.AddTransport<Options, Options, Options>("benchmark", transport =>
transport.Consume("source", consumer => consumer.Handler<Handler>().Batch(BatchSize, TimeSpan.FromMilliseconds(100))));
});
_provider = services.BuildServiceProvider();
_scopes = _provider.GetRequiredService<IServiceScopeFactory>();
_descriptor = _provider.GetRequiredService<HandlerRegistry>().GetBatchHandler<Payload, Handler>();
var definition = _provider.GetRequiredService<RelayerConfiguration>().Transports[0].Consumers[0];
_source = new ActivitySource("Relayer");
_listener = new ActivityListener
{
ShouldListenTo = source => Tracing != TracingMode.None && ReferenceEquals(source, _source),
Sample = static (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.None
};
ActivitySource.AddActivityListener(_listener);
_ambient = new Activity("request").Start();
_links = new ActivityLink[BatchSize];
_tags =
[
new("messaging.operation.type", "process"), new("messaging.operation.name", "process"),
new("messaging.destination.name", "source"), new("messaging.batch.message_count", BatchSize)
];
_pipeline = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService<MessageTypeRegistry>(), _serializer,
static (_, error, _) => ValueTask.FromException(error)).BuildBatch(_descriptor, definition, _source);
_message = new() { MessageId = "benchmark", MessageType = new("benchmark.batch", 1), Body = ReadOnlySequence<byte>.Empty,
Headers = Tracing != TracingMode.None ? new TraceHeaders(Tracing == TracingMode.Utf8) : null };
_contexts = new DefaultMessageContext[BatchSize];
var items = new BatchItem<Payload>[BatchSize];
for (var i = 0; i < items.Length; i++) items[i] = new(_serializer.Deserialize<Payload>(_message.Body), _directContext);
_directBatch = new(items);
}

[Benchmark(Baseline = true)]
public async ValueTask DirectScopedBatch()
{
using var activity = StartDirectActivity();
var scope = new AsyncServiceScope(_scopes.CreateScope());
try
{
_directContext.Provider = scope.ServiceProvider;
_ = scope.ServiceProvider.GetRequiredService<ISender>();
for (var i = 0; i < BatchSize; i++) _ = _serializer.Deserialize<Payload>(_message.Body);
await _descriptor.DispatchAsync(_descriptor.Resolve(scope.ServiceProvider), _directBatch, default).ConfigureAwait(false);
}
finally { await scope.DisposeAsync().ConfigureAwait(false); }
}

private Activity? StartDirectActivity()
{
if (Tracing == TracingMode.None) return null;
for (var i = 0; i < BatchSize; i++)
{
var context = MessageCreationContext.Read<MessageHeaders, CreationHeaderReader>(_message.Headers!, _headerNames);
_links[i] = new(context);
}
return _source.StartActivity("process source", ActivityKind.Consumer, Activity.Current?.Context ?? default, _tags, _links);
}

[Benchmark]
public async ValueTask ComposedBatch()
{
for (var i = 0; i < BatchSize; i++) _contexts[i] = _pipeline.RentContext(_message);
try { await _pipeline.ProcessBatchAsync(_contexts).ConfigureAwait(false); }
finally
{
for (var i = 0; i < BatchSize; i++) { _contexts[i].Dispose(); _contexts[i] = null!; }
}
}

[GlobalCleanup]
public void Cleanup()
{
_ambient.Dispose();
_listener.Dispose();
_source.Dispose();
_provider.Dispose();
}
public sealed class Options;
[Message("benchmark.batch")]
public sealed class Payload { public int Value => 42; }
public sealed class Handler : IBatchHandler<Payload>
{
public int Total { get; private set; }
public ValueTask<BatchResult> HandleAsync(Batch<Payload> batch, CancellationToken cancellationToken)
{
var total = 0;
for (var i = 0; i < batch.Count; i++) total += batch.Items[i].Message.Value;
Total = total;
return new(BatchResult.Success);
}
}
private sealed class Serializer : IMessageSerializer
{
private readonly Payload _payload = new();
public string ContentType => "benchmark/cached";
public TMessage Deserialize<TMessage>(ReadOnlySequence<byte> source) => (TMessage)(object)_payload;
public void Serialize<TMessage>(TMessage message, IBufferWriter<byte> destination) => throw new NotSupportedException();
}
public enum TracingMode { None, Text, Utf8 }

private readonly struct CreationHeaderReader : IMessageHeaderReader<MessageHeaders>
{
public static bool TryGetHeader(MessageHeaders message, string name, out WireString value) =>
message.TryGetValue(name, out value);
}

private sealed class TraceHeaders(bool utf8) : MessageHeaders
{
internal const string Parent = "00-11111111111111111111111111111111-2222222222222222-01";
private readonly WireString _parent = utf8 ? new(Encoding.UTF8.GetBytes(Parent)) : new(Parent);
public override bool TryGetValue(string name, out WireString value)
{
value = name == "traceparent" ? _parent : default;
return !value.IsEmpty;
}
}
private sealed class DirectContext : MessageContext
{
public IServiceProvider Provider { get; set; } = null!;
public override string MessageId => "benchmark";
public override MessageType MessageType => new("benchmark.batch", 1);
public override MessageHeaders Headers => MessageHeaders.Empty;
public override int Attempt => 1;
public override IServiceProvider Services => Provider;
public override MessageFeatures Features { get; } = new();
public override CancellationToken CancellationToken => default;
}
}
32 changes: 32 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D25](#d25-telemetry-follows-the-opentelemetry-messaging-span-model) | Telemetry follows the OpenTelemetry messaging span model | Accepted |
| [D26](#d26-generate-default-json-metadata-with-the-official-systemtextjson-generator) | Generate default JSON metadata with the official System.Text.Json generator | Accepted |
| [D27](#d27-configuration-declarations-are-independent-of-pipeline-execution) | Configuration declarations are independent of pipeline execution | Accepted |
| [D28](#d28-a-batch-attempt-owns-one-scope-and-one-direct-send-buffer) | A batch attempt owns one scope and one direct-send buffer | Accepted |

---

Expand Down Expand Up @@ -408,3 +409,34 @@ Refines [D8](#d8-systemtextjson-source-generation-by-default).
- Configuration can ship independently, and the receive and send pipelines consume its immutable declaration lists during composition.
- Native option objects retain their own mutability semantics. Reload updates named options, not routing or topology, and cannot silently restart a native client.
- The current core example uses the generic transport-author seam; native registration extensions arrive with their adapters.

## D28. A batch attempt owns one scope and one direct-send buffer

**Context.** Batch handlers can report per-message failures, but a scoped `ISender`
belongs to the whole handler invocation. A direct send cannot be attributed to a
successful or failed batch item without a second, implicit message context.

**Decision.**
- Compose a homogeneous generated batch handler with the consumer's existing size,
wait, and concurrency declaration. Each batch attempt uses one fresh async DI scope.
- Retry only failed items unless unattributed buffered sends fail the whole attempt.
Dispose the attempt's scope before final failure work,
direct-send flush, or publication of settlement decisions.
- Buffer direct sends for the attempt. Flush only a wholly successful attempt;
discard a wholly failed attempt's buffer. If partial success has buffered direct
sends, discard the buffer and route every item through the normal failure policy.
This bounds poison-message attempts through configured retry, redelivery and
dead-letter handling. Do not guess which item produced a send or settle an item
successfully after discarding its sends.
- Handlers that need partial success with outgoing messages use explicit durable
per-message outbox transactions. At-least-once native redelivery still applies
if later failure work or scope disposal fails.
- Native batch receive and core accumulation are explicit executors selected before
receives start. Declaring a capability or batch size never supplies an executor.

**Consequences.** Successful deliveries never settle before scope disposal and all
required durable work. Partial failure with buffered sends can retry or dead-letter
otherwise successful items; use per-message outbox transactions for independent
outcomes with outgoing messages. A failed batch call can repeat already durable work on native
redelivery, as expected for at-least-once delivery. The core does not invent native
settlement or per-message ambient sender semantics.
4 changes: 3 additions & 1 deletion src/Relayer/Handling/Batch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace Relayer;
/// <summary>A batch of messages delivered to an <see cref="IBatchHandler{TMessage}"/>.</summary>
/// <typeparam name="TMessage">The message type.</typeparam>
/// <param name="Items">The messages and their contexts, in delivery order.</param>
/// <remarks>The batch, its items and contexts are borrowed only for the handler call. Do not retain them after returning.</remarks>
public sealed record Batch<TMessage>(IReadOnlyList<BatchItem<TMessage>> Items)
{
/// <summary>The number of messages in the batch.</summary>
Expand All @@ -23,7 +24,8 @@ public sealed class BatchResult
/// <summary>Every message succeeded.</summary>
public static BatchResult Success { get; } = new(new Dictionary<int, Exception>());

/// <summary>Failures keyed by index within the batch. Only these messages enter the failure pipeline.</summary>
/// <summary>Failures keyed by index within the batch. These messages enter the failure pipeline.</summary>
/// <remarks>A partial failure with buffered direct sends fails the whole attempt because sends cannot be attributed to individual items.</remarks>
public IReadOnlyDictionary<int, Exception> Failures { get; }

/// <summary>Reports that the messages at the given indexes failed.</summary>
Expand Down
6 changes: 6 additions & 0 deletions src/Relayer/Handling/HandlerDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ public abstract class HandlerDescriptor(Type handlerType, Type messageType, bool

internal virtual ConsumeDelegate CreateConsumeDelegate(IMessageSerializer serializer)
=> throw new InvalidOperationException("A batch handler cannot be composed as a single-message consumer.");

internal virtual BatchDispatcher CreateBatchDispatcher(IMessageSerializer serializer, int size, int concurrency)
=> throw new InvalidOperationException("Select a generated batch handler when composing batch consumption.");
}

/// <summary>A generated, typed single-message dispatcher. Cache it when composing the pipeline.</summary>
Expand Down Expand Up @@ -63,4 +66,7 @@ public abstract class BatchHandlerDescriptor<TMessage>(Type handlerType)
/// <summary>Invokes the resolved handler, preserving its per-message results.</summary>
public abstract ValueTask<BatchResult> DispatchAsync(
IHandlerMarker handler, Batch<TMessage> batch, CancellationToken cancellationToken);

internal sealed override BatchDispatcher CreateBatchDispatcher(IMessageSerializer serializer, int size, int concurrency)
=> new BatchDispatcher<TMessage>(this, serializer, size, concurrency);
}
Loading
Loading