Bundle: redb-route / redb.Route.Redis (redb.Route.Redis.txt), 15 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Redis/AssemblyInfo.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/AssemblyInfo.cs ---- // redb_Route_Redis - placeholder for build Path: redb-route/redb.Route.Redis/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; namespace redb.Route.Redis; /// /// Extension methods for registering the Redis transport in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers the in the route context so that /// redis: URIs are resolved. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteRedis(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteRedis(this IServiceCollection services) { // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteComponent(); return services; } } Path: redb-route/redb.Route.Redis/Fluent/RedisDsl.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/Fluent/RedisDsl.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Redis; /// /// Fluent API for Redis endpoints. /// /// // Key-value /// .To(Redis.Set("user:123").Connection("redis-server:6379").Ttl(300)) /// .From(Redis.Subscribe("events.*").UsePattern()) /// /// // Streams /// .From(Redis.XRead("order-stream").ConsumerGroup("workers").ConsumerName("w1")) /// .To(Redis.XAdd("audit-stream").StreamMaxLength(10000)) /// /// // Generic operation /// .To(Redis.Command("LPUSH", "task-queue")) /// /// public static class Redis { // ── Key-Value ───────────────────────────────────────────────────── /// SET key to a value. public static RedisBuilder Set(string key) => new("SET", key); /// GET value by key. public static RedisBuilder Get(string key) => new("GET", key); /// DEL — delete a key. public static RedisBuilder Del(string key) => new("DEL", key); /// EXISTS — check if key exists. public static RedisBuilder Exists(string key) => new("EXISTS", key); /// EXPIRE — set TTL on a key. public static RedisBuilder Expire(string key) => new("EXPIRE", key); /// INCR — increment a key. public static RedisBuilder Incr(string key) => new("INCR", key); /// DECR — decrement a key. public static RedisBuilder Decr(string key) => new("DECR", key); /// SETNX — set value only if key does not exist. public static RedisBuilder SetNx(string key) => new("SETNX", key); // ── Pub/Sub ─────────────────────────────────────────────────────── /// PUBLISH messages to a channel. public static RedisBuilder Publish(string channel) => new("PUBLISH", channel); /// SUBSCRIBE to a channel (consumer). public static RedisBuilder Subscribe(string channel) => new("SUBSCRIBE", channel); /// PSUBSCRIBE to a pattern (consumer). public static RedisBuilder PSubscribe(string pattern) => new("PSUBSCRIBE", pattern); // ── Streams ─────────────────────────────────────────────────────── /// XADD — write to a stream. public static RedisBuilder XAdd(string stream) => new("XADD", stream); /// XREAD — read from a stream (consumer). public static RedisBuilder XRead(string stream) => new("XREAD", stream); /// XGROUP — manage consumer groups. public static RedisBuilder XGroup(string stream) => new("XGROUP", stream); // ── Lists ───────────────────────────────────────────────────────── /// LPUSH — push to head of list. public static RedisBuilder LPush(string key) => new("LPUSH", key); /// RPUSH — push to tail of list. public static RedisBuilder RPush(string key) => new("RPUSH", key); /// LPOP — pop from head of list. public static RedisBuilder LPop(string key) => new("LPOP", key); /// RPOP — pop from tail of list. public static RedisBuilder RPop(string key) => new("RPOP", key); /// LLEN — get list length. public static RedisBuilder LLen(string key) => new("LLEN", key); /// LRANGE — get range from list. public static RedisBuilder LRange(string key) => new("LRANGE", key); // ── Generic ─────────────────────────────────────────────────────── /// Any Redis operation by name. public static RedisBuilder Command(string operation, string key) => new(operation, key); } /// /// Fluent builder for Redis endpoint URIs. /// public sealed class RedisBuilder { private readonly string _operation; private readonly string _resource; // Connection private string? _connectionString; private string? _database; private string? _password; private string? _connectionFactory; // Common private string? _ttl; private bool _usePattern; private bool? _transacted; private string? _pollDelayMs; private string? _command; // Sorted set private string? _score; private string? _minScore; private string? _maxScore; // Hash private string? _field; // Range private string? _start; private string? _stop; // Geo private string? _longitude; private string? _latitude; private string? _member1; private string? _member2; private string? _geoUnit; // Bit private string? _offset; private bool? _bit; // Stream private string? _consumerGroup; private string? _consumerName; private string? _streamMaxLength; private bool? _streamApproximate; private string? _streamReadCount; private bool _batching; private int? _maxBatchMessages; private int? _pollTimeoutMs; private int? _batchingIntervalMs; private string? _streamBlockTimeMs; private AckMode? _ackMode; private string? _streamClaimMinIdleMs; private string? _processingList; private string? _streamStartPosition; internal RedisBuilder(string operation, string resource) { _operation = operation; _resource = resource; } // ── Connection ──────────────────────────────────────────────────── /// Redis connection string. Default "localhost:6379". public RedisBuilder Connection(IExpression connectionString) { _connectionString = connectionString.ToTemplateString(); return this; } /// Redis connection string (template string, supports ${...}). Default "localhost:6379". public RedisBuilder Connection(string connectionString) { _connectionString = connectionString; return this; } /// Database number. Default 0. public RedisBuilder Database(int db) { _database = db.ToString(); return this; } /// Database number from an expression. public RedisBuilder Database(IExpression db) { _database = db.ToTemplateString(); return this; } /// Redis password. public RedisBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; } /// Redis password (template string, supports ${...}). public RedisBuilder Password(string password) { _password = password; return this; } /// Use a named connection factory registered in DI. public RedisBuilder ConnectionFactory(IExpression name) { _connectionFactory = name.ToTemplateString(); return this; } /// Use a named connection factory registered in DI (template string, supports ${...}). public RedisBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } // ── Common ──────────────────────────────────────────────────────── /// TTL for SET operations in seconds. Default 0 (no expiry). public RedisBuilder Ttl(int seconds) { _ttl = seconds.ToString(); return this; } /// TTL from an expression. public RedisBuilder Ttl(IExpression seconds) { _ttl = seconds.ToTemplateString(); return this; } /// Use pattern matching for SUBSCRIBE/key operations. public RedisBuilder UsePattern() { _usePattern = true; return this; } /// Defers the operation to the commit of the enclosing .Transacted() block (transacted=true). public RedisBuilder Transacted() { _transacted = true; return this; } /// /// Sets transacted explicitly. false makes PUBLISH and XADD go out at once even inside a /// .Transacted() block; left unset, they follow the block and every other write runs at once. /// public RedisBuilder Transacted(bool value) { _transacted = value; return this; } /// Poll delay for consumer operations in milliseconds. Default 1000. public RedisBuilder PollDelay(int ms) { _pollDelayMs = ms.ToString(); return this; } /// Poll delay from an expression. public RedisBuilder PollDelay(IExpression ms) { _pollDelayMs = ms.ToTemplateString(); return this; } /// Custom Redis command string. public RedisBuilder CustomCommand(string cmd) { _command = cmd; return this; } // ── Sorted Set ──────────────────────────────────────────────────── /// Score for sorted set operations. public RedisBuilder Score(double score) { _score = score.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Score from an expression. public RedisBuilder Score(IExpression score) { _score = score.ToTemplateString(); return this; } /// Min score for range queries. public RedisBuilder MinScore(double min) { _minScore = min.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Min score from an expression. public RedisBuilder MinScore(IExpression min) { _minScore = min.ToTemplateString(); return this; } /// Max score for range queries. public RedisBuilder MaxScore(double max) { _maxScore = max.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Max score from an expression. public RedisBuilder MaxScore(IExpression max) { _maxScore = max.ToTemplateString(); return this; } // ── Hash ────────────────────────────────────────────────────────── /// Hash field name. public RedisBuilder Field(IExpression field) { _field = field.ToTemplateString(); return this; } /// Hash field name (template string, supports ${...}). public RedisBuilder Field(string field) { _field = field; return this; } // ── Range ───────────────────────────────────────────────────────── /// Start index for list/range operations. public RedisBuilder Start(long start) { _start = start.ToString(); return this; } /// Start index from an expression. public RedisBuilder Start(IExpression start) { _start = start.ToTemplateString(); return this; } /// Stop index for list/range operations. public RedisBuilder Stop(long stop) { _stop = stop.ToString(); return this; } /// Stop index from an expression. public RedisBuilder Stop(IExpression stop) { _stop = stop.ToTemplateString(); return this; } // ── Geo ─────────────────────────────────────────────────────────── /// Longitude for geo operations. public RedisBuilder Longitude(double lon) { _longitude = lon.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Longitude from an expression. public RedisBuilder Longitude(IExpression lon) { _longitude = lon.ToTemplateString(); return this; } /// Latitude for geo operations. public RedisBuilder Latitude(double lat) { _latitude = lat.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Latitude from an expression. public RedisBuilder Latitude(IExpression lat) { _latitude = lat.ToTemplateString(); return this; } /// First member for geo distance. public RedisBuilder Member1(IExpression member) { _member1 = member.ToTemplateString(); return this; } /// First member for geo distance (template string, supports ${...}). public RedisBuilder Member1(string member) { _member1 = member; return this; } /// Second member for geo distance. public RedisBuilder Member2(IExpression member) { _member2 = member.ToTemplateString(); return this; } /// Second member for geo distance (template string, supports ${...}). public RedisBuilder Member2(string member) { _member2 = member; return this; } /// Geo distance unit: m, km, mi, ft. Default "m". public RedisBuilder GeoUnit(string unit) { _geoUnit = unit; return this; } // ── Bit ─────────────────────────────────────────────────────────── /// Bit offset for GETBIT/SETBIT. public RedisBuilder Offset(long offset) { _offset = offset.ToString(); return this; } /// Bit offset from an expression. public RedisBuilder Offset(IExpression offset) { _offset = offset.ToTemplateString(); return this; } /// Bit value for SETBIT. public RedisBuilder Bit(bool value) { _bit = value; return this; } // ── Stream ──────────────────────────────────────────────────────── /// Consumer group name for stream operations. public RedisBuilder ConsumerGroup(IExpression group) { _consumerGroup = group.ToTemplateString(); return this; } /// Consumer group name for stream operations (template string, supports ${...}). public RedisBuilder ConsumerGroup(string group) { _consumerGroup = group; return this; } /// Consumer name within the group. public RedisBuilder ConsumerName(IExpression name) { _consumerName = name.ToTemplateString(); return this; } /// Consumer name within the group (template string, supports ${...}). public RedisBuilder ConsumerName(string name) { _consumerName = name; return this; } /// Max stream length (XADD with MAXLEN). Default 0 (unlimited). public RedisBuilder StreamMaxLength(int max) { _streamMaxLength = max.ToString(); return this; } /// Max stream length from an expression. public RedisBuilder StreamMaxLength(IExpression max) { _streamMaxLength = max.ToTemplateString(); return this; } /// Approximate MAXLEN trimming. Default true. public RedisBuilder StreamApproximate(bool approx = true) { _streamApproximate = approx; return this; } /// Number of entries to read per XREAD. Default 10. public RedisBuilder StreamReadCount(int count) { _streamReadCount = count.ToString(); return this; } /// Stream read count from an expression. public RedisBuilder StreamReadCount(IExpression count) { _streamReadCount = count.ToTemplateString(); return this; } /// Stream batch mode (batching=true): the route gets the entries as a List<IMessage>. public RedisBuilder Batching() { _batching = true; return this; } /// Largest number of entries in a batch (maxBatchMessages, default streamReadCount). public RedisBuilder MaxBatchMessages(int max) { _maxBatchMessages = max; return this; } /// Batch mode: the idle timeout in milliseconds, restarted by every entry (pollTimeoutMs, default 1000). public RedisBuilder PollTimeoutMs(int ms) { _pollTimeoutMs = ms; return this; } /// Batch mode: the hard limit in milliseconds since a batch's first entry (batchingIntervalMs). public RedisBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms; return this; } /// Block time in milliseconds for XREAD. Default 1000. public RedisBuilder StreamBlockTime(int ms) { _streamBlockTimeMs = ms.ToString(); return this; } /// Stream block time from an expression. public RedisBuilder StreamBlockTime(IExpression ms) { _streamBlockTimeMs = ms.ToTemplateString(); return this; } /// /// When a group consumer settles a stream entry: after the route succeeded (, /// default, at-least-once) or on read with NOACK (, at-most-once). /// public RedisBuilder AckMode(AckMode mode) { _ackMode = mode; return this; } /// /// A group consumer claims entries of its group pending for at least milliseconds (a failed /// one, or one a dead consumer left) and processes them again. Must exceed the longest time a route takes. /// public RedisBuilder StreamClaimMinIdle(int ms) { _streamClaimMinIdleMs = ms.ToString(); return this; } /// /// Where a stream consumer starts: unset, at the entries added from now on; "0" from the beginning; an entry id after /// it. ">" only with a consumer group. /// public RedisBuilder StreamStartPosition(string position) { _streamStartPosition = position; return this; } /// /// A BLPOP/BRPOP consumer moves each item into while its route runs and removes it after /// success; a failed item goes back to the queue, and a previous run's leftovers are returned at start /// (at-least-once). One consumer per processing list. /// public RedisBuilder ProcessingList(string key) { _processingList = key; return this; } // ── Build ───────────────────────────────────────────────────────── /// Builds the Redis endpoint URI string. public string Build() { var sb = new StringBuilder(); sb.Append("redis:"); sb.Append(_operation); sb.Append(':'); sb.Append(_resource); var sep = '?'; void Append(string key, string value) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } void AppendIf(string key, string? value) { if (value != null) Append(key, value); } void AppendBool(string key, bool value) { if (value) Append(key, "true"); } void AppendBoolExplicit(string key, bool? value) { if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant()); } // Connection AppendIf("connectionString", _connectionString); AppendIf("database", _database); AppendIf("password", _password); AppendIf("connectionFactory", _connectionFactory); // Common AppendIf("ttl", _ttl); AppendBool("usePattern", _usePattern); AppendBoolExplicit("transacted", _transacted); AppendIf("pollDelayMs", _pollDelayMs); AppendIf("command", _command); // Sorted set AppendIf("score", _score); AppendIf("minScore", _minScore); AppendIf("maxScore", _maxScore); // Hash AppendIf("field", _field); // Range AppendIf("start", _start); AppendIf("stop", _stop); // Geo AppendIf("longitude", _longitude); AppendIf("latitude", _latitude); AppendIf("member1", _member1); AppendIf("member2", _member2); AppendIf("geoUnit", _geoUnit); // Bit AppendIf("offset", _offset); AppendBoolExplicit("bit", _bit); // Stream AppendIf("consumerGroup", _consumerGroup); AppendIf("consumerName", _consumerName); AppendIf("streamMaxLength", _streamMaxLength); AppendBoolExplicit("streamApproximate", _streamApproximate); AppendIf("streamReadCount", _streamReadCount); if (_batching) AppendIf("batching", "true"); AppendIf("maxBatchMessages", _maxBatchMessages?.ToString()); AppendIf("pollTimeoutMs", _pollTimeoutMs?.ToString()); AppendIf("batchingIntervalMs", _batchingIntervalMs?.ToString()); AppendIf("streamBlockTimeMs", _streamBlockTimeMs); AppendIf("ackMode", _ackMode?.ToString().ToLowerInvariant()); AppendIf("streamClaimMinIdleMs", _streamClaimMinIdleMs); AppendIf("processingList", _processingList); AppendIf("streamStartPosition", _streamStartPosition); return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(RedisBuilder b) => b.Build(); /// public override string ToString() => Build(); } Path: redb-route/redb.Route.Redis/README.md 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/README.md ---- # redb.Route.Redis > Documentation and articles: Redis transport for redb.Route. Pub/Sub, Streams, key-value, lists, sorted sets — every Redis data structure is reachable as an endpoint URI via StackExchange.Redis; the builder has factories for keys, Pub/Sub, streams and lists, and `Redis.Command(operation, key)` for the rest. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Redis?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Redis) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Redis ``` ## Usage ### URI Format ``` redis:OPERATION:resource?connectionString=localhost:6379&... ``` The operation is the first path segment (`SET`, `GET`, `PUBLISH`, `SUBSCRIBE`, `XADD`, `XREAD`, `BLPOP`, …), the resource — key, channel or stream — follows it: `redis:SET:session:42?ttl=300`, `redis:SUBSCRIBE:notifications`. `redis:SET/session/42` works too. A parameter the endpoint cannot read (a misspelt option, a value of the wrong type) is refused by name when the endpoint is created. ### Fluent DSL ```csharp using redb.Route.Redis; // Pub/Sub — subscribe From(Redis.Subscribe("notifications").Connection("localhost:6379")) .Log("Received: ${body}") .To("direct://process"); // Pub/Sub — publish From("direct://outbound") .To(Redis.Publish("events").Connection("localhost:6379")); // Streams — consumer group From(Redis.XRead("order-stream") .Connection("localhost:6379") .ConsumerGroup("processors") .ConsumerName("node-1") .StreamReadCount(100)) .To("direct://handle"); // Key-Value From("direct://cache") .To(Redis.Set("session:user-123") .Connection("localhost:6379") .Ttl(3600)); // Lists From("direct://enqueue") .To(Redis.LPush("task-queue").Connection("localhost:6379")); ``` ## Fluent Builder API | Category | Methods | |----------|---------| | **Connection** | `.Connection()`, `.Database()`, `.Password()`, `.ConnectionFactory()` | | **Key-Value** | `Redis.Set()`, `Redis.Get()`, `Redis.Del()`, `Redis.Exists()`, `Redis.Expire()`, `Redis.Incr()`, `Redis.Decr()`, `Redis.SetNx()` | | **Pub/Sub** | `Redis.Publish()`, `Redis.Subscribe()`, `Redis.PSubscribe()` | | **Streams** | `Redis.XAdd()`, `Redis.XRead()`, `Redis.XGroup()`, `.ConsumerGroup()`, `.ConsumerName()`, `.StreamMaxLength()`, `.StreamReadCount()`, `.StreamBlockTime()`, `.StreamStartPosition()`, `.AckMode()`, `.StreamClaimMinIdle()`, `.Batching()`, `.MaxBatchMessages()`, `.PollTimeoutMs()`, `.BatchingIntervalMs()` | | **Lists** | `Redis.LPush()`, `Redis.RPush()`, `Redis.LPop()`, `Redis.RPop()`, `Redis.LLen()`, `Redis.LRange()`, `.ProcessingList()` | | **Any operation** | `Redis.Command(operation, key)` — the factories above cover keys, Pub/Sub, streams and lists; every other operation (`HSET`, `ZADD`, `GEOADD`, `BLPOP`, …) is built with it | | **Options** | `.Ttl()`, `.Transacted()`, `.PollDelay()`, `.UsePattern()`, `.CustomCommand()` | > Most builder methods accept both constant values and `IExpression` for runtime resolution via the expression engine. `Redis.Command(operation, key)` names an **operation** of this connector. The `COMMAND` operation is something else: a raw Redis command, named with `.CustomCommand("PING")` (or the `redbRedis.Command` header) and run through `ExecuteAsync`. ## Consumers and delivery | Consumer | How it reads | A failed route | |---|---|---| | `SUBSCRIBE` / `PSUBSCRIBE` | Pub/Sub; `PSUBSCRIBE` subscribes to a pattern (`events.*`), `usePattern` makes `SUBSCRIBE` do so too | lost: Pub/Sub keeps nothing | | `XREAD` / `XGROUP` with `consumerGroup` | `XREADGROUP`, acknowledged (`XACK`) after the route succeeded | stays pending; `streamClaimMinIdleMs` claims it again (`XAUTOCLAIM`) once it idled that long — a dead consumer's entries too | | the same with `ackMode=auto` | `XREADGROUP NOACK`: delivered when read | not read again (at-most-once) | | `XREAD` without a group | a position of its own, moved past every entry read; starts at the entries added from now on, or at `streamStartPosition` (`0` = from the beginning) | moved past, like a Kafka consumer without `breakOnFirstError` | | `BLPOP` / `BRPOP` | polls `LPOP` / `RPOP` every `pollDelayMs` (a blocking pop would hold the connection the whole process shares) | lost (at-most-once) | | the same with `processingList` | `LMOVE` into that list, removed after the route succeeded | back to the head of the queue and processed again; what a previous run left there is returned at start. One consumer per processing list | `streamClaimMinIdleMs` must exceed the longest time a route takes: a slower route would have its entry claimed by another consumer while it still works on it. A consumer is ready when its route has started: the subscription, the consumer group and the XREAD position are set up before `Start()` returns, so a message published right after the start is received. A Redis that does not answer at start fails the route start with an error naming the consumer (`redis:SUBSCRIBE:orders cannot start ...`); an outage after the start is ridden out by the client, which reconnects and subscribes again. ### Stream batch mode `batching=true` on an `XREAD` or `XGROUP` consumer hands the route one exchange per batch of entries, by the batch contract every broker of redb.Route follows. Apache Camel's Redis component has no batch consumer; the contract is redb.Route's own, the same as for Kafka, RabbitMQ, IBM MQ, SQS, AMQP 1.0 and Service Bus. - `maxBatchMessages` caps the batch (default `streamReadCount`); `pollTimeoutMs` (default 1000) sends a batch on once no entry came for that long, restarted by every entry; `batchingIntervalMs` sends it on once that long has passed since its first entry. Each read asks for at most `streamReadCount` entries. A batch option without `batching=true`, a value out of range, and `batching=true` on Pub/Sub or a list consumer (nothing there acknowledges a batch) fail the start. - The body is a `List`, one message per entry with the same body (its fields) and headers a single entry gets, even for a batch of one; `redbRedis.Stream` is set on the batch message. The exchange is InOnly. - With a group, every entry is acknowledged in one `XACK` after the route. A failed batch follows the rule of a failed entry for every entry in it: it stays pending, and `streamClaimMinIdleMs` claims it again; the claimed entries are taken into a batch before new ones. `streamClaimMinIdleMs` must exceed the time a batch takes from its first entry to the end of its route. With `ackMode=auto` the entries are read with `NOACK`. - Without a group the consumer's position moves past every entry it reads, a failed batch included, as in single mode. - A batch half collected when the consumer stops is not run; with a group its entries stay pending. ## Transactions Redis is a store first, so inside a route's `.Transacted()` block only the operations that announce work wait for the commit: - **`PUBLISH` and `XADD`** follow the block like a broker send: they run once the database has committed and are dropped if the block rolls back. The entry id (`redbRedis.Stream.MessageId`) and the recipient count reach the exchange headers after the commit. `.Transacted(false)` runs them at once. - **Other writes** (`SET`, `INCR`, `SETNX`, lists, hashes, sets) run at once: they exist for their effect and their result right now. `.Transacted()` holds one back until the commit; the route then does not get its result. - **Reads and pops** (`GET`, `LPOP` and the like) exist for what they return and refuse `.Transacted()` when the route starts. A deferred operation is the same operation, run after the commit on a snapshot of the exchange taken at the step: the same key, body, fields, headers and TTL. Outside a block, `.Transacted()` fails the step instead of losing the write. ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new RedisConnectionFactory { ConnectionString = "redis.internal:6379", Password = secrets.RedisPassword, }); // redis:GET:cache?connectionFactory=prod ``` ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), with `redb.route.endpoint`: - **Consumer.** One `Consumer` span, `redis {operation} receive`, per routed pub/sub message, stream entry or list item, with `messaging.system` = `redis` and the channel, stream or list as `messaging.destination.name`. A Redis value carries no trace context (a stream entry's fields are its body), so the span is a root, never a child of the activity the consumer loop inherited from whoever started the routes; nothing arriving opens none. A failed route marks it an error; our own stop does not. - **Producer.** One `Client` span per command, `redis {operation}`, with `db.system` = `redis`; an error when the command fails, unless our own token cancelled it. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. Path: redb-route/redb.Route.Redis/RedisComponent.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/RedisComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Redis; /// /// Redis transport component for redb.Route. /// Scheme: redis. /// /// URI format (colon-path): redis:SET:mykey?ttl=300&connectionString=localhost:6379
/// URI format (standard): redis://SET/mykey?ttl=300 ///
/// /// The first path segment is the . /// The remaining segments form the resource key / channel / stream name. /// ///
public sealed partial class RedisComponent : ComponentBase { /// public override string Scheme => "redis"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new RedisEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new RedisEndpoint(uri, this, options); } } Path: redb-route/redb.Route.Redis/RedisConnectionFactory.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/RedisConnectionFactory.cs ---- using StackExchange.Redis; using redb.Route.Core; namespace redb.Route.Redis; /// /// Connection factory for Redis. Register via DI or in the route registry /// and reference by name in endpoint URIs (connectionFactory=myFactory). /// public sealed class RedisConnectionFactory { /// Redis connection string (e.g., "localhost:6379" or "host1:6379,host2:6379"). [Sensitive] public string ConnectionString { get; set; } = "localhost:6379"; /// Default database index (default: 0). public int Database { get; set; } /// Redis password (optional). [Sensitive] public string? Password { get; set; } /// Redis ACL username (Redis 6+). Use together with Password for ACL authentication. public string? User { get; set; } /// Client name for identification in Redis INFO. public string ClientName { get; set; } = "redb.Route"; // ── Timeouts ── /// Connection timeout in milliseconds (default: 5000). public int ConnectTimeout { get; set; } = 5000; /// Synchronous operation timeout in milliseconds (default: 5000). public int SyncTimeout { get; set; } = 5000; /// Async operation timeout in milliseconds (default: 5000). public int AsyncTimeout { get; set; } = 5000; /// Number of connection retries (default: 3). public int ConnectRetry { get; set; } = 3; /// Keep-alive interval in seconds (default: 60). public int KeepAlive { get; set; } = 60; /// Abort on connection fail (default: false — allows reconnect). public bool AbortOnConnectFail { get; set; } /// Allow admin commands (default: false). public bool AllowAdmin { get; set; } // ── SSL ── /// Enable SSL encryption. public bool Ssl { get; set; } /// SSL host for certificate validation. public string? SslHost { get; set; } /// SSL/TLS protocol versions (e.g. "Tls12", "Tls13"). Default = system default. public string? SslProtocols { get; set; } /// Enable certificate revocation checking (default: true). public bool CheckCertificateRevocation { get; set; } = true; // ── Advanced ── /// Include detailed diagnostics in exceptions. public bool IncludeDetailInExceptions { get; set; } = true; /// Include performance counters in exceptions. public bool IncludePerformanceCountersInExceptions { get; set; } // ── Sentinel / Cluster / HA ── /// Redis Sentinel service name. Required for Sentinel-based HA setups. public string? ServiceName { get; set; } /// Tie-breaker key for master detection in multi-master scenarios. public string? TieBreaker { get; set; } /// /// Reconnect retry policy: "exponential" or "linear" (default: exponential). /// Controls backoff during reconnection attempts. /// public string ReconnectRetryPolicy { get; set; } = "exponential"; /// Channel prefix for Pub/Sub (optional). public string? ChannelPrefix { get; set; } /// Creates from this factory's settings. public ConfigurationOptions Build() { var config = ConfigurationOptions.Parse(ConnectionString); config.DefaultDatabase = Database; config.ClientName = ClientName; config.ConnectTimeout = ConnectTimeout; config.SyncTimeout = SyncTimeout; config.AsyncTimeout = AsyncTimeout; config.ConnectRetry = ConnectRetry; config.KeepAlive = KeepAlive; config.AbortOnConnectFail = AbortOnConnectFail; config.AllowAdmin = AllowAdmin; config.Ssl = Ssl; config.IncludeDetailInExceptions = IncludeDetailInExceptions; config.IncludePerformanceCountersInExceptions = IncludePerformanceCountersInExceptions; config.CheckCertificateRevocation = CheckCertificateRevocation; if (!string.IsNullOrEmpty(Password)) config.Password = Password; if (!string.IsNullOrEmpty(User)) config.User = User; if (!string.IsNullOrEmpty(SslHost)) config.SslHost = SslHost; // A typo must not silently drop the protocol policy the admin pinned. // Flags-enum: "Tls12, Tls13" is a valid value. if (!string.IsNullOrEmpty(SslProtocols)) { if (!Enum.TryParse(SslProtocols, true, out var protocols)) throw new ArgumentException( $"Unknown value '{SslProtocols}' for 'sslProtocols'. Valid values: " + "Tls12, Tls13 (comma-separated for several)."); config.SslProtocols = protocols; } if (!string.IsNullOrEmpty(ServiceName)) config.ServiceName = ServiceName; if (!string.IsNullOrEmpty(TieBreaker)) config.TieBreaker = TieBreaker; config.ReconnectRetryPolicy = ReconnectRetryPolicy?.Trim().ToLowerInvariant() switch { "linear" => new LinearRetry(ConnectTimeout), _ => new ExponentialRetry(Math.Min(ConnectTimeout, 5000)), }; if (!string.IsNullOrEmpty(ChannelPrefix)) config.ChannelPrefix = new RedisChannel(ChannelPrefix, RedisChannel.PatternMode.Literal); return config; } } Path: redb-route/redb.Route.Redis/RedisConsumer.Batch.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/RedisConsumer.Batch.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Batching; using redb.Route.Core; using StackExchange.Redis; namespace redb.Route.Redis; /// /// Batch mode of the Redis stream consumer (batching=true, XREAD/XGROUP), on the core batch contract: the /// consumer collects up to maxBatchMessages entries, runs them through the route once and settles them once. /// With a consumer group and ackMode=manual, success acknowledges every entry in one XACK; a failure applies the /// rule of a failed single entry to each: it stays pending, and streamClaimMinIdleMs claims it again. Entries /// pending for that long are taken into a batch first, as single mode processes them first. A batch the consumer stops /// on stays pending too. Without a group the consumer's own position moves past every entry it reads, a failed batch /// included, as single mode does. /// public sealed partial class RedisConsumer { private async Task RunStreamBatchAsync(BatchOptions batch, CancellationToken pollCt, CancellationToken processingCt) { var db = _db!; var streamName = _options.StreamName ?? _endpoint.Resource; var reader = new StreamBatchReader(this, db, streamName); var settlement = new StreamBatchSettlement(this, db, streamName); var dispatcher = new BatchDispatcher(Processor, settlement, (entry, _) => StreamMessage(entry, streamName), _endpoint.ScopeFactory, [RedisHeaders.Stream]); var collector = new BatchCollector(batch, reader.ReceiveAsync); Logger?.LogInformation( "Redis stream batch consumer started: stream={Stream}, group={Group}, consumer={Consumer}, batch={Batch}", streamName, _options.ConsumerGroup, reader.ConsumerName, batch.MaxMessages); while (!pollCt.IsCancellationRequested) { CollectedBatch collected; try { collected = await collector.CollectAsync(pollCt).ConfigureAwait(false); } catch (Exception ex) when (!pollCt.IsCancellationRequested) { Logger?.LogError(ex, "Error reading from Redis stream {Stream}", streamName); try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { return; } continue; } if (collected.Items.Count == 0) continue; if (collected.Interrupted) { await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false); return; } var items = collected.Items; using var span = BatchDispatcher.StartSpan( (_endpoint.Component as ComponentBase)?.Context, $"redis {_endpoint.OperationType} receive", "redis", _endpoint.Uri.NormalizedKey, _endpoint.Resource, [], items.Count); IncrementInflight(); try { if (await dispatcher.DispatchAsync(items, span, processingCt).ConfigureAwait(false) == BatchOutcome.Accepted) ProcessedCount += items.Count; } catch (OperationCanceledException) when (processingCt.IsCancellationRequested) { return; } catch (Exception ex) { Logger?.LogError(ex, "Redis stream batch failed to settle on {Stream}", streamName); } finally { DecrementInflight(); } } } /// /// One stream entry as a message, the same for a single entry and an element of a batch: the body the entry's fields /// (raw strings), the stream, the id and each field as headers. /// private static Message StreamMessage(StreamEntry entry, string streamName) { var fields = entry.Values.ToDictionary(nv => nv.Name.ToString(), nv => (object?)nv.Value.ToString()); var message = new Message(fields); message.Headers[RedisHeaders.Stream] = streamName; message.Headers[RedisHeaders.MessageId] = entry.Id.ToString(); message.Headers[RedisHeaders.MessageType] = "Stream"; message.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow; foreach (var nv in entry.Values) message.Headers[$"{RedisHeaders.StreamFieldPrefix}{nv.Name}"] = nv.Value.ToString(); return message; } /// /// The transport's part of collection. With a group: first the entries pending for streamClaimMinIdleMs /// (XAUTOCLAIM), then new ones (XREADGROUP >); without one, XREAD after the consumer's position, which moves past /// every entry read. Redis is not asked to block (the connection is shared): an empty read waits /// streamBlockTimeMs, at most the wait the collector allows. /// private sealed class StreamBatchReader(RedisConsumer owner, IDatabase db, string streamName) { private RedisValue _position = owner._streamPosition; private RedisValue _claimCursor = "0-0"; public string ConsumerName { get; } = owner._options.ConsumerName ?? Environment.MachineName; public async ValueTask ReceiveAsync(List into, int max, TimeSpan wait, CancellationToken ct) { ct.ThrowIfCancellationRequested(); var options = owner._options; var group = options.ConsumerGroup; var count = Math.Min(max, options.StreamReadCount); StreamEntry[] entries; if (!string.IsNullOrEmpty(group)) { if (options.StreamClaimMinIdleMs is { } minIdle) { var claimed = await db.StreamAutoClaimAsync(streamName, group, ConsumerName, minIdle, _claimCursor, count) .ConfigureAwait(false); _claimCursor = claimed.NextStartId; var pending = claimed.ClaimedEntries.Where(e => !e.IsNull).ToArray(); if (pending.Length > 0) { into.AddRange(pending); return pending.Length; } } entries = await db.StreamReadGroupAsync(streamName, group, ConsumerName, StreamPosition.NewMessages, count, noAck: options.AckMode == AckMode.Auto).ConfigureAwait(false); } else { entries = await db.StreamReadAsync(streamName, _position, count).ConfigureAwait(false); if (entries.Length > 0) _position = entries[^1].Id; } if (entries.Length > 0) { into.AddRange(entries); return entries.Length; } var idle = TimeSpan.FromMilliseconds(options.StreamBlockTimeMs); await Task.Delay(idle < wait ? idle : wait, ct).ConfigureAwait(false); return 0; } } /// /// The settlement of a stream batch: with a group and ackMode=manual, one XACK of every entry on success; a /// failed or interrupted batch stays pending. Without a group, or with ackMode=auto, nothing is settled. /// private sealed class StreamBatchSettlement(RedisConsumer owner, IDatabase db, string streamName) : IBatchSettlement { private bool Acknowledges => !string.IsNullOrEmpty(owner._options.ConsumerGroup) && owner._options.AckMode == AckMode.Manual; public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) => ValueTask.FromResult(null); public async ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) { if (Acknowledges) await db.StreamAcknowledgeAsync(streamName, owner._options.ConsumerGroup, items.Select(e => e.Id).ToArray()) .ConfigureAwait(false); } public ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct) { owner.Logger?.LogError(failure, "Redis stream batch of {Count} failed on {Stream}; {Outcome}", items.Count, streamName, Acknowledges ? "its entries stay pending" : "the consumer moves on"); return ValueTask.CompletedTask; } public ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct) => ValueTask.CompletedTask; } } Path: redb-route/redb.Route.Redis/RedisConsumer.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/RedisConsumer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using StackExchange.Redis; namespace redb.Route.Redis; /// /// Redis consumer. Supports three modes based on the operation type: /// /// / — /// Pub/Sub with event-driven callback. /// / — /// Redis Streams polling loop: with a consumer group, acknowledged after the route (or NOACK) and pending entries /// claimed again after an idle time; without one, a position of its own that moves past every entry read. /// / — /// list pop via polling (a blocking pop would hold the shared connection); at-least-once with a processing list. /// /// public sealed partial class RedisConsumer : DrainableConsumer { private readonly RedisEndpoint _endpoint; private readonly RedisEndpointOptions _options; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => $"redis:{_endpoint.OperationType}:{_endpoint.Resource}"; /// Number of messages successfully processed. public long ProcessedCount { get; private set; } /// Creates a Redis consumer. public RedisConsumer(RedisEndpoint endpoint, IProcessor processor, RedisEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } // Set up by OnStarting, read by the loop RunAsync starts. private ISubscriber? _subscriber; private ChannelMessageQueue? _queue; private RedisChannel _channel; private IDatabase? _db; private RedisValue _streamPosition; /// /// Everything a message depends on is in place before returns: the pub/sub /// subscription, the consumer group, the XREAD position. Done in the loop, after Start, it lost whatever was /// published or added in between. A Redis that does not answer fails Start, naming this consumer; it used to leave a /// started consumer that never received anything. /// protected override async Task OnStarting(CancellationToken ct) { try { switch (_endpoint.OperationType) { case RedisOperationType.SUBSCRIBE or RedisOperationType.PSUBSCRIBE: await SubscribeAsync(ct).ConfigureAwait(false); break; case RedisOperationType.XREAD or RedisOperationType.XGROUP: await PrepareStreamAsync(ct).ConfigureAwait(false); break; case RedisOperationType.BLPOP or RedisOperationType.BRPOP: // A list keeps its items, nothing to set up; the round trip only proves Redis answers. _db = await _endpoint.GetDatabaseAsync(ct).ConfigureAwait(false); await _db.PingAsync().ConfigureAwait(false); break; default: throw new NotSupportedException( $"Consumer not supported for operation {_endpoint.OperationType}. " + "Only SUBSCRIBE/PSUBSCRIBE, XREAD/XGROUP, BLPOP/BRPOP are supported."); } } catch (Exception ex) when (ex is RedisException or TimeoutException) { throw new InvalidOperationException( $"Redis consumer {ConsumerName} cannot start, Redis did not answer: {ex.Message}", ex); } } /// protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { return _endpoint.OperationType switch { RedisOperationType.SUBSCRIBE or RedisOperationType.PSUBSCRIBE => RunPubSubConsumerAsync(pollCt, processingCt), RedisOperationType.XREAD or RedisOperationType.XGROUP when _options.Batch is { } batch => RunStreamBatchAsync(batch, pollCt, processingCt), RedisOperationType.XREAD or RedisOperationType.XGROUP => RunStreamConsumerAsync(pollCt, processingCt), RedisOperationType.BLPOP or RedisOperationType.BRPOP => RunListConsumerAsync(pollCt, processingCt), _ => throw new NotSupportedException( $"Consumer not supported for operation {_endpoint.OperationType}. " + "Only SUBSCRIBE/PSUBSCRIBE, XREAD/XGROUP, BLPOP/BRPOP are supported.") }; } // ═══════════════════════════════════════════════════════════ // Pub/Sub // ═══════════════════════════════════════════════════════════ private async Task SubscribeAsync(CancellationToken ct) { _subscriber = await _endpoint.GetSubscriberAsync(ct).ConfigureAwait(false); var channel = _options.Channel ?? _endpoint.Resource; // PSUBSCRIBE is a pattern subscription by itself; usePattern makes SUBSCRIBE one too. var pattern = _endpoint.OperationType == RedisOperationType.PSUBSCRIBE || _options.UsePattern; _channel = pattern ? new RedisChannel(channel, RedisChannel.PatternMode.Pattern) : new RedisChannel(channel, RedisChannel.PatternMode.Literal); _queue = await _subscriber.SubscribeAsync(_channel).ConfigureAwait(false); Logger?.LogInformation("Redis subscribed to channel: {Channel} (pattern={Pattern})", channel, pattern); } private async Task RunPubSubConsumerAsync(CancellationToken pollCt, CancellationToken processingCt) { var subscriber = _subscriber!; var queue = _queue!; var redisChannel = _channel; try { while (!pollCt.IsCancellationRequested) { var msg = await queue.ReadAsync(pollCt).ConfigureAwait(false); await ProcessPubSubMessageAsync(msg.Channel!, msg.Message, processingCt).ConfigureAwait(false); } } catch (OperationCanceledException) { /* normal shutdown */ } catch (Exception ex) { Logger?.LogError(ex, "Error in Redis Pub/Sub consumer for channel {Channel}", redisChannel.ToString()); } finally { try { await subscriber.UnsubscribeAsync(redisChannel).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Error unsubscribing from Redis channel"); } _queue = null; } } private async Task ProcessPubSubMessageAsync(RedisChannel channel, RedisValue message, CancellationToken ct) { var exchange = Exchange.Create(new Message(message.ToString()), _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; using var span = StartReceiveSpan(); IncrementInflight(); try { exchange.In.Headers[RedisHeaders.Channel] = channel.ToString(); exchange.In.Headers[RedisHeaders.MessageType] = "PubSub"; exchange.In.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow; await Processor.Process(exchange, ct).ConfigureAwait(false); exchange.ThrowIfUnhandledFailure(); ProcessedCount++; } catch (Exception ex) { RecordFailure(span, ex, ct); Logger?.LogError(ex, "Error processing Pub/Sub message from channel {Channel}", channel); } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } // ═══════════════════════════════════════════════════════════ // Streams (XREAD / XGROUP) // ═══════════════════════════════════════════════════════════ private async Task PrepareStreamAsync(CancellationToken ct) { var db = _db = await _endpoint.GetDatabaseAsync(ct).ConfigureAwait(false); var streamName = _options.StreamName ?? _endpoint.Resource; var consumerGroup = _options.ConsumerGroup; // Create consumer group if needed if (!string.IsNullOrEmpty(consumerGroup)) { try { // Unset position: the group starts at the stream's end ($), as StackExchange.Redis does by default. await db.StreamCreateConsumerGroupAsync( streamName, consumerGroup, // RedisValue? explicitly: a null string converts to RedisValue.Null, which XGROUP CREATE refuses // ("A null value is not valid"), and a group consumer without streamStartPosition never started. _options.StreamStartPosition is { } start ? (RedisValue?)start : null, createStream: true).ConfigureAwait(false); Logger?.LogInformation("Redis stream consumer group created: {Group} for {Stream}", consumerGroup, streamName); } catch (RedisServerException ex) when (ex.Message.Contains("BUSYGROUP")) { Logger?.LogDebug("Redis stream consumer group {Group} already exists", consumerGroup); } } // Without a group the position is this consumer's to keep, and it moves past every entry read. _streamPosition = string.IsNullOrEmpty(consumerGroup) ? await StartPositionAsync(db, streamName).ConfigureAwait(false) : default; } private async Task RunStreamConsumerAsync(CancellationToken pollCt, CancellationToken processingCt) { var db = _db!; var streamName = _options.StreamName ?? _endpoint.Resource; var consumerGroup = _options.ConsumerGroup; var consumerName = _options.ConsumerName ?? Environment.MachineName; var position = _streamPosition; RedisValue claimCursor = "0-0"; Logger?.LogInformation("Redis stream consumer started: stream={Stream}, group={Group}, consumer={Consumer}", streamName, consumerGroup, consumerName); while (!pollCt.IsCancellationRequested) { try { StreamEntry[] entries; var claimedAny = false; if (!string.IsNullOrEmpty(consumerGroup)) { if (_options.StreamClaimMinIdleMs is { } minIdle) { // Entries of the group pending for longer than minIdle — a failed entry of this consumer, or one // a dead consumer left behind — are taken over and processed again. The cursor walks the // pending list and comes back to the start once it has seen all of it. var claimed = await db.StreamAutoClaimAsync( streamName, consumerGroup, consumerName, minIdle, claimCursor, _options.StreamReadCount) .ConfigureAwait(false); claimCursor = claimed.NextStartId; foreach (var entry in claimed.ClaimedEntries.Where(e => !e.IsNull)) { claimedAny = true; await ProcessStreamEntryAsync(entry, db, streamName, consumerGroup, processingCt) .ConfigureAwait(false); } } entries = await db.StreamReadGroupAsync( streamName, consumerGroup, consumerName, StreamPosition.NewMessages, _options.StreamReadCount, noAck: _options.AckMode == AckMode.Auto).ConfigureAwait(false); } else { entries = await db.StreamReadAsync( streamName, position, _options.StreamReadCount).ConfigureAwait(false); } if (entries is { Length: > 0 }) { foreach (var entry in entries) { await ProcessStreamEntryAsync(entry, db, streamName, consumerGroup, processingCt) .ConfigureAwait(false); // Past a failed entry too: without a group nothing keeps it pending, as a Kafka consumer // without breakOnFirstError moves on. if (string.IsNullOrEmpty(consumerGroup)) position = entry.Id; } } else if (!claimedAny) { await Task.Delay(_options.StreamBlockTimeMs, pollCt).ConfigureAwait(false); } } catch (OperationCanceledException) { break; } catch (Exception ex) { Logger?.LogError(ex, "Error reading from Redis stream {Stream}", streamName); try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } } /// /// Where an XREAD consumer without a group starts. Unset or $: the entries added from now on. XREAD takes /// $ as "after the last entry at the time of this call", which a polling loop would evaluate again on every /// call and so skip whatever arrived in between: it is pinned once, to the id of the stream's last entry, or to the /// start of an empty stream. Anything else (0, an entry id) is taken as given. /// private async Task StartPositionAsync(IDatabase db, string streamName) { if (_options.StreamStartPosition is not (null or "$")) return _options.StreamStartPosition; var last = await db.StreamRangeAsync(streamName, "-", "+", count: 1, messageOrder: Order.Descending) .ConfigureAwait(false); return last.Length > 0 ? last[0].Id : "0-0"; } private async Task ProcessStreamEntryAsync( StreamEntry entry, IDatabase db, string streamName, string? consumerGroup, CancellationToken ct) { using var span = StartReceiveSpan(); try { var exchange = Exchange.Create(StreamMessage(entry, streamName), _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; IncrementInflight(); try { // The entry is acknowledged by this consumer after the unit of work ended well (below), not by // the route transaction: the transaction owns the database and the outgoing sends. await Processor.Process(exchange, ct).ConfigureAwait(false); exchange.ThrowIfUnhandledFailure(); // Acknowledge the entry now that the whole unit of work, the route transaction included, is done. A // failed entry is not acknowledged: it stays pending, for streamClaimMinIdleMs to claim again. if (!string.IsNullOrEmpty(consumerGroup) && _options.AckMode == AckMode.Manual) { await db.StreamAcknowledgeAsync(streamName, consumerGroup, entry.Id).ConfigureAwait(false); } ProcessedCount++; } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } catch (Exception ex) { RecordFailure(span, ex, ct); Logger?.LogError(ex, "Error processing stream entry {MessageId} from {Stream}", entry.Id, streamName); } } // ═══════════════════════════════════════════════════════════ // List (BLPOP / BRPOP) // ═══════════════════════════════════════════════════════════ private async Task RunListConsumerAsync(CancellationToken pollCt, CancellationToken processingCt) { var db = _db!; var key = _options.Key ?? _endpoint.Resource; // BLPOP takes from the head, BRPOP from the tail. Both poll: a blocking pop would hold the multiplexed // connection every other command of this process shares. var side = _endpoint.OperationType == RedisOperationType.BLPOP ? ListSide.Left : ListSide.Right; var processing = _options.ProcessingList; Logger?.LogInformation("Redis list consumer started: key={Key}, operation={Op}, processing list={Processing}", key, _endpoint.OperationType, processing); if (processing is not null) await ReturnLeftoversAsync(db, processing, key, side).ConfigureAwait(false); while (!pollCt.IsCancellationRequested) { try { // With a processing list the item is moved there (LMOVE) and leaves it only once processed; without one // it is popped, and a failed item is gone. var result = processing is null ? side == ListSide.Left ? await db.ListLeftPopAsync(key).ConfigureAwait(false) : await db.ListRightPopAsync(key).ConfigureAwait(false) : await db.ListMoveAsync(key, processing, side, ListSide.Left).ConfigureAwait(false); if (!result.HasValue) { await Task.Delay(_options.PollDelayMs, pollCt).ConfigureAwait(false); continue; } var processed = await ProcessListMessageAsync(result, key, processingCt).ConfigureAwait(false); if (processing is null) continue; if (processed) { await db.ListRemoveAsync(processing, result, count: 1).ConfigureAwait(false); } else { // Back to the side it was taken from, so it is the next one taken; atomically, so a crash in // between cannot leave it in both lists or in neither. var back = db.CreateTransaction(); _ = back.ListRemoveAsync(processing, result, count: 1); _ = side == ListSide.Left ? back.ListLeftPushAsync(key, result) : back.ListRightPushAsync(key, result); await back.ExecuteAsync().ConfigureAwait(false); await Task.Delay(_options.PollDelayMs, pollCt).ConfigureAwait(false); } } catch (OperationCanceledException) { break; } catch (Exception ex) { Logger?.LogError(ex, "Error reading from Redis list {Key}", key); try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } } /// /// Returns what a previous run left in the processing list — items it took and never finished — to the side of the /// queue this consumer takes from, oldest first. /// private async Task ReturnLeftoversAsync(IDatabase db, string processing, string key, ListSide side) { var returned = 0; // The newest item sits at the head of the processing list; moving from the head to the taking side, one by one, // leaves the oldest nearest to it. while ((await db.ListMoveAsync(processing, key, ListSide.Left, side).ConfigureAwait(false)).HasValue) returned++; if (returned > 0) Logger?.LogWarning("Redis list consumer returned {Count} unfinished item(s) from {Processing} to {Key}", returned, processing, key); } /// Whether the route succeeded with the item. private async Task ProcessListMessageAsync(RedisValue message, string key, CancellationToken ct) { var exchange = Exchange.Create(new Message(message.ToString()), _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; using var span = StartReceiveSpan(); IncrementInflight(); try { exchange.In.Headers[RedisHeaders.Key] = key; exchange.In.Headers[RedisHeaders.MessageType] = "List"; exchange.In.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow; await Processor.Process(exchange, ct).ConfigureAwait(false); exchange.ThrowIfUnhandledFailure(); ProcessedCount++; return true; } catch (Exception ex) { RecordFailure(span, ex, ct); Logger?.LogError(ex, "Error processing list message from {Key}", key); return false; } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } /// /// The span of one message, entry or item: it carries no trace context (a Redis value has no headers; a stream entry's /// fields are its body), so the span is a root, never a child of the activity the consumer loop holds. /// private TransportSpan StartReceiveSpan() => RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"redis {_endpoint.OperationType} receive", ActivityKind.Consumer, "messaging.system", "redis", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.Resource, operation: "receive"); /// Marks the span failed; our own stop is not a failure, any other cancellation is. private static void RecordFailure(TransportSpan span, Exception exception, CancellationToken ct) { if (exception is not OperationCanceledException || !ct.IsCancellationRequested) span.Activity.RecordFailure(exception); } } 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; } Path: redb-route/redb.Route.Redis/RedisEndpointOptions.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/RedisEndpointOptions.cs ---- using redb.Route.Batching; using redb.Route.Core; namespace redb.Route.Redis; /// /// Typed options for . Bound from URI query parameters. /// public sealed class RedisEndpointOptions : EndpointOptions { // ── Connection ── /// Redis connection string (default: localhost:6379). [Sensitive] public string ConnectionString { get; set; } = "localhost:6379"; /// Redis database index (default: 0). public int Database { get; set; } /// Redis password (optional). [Sensitive] public string? Password { get; set; } /// Name of in the route registry. [RegistryReference(typeof(RedisConnectionFactory))] public string? ConnectionFactory { get; set; } // ── Operation parameters ── /// Redis key (for key-based operations). May contain dynamic expressions. public string? Key { get; set; } /// Channel name for Pub/Sub operations. public string? Channel { get; set; } /// Stream name for Redis Streams. public string? StreamName { get; set; } /// Consumer group for Streams. public string? ConsumerGroup { get; set; } /// Consumer name within a group. public string? ConsumerName { get; set; } /// Redis command for COMMAND operation type. public string? Command { get; set; } /// /// Subscribe to as a pattern. PSUBSCRIBE always does; this makes SUBSCRIBE do it too. /// public bool UsePattern { get; set; } // ── TTL and score ── /// Time-to-live in seconds for SET/EXPIRE. 0 = no expiry. public int Ttl { get; set; } /// Score for sorted set operations. public double? Score { get; set; } /// Hash field name for HSET/HGET operations. public string? Field { get; set; } // ── Range ── /// Range start for LRANGE/ZRANGE operations. public long? Start { get; set; } /// Range stop for LRANGE/ZRANGE operations. public long? Stop { get; set; } /// Min score for ZRANGEBYSCORE. public double? MinScore { get; set; } /// Max score for ZRANGEBYSCORE. public double? MaxScore { get; set; } // ── Geospatial ── /// Longitude for GEOADD/GEORADIUS. public double? Longitude { get; set; } /// Latitude for GEOADD/GEORADIUS. public double? Latitude { get; set; } /// First member for GEODIST. public string? Member1 { get; set; } /// Second member for GEODIST. public string? Member2 { get; set; } /// Unit for geo operations: m, km, mi, ft (default: m). public string GeoUnit { get; set; } = "m"; // ── Bitmap ── /// Bit offset for SETBIT/GETBIT. public long? Offset { get; set; } /// Bit value for SETBIT. public bool? Bit { get; set; } // ── Streams ── /// Max stream length for XADD (0 = unlimited). public int StreamMaxLength { get; set; } /// Use approximate max length for XADD trimming. public bool StreamApproximate { get; set; } = true; /// Number of entries to read at a time from a stream. public int StreamReadCount { get; set; } = 10; /// Block time in ms when no stream entries available. public int StreamBlockTimeMs { get; set; } = 1000; /// /// When a stream entry read through a consumer group is settled (). Manual /// (default): acknowledged (XACK) after its route succeeded; a failed one stays pending (at-least-once). /// Auto: read with NOACK, it counts as delivered when it is read and never enters the group's pending list, /// so an entry whose route failed is not read again (at-most-once). /// public AckMode AckMode { get; set; } = AckMode.Manual; /// /// Where a stream consumer starts. Unset: at the entries added from now on — for a group, the group is created at the /// stream's end; without one, the consumer pins the stream's last entry when it starts. 0 reads from the /// beginning, an entry id after that entry. > only means something to a group and is refused without one. /// public string? StreamStartPosition { get; set; } /// /// A group consumer claims (XAUTOCLAIM) entries of its group that have stayed pending for at least this many /// milliseconds — a failed entry of its own, or one a consumer that died left behind — and processes them again. /// Unset: pending entries are not claimed. Must exceed the longest time a route takes: a slower one would have its /// entry claimed while it still works on it. Not with ackMode=auto, which leaves nothing pending. /// public int? StreamClaimMinIdleMs { get; set; } // ── Streams: batch mode ── /// /// Batch mode of a stream consumer (Apache Camel batching, the batch contract of every broker of redb.Route): /// the route gets one InOnly exchange whose body is a List<IMessage> of up to /// entries, settled once after the route: with a consumer group acknowledged in one /// XACK on success, left pending on failure, as a failed single entry is. XREAD/XGROUP only. /// public bool Batching { get; set; } /// Largest number of entries in a batch (default ). public int? MaxBatchMessages { get; set; } /// /// Batch mode: a batch with entries is sent on once no entry came for this many milliseconds, restarted by every /// entry (default 1000). /// public int PollTimeoutMs { get; set; } = 1000; /// Batch mode: a batch is sent on once this many milliseconds have passed since its first entry. public int? BatchingIntervalMs { get; set; } /// The batch options, or null outside batch mode. Set by . internal BatchOptions? Batch { get; private set; } /// /// Resolves the batch options. Fails, naming the endpoint, where batch mode cannot work: a batch option without /// batching=true, a value out of range, and an operation other than XREAD/XGROUP: pub/sub and lists have no /// acknowledgement a batch could be settled by. /// internal void ResolveBatch(string endpoint, RedisOperationType operation) { Batch = BatchOptions.Resolve(endpoint, Batching, MaxBatchMessages, PollTimeoutMs, BatchingIntervalMs, StreamReadCount); if (Batch is not null && operation is not (RedisOperationType.XREAD or RedisOperationType.XGROUP)) throw new InvalidOperationException( $"Endpoint '{endpoint}': batching=true needs a stream consumer (XREAD or XGROUP); {operation} has no " + "acknowledgement a batch could be settled by."); } /// /// A BLPOP/BRPOP consumer moves an item into this list (LMOVE) instead of popping it, and removes it from there after /// its route succeeded: a failed item goes back to the head of the queue and is processed again, and what a /// previous run left in this list is returned to the queue when the consumer starts (at-least-once). Unset: the item /// is popped and a failed one is gone (at-most-once). One consumer per processing list. /// public string? ProcessingList { get; set; } // ── Transactions ── /// /// Producer: whether the operation waits for the commit of the enclosing .Transacted() block. PUBLISH and XADD /// announce work and follow the block when unset: deferred inside one, at once outside; false sends at once even /// inside one. Every other write runs at once unless true defers it; true requires a block and is refused /// at start for an operation that exists for what it returns (GET, LPOP and the other reads). /// public bool? Transacted { get; set; } // ── Resilience ── /// Polling delay in ms when list/stream consumer finds no messages. public int PollDelayMs { get; set; } = 1000; /// public override void Validate() { if (StreamReadCount <= 0) throw new ArgumentOutOfRangeException(nameof(StreamReadCount), "StreamReadCount must be > 0."); if (StreamClaimMinIdleMs is <= 0) throw new ArgumentOutOfRangeException(nameof(StreamClaimMinIdleMs), "StreamClaimMinIdleMs must be > 0."); if (StreamClaimMinIdleMs is not null && AckMode == AckMode.Auto) throw new ArgumentException( "'streamClaimMinIdleMs' claims pending entries, and 'ackMode=auto' leaves none: they contradict each other."); if (ProcessingList is not null && string.IsNullOrWhiteSpace(ProcessingList)) throw new ArgumentException("'processingList' is empty: name the list, or leave it unset."); } /// protected override string? UnknownParameterHint(string name) => name.Equals("streamNoAck", StringComparison.OrdinalIgnoreCase) ? "'streamNoAck' is replaced by 'ackMode': ackMode=auto reads with NOACK, as streamNoAck=true did; " + "ackMode=manual (the default) acknowledges after the route." : name.Equals("streamAutoAck", StringComparison.OrdinalIgnoreCase) ? "'streamAutoAck' is gone: 'streamAutoAck=false' read with NOACK while its name promised a manual " + "acknowledgement. A group consumer acknowledges after its route succeeded; 'ackMode=auto' reads " + "with NOACK (at-most-once)." : null; } Path: redb-route/redb.Route.Redis/RedisHeaders.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/RedisHeaders.cs ---- namespace redb.Route.Redis; /// /// Well-known header constants used by the Redis component. /// public static class RedisHeaders { /// Common prefix for all Redis component headers. public const string Prefix = "redbRedis."; // ── Consumer headers ───────────────────────────────────────────── /// PubSub channel name. public const string Channel = "redbRedis.Channel"; /// Message type: "PubSub", "Stream", or "List". public const string MessageType = "redbRedis.MessageType"; /// Timestamp when the message was received. public const string Timestamp = "redbRedis.Timestamp"; /// Stream name (stream mode). public const string Stream = "redbRedis.Stream"; /// Stream entry ID (stream mode). public const string MessageId = "redbRedis.MessageId"; /// List key name (list mode). public const string Key = "redbRedis.Key"; /// Prefix for stream field values. Example: "redbRedis.Stream.fieldName". public const string StreamFieldPrefix = "redbRedis.Stream."; // ── Producer headers (set after operation) ─────────────────────── /// Number of recipients that received a PubSub publish. public const string PublishRecipients = "redbRedis.Publish.Recipients"; /// Message ID returned after XADD to a stream. public const string StreamMessageId = "redbRedis.Stream.MessageId"; // ── Producer input headers (set by user before send) ───────────── /// Custom Redis command name. public const string Command = "redbRedis.Command"; /// Hash fields dictionary for HSET/HMSET operations. public const string HashFields = "redbRedis.HashFields"; /// Explicit stream field map (Dictionary<string,object>) for XADD. public const string StreamFields = "redbRedis.StreamFields"; /// Field names array for HMGET operations. public const string FieldNames = "redbRedis.FieldNames"; /// Custom command arguments array. public const string CommandArgs = "redbRedis.CommandArgs"; /// Source keys array for PFMERGE operations. public const string SourceKeys = "redbRedis.SourceKeys"; /// Center longitude for GeoRadius operations. public const string CenterLongitude = "redbRedis.CenterLongitude"; /// Center latitude for GeoRadius operations. public const string CenterLatitude = "redbRedis.CenterLatitude"; /// Radius value for GeoRadius operations. public const string Radius = "redbRedis.Radius"; /// Radius unit for GeoRadius operations (m, km, mi, ft). public const string RadiusUnit = "redbRedis.RadiusUnit"; /// Bit offset for SETBIT/GETBIT operations. public const string BitOffset = "redbRedis.Offset"; /// Bit value for SETBIT operations. public const string Bit = "redbRedis.Bit"; /// Returns true if the header key belongs to the Redis component. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.Redis/RedisOperationType.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/RedisOperationType.cs ---- namespace redb.Route.Redis; /// /// Redis operation types — determines what the producer/consumer does. /// Parsed from the first path segment of the URI: redis:OPERATION:resource. /// public enum RedisOperationType { // ── Key/Value (Cache) ── SET, GET, DEL, EXISTS, EXPIRE, INCR, DECR, SETNX, // ── Pub/Sub ── PUBLISH, SUBSCRIBE, PSUBSCRIBE, // ── Streams ── XADD, XREAD, XGROUP, // ── Lists ── LPUSH, RPUSH, LPOP, RPOP, LLEN, LRANGE, BLPOP, BRPOP, // ── Hashes ── HSET, HGET, HMSET, HMGET, HGETALL, HDEL, HLEN, // ── Sets ── SADD, SREM, SMEMBERS, SCARD, SISMEMBER, // ── Sorted Sets ── ZADD, ZREM, ZRANGE, ZCARD, ZSCORE, ZRANGEBYSCORE, // ── Geospatial ── GEOADD, GEODIST, GEORADIUS, // ── HyperLogLog ── PFADD, PFCOUNT, PFMERGE, // ── Bitmap ── SETBIT, GETBIT, BITCOUNT, // ── Arbitrary command ── COMMAND } Path: redb-route/redb.Route.Redis/RedisProducer.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/RedisProducer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Transactions; using redb.Route.Core; using redb.Route.Telemetry; using StackExchange.Redis; namespace redb.Route.Redis; /// /// Redis producer. Dispatches to the correct Redis command based on /// . Supports all major Redis data structures: /// strings, lists, hashes, sets, sorted sets, pub/sub, streams, geo, HyperLogLog, bitmap. /// Inside .Transacted(), PUBLISH and XADD wait for the commit (unless transacted=false); other writes wait /// for it only with transacted=true, and run the same code on a snapshot of the exchange once it commits. /// public sealed class RedisProducer : ConnectableProducer { private readonly RedisEndpoint _endpoint; private readonly RedisEndpointOptions _options; private IDatabase? _db; private ISubscriber? _subscriber; /// Creates a Redis producer. public RedisProducer(RedisEndpoint endpoint, RedisEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); if (_options.Transacted == true && !CanDefer(_endpoint.OperationType)) throw new InvalidOperationException( $"'{ProducerName}': {_endpoint.OperationType} exists for what it returns, so it cannot wait for the commit " + $"of a transaction. Drop transacted=true: {_endpoint.OperationType} always runs at once."); } /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"redis:{_endpoint.OperationType}:{_endpoint.Resource}"; /// protected override async Task ConnectAsync(CancellationToken ct) { _db = await _endpoint.GetDatabaseAsync(ct).ConfigureAwait(false); if (RedisEndpoint.IsPubSubOperation(_endpoint.OperationType)) _subscriber = await _endpoint.GetSubscriberAsync(ct).ConfigureAwait(false); } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"redis {_endpoint.OperationType}", ActivityKind.Client, "db.system", "redis", _endpoint.Uri.NormalizedKey, destination: _endpoint.Resource, operation: _endpoint.OperationType.ToString()); if (DefersToTheCommit(exchange)) { DeferToTheCommit(exchange); return; } try { await DispatchOperationAsync(exchange, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { activity.RecordFailure(ex); Logger?.LogError(ex, "Redis {Operation} failed: resource={Resource}, connected={IsConnected}, db={Database}", _endpoint.OperationType, _endpoint.Resource, _db?.Multiplexer?.IsConnected, _db?.Database); throw; } } // ═══════════════════════════════════════════════════════════ // Operation dispatch // ═══════════════════════════════════════════════════════════ private async Task DispatchOperationAsync(IExchange exchange, CancellationToken ct) { switch (_endpoint.OperationType) { // Key/Value case RedisOperationType.SET: case RedisOperationType.GET: case RedisOperationType.DEL: case RedisOperationType.EXISTS: case RedisOperationType.EXPIRE: case RedisOperationType.INCR: case RedisOperationType.DECR: case RedisOperationType.SETNX: await ProcessCacheAsync(exchange).ConfigureAwait(false); break; // Pub/Sub case RedisOperationType.PUBLISH: await ProcessPublishAsync(exchange).ConfigureAwait(false); break; // Streams case RedisOperationType.XADD: await ProcessStreamAddAsync(exchange).ConfigureAwait(false); break; // Lists case RedisOperationType.LPUSH: case RedisOperationType.RPUSH: case RedisOperationType.LPOP: case RedisOperationType.RPOP: case RedisOperationType.LLEN: case RedisOperationType.LRANGE: await ProcessListAsync(exchange).ConfigureAwait(false); break; // Hashes case RedisOperationType.HSET: case RedisOperationType.HGET: case RedisOperationType.HMSET: case RedisOperationType.HMGET: case RedisOperationType.HGETALL: case RedisOperationType.HDEL: case RedisOperationType.HLEN: await ProcessHashAsync(exchange).ConfigureAwait(false); break; // Sets case RedisOperationType.SADD: case RedisOperationType.SREM: case RedisOperationType.SMEMBERS: case RedisOperationType.SCARD: case RedisOperationType.SISMEMBER: await ProcessSetAsync(exchange).ConfigureAwait(false); break; // Sorted Sets case RedisOperationType.ZADD: case RedisOperationType.ZREM: case RedisOperationType.ZRANGE: case RedisOperationType.ZCARD: case RedisOperationType.ZSCORE: case RedisOperationType.ZRANGEBYSCORE: await ProcessSortedSetAsync(exchange).ConfigureAwait(false); break; // Geo case RedisOperationType.GEOADD: case RedisOperationType.GEODIST: case RedisOperationType.GEORADIUS: await ProcessGeoAsync(exchange).ConfigureAwait(false); break; // HyperLogLog case RedisOperationType.PFADD: case RedisOperationType.PFCOUNT: case RedisOperationType.PFMERGE: await ProcessHyperLogLogAsync(exchange).ConfigureAwait(false); break; // Bitmap case RedisOperationType.SETBIT: case RedisOperationType.GETBIT: case RedisOperationType.BITCOUNT: await ProcessBitmapAsync(exchange).ConfigureAwait(false); break; // Arbitrary case RedisOperationType.COMMAND: await ProcessCommandAsync(exchange).ConfigureAwait(false); break; default: throw new NotSupportedException($"Producer does not support operation: {_endpoint.OperationType}"); } } // ═══════════════════════════════════════════════════════════ // Key/Value (Cache) // ═══════════════════════════════════════════════════════════ private async Task ProcessCacheAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.SET: var value = BodyToRedisValue(exchange.In.Body); if (_options.Ttl > 0) await _db!.StringSetAsync(key, value, TimeSpan.FromSeconds(_options.Ttl)).ConfigureAwait(false); else await _db!.StringSetAsync(key, value).ConfigureAwait(false); RecordWritten(value); SetResult(exchange, "OK"); break; case RedisOperationType.GET: var result = await _db!.StringGetAsync(key).ConfigureAwait(false); SetResult(exchange, result.HasValue ? result.ToString() : null); break; case RedisOperationType.DEL: var deleted = await _db!.KeyDeleteAsync(key).ConfigureAwait(false); SetResult(exchange, deleted); break; case RedisOperationType.EXISTS: var exists = await _db!.KeyExistsAsync(key).ConfigureAwait(false); SetResult(exchange, exists); break; case RedisOperationType.EXPIRE: var ttl = _options.Ttl > 0 ? TimeSpan.FromSeconds(_options.Ttl) : TimeSpan.FromHours(1); var expired = await _db!.KeyExpireAsync(key, ttl).ConfigureAwait(false); SetResult(exchange, expired); break; case RedisOperationType.INCR: var incremented = await _db!.StringIncrementAsync(key).ConfigureAwait(false); SetResult(exchange, incremented); break; case RedisOperationType.DECR: var decremented = await _db!.StringDecrementAsync(key).ConfigureAwait(false); SetResult(exchange, decremented); break; case RedisOperationType.SETNX: var setnxValue = BodyToRedisValue(exchange.In.Body); bool wasSet; if (_options.Ttl > 0) wasSet = await _db!.StringSetAsync(key, setnxValue, TimeSpan.FromSeconds(_options.Ttl), When.NotExists).ConfigureAwait(false); else wasSet = await _db!.StringSetAsync(key, setnxValue, when: When.NotExists).ConfigureAwait(false); RecordWritten(setnxValue); // sent whether or not the key was free SetResult(exchange, wasSet ? "OK" : null); break; } } // ═══════════════════════════════════════════════════════════ // Pub/Sub // ═══════════════════════════════════════════════════════════ private async Task ProcessPublishAsync(IExchange exchange) { var channel = _options.ResolveOption(_options.Channel ?? _endpoint.Resource, exchange) ?? _endpoint.Resource; var message = BodyToRedisValue(exchange.In.Body); var recipients = await _subscriber!.PublishAsync( new RedisChannel(channel, RedisChannel.PatternMode.Literal), message).ConfigureAwait(false); RecordWritten(message); SetResult(exchange, recipients); exchange.In.Headers[RedisHeaders.PublishRecipients] = recipients; Logger?.LogDebug("Redis PUBLISH: channel={Channel}, recipients={Recipients}", channel, recipients); } // ═══════════════════════════════════════════════════════════ // Streams // ═══════════════════════════════════════════════════════════ private async Task ProcessStreamAddAsync(IExchange exchange) { var streamName = _options.ResolveOption(_options.StreamName ?? _endpoint.Resource, exchange) ?? _endpoint.Resource; var fields = GetStreamFields(exchange); var maxLength = _options.StreamMaxLength > 0 ? (int?)_options.StreamMaxLength : null; var messageId = await _db!.StreamAddAsync( streamName, fields.ToArray(), maxLength: maxLength, useApproximateMaxLength: _options.StreamApproximate).ConfigureAwait(false); foreach (var entry in fields) RecordWritten(entry.Value); SetResult(exchange, messageId.ToString()); exchange.In.Headers[RedisHeaders.StreamMessageId] = messageId.ToString(); Logger?.LogDebug("Redis XADD: stream={Stream}, messageId={Id}", streamName, messageId); } /// /// Counts a value a write command carried (SET, SETNX, PUBLISH, XADD and HMSET values, LPUSH, RPUSH, HSET, SADD, /// ZADD) in the endpoint's BytesOut, once the command succeeded. Keys, field names and read commands are not counted. /// private void RecordWritten(RedisValue value) => _endpoint.RecordBytesOut(value.GetByteCount()); /// /// Coerces an exchange Body to a suitable for Redis commands. /// Honours pre-marshalled [] (passed as binary RedisValue), /// strings, and falls back to for arbitrary types. /// Avoids the previous Body?.ToString() trap that emitted "System.Byte[]" /// when an upstream .Marshal() step had already produced JSON bytes. /// private static RedisValue BodyToRedisValue(object? body) => body switch { null => RedisValue.EmptyString, byte[] arr => arr, string s => s, _ => BodyText.Of(body) }; // ═══════════════════════════════════════════════════════════ // Lists // ═══════════════════════════════════════════════════════════ private async Task ProcessListAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.LPUSH: var lpushValue = BodyToRedisValue(exchange.In.Body); var lpushLen = await _db!.ListLeftPushAsync(key, lpushValue).ConfigureAwait(false); RecordWritten(lpushValue); SetResult(exchange, lpushLen); break; case RedisOperationType.RPUSH: var rpushValue = BodyToRedisValue(exchange.In.Body); var rpushLen = await _db!.ListRightPushAsync(key, rpushValue).ConfigureAwait(false); RecordWritten(rpushValue); SetResult(exchange, rpushLen); break; case RedisOperationType.LPOP: var lpop = await _db!.ListLeftPopAsync(key).ConfigureAwait(false); SetResult(exchange, lpop.HasValue ? lpop.ToString() : null); break; case RedisOperationType.RPOP: var rpop = await _db!.ListRightPopAsync(key).ConfigureAwait(false); SetResult(exchange, rpop.HasValue ? rpop.ToString() : null); break; case RedisOperationType.LLEN: var len = await _db!.ListLengthAsync(key).ConfigureAwait(false); SetResult(exchange, len); break; case RedisOperationType.LRANGE: var start = _options.Start ?? 0; var stop = _options.Stop ?? -1; var range = await _db!.ListRangeAsync(key, start, stop).ConfigureAwait(false); SetResult(exchange, range.Select(v => v.ToString()).ToArray()); break; } } // ═══════════════════════════════════════════════════════════ // Hashes // ═══════════════════════════════════════════════════════════ private async Task ProcessHashAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.HSET: var field = RequireField(exchange); var hsetValue = BodyToRedisValue(exchange.In.Body); var wasSet = await _db!.HashSetAsync(key, field, hsetValue).ConfigureAwait(false); RecordWritten(hsetValue); SetResult(exchange, wasSet); break; case RedisOperationType.HGET: field = RequireField(exchange); var hgetResult = await _db!.HashGetAsync(key, field).ConfigureAwait(false); SetResult(exchange, hgetResult.HasValue ? hgetResult.ToString() : null); break; case RedisOperationType.HMSET: var hashFields = GetHashFields(exchange); await _db!.HashSetAsync(key, hashFields.ToArray()).ConfigureAwait(false); foreach (var entry in hashFields) RecordWritten(entry.Value); SetResult(exchange, "OK"); break; case RedisOperationType.HMGET: var fieldNames = GetFieldNames(exchange); var hmgetResults = await _db!.HashGetAsync(key, fieldNames).ConfigureAwait(false); SetResult(exchange, hmgetResults.Select(v => v.HasValue ? v.ToString() : null).ToArray()); break; case RedisOperationType.HGETALL: var all = await _db!.HashGetAllAsync(key).ConfigureAwait(false); SetResult(exchange, all.ToDictionary(h => h.Name.ToString(), h => (object?)h.Value.ToString())); break; case RedisOperationType.HDEL: field = RequireField(exchange); var hdel = await _db!.HashDeleteAsync(key, field).ConfigureAwait(false); SetResult(exchange, hdel); break; case RedisOperationType.HLEN: var hlen = await _db!.HashLengthAsync(key).ConfigureAwait(false); SetResult(exchange, hlen); break; } } // ═══════════════════════════════════════════════════════════ // Sets // ═══════════════════════════════════════════════════════════ private async Task ProcessSetAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.SADD: var saddValue = BodyToRedisValue(exchange.In.Body); var added = await _db!.SetAddAsync(key, saddValue).ConfigureAwait(false); RecordWritten(saddValue); SetResult(exchange, added); break; case RedisOperationType.SREM: var removed = await _db!.SetRemoveAsync(key, BodyToRedisValue(exchange.In.Body)).ConfigureAwait(false); SetResult(exchange, removed); break; case RedisOperationType.SMEMBERS: var members = await _db!.SetMembersAsync(key).ConfigureAwait(false); SetResult(exchange, members.Select(m => m.ToString()).ToArray()); break; case RedisOperationType.SCARD: var count = await _db!.SetLengthAsync(key).ConfigureAwait(false); SetResult(exchange, count); break; case RedisOperationType.SISMEMBER: var isMember = await _db!.SetContainsAsync(key, BodyToRedisValue(exchange.In.Body)).ConfigureAwait(false); SetResult(exchange, isMember); break; } } // ═══════════════════════════════════════════════════════════ // Sorted Sets // ═══════════════════════════════════════════════════════════ private async Task ProcessSortedSetAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.ZADD: var score = _options.Score ?? throw new InvalidOperationException("Score is required for ZADD (use ?score=N)."); var zaddValue = BodyToRedisValue(exchange.In.Body); var zadded = await _db!.SortedSetAddAsync(key, zaddValue, score).ConfigureAwait(false); RecordWritten(zaddValue); SetResult(exchange, zadded); break; case RedisOperationType.ZREM: var zremoved = await _db!.SortedSetRemoveAsync(key, BodyToRedisValue(exchange.In.Body)).ConfigureAwait(false); SetResult(exchange, zremoved); break; case RedisOperationType.ZRANGE: var start = _options.Start ?? 0; var stop = _options.Stop ?? -1; var zrange = await _db!.SortedSetRangeByRankAsync(key, start, stop).ConfigureAwait(false); SetResult(exchange, zrange.Select(v => v.ToString()).ToArray()); break; case RedisOperationType.ZCARD: var zcard = await _db!.SortedSetLengthAsync(key).ConfigureAwait(false); SetResult(exchange, zcard); break; case RedisOperationType.ZSCORE: var zscore = await _db!.SortedSetScoreAsync(key, BodyToRedisValue(exchange.In.Body)).ConfigureAwait(false); SetResult(exchange, zscore); break; case RedisOperationType.ZRANGEBYSCORE: var min = _options.MinScore ?? throw new InvalidOperationException("MinScore required for ZRANGEBYSCORE."); var max = _options.MaxScore ?? throw new InvalidOperationException("MaxScore required for ZRANGEBYSCORE."); var byScore = await _db!.SortedSetRangeByScoreAsync(key, min, max).ConfigureAwait(false); SetResult(exchange, byScore.Select(v => v.ToString()).ToArray()); break; } } // ═══════════════════════════════════════════════════════════ // Geospatial // ═══════════════════════════════════════════════════════════ private async Task ProcessGeoAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.GEOADD: var lon = _options.Longitude ?? throw new InvalidOperationException("Longitude required for GEOADD."); var lat = _options.Latitude ?? throw new InvalidOperationException("Latitude required for GEOADD."); var member = BodyToRedisValue(exchange.In.Body); var geoAdded = await _db!.GeoAddAsync(key, lon, lat, member).ConfigureAwait(false); SetResult(exchange, geoAdded); break; case RedisOperationType.GEODIST: var m1 = _options.Member1 ?? throw new InvalidOperationException("Member1 required for GEODIST."); var m2 = _options.Member2 ?? throw new InvalidOperationException("Member2 required for GEODIST."); var unit = ParseGeoUnit(_options.GeoUnit); var dist = await _db!.GeoDistanceAsync(key, m1, m2, unit).ConfigureAwait(false); SetResult(exchange, dist); break; case RedisOperationType.GEORADIUS: var cLon = exchange.In.GetHeader(RedisHeaders.CenterLongitude); var cLat = exchange.In.GetHeader(RedisHeaders.CenterLatitude); var radius = exchange.In.GetHeader(RedisHeaders.Radius); var rUnit = ParseGeoUnit(exchange.In.GetHeader(RedisHeaders.RadiusUnit) ?? "m"); var geoResults = await _db!.GeoRadiusAsync(key, cLon, cLat, radius, rUnit).ConfigureAwait(false); SetResult(exchange, geoResults.Select(r => r.Member.ToString()).ToArray()); break; } } // ═══════════════════════════════════════════════════════════ // HyperLogLog // ═══════════════════════════════════════════════════════════ private async Task ProcessHyperLogLogAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.PFADD: var added = await _db!.HyperLogLogAddAsync(key, BodyToRedisValue(exchange.In.Body)).ConfigureAwait(false); SetResult(exchange, added); break; case RedisOperationType.PFCOUNT: var count = await _db!.HyperLogLogLengthAsync(key).ConfigureAwait(false); SetResult(exchange, count); break; case RedisOperationType.PFMERGE: var sourceKeys = exchange.In.GetHeader(RedisHeaders.SourceKeys) ?? throw new InvalidOperationException("SourceKeys header required for PFMERGE."); await _db!.HyperLogLogMergeAsync(key, sourceKeys.Select(k => (RedisKey)k).ToArray()).ConfigureAwait(false); SetResult(exchange, "OK"); break; } } // ═══════════════════════════════════════════════════════════ // Bitmap // ═══════════════════════════════════════════════════════════ private async Task ProcessBitmapAsync(IExchange exchange) { var key = ResolveKey(exchange); switch (_endpoint.OperationType) { case RedisOperationType.SETBIT: var offset = _options.Offset ?? exchange.In.GetHeader(RedisHeaders.BitOffset); var bit = _options.Bit ?? exchange.In.GetHeader(RedisHeaders.Bit); var oldBit = await _db!.StringSetBitAsync(key, offset, bit).ConfigureAwait(false); SetResult(exchange, oldBit); break; case RedisOperationType.GETBIT: offset = _options.Offset ?? exchange.In.GetHeader(RedisHeaders.BitOffset); var getBit = await _db!.StringGetBitAsync(key, offset).ConfigureAwait(false); SetResult(exchange, getBit); break; case RedisOperationType.BITCOUNT: var bitCount = await _db!.StringBitCountAsync(key).ConfigureAwait(false); SetResult(exchange, bitCount); break; } } // ═══════════════════════════════════════════════════════════ // Command (arbitrary) // ═══════════════════════════════════════════════════════════ private async Task ProcessCommandAsync(IExchange exchange) { var command = _options.Command ?? exchange.In.GetHeader(RedisHeaders.Command) ?? throw new InvalidOperationException("Command is required for COMMAND operation."); var args = GetCommandArguments(exchange); var result = await _db!.ExecuteAsync(command, args).ConfigureAwait(false); SetResult(exchange, result?.ToString()); } // ═══════════════════════════════════════════════════════════ // Transactional (deferred write) // ═══════════════════════════════════════════════════════════ /// /// PUBLISH and XADD announce work, like a broker send: they follow the enclosing .Transacted() block unless /// transacted says otherwise. Every other operation changes data and waits for the commit only when /// transacted=true asks for it (the constructor has already refused it for an operation that cannot wait). /// private bool DefersToTheCommit(IExchange exchange) => _endpoint.OperationType is RedisOperationType.PUBLISH or RedisOperationType.XADD ? TransactedActions.Defers(exchange, _options.Transacted) : _options.Transacted == true; private void DeferToTheCommit(IExchange exchange) { // The same operation, carried out after the commit on a snapshot of the exchange as it is at this step: the key, // body, fields, headers and ttl are the ones the step sees now, whatever the route does to the exchange later. var snapshot = exchange.Snapshot(); var op = _endpoint.OperationType; TransactedActions.RegisterSend(exchange, $"redis-{op}-{Guid.NewGuid():N}", async ct => { await DispatchOperationAsync(snapshot, ct).ConfigureAwait(false); // What an announcement reports reaches the exchange with the commit. var reported = op switch { RedisOperationType.XADD => RedisHeaders.StreamMessageId, RedisOperationType.PUBLISH => RedisHeaders.PublishRecipients, _ => null }; if (reported is not null && snapshot.In.Headers.TryGetValue(reported, out var value)) exchange.In.Headers[reported] = value; }, ProducerName); } /// /// Whether an operation can wait for a commit: the writes can; an operation that exists for what it returns (a read, /// a pop) or that consumes cannot. Listed one by one, so a new operation is classified on purpose. /// private static bool CanDefer(RedisOperationType op) => op switch { RedisOperationType.SET or RedisOperationType.SETNX or RedisOperationType.DEL or RedisOperationType.EXPIRE or RedisOperationType.INCR or RedisOperationType.DECR or RedisOperationType.PUBLISH or RedisOperationType.XADD or RedisOperationType.LPUSH or RedisOperationType.RPUSH or RedisOperationType.HSET or RedisOperationType.HMSET or RedisOperationType.HDEL or RedisOperationType.SADD or RedisOperationType.SREM or RedisOperationType.ZADD or RedisOperationType.ZREM or RedisOperationType.GEOADD or RedisOperationType.PFADD or RedisOperationType.PFMERGE or RedisOperationType.SETBIT or RedisOperationType.COMMAND => true, _ => false }; // ═══════════════════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════════════════ private string ResolveKey(IExchange exchange) { var raw = _options.Key ?? _endpoint.Resource; if (string.IsNullOrEmpty(raw)) throw new InvalidOperationException("Redis key is required but not set in URI or options."); return _options.ResolveOption(raw, exchange) ?? raw; } private string RequireField(IExchange exchange) { var raw = _options.Field ?? throw new InvalidOperationException("Field is required (use ?field=name in URI)."); return _options.ResolveOption(raw, exchange) ?? raw; } private static void SetResult(IExchange exchange, object? value) { exchange.Out ??= new Message(); exchange.Out.Body = value; exchange.Pattern = ExchangePattern.InOut; } private List GetStreamFields(IExchange exchange) { // Check for StreamFields header (Dictionary) — prefixed name, bare accepted for compat if ((exchange.In.Headers.TryGetValue(RedisHeaders.StreamFields, out var raw) || exchange.In.Headers.TryGetValue("StreamFields", out raw)) && raw is Dictionary dict) { return dict.Select(kv => new NameValueEntry(kv.Key, kv.Value?.ToString() ?? "")).ToList(); } // Default: body as "data" field return new List { new("data", BodyToRedisValue(exchange.In.Body)), new("timestamp", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString()) }; } private List GetHashFields(IExchange exchange) { if (exchange.In.Headers.TryGetValue(RedisHeaders.HashFields, out var raw) && raw is Dictionary dict) { return dict.Select(kv => new HashEntry(kv.Key, kv.Value?.ToString() ?? "")).ToList(); } var field = RequireField(exchange); return new List { new(field, BodyToRedisValue(exchange.In.Body)) }; } private RedisValue[] GetFieldNames(IExchange exchange) { if (exchange.In.Headers.TryGetValue(RedisHeaders.FieldNames, out var raw) && raw is string[] names) return names.Select(f => (RedisValue)f).ToArray(); return new RedisValue[] { RequireField(exchange) }; } private static object[] GetCommandArguments(IExchange exchange) { if (exchange.In.Headers.TryGetValue(RedisHeaders.CommandArgs, out var raw) && raw is string[] args) return args.Cast().ToArray(); return new object[] { BodyToRedisValue(exchange.In.Body) }; } private static GeoUnit ParseGeoUnit(string unit) => unit.ToLowerInvariant() switch { "km" => GeoUnit.Kilometers, "mi" => GeoUnit.Miles, "ft" => GeoUnit.Feet, _ => GeoUnit.Meters }; } Path: redb-route/redb.Route.Redis/Repositories/RedisClaimCheckRepository.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/Repositories/RedisClaimCheckRepository.cs ---- using System; using System.Threading; using System.Threading.Tasks; using redb.Route.Abstractions; using StackExchange.Redis; namespace redb.Route.Redis.Repositories; /// /// Redis-backed implementation of . /// Uses Redis STRING commands for binary-safe storage with native TTL. /// Thread-safe; manages its own connection via . /// public sealed class RedisClaimCheckRepository : IClaimCheckRepository, IAsyncDisposable, IDisposable { private readonly RedisConnectionFactory _factory; private readonly string _keyPrefix; private readonly TimeSpan _defaultTtl; private readonly SemaphoreSlim _connectionLock = new(1, 1); private IConnectionMultiplexer? _connection; // Lua script for atomic GET+DEL (GETDEL available only in Redis 6.2+) private const string GetAndDeleteScript = """ local val = redis.call('GET', KEYS[1]) if val then redis.call('DEL', KEYS[1]) end return val """; /// /// Creates a new Redis claim check repository. /// /// Redis connection factory with connection settings. /// Key prefix for all claim check entries (default: "redb:claimcheck:"). /// Default TTL for entries. Zero means no expiry. public RedisClaimCheckRepository( RedisConnectionFactory factory, string keyPrefix = "redb:claimcheck:", TimeSpan? defaultTtl = null) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _keyPrefix = keyPrefix; _defaultTtl = defaultTtl ?? TimeSpan.Zero; } /// public async Task Store(ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default) { var key = Guid.NewGuid().ToString("N"); await StoreInternal(key, data, ttl, ct).ConfigureAwait(false); return key; } /// public async Task Store(string key, ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); await StoreInternal(key, data, ttl, ct).ConfigureAwait(false); } /// public async Task Retrieve(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); var db = await GetDatabaseAsync(ct).ConfigureAwait(false); var value = await db.StringGetAsync(PrefixKey(key)).ConfigureAwait(false); return value.IsNull ? null : (byte[])value!; } /// public async Task RetrieveAndRemove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); var db = await GetDatabaseAsync(ct).ConfigureAwait(false); var result = await db.ScriptEvaluateAsync( GetAndDeleteScript, [(RedisKey)PrefixKey(key)]).ConfigureAwait(false); return result.IsNull ? null : (byte[])result!; } /// public async Task Remove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); var db = await GetDatabaseAsync(ct).ConfigureAwait(false); await db.KeyDeleteAsync(PrefixKey(key)).ConfigureAwait(false); } private async Task StoreInternal(string key, ReadOnlyMemory data, TimeSpan? ttl, CancellationToken ct) { var db = await GetDatabaseAsync(ct).ConfigureAwait(false); var effectiveTtl = ttl ?? _defaultTtl; var redisKey = (RedisKey)PrefixKey(key); var redisValue = (RedisValue)data.ToArray(); if (effectiveTtl > TimeSpan.Zero) await db.StringSetAsync(redisKey, redisValue, effectiveTtl).ConfigureAwait(false); else await db.StringSetAsync(redisKey, redisValue).ConfigureAwait(false); } private string PrefixKey(string key) => $"{_keyPrefix}{key}"; private async Task GetDatabaseAsync(CancellationToken ct) { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); await _connectionLock.WaitAsync(ct).ConfigureAwait(false); try { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); var config = _factory.Build(); _connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false); return _connection.GetDatabase(_factory.Database); } finally { _connectionLock.Release(); } } /// public async ValueTask DisposeAsync() { try { if (_connection is not null) { await _connection.CloseAsync().ConfigureAwait(false); _connection.Dispose(); _connection = null; } } finally { _connectionLock.Dispose(); } } /// public void Dispose() { _connection?.Close(); _connection?.Dispose(); _connection = null; _connectionLock.Dispose(); } } Path: redb-route/redb.Route.Redis/redb.Route.Redis.csproj 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/redb.Route.Redis.csproj ---- redb.Route.Redis Redis transport for redb.Route ESB framework. esb;messaging;redis;redb README.md