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(); }