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
14 changes: 12 additions & 2 deletions benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class BatchConsumePipelineBenchmarks
private ServiceProvider _provider = null!;
private IServiceScopeFactory _scopes = null!;
private ConsumePipeline _pipeline = null!;
private Handler _handler = null!;
private BatchHandlerDescriptor<Payload> _descriptor = null!;
private readonly Serializer _serializer = new();
private readonly DirectContext _directContext = new();
Expand Down Expand Up @@ -48,6 +49,7 @@ public void Setup()
});
_provider = services.BuildServiceProvider();
_scopes = _provider.GetRequiredService<IServiceScopeFactory>();
_handler = _provider.GetRequiredService<Handler>();
_descriptor = _provider.GetRequiredService<HandlerRegistry>().GetBatchHandler<Payload, Handler>();
var definition = _provider.GetRequiredService<RelayerConfiguration>().Transports[0].Consumers[0];
_source = new ActivitySource("Relayer");
Expand Down Expand Up @@ -101,8 +103,11 @@ public async ValueTask DirectScopedBatch()
}

[Benchmark]
public async ValueTask ComposedBatch()
[Arguments(false)]
[Arguments(true)]
public async ValueTask ComposedBatch(bool manualCompletion)
{
_handler.ManualCompletion = manualCompletion;
for (var i = 0; i < BatchSize; i++) _contexts[i] = _pipeline.RentContext(_message);
try { await _pipeline.ProcessBatchAsync(_contexts).ConfigureAwait(false); }
finally
Expand All @@ -125,10 +130,15 @@ public sealed class Payload { public int Value => 42; }
public sealed class Handler : IBatchHandler<Payload>
{
public int Total { get; private set; }
public bool ManualCompletion { get; 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;
for (var i = 0; i < batch.Count; i++)
{
total += batch.Items[i].Message.Value;
if (ManualCompletion) batch.Items[i].Context.Features.GetRequired<ISettlementFeature>().Complete();
}
Total = total;
return new(BatchResult.Success);
}
Expand Down
19 changes: 19 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 _manualFailures = null!;
private ConsumePipeline _instrumentedFailures = null!;
private HandlerDescriptor<Payload> _descriptor = null!;
private readonly DirectContext _direct = new();
Expand Down Expand Up @@ -45,6 +46,8 @@ 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);
_manualFailures = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService<MessageTypeRegistry>(), _serializer,
policy).Handler(_descriptor).Use(new CompleteMiddleware()).Build(1);
var telemetry = _provider.GetRequiredService<RelayerInstrumentation>().CreateEndpoint(new()
{
System = "relayer.inmemory", Destination = "source",
Expand Down Expand Up @@ -88,6 +91,22 @@ public async ValueTask ExecutableFailurePipelineWithTelemetry()
await _instrumentedFailures.ProcessAsync(context).ConfigureAwait(false);
}

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

private sealed class CompleteMiddleware : IConsumeMiddleware
{
public ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next)
{
context.Features.GetRequired<ISettlementFeature>().Complete();
return next(context);
}
}

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

Expand Down
5 changes: 5 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ To change a decision, add a new entry that supersedes it rather than editing his
**Decision.**
- Settlement is automatic by default.
- `ISettlementFeature` allows `DeadLetter(reason)`, `Retry(delay)`, and `Complete()` to be requested from a handler.
- Requests are deferred until handling, middleware and async scope disposal succeed. `Complete` also waits for buffered sends. A handler or middleware exception cancels the request and follows the normal failure policy; cancellation, disposal errors, flush errors and fallback errors propagate without settlement.
- One request is allowed per attempt; another request throws. Immediate retries and pooled deliveries start with no request.
- `Retry(delay)` requests a new delivery with the exact delay, without jitter or the exception policy's in-process retries. It uses native redelivery, scheduled copy, then durable scheduler in capability order. Unsupported runtime delays fail at the request call. `Retry` and `DeadLetter` discard buffered direct sends; applications remain responsible for transactional rollback and native side effects.
- Batch requests are per item. Reported failures override the corresponding requests, and a thrown batch exception overrides all requests. Mixed completing/non-completing outcomes with shared buffered sends fail the entire attempt because sends cannot be attributed to individual items.
- Manual outcomes preserve prior exception history without creating a fictitious exception. A dead-letter copy carries the reason in `FailureHeaders.DeadLetterReason` (`relayer.dead_letter.reason`).
- Native extras, such as ASB `Defer`, are reached through the transport feature.

