Path: redb-route/redb.Route.Redis/RedisEndpoint.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.Redis/RedisEndpoint.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; using StackExchange.Redis; namespace redb.Route.Redis; /// /// Redis endpoint. Parses the operation type and resource from the URI path. /// Manages a shared and . /// /// Path format: OPERATION:resource or OPERATION/resource. /// Example: redis:SET:user:123?ttl=300 → OperationType=SET, Resource="user:123". /// public sealed class RedisEndpoint : EndpointBase, IDisposable { private IConnectionMultiplexer? _connection; private readonly SemaphoreSlim _connectionLock = new(1, 1); /// Parsed Redis operation type. public RedisOperationType OperationType { get; } /// Resource portion of the path (key, channel, stream name, etc.). public string Resource { get; } /// Logger from the parent component. internal ILogger? Logger { get; } /// Typed options (exposed for consumer/producer). internal RedisEndpointOptions EndpointOptions => Options; /// Creates a Redis endpoint. public RedisEndpoint(EndpointUri uri, RedisComponent component, RedisEndpointOptions options) : base(uri, component, options) { Logger = component.Logger; (OperationType, Resource) = ParsePath(uri.Path); options.ResolveBatch(EndpointUri.Sanitize(uri.BaseKey), OperationType); // Apply resource to the correct option field based on operation type if (IsPubSubOperation(OperationType) && string.IsNullOrEmpty(options.Channel)) options.Channel = Resource; else if (IsStreamOperation(OperationType) && string.IsNullOrEmpty(options.StreamName)) options.StreamName = Resource; else if (string.IsNullOrEmpty(options.Key)) options.Key = Resource; } /// public override IProducer CreateProducer() => new RedisProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) { if (OperationType == RedisOperationType.XGROUP && string.IsNullOrEmpty(Options.ConsumerGroup)) throw new InvalidOperationException("ConsumerGroup is required for XGROUP consumers."); if (IsPubSubOperation(OperationType) && string.IsNullOrEmpty(Options.Channel)) throw new InvalidOperationException("Channel is required for Pub/Sub consumers."); var isStream = OperationType is RedisOperationType.XREAD or RedisOperationType.XGROUP; var hasGroup = !string.IsNullOrEmpty(Options.ConsumerGroup); if (isStream && !hasGroup && Options.StreamStartPosition == ">") throw new ArgumentException( "'streamStartPosition=>' means 'the entries not yet delivered to this consumer group', and this XREAD " + "consumer has no consumer group. Leave the position unset to read the entries added from now on, or " + "set 0 to read from the beginning."); if (Options.StreamClaimMinIdleMs is not null && !(isStream && hasGroup)) throw new ArgumentException( "'streamClaimMinIdleMs' claims pending entries of a consumer group; this consumer does not read a stream " + "through a group."); if (Options.ProcessingList is not null && OperationType is not (RedisOperationType.BLPOP or RedisOperationType.BRPOP)) throw new ArgumentException( $"'processingList' belongs to a BLPOP/BRPOP list consumer; this consumer is {OperationType}."); return new RedisConsumer(this, processor, Options); } /// Gets or creates a shared . internal async Task GetOrCreateConnectionAsync(CancellationToken ct = default) { if (_connection is { IsConnected: true }) return _connection; await _connectionLock.WaitAsync(ct).ConfigureAwait(false); try { if (_connection is { IsConnected: true }) return _connection; var config = BuildConfiguration(); _connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false); _connection.ConnectionFailed += (_, args) => Logger?.LogError("Redis connection failed: {EndPoint} - {FailureType}", args.EndPoint, args.FailureType); _connection.ConnectionRestored += (_, args) => Logger?.LogInformation("Redis connection restored: {EndPoint}", args.EndPoint); Logger?.LogInformation("Redis connection established: {Endpoints}", string.Join(", ", _connection.GetEndPoints().Select(e => e.ToString()))); return _connection; } finally { _connectionLock.Release(); } } /// Gets an from the connection. internal async Task GetDatabaseAsync(CancellationToken ct = default) { var conn = await GetOrCreateConnectionAsync(ct).ConfigureAwait(false); return conn.GetDatabase(Options.Database); } /// Gets a for Pub/Sub. internal async Task GetSubscriberAsync(CancellationToken ct = default) { var conn = await GetOrCreateConnectionAsync(ct).ConfigureAwait(false); return conn.GetSubscriber(); } /// public override async Task Stop(CancellationToken ct = default) { if (_connection is not null) { try { await _connection.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Error closing Redis connection"); } _connection.Dispose(); _connection = null; } Logger?.LogInformation("Redis endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger)); } /// public void Dispose() { _connection?.Dispose(); _connection = null; _connectionLock.Dispose(); } // ── Helpers ── private ConfigurationOptions BuildConfiguration() { // 1. Named factory from registry — a set-but-unknown name fails loud, never a // silent fallback to URI parameters. if (!string.IsNullOrEmpty(Options.ConnectionFactory)) { var context = (Component as RedisComponent)?.Context; var registryFactory = context.GetRequiredFromRegistry(Options.ConnectionFactory); Logger?.LogDebug("Redis: using ConnectionFactory '{Name}' from registry", Options.ConnectionFactory); return registryFactory.Build(); } // 2. Fallback: build from URI parameters var config = ConfigurationOptions.Parse(Options.ConnectionString); config.DefaultDatabase = Options.Database; config.AbortOnConnectFail = false; if (!string.IsNullOrEmpty(Options.Password)) config.Password = Options.Password; return config; } /// /// Parses "OPERATION:resource" or "OPERATION/resource" from the URI path. /// private static (RedisOperationType Op, string Resource) ParsePath(string path) { // Path may use : or / as separator between operation and resource // Examples: "SET:user:123", "SET/user/123", "SUBSCRIBE:notifications*" int separatorIndex = -1; // Find the first separator that splits operation from resource // The operation is always a single uppercase word (SET, GET, SUBSCRIBE, etc.) var colonIndex = path.IndexOf(':'); var slashIndex = path.IndexOf('/'); if (colonIndex > 0 && (slashIndex < 0 || colonIndex < slashIndex)) separatorIndex = colonIndex; else if (slashIndex > 0) separatorIndex = slashIndex; string operationName; string resource; if (separatorIndex > 0) { operationName = path[..separatorIndex]; resource = path[(separatorIndex + 1)..]; } else { operationName = path; resource = string.Empty; } if (!Enum.TryParse(operationName, ignoreCase: true, out var op)) throw new ArgumentException($"Unknown Redis operation: '{operationName}'. Use redis:OPERATION:resource format."); return (op, resource); } internal static bool IsPubSubOperation(RedisOperationType op) => op is RedisOperationType.PUBLISH or RedisOperationType.SUBSCRIBE or RedisOperationType.PSUBSCRIBE; internal static bool IsStreamOperation(RedisOperationType op) => op is RedisOperationType.XADD or RedisOperationType.XREAD or RedisOperationType.XGROUP; internal static bool IsListBlockingOperation(RedisOperationType op) => op is RedisOperationType.BLPOP or RedisOperationType.BRPOP; }