Path: redb-route/redb.Route.Sqs/SnsComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sqs/SnsComponent.cs ---- using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.Sqs; /// /// Amazon SNS transport component for redb.Route. Scheme: sns. /// Publisher: sns://my-topic?region=us-east-1 — publishes the exchange body to the topic. /// SNS has no pull consumer; consume a topic by subscribing an SQS queue to it (see /// subscribeSnsToSqs) and reading with the sqs:// connector. /// [EndpointRole(EndpointRole.Producer, Hint = "To consume an SNS topic, subscribe an SQS queue to it " + "(sns://topic?subscribeSnsToSqs=true&subscribeQueueArn=...) and read with sqs://.")] public sealed class SnsComponent : ComponentBase { /// public override string Scheme => "sns"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new SnsEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new SnsEndpoint(uri, this, options); } } /// /// SNS endpoint — owns the shared client and resolves /// the topic ARN (creating the topic on demand when autoCreateTopic=true). Producer-only. /// public sealed class SnsEndpoint : EndpointBase, IDisposable { private IAmazonSimpleNotificationService? _client; private readonly SemaphoreSlim _clientLock = new(1, 1); private string? _topicArn; private readonly SemaphoreSlim _arnLock = new(1, 1); /// Topic name parsed from the URI path. public string TopicName { get; } /// True when the topic is FIFO (the name or an explicit topic ARN ends in .fifo). public bool IsFifo => TopicName.EndsWith(".fifo", StringComparison.Ordinal) || Options.TopicArn.EndsWith(".fifo", StringComparison.Ordinal); /// Logger from the parent component. internal ILogger? Logger { get; } /// Typed options. internal SnsEndpointOptions EndpointOptions => Options; /// Creates an SNS endpoint. public SnsEndpoint(EndpointUri uri, SnsComponent component, SnsEndpointOptions options) : base(uri, component, options) { Logger = component.Logger; TopicName = uri.Path.TrimStart('/'); if (string.IsNullOrEmpty(TopicName) && string.IsNullOrEmpty(options.TopicArn)) throw new ArgumentException("SNS URI must include a topic name in the path (sns://topic-name)."); _headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy); } private readonly EndpointHeaderFilter _headerFilter; /// /// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or /// . A name the registry does not hold fails when the producer is /// built. /// internal IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(SnsHeaderFilterStrategy.Default); /// public override IProducer CreateProducer() => new SnsProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException( "SNS is publish-only — it has no pull consumer. To consume an SNS topic, subscribe an SQS " + "queue to it (sns://topic?subscribeSnsToSqs=true&subscribeQueueArn=...) and read with sqs://."); /// Gets or creates the shared client. internal async Task GetOrCreateClientAsync(CancellationToken ct = default) { if (_client is not null) return _client; await _clientLock.WaitAsync(ct).ConfigureAwait(false); try { if (_client is not null) return _client; if (!string.IsNullOrEmpty(Options.ConnectionFactory)) { // A set-but-unknown name fails loud — never a silent fallback. var context = (Component as SnsComponent)?.Context; _client = context.GetRequiredFromRegistry(Options.ConnectionFactory).BuildSns(); } else { var config = new AmazonSimpleNotificationServiceConfig(); AwsClientSupport.ApplyCommonConfig(config, Options); _client = new AmazonSimpleNotificationServiceClient(AwsClientSupport.ResolveCredentials(Options), config); } var (region, serviceUrl) = AwsClientSupport.Target(_client.Config); Logger?.LogInformation("SNS client created: Region={Region}, ServiceUrl={ServiceUrl}, Topic={Topic}, ConnectionFactory={ConnectionFactory}", region, serviceUrl, TopicName, string.IsNullOrEmpty(Options.ConnectionFactory) ? "-" : Options.ConnectionFactory); return _client; } finally { _clientLock.Release(); } } /// Resolves (and caches) the topic ARN, creating the topic first when autoCreateTopic=true. internal async Task GetTopicArnAsync(CancellationToken ct = default) { if (_topicArn is not null) return _topicArn; await _arnLock.WaitAsync(ct).ConfigureAwait(false); try { if (_topicArn is not null) return _topicArn; if (!string.IsNullOrEmpty(Options.TopicArn)) return _topicArn = Options.TopicArn; var client = await GetOrCreateClientAsync(ct).ConfigureAwait(false); if (Options.AutoCreateTopic) { var request = new CreateTopicRequest { Name = TopicName }; if (IsFifo) { // AWS SDK v4 does not initialize request collections — assign the dictionary. request.Attributes = new Dictionary { ["FifoTopic"] = "true", ["ContentBasedDeduplication"] = "true", }; } var created = await client.CreateTopicAsync(request, ct).ConfigureAwait(false); return _topicArn = created.TopicArn; } // No ARN and no auto-create: build the conventional ARN is not reliable — require an explicit ARN. throw new InvalidOperationException( $"SNS topic ARN unknown for '{TopicName}'. Set topicArn=... or autoCreateTopic=true."); } finally { _arnLock.Release(); } } /// public override async Task Stop(CancellationToken ct = default) { if (_client is not null) { try { _client.Dispose(); } catch (Exception ex) { Logger?.LogWarning(ex, "Error disposing SNS client"); } _client = null; } Logger?.LogInformation("SNS endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger)); await Task.CompletedTask.ConfigureAwait(false); } /// public void Dispose() { _client?.Dispose(); _client = null; _clientLock.Dispose(); _arnLock.Dispose(); } }