## D12. Outbox dispatch: direct for unordered, lane leases for ordered
Expand Down
5 changes: 5 additions & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,11 @@ Fallback exceptions, timeouts, cancellation, scope-disposal errors and flush fai
settlement decision. The native adapter must retain or release the delivery using its own failure semantics.
Copies remain at-least-once: a crash between the copy and completion can duplicate it (D24).

Manual settlement requests follow D11: the pooled `ISettlementFeature` queues an outcome for a successful
attempt, while exceptions override it. The same durable fallback executors resolve manual retry and
dead-letter requests. See [Failure handling](https://relayer.tomlonghurst.dev/docs/guides/failure-handling#manual-settlement)
for the call site, precedence and buffered-send contract.


- **Error metadata** goes on the dead-lettered message: the original message ID, exception type, message and stack trace for **every** attempt (Rebus #1154), attempt count, first and last failure time, consumer name, and host.
- **Redrive API:** `IDeadLetterManager` provides `List`, `Peek`, `Redrive(filter)`, and `Purge`. It is backed natively by the ASB DLQ, SQS redrive, RabbitMQ DLX queue, or Kafka DLT topic. It is also exposed as an optional minimal-API endpoint group and as CLI commands.
Expand Down
18 changes: 18 additions & 0 deletions src/Relayer/Failures/FailureMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public static class FailureHeaders
public const string Redeliveries = "relayer.failure.redeliveries";
/// <summary>JSON error history, including original identity, location and every attempt's exception.</summary>
public const string History = "relayer.failure.history";
/// <summary>The handler's reason when manual dead-lettering requires a durable copy.</summary>
public const string DeadLetterReason = "relayer.dead_letter.reason";
}

internal sealed class FailureHistory
Expand Down Expand Up @@ -88,6 +90,22 @@ internal static void Record(DefaultMessageContext context, Exception error, stri
});
}

internal static KeyValuePair<string, WireString>[] SettlementHeaders(DefaultMessageContext context, int redeliveries,
string? reason = null)
{
var headers = new List<KeyValuePair<string, WireString>>(4)
{
new(FailureHeaders.Attempts, new(context.Attempt.ToString(CultureInfo.InvariantCulture))),
new(FailureHeaders.Redeliveries, new(redeliveries.ToString(CultureInfo.InvariantCulture))),
};
if (context.FailureHistory is { } history)
headers.Add(new(FailureHeaders.History, new(JsonSerializer.Serialize(history, FailureJsonContext.Default.FailureHistory))));
else if (context.Headers.TryGetValue(FailureHeaders.History, out var prior))
headers.Add(new(FailureHeaders.History, prior));
if (reason is not null) headers.Add(new(FailureHeaders.DeadLetterReason, new(reason)));
return headers.ToArray();
}

