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 Relayer.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<Project Path="src/Relayer.AzureServiceBus.HealthChecks/Relayer.AzureServiceBus.HealthChecks.csproj" />
<Project Path="src/dotnet-relayer/dotnet-relayer.csproj" />
<Project Path="src/Relayer.AmazonSqs/Relayer.AmazonSqs.csproj" />
<Project Path="src/Relayer.AmazonSqs.HealthChecks/Relayer.AmazonSqs.HealthChecks.csproj" />
<Project Path="src/Relayer.Outbox.SqlServer/Relayer.Outbox.SqlServer.csproj" />
<Project Path="src/Relayer.RabbitMQ/Relayer.RabbitMQ.csproj" />
<Project Path="src/Relayer.RabbitMQ.HealthChecks/Relayer.RabbitMQ.HealthChecks.csproj" />
Expand Down
37 changes: 37 additions & 0 deletions benchmarks/Relayer.Benchmarks/SqsReceiveBindingBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Text;
using Amazon.Runtime;
using Amazon.SQS;
using Amazon.SQS.Model;
using BenchmarkDotNet.Attributes;
using Relayer.AmazonSqs;

namespace Relayer.Benchmarks;

/// <summary>Native string-to-UTF8 preparation compared with the pooled SQS binding.</summary>
[MemoryDiagnoser]
public class SqsReceiveBindingBenchmarks
{
private readonly Message _message = new() { Body = new string('x', 256), Attributes = new() { ["ApproximateReceiveCount"] = "1" }, MessageAttributes = [] };
private readonly byte[] _raw = new byte[256];
private AmazonSQSClient _client = null!;
private SqsDelivery _delivery = null!;
[GlobalSetup]
public void Setup()
{
_client = new(new BasicAWSCredentials("test", "test"), new AmazonSQSConfig { ServiceURL = "http://localhost", AuthenticationRegion = "us-east-1" });
_delivery = new(_client, "http://localhost/queue");
Binding();
}
[Benchmark(Baseline = true)]
public int Raw() => Encoding.UTF8.GetBytes(_message.Body, _raw);
[Benchmark]
public long Binding()
{
_delivery.Prepare(_message, TimeProvider.System.GetTimestamp(), null);
var length = SqsMessageBinding.GetBody(_delivery).Length;
_delivery.Clear();
return length;
}
[GlobalCleanup]
public void Cleanup() { _delivery.Dispose(); _client.Dispose(); }
}
12 changes: 12 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D64](#d64-sql-server-ordered-dispatch-reuses-native-locks-and-sequence-ranges) | SQL Server ordered dispatch reuses native locks and sequence ranges | Accepted |
| [D65](#d65-mysql-maintenance-uses-native-session-admission-and-existing-dispatch) | MySQL maintenance uses native session admission and existing dispatch | Accepted |
| [D66](#d66-durable-local-work-reuses-outbox-rows-and-native-postgresql-transactions) | Durable local work reuses outbox rows and native PostgreSQL transactions | Accepted |
| [D67](#d67-sqs-visibility-retries-retain-native-receive-semantics) | SQS visibility retries retain native receive semantics | Accepted |

---

Expand Down Expand Up @@ -1595,3 +1596,14 @@ in #459. They must carry row identity and claim token into each attempt and roll
Native row locks serialize deletion with competing claims. Rollback restores both business work and the row;
a successful deletion remains provisional until commit. This permits atomic completion only for work in
that same transaction, not exactly-once external effects. Existing broker dispatch and settlement are unchanged.


## D67. SQS visibility retries retain native receive semantics

**Status:** Accepted.

**Context.** AWSSDK.SQS 4.0.100.25 exposes native ReceiveMessage, ChangeMessageVisibility and DeleteMessage requests, not a consumer processor. Its [receive request](https://github.com/aws/aws-sdk-net/blob/fc1467e31596c357719f389b56100a5e7fcf8d73/sdk/src/Services/SQS/Generated/Model/ReceiveMessageRequest.g.cs) documents invisible FIFO groups; its [visibility request](https://github.com/aws/aws-sdk-net/blob/fc1467e31596c357719f389b56100a5e7fcf8d73/sdk/src/Services/SQS/Generated/Model/ChangeMessageVisibilityRequest.g.cs) cannot replace message attributes and cannot extend the original receive's twelve-hour ceiling. A replacement FIFO dispatcher, visibility renewal runtime or retry-history cache would duplicate native behavior or introduce non-durable state.

**Decision.** Thin bounded workers issue one-message native long polls and use the existing ReceivePipeline and FailurePipeline. Bodies are encoded into retained pooled UTF-8 storage; headers remain lazy native strings. SQS owns group ordering and delivery attempts; the binding derives redeliveries from native receive count plus any count on a durable copy. Visibility changes preserve existing native attributes, so history includes previously persisted errors and the current delivery's in-process errors, not exceptions from earlier visibility deliveries. This qualifies the every-attempt history guarantee for this immutable native operation. Durable poison copies reuse the existing failure pipeline before native deletion; unsupported configured delays reuse IFailureScheduler. The adapter adds no parallel broker capability.

**Consequences.** Applications must configure visibility to cover durable work. Expiration retains native duplicate-delivery semantics. Remaining visibility is checked against monotonic time captured before the receive request; repeated visibility changes do not restart the deadline. The optional health companion uses read-only queue APIs and oldest active worker timestamps. No throughput/allocation budget is relaxed.
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ dead-letter requests. See [Failure handling](https://relayer.tomlonghurst.dev/do
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.
- **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. SQS visibility retries preserve immutable native attributes: their final copy retains previously stored history and the current delivery’s in-process failures; earlier visibility-delivery exceptions are unavailable from SQS (D67).
- **Redrive API:** `IDeadLetterManager` provides `List`, `Peek`, `Redrive(filter)`, and `Purge`, backed by native broker mechanisms. Queue redrive settles an original after an acknowledged send; Kafka redrive commits a dedicated group offset after that send and leaves the original subject to native retention. Kafka purge deletes scanned partition prefixes with native `DeleteRecords`, never arbitrary records. See the [site roadmap](../website/docs/roadmap.md) for implemented transports and optional endpoint/CLI status.
- **Circuit breaker:** when the failure rate of a consumer crosses a threshold, Relayer **pauses the consumer natively** (Kafka `Pause`, ASB processor stop, RabbitMQ consumer cancel) instead of burning messages into the DLQ (SlimMessageBus #454). It then half-opens with a probe message.
- **Retries never duplicate side effects.** Outbox rows written by a failed attempt are rolled back with the transaction. Without a transaction, sends made during a failed attempt are buffered and discarded (Rebus #1198, Rebus.PostgreSql #53).
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Relayer.HealthChecks;

namespace Relayer.AmazonSqs;

/// <summary>Registers optional native health adapters without adding health dependencies to the transport.</summary>
public static class AmazonSqsHealthServiceCollectionExtensions
{
/// <summary>Registers native read-only connectivity and receiver liveness under the exact SQS transport name.</summary>
/// <remarks>Also call AddRelayerHealthChecks to register the checks. Call before starting the application host.</remarks>
public static IServiceCollection AddRelayerAmazonSqsHealthProviders(this IServiceCollection services, string name)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentException.ThrowIfNullOrWhiteSpace(name);
services.TryAddKeyedSingleton<ITransportHealthProbe>(name, (provider, _) =>
new AmazonSqsHealthProvider(provider.GetRequiredKeyedService<SqsSendTransport>(name)));
services.TryAddKeyedSingleton<IConsumerHealthProvider>(name, (provider, _) =>
new AmazonSqsHealthProvider(provider.GetRequiredKeyedService<SqsSendTransport>(name)));
if (!services.Any(descriptor => descriptor.ServiceType == typeof(HealthRegistration) && Equals(descriptor.ServiceKey, name)))
{
services.AddKeyedSingleton(name, new HealthRegistration());
services.AddSingleton<IHostedService>(provider => new AmazonSqsHealthStartup(provider, name));
}
return services;
}

private sealed class HealthRegistration;

private sealed class AmazonSqsHealthStartup(IServiceProvider provider, string name) : IHostedLifecycleService
{
public Task StartingAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
provider.GetRequiredKeyedService<SqsSendTransport>(name).EnableHealthTracking();
return Task.CompletedTask;
}
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StartedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StoppingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

private sealed class AmazonSqsHealthProvider(SqsSendTransport transport) : ITransportHealthProbe, IConsumerHealthProvider
{
public async ValueTask<HealthCheckResult> CheckAsync(CancellationToken cancellationToken)
{
try
{
await transport.CheckConnectivityAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
return HealthCheckResult.Healthy("Native SQS queues are accessible.");
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception error) { return HealthCheckResult.Unhealthy("Native SQS connectivity failed: " + error.Message, error); }
}

public ValueTask<ConsumerHealthState?> GetStateAsync(IConsumerDefinition consumer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var receiver in transport.Consumers)
{
if (!ReferenceEquals(receiver.Declaration, consumer)) continue;
var state = receiver.GetHealthState();
return ValueTask.FromResult<ConsumerHealthState?>(state is { } value ? new(value.IsIdle, value.LastProgressAt) : null);
}
return ValueTask.FromResult<ConsumerHealthState?>(null);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>Optional native connectivity and receiver liveness health adapters for Relayer.AmazonSqs.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Relayer.AmazonSqs/Relayer.AmazonSqs.csproj" />
<ProjectReference Include="../Relayer.HealthChecks/Relayer.HealthChecks.csproj" />
</ItemGroup>
</Project>
30 changes: 20 additions & 10 deletions src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,30 @@

namespace Relayer.AmazonSqs;

/// <summary>Registers named native SQS send transports.</summary>
/// <summary>Registers named native SQS transports.</summary>
public static class AmazonSqsBuilderExtensions
{
/// <summary>Declares SQS queue sending and topology. Receivers are not implemented yet; use AmazonSns for topic sending.</summary>
/// <summary>Declares native SQS sending, long-poll receivers and queue topology.</summary>
public static IRelayerBuilder AmazonSqs(this IRelayerBuilder builder, string name,
Action<TransportBuilder<AmazonSqsTransportOptions, AmazonSqsRouteOptions, AmazonSqsConsumerOptions>> configure)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(configure);
builder.AddTransport(name, configure);
builder.Services.AddSingleton<ITransport>(provider =>
builder.Services.AddKeyedSingleton<SqsSendTransport>(name, (provider, _) =>
{
var declaration = provider.GetRequiredService<RelayerConfiguration>().Transports.Single(item => item.Name == name);
if (declaration.Consumers.Count != 0)
throw new NotSupportedException($"SQS transport '{name}': receiver composition is not implemented yet.");
var options = provider.GetRequiredService<IOptionsMonitor<AmazonSqsTransportOptions>>().Get(name);
SqsSendTransport.ValidateDeclarations(name, options, declaration.Routes.Select(route => route.Destination));
foreach (var consumer in declaration.Consumers)
SqsConsumer.ValidateDeclaration(name, options, (ConsumerDefinition<AmazonSqsConsumerOptions>)consumer);
var identityHeaders = SqsSendTransport.ResolveIdentityHeaders(declaration.Routes);
var client = options.SqsClient ?? new AmazonSQSClient(options.Sqs);
return new SqsSendTransport(name, client, options.SqsClient is null, options,
provider.GetRequiredService<MessageTracing>(), provider.GetService<ILoggerFactory>(), identityHeaders);
});
builder.Services.AddSingleton<IHostedService>(provider => new SqsSendHostedService(provider, name));
builder.Services.AddSingleton<ITransport>(provider => provider.GetRequiredKeyedService<SqsSendTransport>(name));
builder.Services.AddSingleton<IHostedService>(provider => new SqsHostedService(provider, name));
return builder;
}

Expand All @@ -42,12 +43,21 @@ public static SendOptions AmazonSqs(this SendOptions options, Action<SendMessage
/// <summary>SQS route options. Native queue settings belong on the transport declaration.</summary>
public sealed class AmazonSqsRouteOptions;

/// <summary>Reserved for native receiver composition.</summary>
public sealed class AmazonSqsConsumerOptions;
/// <summary>Native long-poll request settings and durable failure handling.</summary>
public sealed class AmazonSqsConsumerOptions
{
/// <summary>CloudEvents header binding used by this queue. Match the sending route's HeaderNames.</summary>
public HeaderNames HeaderNames { get; set; } = new();
/// <summary>Configures each worker's native ReceiveMessageRequest once before polling. QueueUrl, one-message receives and all attributes are required.</summary>
public Action<ReceiveMessageRequest>? ConfigureReceive { get; set; }
/// <summary>Retry policy and explicit dead-letter copy destination. Native redrive cannot attach failure metadata.</summary>
public FailureOptions Failure { get; set; } = new();
}

// SNS uses the same simple send-only lifecycle.
internal sealed class SqsSendHostedService(IServiceProvider provider, string name) : IHostedService
{
private ITransport Transport => provider.GetServices<ITransport>().Single(transport => transport.Name == name);
public Task StartAsync(CancellationToken cancellationToken) => Transport.StartAsync(cancellationToken);
public Task StopAsync(CancellationToken cancellationToken) => Transport.StopAsync(cancellationToken);
public Task StartAsync(CancellationToken token) => Transport.StartAsync(token);
public Task StopAsync(CancellationToken token) => Transport.StopAsync(token);
}
1 change: 1 addition & 0 deletions src/Relayer.AmazonSqs/Relayer.AmazonSqs.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

<ItemGroup>
<InternalsVisibleTo Include="Relayer.Tests" />
<InternalsVisibleTo Include="Relayer.AmazonSqs.HealthChecks" />
<InternalsVisibleTo Include="Relayer.Benchmarks" />
</ItemGroup>

Expand Down
Loading
Loading