internal static KeyValuePair<string, WireString>[] Headers(DefaultMessageContext context, int redeliveries)
=> [new(FailureHeaders.Attempts, new(context.Attempt.ToString(CultureInfo.InvariantCulture))),
new(FailureHeaders.Redeliveries, new(redeliveries.ToString(CultureInfo.InvariantCulture))),
Expand Down
72 changes: 59 additions & 13 deletions src/Relayer/Failures/FailurePipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public sealed class FailurePipeline
private readonly TimeProvider _time;
private readonly RedeliveryPath[] _paths;
private readonly bool _nativeDeadLetter;
private readonly TransportCapabilities _capabilities;

/// <summary>Validates native paths and available fallback executors for this consumer's complete policy.</summary>
public FailurePipeline(IServiceProvider services, string transportName, string source, string consumer,
Expand Down Expand Up @@ -65,6 +66,7 @@ public FailurePipeline(IServiceProvider services, string transportName, string s
var capabilities = validator.GetCapabilities(_transport, source);
if (failures.Count != 0) throw new InvalidOperationException(string.Join(Environment.NewLine, failures));
if (capabilities is null) throw Invalid("TransportCapabilities", "Return a valid endpoint capability declaration.");
_capabilities = capabilities;
_nativeDeadLetter = capabilities.DeadLetter;
if (!_nativeDeadLetter)
{
Expand All @@ -73,18 +75,7 @@ public FailurePipeline(IServiceProvider services, string transportName, string s
validator.GetCapabilities(_transport, _options.DeadLetterEndpoint);
}
_paths = new RedeliveryPath[_redeliveries.Length];
for (var i = 0; i < _paths.Length; i++)
{
var delay = _redeliveries[i];
if (capabilities.MaxRedeliveryDelay is { } native && delay <= native)
_paths[i] = RedeliveryPath.Native;
else if (copy is not null && capabilities.MaxDeliveryDelay is { } scheduled && delay <= scheduled)
_paths[i] = RedeliveryPath.Copy;
else if (copy is not null && scheduler is not null)
_paths[i] = RedeliveryPath.Outbox;
else
throw Invalid("MaxRedeliveryDelay/MaxDeliveryDelay", $"Delay {delay} has no executor. Shorten the delay, enable native redelivery/scheduling, or configure a message copy executor and durable IFailureScheduler.");
}
for (var i = 0; i < _paths.Length; i++) _paths[i] = ResolveRedelivery(_redeliveries[i]);
if (failures.Count != 0) throw new InvalidOperationException(string.Join(Environment.NewLine, failures));
// Compose direct-send routes before receives can resolve their scoped sender.
services.GetRequiredService<SenderPool>().Enable();
Expand All @@ -93,6 +84,52 @@ public FailurePipeline(IServiceProvider services, string transportName, string s
$"Consumer '{consumer}' from '{source}' on transport '{transportName}': {capability} is unavailable. {remedy}");
}

internal void ValidateSettlement(Disposition disposition)
{
if (disposition.Kind == DispositionKind.Redeliver) ResolveRedelivery(disposition.Delay);
}

private RedeliveryPath ResolveRedelivery(TimeSpan delay)
{
if (delay > DateTimeOffset.MaxValue - _time.GetUtcNow())
throw new ArgumentOutOfRangeException(nameof(delay), "The retry delay must fit a delivery timestamp.");
if (_capabilities.MaxRedeliveryDelay is { } native && delay <= native) return RedeliveryPath.Native;
if (_copy is not null && _capabilities.MaxDeliveryDelay is { } scheduled && delay <= scheduled) return RedeliveryPath.Copy;
if (_copy is not null && _scheduler is not null) return RedeliveryPath.Outbox;
throw new InvalidOperationException($"Consumer '{_consumer}' from '{_source}' on transport '{_transport.Name}': redelivery delay {delay} has no executor. Shorten the delay, enable native redelivery/scheduling, or configure a message copy executor and durable IFailureScheduler.");
}

[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
internal async ValueTask HandleSettlementAsync(DefaultMessageContext context, Disposition request)
{
context.CancellationToken.ThrowIfCancellationRequested();
if (request.Kind == DispositionKind.Redeliver)
{
var path = ResolveRedelivery(request.Delay);
// A manual retry is not an exception. Preserve prior error history without inventing a failure.
var headers = FailureMetadata.SettlementHeaders(context, checked(context.Redeliveries + 1));
if (path == RedeliveryPath.Native)
context.FailureDisposition = Disposition.Redeliver(request.Delay, headers);
else
{
await CopyAsync(context, _source, _time.GetUtcNow() + request.Delay, headers,
path == RedeliveryPath.Outbox).ConfigureAwait(false);
context.FailureDisposition = Disposition.Complete;
}
}
else
{
var headers = FailureMetadata.SettlementHeaders(context, context.Redeliveries, request.DeadLetter.Reason);
if (_nativeDeadLetter)
context.FailureDisposition = Disposition.DeadLettered(new(request.DeadLetter.Reason, headers: headers));
else
{
await CopyAsync(context, _options.DeadLetterEndpoint!, null, headers, false).ConfigureAwait(false);
context.FailureDisposition = Disposition.Complete;
}
}
}

internal void Record(DefaultMessageContext context, Exception error) => FailureMetadata.Record(context, error, _consumer, _time);
internal bool CanRetry(int retry) => retry < _retries.Length;
internal ValueTask WaitRetryAsync(int retry, CancellationToken cancellationToken)
Expand Down Expand Up @@ -145,7 +182,16 @@ private async ValueTask CopyAsync(DefaultMessageContext context, string destinat
var original = _copy!(context);
var headers = new List<KeyValuePair<string, WireString>>(original.Headers.Length + metadata.Length);
foreach (var header in original.Headers.Span)
if (header.Key is not (FailureHeaders.Attempts or FailureHeaders.Redeliveries or FailureHeaders.History)) headers.Add(header);
{
var replaced = false;
foreach (var replacement in metadata)
{
if (header.Key != replacement.Key) continue;
replaced = true;
break;
}
if (!replaced) headers.Add(header);
}
headers.AddRange(metadata);
var copy = original.Forward(destination, headers.ToArray(), deliverAt);
if (schedule) copy.ValidateForOutbox();
Expand Down
11 changes: 8 additions & 3 deletions src/Relayer/Failures/Failures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,18 @@ public interface IFailureClassifier
FailureAction Classify(Exception exception, MessageContext context);
}

/// <summary>Lets a handler settle a message manually (docs/decisions.md D11).</summary>
/// <summary>Requests a settlement outcome after successful handling (docs/decisions.md D11).</summary>
/// <remarks>
/// Get from MessageContext.Features. One request is allowed per attempt. A handler or middleware exception
/// overrides the request; cancellation, scope disposal and durable-write failures prevent settlement.
/// Do not retain this pooled feature beyond processing. Native settlement is deferred until durable work succeeds.
/// </remarks>
public interface ISettlementFeature
{
/// <summary>Completes the message.</summary>
/// <summary>Requests completion after successful handling and durable sends.</summary>
void Complete();

/// <summary>Requests redelivery after <paramref name="delay"/>.</summary>
/// <summary>Requests redelivery after the exact non-negative <paramref name="delay"/>, without in-process retries or jitter.</summary>
void Retry(TimeSpan delay);

/// <summary>Dead-letters the message with a reason.</summary>
Expand Down
23 changes: 23 additions & 0 deletions src/Relayer/Failures/PendingSettlement.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Relayer;

// One instance per pooled context. Requests describe an outcome; they never settle native deliveries inline.
internal sealed class PendingSettlement(DefaultMessageContext context, ConsumePipeline owner) : ISettlementFeature
{
internal Disposition? Request { get; private set; }

public void Complete() => Set(Disposition.Complete);
public void Retry(TimeSpan delay) => Set(Disposition.Redeliver(delay));
public void DeadLetter(string reason) => Set(Disposition.DeadLettered(new(reason)));

private void Set(Disposition disposition)
{
if (!context.CanRequestSettlement)
throw new InvalidOperationException("Settlement can be requested only during message handling and scope disposal.");
if (Request is not null)
throw new InvalidOperationException("Only one settlement request is allowed per processing attempt.");
owner.ValidateSettlement(disposition);
Request = disposition;
}

internal void Clear() => Request = null;
}
Loading
Loading