Bundle: redb-route / redb.Route (redb.Route.txt), 317 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/Abstractions/Attachment.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/Abstractions/Attachment.cs ---- namespace redb.Route.Abstractions; /// /// One attachment of a message (Apache Camel's Attachment): a named piece of content that travels beside the body, /// such as a file of a multipart/form-data upload, a mail attachment or an MTOM part. Immutable: replace it on the /// message with . /// /// /// The text fields end up in MIME headers when a producer writes the attachment, so a carriage return or line feed in /// any of them is rejected here rather than written onto the wire. /// public sealed class Attachment { private static readonly IReadOnlyDictionary NoHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly string _name = null!; private readonly string? _fileName; private readonly string _contentType = DefaultContentType; private readonly string? _contentId; private readonly IReadOnlyDictionary _headers = NoHeaders; /// Content type of an attachment that does not declare one. public const string DefaultContentType = "application/octet-stream"; /// /// The key the message finds the attachment by: the file name, the form field name or the Content-ID, /// whichever the source of the attachment uses. Names may repeat on one message. /// public required string Name { get => _name; init => _name = RequireText(value, nameof(Name)); } /// Original file name, without a directory, when the attachment came as a file. public string? FileName { get => _fileName; init => _fileName = value is null ? null : RequireText(value, nameof(FileName)); } /// MIME type of the content; when not set. public string ContentType { get => _contentType; init => _contentType = RequireText(value, nameof(ContentType)); } /// MIME Content-ID without the angle brackets, for parts referenced as cid:. public string? ContentId { get => _contentId; init => _contentId = value is null ? null : RequireText(value, nameof(ContentId)); } /// Headers of the MIME part the attachment came from; empty when it did not come from one. public IReadOnlyDictionary Headers { get => _headers; init { ArgumentNullException.ThrowIfNull(value); var copy = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var (key, text) in value) copy[RequireText(key, nameof(Headers))] = RequireText(text, nameof(Headers), allowEmpty: true); _headers = copy; } } /// The content, readable as often as needed. public required AttachmentContent Content { get; init; } /// Length of the content in bytes (attachments[0].length in an expression). public long Length => Content.Length; /// A copy of this attachment with other content (the metadata stays). public Attachment WithContent(AttachmentContent content) { ArgumentNullException.ThrowIfNull(content); return new Attachment { Name = Name, FileName = FileName, ContentType = ContentType, ContentId = ContentId, Headers = Headers, Content = content }; } private static string RequireText(string? value, string field, bool allowEmpty = false) { if (value is null || (!allowEmpty && value.Length == 0)) throw new ArgumentException($"Attachment {field} must not be empty.", field); if (value.AsSpan().IndexOfAny('\r', '\n') >= 0) throw new ArgumentException($"Attachment {field} must not contain a line break.", field); return value; } } Path: redb-route/redb.Route/Abstractions/AttachmentContent.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/Abstractions/AttachmentContent.cs ---- using redb.Route.Core; namespace redb.Route.Abstractions; /// /// The content of an : a source that opens a new stream from the start on every read. Reading /// more than once is required, not optional: Multicast branches, redelivery and a resend over a fresh connection all /// read the same attachment again, so a forward-only stream is not accepted as a source. /// /// /// A source that holds a resource (a , a file to delete) implements /// ; the exchange that carries the message releases it like a disposable body. /// public abstract class AttachmentContent { /// Length of the content in bytes. public abstract long Length { get; } /// Opens a new read-only stream positioned at the start of the content. public abstract Stream OpenRead(); /// Opens a new read-only stream positioned at the start of the content. public virtual ValueTask OpenReadAsync(CancellationToken ct = default) => ValueTask.FromResult(OpenRead()); /// Reads the whole content into a new array. public virtual byte[] ReadAllBytes() { using var stream = OpenRead(); using var buffer = new MemoryStream(Length > int.MaxValue ? 0 : (int)Length); stream.CopyTo(buffer); return buffer.ToArray(); } /// Reads the whole content into a new array. public virtual async ValueTask ReadAllBytesAsync(CancellationToken ct = default) { var stream = await OpenReadAsync(ct).ConfigureAwait(false); await using (stream.ConfigureAwait(false)) { using var buffer = new MemoryStream(Length > int.MaxValue ? 0 : (int)Length); await stream.CopyToAsync(buffer, ct).ConfigureAwait(false); return buffer.ToArray(); } } /// /// An isolated copy for a checkpoint snapshot: the content is read into memory, so the copy outlives the source and /// later changes to it. /// public virtual AttachmentContent DeepCopy() => new BytesContent(ReadAllBytes()); /// Content held in memory. The array is shared, not copied, like a byte[] body. public static AttachmentContent FromBytes(byte[] bytes) { ArgumentNullException.ThrowIfNull(bytes); return new BytesContent(bytes); } /// Content of a file, read from disk on every open. /// Path of an existing file. /// true to delete the file when the exchange carrying the message is released. public static AttachmentContent FromFile(string path, bool deleteWithExchange = false) { ArgumentException.ThrowIfNullOrEmpty(path); var full = Path.GetFullPath(path); if (!File.Exists(full)) throw new FileNotFoundException("Attachment file does not exist.", full); return deleteWithExchange ? new OwnedFileContent(full) : new FileContent(full); } /// /// Content of a completed ; every open gets an independent reader. The cache is disposed /// with the exchange carrying the message. /// public static AttachmentContent FromStreamCache(StreamCache cache) { ArgumentNullException.ThrowIfNull(cache); if (!cache.CanRead) throw new ArgumentException("The StreamCache must be completed (CompleteWriting) before it becomes attachment content.", nameof(cache)); return new StreamCacheContent(cache); } private sealed class BytesContent(byte[] bytes) : AttachmentContent { public override long Length => bytes.LongLength; public override Stream OpenRead() => new MemoryStream(bytes, writable: false); public override byte[] ReadAllBytes() => (byte[])bytes.Clone(); public override ValueTask ReadAllBytesAsync(CancellationToken ct = default) => ValueTask.FromResult(ReadAllBytes()); public override AttachmentContent DeepCopy() => new BytesContent((byte[])bytes.Clone()); } private class FileContent(string path) : AttachmentContent { protected string FilePath => path; public override long Length => new FileInfo(path).Length; public override Stream OpenRead() => new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 81920, FileOptions.SequentialScan); public override ValueTask OpenReadAsync(CancellationToken ct = default) => ValueTask.FromResult(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan)); } private sealed class OwnedFileContent(string path) : FileContent(path), IAsyncDisposable { public ValueTask DisposeAsync() { File.Delete(FilePath); return ValueTask.CompletedTask; } } private sealed class StreamCacheContent(StreamCache cache) : AttachmentContent, IAsyncDisposable { public override long Length => cache.Length; public override Stream OpenRead() => cache.OpenReader(); public ValueTask DisposeAsync() => cache.DisposeAsync(); } } Path: redb-route/redb.Route/Abstractions/ClaimCheckHeaders.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/Abstractions/ClaimCheckHeaders.cs ---- namespace redb.Route.Abstractions; /// /// Well-known header and property constants used by the Claim Check pattern. /// public static class ClaimCheckHeaders { /// Claim key stored/read by ClaimCheck processors. public const string Key = "ClaimCheck.Key"; /// Original content type before claim check storage. public const string OriginalContentType = "ClaimCheck.OriginalContentType"; /// Original CLR body type for typed deserialization. public const string OriginalBodyType = "ClaimCheck.OriginalBodyType"; /// Exchange property key for the push/pop key stack. internal const string StackPropertyKey = "ClaimCheck.Stack"; } Path: redb-route/redb.Route/Abstractions/ClaimCheckOperation.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/Abstractions/ClaimCheckOperation.cs ---- namespace redb.Route.Abstractions; /// /// Defines the operation to perform in a Claim Check step. /// public enum ClaimCheckOperation { /// Store body under a specific key (key-value mode). Set, /// Retrieve body by key, keep data in store. Get, /// Retrieve body by key, remove data from store. GetAndRemove, /// Push body onto an exchange-scoped stack (no key needed). Push, /// Pop body from the exchange-scoped stack (no key needed). Pop } Path: redb-route/redb.Route/Abstractions/EndpointUri.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/Abstractions/EndpointUri.cs ---- using System.Text; using System.Text.RegularExpressions; namespace redb.Route.Abstractions; /// /// Parsed endpoint URI. Immutable record with normalized cache key. /// Created by EndpointUriParser — the single URI parser for the entire framework. /// /// URI scheme (e.g., "kafka", "rabbitmq", "redis", "direct"). /// Path part (e.g., "orders", "GET:user:123", "my-topic"). /// Cache key: "{scheme}://{path}" without query parameters. /// Query string parameters as raw strings before type conversion. public sealed record EndpointUri( string Scheme, string Path, string NormalizedKey, IReadOnlyDictionary RawParameters) { /// Constant emitted in place of a redacted secret value. public const string Redacted = "****"; /// /// Cache key without query parameters: scheme://path. /// Used by in-process transports (Direct, SEDA) where consumer and producer /// must share the same endpoint regardless of per-side options. /// public string BaseKey => $"{Scheme}://{Path}"; /// public override string ToString() => ToMaskedUriString(); /// /// Reconstructs the full URI string including scheme, path, and all query parameters. /// Example: seda:order-queue?concurrentConsumers=4&size=1000 /// public string ToUriString() { if (RawParameters.Count == 0) return $"{Scheme}:{Path}"; var sb = new StringBuilder(); sb.Append(Scheme); sb.Append(':'); sb.Append(Path); var sep = '?'; foreach (var (key, value) in RawParameters) { sb.Append(sep); sb.Append(Uri.EscapeDataString(key)); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } return sb.ToString(); } // --- Secret detection ------------------------------------------------ // Substring keywords (case-insensitive). A parameter name is treated as a // secret if it CONTAINS any of these. Deliberately avoids bare "key"/"pass" // so benign params (routingKey, partitionKey, ...) are never over-masked; // "password" already covers bindPassword/sslKeyPassword/proxyPassword/etc. private static readonly string[] SensitiveKeywords = { "password", "passphrase", "pwd", "secret", "token", "apikey", "accesskey", "credential", "connectionstring", "privatekey", "authorization", "bearer", "sasljaasconfig" }; // Connector-registered extra names (copy-on-write; read via a stable snapshot). private static volatile HashSet _extraSensitiveKeys = new(StringComparer.OrdinalIgnoreCase); /// /// Registers additional query-parameter names that must be masked in logs and /// telemetry (analogous to Camel's addSanitizeKeywords). Case-insensitive. /// Intended to be called once at startup by connector registration. /// public static void AddSensitiveKeys(params string[] keys) { if (keys is null || keys.Length == 0) return; var copy = new HashSet(_extraSensitiveKeys, StringComparer.OrdinalIgnoreCase); foreach (var k in keys) if (!string.IsNullOrWhiteSpace(k)) copy.Add(k.Trim()); _extraSensitiveKeys = copy; } /// Returns true if a query-parameter name should be masked. public static bool IsSensitiveKey(string key) { if (string.IsNullOrEmpty(key)) return false; if (_extraSensitiveKeys.Contains(key)) return true; foreach (var kw in SensitiveKeywords) if (key.Contains(kw, StringComparison.OrdinalIgnoreCase)) return true; return false; } // Masks the password segment of a "user:password@host..." authority/path. // Anchored at start so only the leading userinfo (authority position) matches; // a bare "host:port/seg@x" (no ':' before '@' within the authority) is left as-is. private static readonly Regex PathUserInfoPassword = new(@"^([^/@:]*:)([^/@]*)@", RegexOptions.Compiled); /// /// Masks the password in userinfo of a scheme-less path/authority /// (user:password@host → user:****@host). Returns the input /// unchanged when there is no userinfo password. /// public static string MaskUserInfoPassword(string pathOrAuthority) { if (string.IsNullOrEmpty(pathOrAuthority) || pathOrAuthority.IndexOf('@') < 0) return pathOrAuthority; return PathUserInfoPassword.Replace(pathOrAuthority, m => m.Groups[1].Value + Redacted + "@"); } /// /// Format-preserving redaction of a raw endpoint URI string. Keeps scheme, /// separator (:// vs :), path, parameter names, order, and every /// non-secret value byte-for-byte; replaces sensitive query-parameter values and /// the userinfo password with . Never throws. /// Use this at every logging / telemetry / DTO boundary that would otherwise emit /// a raw URI (Camel URISupport.sanitizeUri equivalent). /// public static string Sanitize(string? rawUri) { if (string.IsNullOrEmpty(rawUri)) return rawUri ?? string.Empty; var queryIndex = rawUri.IndexOf('?'); var basePart = queryIndex >= 0 ? rawUri[..queryIndex] : rawUri; var queryPart = queryIndex >= 0 ? rawUri[(queryIndex + 1)..] : null; // Mask userinfo password in the authority (only for scheme://authority form). var doubleSlash = basePart.IndexOf("://", StringComparison.Ordinal); if (doubleSlash > 0) { var head = basePart[..(doubleSlash + 3)]; var rest = basePart[(doubleSlash + 3)..]; basePart = head + MaskUserInfoPassword(rest); } if (queryPart is null) return basePart; var pairs = queryPart.Split('&'); for (var i = 0; i < pairs.Length; i++) { var pair = pairs[i]; var eq = pair.IndexOf('='); if (eq <= 0) continue; var rawKey = pair[..eq]; // Key may be URL-encoded; decode only for the sensitivity test. var key = Uri.UnescapeDataString(rawKey); if (IsSensitiveKey(key)) pairs[i] = rawKey + "=" + Redacted; } return basePart + "?" + string.Join("&", pairs); } /// The length up to which keeps a URI whole. public const int LogLength = 120; /// /// The short log form of a raw endpoint URI: d, and when longer than , /// cut at the last parameter boundary (? or &) that keeps at least half of it, or else at the length, /// never inside a value, followed by ... [+N chars #hash]. The hash is the first eight /// hex digits of the SHA-256 of the whole sanitized URI, so two endpoints that share a long prefix still read apart. /// public static string ForLog(string? rawUri) { var full = Sanitize(rawUri); if (full.Length <= LogLength) return full; var cut = full.LastIndexOfAny(['?', '&'], LogLength); if (cut < LogLength / 2) cut = LogLength; // A cut inside a masked value would show part of the mask, as if the secret were cut: keep the mask whole. for (var start = full.IndexOf(Redacted, StringComparison.Ordinal); start >= 0 && start < cut; start = full.IndexOf(Redacted, start + 1, StringComparison.Ordinal)) { if (start + Redacted.Length > cut) { cut = start + Redacted.Length; break; } } var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(full)))[..8].ToLowerInvariant(); return $"{full[..cut]}... [+{full.Length - cut} chars #{hash}]"; } /// /// An endpoint URI or name for an Information line of : the short form of /// , or the whole d URI on the same line when the logger has Debug /// on. Start and stop lines of the engine and the connectors use it. /// public static string ForLog(string? rawUri, Microsoft.Extensions.Logging.ILogger? logger) => logger?.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug) == true ? Sanitize(rawUri) : ForLog(rawUri); /// /// Redacts key=value secret assignments inside arbitrary text — connection strings /// (...;Password=p;...), query fragments, and driver exception messages that may embed /// either. Only the value of a key considered sensitive by is /// replaced, and the password of a URI quoted in the text (amqp://user:password@host); /// everything else is preserved verbatim. Never throws. /// /// Use this as the backstop for text that is not a parseable endpoint URI. Note that logging an /// object itself cannot be scrubbed in-process (the formatter renders /// ToString()); wire this into a logging-sink filter for that case. /// /// public static string RedactSecrets(string? text) { if (string.IsNullOrEmpty(text)) return string.Empty; // A URI quoted in the text may carry a password in its userinfo (amqp://user:password@host). text = RedactUserInfoPasswords(text); if (text.IndexOf('=') < 0) return text; var sb = new StringBuilder(text.Length); var i = 0; while (i < text.Length) { var eq = text.IndexOf('=', i); if (eq < 0) { sb.Append(text, i, text.Length - i); break; } // The key is the run of identifier-ish characters immediately before '='. var keyStart = eq; while (keyStart > i && IsKeyChar(text[keyStart - 1])) keyStart--; var key = text[keyStart..eq]; // The value runs to the next separator (connection-string ';', query '&', quote, space). var valueStart = eq + 1; var valueEnd = valueStart; while (valueEnd < text.Length && !IsValueDelimiter(text[valueEnd])) valueEnd++; sb.Append(text, i, eq - i + 1); // everything up to and including '=' if (valueEnd > valueStart && key.Length > 0 && IsSensitiveKey(key)) sb.Append(Redacted); else sb.Append(text, valueStart, valueEnd - valueStart); i = valueEnd; } return sb.ToString(); } /// /// Masks the password of every scheme://user:password@host in : the authority after /// :// runs to the next /, ?, #, quote or white space, and its userinfo (before the last /// @) keeps the user and loses what follows the first :. /// private static string RedactUserInfoPasswords(string text) { var marker = text.IndexOf("://", StringComparison.Ordinal); if (marker < 0) return text; var sb = new StringBuilder(text.Length); var i = 0; while (marker >= 0) { var authorityStart = marker + 3; var authorityEnd = authorityStart; while (authorityEnd < text.Length && !IsAuthorityEnd(text[authorityEnd])) authorityEnd++; sb.Append(text, i, authorityStart - i); var at = text.LastIndexOf('@', authorityEnd - 1, authorityEnd - authorityStart); var colon = at > authorityStart ? text.IndexOf(':', authorityStart, at - authorityStart) : -1; if (colon >= 0) { sb.Append(text, authorityStart, colon - authorityStart + 1); sb.Append(Redacted); sb.Append(text, at, authorityEnd - at); } else { sb.Append(text, authorityStart, authorityEnd - authorityStart); } i = authorityEnd; marker = authorityEnd < text.Length ? text.IndexOf("://", authorityEnd, StringComparison.Ordinal) : -1; } sb.Append(text, i, text.Length - i); return sb.ToString(); } private static bool IsAuthorityEnd(char c) => c is '/' or '?' or '#' or ';' or '"' or '\'' || char.IsWhiteSpace(c); private static bool IsKeyChar(char c) => char.IsLetterOrDigit(c) || c is '_' or '.' or '-'; private static bool IsValueDelimiter(char c) => c is ';' or '&' or '"' or '\'' || char.IsWhiteSpace(c); /// /// Reconstructs the URI with sensitive parameters and userinfo passwords masked. /// Secret values are fully redacted to (no partial disclosure). /// Example: rabbitmq:my-queue?host=localhost&username=admin&password=**** /// public string ToMaskedUriString() { var maskedPath = MaskUserInfoPassword(Path); if (RawParameters.Count == 0) return $"{Scheme}:{maskedPath}"; var sb = new StringBuilder(); sb.Append(Scheme); sb.Append(':'); sb.Append(maskedPath); var sep = '?'; foreach (var (key, value) in RawParameters) { sb.Append(sep); sb.Append(Uri.EscapeDataString(key)); sb.Append('='); sb.Append(IsSensitiveKey(key) ? Redacted : Uri.EscapeDataString(value)); sep = '&'; } return sb.ToString(); } } Path: redb-route/redb.Route/Abstractions/ExchangePattern.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/Abstractions/ExchangePattern.cs ---- namespace redb.Route.Abstractions; /// /// Defines the message exchange pattern for a route. /// Determines how In/Out messages are used during processing. /// public enum ExchangePattern { /// /// Fire-and-forget. Producer result is written to In. /// Out remains null. Default pattern for most routes. /// InOnly = 0, /// /// Request-reply. Original message preserved in In, /// response written to Out. Used for enrichment scenarios. /// InOut = 1, /// /// Explicit response. Created by DSL .Respond(). /// RPC reply is taken from Out. /// OutOnly = 2 } Path: redb-route/redb.Route/Abstractions/ExchangePrincipal.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/Abstractions/ExchangePrincipal.cs ---- using System.Security.Claims; namespace redb.Route.Abstractions; /// /// The identity of the caller an exchange came from (Apache Camel Exchange.AUTHENTICATION). /// A consumer that knows who sent the request stores the principal here, and processors, policies and /// tools read it from here rather than from transport-specific headers. /// /// It is an exchange property, not a header, on purpose. Headers are filled from the wire, so a /// caller can send any header name it likes, and producers bridge headers on to the next system. /// Properties are written only by code running in this process and never travel to a broker. Every /// exchange copy (child, linked child, clone, snapshot) inherits properties, so a sub-route, a split part /// or a tool call sees the identity of the request that started it. /// /// /// The server-side HTTP-family consumers fill it from the shared host's principal resolver or from the /// transport's own authenticate hook. A route that validates credentials itself — a bearer token checked /// in a processor — records the outcome the same way, with . /// /// public static class ExchangePrincipal { /// Exchange property key holding the principal (Camel: Exchange.AUTHENTICATION). public const string PropertyKey = "CamelAuthentication"; /// Returns the caller's principal, or null when the exchange carries no identity. public static ClaimsPrincipal? Get(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange); return exchange.Properties.TryGetValue(PropertyKey, out var raw) ? raw as ClaimsPrincipal : null; } /// Stores as the caller's identity; null removes it. public static void Set(IExchange exchange, ClaimsPrincipal? principal) { ArgumentNullException.ThrowIfNull(exchange); if (principal is null) exchange.Properties.Remove(PropertyKey); else exchange.Properties[PropertyKey] = principal; } } Path: redb-route/redb.Route/Abstractions/ExchangePropertyKeys.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/Abstractions/ExchangePropertyKeys.cs ---- namespace redb.Route.Abstractions; /// /// Names of the exchange properties the EIP processors set, as Apache Camel's ExchangePropertyKey. They are /// properties of the exchange, not message headers: they never travel to a broker with the message. Read them with /// exchange.GetProperty<T>(name) in C# and ${property.CamelSplitIndex} in the expression language. /// public static class ExchangePropertyKeys { /// /// Id of the exchange this one was copied from: set by Split and Multicast on every copy they make. /// public const string CorrelationId = "CamelCorrelationId"; /// Endpoint URI the exchange is being sent to, set by interceptSendToEndpoint. public const string ToEndpoint = "CamelToEndpoint"; /// Zero-based index of the part in a Split. public const string SplitIndex = "CamelSplitIndex"; /// /// Number of parts in a Split. A streaming Split knows it only at the end: the last part carries it, and the /// parent exchange carries it after the Split. /// public const string SplitSize = "CamelSplitSize"; /// Whether this is the last part of a Split. public const string SplitComplete = "CamelSplitComplete"; /// Zero-based index of the current iteration of a Loop. public const string LoopIndex = "CamelLoopIndex"; /// Number of iterations of a counted Loop (absent on a doWhile loop). public const string LoopSize = "CamelLoopSize"; /// Zero-based index of the branch in a Multicast. public const string MulticastIndex = "CamelMulticastIndex"; /// Whether this is the last branch of a Multicast. public const string MulticastComplete = "CamelMulticastComplete"; /// Number of exchanges an Aggregate combined into the completed one. public const string AggregatedSize = "CamelAggregatedSize"; /// What completed the aggregation: size, timeout, predicate, interval, force. public const string AggregatedCompletedBy = "CamelAggregatedCompletedBy"; /// Correlation key of the completed aggregation. public const string AggregatedCorrelationKey = "CamelAggregatedCorrelationKey"; /// Endpoint URI a Recipient List sends this copy to. public const string RecipientListEndpoint = "CamelRecipientListEndpoint"; /// Endpoint URI the current step of a Routing Slip sends to. public const string SlipEndpoint = "CamelSlipEndpoint"; /// Set to true by the Idempotent Consumer on a duplicate it lets through. public const string DuplicateMessage = "CamelDuplicateMessage"; } Path: redb-route/redb.Route/Abstractions/ExchangeResources.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/Abstractions/ExchangeResources.cs ---- namespace redb.Route.Abstractions; /// /// Resources an exchange releases when it ends (Apache Camel: exchange.getExchangeExtension().addOnCompletion(...)). /// A component that hands the route something still holding a connection — a streamed query result, say — registers it /// here, so the connection is returned when the exchange is released: whether or not the route used it, and whatever became /// of the body or header that carried it. /// /// Registered resources live in the exchange's properties under . The exchange releases them in /// ReleaseScopes (and so in DisposeAsync), most recent first and before its DI scopes; a failing release is /// logged and does not stop the others. Copies of the exchange — child, linked child, clone, snapshot — do not inherit them: /// a resource belongs to the exchange that registered it. /// /// /// Work that depends on how the exchange ended — confirm on success, undo on failure — registers an /// with instead: it runs when the exchange's unit of work /// ends, which for a consumed message is before the consumer acknowledges it or hands it back to the broker. /// /// public static class ExchangeResources { /// Property key prefix under which registered resources are kept. public const string PropertyPrefix = "__redb_resource:"; private const string ScopePrefix = "__redb_scope:"; private static long _sequence; /// Registers to be released when ends. public static void ReleaseWithExchange(IExchange exchange, IAsyncDisposable resource) { ArgumentNullException.ThrowIfNull(exchange); ArgumentNullException.ThrowIfNull(resource); // A fixed-width sequence keeps registration order sortable, so release can run most recent first. exchange.Properties[PropertyPrefix + Interlocked.Increment(ref _sequence).ToString("D19")] = resource; } /// /// Moves every resource registered on to , so it is released when /// ends (Apache Camel: handoverCompletions). Enrich uses it: the body it merges into the /// original exchange may be a stream still holding a connection, and the resource exchange it came from is disposed at once. /// public static void HandOver(IExchange from, IExchange to) { ArgumentNullException.ThrowIfNull(from); ArgumentNullException.ThrowIfNull(to); if (ReferenceEquals(from, to)) return; foreach (var key in from.Properties.Keys.Where(k => k.StartsWith(PropertyPrefix, StringComparison.Ordinal)).ToList()) { to.Properties[key] = from.Properties[key]; from.Properties.Remove(key); } } /// /// Registers to run when the unit of work of ends (Apache /// Camel: addOnCompletion with a Synchronization): when it /// succeeded, when it did not. /// /// The unit of work belongs to the outermost route the exchange entered and ends before that route returns to its /// consumer — so a completion has run before the message is acknowledged or handed back to the broker. A route called /// with the same exchange (direct:) shares it. An exchange that entered no route of its own — a Split or /// Multicast branch, the copy .Threads() continues on, an exchange processed outside any route — ends its unit of /// work when it is released, and its outcome is then read from the exchange. Copies do not inherit completions. /// /// public static void OnCompletion(IExchange exchange, IExchangeCompletion completion) { ArgumentNullException.ThrowIfNull(exchange); ArgumentNullException.ThrowIfNull(completion); if (!exchange.Properties.TryGetValue(ExchangeUnitOfWork.PropertyKey, out var value) || value is not ExchangeUnitOfWork unitOfWork) { unitOfWork = new ExchangeUnitOfWork(ownedByRoute: false); exchange.Properties[ExchangeUnitOfWork.PropertyKey] = unitOfWork; } unitOfWork.Add(completion); } /// /// Opens the unit of work of an exchange entering a route: a new one when the exchange has none, which the route then /// ends; when one is already open — the route was called with the exchange of another. /// internal static ExchangeUnitOfWork? OpenUnitOfWork(IExchange exchange) { if (exchange.Properties.ContainsKey(ExchangeUnitOfWork.PropertyKey)) return null; var unitOfWork = new ExchangeUnitOfWork(ownedByRoute: true); exchange.Properties[ExchangeUnitOfWork.PropertyKey] = unitOfWork; return unitOfWork; } /// The first completion of type registered on the exchange that matches. internal static T? FindCompletion(IExchange exchange, Func match) where T : class, IExchangeCompletion => exchange.Properties.TryGetValue(ExchangeUnitOfWork.PropertyKey, out var value) && value is ExchangeUnitOfWork unitOfWork ? unitOfWork.Find(match) : null; /// /// The property is the exchange's own bookkeeping — a cached DI scope, a registered resource, the unit of work — which /// copies do not inherit and property masks do not remove. /// internal static bool IsOwnedByExchange(string propertyKey) => propertyKey.StartsWith(ScopePrefix, StringComparison.Ordinal) || propertyKey.StartsWith(PropertyPrefix, StringComparison.Ordinal) || propertyKey == ExchangeUnitOfWork.PropertyKey || propertyKey == ResumePointsPropertyKey; /// /// Where routing picks up after a continued failure (Processors.ResumePoints): the exchange's own bookkeeping, /// naming pipelines of the route it is running in, which a copy must not inherit. /// private const string ResumePointsPropertyKey = "__redb_resume"; } Path: redb-route/redb.Route/Abstractions/ExchangeUnitOfWork.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/Abstractions/ExchangeUnitOfWork.cs ---- using Microsoft.Extensions.Logging; namespace redb.Route.Abstractions; /// /// An exchange's unit of work (Apache Camel: UnitOfWork): the completions registered with /// , run once, in registration order, when it ends. The outermost route the /// exchange entered opens and ends it (); otherwise the exchange's release ends it. /// internal sealed class ExchangeUnitOfWork { /// Exchange property holding the unit of work. Owned by the exchange: copies do not inherit it. internal const string PropertyKey = "__redb_uow"; private readonly object _gate = new(); private List? _completions; private bool _ended; internal ExchangeUnitOfWork(bool ownedByRoute) => OwnedByRoute = ownedByRoute; /// /// A route opened the unit of work and ends it before returning to its consumer; a release of the exchange in the /// middle of that route (an error handler calling ReleaseScopes) leaves it alone. /// internal bool OwnedByRoute { get; } internal void Add(IExchangeCompletion completion) { lock (_gate) { if (_ended) throw new InvalidOperationException( "The exchange's unit of work has already ended: a completion registered now would never run."); (_completions ??= []).Add(completion); } } internal T? Find(Func match) where T : class, IExchangeCompletion { lock (_gate) return _completions?.OfType().FirstOrDefault(match); } /// /// Ends the unit of work: detaches it from the exchange (a later route entry with the same exchange opens a new one) /// and runs every completion. A failing completion is logged; the others still run and the outcome stands. /// internal async Task End(IExchange exchange, bool failed, ILogger? logger) { IExchangeCompletion[] completions; lock (_gate) { if (_ended) return; _ended = true; completions = _completions?.ToArray() ?? []; } if (exchange.Properties.TryGetValue(PropertyKey, out var current) && ReferenceEquals(current, this)) exchange.Properties.Remove(PropertyKey); foreach (var completion in completions) { try { // Deliberately without the exchange's token: a cancelled exchange is a failed one, and its failure has to // be recorded, or the redelivery would pass for a duplicate. if (failed) await completion.OnFailure(exchange, CancellationToken.None).ConfigureAwait(false); else await completion.OnComplete(exchange, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { logger?.LogError(ex, "Completion {Completion} failed on exchange {ExchangeId} (route '{RouteId}', outcome {Outcome}); the outcome stands and the remaining completions still run.", completion.GetType().Name, exchange.ExchangeId, exchange.RouteId, failed ? "failure" : "success"); } } } } Path: redb-route/redb.Route/Abstractions/IBeanTypeResolver.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/Abstractions/IBeanTypeResolver.cs ---- namespace redb.Route.Abstractions; /// /// Resolves a type name of a route (Namespace.Type, AssemblyName or a bare full name) to a CLR type: the /// class of bean:, the type of an XML <bean>, the SQL outputClass. Registered as a /// context service (): hosts that load user code into their own /// register a resolver that searches that code first, as /// Apache Camel's ClassResolver does under OSGi. Tsak registers one in the context of every module: the module's /// assemblies (a package's entry points and companions), then the process. When none is registered, /// searches the loaded assemblies of the process, and with two /// assemblies of one name loaded (a module reloaded beside its previous version) finds the one loaded first. /// public interface IBeanTypeResolver { /// Returns the resolved type, or null when no loaded assembly carries it. Type? Resolve(string typeName); } Path: redb-route/redb.Route/Abstractions/IClaimCheckRepository.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/Abstractions/IClaimCheckRepository.cs ---- using System; using System.Threading; using System.Threading.Tasks; namespace redb.Route.Abstractions; /// /// Repository for the Claim Check EIP pattern. /// Stores opaque binary data associated with a unique key. /// Implementations may provide TTL-based auto-expiry. /// public interface IClaimCheckRepository { /// /// Stores data under an auto-generated unique key. /// /// Binary payload to store. /// Optional time-to-live. Null uses repository default or no expiry. /// Cancellation token. /// Unique claim key for later retrieval. Task Store(ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default); /// /// Stores data under a specific key. Overwrites if key already exists. /// /// Explicit claim key. /// Binary payload to store. /// Optional time-to-live. Null uses repository default or no expiry. /// Cancellation token. Task Store(string key, ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default); /// /// Retrieves data by claim key without removing it. /// Returns null if key not found or expired. /// Task Retrieve(string key, CancellationToken ct = default); /// /// Retrieves and removes data by claim key atomically. /// Returns null if key not found or expired. /// Task RetrieveAndRemove(string key, CancellationToken ct = default); /// /// Explicitly removes data by claim key. /// No-op if key not found. /// Task Remove(string key, CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/IComponent.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/Abstractions/IComponent.cs ---- namespace redb.Route.Abstractions; /// /// Creates endpoints for a specific URI scheme (e.g., kafka, rabbitmq, redis). /// Each component handles one scheme and creates configured endpoints. /// public interface IComponent { /// The URI scheme this component handles (e.g., "kafka", "rabbitmq"). string Scheme { get; } /// /// Optional alternate scheme aliases (e.g., "es" for "elasticsearch"). /// registers the component under all schemes. /// IReadOnlyList AlternateSchemes => []; /// Creates an endpoint from a parsed URI. /// Parsed endpoint URI with scheme, path, and parameters. /// Configured endpoint ready for producing/consuming. IEndpoint CreateEndpoint(EndpointUri uri); } Path: redb-route/redb.Route/Abstractions/IConditionSource.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/Abstractions/IConditionSource.cs ---- namespace redb.Route.Abstractions; /// /// Declarative capture of the condition a scope was built from, for definitions whose behaviour is /// driven by a condition: Filter and the When branch of a Choice. /// /// The DSL offers three ways to write a condition, and this contract keeps one name and one fixed /// type for each of them, so a reader never has to guess what a property holds: /// /// /// /// /// — the condition was written as a predicate instance, /// or was compiled from a condition string into one. /// /// /// /// — the condition was written as an expression /// instance. /// /// /// /// — the condition string exactly as the author wrote it. /// /// /// /// /// A condition written as a plain delegate leaves all three null: a lambda has no source to /// capture. A condition written as a string sets and, since it is /// compiled into one, . /// /// /// Only reading is offered. The properties are filled while the route is being built and are not /// meant to be rewritten afterwards. /// /// public interface IConditionSource { /// The predicate the condition was built from, or built into; null if there is none. IPredicate? SourcePredicate { get; } /// The expression instance the condition was built from; null if there is none. IExpression? SourceExpression { get; } /// The condition string as the author wrote it; null if the condition was not written as a string. string? SourceTemplate { get; } } Path: redb-route/redb.Route/Abstractions/IConsumer.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/Abstractions/IConsumer.cs ---- namespace redb.Route.Abstractions; /// /// Receives messages from an endpoint and delegates to a processor. /// Manages its own lifecycle (polling, subscribing, etc.). /// public interface IConsumer { /// The endpoint this consumer is attached to (for diagnostics/logging). IEndpoint? Endpoint => null; /// Starts consuming messages. /// Cancellation token. Task Start(CancellationToken ct = default); /// Stops consuming messages. /// Cancellation token. Task Stop(CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/IConsumerTemplate.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/Abstractions/IConsumerTemplate.cs ---- namespace redb.Route.Abstractions; /// /// Template for polling messages from endpoints programmatically, /// without creating a full route. Mirrors Apache Camel's ConsumerTemplate. /// /// Use for blocking poll, /// for timed poll, /// and for non-blocking poll. /// /// public interface IConsumerTemplate { /// Gets the route context associated with this template. IRouteContext Context { get; } /// Gets whether this template has been started and is ready for use. bool IsStarted { get; } // ── Receive (blocking) ── /// /// Receives an exchange from the specified endpoint URI, blocking until one is available. /// /// Source endpoint URI (e.g., "seda:queue"). /// Cancellation token. /// The received exchange. Task Receive(string endpointUri, CancellationToken ct = default); /// /// Receives an exchange from the specified endpoint, blocking until one is available. /// /// Source endpoint instance. /// Cancellation token. /// The received exchange. Task Receive(IEndpoint endpoint, CancellationToken ct = default); // ── Receive with timeout ── /// /// Receives an exchange from the specified endpoint URI, waiting up to the given timeout. /// Returns null if no exchange is available within the timeout. /// /// Source endpoint URI. /// Maximum time to wait. /// Cancellation token. /// The received exchange, or null if timed out. Task Receive(string endpointUri, TimeSpan timeout, CancellationToken ct = default); /// /// Receives an exchange from the specified endpoint, waiting up to the given timeout. /// Returns null if no exchange is available within the timeout. /// /// Source endpoint instance. /// Maximum time to wait. /// Cancellation token. /// The received exchange, or null if timed out. Task Receive(IEndpoint endpoint, TimeSpan timeout, CancellationToken ct = default); // ── ReceiveNoWait (non-blocking) ── /// /// Attempts to receive an exchange without waiting. /// Returns null immediately if no exchange is available. /// /// Source endpoint URI. /// Cancellation token. /// The received exchange, or null if none available. Task ReceiveNoWait(string endpointUri, CancellationToken ct = default); /// /// Attempts to receive an exchange without waiting. /// Returns null immediately if no exchange is available. /// /// Source endpoint instance. /// Cancellation token. /// The received exchange, or null if none available. Task ReceiveNoWait(IEndpoint endpoint, CancellationToken ct = default); // ── Typed body convenience ── /// /// Receives the message body from the specified endpoint URI, blocking until available. /// /// Source endpoint URI. /// Cancellation token. /// The body of the incoming message. Task ReceiveBody(string endpointUri, CancellationToken ct = default); /// /// Receives the message body from the specified endpoint URI, blocking until available, /// and converts it to . /// /// Expected body type. /// Source endpoint URI. /// Cancellation token. /// The typed body, or default. Task ReceiveBody(string endpointUri, CancellationToken ct = default); /// /// Receives the message body with a timeout. Returns default if timed out. /// /// Expected body type. /// Source endpoint URI. /// Maximum time to wait. /// Cancellation token. /// The typed body, or default if timed out or conversion failed. Task ReceiveBody(string endpointUri, TimeSpan timeout, CancellationToken ct = default); // ── Unit of work ── /// /// Completes the unit of work of an exchange handed out by a Receive call, Camel's /// doneUoW: only now does the source commit it — a polled file is deleted or moved, a /// broker message acknowledged. An exchange whose is set is /// rolled back instead (the file stays, the message is redelivered). Read the body before this /// call: the source releases the exchange's resources afterwards. ReceiveBody calls it /// itself. Until it is called the source keeps the exchange uncommitted; a stopped template rolls /// back every exchange still open. /// /// An exchange this template handed out and has not completed yet. /// The exchange was not handed out by this template, /// was already completed, or was rolled back when the template stopped. Task DoneUoW(IExchange exchange); // ── Lifecycle ── /// Starts the consumer template. Must be called before any receive methods. void Start(); /// /// Stops the consumer template and its cached consumers. Exchanges received but not completed /// with , and those the sources offered but no Receive took, are /// rolled back. /// void Stop(); } Path: redb-route/redb.Route/Abstractions/IDataFormatRegistry.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/Abstractions/IDataFormatRegistry.cs ---- namespace redb.Route.Abstractions; /// /// Registry of content-type → serializer mappings. /// Used by -based processors to auto-select /// the appropriate serializer based on the exchange's ContentType. /// /// Two lookup dimensions are supported: /// /// /// Media type — resolves by MIME string /// (application/json, application/scim+json). Used for wire-format /// interop; honors RFC 6838 structured-suffix fallbacks (+json/+xml). /// Profile name — resolves by a caller-chosen alias /// (e.g. "scim", "problem"). Used by application code that wants a /// named preset independent of the wire media type. /// /// public interface IDataFormatRegistry { /// Finds a serializer for the given content type (e.g. "application/json"). /// MIME content type, optionally with parameters (charset, etc.). /// Matching serializer, or null if none registered. IMessageSerializer? GetSerializer(string contentType); /// Registers a serializer for the given content type. /// MIME content type (e.g. "application/json"). /// Serializer instance. void Register(string contentType, IMessageSerializer serializer); /// /// Resolves a serializer registered under a named profile (e.g. "scim", /// "problem", "oauth"). Profiles are separate from media-type lookup — /// used by application code that selects a preset by name rather than by wire media type. /// /// Profile alias. /// Matching serializer, or null if no profile by that name is registered. /// /// Default implementation returns null; registries that don't care about profiles /// remain source-compatible with the original contract. /// IMessageSerializer? ResolveProfile(string profileName) => null; /// /// Registers a serializer under a named profile alias. /// /// Profile alias (e.g. "scim"). /// Serializer instance. /// /// Default implementation is a no-op, preserving source compatibility with /// external implementations. /// void RegisterProfile(string profileName, IMessageSerializer serializer) { } } Path: redb-route/redb.Route/Abstractions/IEndpoint.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/Abstractions/IEndpoint.cs ---- using Microsoft.Extensions.DependencyInjection; namespace redb.Route.Abstractions; /// /// Represents a lightweight endpoint in the route pipeline. /// An endpoint is an addressable destination/source identified by a normalized URI key. /// No metrics or health checks — those are handled by OpenTelemetry infrastructure. /// public interface IEndpoint { /// Parsed URI identifying this endpoint. EndpointUri Uri { get; } /// The component that created this endpoint. IComponent Component { get; } /// Creates a producer for sending messages to this endpoint. IProducer CreateProducer(); /// Creates a consumer for receiving messages from this endpoint. /// The processor to invoke when a message arrives. IConsumer CreateConsumer(IProcessor processor); /// Starts the endpoint lifecycle. /// Cancellation token. Task Start(CancellationToken ct = default); /// Stops the endpoint lifecycle. /// Cancellation token. Task Stop(CancellationToken ct = default); /// /// Optional scope factory for creating per-exchange DI scopes. /// Set by RouteContext during endpoint creation. Null when running without DI. /// IServiceScopeFactory? ScopeFactory { get => null; set { } } } Path: redb-route/redb.Route/Abstractions/IEndpointStatistics.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/Abstractions/IEndpointStatistics.cs ---- namespace redb.Route.Abstractions; /// /// Health status of an endpoint based on recent error rate and activity. /// public enum EndpointHealthStatus { /// Everything is operating normally. Healthy, /// There are issues, but endpoint is operational. Warning, /// High error rate detected. Critical, /// Endpoint is not running. Failed } /// /// Optional statistics interface for endpoints that track message counts. /// Not part of — consumers/services check via endpoint is IEndpointStatistics stats. /// Counters use for thread safety. /// public interface IEndpointStatistics { /// Number of messages received (consumed) by this endpoint. long MessagesIn { get; } /// Number of messages sent (produced) by this endpoint. long MessagesOut { get; } /// Number of errors during processing. long Errors { get; } /// Number of warnings during processing. long Warnings { get; } /// /// Bytes that entered the endpoint (estimated from message bodies): what a consumer received, /// and what a producer got back in reply. /// long BytesIn { get; } /// /// Bytes that left the endpoint: what a producer sent, and what a consumer wrote back as a /// reply. Counterpart of , so the two together describe an endpoint's /// volume in both directions rather than lumping it into one number. /// long BytesOut { get; } /// /// Requests shed by an admission limit (e.g. maxConcurrentRequests) BEFORE a pipeline /// ran: the transport answered 429/503 and no exchange was created, so these are counted in /// neither nor . /// long Rejected { get; } /// /// Exchanges abandoned by a cooperative cancellation: the caller's token was cancelled while /// the pipeline ran (a closed dashboard mid-poll, an aborted HTTP request). Unlike /// these ARE counted in — the exchange had /// entered the pipeline — but never in : the route did nothing wrong, and /// counting them there turned healthy routes red under nothing but polling churn. An /// thrown while the caller's token is still live is /// an internal failure and stays in . A consumer endpoint's completed /// count is therefore MessagesIn - Errors - Cancelled. /// long Cancelled { get; } /// /// Requests the transport refused as the caller's fault and answered with the protocol's own error: malformed or /// oversized, not authenticated, not what the agreement allows (an AS4 ebMS error, a SOAP Sender fault). No /// exchange was created, so like they are counted in neither nor /// , and they do not feed : a partner sending what the endpoint cannot /// accept is not a failure of the route. A rise is still worth a look: a partner's broken configuration, or our /// key or agreement changed under it. says why the last one was refused. /// The refusal members have default implementations (none counted) so that an implementation written before them /// still compiles; EndpointBase counts them. /// long Refused => 0; /// /// Connections or links of this endpoint that were lost while a route ran and came back, as its connection supervisors /// () report them. Default implementation: none counted, so that an /// implementation written before it still compiles; EndpointBase counts them. /// long Reconnects => 0; /// Timestamp of the last refusal, or null if none. DateTime? LastRefusalTime => null; /// Why the last request was refused, or empty string. string LastRefusalMessage => string.Empty; /// Timestamp of the last message activity (in or out), or null if no activity yet. DateTime? LastActivity { get; } /// Timestamp when the endpoint started tracking statistics. DateTime StartTime { get; } /// Duration the endpoint has been tracking statistics. TimeSpan Uptime { get; } /// Average processing time over the last 100 messages. TimeSpan AverageProcessingTime { get; } /// Messages per second over a 60-second sliding window. double ThroughputPerSecond { get; } /// Timestamp of the last error, or null if no errors. DateTime? LastErrorTime { get; } /// Message text of the last error, or empty string. string LastErrorMessage { get; } /// Timestamp of the last warning, or null if no warnings. DateTime? LastWarningTime { get; } /// Message text of the last warning, or empty string. string LastWarningMessage { get; } /// Health status computed from error rate and activity. EndpointHealthStatus HealthStatus { get; } /// Human-readable reason for the current health status. string HealthReason { get; } /// Resets all counters to zero. void ResetStatistics(); /// Record an incoming message (consumed). Thread-safe. void RecordMessageIn(); /// Record an outgoing message (produced). Thread-safe. void RecordMessageOut(); /// Record a processing error. Thread-safe. void RecordError(); /// Record a processing error with exception details. Thread-safe. void RecordError(Exception exception); /// Record a processing warning. Thread-safe. void RecordWarning(); /// Record a processing warning with message. Thread-safe. void RecordWarning(string message); /// Record processing time of a single message. Thread-safe. void RecordProcessingTime(TimeSpan duration); /// Record a request shed by an admission limit before the pipeline ran. Thread-safe. void RecordRejected(); /// Record an exchange abandoned by a cooperative cancellation. Thread-safe. void RecordCancelled(); /// Record a request refused as the caller's fault, with the reason (see ). Thread-safe. void RecordRefused(string reason) { } /// Record incoming bytes (message body size). Thread-safe. void RecordBytesIn(long bytes); /// Record outgoing bytes (message body size). Thread-safe. void RecordBytesOut(long bytes); } Path: redb-route/redb.Route/Abstractions/IErrorHandler.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/Abstractions/IErrorHandler.cs ---- namespace redb.Route.Abstractions; /// /// Last-resort error handler invoked when no local or global exception handler matches. /// Implement to define application-wide fallback error handling (e.g., dead-letter, alerting). /// public interface IErrorHandler { /// /// Handles an exception that was not caught by any registered exception handler. /// /// The exchange that caused the exception. /// The unhandled exception. /// Cancellation token. /// A task representing the asynchronous operation. Task HandleError(IExchange exchange, Exception exception, CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/IExchange.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/Abstractions/IExchange.cs ---- namespace redb.Route.Abstractions; /// /// Represents a message exchange in the route pipeline. /// Contains In message (always present), optional Out message (lazy), /// exchange pattern, route-level properties, and error state. /// Supports both C# idiomatic properties and Java-style methods. /// public interface IExchange : IAsyncDisposable { // ── C# idiomatic API ── /// Primary message flowing through the pipeline. Always non-null. IMessage In { get; set; } /// /// Response message from request-reply or explicit .Respond(). /// Null when InOnly (default). Lazy — not allocated until needed. /// IMessage? Out { get; set; } /// Current exchange pattern. Default = InOnly. ExchangePattern Pattern { get; set; } /// Whether Out is populated (non-null). bool HasOut => Out != null; /// /// Route-level metadata (RouteId, TRANSACT_ACTION, etc.). /// Does NOT travel to brokers — use In.Headers for that. /// IDictionary Properties { get; } /// Gets a property value with type conversion. /// Target type for the property value. /// Property key. /// /// The converted value; default when the property is missing or has no conversion to /// (as Camel's getProperty(name, type)). /// /// The value cannot be parsed as . T? GetProperty(string key); /// Current exception if processing failed. Exception? Exception { get; set; } /// Whether the current exception has been handled by error handling logic. bool ExceptionHandled { get; set; } /// Identifier of the route this exchange belongs to. string? RouteId { get; set; } /// /// The route context currently processing this exchange (Apache Camel's /// exchange.getContext()). null for an exchange that was never handed to a route. /// /// /// Stamped by the route wrapper on entry and restored on exit, so inside a direct: or /// vm: sub-route it is the inner route's context — Camel's reading of /// "current" — and after the sub-route returns, the caller sees its own context again. This is /// what lets a processor reach measurements and services without capturing the context into a /// lambda: (IEndpointStatistics)e.Context.GetEndpoint("direct:x"). /// IRouteContext? Context => null; /// Unique identifier of this exchange instance, generated at creation. string ExchangeId { get; } /// Whether processing of this exchange has been stopped. bool IsStopped { get; } /// Stops further processing of this exchange in the pipeline. void Stop(); /// /// Structural copy of the exchange (In, Out, Properties containers + a fresh DI scope). The /// message body reference and property/header values are shared (shallow) — intentional /// and relied upon across the framework (e.g. Splitter aggregation). For an isolated deep copy /// use . /// IExchange Clone(); /// /// Deep, isolated snapshot for checkpoint/replay. Unlike it deep-copies /// the message body (In and Out) so the captured state is frozen and immune to later /// in-place mutation of the payload. Properties/headers follow (values /// shared) as they carry immutable route metadata. /// /// No DI scope is created at capture: a snapshot is dormant data taken on every marker /// pass and usually never replayed, so minting a scope here would leak one per message. A /// snapshot that is never replayed owns nothing to dispose; a replay mints (and disposes) a /// scope on demand. /// /// Throws if a body cannot be safely deep-copied. /// IExchange Snapshot(); // ── DI Scope ── /// /// Optional scoped service provider bound to this exchange's lifetime. /// Null when running without DI (tests, standalone). Processors can resolve /// scoped services (DbContext, IRedbService, etc.) from this provider. /// IServiceProvider? ServiceProvider => null; /// /// Creates a child exchange with the given message, inheriting Properties, RouteId, /// Pattern, and scope factory. A new DI scope is created for the child. /// IExchange CreateChild(IMessage message) { var child = Clone(); child.In = message; return child; } /// /// Creates a child exchange that shares the parent's DI scope (no new scope). /// Use for sequential processing where children should reuse the same DB connection /// and participate in the parent's transaction. /// The child does NOT own the scope and will not dispose it. /// IExchange CreateLinkedChild(IMessage message) => CreateChild(message); /// /// Creates a deep copy of the exchange that shares the parent's DI scope (no new scope). /// Like but without creating a new DI scope. /// Use for sequential fan-out (Multicast, ScatterGather, RecipientList) where /// each target should reuse the same DB connection and transaction. /// IExchange CloneLinked() => Clone(); /// /// A copy that goes on as an exchange of its own, as Apache Camel's ExchangeHelper.createCorrelatedCopy /// makes one for seda, multicast, recipient list, enrich and on-completion: everything copies, a /// new , and the CamelCorrelationId property /// () set to this exchange's id, the immediate parent's, as in Camel. /// A fresh DI scope, as . /// IExchange CorrelatedCopy() => throw new NotSupportedException( $"{GetType().Name} does not implement CorrelatedCopy: an exchange that crosses to another unit of work needs a new id."); /// /// sharing this exchange's DI scope, as : for a copy processed /// in sequence within the caller's unit of work (a sequential multicast or recipient list). /// IExchange CorrelatedCopyLinked() => throw new NotSupportedException( $"{GetType().Name} does not implement CorrelatedCopyLinked: an exchange that crosses to another unit of work needs a new id."); /// /// Releases DI scopes (main scope + named __redb_scope:* entries) and the resources registered with /// , without disposing the exchange body or headers. For an exchange /// no route owns (a Split or Multicast branch) it also ends the unit of work, running the completions registered with /// . /// Call after processing to free DB connections early while keeping message data alive for aggregation. /// Idempotent — safe to call multiple times. /// ValueTask ReleaseScopes() => default; /// Disposes the exchange and its associated DI scope (if any). ValueTask IAsyncDisposable.DisposeAsync() => default; // ── Java-style API (kept forever, default interface methods) ── /// Java-style: returns In message. IMessage getIn() => In; /// Java-style: returns Out message. IMessage? getOut() => Out; /// Java-style: returns property value by key. object? getProperty(string key) => Properties.TryGetValue(key, out var v) ? v : null; /// Java-style: returns property value cast to . T? getProperty(string key) => GetProperty(key); /// Java-style: sets property value. void setProperty(string key, object? value) => Properties[key] = value; /// Java-style: returns true if route processing is stopped. bool isStop() => IsStopped; /// Java-style: stops route processing (alias for Stop). void RouteStop() => Stop(); /// Java-style: deep copy (alias for Clone). IExchange copy() => Clone(); } Path: redb-route/redb.Route/Abstractions/IExchangeBoundBody.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/Abstractions/IExchangeBoundBody.cs ---- namespace redb.Route.Abstractions; /// /// Marks a message body that reads from resources its exchange holds (registered with /// ), such as a streamed query result, and so cannot be read once the /// exchange has ended. /// /// A caller that ends the exchange before it hands the body on refuses such a body instead of returning one that is /// already dead: does. Read it through /// and dispose the exchange after /// the body has been read. /// /// public interface IExchangeBoundBody; Path: redb-route/redb.Route/Abstractions/IExchangeCompletion.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/Abstractions/IExchangeCompletion.cs ---- namespace redb.Route.Abstractions; /// /// Work attached to the outcome of an exchange's unit of work (Apache Camel: a Synchronization passed to /// addOnCompletion). Register it with ; exactly one of the two /// methods runs, once, when the unit of work ends. /// /// A failing completion is logged and does not change the exchange's outcome or stop the other completions. Both methods /// receive : the outcome has to be recorded even for an exchange that was cancelled. /// /// public interface IExchangeCompletion { /// The unit of work succeeded: the consumer acknowledges the message. Task OnComplete(IExchange exchange, CancellationToken ct); /// /// The unit of work did not succeed: an exception escaped the route, a failure was left unhandled on the exchange, /// or the route marked it rollback-only (.RollbackAll()). The consumer does not acknowledge the message. /// Task OnFailure(IExchange exchange, CancellationToken ct); } Path: redb-route/redb.Route/Abstractions/IExpression.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/Abstractions/IExpression.cs ---- namespace redb.Route.Abstractions; /// /// Represents an expression that can be evaluated against an exchange context. /// Expressions extract or compute values from a message exchange. /// Used for content-based routing, transformations, and predicate construction. /// public interface IExpression { /// /// Evaluates the expression and returns the result cast to . /// /// Target return type. /// The exchange to evaluate against. /// Evaluation result converted to . T Evaluate(IExchange exchange); /// Creates a predicate that checks equality of this expression's result with the given value. IPredicate isEqualTo(object value); /// Creates a "greater than" predicate. IPredicate isGreaterThan(object value); /// Creates a "less than" predicate. IPredicate isLessThan(object value); /// Creates a "greater than or equal" predicate. IPredicate isGreaterThanOrEqualTo(object value); /// Creates a "less than or equal" predicate. IPredicate isLessThanOrEqualTo(object value); /// Creates a "between" predicate (inclusive). IPredicate isBetween(object low, object high); /// Creates a "contains" predicate (for strings and collections). IPredicate contains(object value); /// Creates a "starts with" predicate (for strings). IPredicate startsWith(object value); /// Creates an "ends with" predicate (for strings). IPredicate endsWith(object value); /// Creates a regex-match predicate. IPredicate regex(string pattern); /// Creates an "in set" predicate. IPredicate In(params object[] values); /// Creates a "not equal" predicate. IPredicate isNotEqualTo(object value); /// Creates an "is null" predicate. IPredicate isNull(); /// Creates an "is not null" predicate. IPredicate isNotNull(); /// Creates a logical AND predicate combining this expression with another predicate. IPredicate and(IPredicate predicate); /// Creates a logical OR predicate combining this expression with another predicate. IPredicate or(IPredicate predicate); /// Creates a logical NOT predicate negating this expression. IPredicate not(); /// /// Sets a value in the exchange according to this expression's semantics. /// For example, sets a header, /// sets the body. /// /// The target exchange. /// The value to set. void SetValue(IExchange exchange, object value); /// /// Serializes this expression to a ${...} template string suitable for URI parameters. /// /// Template string representation, e.g. ${header.orderId}. /// Thrown when the expression cannot be serialized (e.g. delegate-based). string ToTemplateString(); } Path: redb-route/redb.Route/Abstractions/IHeaderFilterStrategy.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/Abstractions/IHeaderFilterStrategy.cs ---- namespace redb.Route.Abstractions; /// /// Decides which headers a transport carries between an exchange and the messages of its protocol: the HTTP request /// and response headers, the headers of a Kafka record, the application properties of an AMQP or Service Bus message. /// Apache Camel's HeaderFilterStrategy. /// /// Two directions, asked about every header one by one: /// /// — the exchange's header is about to go into an outgoing message: the request a /// producer sends, the reply a consumer sends back (Camel: applyFilterToCamelHeaders); /// — a header of an incoming message is about to come into the exchange: the /// message a consumer receives, the reply a producer gets (Camel: applyFilterToExternalHeaders). /// /// Both return true to drop the header and false to let it through, as in Camel. /// /// /// Every transport that carries arbitrary headers has a default strategy that keeps its documented behaviour; a /// strategy set on an endpoint (headerFilterStrategy=#name) replaces that default entirely. A strategy decides /// about the headers of the route only: the fields a transport sets itself (trace context, content type, the native /// properties of the message) do not go through it. covers the usual /// cases — a list of names, a regular expression, name prefixes — as a blacklist or a whitelist. /// /// public interface IHeaderFilterStrategy { /// /// Whether the exchange header is dropped instead of going into an outgoing message /// (a producer's request, a consumer's reply). /// /// The header name. /// The header value; may be null. /// The exchange the header belongs to. /// true to drop the header; false to send it. bool FilterOutgoing(string name, object? value, IExchange exchange); /// /// Whether the header of an incoming message (a consumed message, a producer's reply) is /// dropped instead of coming into the exchange. /// /// The header name as the protocol carries it. /// The header value; may be null. /// The exchange the header would come into. /// true to drop the header; false to take it. bool FilterIncoming(string name, object? value, IExchange exchange); } Path: redb-route/redb.Route/Abstractions/IIdempotentRepository.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/Abstractions/IIdempotentRepository.cs ---- namespace redb.Route.Abstractions; /// /// Repository that tracks message identifiers for idempotent consumption. /// Implementations may use in-memory stores, Redis, or a database. /// public interface IIdempotentRepository { /// /// Attempts to add the key. Returns true if the key was new (not a duplicate). /// Returns false if the key already exists (duplicate). /// /// Unique message identifier. /// Cancellation token. /// True if the message should be processed; false if it is a duplicate. Task Add(string key, CancellationToken ct = default); /// /// Confirms the key after successful processing. /// For implementations that use two-phase commit (add → process → confirm). /// /// Unique message identifier. /// Cancellation token. Task Confirm(string key, CancellationToken ct = default); /// /// Removes the key, allowing it to be reprocessed. /// Called on rollback or when retrying. /// /// Unique message identifier. /// Cancellation token. Task Remove(string key, CancellationToken ct = default); /// /// Checks if the key already exists in the repository. /// /// Unique message identifier. /// Cancellation token. /// True if the key exists. Task Contains(string key, CancellationToken ct = default); /// /// Removes all keys from the repository. /// Primarily for testing. /// /// Cancellation token. Task Clear(CancellationToken ct = default); /// /// Whether writes through an ambient , so that its /// rollback takes the key back. The idempotent consumer relies on it inside a .Transacted() block: a key that /// is part of the transaction goes with its rollback and stays with its commit, and the consumer must not remove it /// afterwards — another node may already hold the same key again. A repository that keeps its keys outside the /// transaction (in memory, say) returns , the default, and the consumer removes the key itself /// when the transaction does not commit. /// bool JoinsAmbientTransaction => false; /// /// Claims the key as does, and when it is held already tells why: the message is still being /// processed under an earlier claim () or was processed and confirmed /// (). An unconfirmed claim older than is /// taken to be abandoned (its holder stopped between and ) and is taken over /// (): the repository replaces exactly that claim, so when two callers try it at /// once one wins and the other gets . /// /// The default claims with and takes any held key for confirmed, which is what a caller of /// assumes. A repository that keeps the confirmed state and the time of the claim overrides it, so /// that a receiver can tell a resend of a message still in flight from a duplicate, and so that a claim left behind /// by a stopped node does not block its message for good. /// /// /// Unique message identifier. /// Age past which an unconfirmed claim is taken over; null never takes one over. /// Cancellation token. async Task Claim(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) => await Add(key, ct).ConfigureAwait(false) ? IdempotentClaim.Claimed : IdempotentClaim.Confirmed; /// /// that also names the claim it took: identifies this claim of /// the key, so that and /// act on it only while it is still the one held. A holder /// that outlived and was taken over then confirms or removes nothing of the new /// holder's claim. /// /// The default answers without a token, and the token methods then act on the key as /// and do. /// /// /// Unique message identifier. /// Age past which an unconfirmed claim is taken over; null never takes one over. /// Cancellation token. async Task Lease(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) => new(await Claim(key, abandonedAfter, ct).ConfigureAwait(false), null); /// /// Confirms the claim names (from ) after successful processing. Returns /// false, and confirms nothing, when the key is no longer held by that claim: it was taken over or removed. A null /// token confirms the key as does. /// /// Unique message identifier. /// The of the claim. /// Cancellation token. async Task Confirm(string key, string? token, CancellationToken ct = default) { await Confirm(key, ct).ConfigureAwait(false); return true; } /// /// Removes the claim names (from ), so the message can be processed again. /// Returns false, and removes nothing, when the key is no longer held by that claim: another holder's claim stays. A /// null token removes the key as does. /// /// Unique message identifier. /// The of the claim. /// Cancellation token. async Task Release(string key, string? token, CancellationToken ct = default) { await Remove(key, ct).ConfigureAwait(false); return true; } } /// The outcome of : the claim's outcome and, when the caller holds it, its token. /// As answers. /// /// The id of the claim the caller holds ( or ), /// for and /// ; null otherwise, and from a repository /// that keeps no claim ids. /// public readonly record struct IdempotentLease(IdempotentClaim Outcome, string? Token) { /// Whether the caller holds the claim and processes the message. public bool Holds => Outcome is IdempotentClaim.Claimed or IdempotentClaim.TakenOver; } /// The outcome of . public enum IdempotentClaim { /// The key was new: the caller holds the claim and processes the message. Claimed, /// An abandoned, unconfirmed claim was replaced: the caller holds the claim and processes the message. TakenOver, /// Another claim of the key is not confirmed yet: its message is still being processed. InFlight, /// The message was processed and its claim confirmed: a duplicate. Confirmed, } Path: redb-route/redb.Route/Abstractions/IIdempotentRepositoryProvider.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/Abstractions/IIdempotentRepositoryProvider.cs ---- namespace redb.Route.Abstractions; /// /// Lookup service for named instances. Lets routes refer /// to repositories by string name (resolved lazily during pipeline execution) instead of /// holding a hard reference at definition time. /// /// Useful when the same route definition is reused across multiple contexts/tenants where /// each picks its own backing store, or when DI registration occurs after routes are defined. /// /// public interface IIdempotentRepositoryProvider { /// /// Returns the repository registered under . /// /// Logical repository name (case-insensitive). /// The repository. /// /// Thrown when no repository is registered under the given name. /// IIdempotentRepository Get(string name); /// /// Looks up a repository by name. false when nothing is registered under it; an object of another type /// under the name is a configuration error and throws . /// bool TryGet(string name, out IIdempotentRepository repository); } Path: redb-route/redb.Route/Abstractions/IInflightRepository.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/Abstractions/IInflightRepository.cs ---- namespace redb.Route.Abstractions; /// /// Tracks exchanges currently being processed (in-flight) across all routes. /// Thread-safe. Used by watchdog/monitoring to detect hung exchanges. /// public interface IInflightRepository { /// Registers an exchange as in-flight. void Register(InflightExchange entry); /// Removes an exchange from the in-flight registry. void Unregister(string exchangeId); /// Returns a snapshot of all in-flight exchanges. IReadOnlyList Browse(); /// Returns a snapshot of in-flight exchanges for a specific route. IReadOnlyList Browse(string routeId); /// Total number of in-flight exchanges across all routes. int Count { get; } /// Number of in-flight exchanges for a specific route. int CountByRoute(string routeId); /// /// Marks an in-flight exchange as held by the engine on purpose for (a redelivery delay, a /// delay step): is set until the returned handle is disposed, then /// . A monitor does not take such an exchange for a hung one. The /// default does nothing, so a repository of one's own keeps working as before. /// IDisposable BeginWait(string exchangeId, TimeSpan delay) => NoWait.Instance; /// The handle of a wait nothing records. private sealed class NoWait : IDisposable { public static readonly NoWait Instance = new(); public void Dispose() { } } } Path: redb-route/redb.Route/Abstractions/ILoadBalancerDefinition.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/Abstractions/ILoadBalancerDefinition.cs ---- using System; namespace redb.Route.Abstractions; /// /// Fluent builder for configuring a Load Balancer step. /// Allows setting endpoints and strategy via explicit instance or shortcut methods. /// public interface ILoadBalancerDefinition { /// Sets the target endpoint URIs to balance across. /// One or more endpoint URIs. ILoadBalancerDefinition Endpoints(params string[] uris); /// Sets a custom load balancer strategy. /// The strategy instance. ILoadBalancerDefinition Strategy(ILoadBalancerStrategy strategy); /// Uses round-robin strategy (default). ILoadBalancerDefinition UseRoundRobin(); /// Uses random strategy. ILoadBalancerDefinition UseRandom(); /// Uses failover strategy (tries next endpoint on failure). ILoadBalancerDefinition UseFailover(); /// Uses sticky strategy with the specified correlation key extractor. /// Function extracting a correlation key from the exchange. ILoadBalancerDefinition UseSticky(Func correlationKeyExtractor); /// Uses weighted strategy with the specified endpoint weights. /// Dictionary mapping endpoint URI to relative weight. ILoadBalancerDefinition UseWeighted(System.Collections.Generic.Dictionary weights); } Path: redb-route/redb.Route/Abstractions/ILoadBalancerStrategy.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/Abstractions/ILoadBalancerStrategy.cs ---- using System; using System.Collections.Generic; namespace redb.Route.Abstractions; /// /// Strategy for selecting a target URI from a list of candidates. /// Implementations must be thread-safe for concurrent pipeline usage. /// public interface ILoadBalancerStrategy { /// /// Selects the next target URI based on strategy logic. /// /// Current exchange (for sticky/content-based routing). /// Available endpoint URIs. /// Selected URI. string Select(IExchange exchange, IReadOnlyList endpoints); /// /// Reports that a selected endpoint has failed. /// Used by failover strategies to track unhealthy endpoints. /// Default implementation is a no-op. /// /// The failed endpoint URI. /// The exception that occurred. void ReportFailure(string endpoint, Exception exception) { } /// /// Reports that a selected endpoint succeeded. /// Used by failover strategies to mark endpoints as healthy again. /// Default implementation is a no-op. /// /// The successful endpoint URI. void ReportSuccess(string endpoint) { } } Path: redb-route/redb.Route/Abstractions/IMessage.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/Abstractions/IMessage.cs ---- using redb.Route.Core; namespace redb.Route.Abstractions; /// /// Represents a message flowing through the route pipeline. /// Contains payload (Body), metadata (Headers), and supports both /// C# idiomatic properties and Java-style methods for backward compatibility. /// public interface IMessage { // ── C# idiomatic API ── /// Message payload. Can be any object or null. object? Body { get; set; } /// /// MIME content type of the message body (e.g. "application/json"). /// Set by transport consumers from protocol-native metadata. /// Null means unknown — no assumptions about body format. /// string? ContentType { get; set; } /// /// Headers that travel with the message (ContentType, CorrelationId, custom). /// These headers are propagated to brokers when sending. /// IDictionary Headers { get; } /// Gets a header value with type conversion. /// Target type for the header value. /// Header key. /// /// The converted value; default when the header is missing or has no conversion to /// (as Camel's getHeader(name, type)). /// /// The value cannot be parsed as . T? GetHeader(string key); /// /// Attachments of this message (Apache Camel's AttachmentMessage): named content beside the body, such as the /// files of a form upload or of an e-mail. They belong to the message, not to the exchange, so In and /// Out carry their own; a broker producer does not send them unless its protocol has a place for them. /// implements them; a message type that does not answers with an empty list that /// refuses additions. /// IMessageAttachments Attachments => Core.MessageAttachments.Unsupported; /// /// Structural copy of the message. Headers get a new dictionary, but the /// reference and header values are shared (shallow) — this is intentional and relied upon /// (e.g. a Splitter branch cloning into a shared aggregation list). For an isolated deep copy of /// the body use . /// IMessage Clone(); /// /// Deep, isolated copy for checkpoint/replay: like but the /// is deep-copied so the captured payload is frozen and immune to later in-place mutation. /// Header values follow (shared) as they carry immutable metadata. /// Throws if the body cannot be safely deep-copied /// (it must be immutable, a byte[], or implement ). /// IMessage Snapshot(); // ── Java-style API (kept forever, default interface methods) ── /// Java-style: returns Body. object? getBody() => Body; /// Java-style: returns Body cast to . T? getBody() { if (Body is null) return default; if (Body is T typed) return typed; try { return (T)RouteDecimal.ChangeType(Body, typeof(T)); } catch { return default; } // conversion failure — return default by design } /// Java-style: sets Body. void setBody(object? value) => Body = value; /// Java-style: returns ContentType. string? getContentType() => ContentType; /// Java-style: sets ContentType. void setContentType(string? value) => ContentType = value; /// Java-style: returns header value by key. object? getHeader(string key) => Headers.TryGetValue(key, out var v) ? v : null; /// Java-style: returns header value cast to . T? getHeader(string key) => GetHeader(key); /// Java-style: sets header value. void setHeader(string key, object? value) => Headers[key] = value; /// Java-style: returns Headers dictionary. IDictionary getHeaders() => Headers; /// Java-style: removes a header by key. void removeHeader(string key) => Headers.Remove(key); /// Java-style: deep copy (alias for Clone). IMessage copy() => Clone(); } Path: redb-route/redb.Route/Abstractions/IMessageAttachments.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/Abstractions/IMessageAttachments.cs ---- namespace redb.Route.Abstractions; /// /// The attachments of one message, in order. Unlike Camel's map, names may repeat: a form posts several files under one /// field and two files may share a name, and a map would lose all but one. Lookups by name return the first match. /// Names compare ordinally (file names and Content-IDs are case-sensitive). /// /// Not thread-safe, like . public interface IMessageAttachments : IReadOnlyList { /// The first attachment named , or null. Attachment? Find(string name); /// Every attachment named , in order; empty when there is none. IReadOnlyList FindAll(string name); /// Appends an attachment; an attachment with the same name may already be there. void Add(Attachment attachment); /// /// Puts in place of every attachment with its name: at the position of the first one, /// or at the end when there is none. /// void Set(Attachment attachment); /// Removes every attachment named . /// How many were removed. int Remove(string name); /// Removes all attachments. void Clear(); } Path: redb-route/redb.Route/Abstractions/IMessageDataFormat.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/Abstractions/IMessageDataFormat.cs ---- namespace redb.Route.Abstractions; /// /// A data format that works on the whole exchange rather than on bytes alone, as Apache Camel's DataFormat /// receives the exchange: it reads the content type of the In message with its parameters (a boundary, a /// charset), reads the body as it came (byte[], string or a , without buffering /// by the step), writes the body, the content type and the attachments, and takes engine settings from /// (the stream cache a large part spools to). Marshal, Unmarshal and /// ConvertBody call these methods when the resolved format implements this interface, and the byte methods of /// otherwise. /// /// /// Registration, lookup by content type and the XML dataFormat element are those of /// . A format sets and the Content-Type header /// itself; the step does not overwrite them. A format decides itself what to do with a body that is not its own (MIME /// multipart leaves it unchanged, as Camel's mimeMultipart does). /// public interface IMessageDataFormat : IMessageSerializer { /// Turns the wire form in exchange.In into , in place. ValueTask UnmarshalAsync(IExchange exchange, Type targetType, CancellationToken ct = default); /// Turns the body of exchange.In (and its attachments, when the format carries them) into the wire form, in place. ValueTask MarshalAsync(IExchange exchange, CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/IMessageSerializer.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/Abstractions/IMessageSerializer.cs ---- namespace redb.Route.Abstractions; /// /// Defines a strategy for serializing and deserializing message bodies. /// Implementations handle specific formats (JSON, Protobuf, MessagePack, etc.). /// public interface IMessageSerializer { /// Content type this serializer handles (e.g., "application/json"). string ContentType { get; } /// /// All media types this serializer can handle, including structured-suffix aliases /// (e.g. application/json, application/vnd.api+json, application/problem+json). /// Default implementation returns a single-element list containing . /// Implementations override this to claim multiple media types in a single registration. /// /// /// Used by during Register so that one /// serializer instance covers all its aliases without repeated calls. /// IReadOnlyCollection MediaTypes => new[] { ContentType }; /// /// true for a format whose input is raw bytes rather than an object model (Base64, GZip, Zip): /// a byte[] body is the payload to wrap, not an already-marshalled result, so Marshal /// must not pass it through. Default false. /// bool WrapsBytes => false; /// Serializes a value to a byte array. /// Value type. /// Value to serialize. /// Serialized bytes. byte[] Serialize(T value); /// Deserializes a byte array to a typed value. /// Target type. /// Serialized bytes. /// Deserialized value. T? Deserialize(byte[] data); /// Deserializes a byte array to a typed value. /// Serialized bytes. /// Target type. /// Deserialized value. object? Deserialize(byte[] data, Type type); } Path: redb-route/redb.Route/Abstractions/INormalizerDefinition.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/Abstractions/INormalizerDefinition.cs ---- using System; namespace redb.Route.Abstractions; /// /// Fluent builder for configuring a Normalizer step. /// Maps different input formats to a single canonical form using predicate-based routing. /// public interface INormalizerDefinition { /// When the predicate matches, apply the transform to normalize the body. /// Condition to evaluate against the exchange. /// Transform function producing the normalized body. INormalizerDefinition When( Func predicate, Func transform); /// When the content type matches, apply the transform to normalize the body. /// Expected content type value. /// Transform function producing the normalized body. INormalizerDefinition WhenContentType( string contentType, Func transform); /// Default transform when no predicate matches. /// Fallback transform function. INormalizerDefinition Otherwise(Func transform); } Path: redb-route/redb.Route/Abstractions/IPredicate.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/Abstractions/IPredicate.cs ---- namespace redb.Route.Abstractions; /// /// Predicate for conditional message processing in route pipelines. /// Determines whether a given condition is satisfied for a specific exchange. /// Used by filter, choice, when, and other routing constructs. /// public interface IPredicate { /// /// Evaluates the predicate synchronously against the exchange. /// /// The exchange to test. /// true if the condition is satisfied; otherwise false. bool Matches(IExchange exchange); /// /// Evaluates the predicate asynchronously against the exchange. /// /// The exchange to test. /// A task yielding true if the condition is satisfied; otherwise false. Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Abstractions/IPredicateExpression.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/Abstractions/IPredicateExpression.cs ---- namespace redb.Route.Abstractions; /// /// An expression that defines its own reading in a condition, rather than being evaluated to a /// value and read for truthiness. /// /// /// /// A query language brings a notion of a match that evaluating-then-reading cannot reconstruct. /// XPath("/order/discount") in a condition asks whether the path matched; flattening the /// node-set to a value first answers with the node's content instead, so /// <discount>0</discount> would read as "no match". Implementing this interface /// keeps that decision where the language's semantics live. /// /// /// It deliberately does not extend . Condition-taking verbs are /// overloaded on and both, so an expression that /// implemented the latter would make Filter(XPath("/a/b")) an ambiguous call — the language /// would gain a semantics and lose the spelling that needed it. /// /// public interface IPredicateExpression : IExpression { /// /// Evaluates the expression in a condition position. /// /// The exchange to test. /// true when the condition holds for the exchange. bool Matches(IExchange exchange); } Path: redb-route/redb.Route/Abstractions/IProcessor.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/Abstractions/IProcessor.cs ---- namespace redb.Route.Abstractions; /// /// Processes a message exchange asynchronously. /// All processors in redb.Route are async-first with CancellationToken support. /// public interface IProcessor { /// Processes the exchange asynchronously. /// The message exchange to process. /// Cancellation token for graceful shutdown. Task Process(IExchange exchange, CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/IProcessorDefinition.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/Abstractions/IProcessorDefinition.cs ---- namespace redb.Route.Abstractions; /// /// Camel-canonical processor definition. Each EIP node implements this interface /// and knows how to compile itself into a runtime . /// public interface IProcessorDefinition { /// Child nodes compiled as a linear pipeline by default. IList Outputs { get; } /// Parent node in the AST; null for the root route. IProcessorDefinition? Parent { get; set; } /// Compile this node into a runtime processor. IProcessor CreateProcessor(IRouteContext context); } Path: redb-route/redb.Route/Abstractions/IProducer.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/Abstractions/IProducer.cs ---- namespace redb.Route.Abstractions; /// /// Sends messages to an endpoint. Extends IProcessor — producing is just processing. /// public interface IProducer : IProcessor { /// Starts the producer. /// Cancellation token. Task Start(CancellationToken ct = default); /// Stops the producer. /// Cancellation token. Task Stop(CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/IProducerTemplate.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/Abstractions/IProducerTemplate.cs ---- namespace redb.Route.Abstractions; /// /// Client API for sending messages to endpoints programmatically, outside of route pipelines. /// Must be started before use via . Supports fire-and-forget, request/reply, /// and processor-based send patterns. Thread-safe after is called. /// public interface IProducerTemplate { /// Gets the route context associated with this template. IRouteContext Context { get; } /// Gets whether this template has been started and is ready for use. bool IsStarted { get; } // ── Synchronous Send ── /// Sends a message body to the specified endpoint URI. /// Target endpoint URI (e.g., "direct:orders"). /// Message body to send. void Send(string endpointUri, object body); /// Sends a message body to the specified endpoint. /// Target endpoint instance. /// Message body to send. void Send(IEndpoint endpoint, object body); /// Sends a pre-built exchange to the specified endpoint. /// Target endpoint instance. /// Exchange to send. void Send(IEndpoint endpoint, IExchange exchange); /// Sends a pre-built exchange to the endpoint resolved from URI. /// Target endpoint URI. /// Exchange to send. void Send(string endpointUri, IExchange exchange); /// Sends a message to the specified endpoint. /// Target endpoint instance. /// Message to wrap in an exchange and send. void Send(IEndpoint endpoint, IMessage message); /// Sends a message to the endpoint resolved from URI. /// Target endpoint URI. /// Message to send. void Send(string endpointUri, IMessage message); /// Applies a processor to an exchange and sends it to the endpoint. /// Target endpoint instance. /// Processor to apply to the exchange before sending. void Send(IEndpoint endpoint, IProcessor processor); // ── Async Send (fire-and-forget) ── /// Asynchronously sends a message body to the endpoint. /// Target endpoint instance. /// Message body to send. Task SendAsync(IEndpoint endpoint, object body); /// Asynchronously sends a message body to the endpoint URI. /// Target endpoint URI. /// Message body to send. Task SendAsync(string endpointUri, object body); /// Asynchronously sends a message to the endpoint. /// Target endpoint instance. /// Message to send. Task SendAsync(IEndpoint endpoint, IMessage message); /// Asynchronously sends a message to the endpoint URI. /// Target endpoint URI. /// Message to send. Task SendAsync(string endpointUri, IMessage message); // ── Async Send of a pre-built exchange (caller-owned) ── /// /// Asynchronously sends a pre-built exchange to the endpoint. /// Unlike the body/message overloads the exchange is caller-owned: it is neither cloned /// nor disposed, and no DI scope is attached — the caller controls its lifetime and any scope /// it carries. Intended for forwarding an existing exchange, e.g. replaying a captured snapshot /// into an internal direct: endpoint. /// /// Target endpoint instance. /// Pre-built exchange to send. /// Token to cancel the in-flight send. Task SendAsync(IEndpoint endpoint, IExchange exchange, CancellationToken cancellationToken = default); /// Asynchronously sends a pre-built, caller-owned exchange to the endpoint resolved from URI. /// Target endpoint URI. /// Pre-built exchange to send. /// Token to cancel the in-flight send. Task SendAsync(string endpointUri, IExchange exchange, CancellationToken cancellationToken = default); // ── Request/Reply ── /// /// Sends a pre-built exchange with and returns the same /// exchange once the producer has populated . The exchange is /// caller-owned — not cloned or disposed — so the caller reads the reply and controls /// its lifetime. /// /// Target endpoint instance. /// Pre-built request exchange. /// Token to cancel the in-flight request. /// The same exchange instance, now carrying the reply in . Task RequestAsync(IEndpoint endpoint, IExchange exchange, CancellationToken cancellationToken = default); /// Sends a pre-built, caller-owned exchange (InOut) by URI and returns it once is populated. /// Target endpoint URI. /// Pre-built request exchange. /// Token to cancel the in-flight request. Task RequestAsync(string endpointUri, IExchange exchange, CancellationToken cancellationToken = default); /// /// Sends a request and waits for the reply body asynchronously. /// Uses to signal request/reply semantics. /// The exchange ends before this method returns, so a reply that reads from resources of its exchange (a streamed /// query result, ) is refused with : read such a /// reply through and dispose the exchange afterwards. /// /// Target endpoint instance. /// Request body. /// Token to cancel the in-flight request. /// The response body from , or null. Task RequestBody(IEndpoint endpoint, object body, CancellationToken cancellationToken = default); /// /// Sends a request by URI and waits for the reply body asynchronously. /// /// Target endpoint URI. /// Request body. /// Token to cancel the in-flight request. /// The response body from , or null. Task RequestBody(string endpointUri, object body, CancellationToken cancellationToken = default); /// /// Sends an explicit as the request and waits for the reply body. /// Headers and ContentType on the message are preserved (the message is not re-wrapped). /// Task RequestBody(IEndpoint endpoint, IMessage message, CancellationToken cancellationToken = default); /// /// Sends an explicit by URI and waits for the reply body. /// Task RequestBody(string endpointUri, IMessage message, CancellationToken cancellationToken = default); /// /// Sends a request and returns the reply body cast to . /// A nullable converts to its underlying type; a reply that does not convert throws /// . /// /// Expected response type. /// Target endpoint instance. /// Request body. /// Token to cancel the in-flight request. /// The typed response body, or default when the reply has no body. Task RequestBody(IEndpoint endpoint, object body, CancellationToken cancellationToken = default); /// /// Sends a request by URI and returns the reply body cast to . /// /// Expected response type. /// Target endpoint URI. /// Request body. /// Token to cancel the in-flight request. /// The typed response body, or default. Task RequestBody(string endpointUri, object body, CancellationToken cancellationToken = default); // ── Lifecycle ── /// Starts the producer template. Must be called before any send/request methods. void Start(); /// Stops the producer template. No send/request methods may be called after this. void Stop(); } Path: redb-route/redb.Route/Abstractions/IRouteBuilder.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/Abstractions/IRouteBuilder.cs ---- namespace redb.Route.Abstractions; /// /// Configures routes using fluent DSL. Implement this to define route topology. /// public interface IRouteBuilder { /// Configures routes on the given context. /// The route context to configure. void Configure(IRouteContext context); } Path: redb-route/redb.Route/Abstractions/IRouteContext.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/Abstractions/IRouteContext.cs ---- #pragma warning disable CS0619 using redb.Route.Core; namespace redb.Route.Abstractions; /// /// Central runtime context for route management: endpoint cache, component registry, /// named object registry, context-level properties, service locator, and route lifecycle. /// Provides three-tier exception handling (local route → global → error handler fallback). /// Thread-safe via . /// public interface IRouteContext : IDisposable { // ── Identity ── /// Unique context identifier (GUID by default). string ContextId { get; } /// Whether has been called and the context is running. bool IsStarted { get; } // ── Endpoint Management ── /// Resolves or creates an endpoint by URI string. Caches by NormalizedKey. /// Endpoint URI (e.g., "direct:orders", "kafka://topic?brokers=localhost"). /// Cached or newly created endpoint. IEndpoint GetEndpoint(string uri); /// Returns a snapshot of all currently cached endpoints. IReadOnlyList GetEndpoints(); // ── Thread pool profiles ── /// /// Registers a named thread pool profile that a detached step (WireTap, asynchronous OnCompletion) /// picks with executorService. A module that builds its routes in code registers its profile here before its /// routes are compiled. Registering a name again with the same bounds does nothing; with other bounds it throws, /// naming both, so two modules cannot silently size one pool. /// /// The profile's name. /// Its bounds; the context keeps a copy. void AddThreadPoolProfile(string name, Configuration.ThreadPoolProfile profile); /// /// The profile a detached step builds its pool from: the named one, or the context's default when /// is null. An unknown name throws, naming it. /// /// The profile's name, or null for the default profile. Configuration.ThreadPoolProfile GetThreadPoolProfile(string? name); // ── Component Management ── /// Registers a component for its URI scheme. /// The component to register. void AddComponent(IComponent component); /// Gets a component by type, optionally filtering by scheme name. /// Component type. /// Optional scheme to match. If null, returns first matching type. /// The component, or default if not found. T? GetComponent(string? scheme = null) where T : class, IComponent; /// Returns whether a component with the specified scheme is registered. bool HasComponent(string scheme); /// Returns a snapshot of all registered component scheme names. IReadOnlyList GetComponentNames(); /// Removes a component by scheme. Returns true if removed. bool RemoveComponent(string scheme); // ── Properties (context-level shared state) ── /// Gets or sets a context-level property by key. Returns null if not found. object? this[string key] { get; set; } /// Gets a typed property value with automatic conversion. /// Target type. /// Property key. /// Converted value, or default. T? GetProperty(string key); /// Sets a typed property. Returns this context for chaining. IRouteContext SetProperty(string key, T value); // ── Named Object Registry ── /// Stores a named object in the registry (factories, shared state, etc.). /// Registry key. /// Object to store. /// This context for chaining. IRouteContext AddToRegistry(string key, object value); /// Retrieves a typed object from the registry. /// Expected type. /// Registry key. A leading # prefix (registry reference) is stripped automatically. /// The object, or default if not found or wrong type. T? GetFromRegistry(string key); // ── Service Locator ── /// Registers a service instance by type. /// Service type key. /// Service instance. void AddService(Type serviceType, object service); /// Retrieves a service by type. /// Service type. /// Service instance, or default if not registered. T? GetService() where T : class; // ── Dependency Injection ── /// /// Stores an for DI container integration. /// Services resolved from this provider are available to processors and components. /// /// DI service provider. /// This context for chaining. IRouteContext SetServiceProvider(IServiceProvider serviceProvider); /// /// Retrieves the registered , or null if not set. /// IServiceProvider? GetServiceProvider(); // ── Exception Handling ── /// /// Gets or sets the context's error handler — Apache Camel's context-level error handler: on every route, the /// last resort for a failure no OnException took and no local or global handler matches. A handler that /// marks the exchange handled (, as a dead letter channel does) ends the /// failure; otherwise the failure goes on to the caller. Set to null to disable. /// IErrorHandler? ErrorHandler { get; set; } /// /// Checks whether an exception handler is registered (globally or locally) /// for the specified exception type. /// /// Exception type to check. /// true if a handler is registered. bool HasExceptionRoute() where TException : Exception; /// /// Handles an exception using three-tier search order: /// 1. Local route handler (by ). /// 2. Global handler (registered via ). /// 3. Fallback error handler. /// Walks the exception type hierarchy to find the best matching handler; throws when none matches. The same /// lookup is the outermost layer of every route's error scope, so the engine does not call this method itself — /// it is for a caller outside a route. /// /// The exchange that caused the exception. /// The exception to handle. /// Cancellation token. Task HandleException(IExchange exchange, Exception exception, CancellationToken ct = default); // ── Replay checkpoints ── /// /// Re-runs the tail of a route from a captured checkpoint snapshot. Runs the compiled body of /// the .Replayable(markerName) marker directly (no synthetic endpoint) with the supplied /// snapshot as the exchange. Intended for the platform (Tsak) to replay a failed exchange from a /// save-point. The snapshot is caller-owned (typically a /// read from a failed exchange's property, or a /// rehydrated one from durable storage). /// /// Route the marker belongs to. /// Name of the .Replayable marker to replay into. /// The exchange snapshot to run the tail with. /// Cancellation token. /// No such marker on the route. Task ReplayAsync(string routeId, string markerName, IExchange snapshot, CancellationToken ct = default); /// /// Lists every compiled replay marker as (routeId, markerName). Lets the platform show /// which routes are replayable and into which save-points, before any traffic has flowed. /// IReadOnlyCollection<(string RouteId, string MarkerName)> GetReplayMarkers(); /// /// Registers a global exception handler for a specific exception type: on every route, for a failure of this type /// no OnException took. The processor runs with the failure on the exchange; unless it marks the exchange /// handled, the failure goes on to the caller. /// /// Exception type to handle. /// Processor to invoke when this exception type is caught. void AddGlobalExceptionHandler(IProcessor processor) where TException : Exception; /// /// Registers a global exception handler for the specified exception type (non-generic overload). /// /// Exception type to handle. /// Processor to invoke when the exception is caught. void AddGlobalExceptionHandler(Type exceptionType, IProcessor processor); /// /// Registers a local exception handler for a specific route and exception type: checked before the global /// handlers, for a failure of that route no OnException took. /// /// Route identifier. /// Exception type to handle. /// Processor to invoke when this exception type is caught in this route. void AddLocalExceptionHandler(string routeId, Type exceptionType, IProcessor processor); // ── Routes ── /// Returns a snapshot of all compiled routes managed by this context. IReadOnlyList Routes { get; } // ── Lifecycle ── /// Registers a lifecycle listener for route and context state change notifications. /// Listener to add. /// This context for chaining. IRouteContext AddLifecycleListener(IRouteLifecycleListener listener); /// /// Registers a factory that can create instances for routes /// during compilation. When multiple factories are registered, the first non-null result wins. /// /// Policy factory to add. /// This context for chaining. IRouteContext AddRoutePolicyFactory(IRoutePolicyFactory factory); /// /// Returns the effective cluster-policy resolution for a compiled route. /// /// Route identifier. /// /// A describing whether .Cluster(true) was requested /// and which policy (if any) was actually attached. Returns a descriptor with /// = "AllNodes" and /// = "Route not found" when the route is unknown. /// RoutePolicyDescriptor GetRoutePolicy(string routeId); /// /// Starts all registered endpoints and consumers. Uses degraded-mode startup: /// logs individual endpoint failures but continues starting remaining endpoints. /// /// Cancellation token. Task Start(CancellationToken ct = default); /// Stops all routes managed by this context. /// Cancellation token. Task Stop(CancellationToken ct = default); /// Starts an individual route by its route ID. /// The route identifier. /// Cancellation token. Task StartRoute(string routeId, CancellationToken ct = default); /// Stops an individual route by its route ID. /// The route identifier. /// Cancellation token. Task StopRoute(string routeId, CancellationToken ct = default); /// Stops an individual route with an optional timeout override. /// The route identifier. /// Timeout for graceful drain. If null, uses default shutdown timeout. /// Cancellation token. Task StopRoute(string routeId, TimeSpan? timeout, CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/IRouteDefinition.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/Abstractions/IRouteDefinition.cs ---- using Json.Schema; using Microsoft.Extensions.Logging; using redb.Route.Definitions; using redb.Route.Transactions; using redb.Route.Validation; using redb.Route.Xslt; using System.Threading; using System.Threading.Tasks; using System.Xml.Schema; namespace redb.Route.Abstractions; /// /// New fluent DSL for defining a message route using the canonical ProcessorDefinition model. /// All leaf methods return for chaining. /// Scope-opener methods (Filter, Choice, Split, TryCatch, etc.) return the opened definition /// and expose an End()/EndXxx() method that returns the parent definition. /// public interface IRouteDefinition : IProcessorDefinition { // ── Identity ── /// Assigns a unique route identifier. IRouteDefinition RouteId(string routeId); /// Gets the assigned route ID (null if not set). string? GetRouteId(); /// /// Names the most recently added step (Apache Camel id()), for AdviceWith weaving /// (WeaveById) and diagnostics. Before any step has been added it names the route itself. /// IRouteDefinition Id(string id); /// /// Gives the most recently added step a human-readable label (Apache Camel description()). /// The label replaces the type-derived one in message history; the node id is unaffected. Before /// any step has been added it describes the route itself. /// IRouteDefinition Description(string description); // ── Interception and completion (declared on the route; RouteBuilder has the same verbs for every route) ── /// Opens steps that run before every step of this route, including steps nested in scopes (Camel intercept()). Close with EndIntercept(). Definitions.InterceptDefinition Intercept(); /// Opens steps that run once when a message enters the route, optionally only for a From URI matching the mask (Camel interceptFrom()). Definitions.InterceptDefinition InterceptFrom(string? uriPattern = null); /// Opens steps that run before a To / ToD whose target matches the mask; .SkipSendToOriginalEndpoint() replaces the send (Camel interceptSendToEndpoint()). Definitions.InterceptDefinition InterceptSendToEndpoint(string uriPattern); /// Opens steps that run after the route finished with an exchange, on a copy, outside the route's transaction (Camel onCompletion()). Close with EndOnCompletion(). Definitions.OnCompletionDefinition OnCompletion(); // ── Header / property / body sugar ── /// Sets several headers in one step; an or Func<IExchange, object?> value is evaluated per message, anything else is a constant. IRouteDefinition SetHeaders(params (string Name, object? Value)[] headers); /// Sets several exchange properties in one step, in order; an or Func<IExchange, object?> value is evaluated per message, anything else is a constant. IRouteDefinition SetProperties(params (string Name, object? Value)[] properties); /// Removes every header whose name matches the mask (exact, trailing *, or regex:), except those listed. IRouteDefinition RemoveHeaders(string pattern, params string[] except); /// Removes every exchange property whose key matches the mask, except those listed. IRouteDefinition RemoveProperties(string pattern, params string[] except); /// Sorts the collection selected by a route-language expression and puts the sorted list into the body; the key expression sees each element as body (Sort("body.items", "body.priority")). IRouteDefinition Sort(string collectionExpression, string? keyExpression = null, bool descending = false); /// Sorts a typed collection selected from the exchange; the body becomes a List<T>. IRouteDefinition Sort(Func> source, Func? key = null, bool descending = false, IComparer? comparer = null); /// Sets whether this route should auto-start. Default is true. IRouteDefinition AutoStart(bool value = true); /// Gets whether this route auto-starts. bool GetAutoStart(); /// Sets the per-exchange processing timeout for this route. /// Thrown when is zero or negative (excluding ). IRouteDefinition ProcessingTimeout(TimeSpan timeout); // ── Source ── /// Sets the source (consumer) endpoint URI. IRouteDefinition From(string uri); /// Gets the source endpoint URI (null if not set). string? GetFromUri(); // ── Destination ── /// Sends the exchange to an endpoint via producer. IRouteDefinition To(string uri); /// Camel-style dynamic-to: sends the exchange to an endpoint URI computed /// per message from a ${...} template (e.g. .ToD("kafka://orders-${header.region}")). /// Producers are cached per resolved URI and tracked by . IRouteDefinition ToD(string uriTemplate); /// Camel-style dynamic-to using an that yields the URI. IRouteDefinition ToD(IExpression uriExpression); /// Camel-style dynamic-to using a delegate that yields the URI per exchange. IRouteDefinition ToD(Func uriFactory); // ── Processing delegates ── /// Processes the exchange with a synchronous action. IRouteDefinition Process(Action action); /// Processes the exchange with an asynchronous action. IRouteDefinition Process(Func action); /// Processes the exchange with a pre-built processor instance. IRouteDefinition Process(IProcessor processor); // ── Transform / body ── /// Sets the exchange body to a static value. IRouteDefinition SetBody(object? value); /// Sets the exchange body using a factory. IRouteDefinition SetBody(Func factory); /// /// Sets the exchange body using an . A ${...} template is one: /// SetBody(Expr("Hello ${header.name}")). A plain string passed to /// stays a literal — the position decides, the content never does. /// IRouteDefinition SetBody(IExpression expression); /// Transforms the exchange body using a factory. IRouteDefinition Transform(Func transform); /// Transforms the exchange body using an . IRouteDefinition Transform(IExpression expression); /// Removes (nulls) the exchange body. IRouteDefinition RemoveBody(); // ── Headers ── /// Sets a header to a static value. IRouteDefinition SetHeader(string key, object? value); /// Sets a header using a factory. IRouteDefinition SetHeader(string key, Func factory); /// /// Sets a header using an ; a ${...} template is one: /// SetHeader("target", Expr("queue-${header.tenant}")). /// IRouteDefinition SetHeader(string name, IExpression expression); /// Removes a header. IRouteDefinition RemoveHeader(string key); // ── Attachments ── /// /// Adds an attachment to the message with the value of (byte[], string as /// UTF-8, a Stream, an ). The text arguments are literal. /// IRouteDefinition AddAttachment(string name, IExpression content, string? fileName = null, string? contentType = null); /// As with the file name evaluated per message. IRouteDefinition AddAttachment(string name, IExpression content, IExpression fileName, string? contentType = null); /// /// Adds the message body as an attachment; the body stays. The content type defaults to the message's. The text /// arguments are literal. /// IRouteDefinition AddAttachmentFromBody(string name, string? fileName = null, string? contentType = null); /// As with the file name evaluated per message. IRouteDefinition AddAttachmentFromBody(string name, IExpression fileName, string? contentType = null); /// /// Adds the file at as an attachment, read from disk whenever it is sent; the name and file /// name default to the file's name. The text arguments are literal. /// IRouteDefinition AddAttachmentFromFile(string path, string? name = null, string? contentType = null); /// As with the path evaluated per message. IRouteDefinition AddAttachmentFromFile(IExpression path, string? name = null, string? contentType = null); /// Removes the attachments named . IRouteDefinition RemoveAttachment(string name); /// Removes every attachment of the message. IRouteDefinition RemoveAttachments(); // ── Properties ── /// Sets a property to a static value. IRouteDefinition SetProperty(string key, object? value); /// Sets a property using a factory. IRouteDefinition SetProperty(string key, Func factory); /// /// Sets a property using an ; a ${...} template is one: /// SetProperty("tenant", Expr("${header.tenant}")). /// IRouteDefinition SetProperty(string key, IExpression expression); /// Removes a property. IRouteDefinition RemoveProperty(string key); // ── Logging ── /// Logs a static message. IRouteDefinition Log(string message, LogLevel level = LogLevel.Information); /// Logs a dynamic message from a factory. IRouteDefinition Log(Func messageFactory, LogLevel level = LogLevel.Information); // ── Stop / Throw ── /// Stops exchange processing. IRouteDefinition Stop(); /// Rethrows the exception stored on the exchange. IRouteDefinition ThrowException(); /// Throws a new exception with the given message. IRouteDefinition ThrowException(string message); /// Throws a specific pre-built exception instance. IRouteDefinition ThrowException(Exception exception); /// Instantiates and throws an exception by type and message. IRouteDefinition ThrowException(Type exceptionType, string message); /// Instantiates and throws a typed exception. IRouteDefinition ThrowException(string? message = null) where TException : Exception, new(); // ── Delay / Sampling ── /// Delays processing by a fixed duration. IRouteDefinition Delay(TimeSpan duration); /// Delays processing by a dynamic duration computed from the exchange. IRouteDefinition Delay(Func factory); /// Delays by a route-language expression evaluated per message: milliseconds ("${header.backoff}", "header.attempt * 500"), a , or hh:mm:ss text. IRouteDefinition Delay(string durationExpression); /// Samples messages by passing every N-th message (count-based). IRouteDefinition Sample(long messageFrequency); /// Samples messages by period — at most one message per . IRouteDefinition Sample(TimeSpan period); // ── Stream caching ── /// /// Wraps a forward-only body with a seekable cache so /// subsequent steps can re-read it multiple times. Non-Stream bodies pass through unchanged. /// /// Bytes threshold before spooling to a temp file (null = default 128 KB). IRouteDefinition StreamCaching(long? spoolThreshold = null); // ── Validation ── /// Validates the exchange using the provided instance. IRouteDefinition Validate(IMessageValidator validator, bool throwOnFailure = true); /// Validates the exchange using a predicate function. IRouteDefinition Validate(Func predicate, string errorMessage = "Validation failed", bool throwOnFailure = true); /// Validates the exchange against an . IRouteDefinition Validate(IPredicate predicate, string errorMessage = "Validation failed", bool throwOnFailure = true); /// /// Validates the exchange against an expression read as a condition, as Filter and When read one: /// Validate(Expr("header.amount > 0")), Validate(Method("#rules", "IsValid(${body})")), where a /// Task<bool> method is awaited. /// IRouteDefinition Validate(IExpression condition, string errorMessage = "Validation failed", bool throwOnFailure = true) => Validate(Predicates.PredicateFactory.FromExpression(condition), errorMessage, throwOnFailure); /// Validates the exchange body against a JSON Schema provided as a string. IRouteDefinition ValidateJsonSchema(string schemaJson, bool throwOnFailure = true); /// Validates the exchange body against a pre-parsed . IRouteDefinition ValidateJsonSchema(JsonSchema schema, bool throwOnFailure = true); /// Validates the exchange body against an XSD schema string. IRouteDefinition ValidateXsd(string xsdContent, bool throwOnFailure = true); /// Validates the exchange body against an XSD schema string with an explicit target namespace. IRouteDefinition ValidateXsd(string? targetNamespace, string xsdContent, bool throwOnFailure = true); /// Validates the exchange body against a pre-built . IRouteDefinition ValidateXsd(XmlSchemaSet schemaSet, bool throwOnFailure = true); /// /// Validates the exchange body against an XSD file whose xs:import and xs:include are read relative /// to it, from under only (never the network); a reference that does not load is an /// error when the route is built. The path resolves through the context's resource resolver. /// /// The XSD file (schemas/order.xsd). /// Target namespace; null takes the schema's own. /// /// The directory imports stay under, relative to the schema's directory; null is that directory. /// /// Whether a validation failure throws. IRouteDefinition ValidateXsdFile(string schemaPath, string? targetNamespace = null, string? schemaRoot = null, bool throwOnFailure = true); // ── XSLT ── /// Apache Camel xslt: parity: transform the body through an XSLT stylesheet file. IRouteDefinition Xslt(string stylesheetPath, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false); /// Transform the body through an inline XSLT stylesheet document. IRouteDefinition XsltContent(string stylesheetXml, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false); // ── Control Bus ── /// Apache Camel controlbus: parity: manage a route at runtime (start/stop/suspend/resume/restart/status/stats/fail). IRouteDefinition ControlBus(redb.Route.ControlBus.ControlBusAction action, string routeId, bool async = false); // ── Serialization ── /// Marshals (serializes) the exchange body using the specified serializer type. IRouteDefinition Marshal(Type serializerType); /// Marshals (serializes) the exchange body using the specified serializer type. IRouteDefinition Marshal() where TSerializer : class; /// Unmarshals (deserializes) the exchange body to using the specified serializer type. IRouteDefinition Unmarshal(Type serializerType, Type targetType); /// Unmarshals (deserializes) the exchange body using the specified serializer and target types. IRouteDefinition Unmarshal() where TSerializer : class; /// Marshals the body with the data format registered for ("text/csv"); an unregistered format fails Start(). IRouteDefinition Marshal(string contentType); /// Marshals the body with a configured serializer instance (per-node options): Marshal(new CsvDataFormat(o)). IRouteDefinition Marshal(IMessageSerializer serializer); /// Unmarshals the body to with the data format registered for . IRouteDefinition Unmarshal(string contentType); /// Unmarshals the body to with the data format registered for . IRouteDefinition Unmarshal(string contentType, Type targetType); /// Unmarshals the body to with a configured serializer instance. IRouteDefinition Unmarshal(IMessageSerializer serializer); /// Unmarshals the body to with a configured serializer instance. IRouteDefinition Unmarshal(IMessageSerializer serializer, Type targetType); /// Apache Camel parity: unmarshal the body to using the data format /// registry entry resolved from the incoming message ContentType. IRouteDefinition Unmarshal(); /// Apache Camel parity: convert the exchange body to . IRouteDefinition ConvertBody(); /// Apache Camel parity: convert the exchange body to . IRouteDefinition ConvertBody(Type targetType); /// Apache Camel parity: open a typed scope auto-converting the body to . OfTypeDefinition OfType(); // ── Transactions ── /// Begins an imperative transaction scope on the exchange (default Required policy). IRouteDefinition BeginTransaction(); /// Begins an imperative transaction scope with the specified . IRouteDefinition BeginTransaction(TransactionPolicy policy); /// Commits the imperative transaction scope and all deferred actions. IRouteDefinition CommitTransaction(); /// Rolls back the imperative transaction scope and all deferred actions. IRouteDefinition RollbackTransaction(); /// /// Opens a declarative transaction scope. All child steps execute inside a /// TransactedProcessor that auto-commits on success and auto-rolls-back on failure. /// Close the scope with or /// the universal . /// Definitions.TransactionDefinition Transaction(TransactionPolicy? policy = null); // ── Replay checkpoints ── /// /// Opens a replay checkpoint (save-point). The steps that follow are the marker's body (the tail /// re-run on replay); the exchange is snapshotted into route.checkpoint on each pass. At /// the start of a route no End is needed; otherwise close with /// or use the lambda-body overload. /// Definitions.ReplayableDefinition Replayable(string name, bool exposed = false); /// Lambda-body form of ; the chain stays on the current definition. IRouteDefinition Replayable(string name, Action body, bool exposed = false); // ── Telemetry ── /// /// Opens a tracing scope. All child steps run inside a single Activity span named . /// Close with or . /// Definitions.TracedDefinition Traced(string operationName); /// /// Inline tracing — wraps a single synchronous action in an Activity span named . /// IRouteDefinition Traced(string operationName, Action action); /// /// Inline tracing — wraps an asynchronous action in an Activity span named . /// IRouteDefinition Traced(string operationName, Func action); /// /// Inline tracing — wraps an in an Activity span named . /// IRouteDefinition Traced(string operationName, IProcessor processor); /// /// Opens a metrics scope. All child steps are measured by MeteredStepProcessor /// tagged with . /// Close with or . /// Definitions.MeteredDefinition Metered(string stepName); /// /// Inline metering — wraps a single synchronous action in a MeteredStepProcessor tagged with . /// IRouteDefinition Metered(string stepName, Action action); /// /// Inline metering — wraps an asynchronous action in a MeteredStepProcessor tagged with . /// IRouteDefinition Metered(string stepName, Func action); /// /// Inline metering — wraps an in a MeteredStepProcessor tagged with . /// IRouteDefinition Metered(string stepName, IProcessor processor); /// /// Puts the attribute = (a literal) on a span of the engine, so the /// trace can be found by it. See . /// /// Attribute name: lowercase, dot-separated, outside the reserved namespaces (redb., http., ...). /// The value, as is — a literal, never a template; a template is Expr("${...}"). /// Which span receives it; the enclosing Traced scope or route span by default. IRouteDefinition SpanTag(string key, string value, Telemetry.SpanTarget target = Telemetry.SpanTarget.Enclosing); /// /// Puts the attribute on a span of the engine, its value evaluated per message — the way to /// find a trace by a business key (.SpanTag("sap.order.id", XPath("/Ack/OrderNo"))). The exchange is not /// touched. Nothing is set without a listener, on an unsampled span (the value is then not evaluated), for a /// null or empty value, or when the value fails to evaluate (logged at Debug). The value is exported /// unfiltered: never personal data or credentials. Its length is limited by the OpenTelemetry SDK /// (OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT). /// /// Attribute name: lowercase, dot-separated, outside the reserved namespaces (redb., http., ...). /// Expression producing the value. /// Which span receives it; the enclosing Traced scope or route span by default. /// is templated, malformed, reserved or names a secret. IRouteDefinition SpanTag(string key, IExpression value, Telemetry.SpanTarget target = Telemetry.SpanTarget.Enclosing); // ── Enrichment ── /// /// Sends a copy of the exchange to a URI and continues (wire tap). The copy runs on the tap's own bounded pool; /// when the pool and its queue are full, the profile's rejected policy decides (by default the caller runs it). /// /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(string uri, string? executorService = null); /// Sends a wire-tap copy to a URI, calling on the clone before dispatching. /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(string uri, Action onPrepare, string? executorService = null); /// Sends a wire-tap copy to a URI, replacing the clone's body with the result of . /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(string uri, Func newBodyFactory, string? executorService = null); /// Sends a wire-tap copy to a URI with both an callback and a body replacement factory. /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(string uri, Action onPrepare, Func newBodyFactory, string? executorService = null); /// Wire-tap to a dynamic URI computed per message from a factory. /// Producers are cached per resolved URI. /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(Func uriFactory, string? executorService = null); /// Dynamic-URI wire-tap with an callback. /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(Func uriFactory, Action onPrepare, string? executorService = null); /// Dynamic-URI wire-tap with a body replacement factory. /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(Func uriFactory, Func newBodyFactory, string? executorService = null); /// Dynamic-URI wire-tap with both an callback and a body factory. /// The thread pool profile the tap builds its own pool from (Camel executorService); the context's default profile when null. An unknown name fails when the route is built. IRouteDefinition WireTap(Func uriFactory, Action onPrepare, Func newBodyFactory, string? executorService = null); /// Content enricher — calls an endpoint and merges the result. IRouteDefinition Enrich(string resourceUri, Func mergeStrategy); /// Content enricher with a dynamic endpoint URI computed per message. IRouteDefinition Enrich(Func uriFactory, Func mergeStrategy); /// Content enricher whose endpoint URI comes from an expression, e.g. Enrich(XPath("/order/service"), merge). IRouteDefinition Enrich(IExpression uri, Func mergeStrategy); /// Content enricher from an expression, keeping the enriched result (UseLatest). IRouteDefinition Enrich(IExpression uri); /// Apache Camel parity: poll an external endpoint and merge the polled result. IRouteDefinition PollEnrich( string resourceUri, Func mergeStrategy, TimeSpan? timeout = null); /// Poll enricher with a dynamic endpoint URI computed per message. IRouteDefinition PollEnrich( Func uriFactory, Func mergeStrategy, TimeSpan? timeout = null); /// Enrich without a strategy: the response becomes the current message (Camel default, AggregationStrategies.UseLatest()). IRouteDefinition Enrich(string resourceUri); /// Enrich with a dynamic URI and no strategy: the response becomes the current message. IRouteDefinition Enrich(Func uriFactory); /// Poll enricher without a strategy: the polled message becomes the current one; on timeout the original stays. IRouteDefinition PollEnrich(string resourceUri, TimeSpan? timeout = null); /// Poll enricher with a dynamic URI and no strategy: the polled message becomes the current one; on timeout the original stays. IRouteDefinition PollEnrich(Func uriFactory, TimeSpan? timeout = null); /// Poll enricher whose endpoint URI comes from an expression. IRouteDefinition PollEnrich( IExpression uri, Func mergeStrategy, TimeSpan? timeout = null); /// Poll enricher from an expression with no strategy: the polled message becomes the current one. IRouteDefinition PollEnrich(IExpression uri, TimeSpan? timeout = null); /// Apache Camel parity: route to a list of recipient URIs computed at runtime. IRouteDefinition RecipientList( Func> recipientListFactory, bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null); /// /// Recipient list from an expression yielding either a sequence of URIs or one delimited /// string, e.g. RecipientList(XPath("/order/recipients/uri")). /// IRouteDefinition RecipientList( IExpression recipients, bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null, string uriDelimiter = ","); /// Apache Camel parity: iteratively route to URIs returned by a routing function. IRouteDefinition DynamicRouter(Func routingFunction); /// Dynamic router whose next hop comes from an expression; no value ends the routing. IRouteDefinition DynamicRouter(IExpression routingExpression); /// Apache Camel parity: Routing Slip — pipe the exchange through a list of endpoints /// computed once up front (Out→In between hops). IRouteDefinition RoutingSlip(Func> slipFactory, bool ignoreInvalidEndpoints = false); /// Apache Camel parity: Routing Slip from an expression yielding a delimited URI string. IRouteDefinition RoutingSlip(IExpression slip, string uriDelimiter = ",", bool ignoreInvalidEndpoints = false); /// Apache Camel parity: Routing Slip from a ${...} template resolving to a delimited URI string. IRouteDefinition RoutingSlip(string slipTemplate, string uriDelimiter = ",", bool ignoreInvalidEndpoints = false); /// Apache Camel parity: open a Resequencer scope. Child outputs receive exchanges /// in the order determined by . ResequenceDefinition Resequence( Func keySelector, int batchSize = 100, TimeSpan? timeout = null); // ── Scope openers ── /// /// Opens a Filter scope. Only exchanges matching the predicate will be processed by steps /// inside the scope. Close with . /// FilterDefinition Filter(Func predicate); /// /// Opens a Filter scope using an predicate. /// Close with . /// FilterDefinition Filter(IExpression expression); /// /// Opens a Filter scope guarded by an . The predicate is stored as the /// filter's condition and awaited per message through . /// FilterDefinition Filter(IPredicate predicate); /// /// Opens an Idempotent Consumer scope. Duplicate exchanges (same key) are skipped. /// Close with . /// IdempotentConsumerDefinition IdempotentConsumer( IIdempotentRepository repository, Func keyExtractor, bool skipDuplicate = true); /// /// Opens an Idempotent Consumer scope with the repository looked up by registered name at /// compile time — available on every definition, so the scope nests like any other. /// IdempotentConsumerDefinition IdempotentConsumer( Func keyExtractor, string repositoryName, bool skipDuplicate = true); /// Idempotent Consumer whose message id comes from an expression, e.g. IdempotentConsumer(repo, jpath("$.messageId")). IdempotentConsumerDefinition IdempotentConsumer( IIdempotentRepository repository, IExpression messageId, bool skipDuplicate = true); /// Idempotent Consumer from an expression, with the repository looked up by registered name. IdempotentConsumerDefinition IdempotentConsumer( IExpression messageId, string repositoryName, bool skipDuplicate = true); /// /// Claim Check step (Hohpe/Woolf). Stores the body away and lets a short claim key travel /// the route in its place, or restores the body from such a key. /// /// /// / / /// address an explicit key; /// / use an /// exchange-scoped stack and need none. /// /// Explicit claim key for Set/Get/GetAndRemove. Ignored by Push/Pop. /// Time-to-live for stored data. Used by Set/Push. /// /// Logical name of a repository registered with /// context.AddClaimCheckRepository(name, repository). Null uses the context default. /// IRouteDefinition ClaimCheck( ClaimCheckOperation operation, string? key = null, TimeSpan? ttl = null, string? repositoryName = null); /// /// Claim Check step against an explicit repository instance. /// IRouteDefinition ClaimCheck( IClaimCheckRepository repository, ClaimCheckOperation operation, string? key = null, TimeSpan? ttl = null); /// /// Opens a Choice (content-based router) scope. /// Add branches with .When() / .Otherwise(), close with .EndChoice(). /// ChoiceDefinition Choice(); /// /// Opens a Split scope. The splitter function splits the exchange body into parts; /// each part is processed through the scope pipeline. /// Close with . /// SplitDefinition Split(Func> splitter); /// /// Opens a Split scope using an expression to produce the split parts. /// The expression must evaluate to . /// Close with . /// SplitDefinition Split(IExpression expression); /// /// Opens a streaming Split scope backed by an async enumerable (no parallel / aggregation). /// Parts are processed one at a time without buffering. One part is read ahead, as Apache Camel's streaming split /// asks its iterator: whether a part is the last one (CamelSplitComplete) is known only once the next read /// finds nothing. A part must therefore stay valid after the next one is read: yield a value, not a view into a /// buffer the next read reuses. /// Close with . /// SplitDefinition Split(Func> splitter); /// /// Opens a Multicast scope (fan-out). Add targets with .To() / .Process(). /// Close with . /// MulticastDefinition Multicast(); /// /// Opens a Threads scope (Camel-style concurrency handoff). The child pipeline runs on a bounded /// pool of persistent workers, so a serial polling consumer can process /// up to exchanges concurrently. Async boundary — does not extend the /// caller's transaction; ordering is not preserved when > 1. /// Close with . /// /// Number of concurrent workers (must be >= 1). ThreadsDefinition Threads(int poolSize); /// /// Opens a TryCatch scope. Build the try body with leaf methods, /// then open catch branches with .Catch<T>() and optionally .Finally(). /// Close with .EndTryCatch(). /// TryCatchDefinition TryCatch(); /// /// Opens an Aggregate scope. Collects exchanges by correlation key and forwards completed /// aggregates to the body pipeline. Close with .EndAggregate(). /// AggregateDefinition Aggregate( Func correlationKey, Func aggregationStrategy, Func completionPredicate); /// /// Opens an Aggregate scope whose correlation key comes from an expression, e.g. /// Aggregate(XPath("/order/customerId"), strategy, completion). /// AggregateDefinition Aggregate( IExpression correlationKey, Func aggregationStrategy, Func completionPredicate); /// /// Opens a Throttle scope that limits exchange throughput to /// per period. Close with .EndThrottle(). /// ThrottleDefinition Throttle(int maxPerPeriod); /// /// Opens a Throttle scope whose limit is computed per exchange: the factory runs on every /// message, so the limit can come from a header, a property or an expression and change /// between messages. Close with .EndThrottle(). /// ThrottleDefinition Throttle(Func maxPerPeriodFactory); /// Throttle whose per-period limit is a route-language expression evaluated per message ("${header.rate}", "header.tier == 'gold' ? 100 : 10"). ThrottleDefinition Throttle(string maxPerPeriodExpression, TimeSpan? period = null); /// /// Opens a keyed Throttle scope that limits throughput per unique key extracted from the exchange. /// Close with .EndKeyedThrottle(). /// KeyedThrottleDefinition Throttle( Func keyExtractor, int maxPerPeriod, TimeSpan? period = null); /// /// Keyed Throttle whose limit is read from each message as well as its key: "gold customers 100 /// per second, others 10, each under its own key". Close with .EndKeyedThrottle(). /// KeyedThrottleDefinition Throttle( Func keyExtractor, Func maxPerPeriodFactory, TimeSpan? period = null); /// /// Keyed Throttle from two route-language expressions: the key ("header.customerId") and the /// per-message limit ("header.tier == 'gold' ? 100 : 10"). Both compile at build. /// KeyedThrottleDefinition Throttle( string keyExpression, string maxPerPeriodExpression, TimeSpan? period = null); /// /// Opens a CircuitBreaker scope. Configure options before adding downstream steps. /// Optionally add a fallback with .OnFallback(). /// Close with .EndCircuitBreaker(). /// CircuitBreakerDefinition CircuitBreaker(); /// /// Opens a Debounce scope. Suppresses rapid-fire messages per key, forwarding only the last /// exchange after of silence. Close with .EndDebounce(). /// DebounceDefinition Debounce(Func keyExtractor, TimeSpan quietPeriod); /// /// Opens a Loop scope that repeats the body pipeline times. /// Close with . /// /// Fixed number of iterations (non-negative). /// If true each iteration receives a clone of the original exchange. /// If true (default) clone iterations share the parent DI scope. LoopDefinition Loop(int count, bool copy = false, bool shareScope = true); /// /// Opens a Loop scope that repeats the body pipeline while holds. /// Close with . /// LoopDefinition Loop(Func condition, bool copy = false, bool shareScope = true); /// /// Opens a Loop scope that repeats while an holds; the predicate is /// awaited before every iteration. /// LoopDefinition Loop(IPredicate condition, bool copy = false, bool shareScope = true); /// /// Opens a Loop scope that repeats the body pipeline a number of times resolved from the exchange at runtime. /// Close with . /// LoopDefinition Loop(Func countFactory, bool copy = false, bool shareScope = true); /// Loop whose iteration count is a route-language expression evaluated per message ("${header.count}", "header.items.Count"); for a condition use LoopWhile(string). LoopDefinition Loop(string countExpression, bool copy = false, bool shareScope = true); // ── Bean / Service Activator ── /// Resolves from the exchange's ServiceProvider and invokes . IRouteDefinition Bean(Func method); /// Resolves from the exchange's ServiceProvider and invokes (no cancellation token). IRouteDefinition Bean(Func method); /// Resolves from the exchange's ServiceProvider and invokes a synchronous . IRouteDefinition Bean(Action method); /// /// Apache Camel's bean(ref, method): calls user code through the bean: component, as the step /// To("bean:" + reference + "?method=" + method) does, with the same endpoint, cache entry and statistics. /// /// /// #name for an object in the context registry, or Namespace.Type, Assembly for an instance the /// endpoint creates. /// /// /// The method in the bean: URI spelling: a name (Handle) or a name with bound arguments /// (Gross(${header.qty}, ${header.price})). Null picks the single suitable method. /// IRouteDefinition Bean(string reference, string? method = null) => To(Components.Bean.BeanComponent.UriFor(reference, method)); // ── Scatter-Gather ── /// /// Adds a scatter-gather step with static recipients and the specified aggregation strategy. /// IRouteDefinition ScatterGather( Func aggregationStrategy, params string[] recipients); /// /// Adds a scatter-gather step configured via a builder callback. /// IRouteDefinition ScatterGather(Action configure); // ── Saga ── /// /// Adds a saga step configured via a builder callback. /// IRouteDefinition Saga(Action configure); /// /// Opens a saga scope. Add steps with SagaStep() / OnSagaCompletion(), /// then close with or /// . /// Definitions.SagaDefinition Saga(); // ── LoadBalance ── /// /// Adds a load-balance step with the specified strategy and endpoint URIs. /// IRouteDefinition LoadBalance(ILoadBalancerStrategy strategy, params string[] uris); /// /// Adds a load-balance step configured via a builder callback. /// IRouteDefinition LoadBalance(Action configure); // ── Normalizer ── /// /// Adds a normalizer step configured via a builder callback. /// Each when-clause transforms messages matching its predicate. /// IRouteDefinition Normalize(Action configure); // ── Exception handling ── /// Marks the exchange exception as handled: clears the exception and sets ExceptionHandled = true. IRouteDefinition ExceptionHandled(); /// /// Camel's markRollbackOnly(): marks the unit of work for rollback (the RollbackOnly property), rolls /// back the deferred sends and stops the route. The enclosing transaction rolls the database back without an /// exception, and the consumer does not acknowledge the message, so the broker delivers it again. /// IRouteDefinition RollbackAll(); /// /// Opens an OnException scope for . /// Configure redelivery/handling, then close with .EndOnException() or .End(). /// The child steps (added before closing) form the body to protect. /// Definitions.OnExceptionDefinition OnException() where TException : Exception; /// /// Opens an OnException scope for multiple exception types. /// Configure redelivery/handling, then close with .EndOnException() or .End(). /// The child steps (added before closing) form the body to protect. /// /// Thrown when is empty or contains a non-Exception type. Definitions.OnExceptionDefinition OnException(params Type[] exceptionTypes); // ── Route-level policy ── /// Sets whether this route participates in cluster-aware routing. Default: false. IRouteDefinition Cluster(bool value = true); /// Gets whether this route participates in cluster-aware routing. bool GetCluster(); /// Apache Camel parity: enable/disable per-node message history for this route, overriding /// the global RouteEngineOptions.EnableMessageHistory. IRouteDefinition MessageHistory(bool value = true); /// Gets the route-level message-history override (null = inherit the global setting). bool? GetMessageHistory(); /// Apache Camel parity: enable/disable OpenTelemetry tracing for this route, overriding /// the global RouteEngineOptions.EnableTelemetry. Pass false for a service route /// (a health check, a metric summary on a timer) whose single-span traces only crowd the collector. IRouteDefinition Tracing(bool value = true); /// Gets the route-level tracing override (null = inherit the global setting). bool? GetTracing(); /// Sets an explicit route policy, overriding any factory-resolved policy. IRouteDefinition RoutePolicy(IRoutePolicy policy); /// /// Attaches a route policy by its registry name: the instance is resolved /// from when the route compiles, and a missing /// registration fails Start() naming the route. A leading # is accepted. /// IRouteDefinition RoutePolicy(string policyName); /// Registry name set by , null when unset. string? GetRoutePolicyName(); /// Gets the explicitly set route policy, or null if not set. IRoutePolicy? GetRoutePolicy(); /// /// Assigns route configurations to the route by id (Apache Camel's routeConfigurationId): several ids /// separated by commas, each an exact id, a wildcard ending in * or a regular expression. A route with /// assigned configurations does not get the nameless ones — those are the default for routes without an assignment. /// An exact id no configuration of the context has fails Start(), naming the route. /// IRouteDefinition RouteConfigurationId(string ids); /// The ids set by , null when unset. string? GetRouteConfigurationId(); // ── Rich logging scope ── /// /// Opens a rich-log scope at . /// Shorthand for : add messages/headers/properties, then /// close with .EndLog() or .End(). /// Definitions.RichLogScopeDefinition Log(); /// /// Opens a rich-log scope at the given . /// Add messages/headers/properties, then close with .EndLog() or .End(). /// Definitions.RichLogScopeDefinition Log(LogLevel level); } Path: redb-route/redb.Route/Abstractions/IRouteLifecycleListener.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/Abstractions/IRouteLifecycleListener.cs ---- namespace redb.Route.Abstractions; /// /// Receives lifecycle events from when routes change state. /// All methods have default no-op implementations — override only what you need. /// public interface IRouteLifecycleListener { /// Fired after a route has been started and is processing exchanges. Task OnRouteStarted(string routeId, CancellationToken ct) => Task.CompletedTask; /// Fired after a route has been stopped. Task OnRouteStopped(string routeId, CancellationToken ct) => Task.CompletedTask; /// Fired when a route enters the Suspending state (drain starting). Task OnRouteSuspending(string routeId, CancellationToken ct) => Task.CompletedTask; /// Fired when a route fails to start or encounters a fatal error. Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) => Task.CompletedTask; /// Fired when an exchange times out (per-exchange processing timeout from Phase 5). Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) => Task.CompletedTask; /// /// Fired when a supervised connection of an endpoint changes: lost, a reconnect attempt failed, restored. The /// listener gets the event from the context's queue after the change, so it cannot hold up or break the reconnect; an /// exception it throws is logged. React with what the context already offers: alert, or stop, restart or fail the /// route (controlbus:route, ). Do not resend messages from here: a send that failed /// on a lost connection may have arrived. /// Task OnConnectionEvent(Core.ConnectionEvent connectionEvent, CancellationToken ct) => Task.CompletedTask; // ── Exchange-level events (NotifyBuilder / test-kit seam) ── /// Fired when an exchange enters a route's pipeline, before any step runs. Task OnExchangeReceived(string routeId, IExchange exchange, CancellationToken ct) => Task.CompletedTask; /// /// Fired after an exchange has been fully processed by a route and no exception propagated /// (an error caught and marked handled by error handling counts as completed). /// Task OnExchangeCompleted(string routeId, IExchange exchange, CancellationToken ct) => Task.CompletedTask; /// Fired when an exchange escapes a route's pipeline with an exception (error handling declined or rethrew it). Task OnExchangeFailed(string routeId, IExchange exchange, Exception exception, CancellationToken ct) => Task.CompletedTask; // ── Context-level events ── /// Fired before the context starts compiling and starting routes. Task OnContextStarting(IRouteContext context, CancellationToken ct) => Task.CompletedTask; /// Fired after the context has started all auto-start routes. Task OnContextStarted(IRouteContext context, CancellationToken ct) => Task.CompletedTask; /// Fired before the context begins stopping routes. Task OnContextStopping(IRouteContext context, CancellationToken ct) => Task.CompletedTask; /// Fired after the context has stopped all routes and cleaned up. Task OnContextStopped(IRouteContext context, CancellationToken ct) => Task.CompletedTask; } Path: redb-route/redb.Route/Abstractions/IRoutePolicy.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/Abstractions/IRoutePolicy.cs ---- #pragma warning disable CS0619 using redb.Route.Core; namespace redb.Route.Abstractions; /// /// Controls route lifecycle and receives per-exchange notifications. /// Analogous to Apache Camel's RoutePolicy. /// All methods have default no-op implementations — override only what you need. /// public interface IRoutePolicy { // ── Lifecycle ── /// Called once after the route is compiled but before consumers start. Task OnInit(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// Called before the route consumer is started. Throw to prevent startup. Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// Called after the route consumer has been stopped. Task OnStop(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// Called when the route is being removed from the context (final cleanup). Task OnRemove(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// Called when the route is being suspended (drain starting). Task OnSuspend(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// Called when the route is being resumed after suspension. Task OnResume(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; // ── Metadata ── /// /// Returns policy-specific metadata for observability (UI, API, diagnostics). /// Keys are policy-defined; values should be JSON-serializable primitives. /// IReadOnlyDictionary? GetMetadata() => null; // ── Per-exchange ── /// Called when an exchange starts processing in this route. Task OnExchangeBegin(IRouteContext context, IExchange exchange, CancellationToken ct) => Task.CompletedTask; /// Called when an exchange finishes processing (success or failure). Task OnExchangeDone(IRouteContext context, IExchange exchange, CancellationToken ct) => Task.CompletedTask; } Path: redb-route/redb.Route/Abstractions/IRoutePolicyFactory.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/Abstractions/IRoutePolicyFactory.cs ---- using redb.Route.Definitions; namespace redb.Route.Abstractions; /// /// Factory that creates instances for routes during compilation. /// Registered via . /// When multiple factories are registered, the first non-null result wins. /// public interface IRoutePolicyFactory { /// /// Creates a route policy for the given route, or returns null if this factory /// does not apply to the route. /// /// Route context. /// Route identifier. /// Route definition (access GetCluster(), etc.). /// A route policy, or null if this factory does not handle this route. IRoutePolicy? CreateRoutePolicy(IRouteContext context, string routeId, RouteDefinition definition); } Path: redb-route/redb.Route/Abstractions/IRouteResourceResolver.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/Abstractions/IRouteResourceResolver.cs ---- namespace redb.Route.Abstractions; /// /// Resolves a resource reference (a schema file, an XSLT stylesheet) to an absolute path. /// Registered as a context service (); hosts that unpack /// resources elsewhere (a Tsak package root) register their own instance with the package root /// as the search base. When none is registered, components fall back to /// , whose last probe is the current working /// directory — today's behaviour. /// public interface IRouteResourceResolver { /// Returns an absolute path to an existing file for the reference, or null when not found. string? Resolve(string reference); /// Where looked, for error messages. Defaults to the reference itself. string DescribeSearch(string reference) => reference; } Path: redb-route/redb.Route/Abstractions/IRouteScope.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/Abstractions/IRouteScope.cs ---- namespace redb.Route.Abstractions; /// /// Implemented by every scope-opener definition (Filter, Loop, TryCatch, Choice, Split, etc.). /// Provides a universal method as a shorter alias for the scope-specific /// EndXxx() methods (e.g. EndLoop(), EndFilter()). /// public interface IRouteScope { /// /// Closes this scope and returns the parent . /// Equivalent to calling the scope-specific EndXxx() method. /// /// /// Thrown if the scope was not attached to a parent route definition. /// IRouteDefinition End(); } Path: redb-route/redb.Route/Abstractions/ISagaDefinition.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/Abstractions/ISagaDefinition.cs ---- namespace redb.Route.Abstractions; /// /// Fluent builder for configuring saga steps with forward actions and compensation. /// public interface ISagaDefinition { /// Adds a synchronous saga step with compensation. /// Forward action to execute. /// Compensation action to run on rollback. /// This definition for chaining. ISagaDefinition Step(Action action, Action compensate); /// Adds an async saga step with compensation. /// Forward action to execute. /// Compensation action to run on rollback. /// This definition for chaining. ISagaDefinition Step( Func action, Func compensate); /// Adds a forward-only saga step (no compensation on rollback). /// Forward action to execute. /// This definition for chaining. ISagaDefinition Step(Action action); /// Adds an async forward-only saga step (no compensation on rollback). /// Forward action to execute. /// This definition for chaining. ISagaDefinition Step(Func action); /// /// Adds a saga step from processor instances — the seam declarative forms use (Route-XML /// <saga>: steps are #name registry references to s). /// /// Forward processor. /// Compensation processor to run on rollback; null for forward-only. /// This definition for chaining. ISagaDefinition Step(IProcessor action, IProcessor? compensate = null); /// Sets a callback invoked when all saga steps complete successfully. /// Callback to invoke on saga completion. /// This definition for chaining. ISagaDefinition OnCompletion(Action callback); /// Sets an async callback invoked when all saga steps complete successfully. /// Callback to invoke on saga completion. /// This definition for chaining. ISagaDefinition OnCompletion(Func callback); } Path: redb-route/redb.Route/Abstractions/IScatterGatherDefinition.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/Abstractions/IScatterGatherDefinition.cs ---- using System; using System.Collections.Generic; namespace redb.Route.Abstractions; /// /// Fluent builder for configuring a Scatter-Gather step. /// Allows setting recipients (static or dynamic), aggregation strategy, /// timeout, parallelism, and error handling options. /// public interface IScatterGatherDefinition { /// Sets the static list of recipient endpoint URIs. /// Endpoint URIs to scatter to. IScatterGatherDefinition Recipients(params string[] uris); /// Sets a dynamic recipient factory that resolves URIs from the exchange at runtime. /// Function returning target URIs from the current exchange. IScatterGatherDefinition Recipients(Func> factory); /// Sets the mandatory pair-wise aggregation strategy: (accumulated, current) → merged. /// Aggregation function applied pair-wise to collected responses. IScatterGatherDefinition AggregationStrategy(Func strategy); /// Sets the timeout for the entire scatter-gather operation. /// Maximum duration to wait for all responses. IScatterGatherDefinition Timeout(TimeSpan timeout); /// Enables or disables parallel processing of recipients (default: true). /// True for parallel, false for sequential. IScatterGatherDefinition ParallelProcessing(bool parallel = true); /// Sets the maximum degree of parallelism (0 = processor count). /// Maximum concurrent sends. IScatterGatherDefinition MaxDegreeOfParallelism(int maxDop); /// Enables or disables stop-on-exception behavior (default: false). /// True to propagate exceptions immediately, false to aggregate partial results. IScatterGatherDefinition StopOnException(bool stop = true); } Path: redb-route/redb.Route/Abstractions/ITransactedAction.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/Abstractions/ITransactedAction.cs ---- namespace redb.Route.Abstractions; /// /// Represents a transacted action that can be committed or rolled back. /// Used for deferred-commit transaction pattern across brokers. /// public interface ITransactedAction { /// Commits the transaction. /// Cancellation token. Task Commit(CancellationToken ct = default); /// Rolls back the transaction. /// Cancellation token. Task Rollback(CancellationToken ct = default); } Path: redb-route/redb.Route/Abstractions/InflightExchange.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/Abstractions/InflightExchange.cs ---- namespace redb.Route.Abstractions; /// /// Snapshot of an exchange currently being processed (in-flight). /// /// The exchange. /// The route it entered. /// When it entered the route (UTC). /// The thread it entered on. /// The endpoint the route consumes from, when known. /// /// Set while the engine holds the exchange on purpose (a redelivery delay of onException, Retry or the dead /// letter channel, a delay step): when that wait ends (UTC). Null while the exchange is being processed. /// /// When the last such wait ended (UTC); null when the exchange has not waited. public record InflightExchange( string ExchangeId, string RouteId, DateTime StartedAt, int ManagedThreadId, string? FromEndpoint, DateTime? WaitingUntil = null, DateTime? LastWaitEndedAt = null) { /// /// When the exchange's current stretch of work began: the end of its last planned wait, or its start. A monitor /// measures how long an exchange has been busy from here, so a redelivery after a delay is a fresh attempt. /// public DateTime BusySince => LastWaitEndedAt ?? StartedAt; } Path: redb-route/redb.Route/Abstractions/MalformedRequestException.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/Abstractions/MalformedRequestException.cs ---- namespace redb.Route.Abstractions; /// /// The incoming request could not be bound to what the receiver expects — an unparsable body, a /// parameter of the wrong shape. It is the CALLER's error, and transports that catch it answer /// with their "your request is wrong" form: the SOAP consumer writes a Sender/Client /// fault carrying this message instead of a Receiver fault with a generic text. /// /// /// The message deliberately describes the caller's own bytes (the missing member, the token that /// did not parse) — returning it is the BR-4 rule, not a violation of it: unlike an action /// failure, nothing in it is ours to hide. This type lives in the core so that a dispatcher /// (redb.Route.Controllers) can signal it without referencing any transport package, and a /// transport (redb.Route.Soap) can recognise it without referencing the dispatchers. /// public sealed class MalformedRequestException : Exception { /// Creates the exception with a caller-facing description of what did not bind. public MalformedRequestException(string message, Exception? innerException = null) : base(message, innerException) { } } Path: redb-route/redb.Route/Abstractions/RouteCheckpoint.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/Abstractions/RouteCheckpoint.cs ---- namespace redb.Route.Abstractions; /// /// The last .Replayable("name") save-point an exchange passed. Captured on each pass into /// [] (the last marker wins) and read by /// an error handler / the platform (Tsak) to replay the tail of the route from the frozen snapshot /// via . /// /// SECURITY: is a verbatim, UNREDACTED copy of the mid-flight exchange — /// body, headers and Properties may hold decrypted tokens, PII or secrets. Nothing is masked (URI /// redaction covers endpoint URIs, NOT payloads). Storing or exposing snapshots (e.g. via Tsak) is /// the platform's responsibility, not the route's. /// /// /// Route the checkpoint belongs to. /// Name of the .Replayable marker. /// Deep, isolated snapshot of the exchange at the marker (see ). public sealed record RouteCheckpoint(string RouteId, string MarkerName, IExchange Snapshot) { /// Well-known key holding the last passed . public const string PropertyKey = "route.checkpoint"; /// /// The direct: endpoint URI an exposed marker is addressable at /// (.To("direct:__replay:{routeId}:{markerName}") from another route). Single source of /// the format; internal (non-exposed) markers register no such endpoint. /// public static string EndpointUri(string routeId, string markerName) => $"direct:__replay:{routeId}:{markerName}"; } Path: redb-route/redb.Route/Abstractions/RoutePolicyDescriptor.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/Abstractions/RoutePolicyDescriptor.cs ---- namespace redb.Route.Abstractions; /// /// Effective cluster-policy resolution result for a single compiled route. /// Surfaces what the route requested versus what actually got applied at compile time — /// the answer to "the route is marked .Cluster(true), but is it actually clustered?". /// /// /// true if the route definition called .Cluster(true) (i.e., requested clustered execution). /// /// /// Short tag describing the policy that was actually attached: /// /// "AllNodes" — no policy attached; the route runs on every node. /// "ClusterLeader" — a clustered policy from a registered factory was attached. /// "Custom" — an explicit .RoutePolicy(...) was set on the definition. /// /// /// /// Fully-qualified type name of the that produced the policy, /// or null when no factory was used. /// /// /// Human-readable explanation, e.g. "No IRoutePolicyFactory registered — running on all nodes" /// or "Policy supplied by ClusteredRoutePolicyFactory". /// public sealed record RoutePolicyDescriptor( bool RequestedCluster, string EffectivePolicy, string? PolicyFactoryType, string Reason); Path: redb-route/redb.Route/Abstractions/RoutePolicySupport.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/Abstractions/RoutePolicySupport.cs ---- #pragma warning disable CS0619 using redb.Route.Core; namespace redb.Route.Abstractions; /// /// Convenience base class for implementations. /// Captures and in . /// Override only the callbacks you need. /// Analogous to Apache Camel's RoutePolicySupport. /// public abstract class RoutePolicySupport : IRoutePolicy { /// Route context (available after ). protected IRouteContext? Context { get; private set; } /// Route identifier (available after ). protected string? RouteId { get; private set; } /// public virtual Task OnInit(IRouteContext context, CompiledRoute route, CancellationToken ct) { Context = context; RouteId = route.RouteId; return Task.CompletedTask; } /// public virtual Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// public virtual Task OnStop(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// public virtual Task OnRemove(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// public virtual Task OnSuspend(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// public virtual Task OnResume(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; /// public virtual IReadOnlyDictionary? GetMetadata() => null; /// public virtual Task OnExchangeBegin(IRouteContext context, IExchange exchange, CancellationToken ct) => Task.CompletedTask; /// public virtual Task OnExchangeDone(IRouteContext context, IExchange exchange, CancellationToken ct) => Task.CompletedTask; } Path: redb-route/redb.Route/Abstractions/ScopeNesting.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/Abstractions/ScopeNesting.cs ---- namespace redb.Route.Abstractions; /// Severity of an verdict. public enum NestingPolicy { /// The nesting is fine. Allowed, /// Allowed but semantically risky — emit a build warning. Warn, /// Structurally ill-formed — fail the build. Forbid } /// Result of evaluating an against one enclosing scope. /// What to do about the nesting. /// Human-readable reason (required for Warn/Forbid). public readonly record struct NestingVerdict(NestingPolicy Policy, string? Message) { /// No constraint. public static NestingVerdict Allowed => new(NestingPolicy.Allowed, null); /// Allowed but risky — warn with the given message. public static NestingVerdict Warn(string message) => new(NestingPolicy.Warn, message); /// Ill-formed — fail the build with the given message. public static NestingVerdict Forbid(string message) => new(NestingPolicy.Forbid, message); } /// /// Marker: a branching scope whose body is a bounded sub-region — the exchange is /// conditionally executed (Filter), branched (Choice), or fanned out (Split/Multicast). A node with /// linear "tail" semantics (e.g. a replay checkpoint) generally cannot span such a boundary. /// public interface ICompositeScope { } /// /// Marker: a durable/transactional scope (e.g. Transaction). Nesting is structurally fine, /// but a re-invocation (replay) runs OUTSIDE the original transaction — usually a warn, not a forbid. /// public interface IDurableScope { } /// /// Declarative nesting constraint on a definition — reusable, generic validation instead of ad-hoc /// per-type checks in the validator. While walking the definition tree the validator calls /// for each enclosing scope (a node implementing ); /// a fails the build, a logs a /// warning. Any future definition that must constrain where it nests just implements this interface — /// the validator never changes. /// /// Scopes advertise their category with marker interfaces (, /// ), so a rule reacts to a category rather than to concrete types. /// /// public interface IScopeNestingRule { /// Evaluates this node's policy against one enclosing scope ancestor. /// An enclosing scope definition (nearest and outer scopes are both offered). NestingVerdict CheckAncestor(IProcessorDefinition ancestor); } /// /// Implemented by definitions whose logical children live outside /// — e.g. a Choice keeps its When/Otherwise /// branches in dedicated lists. A generic tree-walk (validation, analysis) recurses into /// so it reaches those children without any per-type knowledge. /// public interface IBranchingDefinition { /// Child definitions not present in . IEnumerable Branches { get; } } Path: redb-route/redb.Route/Aggregation/AggregationStrategies.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/Aggregation/AggregationStrategies.cs ---- using System.Globalization; using redb.Route.Abstractions; using redb.Route.Expressions; using redb.Route.Core; namespace redb.Route.Aggregation; /// /// Ready-made aggregation strategies (Apache Camel AggregationStrategies parity). Each is the /// existing Func<IExchange, IExchange, IExchange> the DSL already takes, so one strategy /// serves Aggregate, Multicast, ScatterGather, Split and Enrich. /// /// Argument order is (accumulated, incoming); for Enrich that is (original, resource). /// Every strategy tolerates a null accumulator (Split calls the strategy for the first fragment /// with null, Camel-style) and an accumulator that is still a plain first exchange (Multicast and /// Aggregate start with the first result as the accumulator). /// /// Named forms for the XML format: . /// public static class AggregationStrategies { /// /// The list builds. A private subtype, so the strategy appends only to a /// list it created itself: bodies are cloned by reference, and an incoming List<object?> /// body is shared by the caller and every branch clone — appending to it would mutate the caller's /// data and, when a branch kept that list as its body, add the list to itself. /// private sealed class GroupedList : List; /// Typed counterpart of for . private sealed class GroupedList : List; /// Collects the bodies into a List<object?> in the accumulated body. public static Func GroupedBody() => (old, @new) => { if (old is null) { @new.In.Body = new GroupedList { @new.In.Body }; return @new; } if (old.In.Body is GroupedList list) list.Add(@new.In.Body); else old.In.Body = new GroupedList { old.In.Body, @new.In.Body }; return old; }; /// Collects the bodies into a typed List<T>; a body that is not a fails with an explicit message. public static Func GroupedBody() => (old, @new) => { if (old is null) { @new.In.Body = new GroupedList { As(@new.In.Body) }; return @new; } if (old.In.Body is GroupedList list) list.Add(As(@new.In.Body)); else old.In.Body = new GroupedList { As(old.In.Body), As(@new.In.Body) }; return old; }; /// Collects the exchanges themselves into a List<IExchange> (for a Split whose fragments are processed later). public static Func GroupedExchange() => (old, @new) => { if (old is null) { @new.In.Body = new List { @new }; return @new; } if (old.In.Body is List list) list.Add(@new); else old.In.Body = new List { old, @new }; return old; }; /// The incoming exchange wins (for Enrich: the response becomes the current message). Camel's default when no strategy is given. public static Func UseLatest() => (_, @new) => @new; /// The accumulated (first / original) exchange wins; the incoming one is dropped. public static Func UseOriginal() => (old, @new) => old ?? @new; /// Bodies as strings joined with . public static Func Concat(string separator = "") { ArgumentNullException.ThrowIfNull(separator); return (old, @new) => { if (old is null) { @new.In.Body = Text(@new.In.Body); return @new; } old.In.Body = Text(old.In.Body) + separator + Text(@new.In.Body); return old; }; } /// Keeps the accumulated body; headers of the incoming exchange are merged in (the later one wins). public static Func MergeHeaders() => (old, @new) => { if (old is null) return @new; foreach (var (key, value) in @new.In.Headers) old.In.Headers[key] = value; return old; }; /// Puts the incoming body into header of the accumulated exchange — the most common Enrich. public static Func IntoHeader(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); return (old, @new) => { if (old is null) return @new; old.In.Headers[name] = @new.In.Body; return old; }; } /// Puts the incoming body into exchange property of the accumulated exchange. public static Func IntoProperty(string key) { ArgumentException.ThrowIfNullOrWhiteSpace(key); return (old, @new) => { if (old is null) return @new; old.Properties[key] = @new.In.Body; return old; }; } /// Numeric sum of a route-language expression ("body.amount") over the exchanges; the running total is the accumulated body (decimal). public static Func Sum(string expression) => Fold(new StringExpression(expression), (a, b) => a + b); /// Numeric sum of over the exchanges. public static Func Sum(IExpression expression) => Fold(expression, (a, b) => a + b); /// Maximum of a route-language expression over the exchanges. public static Func Max(string expression) => Fold(new StringExpression(expression), Math.Max); /// Maximum of over the exchanges. public static Func Max(IExpression expression) => Fold(expression, Math.Max); /// Minimum of a route-language expression over the exchanges. public static Func Min(string expression) => Fold(new StringExpression(expression), Math.Min); /// Minimum of over the exchanges. public static Func Min(IExpression expression) => Fold(expression, Math.Min); /// A caller-supplied strategy, wrapped so it reads like the others in a chain. public static Func Custom(Func strategy) => strategy ?? throw new ArgumentNullException(nameof(strategy)); /// /// Resolves a strategy from its XML / configuration name: groupedBody, groupedExchange, /// useLatest, useOriginal, mergeHeaders, concat:<separator>, /// intoHeader:<name>, intoProperty:<key>, sum:<expression>, /// max:<expression>, min:<expression>. Case-insensitive. /// public static Func ByName(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); var colon = name.IndexOf(':'); var head = (colon >= 0 ? name[..colon] : name).Trim(); var argument = colon >= 0 ? name[(colon + 1)..] : null; return head.ToLowerInvariant() switch { "groupedbody" => GroupedBody(), "groupedexchange" => GroupedExchange(), "uselatest" => UseLatest(), "useoriginal" => UseOriginal(), "mergeheaders" => MergeHeaders(), "concat" => Concat(argument ?? ""), "intoheader" => IntoHeader(Required(argument, name)), "intoproperty" => IntoProperty(Required(argument, name)), "sum" => Sum(Required(argument, name)), "max" => Max(Required(argument, name)), "min" => Min(Required(argument, name)), _ => throw new ArgumentException( $"Unknown aggregation strategy '{name}'. Known: groupedBody, groupedExchange, useLatest, useOriginal, mergeHeaders, " + "concat:, intoHeader:, intoProperty:, sum:, max:, min:.", nameof(name)), }; } private static string Required(string? argument, string name) => string.IsNullOrWhiteSpace(argument) ? throw new ArgumentException($"Aggregation strategy '{name}' needs an argument after the colon.", nameof(name)) : argument; /// Marks an accumulator whose body is the running value of a numeric fold. private const string FoldMarker = "__redb_agg:fold"; /// /// Numeric fold. The accumulated body holds the running value once aggregation has started — marked /// as such on the accumulator, because "the body is a number" is not proof: a plain first exchange /// (Multicast / Aggregate seed the accumulator with the first result) may carry a numeric body of its /// own, and its value must still be taken through the expression. /// private static Func Fold(IExpression expression, Func combine) { ArgumentNullException.ThrowIfNull(expression); return (old, @new) => { var incoming = Number(expression.Evaluate(@new), expression); if (old is null) { @new.In.Body = incoming; @new.Properties[FoldMarker] = true; return @new; } var running = old.Properties.ContainsKey(FoldMarker) && old.In.Body is { } body && IsNumber(body) ? RouteDecimal.From(body) : Number(expression.Evaluate(old), expression); old.In.Body = combine(running, incoming); old.Properties[FoldMarker] = true; return old; }; } private static decimal Number(object? value, IExpression expression) => value switch { null => throw new InvalidOperationException($"Aggregation: expression '{expression}' evaluated to null; a number is required."), _ when IsNumber(value) => RouteDecimal.From(value), string s when decimal.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out var parsed) => parsed, _ => throw new InvalidOperationException($"Aggregation: expression '{expression}' evaluated to '{value}' ({value.GetType().Name}); a number is required."), }; private static bool IsNumber(object value) => value is sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal; private static string Text(object? body) => body switch { null => string.Empty, string s => s, byte[] bytes => System.Text.Encoding.UTF8.GetString(bytes), IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), _ => body.ToString() ?? string.Empty, }; private static T As(object? body) => body switch { T typed => typed, null when default(T) is null => default!, _ => throw new InvalidOperationException($"GroupedBody<{typeof(T).Name}>: body is {body?.GetType().Name ?? "null"}, not {typeof(T).Name}."), }; } Path: redb-route/redb.Route/Batching/BatchCollector.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/Batching/BatchCollector.cs ---- namespace redb.Route.Batching; /// /// Receives up to messages into , waiting at most /// for the first of them, and returns how many it added. A transport that hands out one /// message at a time adds at most one; one that receives several in a call (SQS) adds up to . /// It never adds more than . /// public delegate ValueTask BatchReceive(List into, int max, TimeSpan wait, CancellationToken ct); /// A batch the collector gathered. /// The messages, in the order they were received. /// /// The consumer stopped while the batch was still being collected. Such a batch is not run: the consumer gives its /// messages back to the broker (). /// public readonly record struct CollectedBatch(IReadOnlyList Items, bool Interrupted); /// /// Collects a batch by the contract of : the first message is awaited for /// ; after it the batch grows until it holds /// , until no message came for , or until /// has passed since its first message. One implementation for every broker: the /// transport supplies only . /// public sealed class BatchCollector { private readonly BatchOptions _options; private readonly BatchReceive _receive; private readonly TimeProvider _time; /// Creates a collector over a transport's receive. public BatchCollector(BatchOptions options, BatchReceive receive, TimeProvider? time = null) { _options = options ?? throw new ArgumentNullException(nameof(options)); _receive = receive ?? throw new ArgumentNullException(nameof(receive)); _time = time ?? TimeProvider.System; } /// /// Collects one batch. Returns an empty batch when no message came within , /// so the caller's loop gets to look at its stop token; returns the messages received so far, marked /// , when fires mid-batch. /// public async Task> CollectAsync(CancellationToken stop) { var items = new List(Math.Min(_options.MaxMessages, 1024)); if (stop.IsCancellationRequested) return new(items, Interrupted: false); try { await _receive(items, _options.MaxMessages, _options.PollTimeout, stop).ConfigureAwait(false); } catch (OperationCanceledException) when (stop.IsCancellationRequested) { return new(items, Interrupted: items.Count > 0); } if (items.Count == 0) return new(items, Interrupted: false); var now = _time.GetUtcNow(); var hardDeadline = _options.Interval is { } interval ? now + interval : DateTimeOffset.MaxValue; var idleDeadline = now + _options.PollTimeout; while (items.Count < _options.MaxMessages) { if (stop.IsCancellationRequested) return new(items, Interrupted: true); now = _time.GetUtcNow(); var deadline = idleDeadline < hardDeadline ? idleDeadline : hardDeadline; var wait = deadline - now; if (wait <= TimeSpan.Zero) break; int added; try { added = await _receive(items, _options.MaxMessages - items.Count, wait, stop).ConfigureAwait(false); } catch (OperationCanceledException) when (stop.IsCancellationRequested) { return new(items, Interrupted: true); } if (added > 0) idleDeadline = _time.GetUtcNow() + _options.PollTimeout; } return new(items, Interrupted: false); } } Path: redb-route/redb.Route/Batching/BatchDispatcher.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/Batching/BatchDispatcher.cs ---- using System.Diagnostics; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Batching; /// What became of a dispatched batch. public enum BatchOutcome { /// The route succeeded; the batch was accepted. Accepted, /// The route failed; the batch was settled by the connector's failure rule. Rejected, /// The consumer was cancelled while the route ran; the batch was given back to the broker. Returned, } /// /// Runs a collected batch through the route, one implementation for every broker: it builds the batch exchange /// (InOnly, body a of , one message per broker message, even for a batch of /// one), runs the route once, and settles the batch once after the route has returned, through the connector's /// . /// public sealed class BatchDispatcher { private readonly IProcessor _processor; private readonly IBatchSettlement _settlement; private readonly Func _toMessage; private readonly IServiceScopeFactory? _scopeFactory; private readonly IReadOnlyCollection _sharedHeaders; /// Creates a dispatcher for one consumer. /// The route. /// How the connector settles a batch. /// /// One broker message into a message, built as the connector builds a single message's, so a destination gives one /// message shape in both modes. The exchange is the batch exchange, for header filtering. /// /// The endpoint's scope factory, for the batch exchange's DI scope. /// /// Transport headers set on the batch message when every message of the batch carries the same value, as Camel's /// CamelKafkaTopic on a batch (a topic, a queue, a partition). /// public BatchDispatcher(IProcessor processor, IBatchSettlement settlement, Func toMessage, IServiceScopeFactory? scopeFactory, IReadOnlyCollection sharedHeaders) { _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _settlement = settlement ?? throw new ArgumentNullException(nameof(settlement)); _toMessage = toMessage ?? throw new ArgumentNullException(nameof(toMessage)); _scopeFactory = scopeFactory; _sharedHeaders = sharedHeaders ?? throw new ArgumentNullException(nameof(sharedHeaders)); } /// /// Runs through the route and settles them. A failure of the route is not thrown: it marks /// , and the batch is settled by the connector's failure rule. Only a cancellation by /// is thrown, after the batch has been given back. /// public async Task DispatchAsync(IReadOnlyList items, TransportSpan span, CancellationToken processingCt) { ArgumentNullException.ThrowIfNull(items); if (items.Count == 0) throw new ArgumentException("A batch has at least one message.", nameof(items)); var exchange = CreateExchange(items); try { Exception? failure; try { var scope = await _settlement.BeforeRouteAsync(exchange, items, processingCt).ConfigureAwait(false); try { await _processor.Process(exchange, processingCt).ConfigureAwait(false); } finally { scope?.Dispose(); } failure = ExchangeFailureExtensions.FailureOf(exchange); } catch (OperationCanceledException) when (processingCt.IsCancellationRequested) { await _settlement.ReturnAsync(items, CancellationToken.None).ConfigureAwait(false); throw; } catch (Exception ex) { failure = ex; } if (failure is not null) { span.Activity.RecordFailure(failure); await _settlement.RejectAsync(exchange, items, failure, CancellationToken.None).ConfigureAwait(false); return BatchOutcome.Rejected; } await _settlement.AcceptAsync(exchange, items, CancellationToken.None).ConfigureAwait(false); return BatchOutcome.Accepted; } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// Builds the batch exchange: InOnly, body a list of one message per broker message. internal Exchange CreateExchange(IReadOnlyList items) { var batchMessage = new Message(); var exchange = Exchange.Create(batchMessage, _scopeFactory); exchange.Pattern = ExchangePattern.InOnly; var messages = new List(items.Count); foreach (var item in items) messages.Add(_toMessage(item, exchange)); batchMessage.Body = messages; foreach (var header in _sharedHeaders) { if (SharedValue(messages, header, out var value)) batchMessage.Headers[header] = value; } return exchange; } private static bool SharedValue(List messages, string header, out object? value) { value = null; for (var i = 0; i < messages.Count; i++) { if (!messages[i].Headers.TryGetValue(header, out var current)) return false; if (i == 0) value = current; else if (!Equals(value, current)) return false; } return true; } /// /// The receive span of a batch: a root of its own (its messages come from different senders and traces, none of /// them is its parent), linked to the context of every message that carries one, with the batch size as /// messaging.batch.message_count. /// public static TransportSpan StartSpan(IRouteContext? context, string name, string systemValue, string endpointUri, string? destination, IEnumerable senders, int count) { ArgumentNullException.ThrowIfNull(senders); var links = new List(); foreach (var sender in senders) { if (sender != default) links.Add(new ActivityLink(sender)); } var span = RouteTelemetryExtensions.StartConsumerSpan( context, name, ActivityKind.Consumer, "messaging.system", systemValue, endpointUri, carrier: null, static (_, _) => null, destination: destination, operation: "receive", links: links); span.Activity?.SetTag("messaging.batch.message_count", count); return span; } } Path: redb-route/redb.Route/Batching/BatchOptions.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/Batching/BatchOptions.cs ---- namespace redb.Route.Batching; /// /// How a batch consumer collects a batch, one contract for every broker, with Apache Camel's names: a batch is sent on /// once it holds messages, once no message came for (the idle /// timeout, restarted by every message), or once has passed since its first message (the hard /// limit), whichever comes first. /// public sealed record BatchOptions { /// Endpoint option that switches batch mode on; no other option does. public const string BatchingOption = "batching"; /// Endpoint option for . public const string MaxBatchMessagesOption = "maxBatchMessages"; /// Endpoint option for , in milliseconds. public const string PollTimeoutMsOption = "pollTimeoutMs"; /// Endpoint option for , in milliseconds. public const string BatchingIntervalMsOption = "batchingIntervalMs"; /// Largest number of messages in one batch. public int MaxMessages { get; } /// A batch with messages is sent on when no further message came for this long. public TimeSpan PollTimeout { get; } /// A batch is sent on when this much time has passed since its first message; null: no limit. public TimeSpan? Interval { get; } /// Creates batch options; values out of range throw. public BatchOptions(int maxMessages, TimeSpan pollTimeout, TimeSpan? interval = null) { if (Problem(maxMessages, pollTimeout, interval) is { } problem) throw new ArgumentOutOfRangeException(null, problem); MaxMessages = maxMessages; PollTimeout = pollTimeout; Interval = interval; } /// /// The batch options of an endpoint from its option values, or null when batch mode is off. A batch option /// set without batching=true means nothing, so it fails the start, naming the endpoint, as does a value out of /// range. /// /// The endpoint, for the message (sanitized by the caller). /// The batching option. /// The maxBatchMessages option, null when not set. /// The pollTimeoutMs option of the connector, its default applied. /// The batchingIntervalMs option, null when not set. /// The connector's default for maxBatchMessages. public static BatchOptions? Resolve(string endpoint, bool batching, int? maxBatchMessages, int pollTimeoutMs, int? batchingIntervalMs, int defaultMaxBatchMessages) { if (!batching) { var stray = maxBatchMessages is not null ? MaxBatchMessagesOption : batchingIntervalMs is not null ? BatchingIntervalMsOption : null; if (stray is not null) throw new InvalidOperationException( $"Endpoint '{endpoint}' sets {stray} without {BatchingOption}=true: a batch option without batch mode " + $"means nothing. Add {BatchingOption}=true, or remove {stray}."); return null; } var max = maxBatchMessages ?? defaultMaxBatchMessages; var poll = TimeSpan.FromMilliseconds(pollTimeoutMs); TimeSpan? interval = batchingIntervalMs is { } ms ? TimeSpan.FromMilliseconds(ms) : null; if (Problem(max, poll, interval) is { } problem) throw new InvalidOperationException($"Endpoint '{endpoint}': {problem}"); return new BatchOptions(max, poll, interval); } private static string? Problem(int maxMessages, TimeSpan pollTimeout, TimeSpan? interval) => maxMessages < 1 ? $"{MaxBatchMessagesOption} must be at least 1, not {maxMessages}." : pollTimeout <= TimeSpan.Zero ? $"{PollTimeoutMsOption} must be positive, not {pollTimeout.TotalMilliseconds}." : interval is { } i && i <= TimeSpan.Zero ? $"{BatchingIntervalMsOption} must be positive, not {i.TotalMilliseconds}." : null; } Path: redb-route/redb.Route/Batching/IBatchSettlement.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/Batching/IBatchSettlement.cs ---- using redb.Route.Abstractions; namespace redb.Route.Batching; /// /// How a broker settles the messages of a batch: the one part of batch mode that differs by broker. Kafka settles by /// position (the last offset of each partition covers the earlier ones); the other brokers settle each message (a /// delivery tag, a receipt, a lock token). calls exactly one of /// , or per batch, once the route has /// returned. /// public interface IBatchSettlement { /// /// Called after the batch exchange is built and before the route runs, with the scope the route runs in: a /// transport that offers its settlement to the route (Kafka's offsets to a transaction) does it here, a transport that /// settles on receipt (an automatic acknowledgement) settles here. The returned object, when there is one, is /// disposed once the route has returned, before the outcome is settled. /// ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct); /// The route succeeded: settle every message as consumed. ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct); /// /// The route failed: settle the messages by the connector's rule for a failed single message, applied to every /// message of the batch (Kafka: breakOnFirstError; RabbitMQ: retries, then reject without requeue). /// ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct); /// /// The batch did not run to an outcome: the consumer stopped while collecting it, or cancelled it while it ran. /// Give every message back to the broker unsettled, so it is delivered again. /// ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct); } Path: redb-route/redb.Route/Components/Bean/BeanComponent.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/Components/Bean/BeanComponent.cs ---- using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components.Bean; /// /// The bean: component: a reference to user code as an /// ordinary endpoint, so declarative routes never carry class=/ref= attributes. /// Two URI forms: /// /// bean:#orderEnricher?method=Enrich — object from the context registry /// bean:Acme.Orders.EnrichProcessor, Acme.Orders?timeoutMs=5 — instance created per endpoint /// /// The instance lives as long as the endpoint (endpoints are cached by normalized URI, so equal /// URIs share one instance and different parameter sets get their own). Unrecognised query /// parameters bind to the instance's public settable properties through the same converter the /// endpoint options use; [Sensitive]-marked properties join the URI redaction set. The /// target method is picked once and compiled into a delegate — reflection never runs per message. /// [EndpointRole(EndpointRole.Producer, Hint = "Use bean: as a To() destination.")] public sealed class BeanComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.Ordinal); /// public override string Scheme => "bean"; /// /// The URI of : bean:reference?method=spec. The /// method travels raw, like a hand-written URI, except '%' and '&', which the URI parse would unescape or split. /// internal static string UriFor(string reference, string? method) { ArgumentException.ThrowIfNullOrWhiteSpace(reference); if (reference.Contains('?')) throw new ArgumentException( $"bean reference '{reference}' contains '?'; pass the method as the second argument, not in the reference.", nameof(reference)); return string.IsNullOrWhiteSpace(method) ? "bean:" + reference : "bean:" + reference + "?method=" + method.Replace("%", "%25").Replace("&", "%26"); } /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); return _endpoints.GetOrAdd(uri.NormalizedKey, _ => BuildEndpoint(uri)); } private BeanEndpoint BuildEndpoint(EndpointUri uri) { var reference = uri.Path?.Trim(); if (string.IsNullOrEmpty(reference)) throw new ArgumentException( "bean: needs a target — 'bean:#registryName' or 'bean:Namespace.Type, AssemblyName'."); var options = new BeanEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); var instance = reference.StartsWith('#') ? ResolveFromRegistry(reference) : CreateFromTypeName(reference, options.UnmappedParameters); var invoker = BeanInvoker.For(instance.GetType(), options.Method, reference); return new BeanEndpoint(uri, this, options, instance, invoker); } private object ResolveFromRegistry(string reference) { var context = Context ?? throw new InvalidOperationException( "bean: component has no context; register it via AddComponent."); return context.GetFromRegistry(reference) ?? throw new InvalidOperationException( $"bean: object '{reference}' is not in the context registry. " + "Register it with AddToRegistry (or a declaration) before Start()."); } private object CreateFromTypeName(string typeName, IReadOnlyDictionary properties) { if (typeName.Contains("Version=", StringComparison.OrdinalIgnoreCase) || typeName.Contains("PublicKeyToken=", StringComparison.OrdinalIgnoreCase) || typeName.Contains("Culture=", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException( $"bean: type name '{typeName}' pins an assembly version/key. Use 'Namespace.Type, AssemblyName' " + "only — a pinned version silently breaks the route on every assembly bump."); var resolver = Context?.GetService() ?? DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(typeName) ?? throw new InvalidOperationException( $"bean: type '{typeName}' was not found in the loaded assemblies. " + "Check the 'Namespace.Type, AssemblyName' spelling and that the assembly is loaded."); if (!(type.IsPublic || type.IsNestedPublic)) throw new InvalidOperationException( $"bean: type '{type.FullName}' was found but is not public. Module discovery and bean: " + "work through exported types only — make the class public."); var provider = Context?.GetServiceProvider() ?? EmptyServiceProvider.Instance; var instance = ActivatorUtilities.CreateInstance(CollectibleTypeServiceProvider.For(provider), type); BindProperties(instance, type, properties); return instance; } private static void BindProperties(object instance, Type type, IReadOnlyDictionary properties) { if (properties.Count == 0) return; EndpointOptions.RegisterSensitiveKeysFor(type); var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var (key, rawValue) in properties) { var prop = Array.Find(props, p => p.Name.Equals(key, StringComparison.OrdinalIgnoreCase)); if (prop is null || !prop.CanWrite) throw new ArgumentException( $"bean: type '{type.FullName}' has no writable public property '{key}'. " + $"Writable properties: {string.Join(", ", props.Where(p => p.CanWrite).Select(p => p.Name))}."); var converted = OptionValueConverter.Convert(rawValue, prop.PropertyType) ?? throw new ArgumentException( $"bean: value '{rawValue}' is not convertible to {prop.PropertyType.Name} " + $"for property '{type.FullName}.{prop.Name}'."); prop.SetValue(instance, converted); } } private sealed class EmptyServiceProvider : IServiceProvider { public static readonly EmptyServiceProvider Instance = new(); public object? GetService(Type serviceType) => null; } } /// Options for bean: endpoints. Everything unmapped binds to the bean instance. [LenientProperties] public sealed class BeanEndpointOptions : EndpointOptions { /// /// Target method name. Optional when the type has exactly one suitable public method; with /// several, the error lists the candidates. /// public string? Method { get; set; } /// public override void Validate() { } } /// Endpoint holding the bean instance and its compiled invoker. public sealed class BeanEndpoint : EndpointBase { internal object Instance { get; } internal BeanInvoker Invoker { get; } internal BeanEndpoint(EndpointUri uri, BeanComponent component, BeanEndpointOptions options, object instance, BeanInvoker invoker) : base(uri, component, options) { Instance = instance; Invoker = invoker; } /// public override IProducer CreateProducer() => new BeanProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException("bean: endpoints are producers only — use them as To() destinations."); } /// Producer invoking the bean's compiled delegate per exchange. public sealed class BeanProducer : IProducer { private readonly BeanEndpoint _endpoint; /// Creates the producer for a bean endpoint. public BeanProducer(BeanEndpoint endpoint) => _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var invoker = _endpoint.Invoker; var raw = invoker.Invoke(_endpoint.Instance, exchange, ct); if (raw is Task task) { await task.ConfigureAwait(false); if (invoker.TaskResult is { } getResult && getResult(task) is { } asyncResult) exchange.In.Body = asyncResult; return; } // Camel bean: semantics — a non-null return value (other than Task) becomes the body. if (invoker.ReturnsValue && raw is not null) exchange.In.Body = raw; } } /// /// The bean's target method, selected once and compiled into a delegate at endpoint creation: /// reflection never runs on the message path. /// public sealed partial class BeanInvoker { /// Raw invocation: returns the method's result (a Task for async methods, null for void). internal Func Invoke { get; } /// True when the method returns a plain (non-Task) value that should become the body. internal bool ReturnsValue { get; } /// For Task<T> methods: reads the completed task's result. Null otherwise. internal Func? TaskResult { get; } private BeanInvoker(Func invoke, bool returnsValue, Func? taskResult) { Invoke = invoke; ReturnsValue = returnsValue; TaskResult = taskResult; } /// /// Selects the target method — by when given, otherwise the /// single suitable public method — and compiles the invoker. A suitable method takes /// (IExchange) or (IExchange, CancellationToken); the two-parameter form wins /// when both names match. A method=name(arg, …) specification switches to Camel-style /// parameter binding: each argument is a route-language expression and the /// method's parameters carry ordinary types. /// internal static BeanInvoker For(Type type, string? methodName, string reference) { if (methodName is not null && methodName.Contains('(')) return ForBound(type, methodName, reference); var suitable = type .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(IsSuitable) .OrderByDescending(m => m.GetParameters().Length) // (IExchange, ct) preferred .ToList(); if (suitable.Count == 0) throw new InvalidOperationException( $"bean: '{reference}' ({type.FullName}) has no suitable public method. Expected a public " + "instance method taking (IExchange) or (IExchange, CancellationToken)."); MethodInfo method; if (methodName is not null) { method = suitable.FirstOrDefault(m => m.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase)) ?? throw new InvalidOperationException( $"bean: '{reference}' has no suitable method '{methodName}'. " + $"Suitable methods: {Describe(suitable)}."); } else { var distinctNames = suitable.Select(m => m.Name).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); if (distinctNames.Count > 1) throw new InvalidOperationException( $"bean: '{reference}' has several suitable methods — name one with ?method=. " + $"Candidates: {Describe(suitable)}."); method = suitable[0]; } return Compile(type, method); } private static bool IsSuitable(MethodInfo m) { if (m.IsSpecialName || m.DeclaringType == typeof(object)) return false; var p = m.GetParameters(); return p.Length switch { 1 => p[0].ParameterType == typeof(IExchange), 2 => p[0].ParameterType == typeof(IExchange) && p[1].ParameterType == typeof(CancellationToken), _ => false, }; } private static string Describe(IEnumerable methods) => string.Join(", ", methods.Select(m => $"{m.Name}({string.Join(", ", m.GetParameters().Select(p => p.ParameterType.Name))})")); private static BeanInvoker Compile(Type type, MethodInfo method) { var instance = Expression.Parameter(typeof(object), "instance"); var exchange = Expression.Parameter(typeof(IExchange), "exchange"); var ct = Expression.Parameter(typeof(CancellationToken), "ct"); var args = method.GetParameters().Length == 2 ? new Expression[] { exchange, ct } : [exchange]; Expression call = Expression.Call(Expression.Convert(instance, type), method, args); Expression body = method.ReturnType == typeof(void) ? Expression.Block(call, Expression.Constant(null, typeof(object))) : Expression.Convert(call, typeof(object)); var invoke = Expression .Lambda>(body, instance, exchange, ct) .Compile(); var (returnsValue, taskResult, toTask) = ClassifyReturn(method.ReturnType); return new BeanInvoker(AwaitableAsTask(invoke, toTask), returnsValue, taskResult); } } // ── Camel-style parameter binding ──────────────────────────────────────────── public sealed partial class BeanInvoker { // (partial: the base selection/compilation half lives above in this file) /// /// Builds the invoker for a method=name(arg, …) specification. Each argument is a /// route-language expression compiled at endpoint creation (a malformed one fails the build); /// the overload is picked by the number of bindable parameters. A parameter of type /// is the exchange itself, one of type its In /// message: both are supplied by the binding, like a Camel bean's Exchange/Message, /// and neither counts among the arguments. A is filled in /// wherever it stands, counted the same way. So method=Require('incident.view') binds /// Require(IExchange exchange, string permission). Argument values convert to the /// parameter types through the shared option converter; a value already of the parameter /// type passes as-is. Boundary: an argument must not contain a bare & — the URI /// query splits on it; write the word form AND. /// private static BeanInvoker ForBound(Type type, string methodSpec, string reference) { var (name, argTexts) = ParseMethodSpec(methodSpec, reference); var expressions = argTexts.Select(t => new redb.Route.Expressions.StringExpression(t)).ToArray(); var bound = BindMethod(type, name, argTexts.Count, reference); object? Invoke(object instance, IExchange exchange, CancellationToken ct) { var values = new object?[expressions.Length]; for (var i = 0; i < expressions.Length; i++) values[i] = expressions[i].Evaluate(exchange); return bound.Call(instance, values, exchange, ct); } var (returnsValue, taskResult, toTask) = ClassifyReturn(bound.Method.ReturnType); return new BeanInvoker(AwaitableAsTask(Invoke, toTask), returnsValue, taskResult); } /// /// A method specification in the bean: URI spelling: Name (no arguments) or Name(arg, ...), /// each argument a route-language expression. Shared by the URI form and Method(). /// internal static (string Name, IReadOnlyList Arguments) ParseMethodSpec(string methodSpec, string reference) { var open = methodSpec.IndexOf('('); if (open < 0) return (methodSpec.Trim(), []); var name = methodSpec[..open].Trim(); var closing = methodSpec.LastIndexOf(')'); if (name.Length == 0 || closing < open) throw new ArgumentException( $"bean: malformed method specification '{methodSpec}' for '{reference}'. Expected name(arg, ...)."); return (name, SplitArguments(methodSpec[(open + 1)..closing])); } /// /// A bean method bound to argument values: the method picked by name and bindable count, and the call that /// converts each value to its parameter type and supplies the ambient parameters. The one selection and conversion /// path behind the method=name(args) URI form, the bean: expression function and Method(). /// internal sealed record BoundMethod(MethodInfo Method, Func Call); /// /// Binds of for values that /// the caller evaluates itself (the third entry point, beside the URI's two). Rules as for /// method=name(args): by name, case-insensitive, and bindable count; an , /// or parameter is supplied by the binding. /// internal static BoundMethod ForValues(Type type, string methodName, int argumentCount, string reference) => BindMethod(type, methodName, argumentCount, reference); private static BoundMethod BindMethod(Type type, string name, int argumentCount, string reference) { var candidates = type .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => !m.IsSpecialName && m.DeclaringType != typeof(object) && m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) .Where(m => BindableCount(m.GetParameters()) == argumentCount) .OrderByDescending(m => m.GetParameters().Length) // the ambient-taking overload wins .ToList(); if (candidates.Count == 0) throw new InvalidOperationException( $"bean: '{reference}' has no public method '{name}' taking {argumentCount} argument(s) " + "(IExchange, IMessage and CancellationToken parameters are supplied by the binding and do not count)."); if (candidates.Count > 1 && candidates[0].GetParameters().Length == candidates[1].GetParameters().Length) throw new InvalidOperationException( $"bean: '{reference}' has several '{name}' overloads with {argumentCount} argument(s) — " + $"parameter binding picks by count only. Candidates: {Describe(candidates)}."); var method = candidates[0]; var converters = new Func[argumentCount]; var argIndex = 0; foreach (var parameter in method.GetParameters()) { if (IsAmbient(parameter.ParameterType)) continue; var target = parameter.ParameterType; var where = $"parameter '{parameter.Name}' of {type.Name}.{method.Name}"; converters[argIndex++] = value => ConvertArgument(value, target, where); } var call = CompileBoundCall(type, method); return new BoundMethod(method, (instance, values, exchange, ct) => { var args = new object?[values.Length]; for (var i = 0; i < values.Length; i++) args[i] = converters[i](values[i]); return call(instance, args, exchange, ct); }); } /// Whether is an awaitable the invoker awaits (Task, ValueTask and their generic forms). internal static bool IsAwaitable(Type returnType) => returnType == typeof(Task) || returnType == typeof(ValueTask) || (returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(Task<>) || returnType.GetGenericTypeDefinition() == typeof(ValueTask<>))); /// A parameter the binding supplies itself: the exchange, its In message, or the token. private static bool IsAmbient(Type parameterType) => parameterType == typeof(IExchange) || parameterType == typeof(IMessage) || parameterType == typeof(CancellationToken); /// Counts the parameters an argument list binds, that is, every parameter but the ambient ones. private static int BindableCount(ParameterInfo[] parameters) { var count = 0; foreach (var parameter in parameters) if (!IsAmbient(parameter.ParameterType)) count++; return count; } /// Splits top-level commas, respecting quotes (with backslash escapes) and nesting. private static List SplitArguments(string text) { var args = new List(); if (string.IsNullOrWhiteSpace(text)) return args; var depth = 0; char? quote = null; var start = 0; for (var i = 0; i < text.Length; i++) { var c = text[i]; if (quote is { } q) { if (c == '\\') i++; else if (c == q) quote = null; continue; } switch (c) { case '\'' or '"': quote = c; break; case '(' or '[' or '{': depth++; break; case ')' or ']' or '}': depth--; break; case ',' when depth == 0: args.Add(text[start..i].Trim()); start = i + 1; break; } } args.Add(text[start..].Trim()); return args; } private static object? ConvertArgument(object? value, Type target, string where) { if (value is null) { if (!target.IsValueType || Nullable.GetUnderlyingType(target) is not null) return null; throw new InvalidOperationException( $"bean: the argument for {where} evaluated to null, but {target.Name} is a value type."); } if (target.IsInstanceOfType(value)) return value; if (value is string text) return OptionValueConverter.Convert(text, target) ?? throw new InvalidOperationException( $"bean: the argument value '{text}' is not convertible to {target.Name} for {where}."); try { return RouteDecimal.ChangeType(value, Nullable.GetUnderlyingType(target) ?? target, System.Globalization.CultureInfo.InvariantCulture); } catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException) { throw new InvalidOperationException( $"bean: the argument value '{value}' ({value.GetType().Name}) is not convertible to " + $"{target.Name} for {where}.", ex); } } private static Func CompileBoundCall( Type type, MethodInfo method) { var instance = Expression.Parameter(typeof(object), "instance"); var args = Expression.Parameter(typeof(object?[]), "args"); var exchange = Expression.Parameter(typeof(IExchange), "exchange"); var ct = Expression.Parameter(typeof(CancellationToken), "ct"); var parameters = method.GetParameters(); var callArgs = new List(parameters.Length); var argIndex = 0; foreach (var parameter in parameters) { var target = parameter.ParameterType; if (target == typeof(IExchange)) callArgs.Add(exchange); else if (target == typeof(IMessage)) callArgs.Add(Expression.Convert(Expression.Property(exchange, nameof(IExchange.In)), target)); else if (target == typeof(CancellationToken)) callArgs.Add(ct); else callArgs.Add(Expression.Convert( Expression.ArrayIndex(args, Expression.Constant(argIndex++)), target)); } Expression call = Expression.Call(Expression.Convert(instance, type), method, callArgs); Expression body = method.ReturnType == typeof(void) ? Expression.Block(call, Expression.Constant(null, typeof(object))) : Expression.Convert(call, typeof(object)); return Expression .Lambda>(body, instance, args, exchange, ct) .Compile(); } /// Shared return-shape classification for both invoker forms. // A ValueTask or ValueTask is awaited like Task and Task: the method's return value is turned into a Task // once, where the invoker is built, so the producer awaits one shape. It used to be taken for a plain value — the // struct became the body and an async method was not awaited. internal static (bool ReturnsValue, Func? TaskResult, Func? ToTask) ClassifyReturn(Type returnType) { if (returnType == typeof(void) || returnType == typeof(Task)) return (false, null, null); if (returnType == typeof(ValueTask)) return (false, null, static raw => ((ValueTask)raw!).AsTask()); if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) { var raw = Expression.Parameter(typeof(object), "raw"); var asTask = Expression.Call(Expression.Convert(raw, returnType), returnType.GetMethod(nameof(ValueTask.AsTask))!); var toTask = Expression .Lambda>(Expression.Convert(asTask, typeof(object)), raw) .Compile(); var (_, getter, _) = ClassifyReturn(typeof(Task<>).MakeGenericType(returnType.GetGenericArguments())); return (false, getter, toTask); } if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>)) { var task = Expression.Parameter(typeof(Task), "task"); var result = Expression.Property(Expression.Convert(task, returnType), "Result"); var getter = Expression .Lambda>(Expression.Convert(result, typeof(object)), task) .Compile(); return (false, getter, null); } return (true, null, null); } private static Func AwaitableAsTask( Func invoke, Func? toTask) => toTask is null ? invoke : (instance, exchange, ct) => toTask(invoke(instance, exchange, ct)); } /// /// Default : Type.GetType first (the default load context), /// then every loaded assembly — which includes collectible load contexts, so a type inside an /// already-loaded plugin is found even without a host-specific resolver. /// public sealed class DefaultBeanTypeResolver : IBeanTypeResolver { /// The shared instance used when no resolver is registered on the context. public static DefaultBeanTypeResolver Instance { get; } = new(); /// public Type? Resolve(string typeName) { ArgumentException.ThrowIfNullOrWhiteSpace(typeName); var direct = Type.GetType(typeName, throwOnError: false); if (direct is not null) return direct; var comma = typeName.IndexOf(','); var fullName = (comma >= 0 ? typeName[..comma] : typeName).Trim(); var assemblyName = comma >= 0 ? typeName[(comma + 1)..].Trim() : null; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assemblyName is not null && !string.Equals(assembly.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase)) continue; var type = assembly.GetType(fullName, throwOnError: false); if (type is not null) return type; } return null; } } Path: redb-route/redb.Route/Components/ComponentConstruction.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/Components/ComponentConstruction.cs ---- using System.Reflection; using redb.Route.Abstractions; namespace redb.Route.Components; /// /// The one rule by which a component type found by a scan is created, for the engine's /// and the catalog command of the XML code generator /// alike: a concrete with a public constructor callable without arguments (none at all, or only /// optional ones, as HttpComponent(string scheme = "http")), called with the parameters' defaults. A component /// left out is reported with its reason, one call each, so a scheme never drops out in silence (mcp did from the /// catalog, until its constructor without arguments; http did from the engine's scan). /// internal static class ComponentConstruction { /// The reason given for a component without a constructor callable without arguments. internal const string NoArgumentFreeConstructor = "no constructor callable without arguments"; /// /// The components among ; gets each component type left out and /// the reason. Abstract types, interfaces and types that are not components are passed over without a report. /// public static IEnumerable Create(IEnumerable types, Action skipped) { foreach (var type in types.Where(t => !t.IsAbstract && !t.IsInterface && typeof(IComponent).IsAssignableFrom(t))) { ConstructorInfo? constructor; try { constructor = type.GetConstructors().FirstOrDefault(c => c.GetParameters().All(p => p.IsOptional)); } catch (Exception ex) when (ex is TypeLoadException or FileNotFoundException or FileLoadException) { // A parameter type of a constructor lives in an assembly this process does not carry. skipped(type, $"constructor types did not load ({ex.Message})"); continue; } if (constructor is null) { skipped(type, NoArgumentFreeConstructor); continue; } IComponent component; try { component = (IComponent)constructor.Invoke([.. constructor.GetParameters().Select(p => p.DefaultValue)]); } catch (Exception ex) when (ex is TargetInvocationException or MissingMethodException) { skipped(type, $"constructor failed ({ex.InnerException?.Message ?? ex.Message})"); continue; } yield return component; } } } Path: redb-route/redb.Route/Components/DirectComponent.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/Components/DirectComponent.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components; /// /// In-memory synchronous component. Scheme: "direct". /// When a producer sends an exchange to a direct endpoint, the consumer's processor /// is invoked synchronously (in-process). No threading, no queuing — direct call. /// Ideal for testing and for connecting route segments within the same process. /// public class DirectComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); /// public override string Scheme => "direct"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); return _endpoints.GetOrAdd(uri.BaseKey, _ => new DirectEndpoint(uri, this)); } } /// /// Options for direct endpoints. Currently no parameters needed. /// public class DirectEndpointOptions : EndpointOptions { /// public override void Validate() { } } /// /// Direct endpoint. Holds a reference to the consumer processor so producers can invoke it. /// public class DirectEndpoint : EndpointBase { private volatile IProcessor? _consumerProcessor; /// Creates a new direct endpoint. public DirectEndpoint(EndpointUri uri, DirectComponent component) : base(uri, component, new DirectEndpointOptions()) { } /// Gets the consumer processor (null if no consumer registered). internal IProcessor? ConsumerProcessor => _consumerProcessor; /// public override IProducer CreateProducer() => new DirectProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new DirectConsumer(this, processor); } /// Registers the consumer processor (called by DirectConsumer.Start). internal void RegisterConsumerProcessor(IProcessor processor) { _consumerProcessor = processor; } /// Unregisters the consumer processor (called by DirectConsumer.Stop). internal void UnregisterConsumerProcessor() { _consumerProcessor = null; } } /// /// Direct producer. Sends exchanges by invoking the endpoint's consumer processor synchronously. /// public class DirectProducer : IProducer { private readonly DirectEndpoint _endpoint; private ILogger? _logger; /// Creates a direct producer. public DirectProducer(DirectEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var processor = _endpoint.ConsumerProcessor ?? throw new InvalidOperationException( $"No consumer registered for direct endpoint '{_endpoint.Uri.NormalizedKey}'. " + "Ensure the consumer route is started before sending."); // direct: runs the target route on THIS exchange, and the target's first step stamps // exchange.RouteId; nothing restores it, so after the call the caller would carry the callee's id // and its own route span and step metrics would be attributed to the callee. Save ours and put it // back once the target returns — on failure too, before the caller's own error handler runs. var callerRouteId = exchange.RouteId; try { await processor.Process(exchange, ct).ConfigureAwait(false); } finally { exchange.RouteId = callerRouteId; } } /// public Task Start(CancellationToken ct = default) { _logger?.LogInformation("Direct producer started: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _logger?.LogInformation("Direct producer stopped: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } } /// /// Direct consumer. Registers the processor on the endpoint so producers can call it. /// Does not poll or subscribe — just holds a reference. /// public class DirectConsumer : IConsumer { private readonly DirectEndpoint _endpoint; public IEndpoint Endpoint => _endpoint; private readonly IProcessor _processor; private ILogger? _logger; /// Creates a direct consumer. public DirectConsumer(DirectEndpoint endpoint, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public Task Start(CancellationToken ct = default) { _endpoint.RegisterConsumerProcessor(_processor); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("Direct consumer started: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _endpoint.UnregisterConsumerProcessor(); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("Direct consumer stopped: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } } Path: redb-route/redb.Route/Components/DirectVmComponent.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/Components/DirectVmComponent.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components; /// /// Cross-context synchronous component. Scheme: "direct-vm". /// Like Direct but the processor registry is shared across all RouteContexts /// via (DI singleton). /// A consumer in context A registers its processor; a producer in context B /// can invoke it directly — synchronous, zero-copy, cross-context call. /// public class DirectVmComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); /// public override string Scheme => "direct-vm"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new DirectVmEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); // Keyed with the parameters: a producer's headerFilterStrategy must not be lost to, or leak into, a consumer of // the same name in this context. The call itself finds its target by name (Uri.BaseKey) in the shared registry. return _endpoints.GetOrAdd(uri.NormalizedKey, _ => new DirectVmEndpoint(uri, this, options)); } /// Resolves the shared registry from DI. Returns null if not registered. internal SharedVmRegistry? GetRegistry() { return Context?.GetServiceProvider()?.GetService(); } } /// /// Options for direct-vm endpoints. /// public class DirectVmEndpointOptions : EndpointOptions { /// /// Producer only, as in Apache Camel 3: a registry reference (#name) to an /// for the call, in both directions. With it the called context works on a /// copy of the exchange that carries the headers the strategy lets out; when the call returns, the caller keeps /// its own headers and takes the reply's body and the reply headers the strategy lets in. Without it (the /// default) the called context works on the caller's own exchange and every header crosses both ways. /// [EndpointRole(EndpointRole.Producer)] [RegistryReference(typeof(IHeaderFilterStrategy))] public string? HeaderFilterStrategy { get; set; } /// public override void Validate() { } } /// /// Direct-VM endpoint. Unlike DirectEndpoint, does not hold a local processor reference — /// it delegates to for cross-context lookup. /// public class DirectVmEndpoint : EndpointBase { internal new DirectVmComponent Component => (DirectVmComponent)base.Component; /// The logical name used as key in the shared registry (the URI host). internal string Name => Uri.BaseKey; /// Creates a new direct-vm endpoint. public DirectVmEndpoint(EndpointUri uri, DirectVmComponent component, DirectVmEndpointOptions options) : base(uri, component, options) { _headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy); } private readonly EndpointHeaderFilter _headerFilter; /// /// The strategy headerFilterStrategy=#name names, or null: direct-vm has no default strategy. A name /// the registry does not hold fails when the producer is built. /// internal IHeaderFilterStrategy? HeaderFilterStrategy => _headerFilter.Configured; /// public override IProducer CreateProducer() => new DirectVmProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); var written = EndpointOptions.WrittenForOtherRole(Options.GetType(), Uri, EndpointRole.Consumer); if (written.Count > 0) throw new InvalidOperationException( $"direct-vm consumer '{EndpointUri.Sanitize(Uri.NormalizedKey)}' sets {string.Join(", ", written)}, " + "which applies to the calling side (.To), as in Apache Camel; a consumer has nothing to filter. " + "Move it to the producer URI."); return new DirectVmConsumer(this, processor); } } /// /// Direct-VM producer. Looks up the processor from the shared registry and invokes it synchronously. /// public class DirectVmProducer : IProducer { private readonly DirectVmEndpoint _endpoint; private readonly IHeaderFilterStrategy? _headerFilter; private ILogger? _logger; /// Creates a direct-vm producer. public DirectVmProducer(DirectVmEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _logger = (_endpoint.Component as ComponentBase)?.Logger; _headerFilter = endpoint.HeaderFilterStrategy; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var registry = _endpoint.Component.GetRegistry() ?? throw new InvalidOperationException( $"SharedVmRegistry is not available. Register it in DI to use direct-vm endpoints."); var processor = registry.GetProcessor(_endpoint.Name) ?? throw new InvalidOperationException( $"No consumer registered for direct-vm endpoint '{_endpoint.Name}'. " + "Ensure the consumer route is started before sending."); if (_headerFilter is not null) { await ProcessFiltered(processor, exchange, _headerFilter, ct).ConfigureAwait(false); return; } // direct-vm: runs the target route — in another context — on THIS exchange, and the target's // first step stamps exchange.RouteId; nothing restores it, so after the call the caller would // carry the callee's id and its own route span and step metrics would be attributed to the callee. // Save ours and put it back once the target returns — on failure too, before the caller's own // error handler runs. var callerRouteId = exchange.RouteId; try { await processor.Process(exchange, ct).ConfigureAwait(false); } finally { exchange.RouteId = callerRouteId; } } /// /// The call under a header filter strategy, Apache Camel 3's DirectVmProducer: the called context works on a /// copy, so dropping a header there never takes it from the caller. The copy shares the caller's DI scope, unit of /// work and properties (), as the zero-copy call does. When it returns, the /// caller keeps its own headers and takes the reply's body, content type and the reply headers the strategy lets /// in, plus the copy's properties, exception and stop, which the zero-copy call would have left on it. /// private static async Task ProcessFiltered(IProcessor processor, IExchange exchange, IHeaderFilterStrategy headerFilter, CancellationToken ct) { var submitted = exchange.CloneLinked(); try { foreach (var (name, value) in submitted.In.Headers.ToList()) { if (headerFilter.FilterOutgoing(name, value, submitted)) submitted.In.Headers.Remove(name); } try { await processor.Process(submitted, ct).ConfigureAwait(false); } finally { var reply = submitted.HasOut ? submitted.Out! : submitted.In; exchange.In.Body = reply.Body; exchange.In.ContentType = reply.ContentType; foreach (var (name, value) in reply.Headers) { if (!headerFilter.FilterIncoming(name, value, submitted)) exchange.In.Headers[name] = value; } foreach (var (key, value) in submitted.Properties) { if (!ExchangeResources.IsOwnedByExchange(key)) exchange.Properties[key] = value; } if (submitted.Exception is not null) { exchange.Exception = submitted.Exception; exchange.ExceptionHandled = submitted.ExceptionHandled; } if (submitted.IsStopped) exchange.Stop(); } } finally { // A streamed reply body now on the caller keeps its connection until the caller ends, as with Enrich. ExchangeResources.HandOver(submitted, exchange); await submitted.DisposeAsync().ConfigureAwait(false); } } /// public Task Start(CancellationToken ct = default) { _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("DirectVm producer started: {Name}", _endpoint.Name); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("DirectVm producer stopped: {Name}", _endpoint.Name); return Task.CompletedTask; } } /// /// Direct-VM consumer. Registers the processor in the shared registry on Start, /// unregisters on Stop. Only one consumer per name allowed globally. /// public class DirectVmConsumer : IConsumer { private readonly DirectVmEndpoint _endpoint; public IEndpoint Endpoint => _endpoint; private readonly IProcessor _processor; private ILogger? _logger; /// Creates a direct-vm consumer. public DirectVmConsumer(DirectVmEndpoint endpoint, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public Task Start(CancellationToken ct = default) { var registry = _endpoint.Component.GetRegistry() ?? throw new InvalidOperationException( "SharedVmRegistry is not available. Register it in DI to use direct-vm endpoints."); if (!registry.TryRegisterProcessor(_endpoint.Name, _processor)) throw new InvalidOperationException( $"A consumer is already registered for direct-vm endpoint '{_endpoint.Name}'. " + "Only one consumer per name is allowed across all contexts."); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("DirectVm consumer started: {Name}", _endpoint.Name); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { var registry = _endpoint.Component.GetRegistry(); registry?.TryUnregisterProcessor(_endpoint.Name, _processor); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("DirectVm consumer stopped: {Name}", _endpoint.Name); return Task.CompletedTask; } } Path: redb-route/redb.Route/Components/LogComponent.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/Components/LogComponent.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components; /// /// Log component. Scheme: "log". /// Logs the exchange body and headers to . /// URI: log://category?level=Information&showHeaders=true&showBody=true /// [EndpointRole(EndpointRole.Producer, Hint = "Use it as a To() destination.")] public class LogComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); private readonly ILoggerFactory? _loggerFactory; /// Creates a log component with an optional logger factory. /// Logger factory for creating category-specific loggers. public LogComponent(ILoggerFactory? loggerFactory = null) { _loggerFactory = loggerFactory; } /// public override string Scheme => "log"; /// Gets the logger factory (may be null). internal ILoggerFactory? LoggerFactory => _loggerFactory; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new LogEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return _endpoints.GetOrAdd(uri.NormalizedKey, _ => new LogEndpoint(uri, this, options)); } } /// /// Options for log endpoints. /// public class LogEndpointOptions : EndpointOptions { /// /// Log level name (default: "Information"), any case: the .NET names Trace, Debug, Information, Warning, Error, /// Critical, None, or Apache Camel's TRACE, DEBUG, INFO, WARN, ERROR, OFF. Any other name is refused when the /// endpoint is created. /// public string Level { get; set; } = "Information"; private static readonly Dictionary LevelNames = new(StringComparer.OrdinalIgnoreCase) { ["Trace"] = LogLevel.Trace, ["Debug"] = LogLevel.Debug, ["Information"] = LogLevel.Information, ["Warning"] = LogLevel.Warning, ["Error"] = LogLevel.Error, ["Critical"] = LogLevel.Critical, ["None"] = LogLevel.None, // Apache Camel's LoggingLevel names; ERROR, DEBUG and TRACE are the .NET names already. ["INFO"] = LogLevel.Information, ["WARN"] = LogLevel.Warning, ["OFF"] = LogLevel.None, }; /// Whether to include headers in the log output (default: true). public bool ShowHeaders { get; set; } = true; /// Whether to include body in the log output (default: true). public bool ShowBody { get; set; } = true; /// Gets the parsed . internal LogLevel ParsedLevel => LevelNames[Level]; /// public override void Validate() { if (Level is null || !LevelNames.ContainsKey(Level)) throw new ArgumentException( $"log: level '{Level}' is not a log level. Use Trace, Debug, Information, Warning, Error, Critical or None, " + "or Apache Camel's TRACE, DEBUG, INFO, WARN, ERROR, OFF (any case).", nameof(Level)); } } /// /// Log endpoint. Produces a log entry for each exchange sent through it. /// public class LogEndpoint : EndpointBase { private readonly ILogger? _logger; private readonly LogEndpointOptions _logOptions; /// Creates a log endpoint. public LogEndpoint(EndpointUri uri, LogComponent component, LogEndpointOptions options) : base(uri, component, options) { _logOptions = options; var category = uri.Path; _logger = component.LoggerFactory?.CreateLogger( string.IsNullOrEmpty(category) ? "redb.Route.Log" : $"redb.Route.Log.{category}"); } /// Gets the configured logger (may be null). internal ILogger? Logger => _logger; /// Gets the log options. internal LogEndpointOptions LogOptions => _logOptions; /// public override IProducer CreateProducer() => new LogProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) { throw new NotSupportedException("Log endpoints do not support consumers. Use them only as To() destinations."); } } /// /// Log producer. Logs the exchange body and/or headers. /// public class LogProducer : IProducer { private readonly LogEndpoint _endpoint; private ILogger? _logger; /// Creates a log producer. public LogProducer(LogEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var logger = _endpoint.Logger; if (logger == null || !logger.IsEnabled(_endpoint.LogOptions.ParsedLevel)) return Task.CompletedTask; var options = _endpoint.LogOptions; var parts = new List(3); if (options.ShowBody) { var body = exchange.In.Body; parts.Add($"Body: {body ?? "(null)"}"); } if (options.ShowHeaders && exchange.In.Headers.Count > 0) { var headers = string.Join(", ", exchange.In.Headers.Select(h => $"{h.Key}={h.Value}")); parts.Add($"Headers: [{headers}]"); } var message = parts.Count > 0 ? string.Join(" | ", parts) : "(empty exchange)"; #pragma warning disable CA2254 // Template should be a static expression logger.Log(_endpoint.LogOptions.ParsedLevel, "Exchange [{RouteId}]: {Message}", exchange.RouteId ?? "(no-route)", message); #pragma warning restore CA2254 return Task.CompletedTask; } /// public Task Start(CancellationToken ct = default) { _logger?.LogInformation("Log producer started: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _logger?.LogInformation("Log producer stopped: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } } Path: redb-route/redb.Route/Components/MockAssertionException.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/Components/MockAssertionException.cs ---- namespace redb.Route.Components; /// /// Thrown by / /// when the mock's expectations do not hold. Independent of any test framework so the test kit /// works with xUnit, NUnit and MSTest alike; the message lists every failed expectation followed /// by the bodies actually received, one per line. /// public sealed class MockAssertionException : Exception { /// Creates the exception with a fully formatted message. public MockAssertionException(string message) : base(message) { } } Path: redb-route/redb.Route/Components/MockComponent.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/Components/MockComponent.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components; /// /// Mock component for testing. Scheme: "mock". /// Captures all received exchanges so tests can assert on them. /// Supports count expectations, latch-based waiting, and body predicates. /// URI: mock://name?expectedMessageCount=0 /// public class MockComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); /// public override string Scheme => "mock"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new MockEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return _endpoints.GetOrAdd(uri.NormalizedKey, _ => new MockEndpoint(uri, this, options)); } /// /// Gets a mock endpoint by name (e.g., "result" for "mock://result"). /// Returns null if not found. /// /// Endpoint name (path portion of the URI). /// Mock endpoint or null. public MockEndpoint? GetEndpoint(string name) { var key = $"mock://{name}"; return _endpoints.TryGetValue(key, out var ep) ? ep : null; } } /// /// Options for mock endpoints. /// public class MockEndpointOptions : EndpointOptions { /// Expected number of messages. 0 = no expectation (default: 0). public int ExpectedMessageCount { get; set; } /// public override void Validate() { } } /// /// Mock endpoint. Captures received exchanges for testing. /// public partial class MockEndpoint : EndpointBase { private readonly ConcurrentQueue _received = new(); private readonly SemaphoreSlim _latch = new(0); private readonly MockEndpointOptions _mockOptions; /// Creates a mock endpoint. public MockEndpoint(EndpointUri uri, MockComponent component, MockEndpointOptions options) : base(uri, component, options) { _mockOptions = options; } /// Gets all received exchanges in order. public IReadOnlyList ReceivedExchanges => [.. _received]; /// Gets the number of received exchanges. public int ReceivedCount => _received.Count; /// Gets the expected message count (from options). public int ExpectedMessageCount => _mockOptions.ExpectedMessageCount; /// /// Waits until the expected number of messages are received, or until timeout. /// /// Maximum wait time. /// Cancellation token. /// True if the expected count was reached; false on timeout. public async Task WaitForSatisfied(TimeSpan timeout, CancellationToken ct = default) { if (_mockOptions.ExpectedMessageCount <= 0) return true; using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(timeout); try { while (ReceivedCount < _mockOptions.ExpectedMessageCount) { await _latch.WaitAsync(cts.Token).ConfigureAwait(false); } return true; } catch (OperationCanceledException) { return ReceivedCount >= _mockOptions.ExpectedMessageCount; } } /// Resets all captured exchanges, the latch counter, expectations and scripted responses. public void Reset() { while (_received.TryDequeue(out _)) { } // Drain semaphore while (_latch.CurrentCount > 0) _latch.Wait(0); ResetExpectations(); } /// Records an exchange (called by MockProducer/MockConsumer). internal void RecordExchange(IExchange exchange) { _received.Enqueue(exchange); _latch.Release(); } /// public override IProducer CreateProducer() => new MockProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new MockConsumer(this, processor); } } /// /// Mock producer. Records the exchange and optionally invokes a registered consumer. /// public class MockProducer : IProducer { private readonly MockEndpoint _endpoint; private ILogger? _logger; /// Creates a mock producer. public MockProducer(MockEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public Task Process(IExchange exchange, CancellationToken ct = default) => _endpoint.OnMessageAsync(exchange, ct); /// public Task Start(CancellationToken ct = default) { _logger?.LogInformation("Mock producer started: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _logger?.LogInformation("Mock producer stopped: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } } /// /// Mock consumer. Delegates to the inner processor and records the exchange. /// public class MockConsumer : IConsumer { private readonly MockEndpoint _endpoint; public IEndpoint Endpoint => _endpoint; private readonly IProcessor _processor; private ILogger? _logger; /// Creates a mock consumer. public MockConsumer(MockEndpoint endpoint, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/redb.Route/Components/MockEndpoint.Expectations.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/Components/MockEndpoint.Expectations.cs ---- using System.Diagnostics; using System.Text; using redb.Route.Abstractions; using redb.Route.Predicates; namespace redb.Route.Components; /// /// Expectations, assertions and scripted responses of the mock endpoint (Apache Camel /// MockEndpoint parity). Expectations are fluent and cumulative; /// waits until all of them hold or the timeout elapses and then fails with every unmet expectation /// and the bodies actually received. /// public partial class MockEndpoint { private readonly object _sync = new(); private readonly List _expectations = []; private readonly List _responses = []; private readonly List _captured = []; private TaskCompletionSource _changed = NewSignal(); private int _messageNumber; // ── Receive path (called by MockProducer) ───────────────────────────────── /// Records the message, wakes waiters, then applies the scripted responses that target it. internal async Task OnMessageAsync(IExchange exchange, CancellationToken ct) { int number; MockResponse[] responses; lock (_sync) { number = ++_messageNumber; _captured.Add(MockReceived.Capture(exchange)); responses = _responses.Where(r => r.AppliesTo(number)).ToArray(); } RecordExchange(exchange); Interlocked.Exchange(ref _changed, NewSignal()).TrySetResult(true); foreach (var response in responses) await response.ApplyAsync(exchange, ct).ConfigureAwait(false); } private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously); private void ResetExpectations() { lock (_sync) { _expectations.Clear(); _responses.Clear(); _captured.Clear(); _messageNumber = 0; } } // ── Expectations ────────────────────────────────────────────────────────── /// Expects exactly messages. public MockEndpoint ExpectMessageCount(int count) => Add(new MessageCountExpectation(Positive(count), minimum: false)); /// Expects at least messages. public MockEndpoint ExpectMinimumMessageCount(int count) => Add(new MessageCountExpectation(Positive(count), minimum: true)); /// Expects exactly these bodies, in this order (numbers compare across CLR types). public MockEndpoint ExpectBodies(params object?[] bodies) => Add(new BodiesExpectation(bodies ?? [], anyOrder: false)); /// Expects exactly these bodies, in any order. public MockEndpoint ExpectBodiesInAnyOrder(params object?[] bodies) => Add(new BodiesExpectation(bodies ?? [], anyOrder: true)); /// Expects every message to carry header equal to . public MockEndpoint ExpectHeader(string name, object? value) => Add(new KeyValueExpectation("Header", Required(name), value, every: true)); /// Expects at least one message to carry header equal to . public MockEndpoint ExpectHeaderReceived(string name, object? value) => Add(new KeyValueExpectation("Header", Required(name), value, every: false)); /// Expects every message to carry exchange property equal to . public MockEndpoint ExpectProperty(string key, object? value) => Add(new KeyValueExpectation("Property", Required(key), value, every: true)); /// Expects to hold on every message. public MockEndpoint Expect(Func predicate, string? description = null) { ArgumentNullException.ThrowIfNull(predicate); return Add(new PredicateExpectation(e => Task.FromResult(predicate(e)), description ?? "")); } /// Expects to hold on every message (awaited, so async predicates work). public MockEndpoint Expect(IPredicate predicate, string? description = null) { ArgumentNullException.ThrowIfNull(predicate); return Add(new PredicateExpectation(predicate.MatchesAsync, description ?? predicate.GetType().Name)); } /// /// Expects the route-language condition ("header.priority == 'high' and body.total > 100") /// to hold on every message; compiled through the same PredicateFactory as Filter(string). /// public MockEndpoint Expect(string condition) { ArgumentException.ThrowIfNullOrWhiteSpace(condition); return Add(new PredicateExpectation(PredicateFactory.FromString(condition).MatchesAsync, $"'{condition}'")); } private MockEndpoint Add(MockExpectation expectation) { lock (_sync) _expectations.Add(expectation); return this; } private static int Positive(int count) => count >= 0 ? count : throw new ArgumentOutOfRangeException(nameof(count)); private static string Required(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); return name; } // ── Scripted responses ──────────────────────────────────────────────────── /// Scripts what happens to the -th message (1-based): reply body, delay, exception. public MockResponse Whenever(int messageNumber) { if (messageNumber < 1) throw new ArgumentOutOfRangeException(nameof(messageNumber), "Message numbers are 1-based."); var response = new MockResponse(messageNumber); lock (_sync) _responses.Add(response); return response; } /// Scripts what happens to every message. public MockResponse WheneverAny() { var response = new MockResponse(null); lock (_sync) _responses.Add(response); return response; } // ── Assertions ──────────────────────────────────────────────────────────── /// Returns true when every expectation currently holds (no waiting). public async Task IsSatisfiedAsync() => (await EvaluateAsync().ConfigureAwait(false)).Count == 0; /// /// Waits up to for every expectation to hold, then throws /// listing each unmet expectation and the bodies received. /// An expectedMessageCount URI option counts as an expectation when no explicit count was set. /// public async Task AssertIsSatisfiedAsync(TimeSpan timeout, CancellationToken ct = default) { var clock = Stopwatch.StartNew(); while (true) { var signal = Volatile.Read(ref _changed).Task; var failures = await EvaluateAsync().ConfigureAwait(false); if (failures.Count == 0) return; var remaining = timeout - clock.Elapsed; if (remaining <= TimeSpan.Zero) throw new MockAssertionException(FormatFailures(failures)); await Task.WhenAny(signal, Task.Delay(remaining, ct)).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); } } /// Waits the full , then throws if the expectations turned out to be satisfied. public async Task AssertIsNotSatisfiedAsync(TimeSpan timeout, CancellationToken ct = default) { await Task.Delay(timeout, ct).ConfigureAwait(false); var failures = await EvaluateAsync().ConfigureAwait(false); if (failures.Count == 0) throw new MockAssertionException($"{Uri.NormalizedKey} expectations were satisfied but were expected not to be ({ReceivedCount} message(s) received)"); } private async Task> EvaluateAsync() { MockExpectation[] expectations; MockReceived[] received; lock (_sync) { expectations = _expectations.ToArray(); received = _captured.ToArray(); } var effective = expectations.ToList(); if (_mockOptions.ExpectedMessageCount > 0 && !expectations.Any(e => e is MessageCountExpectation { IsMinimum: false })) effective.Insert(0, new MessageCountExpectation(_mockOptions.ExpectedMessageCount, minimum: false)); var failures = new List(); foreach (var expectation in effective) { var failure = await expectation.EvaluateAsync(received).ConfigureAwait(false); if (failure is not null) failures.Add(failure); } return failures; } private string FormatFailures(List failures) { MockReceived[] received; lock (_sync) received = _captured.ToArray(); var sb = new StringBuilder(); foreach (var failure in failures) sb.Append(Uri.NormalizedKey).Append(' ').AppendLine(failure); sb.Append(" received ").Append(received.Length).AppendLine(" message(s):"); for (var i = 0; i < received.Length; i++) sb.Append(" ").Append(i + 1).Append(": ").AppendLine(MockValues.Describe(received[i].Body)); return sb.ToString().TrimEnd(); } } Path: redb-route/redb.Route/Components/MockExpectation.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/Components/MockExpectation.cs ---- using System.Globalization; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components; /// /// What a captured when a message arrived: the live exchange plus the /// body, headers and properties as they were at that moment. Built-in expectations compare /// against the captured values, so a step that mutates the exchange after the mock cannot change /// what the mock "saw" (Apache Camel's mock copies the exchange for the same reason). /// internal sealed class MockReceived { public required IExchange Exchange { get; init; } public required object? Body { get; init; } public required IReadOnlyDictionary Headers { get; init; } public required IReadOnlyDictionary Properties { get; init; } public static MockReceived Capture(IExchange exchange) => new() { Exchange = exchange, Body = exchange.In.Body, Headers = new Dictionary(exchange.In.Headers, StringComparer.OrdinalIgnoreCase), Properties = new Dictionary(exchange.Properties), }; } /// /// One expectation registered on a . Evaluated against the captured /// messages; returns null when satisfied, otherwise one human-readable failure line in the /// Apache Camel style (Received message count. Expected: 1 but was: 0). /// internal abstract class MockExpectation { public abstract ValueTask EvaluateAsync(IReadOnlyList received); } /// Exact or minimum number of received messages. internal sealed class MessageCountExpectation(int expected, bool minimum) : MockExpectation { public bool IsMinimum => minimum; public override ValueTask EvaluateAsync(IReadOnlyList received) { var ok = minimum ? received.Count >= expected : received.Count == expected; if (ok) return ValueTask.FromResult(null); var kind = minimum ? "Expected at least" : "Expected"; return ValueTask.FromResult($"Received message count. {kind}: {expected} but was: {received.Count}"); } } /// Bodies received, in order or in any order. internal sealed class BodiesExpectation(object?[] bodies, bool anyOrder) : MockExpectation { public override ValueTask EvaluateAsync(IReadOnlyList received) { if (received.Count != bodies.Length) return ValueTask.FromResult( $"Received message count. Expected: {bodies.Length} but was: {received.Count}"); if (!anyOrder) { for (var i = 0; i < bodies.Length; i++) { if (!MockValues.AreEqual(bodies[i], received[i].Body)) return ValueTask.FromResult( $"Body of message {i + 1}. Expected: {MockValues.Describe(bodies[i])} but was: {MockValues.Describe(received[i].Body)}"); } return ValueTask.FromResult(null); } var remaining = received.Select(r => r.Body).ToList(); foreach (var expected in bodies) { var index = remaining.FindIndex(actual => MockValues.AreEqual(expected, actual)); if (index < 0) return ValueTask.FromResult( $"Body {MockValues.Describe(expected)} expected in any order but was not received"); remaining.RemoveAt(index); } return ValueTask.FromResult(null); } } /// A header (or exchange property) with a given value on every message, or on at least one. internal sealed class KeyValueExpectation(string kind, string key, object? value, bool every) : MockExpectation { public override ValueTask EvaluateAsync(IReadOnlyList received) { if (received.Count == 0) return ValueTask.FromResult($"{kind} '{key}'. Expected: {MockValues.Describe(value)} but no message was received"); for (var i = 0; i < received.Count; i++) { var store = kind == "Property" ? received[i].Properties : received[i].Headers; var present = store.TryGetValue(key, out var actual); var matches = present && MockValues.AreEqual(value, actual); if (matches && !every) return ValueTask.FromResult(null); if (!matches && every) return ValueTask.FromResult( $"{kind} '{key}' on message {i + 1}. Expected: {MockValues.Describe(value)} but was: {(present ? MockValues.Describe(actual) : "")}"); } return ValueTask.FromResult(every ? null : $"{kind} '{key}'. Expected: {MockValues.Describe(value)} on at least one message but none matched"); } } /// An arbitrary predicate holding on every message (evaluated against the live exchange). internal sealed class PredicateExpectation(Func> predicate, string description) : MockExpectation { public override async ValueTask EvaluateAsync(IReadOnlyList received) { if (received.Count == 0) return $"Predicate {description}. Expected to hold but no message was received"; for (var i = 0; i < received.Count; i++) { if (!await predicate(received[i].Exchange).ConfigureAwait(false)) return $"Predicate {description} failed on message {i + 1}: {MockValues.Describe(received[i].Body)}"; } return null; } } /// Value comparison and formatting shared by the expectations. internal static class MockValues { /// /// plus two conveniences that make expectations /// read naturally: numbers compare across CLR types (1 equals 1L), and byte arrays /// compare by content. /// public static bool AreEqual(object? expected, object? actual) { if (Equals(expected, actual)) return true; if (expected is null || actual is null) return false; if (IsNumeric(expected) && IsNumeric(actual)) { try { return RouteDecimal.From(expected) == RouteDecimal.From(actual); } catch (OverflowException) { return false; } } if (expected is byte[] eb && actual is byte[] ab) return eb.AsSpan().SequenceEqual(ab); return false; } public static string Describe(object? value) => value switch { null => "", string s => $"\"{s}\"", byte[] b => $"byte[{b.Length}]", IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), _ => value.ToString() ?? value.GetType().Name, }; private static bool IsNumeric(object value) => value is sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal; } Path: redb-route/redb.Route/Components/MockResponse.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/Components/MockResponse.cs ---- using redb.Route.Abstractions; namespace redb.Route.Components; /// /// Scripted behaviour of a for one message () /// or for every message (): set the reply body or a header, /// delay, throw, or run arbitrary code. Actions run in the order they were added, after the exchange /// has been recorded, so a throwing mock still counts the message it rejected. /// /// This is what makes mock:// usable behind Enrich / PollEnrich / request-reply: /// the reply body is whatever left in the exchange. /// /// public sealed class MockResponse { private readonly List> _actions = []; internal MockResponse(int? messageNumber) { MessageNumber = messageNumber; } /// 1-based ordinal of the message this response applies to; null = every message. public int? MessageNumber { get; } /// Replaces the message body (the reply seen by Enrich / request-reply callers). public MockResponse SetBody(object? body) { _actions.Add((exchange, _) => { exchange.In.Body = body; return Task.CompletedTask; }); return this; } /// Sets a header on the message. public MockResponse SetHeader(string name, object? value) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _actions.Add((exchange, _) => { exchange.In.Headers[name] = value; return Task.CompletedTask; }); return this; } /// Waits before continuing — simulates a slow downstream system. public MockResponse Delay(TimeSpan delay) { if (delay < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(delay)); _actions.Add((_, ct) => Task.Delay(delay, ct)); return this; } /// Throws the given exception — simulates a failing downstream system. public MockResponse Throw(Exception exception) { ArgumentNullException.ThrowIfNull(exception); _actions.Add((_, _) => throw exception); return this; } /// Throws a new with the given message. public MockResponse Throw(string message) where TException : Exception { ArgumentNullException.ThrowIfNull(message); _actions.Add((_, _) => throw (Exception)Activator.CreateInstance(typeof(TException), message)!); return this; } /// Runs arbitrary synchronous code against the exchange. public MockResponse Do(Action action) { ArgumentNullException.ThrowIfNull(action); _actions.Add((exchange, _) => { action(exchange); return Task.CompletedTask; }); return this; } /// Runs arbitrary asynchronous code against the exchange. public MockResponse Do(Func action) { ArgumentNullException.ThrowIfNull(action); _actions.Add(action); return this; } internal bool AppliesTo(int messageNumber) => MessageNumber is null || MessageNumber == messageNumber; internal async Task ApplyAsync(IExchange exchange, CancellationToken ct) { foreach (var action in _actions) await action(exchange, ct).ConfigureAwait(false); } } Path: redb-route/redb.Route/Components/RegistryClaimCheckRepositoryProvider.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/Components/RegistryClaimCheckRepositoryProvider.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Components; /// /// Resolves instances for Claim Check steps. A named repository is found in the /// registry by its bare name, checked for type (Camel's lookupByNameAndType), the /// same key every other #name reference uses. The repository of steps that name none is the context's /// service, looked up by type. /// public static class ClaimCheckRepositoryRegistry { private static readonly object DefaultLock = new(); /// /// Registers an in the context registry under , so /// route steps can refer to it as .ClaimCheck(operation, repositoryName: "large-payloads"). /// public static IRouteContext AddClaimCheckRepository( this IRouteContext context, string name, IClaimCheckRepository repository) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrEmpty(name); ArgumentNullException.ThrowIfNull(repository); context.AddToRegistry(RegistryLookup.Key(name), repository); return context; } /// /// Registers the repository used by Claim Check steps that name none, as the context's /// service. Without it the context falls back to a shared /// . /// public static IRouteContext SetDefaultClaimCheckRepository( this IRouteContext context, IClaimCheckRepository repository) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(repository); context.AddService(typeof(IClaimCheckRepository), repository); return context; } /// /// Resolves the repository for a Claim Check step. A name is looked up in the registry; without one, the context's /// service (, or one the host /// registered), else a shared in-memory repository created once per context and kept as that service. /// /// Route context being compiled. /// Registry name, or null for the default. /// A name was given and nothing, or an object of another type, is registered under it. public static IClaimCheckRepository ResolveClaimCheckRepository( this IRouteContext context, string? repositoryName = null) { ArgumentNullException.ThrowIfNull(context); if (!string.IsNullOrEmpty(repositoryName)) { var key = RegistryLookup.Key(repositoryName); return RegistryLookup.Find(context, key) ?? throw new InvalidOperationException( $"Nothing is registered under '{key}': register an IClaimCheckRepository with " + $"context.AddClaimCheckRepository(\"{key}\", repository), or declare in Route-XML."); } var fromServices = context.GetService(); if (fromServices is not null) return fromServices; // The fallback must be shared across steps: a Set in one step and a Get in another // have to reach the same store, otherwise the claim key resolves to nothing. lock (DefaultLock) { var existing = context.GetService(); if (existing is not null) return existing; var created = new InMemoryClaimCheckRepository(); context.AddService(typeof(IClaimCheckRepository), created); return created; } } } Path: redb-route/redb.Route/Components/RegistryIdempotentRepositoryProvider.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/Components/RegistryIdempotentRepositoryProvider.cs ---- using redb.Route.Abstractions; namespace redb.Route.Components; /// /// Default : resolves a repository from the /// registry by its bare name, checked for type — Camel's lookupByNameAndType. The name is the registry key as /// is, the same key every other #name reference uses, so a bean declared in markup under dedup is the /// repository repository="#dedup" names. /// public sealed class RegistryIdempotentRepositoryProvider : IIdempotentRepositoryProvider { private readonly IRouteContext _context; /// Creates a provider backed by the given route context's registry. public RegistryIdempotentRepositoryProvider(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); _context = context; } /// public IIdempotentRepository Get(string name) { ArgumentException.ThrowIfNullOrEmpty(name); if (TryGet(name, out var repository)) return repository; var key = RegistryLookup.Key(name); throw new InvalidOperationException( $"Nothing is registered under '{key}': register an IIdempotentRepository with " + $"context.AddIdempotentRepository(\"{key}\", repository), or declare in Route-XML."); } /// /// Finds the repository registered under . false when nothing is registered there; /// an object of another type under the name is a configuration error and throws. /// public bool TryGet(string name, out IIdempotentRepository repository) { repository = null!; if (string.IsNullOrEmpty(name)) return false; var found = RegistryLookup.Find(_context, name); if (found is null) return false; repository = found; return true; } } /// A registry lookup by bare name, checked for type: nothing there, or the wrong type, are told apart. internal static class RegistryLookup { /// The registry key of a reference: #name and name are the same key. public static string Key(string name) => name.StartsWith('#') ? name[1..] : name; /// The object under as ; null when nothing is there. /// An object of another type is registered under the name. public static T? Find(IRouteContext context, string name) where T : class { var key = Key(name); var found = context.GetFromRegistry(key); return found switch { null => null, T typed => typed, _ => throw new InvalidOperationException( $"'{key}' is registered as {found.GetType().FullName}, which is not an {typeof(T).Name}."), }; } } /// /// Convenience extensions for working with named idempotent repositories on /// . /// public static class IdempotentRepositoryRegistryExtensions { /// /// Registers an in the context registry under , the /// name routes refer to it by (IdempotentConsumer(..., "name"), repository="#name", /// idempotentRepository=name on a consumer). /// public static IRouteContext AddIdempotentRepository(this IRouteContext context, string name, IIdempotentRepository repository) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrEmpty(name); ArgumentNullException.ThrowIfNull(repository); context.AddToRegistry(RegistryLookup.Key(name), repository); return context; } /// /// Resolves the registered on the context, /// or returns a default one backed by the context registry if no override was added. /// public static IIdempotentRepositoryProvider GetIdempotentRepositoryProvider(this IRouteContext context) { ArgumentNullException.ThrowIfNull(context); var custom = context.GetService(); return custom ?? new RegistryIdempotentRepositoryProvider(context); } } Path: redb-route/redb.Route/Components/SedaComponent.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/Components/SedaComponent.cs ---- using System.Collections.Concurrent; using System.Threading.Channels; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Transactions; namespace redb.Route.Components; /// /// SEDA (Staged Event-Driven Architecture) component. Scheme: "seda". /// Provides asynchronous in-memory queuing between route segments. /// Producer enqueues the exchange and returns immediately; a background consumer /// loop dequeues and processes exchanges asynchronously. /// URI: seda://name?concurrentConsumers=1&size=0 /// public class SedaComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); /// public override string Scheme => "seda"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new SedaEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return _endpoints.GetOrAdd(uri.BaseKey, _ => new SedaEndpoint(uri, this, options)); } } /// /// Options for SEDA endpoints. /// public class SedaEndpointOptions : EndpointOptions { /// Concurrent consumer workers: a number or "auto" (= max(CPU, 2)). Default 1. // A string so "auto" binds verbatim instead of silently degrading to the int default. public string? ConcurrentConsumers { get; set; } /// Resolved worker count (see ). public int ResolvedConcurrentConsumers => ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); /// /// Maximum queue size (default: 1000, as Camel). A full queue makes the sender wait up to timeout. 0 = unbounded, /// an explicit choice: a consumer slower than its senders then grows the queue without limit. /// public int Size { get; set; } = 1000; /// Timeout in milliseconds for enqueue when queue is bounded. 0 = wait forever (default: 30000). public int Timeout { get; set; } = 30000; /// public override void Validate() { _ = ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); // loud on garbage if (Size < 0) throw new ArgumentOutOfRangeException(nameof(Size), Size, "Size cannot be negative."); } } /// /// SEDA endpoint. Uses as the in-memory async queue. /// public class SedaEndpoint : EndpointBase { private readonly object _queueGate = new(); private Channel _queue; private bool _closed; /// /// The queue of the endpoint. A stopping consumer closes it () and the next start of a consumer /// opens a new one (): the endpoint is cached by its component and outlives a /// Stop() and Start() of the route context, while a closed channel cannot take writes again. /// internal Channel Queue => Volatile.Read(ref _queue); /// Creates a SEDA endpoint. public SedaEndpoint(EndpointUri uri, SedaComponent component, SedaEndpointOptions options) : base(uri, component, options) { _queue = CreateQueue(options); } private static Channel CreateQueue(SedaEndpointOptions options) => options.Size > 0 ? Channel.CreateBounded(new BoundedChannelOptions(options.Size) { FullMode = BoundedChannelFullMode.Wait, SingleReader = options.ResolvedConcurrentConsumers == 1, SingleWriter = false }) : Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = options.ResolvedConcurrentConsumers == 1, SingleWriter = false }); /// /// Stops the queue taking new exchanges: a send fails with , and the consumer /// finishes what is already queued. /// internal void Close() { lock (_queueGate) { _closed = true; _queue.Writer.TryComplete(); } } /// /// Opens a new queue in place of a closed one, for a consumer that starts again. Exchanges the stopping consumer /// did not get to (its drain timed out) cannot be read from the closed queue by anyone: they are returned to be /// released, and never handed over silently to the new one. /// internal IReadOnlyList Reopen() { lock (_queueGate) { if (!_closed) return []; var left = new List(); while (_queue.Reader.TryRead(out var exchange)) left.Add(exchange); Volatile.Write(ref _queue, CreateQueue(Options)); _closed = false; return left; } } /// Gets the current approximate queue size. public int CurrentQueueSize => Queue.Reader.CanCount ? Queue.Reader.Count : -1; /// public override IProducer CreateProducer() => new SedaProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new SedaConsumer(this, processor, Options); } } /// /// SEDA producer. Enqueues the exchange into the channel and returns immediately. /// The exchange is processed asynchronously by the consumer. /// public class SedaProducer : IProducer { private readonly SedaEndpoint _endpoint; private ILogger? _logger; /// Creates a SEDA producer. public SedaProducer(SedaEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // Clone to ensure thread-safety: the pipeline thread and the SEDA worker // must not share a mutable exchange. Clone also creates a new DI scope. var copy = exchange.CorrelatedCopy(); // The copy runs later on the SEDA worker, a unit of work of its own: it must not see the sending // .Transacted() block as its own. TransactedActions.DetachFromBlock(copy); try { await _endpoint.Queue.Writer.WriteAsync(copy, ct).ConfigureAwait(false); } catch { // The clone was NOT enqueued (cancellation, or the queue was completed on shutdown), so // the consumer will never dispose it — release its per-exchange DI scope / DB connection // here, then rethrow so the caller still observes the failure. await copy.DisposeAsync().ConfigureAwait(false); throw; } } /// public Task Start(CancellationToken ct = default) { _logger?.LogInformation("SEDA producer started: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _logger?.LogInformation("SEDA producer stopped: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } } /// /// SEDA consumer. Runs N concurrent workers that dequeue and process exchanges. /// public class SedaConsumer : DrainableConsumer { private readonly SedaEndpoint _endpoint; private readonly SedaEndpointOptions _options; private Task[]? _workers; private long _processedCount; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => _endpoint.Uri.NormalizedKey; /// Total number of exchanges processed across all workers. public long ProcessedCount => Interlocked.Read(ref _processedCount); /// Creates a SEDA consumer. public SedaConsumer(SedaEndpoint endpoint, IProcessor processor, SedaEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { _workers = new Task[_options.ResolvedConcurrentConsumers]; for (var i = 0; i < _options.ResolvedConcurrentConsumers; i++) _workers[i] = WorkerLoop(pollCt, processingCt); return Task.CompletedTask; } /// protected override async Task OnStarting(CancellationToken ct) { // A consumer that starts again after a stop (a Stop() and Start() of the route context, a restart of the route) // gets a new queue: the stop closed the old one for good. var left = _endpoint.Reopen(); if (left.Count == 0) return; Logger?.LogWarning( "{Consumer}: {Count} exchange(s) were still queued when the consumer last stopped and are dropped.", ConsumerName, left.Count); foreach (var exchange in left) await exchange.DisposeAsync().ConfigureAwait(false); } /// protected override Task OnStopAccepting() { // Sends fail from here on, and the workers finish what is already queued (ReadAllAsync reads buffered // exchanges without looking at the poll token). _endpoint.Close(); return Task.CompletedTask; } /// protected override async Task AwaitRunTask() { if (_workers != null) { try { await Task.WhenAll(_workers).ConfigureAwait(false); } catch (OperationCanceledException) { } } } private async Task WorkerLoop(CancellationToken pollCt, CancellationToken processingCt) { try { await foreach (var exchange in _endpoint.Queue.Reader.ReadAllAsync(pollCt).ConfigureAwait(false)) { await ProcessWithTracking(exchange, processingCt).ConfigureAwait(false); Interlocked.Increment(ref _processedCount); } } catch (OperationCanceledException) { } catch (ChannelClosedException) { } } } Path: redb-route/redb.Route/Components/SharedVmRegistry.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/Components/SharedVmRegistry.cs ---- using System.Collections.Concurrent; using System.Threading.Channels; using redb.Route.Abstractions; namespace redb.Route.Components; /// /// Shared cross-context registry for direct-vm and vm components. /// Registered as a singleton in DI — all RouteContexts share the same instance, /// enabling cross-context communication without static state. /// public class SharedVmRegistry { // ── direct-vm: synchronous cross-context processors ── private readonly ConcurrentDictionary _processors = new(StringComparer.OrdinalIgnoreCase); /// Registers a processor for a direct-vm endpoint name. /// true if registered; false if another consumer already holds this name. public bool TryRegisterProcessor(string name, IProcessor processor) { ArgumentNullException.ThrowIfNull(name); ArgumentNullException.ThrowIfNull(processor); return _processors.TryAdd(name, processor); } /// Unregisters the processor for a direct-vm endpoint name (only if same instance). public bool TryUnregisterProcessor(string name, IProcessor processor) { ArgumentNullException.ThrowIfNull(name); ArgumentNullException.ThrowIfNull(processor); return _processors.TryRemove(new KeyValuePair(name, processor)); } /// Gets the processor for a direct-vm endpoint name, or null if none registered. public IProcessor? GetProcessor(string name) { return _processors.TryGetValue(name, out var p) ? p : null; } // ── vm: asynchronous cross-context channels ── private readonly ConcurrentDictionary> _channels = new(StringComparer.OrdinalIgnoreCase); /// Gets or creates the shared channel for a vm endpoint name. public Channel GetOrCreateChannel(string name, int boundedSize = 0) { ArgumentNullException.ThrowIfNull(name); return _channels.GetOrAdd(name, _ => boundedSize > 0 ? Channel.CreateBounded(new BoundedChannelOptions(boundedSize) { FullMode = BoundedChannelFullMode.Wait, SingleReader = false, SingleWriter = false }) : Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = false, SingleWriter = false })); } /// Tries to remove a channel (e.g. on last consumer stop). Returns the removed channel if any. public bool TryRemoveChannel(string name, out Channel? channel) { var result = _channels.TryRemove(name, out var ch); channel = ch; return result; } } Path: redb-route/redb.Route/Components/TimerComponent.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/Components/TimerComponent.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components; /// /// Timer component. Scheme: "timer". /// Generates exchanges on a periodic schedule. Used as a route source (From). /// URI: timer://name?period=1000&delay=0&repeatCount=-1 /// [EndpointRole(EndpointRole.Consumer, Hint = "Use it as a From() source.")] public class TimerComponent : ComponentBase { /// public override string Scheme => "timer"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new TimerEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new TimerEndpoint(uri, this, options); } } /// /// Timer endpoint options. /// public class TimerEndpointOptions : EndpointOptions { /// Period between fires in milliseconds (default: 1000). public int Period { get; set; } = 1000; /// Initial delay before first fire in milliseconds (default: 0). public int Delay { get; set; } /// Number of times to fire. -1 means indefinitely (default: -1). public int RepeatCount { get; set; } = -1; /// public override void Validate() { if (Period <= 0) throw new ArgumentOutOfRangeException(nameof(Period), Period, "Period must be greater than 0."); } } /// /// Timer endpoint. The consumer is the primary artifact — a timer that fires periodically. /// public class TimerEndpoint : EndpointBase { /// Creates a timer endpoint. public TimerEndpoint(EndpointUri uri, TimerComponent component, TimerEndpointOptions options) : base(uri, component, options) { } /// public override IProducer CreateProducer() { throw new NotSupportedException("Timer endpoints do not support producers. Use them only as From() source."); } /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new TimerConsumer(this, processor, Options); } } /// /// Timer consumer. Fires the processor on a periodic schedule. /// Creates a new exchange per tick. /// public class TimerConsumer : DrainableConsumer { private readonly TimerEndpoint _endpoint; private readonly TimerEndpointOptions _options; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => _endpoint.Uri.NormalizedKey; /// Gets the number of fires completed. public long FireCount { get; private set; } /// Creates a timer consumer. public TimerConsumer(TimerEndpoint endpoint, IProcessor processor, TimerEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { if (_options.Delay > 0) await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false); var period = TimeSpan.FromMilliseconds(_options.Period); var count = 0; while (!pollCt.IsCancellationRequested) { if (_options.RepeatCount >= 0 && count >= _options.RepeatCount) break; var exchange = CreateTimerExchange(count); await ProcessWithTracking(exchange, processingCt).ConfigureAwait(false); FireCount++; count++; if (_options.RepeatCount >= 0 && count >= _options.RepeatCount) break; try { await Task.Delay(period, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested) { break; } } } private Exchange CreateTimerExchange(int fireIndex) { var message = new Message { Body = null, Headers = { ["CamelTimerName"] = _endpoint.Uri.Path, ["CamelTimerFiredTime"] = DateTimeOffset.UtcNow, ["CamelTimerCounter"] = fireIndex } }; var exchange = Exchange.Create(message, _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; return exchange; } } Path: redb-route/redb.Route/Components/VmComponent.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/Components/VmComponent.cs ---- using System.Collections.Concurrent; using System.Threading.Channels; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Transactions; namespace redb.Route.Components; /// /// Cross-context asynchronous component. Scheme: "vm". /// Like SEDA but the channel is shared across all RouteContexts /// via (DI singleton). /// Producer enqueues the exchange (with clone) and returns immediately; /// a consumer in any context dequeues and processes asynchronously. /// URI: vm://name?concurrentConsumers=1&size=0 /// public class VmComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); /// public override string Scheme => "vm"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new VmEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); // Keyed with the parameters: a producer's headerFilterStrategy must not be lost to, or leak into, a consumer of // the same name in this context. Both find the queue by name (Uri.BaseKey) in the shared registry. return _endpoints.GetOrAdd(uri.NormalizedKey, _ => new VmEndpoint(uri, this, options)); } /// Resolves the shared registry from DI. Returns null if not registered. internal SharedVmRegistry? GetRegistry() { return Context?.GetServiceProvider()?.GetService(); } } /// /// Options for VM endpoints. /// public class VmEndpointOptions : EndpointOptions { /// Concurrent consumer workers: a number or "auto" (= max(CPU, 2)). Default 1. // A string so "auto" binds verbatim instead of silently degrading to the int default. public string? ConcurrentConsumers { get; set; } /// Resolved worker count (see ). public int ResolvedConcurrentConsumers => ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); /// /// Maximum queue size (default: 1000, as Camel). A full queue makes the sender wait up to timeout. 0 = unbounded, /// an explicit choice: a consumer slower than its senders then grows the queue without limit. /// public int Size { get; set; } = 1000; /// /// Producer only: a registry reference (#name) to an deciding which /// headers the copy handed to the other context carries (its outgoing direction). Without it every header goes. /// Apache Camel's vm has no such option (its direct-vm has); a vm call has no reply to filter. /// [EndpointRole(EndpointRole.Producer)] [RegistryReference(typeof(IHeaderFilterStrategy))] public string? HeaderFilterStrategy { get; set; } /// public override void Validate() { _ = ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); // loud on garbage if (Size < 0) throw new ArgumentOutOfRangeException(nameof(Size), Size, "Size cannot be negative."); } } /// /// VM endpoint. Uses a shared from . /// public class VmEndpoint : EndpointBase { internal new VmComponent Component => (VmComponent)base.Component; /// The logical name used as key in the shared registry. internal string Name => Uri.BaseKey; private Channel? _channel; /// Gets the shared channel (lazy-resolved from registry). internal Channel Channel { get { if (_channel is not null) return _channel; var registry = Component.GetRegistry() ?? throw new InvalidOperationException( "SharedVmRegistry is not available. Register it in DI to use vm endpoints."); _channel = registry.GetOrCreateChannel(Name, Options.Size); return _channel; } } /// Creates a VM endpoint. public VmEndpoint(EndpointUri uri, VmComponent component, VmEndpointOptions options) : base(uri, component, options) { _headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy); } private readonly EndpointHeaderFilter _headerFilter; /// /// The strategy headerFilterStrategy=#name names, or null: vm has no default strategy. A name the /// registry does not hold fails when the producer is built. /// internal IHeaderFilterStrategy? HeaderFilterStrategy => _headerFilter.Configured; /// public override IProducer CreateProducer() => new VmProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); var written = EndpointOptions.WrittenForOtherRole(Options.GetType(), Uri, EndpointRole.Consumer); if (written.Count > 0) throw new InvalidOperationException( $"vm consumer '{EndpointUri.Sanitize(Uri.NormalizedKey)}' sets {string.Join(", ", written)}, which " + "applies to the sending side (.To); a consumer has nothing to filter. Move it to the producer URI."); return new VmConsumer(this, processor, Options); } } /// /// VM producer. Clones the exchange and enqueues into the shared channel. /// public class VmProducer : IProducer { private readonly VmEndpoint _endpoint; private readonly IHeaderFilterStrategy? _headerFilter; private ILogger? _logger; /// Creates a VM producer. public VmProducer(VmEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _logger = (endpoint.Component as ComponentBase)?.Logger; _headerFilter = endpoint.HeaderFilterStrategy; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var copy = exchange.CorrelatedCopy(); if (_headerFilter is not null) { foreach (var (name, value) in copy.In.Headers.ToList()) { if (_headerFilter.FilterOutgoing(name, value, copy)) copy.In.Headers.Remove(name); } } // The copy runs later on the vm consumer, a unit of work of its own: it must not see the sending // .Transacted() block as its own. TransactedActions.DetachFromBlock(copy); try { await _endpoint.Channel.Writer.WriteAsync(copy, ct).ConfigureAwait(false); } catch { // The clone was NOT enqueued (cancellation, or the channel was completed on shutdown), so // the consumer will never dispose it — release its per-exchange DI scope / DB connection // here, then rethrow so the caller still observes the failure. await copy.DisposeAsync().ConfigureAwait(false); throw; } } /// public Task Start(CancellationToken ct = default) { _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("Vm producer started: {Name}", _endpoint.Name); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("Vm producer stopped: {Name}", _endpoint.Name); return Task.CompletedTask; } } /// /// VM consumer. Runs N concurrent workers that dequeue from the shared channel and process. /// public class VmConsumer : DrainableConsumer { private readonly VmEndpoint _endpoint; private readonly VmEndpointOptions _options; private Task[]? _workers; private long _processedCount; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => _endpoint.Name; /// Total number of exchanges processed across all workers. public long ProcessedCount => Interlocked.Read(ref _processedCount); /// Creates a VM consumer. public VmConsumer(VmEndpoint endpoint, IProcessor processor, VmEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { _workers = new Task[_options.ResolvedConcurrentConsumers]; for (var i = 0; i < _options.ResolvedConcurrentConsumers; i++) _workers[i] = WorkerLoop(pollCt, processingCt); return Task.CompletedTask; } /// protected override async Task AwaitRunTask() { if (_workers != null) { try { await Task.WhenAll(_workers).ConfigureAwait(false); } catch (OperationCanceledException) { } } } private async Task WorkerLoop(CancellationToken pollCt, CancellationToken processingCt) { try { await foreach (var exchange in _endpoint.Channel.Reader.ReadAllAsync(pollCt).ConfigureAwait(false)) { await ProcessWithTracking(exchange, processingCt).ConfigureAwait(false); Interlocked.Increment(ref _processedCount); } } catch (OperationCanceledException) { } catch (ChannelClosedException) { } } } Path: redb-route/redb.Route/Configuration/AttachmentOptions.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/Configuration/AttachmentOptions.cs ---- namespace redb.Route.Configuration; /// Message attachment options, section RedbRoute:Attachments. public sealed class AttachmentOptions { /// Default : 10 MB, the default HTTP request body limit. public const long DefaultMaxReplayableBytes = 10L * 1024 * 1024; /// /// The total attachment content of one exchange (In and Out) that a snapshot for replay keeps. A /// .Replayable() checkpoint of an exchange whose attachments are larger is not captured (logged, processing /// goes on), and so the exchange cannot be replayed from a checkpoint or from the Tsak DLQ, which stores that /// checkpoint. 0 means an exchange with any attachment is not replayable. Default: 10 MB. /// public long MaxReplayableBytes { get; set; } = DefaultMaxReplayableBytes; } Path: redb-route/redb.Route/Configuration/ConsumerStartRetryOptions.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/Configuration/ConsumerStartRetryOptions.cs ---- namespace redb.Route.Configuration; /// /// Retry of a consumer that failed to start with its context (RedbRoute:ConsumerStartRetry), the back-off of /// Apache Camel's supervising route controller. A broker or a server that is not up yet when the context starts /// leaves the route Errored; the context then starts its consumer again in the background, with a pause that /// grows from by up to , until it starts or /// runs out. The route stays Errored while it waits, so health reports it. /// public sealed class ConsumerStartRetryOptions { /// Whether a consumer that failed to start is started again. Default: true. public bool Enabled { get; set; } = true; /// Pause before the first retry (Camel backOffDelay). Default: 2 seconds. public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(2); /// Factor the pause grows by after each failed retry (Camel backOffMultiplier). Default: 2. public double Multiplier { get; set; } = 2.0; /// The longest pause between two retries (Camel backOffMaxDelay). Default: 1 minute. public TimeSpan MaxDelay { get; set; } = TimeSpan.FromMinutes(1); /// /// How many retries a consumer gets; 0 retries until the context stops (Camel backOffMaxAttempts). /// After the last one the route stays Errored. Default: 0. /// public int MaxAttempts { get; set; } /// /// Whether an Errored route whose consumer waits for a start retry makes health Unhealthy (Camel /// unhealthyOnRestarting); false reports it Degraded. Default: true, as in Camel since 4.7. /// public bool UnhealthyOnRestarting { get; set; } = true; /// /// Whether an Errored route no start retry waits for (the retries ran out, retry is off, or a route policy /// refused the start) makes health Unhealthy (Camel unhealthyOnExhausted); false reports it Degraded. /// Default: true, as in Camel since 4.7. /// public bool UnhealthyOnExhausted { get; set; } = true; /// /// Whether an Errored route makes health Unhealthy rather than Degraded: /// while a start retry waits for it (), otherwise. /// public bool ErroredRouteIsUnhealthy(bool retryPending) => retryPending ? UnhealthyOnRestarting : UnhealthyOnExhausted; /// The pauses between retries: , grown by up to . internal Core.BackoffSchedule Schedule => new(Delay, Multiplier, MaxDelay); internal void Validate() { Core.BackoffSchedule.Validate("ConsumerStartRetry", Delay, Multiplier, MaxDelay); if (MaxAttempts < 0) throw new ArgumentOutOfRangeException(nameof(MaxAttempts), MaxAttempts, "ConsumerStartRetry.MaxAttempts must be 0 (no limit) or more."); } } Path: redb-route/redb.Route/Configuration/JsonCodecOptions.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/Configuration/JsonCodecOptions.cs ---- using redb.Route.Abstractions; namespace redb.Route.Configuration; /// /// Strongly-typed view of the redbRoute:Codecs:Json configuration section. /// Used by . /// /// These knobs govern the generic JSON codec registered under /// application/json in . They do NOT override /// media-type-specific profiles registered separately (e.g. SCIM, Problem Details, /// OAuth): such profiles own their own options and are not exposed to app config /// by design. /// /// public sealed class JsonCodecOptions { /// /// Property naming policy. Accepted values (case-insensitive): /// null/"None" (verbatim), "CamelCase", "SnakeCaseLower", /// "SnakeCaseUpper", "KebabCaseLower", "KebabCaseUpper". /// Default: "CamelCase". /// public string? PropertyNamingPolicy { get; set; } = "CamelCase"; /// /// When true, null property values are omitted during serialization. /// Default: true. /// public bool IgnoreNullValues { get; set; } = true; /// /// When true, property name matching during deserialization is case-insensitive. /// Default: true. /// public bool PropertyNameCaseInsensitive { get; set; } = true; /// /// When true, output JSON is indented. Default: false. /// public bool WriteIndented { get; set; } /// /// When true (default), uses UnsafeRelaxedJsonEscaping so non-ASCII /// bytes (Cyrillic, emoji, etc.) and ASCII quotes are emitted as UTF-8 literals /// per RFC 8259 §8.1. Only flip to false if the output is embedded into /// HTML/JS inline — which is not a Route-message scenario. /// public bool UnsafeRelaxedEscaping { get; set; } = true; } Path: redb-route/redb.Route/Configuration/ReconnectOptions.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/Configuration/ReconnectOptions.cs ---- namespace redb.Route.Configuration; /// /// Reconnect after a connection or a link is lost while a route runs (RedbRoute:Reconnect). The start of a /// consumer has its own retry (); this one keeps the route Started and /// reports the loss through the endpoint's health. Used by every connector that reports its connections to a /// . /// public sealed class ReconnectOptions { /// Pause before the first attempt after a loss. Default: 1 second. public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(1); /// Factor the pause grows by after each failed attempt. Default: 2. public double Multiplier { get; set; } = 2.0; /// The longest pause between two attempts. Default: 30 seconds. public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(30); /// /// The longest wait for one connect of an attempt. A connect that has not finished by then counts as failed, and a /// connection it still opens later is closed. Guards against clients whose connect can hang. Default: 30 seconds. /// public TimeSpan AttemptTimeout { get; set; } = TimeSpan.FromSeconds(30); /// /// How long a loss is reported as health Warning before it turns Critical, for clients that heal short blips by /// themselves. Default: zero, so the first failed attempt makes the endpoint Critical (and the route Unhealthy when /// the endpoint is its source). /// public TimeSpan WarningPeriod { get; set; } = TimeSpan.Zero; /// The pauses between attempts: , grown by up to . internal Core.BackoffSchedule Schedule => new(Delay, Multiplier, MaxDelay); internal void Validate() { Core.BackoffSchedule.Validate("Reconnect", Delay, Multiplier, MaxDelay); if (AttemptTimeout <= TimeSpan.Zero || AttemptTimeout.TotalMilliseconds > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(AttemptTimeout), AttemptTimeout, "Reconnect.AttemptTimeout must be positive and not exceed 24 days."); if (WarningPeriod < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(WarningPeriod), WarningPeriod, "Reconnect.WarningPeriod must not be negative."); } } Path: redb-route/redb.Route/Configuration/RouteEngineOptions.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/Configuration/RouteEngineOptions.cs ---- namespace redb.Route.Configuration; /// /// Root configuration options for the route engine. /// Bound from configuration section "RedbRoute". /// public sealed class RouteEngineOptions { /// Configuration section name. public const string SectionName = "RedbRoute"; /// /// Whether to enable OpenTelemetry tracing: the route spans and the transport spans connectors open through /// with this context. Off, neither is opened, so a trace never /// holds a transport span without the route it belongs to; an incoming or ambient trace context is still passed /// on to the next hop. Default: true. /// public bool EnableTelemetry { get; set; } = true; /// /// Whether to enable metrics collection (exchange count, duration, failures). /// Default: true. /// public bool EnableMetrics { get; set; } = true; /// /// Whether to record per-node message history on every exchange (Apache Camel Message History EIP): /// each node is timed and appended to exchange.Properties["CamelMessageHistory"], and the /// trail is dumped on failure. A route may override this with .MessageHistory(bool). /// Default: false (matches Camel — slight overhead, opt-in). /// public bool EnableMessageHistory { get; set; } /// /// Graceful shutdown timeout when stopping routes. /// Default: 30 seconds. /// public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(30); /// /// Whether to throw on startup if a route fails to compile. /// When false, failed routes are logged and skipped. /// Default: true. /// public bool ThrowOnCompilationError { get; set; } = true; /// /// Whether the engine performs cross-cutting startup checks during route compilation /// and emits warnings for misconfigurations (e.g., a route declares .Cluster(true) /// but no is registered, so it would run /// on all nodes despite the intent). /// Default: true. Set to false in tests that intentionally exercise mis-wiring. /// public bool StartupChecks { get; set; } = true; /// /// Default per-exchange processing timeout applied to all routes /// that don't specify their own via .ProcessingTimeout(). /// Default: (no timeout). /// public TimeSpan DefaultProcessingTimeout { get; set; } = Timeout.InfiniteTimeSpan; /// /// Stream caching options. When is true, /// all routes automatically wrap Stream bodies with a seekable cache. /// public StreamCacheOptions StreamCaching { get; set; } = new(); /// Message attachment options (RedbRoute:Attachments). public AttachmentOptions Attachments { get; set; } = new(); /// /// Retry of a consumer that failed to start with the context (RedbRoute:ConsumerStartRetry). On by default. /// public ConsumerStartRetryOptions ConsumerStartRetry { get; set; } = new(); /// /// Reconnect of a connection lost while a route runs (RedbRoute:Reconnect), for the connectors that report their /// connections to a : pauses, the bound of one connect, the warning period. /// public ReconnectOptions Reconnect { get; set; } = new(); /// /// The profile every detached step (WireTap, asynchronous OnCompletion) builds its own pool from when /// it names none (RedbRoute:DefaultThreadPoolProfile): 20 at a time, 1000 waiting, the caller runs a branch /// that finds both full. Apache Camel's default thread pool profile. /// public ThreadPoolProfile DefaultThreadPoolProfile { get; set; } = new(); /// /// Named profiles a step picks with executorService (RedbRoute:ThreadPoolProfiles:<name>). A module /// that builds its routes in code can add its own with . /// public Dictionary ThreadPoolProfiles { get; set; } = new(StringComparer.Ordinal); } Path: redb-route/redb.Route/Configuration/StreamCacheOptions.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/Configuration/StreamCacheOptions.cs ---- namespace redb.Route.Configuration; /// /// Options for stream caching behavior. /// public sealed class StreamCacheOptions { /// Threshold in bytes before spooling from memory to a temp file. Default: 128 KB. public long SpoolThreshold { get; set; } = 128 * 1024; /// Directory for temporary spool files. Default: system temp directory. public string? TempDirectory { get; set; } /// Enable stream caching globally for all routes. Default: false. public bool Enabled { get; set; } } Path: redb-route/redb.Route/Configuration/ThreadPoolProfile.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/Configuration/ThreadPoolProfile.cs ---- namespace redb.Route.Configuration; /// /// The bounds of the pool a detached step runs on (a WireTap, an asynchronous OnCompletion), Apache /// Camel's thread pool profile. Every such step gets a pool of its own built from a profile: the context's default /// profile, or a named one the step picks with executorService. /// /// At most branches of one step run at a time and at most wait; /// a branch that finds both full is handled by . Branches are tasks, not threads: the /// limit bounds how much work a step has in flight, not how many threads it holds. /// /// public sealed class ThreadPoolProfile { /// Branches of one step that run at a time (Camel maxPoolSize). Default: 20. public int MaxConcurrency { get; set; } = 20; /// Branches of one step that wait for a free slot (Camel maxQueueSize). Default: 1000. public int MaxQueueSize { get; set; } = 1000; /// /// What a branch that finds the pool and its queue full does (Camel rejectedPolicy). Default: /// , so nothing is lost and the source slows down. /// public ThreadPoolRejectedPolicy RejectedPolicy { get; set; } = ThreadPoolRejectedPolicy.CallerRuns; /// Checks the bounds; names the profile in the message. internal void Validate(string name) { if (MaxConcurrency < 1) throw new ArgumentOutOfRangeException(nameof(MaxConcurrency), MaxConcurrency, $"Thread pool profile '{name}': MaxConcurrency must be at least 1."); if (MaxQueueSize < 0) throw new ArgumentOutOfRangeException(nameof(MaxQueueSize), MaxQueueSize, $"Thread pool profile '{name}': MaxQueueSize must not be negative."); if (!Enum.IsDefined(RejectedPolicy)) throw new ArgumentOutOfRangeException(nameof(RejectedPolicy), RejectedPolicy, $"Thread pool profile '{name}': unknown RejectedPolicy."); } /// Whether sets the same bounds. internal bool SameAs(ThreadPoolProfile other) => MaxConcurrency == other.MaxConcurrency && MaxQueueSize == other.MaxQueueSize && RejectedPolicy == other.RejectedPolicy; /// A copy, so a profile registered with a context is not changed through the caller's instance. internal ThreadPoolProfile Copy() => new() { MaxConcurrency = MaxConcurrency, MaxQueueSize = MaxQueueSize, RejectedPolicy = RejectedPolicy, }; /// public override string ToString() => $"MaxConcurrency={MaxConcurrency}, MaxQueueSize={MaxQueueSize}, RejectedPolicy={RejectedPolicy}"; } /// What a branch that finds its pool and the pool's queue full does (Camel's rejected policies). public enum ThreadPoolRejectedPolicy { /// The caller runs the branch itself before it goes on: nothing is lost, the source slows down. CallerRuns, /// The branch is dropped, counted and logged; the caller goes on at once. Discard, /// The caller's step fails with , which its route can handle. Abort, } Path: redb-route/redb.Route/ControlBus/ControlBusComponent.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/ControlBus/ControlBusComponent.cs ---- using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.ControlBus; /// The control-bus command family. public enum ControlBusCommand { /// controlbus:route — act on a route by id (Apache Camel parity). Route, /// controlbus:language:<lang> — evaluate an expression against the context (Camel parity). Language, /// controlbus:notify — consume route/context lifecycle events as messages (redb extension beyond Camel). Notify } /// Exchange header keys set by the controlbus:notify event consumer. public static class ControlBusHeaders { /// Event name: RouteStarted / RouteStopped / RouteSuspending / RouteErrored / ContextStarting / ContextStarted / ContextStopping / ContextStopped / ExchangeTimedOut / ConnectionLost / ReconnectFailed / ConnectionRestored. public const string Event = "controlbus.event"; /// Affected route id (route/exchange events; connection events of a route's consumer endpoint). public const string RouteId = "controlbus.routeId"; /// Event timestamp (UTC). public const string Timestamp = "controlbus.timestamp"; /// Error message (RouteErrored; on connection events the masked failure, absent on ConnectionRestored). public const string Error = "controlbus.error"; /// Exchange id (ExchangeTimedOut only). public const string ExchangeId = "controlbus.exchangeId"; /// Elapsed milliseconds (ExchangeTimedOut only). public const string ElapsedMs = "controlbus.elapsedMs"; /// Connection events: the endpoint whose connection changed, short form, secrets masked. public const string Endpoint = "controlbus.endpoint"; /// Connection events: which connection of the endpoint (the supervisor's name). public const string Connection = "controlbus.connection"; /// Connection events: Connected, Recovering or Disconnected after the change. public const string ConnectionState = "controlbus.connectionState"; /// Connection events: failed reconnect attempts since the loss (0 on ConnectionLost). public const string Attempt = "controlbus.attempt"; /// Connection events: milliseconds until the next attempt; absent on ConnectionRestored. public const string NextDelayMs = "controlbus.nextDelayMs"; /// Connection events: milliseconds the connection has been lost; on ConnectionRestored, how long it was. public const string OutageMs = "controlbus.outageMs"; /// Connection events: how many times this connection was restored since it started. public const string Reconnects = "controlbus.reconnects"; } /// Actions for the route command (Apache Camel parity). public enum ControlBusAction { /// Start the route. Start, /// Stop the route (consumer removed; route stays registered). Stop, /// Suspend the route. Same effect as in redb (route stays registered). Suspend, /// Resume a stopped/suspended route (policy-aware). Resume, /// Stop then start after restartDelay. Restart, /// Return the route status on the message body. Status, /// Return route statistics (all routes when routeId is omitted) on the message body. Stats, /// Stop the route and mark it failed (Errored). Fail } // ── Component ──────────────────────────────────────────────────────────────── /// /// Control Bus EIP component (Apache Camel controlbus: parity). Producer-only — you send to it /// to manage routes at runtime. Modelled on the . /// /// URI forms: /// /// controlbus:route?routeId=foo&action=start — act on a route. /// controlbus:language:simple — evaluate the message body as an expression. /// /// Parameters: routeId (or current = the sending route), action /// (start|stop|suspend|resume|restart|status|stats|fail), async (default false), restartDelay /// (ms, default 1000), loggingLevel. Registered out of the box under the controlbus scheme. /// Per-context, like Camel: for cross-context control, send over direct-vm/vm to the target /// context and run controlbus: there. /// /// public sealed class ControlBusComponent : ComponentBase { /// public override string Scheme => "controlbus"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new ControlBusEndpointOptions(); options.BindFromUri(uri.RawParameters); // Command from the URI path: "route" (default), "language[:lang]", or "notify" / "event". var path = uri.Path ?? string.Empty; if (path.StartsWith("language", StringComparison.OrdinalIgnoreCase)) { options.Command = ControlBusCommand.Language; var colon = path.IndexOf(':'); options.Language = colon >= 0 && colon + 1 < path.Length ? path[(colon + 1)..] : "simple"; } else if (path.StartsWith("notify", StringComparison.OrdinalIgnoreCase) || path.StartsWith("event", StringComparison.OrdinalIgnoreCase)) { options.Command = ControlBusCommand.Notify; } else { options.Command = ControlBusCommand.Route; } options.Validate(); return new ControlBusEndpoint(uri, this, options); } } // ── Options ────────────────────────────────────────────────────────────────── /// Options for the control-bus endpoint. public sealed class ControlBusEndpointOptions : EndpointOptions { /// Command family (set from the URI path). public ControlBusCommand Command { get; set; } = ControlBusCommand.Route; /// Target route id. current resolves to the sending route. Optional for stats. public string? RouteId { get; set; } /// Action for the route command. public ControlBusAction? Action { get; set; } /// Perform the action asynchronously (fire-and-forget). Default: false. public bool Async { get; set; } /// Delay in ms between stop and start on restart. Default: 1000. public int RestartDelay { get; set; } = 1000; /// Logging level for the action. Default: Info. public string LoggingLevel { get; set; } = "Info"; /// Expression language name for the language command (e.g. simple). public string? Language { get; set; } /// /// notify command only: comma-separated event-name filter (e.g. RouteStarted,RouteStopped). /// Empty = all events. Combine with to filter to one route. /// public string? Events { get; set; } /// public override void Validate() { switch (Command) { case ControlBusCommand.Route: if (Action is null) throw new ArgumentException("controlbus:route requires an 'action' (start|stop|suspend|resume|restart|status|stats|fail)."); // routeId is required for everything except stats (stats without routeId = whole context). if (Action != ControlBusAction.Stats && string.IsNullOrWhiteSpace(RouteId)) throw new ArgumentException($"controlbus:route action '{Action}' requires a 'routeId' (or 'current')."); break; case ControlBusCommand.Language: if (string.IsNullOrWhiteSpace(Language)) throw new ArgumentException("controlbus:language requires a language name, e.g. controlbus:language:simple."); break; case ControlBusCommand.Notify: // No required options — routeId and events are optional filters. break; } } } // ── Endpoint ───────────────────────────────────────────────────────────────── /// Endpoint that runs a control-bus action when the route sends to it. public sealed class ControlBusEndpoint : EndpointBase { private readonly ControlBusEndpointOptions _options; internal ControlBusEndpoint(EndpointUri uri, ControlBusComponent component, ControlBusEndpointOptions options) : base(uri, component, options) => _options = options; internal ControlBusEndpointOptions ControlOptions => _options; /// public override IProducer CreateProducer() => _options.Command == ControlBusCommand.Notify ? throw new NotSupportedException( "controlbus:notify is a consumer (from) — it emits lifecycle events. Use From(\"controlbus:notify\").") : new ControlBusProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) => _options.Command == ControlBusCommand.Notify ? new ControlBusEventConsumer(this, processor) : throw new NotSupportedException( "controlbus:route / controlbus:language are producer-only. Use .To(\"controlbus:...\") or .ControlBus(...); " + "to consume lifecycle events use From(\"controlbus:notify\")."); } // ── Producer ───────────────────────────────────────────────────────────────── /// Producer that dispatches the control-bus action against the route context. public sealed class ControlBusProducer : IProducer { private readonly ControlBusEndpoint _endpoint; internal ControlBusProducer(ControlBusEndpoint endpoint) => _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var context = (_endpoint.Component as ComponentBase)?.Context as RouteContext ?? throw new InvalidOperationException("Control Bus requires a RouteContext."); var o = _endpoint.ControlOptions; using var span = RouteTelemetryExtensions.StartTransportSpan( $"controlbus {o.Command}:{o.Action?.ToString() ?? o.Language}", ActivityKind.Client, "messaging.system", "controlbus", _endpoint.Uri.NormalizedKey, o.RouteId, o.Action?.ToString()); if (o.Command == ControlBusCommand.Language) { // Evaluate a ${...} template against the exchange and return the result. // Boundary vs Camel: our engine is a template evaluator, not an OGNL that can invoke // context methods; lifecycle control is done via the 'route' command above. var template = exchange.In.Body?.ToString() ?? string.Empty; exchange.In.Body = ((EndpointOptions)o).ResolveOption(template, exchange); return; } var routeId = o.RouteId; if (string.Equals(routeId, "current", StringComparison.OrdinalIgnoreCase)) routeId = exchange.RouteId; switch (o.Action) { case ControlBusAction.Status: exchange.In.Body = context.GetRoute(routeId!)?.Status.ToString() ?? "NotFound"; return; case ControlBusAction.Stats: exchange.In.Body = BuildStats(context, routeId); return; } Func op = o.Action switch { ControlBusAction.Start => () => context.StartRoute(routeId!, ct), ControlBusAction.Stop or ControlBusAction.Suspend => () => context.StopRoute(routeId!, ct), ControlBusAction.Resume => () => context.ResumeRoute(routeId!, ct), ControlBusAction.Restart => async () => { await context.StopRoute(routeId!).ConfigureAwait(false); if (o.RestartDelay > 0) await Task.Delay(o.RestartDelay).ConfigureAwait(false); await context.StartRoute(routeId!).ConfigureAwait(false); }, ControlBusAction.Fail => async () => { await context.StopRoute(routeId!).ConfigureAwait(false); if (context.GetRoute(routeId!) is { } r) r.Status = RouteStatus.Errored; }, _ => throw new InvalidOperationException($"Unsupported control-bus action '{o.Action}'.") }; // Stopping the current route synchronously would deadlock (this exchange is in-flight on it), // so self-targeting stop-like actions are always deferred, matching Camel's async guidance. var stopsRoute = o.Action is ControlBusAction.Stop or ControlBusAction.Suspend or ControlBusAction.Restart or ControlBusAction.Fail; var selfTarget = string.Equals(routeId, exchange.RouteId, StringComparison.OrdinalIgnoreCase); if (o.Async || (stopsRoute && selfTarget)) _ = Task.Run(op, CancellationToken.None); else await op().ConfigureAwait(false); } private static string BuildStats(RouteContext context, string? routeId) { var routes = routeId is null ? context.Routes : context.GetRoute(routeId) is { } one ? new[] { one } : System.Array.Empty(); var sb = new StringBuilder(); sb.Append(""); foreach (var r in routes) { sb.Append(" 0 } lastError) sb.Append(" lastError=\"").Append(Escape(lastError)).Append('"'); if (s.LastRefusalMessage is { Length: > 0 } lastRefusal) sb.Append(" lastRefusal=\"").Append(Escape(lastRefusal)).Append('"'); } sb.Append("/>"); } sb.Append(""); return sb.ToString(); } /// /// Attribute-escapes free text. Route ids and error messages are arbitrary strings; a quote or /// an angle bracket appended raw would corrupt the document for whoever parses it downstream. /// private static string Escape(string value) => System.Security.SecurityElement.Escape(value); /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } // ── Event consumer (redb extension beyond Camel) ───────────────────────────── /// /// Consumer for controlbus:notify: emits route/context lifecycle events as exchanges into the route, /// so you can react to them with the full EIP pipeline (filter, route, alert) instead of a callback. /// Backed by (redb's equivalent of Camel's EventNotifier SPI); Camel /// has no such consumer, so this goes beyond parity. Optional filters: routeId (one route) and /// events (comma-separated event names). Events are dispatched off the lifecycle-notification thread /// so a slow reaction never stalls route start/stop. /// public sealed class ControlBusEventConsumer : IConsumer, IRouteLifecycleListener { private readonly ControlBusEndpoint _endpoint; private readonly IProcessor _processor; private readonly string? _routeFilter; private readonly HashSet? _eventFilter; private readonly Microsoft.Extensions.Logging.ILogger? _logger; private int _registered; private volatile bool _active; internal ControlBusEventConsumer(ControlBusEndpoint endpoint, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); var o = endpoint.ControlOptions; _routeFilter = string.IsNullOrWhiteSpace(o.RouteId) ? null : o.RouteId; _eventFilter = string.IsNullOrWhiteSpace(o.Events) ? null : new HashSet(o.Events!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), StringComparer.OrdinalIgnoreCase); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public IEndpoint Endpoint => _endpoint; /// public Task Start(CancellationToken ct = default) { // Register with the context once (no RemoveLifecycleListener API); toggle emission with _active // so a restart does not double-register and a stop simply goes quiet. if (Interlocked.Exchange(ref _registered, 1) == 0) (_endpoint.Component as ComponentBase)?.Context?.AddLifecycleListener(this); _active = true; return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _active = false; return Task.CompletedTask; } // ── IRouteLifecycleListener → exchanges ── Task IRouteLifecycleListener.OnRouteStarted(string routeId, CancellationToken ct) { Emit("RouteStarted", routeId); return Task.CompletedTask; } Task IRouteLifecycleListener.OnRouteStopped(string routeId, CancellationToken ct) { Emit("RouteStopped", routeId); return Task.CompletedTask; } Task IRouteLifecycleListener.OnRouteSuspending(string routeId, CancellationToken ct) { Emit("RouteSuspending", routeId); return Task.CompletedTask; } Task IRouteLifecycleListener.OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { Emit("RouteErrored", routeId, m => m.Headers[ControlBusHeaders.Error] = ex.Message); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStarting(IRouteContext context, CancellationToken ct) { Emit("ContextStarting", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStarted(IRouteContext context, CancellationToken ct) { Emit("ContextStarted", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStopping(IRouteContext context, CancellationToken ct) { Emit("ContextStopping", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStopped(IRouteContext context, CancellationToken ct) { Emit("ContextStopped", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { Emit("ExchangeTimedOut", routeId, m => { m.Headers[ControlBusHeaders.ExchangeId] = exchangeId; m.Headers[ControlBusHeaders.ElapsedMs] = elapsed.TotalMilliseconds; }); return Task.CompletedTask; } Task IRouteLifecycleListener.OnConnectionEvent(ConnectionEvent e, CancellationToken ct) { var eventName = e.Kind switch { ConnectionEventKind.Lost => "ConnectionLost", ConnectionEventKind.AttemptFailed => "ReconnectFailed", _ => "ConnectionRestored", }; Emit(eventName, e.RouteId, m => { m.Headers[ControlBusHeaders.Timestamp] = e.Time; m.Headers[ControlBusHeaders.Endpoint] = e.Endpoint; m.Headers[ControlBusHeaders.Connection] = e.Connection; m.Headers[ControlBusHeaders.ConnectionState] = e.State.ToString(); m.Headers[ControlBusHeaders.Attempt] = e.Attempt; m.Headers[ControlBusHeaders.OutageMs] = e.Outage.TotalMilliseconds; m.Headers[ControlBusHeaders.Reconnects] = e.Reconnects; if (e.NextDelay is { } next) m.Headers[ControlBusHeaders.NextDelayMs] = next.TotalMilliseconds; if (e.ErrorMessage is { } error) m.Headers[ControlBusHeaders.Error] = error; }); return Task.CompletedTask; } private void Emit(string eventName, string? routeId, Action? decorate = null) { if (!_active) return; if (_eventFilter is not null && !_eventFilter.Contains(eventName)) return; // Route filter: when set, route-scoped events must match; context events (no routeId) are skipped. if (_routeFilter is not null && !string.Equals(routeId, _routeFilter, StringComparison.OrdinalIgnoreCase)) return; var message = new Message(eventName); message.Headers[ControlBusHeaders.Event] = eventName; if (routeId is not null) message.Headers[ControlBusHeaders.RouteId] = routeId; message.Headers[ControlBusHeaders.Timestamp] = DateTimeOffset.UtcNow; decorate?.Invoke(message); var exchange = Exchange.Create(message, _endpoint.ScopeFactory); // Off the lifecycle-notification thread: a slow reaction must not stall route start/stop, // and running the route pipeline reentrantly inside Start()/Stop() would be unsafe. _ = Task.Run(async () => { try { await _processor.Process(exchange).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "controlbus:notify handler failed for event {Event}", eventName); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } }); } } Path: redb-route/redb.Route/Core/AckMode.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/Core/AckMode.cs ---- namespace redb.Route.Core; /// /// When a consumer settles the message it received — acknowledges it to RabbitMQ, accepts it on AMQP, commits the /// Kafka offset, deletes it from SQS, completes it on Service Bus, XACKs the Redis stream entry. One option, /// ackMode, with the same meaning on every broker consumer. /// /// It is independent of .Transacted(): the transaction owns the database and the outgoing sends; the /// acknowledgement of the incoming message is always the consumer's, once, after the transaction has committed. /// /// public enum AckMode { /// /// Settled once the route has run: acknowledged when the exchange ended well (no exception, or one an error /// handler handled), rejected or released for redelivery when it failed. At-least-once. The default. /// Manual, /// /// Settled on receipt, before the route runs — by the broker (RabbitMQ auto-ack, Service Bus receive-and-delete, /// Redis NOACK) or by the consumer right away (AMQP accept, Kafka offset, SQS delete). A message whose route then /// fails is not delivered again. At-most-once. /// Auto, } Path: redb-route/redb.Route/Core/BackoffSchedule.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/Core/BackoffSchedule.cs ---- namespace redb.Route.Core; /// /// A pause that grows after each failed attempt: , then multiplied by each /// time, never longer than . Shared by the start retry of a consumer /// () and the reconnect of a lost connection /// (), so both count their pauses the same way. /// internal readonly record struct BackoffSchedule(TimeSpan First, double Multiplier, TimeSpan Max) { /// The pause after has passed and the attempt after it failed too. public TimeSpan Next(TimeSpan current) => TimeSpan.FromTicks((long)Math.Min(current.Ticks * Multiplier, Max.Ticks)); /// /// Checks the three values of a schedule configured under ; the messages name the /// configuration key (ConsumerStartRetry.Delay, Reconnect.MaxDelay). /// public static void Validate(string section, TimeSpan first, double multiplier, TimeSpan max) { if (first <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("Delay", first, $"{section}.Delay must be positive."); if (max < first) throw new ArgumentOutOfRangeException("MaxDelay", max, $"{section}.MaxDelay must not be shorter than Delay."); if (max.TotalMilliseconds > int.MaxValue) throw new ArgumentOutOfRangeException("MaxDelay", max, $"{section}.MaxDelay must not exceed 24 days."); if (double.IsNaN(multiplier) || multiplier < 1.0) throw new ArgumentOutOfRangeException("Multiplier", multiplier, $"{section}.Multiplier must be 1 or more."); } } Path: redb-route/redb.Route/Core/BodyText.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/Core/BodyText.cs ---- using System.Collections; using System.Collections.Concurrent; namespace redb.Route.Core; /// /// The text a producer sends for a body: text as it is, bytes and a stream as UTF-8 text (as Camel converts them), any /// other body its own ToString(). A body without a text form of its own, whose ToString() is only its type name (a list, /// an object that does not override it), is refused instead of sending that name, the way Apache Camel's type /// conversion fails for a body it cannot convert. /// public static class BodyText { private static readonly ConcurrentDictionary OwnToString = new(); /// Whether writes itself as text (overrides ToString()). public static bool HasOwnText(object body) { ArgumentNullException.ThrowIfNull(body); return OwnToString.GetOrAdd(body.GetType(), static type => type.GetMethod(nameof(ToString), Type.EmptyTypes)?.DeclaringType != typeof(object)); } /// /// The body's own text, or a refusal naming the endpoint (sanitized by the caller) and the body's type when its text /// would be the type name. /// public static string Of(object body, string? endpoint = null) { ArgumentNullException.ThrowIfNull(body); switch (body) { case string text: return text; case byte[] bytes: return System.Text.Encoding.UTF8.GetString(bytes); case ReadOnlyMemory memory: return System.Text.Encoding.UTF8.GetString(memory.Span); case Stream stream: // As Camel's InputStream-to-String conversion: the stream's content as UTF-8 text, read to its end. if (stream.CanSeek) stream.Position = 0; using (var reader = new StreamReader(stream, System.Text.Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true)) return reader.ReadToEnd(); } if (HasOwnText(body)) return body.ToString() ?? string.Empty; var where = endpoint is null ? "This endpoint" : $"Endpoint '{endpoint}'"; throw body is IEnumerable ? new InvalidOperationException( $"{where} cannot send a body of type {body.GetType().Name}: a list has no wire form here, and its text " + "would be the type name. Serialize the list (to JSON, for example), or Split it.") : new InvalidOperationException( $"{where} cannot send a body of type {body.GetType().Name}: it has no text form of its own, and its text " + "would be the type name. Convert it before the send (Marshal, ConvertBody, a Process step)."); } } Path: redb-route/redb.Route/Core/CollectibleContextCleanup.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/Core/CollectibleContextCleanup.cs ---- using System.Reflection; using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.Loader; using Microsoft.Extensions.Logging; namespace redb.Route.Core; /// /// Lets a collectible go when it unloads (a host's module or plugin): the caches the /// .NET libraries keep over the types they handled drop that context's types. The caches of redb.Route keyed by type /// hold their key weakly and need nothing here. The same cleanup as redb.Core's, for hosts of redb.Route without it; /// with both in the process each runs once per unload, which costs one more emptying of those caches. /// /// Every collectible context is watched from the moment one of its assemblies loads (and the ones that existed before /// this class first ran are picked up then), so the hot path pays nothing: the work happens once per unload, in /// , which Unload() raises before the context can be collected. /// /// internal static class CollectibleContextCleanup { private static readonly ConditionalWeakTable Watched = new(); private static readonly object Marker = new(); private static int _started; private static int _noHandlersReported; private static ILogger? _logger; /// /// Starts watching collectible contexts; called by every route context and by the serializers that build metadata /// over message types. The first logger handed over reports the cleanup. /// public static void EnsureWatching(ILogger? logger = null) { if (logger != null) Interlocked.CompareExchange(ref _logger, logger, null); if (Interlocked.Exchange(ref _started, 1) == 1) return; AppDomain.CurrentDomain.AssemblyLoad += static (_, e) => Watch(e.LoadedAssembly); foreach (var context in AssemblyLoadContext.All) if (context.IsCollectible) Watch(context); } private static void Watch(Assembly assembly) { if (assembly.IsCollectible && AssemblyLoadContext.GetLoadContext(assembly) is { } context) Watch(context); } private static void Watch(AssemblyLoadContext context) { if (Watched.TryAdd(context, Marker)) context.Unloading += OnUnloading; } private static void OnUnloading(AssemblyLoadContext context) { context.Unloading -= OnUnloading; ClearMetadataUpdateCaches(context); } /// /// The libraries of .NET keep process-wide caches built over the types they handled, and do not let a collectible /// context go while one of its types is in them: System.Text.Json above all (metadata in every options instance, /// the static options of the JSON serializer of redb.Route included, and emitted member accessors), TypeDescriptor /// and others. They declare a handler for hot reload () whose /// ClearCache empties those caches; redb.Route calls ClearCache(null) of every handler declared by a /// loaded assembly, as dotnet watch does, once per unload. The assemblies of the unloading context are left /// out. Unloadable assemblies are not supported by System.Text.Json otherwise: /// https://github.com/dotnet/runtime/issues/65323. Costs cold caches in those libraries for what follows, once per /// unload. /// internal static int ClearMetadataUpdateCaches(AssemblyLoadContext unloading) { var found = 0; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.IsDynamic || AssemblyLoadContext.GetLoadContext(assembly) == unloading) continue; MetadataUpdateHandlerAttribute[] handlers; try { handlers = (MetadataUpdateHandlerAttribute[])assembly.GetCustomAttributes(typeof(MetadataUpdateHandlerAttribute), false); } catch (Exception ex) { _logger?.LogWarning(ex, "Unloading context {Context}: cannot read the hot reload handlers of {Assembly}", unloading.Name, assembly.FullName); continue; } foreach (var handler in handlers) { var clearCache = handler.HandlerType.GetMethod("ClearCache", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, [typeof(Type[])]); if (clearCache == null) continue; found++; try { clearCache.Invoke(null, [null]); } catch (Exception ex) { _logger?.LogWarning(ex, "Unloading context {Context}: ClearCache of {Handler} failed, the other caches are cleared", unloading.Name, handler.HandlerType.FullName); } } } if (found == 0 && Interlocked.Exchange(ref _noHandlersReported, 1) == 0) _logger?.LogWarning( "Unloading context {Context}: no loaded assembly declares a hot reload cache handler; caches of the .NET " + "libraries (System.Text.Json among them) may keep the context alive", unloading.Name); return found; } /// For tests: whether is watched. internal static bool IsWatched(AssemblyLoadContext context) => Watched.TryGetValue(context, out _); } Path: redb-route/redb.Route/Core/CollectibleTypeServiceProvider.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/Core/CollectibleTypeServiceProvider.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace redb.Route.Core; /// /// The service provider gets when redb.Route builds a bean or a component: the host's /// provider, except for a service type that involves a type of a collectible load context (a module's own type, or a /// generic closed over one, such as ILogger<TheModulesBean>). /// /// The container of Microsoft.Extensions.DependencyInjection keeps every service type it was asked for, found or not, /// for as long as it lives. The host's container lives as long as the process, so one question about /// ILogger<T> of a module's type kept the module's load context in memory after its unload. Such a type /// cannot be registered in the host's container, which was built before the module loaded, so the question never goes /// there. What the host's open generic registrations would answer is built here instead: ILogger<T> from the /// host's ; IOptions<T>, IOptionsSnapshot<T>, /// IOptionsMonitor<T>, IOptionsFactory<T> and IOptionsMonitorCache<T> over the type's /// default instance, since nothing in the host configures a module's type; an empty IEnumerable<T>. /// Anything else over a module's type is not a service. /// /// internal sealed class CollectibleTypeServiceProvider : IServiceProvider, IServiceProviderIsKeyedService, IKeyedServiceProvider { private readonly IServiceProvider _host; private CollectibleTypeServiceProvider(IServiceProvider host) => _host = host; /// The provider to hand instead of . internal static IServiceProvider For(IServiceProvider host) => host as CollectibleTypeServiceProvider ?? new CollectibleTypeServiceProvider(host); public object? GetService(Type serviceType) { if (serviceType == typeof(IServiceProviderIsService) || serviceType == typeof(IServiceProviderIsKeyedService)) return _host.GetService(serviceType) is null ? null : this; if (!InvolvesCollectible(serviceType)) return _host.GetService(serviceType); if (!serviceType.IsGenericType) return null; var definition = serviceType.GetGenericTypeDefinition(); var argument = serviceType.GetGenericArguments()[0]; if (definition == typeof(ILogger<>)) return _host.GetService(typeof(ILoggerFactory)) is ILoggerFactory factory ? Activator.CreateInstance(typeof(Logger<>).MakeGenericType(argument), factory) : null; if (definition == typeof(IEnumerable<>)) return Array.CreateInstance(argument, 0); if (OptionsServices.Contains(definition)) return DefaultOptions(definition, argument); return null; } /// The options services the host registers as open generics (AddOptions). private static readonly HashSet OptionsServices = [ typeof(IOptions<>), typeof(IOptionsSnapshot<>), typeof(IOptionsMonitor<>), typeof(IOptionsFactory<>), typeof(IOptionsMonitorCache<>), ]; /// /// What the host's options services would answer for a module's type: nothing in the host configures it (the host /// was built before the module loaded), so the value is the type's default instance. Built here, as the host's /// open generic registrations build it, over empty configure, post-configure and change-token lists. /// private static object? DefaultOptions(Type definition, Type options) { Type Closed(Type open) => open.MakeGenericType(options); object Empty(Type open) => Array.CreateInstance(Closed(open), 0); try { if (definition == typeof(IOptionsMonitorCache<>)) return Activator.CreateInstance(Closed(typeof(OptionsCache<>))); var factory = Activator.CreateInstance(Closed(typeof(OptionsFactory<>)), Empty(typeof(IConfigureOptions<>)), Empty(typeof(IPostConfigureOptions<>)))!; if (definition == typeof(IOptionsFactory<>)) return factory; if (definition == typeof(IOptionsMonitor<>)) return Activator.CreateInstance(Closed(typeof(OptionsMonitor<>)), factory, Empty(typeof(IOptionsChangeTokenSource<>)), Activator.CreateInstance(Closed(typeof(OptionsCache<>)))); return Activator.CreateInstance(Closed(typeof(OptionsManager<>)), factory); // IOptions, IOptionsSnapshot } catch (ArgumentException) { return null; // not an options type (a struct): the host could not build it either } } public bool IsService(Type serviceType) { if (!InvolvesCollectible(serviceType)) return _host.GetService(typeof(IServiceProviderIsService)) is IServiceProviderIsService host && host.IsService(serviceType); if (!serviceType.IsGenericType) return false; var definition = serviceType.GetGenericTypeDefinition(); return definition == typeof(IEnumerable<>) || OptionsServices.Contains(definition) || (definition == typeof(ILogger<>) && _host.GetService(typeof(ILoggerFactory)) is not null); } public bool IsKeyedService(Type serviceType, object? serviceKey) => !InvolvesCollectible(serviceType) && _host.GetService(typeof(IServiceProviderIsKeyedService)) is IServiceProviderIsKeyedService host && host.IsKeyedService(serviceType, serviceKey); public object? GetKeyedService(Type serviceType, object? serviceKey) => !InvolvesCollectible(serviceType) && _host is IKeyedServiceProvider keyed ? keyed.GetKeyedService(serviceType, serviceKey) : null; public object GetRequiredKeyedService(Type serviceType, object? serviceKey) { if (!InvolvesCollectible(serviceType) && _host is IKeyedServiceProvider keyed) return keyed.GetRequiredKeyedService(serviceType, serviceKey); throw new InvalidOperationException( $"No keyed service for type '{serviceType}' has been registered: the host's container cannot hold a type of a collectible module."); } /// Whether is, or is built over, a type of a collectible load context. internal static bool InvolvesCollectible(Type type) { if (type.HasElementType) return InvolvesCollectible(type.GetElementType()!); if (type.Assembly.IsCollectible) return true; return type.IsGenericType && !type.IsGenericTypeDefinition && type.GetGenericArguments().Any(InvolvesCollectible); } } Path: redb-route/redb.Route/Core/CompiledRoute.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/Core/CompiledRoute.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Core; /// /// Represents a compiled route with lifecycle state (v2 — backed by the /// canonical ProcessorDefinition tree). /// public sealed class CompiledRoute { /// Creates a compiled route. public CompiledRoute( string routeId, string fromUri, IRouteDefinition definition, IProcessor pipeline, IConsumer consumer, IEndpoint endpoint) { RouteId = routeId; FromUri = fromUri; Definition = definition; Pipeline = pipeline; Consumer = consumer; Endpoint = endpoint; } /// Route identifier. public string RouteId { get; } /// /// Source endpoint URI, with secrets redacted (passwords, tokens, keys, and userinfo /// passwords masked to ****). Safe to log, expose via health checks, and render /// in dashboards. This is a display value — it is NOT byte-identical to the original URI /// and must not be re-parsed to recover connection credentials. /// public string FromUri { get; } /// Original route definition (v2 tree). public IRouteDefinition Definition { get; } /// Compiled processor pipeline (root of the route's processor tree). public IProcessor Pipeline { get; } /// The consumer instance. public IConsumer Consumer { get; } /// The source endpoint. public IEndpoint Endpoint { get; } /// /// Whether this route should auto-start when the context starts. /// Can be overridden at runtime (e.g., by Tsak StateStore). /// public bool AutoStart { get; set; } = true; /// Route policy for lifecycle control, or null if none assigned. public IRoutePolicy? Policy { get; internal set; } /// /// Effective cluster-policy resolution captured at compile time. Never null; /// reports "AllNodes" when no policy was attached. /// public RoutePolicyDescriptor PolicyDescriptor { get; internal set; } = new(false, "AllNodes", null, "No policy attached"); /// Current route status. Defaults to Stopped until started by the context. public RouteStatus Status { get; internal set; } = RouteStatus.Stopped; } Path: redb-route/redb.Route/Core/ComponentBase.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/Core/ComponentBase.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Base class for components. Provides scheme registration and endpoint creation contract. /// Components MAY hold long-lived resources (connection pools, broker sessions); /// override to release them when shuts down. /// public abstract class ComponentBase : IComponent, IAsyncDisposable { /// public abstract string Scheme { get; } /// public virtual IReadOnlyList AlternateSchemes => []; /// /// Route context that owns this component. Set automatically by . /// Used by transport endpoints to resolve named connection factories from the registry. /// public IRouteContext? Context { get; internal set; } /// /// Logger for the component. Set automatically by /// from the context's . /// public ILogger? Logger { get; internal set; } /// public abstract IEndpoint CreateEndpoint(EndpointUri uri); /// /// Optional one-line path synonym for the structured XML form: /// kafka → topic, rabbitmq → queue, file → directory. Read by the XML /// loader, the component catalog and the generated schema — never from a hand-kept list. /// A component without an override is addressed by the universal path attribute. /// public virtual string? StructuredPathSynonym => null; /// /// The path part of this component's URIs is a text body (sql: the query). The structured /// XML form then reads the path from the element's content (CDATA) rather than an attribute. /// public virtual bool PathIsText => false; /// /// Releases component-owned long-lived resources. Default implementation is a no-op. /// Override in subclasses that hold connection pools, broker sessions, etc. /// Called by . /// public virtual ValueTask DisposeAsync() => ValueTask.CompletedTask; } Path: redb-route/redb.Route/Core/ConcurrencyOption.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/Core/ConcurrencyOption.cs ---- using System.Globalization; namespace redb.Route.Core; /// /// One resolver for every consumer-concurrency option that accepts auto. The industry default /// for broker consumers is 1 — ordering is preserved and handlers need not be thread-safe (Camel /// JMS/SQS, Spring, the Azure SDK all ship 1) — so the default stays 1 and parallelism is an explicit /// opt-in: a number, or auto = max(CPU count, 2), the NServiceBus formula. /// /// The option is a string because it accepts the word auto beside a number, which an int /// property cannot hold. The string binds verbatim and this resolver fails loud on anything that is /// neither a positive integer nor auto. /// /// public static class ConcurrencyOption { /// The value auto resolves to: max(logical CPU count, 2). public static int Auto => Math.Max(Environment.ProcessorCount, 2); /// /// Resolves a raw option value: null/empty → , an integer ≥ 1 → /// itself, auto (case-insensitive) → ; anything else throws, naming /// the option and the valid values. /// public static int Resolve(string? raw, string optionName, int defaultValue = 1) { if (string.IsNullOrWhiteSpace(raw)) return defaultValue; var value = raw.Trim(); if (value.Equals("auto", StringComparison.OrdinalIgnoreCase)) return Auto; if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) && n >= 1) return n; throw new ArgumentException( $"Invalid value '{raw}' for option '{optionName}'. " + "Valid values: an integer >= 1, or 'auto' (= max(CPU count, 2))."); } } Path: redb-route/redb.Route/Core/ConnectableProducer.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/Core/ConnectableProducer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Base class for connection-based producers. /// Handles: started guard, logger resolution, Start/Stop lifecycle. /// Subclasses implement and optionally override . /// public abstract class ConnectableProducer : IProducer { private int _started; // 0 = stopped, 1 = fully started (ConnectAsync completed) private readonly object _startLock = new(); private Task? _startTask; private ILogger? _logger; /// The endpoint this producer sends to. protected abstract IEndpoint ProducerEndpoint { get; } /// Display name for logging (e.g. "http:https://api.example.com", "kafka:orders"). protected abstract string ProducerName { get; } /// Logger resolved from the component. protected ILogger? Logger => _logger ??= (ProducerEndpoint.Component as ComponentBase)?.Logger; /// Whether the producer has been started. public bool IsStarted => Volatile.Read(ref _started) == 1; // ── IProducer lifecycle ── /// public Task Start(CancellationToken ct = default) { // Single-flight: the first caller creates the start task; concurrent callers await the SAME // task rather than each starting their own. Crucially, IsStarted flips to true only AFTER // ConnectAsync completes (see StartCoreAsync), so a racing Process()/EnsureStarted() can never // observe a half-initialised producer (e.g. a Redis producer whose _db is not yet assigned). lock (_startLock) { return _startTask ??= StartCoreAsync(ct); } } private async Task StartCoreAsync(CancellationToken ct) { try { await ConnectAsync(ct).ConfigureAwait(false); Volatile.Write(ref _started, 1); // observable as started ONLY now that resources are ready Logger?.LogInformation("{Producer} started.", EndpointUri.ForLog(ProducerName, Logger)); } catch { // Let a later Start() retry a failed cold start instead of caching the failure forever. lock (_startLock) { _startTask = null; } throw; } } /// public async Task Stop(CancellationToken ct = default) { Task? startInFlight; lock (_startLock) { startInFlight = _startTask; _startTask = null; } if (startInFlight is null) return; // never started // Let a concurrent start settle before tearing down (ignore its failure — nothing connected). try { await startInFlight.ConfigureAwait(false); } catch { /* start failed */ } if (Interlocked.CompareExchange(ref _started, 0, 1) != 1) return; // A reconnect in flight finishes first, so a connection it opens is closed here rather than left open after the // stop; a send that waits for one finds the producer stopped. await _reconnectLock.WaitAsync(CancellationToken.None).ConfigureAwait(false); try { await DisconnectAsync(ct).ConfigureAwait(false); } finally { _reconnectLock.Release(); } ReleaseSupervisor(); Logger?.LogInformation("{Producer} stopped.", EndpointUri.ForLog(ProducerName, Logger)); } // ── Lost connection ── private ConnectionSupervisor? _supervisor; private readonly object _supervisorLock = new(); private readonly SemaphoreSlim _reconnectLock = new(1, 1); /// /// The supervisor of this producer's connection, created on first use with the context's reconnect options /// (RedbRoute:Reconnect) and registered with the endpoint, so a lost connection shows in the endpoint's health. /// A producer that never calls behaves as before; a stop removes the supervisor. /// protected ConnectionSupervisor Supervisor { get { lock (_supervisorLock) { return _supervisor ??= ProducerEndpoint is ISupervisingEndpoint endpoint ? endpoint.Supervise(ProducerName, Logger) : new ConnectionSupervisor(ProducerName, new Configuration.ReconnectOptions(), Logger); } } } /// /// Reports that the connection is lost: from a send, a reply loop, a transacted action's commit or a client callback. /// The first report of a loss calls , so the producer fails what waits on the connection /// once; the next reconnects. Nothing is sent again: a send that failed this way may /// or may not have arrived. /// protected internal void MarkConnectionLost(Exception cause) { if (Supervisor.Lost(cause)) OnConnectionLost(cause); } /// Fails what waits on the lost connection, such as pending request-reply calls. Default: nothing. protected virtual void OnConnectionLost(Exception cause) { } /// /// Called by before it sends: when the connection was marked lost, either fails at once while /// the next attempt is not due yet ("the next reconnect attempt is due in N s"), or runs /// and again, one caller at a time; concurrent sends wait for that attempt. A failed attempt /// grows the pause; a successful one reports the connection restored. Returns at once while connected. /// protected async Task EnsureConnectedAsync(CancellationToken ct) { var supervisor = Volatile.Read(ref _supervisor); if (supervisor is null || supervisor.State == ConnectionState.Connected) return; await _reconnectLock.WaitAsync(ct).ConfigureAwait(false); try { EnsureStarted(); // stopped while this send waited: no reconnect behind the stop if (supervisor.State == ConnectionState.Connected) return; var dueIn = supervisor.DueIn; if (dueIn > TimeSpan.Zero) throw new InvalidOperationException( $"{ProducerName}: the connection was lost; the next reconnect attempt is due in {ConnectionSupervisor.FormatDuration(dueIn)}." + (supervisor.LastFailure is { Length: > 0 } failure ? $" Last failure: {failure}" : string.Empty)); await DisconnectAsync(CancellationToken.None).ConfigureAwait(false); try { await ConnectAsync(ct).ConfigureAwait(false); } catch (Exception ex) { await DisconnectAsync(CancellationToken.None).ConfigureAwait(false); if (ex is not OperationCanceledException || !ct.IsCancellationRequested) supervisor.Failed(ex); throw; } supervisor.Restored(); } finally { _reconnectLock.Release(); } } private void ReleaseSupervisor() { ConnectionSupervisor? supervisor; lock (_supervisorLock) { supervisor = _supervisor; _supervisor = null; } if (supervisor is not null && ProducerEndpoint is ISupervisingEndpoint endpoint) endpoint.Unsupervise(supervisor); } // ── Abstract / virtual hooks ── /// /// Set up connection/resources. Awaited by Start() to completion before IsStarted flips to /// true, so subclasses may assign their fields here knowing no Process() can run until it returns. /// protected abstract Task ConnectAsync(CancellationToken ct); /// Tear down connection/resources. Called from Stop() after the started flag is cleared. protected virtual Task DisconnectAsync(CancellationToken ct) => Task.CompletedTask; /// public abstract Task Process(IExchange exchange, CancellationToken ct = default); /// Throws if the producer has not been started. protected void EnsureStarted() { if (!IsStarted) throw new InvalidOperationException($"{ProducerName} has not been started. Call Start() first."); } } Path: redb-route/redb.Route/Core/ConnectionEvent.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/Core/ConnectionEvent.cs ---- namespace redb.Route.Core; /// What changed in a supervised connection. public enum ConnectionEventKind { /// The connection was lost. Lost, /// An attempt to restore it failed. AttemptFailed, /// It was restored. Restored, } /// /// One change of a supervised connection: lost, a reconnect attempt failed, restored. A /// reports it; the route context hands it to every /// and, as the events ConnectionLost, /// ReconnectFailed and ConnectionRestored, to the routes that read controlbus:notify. Listeners get /// it from a queue, after the change: what they do cannot hold up or break the reconnect. /// /// What changed. /// The supervisor's name: which connection or link. /// The state after the change. /// The exception of the loss or of the failed attempt; null on . /// Failed attempts since the loss; 0 on . /// Time until the next attempt; null on . /// How long the connection has been lost; on , how long it was. /// Losses this supervisor recovered from, this one included when restored. /// When the change happened. public sealed record ConnectionEvent( ConnectionEventKind Kind, string Connection, ConnectionState State, Exception? Error, int Attempt, TimeSpan? NextDelay, TimeSpan Outage, long Reconnects, DateTimeOffset Time) { /// The endpoint the connection belongs to, in its short form with secrets masked. public string Endpoint { get; init; } = string.Empty; /// The route that reads from the endpoint; null for a producer, or when several routes share it. public string? RouteId { get; init; } /// The message of with secrets masked, as the log and the health reason show it. public string? ErrorMessage { get; init; } } /// /// Receives the changes of a . is called on the thread that reported /// the change, under the supervisor's lock, so the changes of one connection arrive in their order: it must return at /// once, never throw and never call back into the supervisor. /// internal interface IConnectionEventSink { /// Takes one change; returns at once. void Post(ConnectionEvent change); } Path: redb-route/redb.Route/Core/ConnectionEventDispatcher.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/Core/ConnectionEventDispatcher.cs ---- using System.Threading.Channels; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// The route context's queue of connection events: supervisors post into it and return at once, one background reader /// hands the events, in order, to the lifecycle listeners. The queue is bounded: when listeners fall so far behind that /// it is full, the oldest event is dropped, counted, and one warning line says so; a reconnect loop never waits for it. /// internal sealed class ConnectionEventDispatcher { /// How many events wait at most for slow listeners. internal const int Capacity = 1024; private readonly Channel _queue; private readonly Func _deliver; private readonly ILogger? _logger; private readonly object _readerLock = new(); private Task? _reader; private long _dropped; private int _dropWarned; /// Hands one event to the listeners; its errors are logged, the reader goes on. /// Logger for dropped events and delivery errors. public ConnectionEventDispatcher(Func deliver, ILogger? logger) { _deliver = deliver; _logger = logger; _queue = Channel.CreateBounded( new BoundedChannelOptions(Capacity) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }, _ => OnDropped()); } /// The background reader, once the first event started it; it completes after . internal Task? Reader => Volatile.Read(ref _reader); /// Events dropped because the queue was full. public long Dropped => Interlocked.Read(ref _dropped); /// Queues one event and returns at once; the reader starts with the first event. public void Post(ConnectionEvent change) { if (!_queue.Writer.TryWrite(change)) return; // completed: the context is disposed if (Volatile.Read(ref _reader) is null) { lock (_readerLock) _reader ??= Task.Run(ReadAsync); } } /// Ends the queue: the reader delivers what is queued and stops. public void Complete() => _queue.Writer.TryComplete(); private async Task ReadAsync() { await foreach (var change in _queue.Reader.ReadAllAsync().ConfigureAwait(false)) { try { await _deliver(change).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogError(ex, "Delivering the connection event {Kind} of {Connection} failed", change.Kind, change.Connection); } } } private void OnDropped() { Interlocked.Increment(ref _dropped); if (Interlocked.Exchange(ref _dropWarned, 1) == 0) _logger?.LogWarning( "Connection events are dropped: lifecycle listeners fall behind and {Capacity} events wait already. " + "The oldest are dropped; reconnects go on.", Capacity); } } /// /// The event sink an endpoint gives its supervisors: stamps the endpoint on each event and passes it to the context. /// internal sealed class EndpointConnectionEventSink(RouteContext context, IEndpoint endpoint, string endpointName) : IConnectionEventSink { public void Post(ConnectionEvent change) => context.PostConnectionEvent(change with { Endpoint = endpointName }, endpoint); } Path: redb-route/redb.Route/Core/ConnectionParameterAttribute.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/Core/ConnectionParameterAttribute.cs ---- namespace redb.Route.Core; /// /// Declares that a named connection factory sets this option: it describes the connection (host, credentials, TLS, /// timeouts), not the endpoint. A factory is the whole connection, as in Camel ("all connection options set on URI are /// not used"), so this option written in a URI beside the factory /// reference would be ignored and send the route elsewhere than written; the core refuses it when the options are /// bound (). Tooling reads the declaration by reflection. /// [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public sealed class ConnectionParameterAttribute : Attribute; /// /// Marks the option that names a registered connection factory (usually connectionFactory). An options type /// that declares options declares exactly one of these: the core does not /// guess which option names the factory. It is a too: the value names a /// registry object. /// /// The type the registry object must have, or null when the option does not say. [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public sealed class ConnectionFactoryReferenceAttribute(Type? expected = null) : RegistryReferenceAttribute(expected); /// /// Declares that the option's value names an object in the context registry (connectionFactory=main, /// headerFilterStrategy=#filter; the # is optional, the lookup strips it). The engine resolves the name /// where the endpoint is built; tooling reads the declaration by reflection: the component catalog writes it as the /// option's reference, and the package gate holds the name against the beans the package declares. /// /// The type the registry object must have, or null when the option does not say. [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public class RegistryReferenceAttribute(Type? expected = null) : Attribute { /// The type the registry object must have, or null when the option does not say. public Type? Expected { get; } = expected; } Path: redb-route/redb.Route/Core/ConnectionState.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/Core/ConnectionState.cs ---- namespace redb.Route.Core; /// The state of one connection or link a watches. public enum ConnectionState { /// Connected, or not connected yet: the first connect is the start's business, not the supervisor's. Connected, /// /// Lost, and no attempt has failed yet (or the loss is younger than ). /// The endpoint's health is Warning. /// Recovering, /// Lost, and an attempt failed (or the warning period passed). The endpoint's health is Critical. Disconnected, } Path: redb-route/redb.Route/Core/ConnectionSupervisor.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/Core/ConnectionSupervisor.cs ---- using System.Globalization; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Configuration; namespace redb.Route.Core; /// /// Watches one connection or link of a consumer or a producer while its route runs. The connector reports what /// happens (, , ); the supervisor keeps the /// , the pause before the next attempt (), one log line when the /// connection is lost and one when it comes back, the count of recoveries, and the health it gives its endpoint /// (). A connector that restores the connection itself runs ; one whose /// client restores it only reports. /// /// Thread-safe. The read members (, , ) take no lock and do no /// I/O, so health checks read them on every probe. /// /// public sealed class ConnectionSupervisor { private readonly ReconnectOptions _options; private readonly BackoffSchedule _schedule; private readonly ILogger? _logger; private readonly TimeProvider _time; private readonly object _gate = new(); // Written under _gate; read without it (health probes), each field on its own. private volatile ConnectionState _state = ConnectionState.Connected; private volatile string? _lastFailure; private long _lostAtTicks; private long _nextAttemptTicks; private int _attempt; private long _reconnects; private TimeSpan _delay; // Set by the endpoint the supervisor is registered with (EndpointBase.Supervise). private Func? _mask; private Action? _recordReconnect; /// Creates a supervisor. /// /// What is supervised, for the log lines and the health reason: wmq:ORDERS consumer worker 2, /// wmq:ORDERS reply receiver. /// /// The pauses, the bound of one connect and the warning period. /// Logger for the loss and recovery lines; failed attempts log at debug level. /// Clock and timers; when null. public ConnectionSupervisor(string name, ReconnectOptions options, ILogger? logger, TimeProvider? time = null) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(options); options.Validate(); Name = name; _options = options; _schedule = options.Schedule; _logger = logger; _time = time ?? TimeProvider.System; _delay = _schedule.First; } /// What is supervised. public string Name { get; } /// /// The state now. A loss reads until an attempt fails, or, with a /// , until the loss is older than it. /// public ConnectionState State { get { var state = _state; if (state == ConnectionState.Recovering && _options.WarningPeriod > TimeSpan.Zero && Outage >= _options.WarningPeriod) return ConnectionState.Disconnected; return state; } } /// The message of the loss or of the last failed attempt, masked as the endpoint masks its errors. public string? LastFailure => _lastFailure; /// Time until the next attempt is due; zero when one may run now, and while connected. public TimeSpan DueIn { get { if (_state == ConnectionState.Connected) return TimeSpan.Zero; var left = Interlocked.Read(ref _nextAttemptTicks) - _time.GetUtcNow().UtcTicks; return left > 0 ? TimeSpan.FromTicks(left) : TimeSpan.Zero; } } /// Losses recovered from since the supervisor was created. public long Reconnects => Interlocked.Read(ref _reconnects); /// How long the current loss has lasted; zero while connected. public TimeSpan Outage { get { if (_state == ConnectionState.Connected) return TimeSpan.Zero; var lost = Interlocked.Read(ref _lostAtTicks); var now = _time.GetUtcNow().UtcTicks; return now > lost ? TimeSpan.FromTicks(now - lost) : TimeSpan.Zero; } } /// /// The health this connection gives its endpoint: null while connected, Warning while /// , Critical while . /// public (EndpointHealthStatus Status, string Reason)? Condition { get { var state = State; if (state == ConnectionState.Connected) return null; var outage = FormatDuration(Outage); var failure = _lastFailure is { Length: > 0 } f ? $": {f}" : string.Empty; if (state == ConnectionState.Recovering) return (EndpointHealthStatus.Warning, $"{Name}: connection lost {outage} ago, reconnecting{failure}"); return (EndpointHealthStatus.Critical, $"{Name}: no connection for {outage}, next attempt in {FormatDuration(DueIn)}{failure}"); } } /// /// Receives every change (seam for listeners of connection changes); null sends them nowhere. Its /// must return at once. /// internal IConnectionEventSink? EventSink { get; set; } /// /// Reports that the connection is lost. The first report after logs one /// warning, records the error on the endpoint and starts the schedule: the first attempt is due /// from now. Further reports while lost only replace . /// /// /// true for the report that changed the state, so the caller fails the work that waits on the connection /// once and starts one reconnect. /// public bool Lost(Exception cause) { ArgumentNullException.ThrowIfNull(cause); ConnectionEvent change; lock (_gate) { _lastFailure = Mask(cause.Message); if (_state != ConnectionState.Connected) return false; var now = _time.GetUtcNow().UtcTicks; _delay = _schedule.First; _attempt = 0; Interlocked.Exchange(ref _lostAtTicks, now); Interlocked.Exchange(ref _nextAttemptTicks, now + _delay.Ticks); _state = ConnectionState.Recovering; change = Change(ConnectionEventKind.Lost, cause, _delay); // Posted under the gate: the events of one connection reach the sink in the order of the changes. EventSink?.Post(change); } _logger?.LogWarning("{Connection} lost its connection: {Reason}; reconnecting", Name, change.ErrorMessage); return true; } /// /// Reports that an attempt failed: the next one is due after a pause grown by , /// up to , and the state is (with a /// warning period, once the loss is older than it). Logged at debug level, so a long outage writes two lines. /// Ignored while connected. /// public void Failed(Exception cause) { ArgumentNullException.ThrowIfNull(cause); ConnectionEvent change; TimeSpan delay; int attempt; lock (_gate) { if (_state == ConnectionState.Connected) return; _lastFailure = Mask(cause.Message); attempt = ++_attempt; // The pause before the first attempt was Delay (set by Lost); each failure grows it: 1, 2, 4 ... MaxDelay. delay = _delay = _schedule.Next(_delay); Interlocked.Exchange(ref _nextAttemptTicks, _time.GetUtcNow().UtcTicks + delay.Ticks); if (_options.WarningPeriod <= TimeSpan.Zero || Outage >= _options.WarningPeriod) _state = ConnectionState.Disconnected; change = Change(ConnectionEventKind.AttemptFailed, cause, delay); EventSink?.Post(change); } _logger?.LogDebug("{Connection} reconnect attempt {Attempt} failed: {Reason}; next attempt in {Delay}", Name, attempt, change.ErrorMessage, FormatDuration(delay)); } /// /// Reports that the connection is back: logs one information line with the length of the outage, counts the /// recovery and resets the schedule. Ignored while connected. /// public void Restored() { ConnectionEvent change; TimeSpan outage; lock (_gate) { if (_state == ConnectionState.Connected) return; outage = Outage; Interlocked.Increment(ref _reconnects); _state = ConnectionState.Connected; _lastFailure = null; _attempt = 0; _delay = _schedule.First; change = new ConnectionEvent(ConnectionEventKind.Restored, Name, ConnectionState.Connected, null, 0, null, outage, Reconnects, _time.GetUtcNow()); EventSink?.Post(change); } _recordReconnect?.Invoke(); _logger?.LogInformation("{Connection} reconnected after {Outage}", Name, FormatDuration(outage)); } /// /// Runs one connect bounded by . A connect that has not finished by then /// fails with a ; if it still succeeds later, its result goes to /// , which closes it. Errors of the connect propagate; the caller reports /// (or lets do it). /// public async Task AttemptAsync(Func> connect, Action discardLate, CancellationToken ct) { ArgumentNullException.ThrowIfNull(connect); ArgumentNullException.ThrowIfNull(discardLate); var connecting = connect(ct); try { return await connecting.WaitAsync(_options.AttemptTimeout, _time, ct).ConfigureAwait(false); } catch (Exception ex) when (!connecting.IsCompleted) { _ = connecting.ContinueWith(t => { try { discardLate(t.Result); } catch (Exception closeEx) { _logger?.LogDebug(closeEx, "{Connection}: error closing a connect that was given up", Name); } }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); if (ex is TimeoutException) throw new TimeoutException( $"{Name}: the connect did not finish within {FormatDuration(_options.AttemptTimeout)} (Reconnect.AttemptTimeout).", ex); throw; } } /// /// The reconnect loop of a connector that restores its connection itself: waits until the next attempt is due, runs /// , reports or , and repeats until an attempt /// succeeds. A connect inside that can hang goes through . /// Call it after . /// /// true once restored; false when stopped it (the owner is stopping). public async Task ReconnectAsync(Func reconnect, CancellationToken ct) { ArgumentNullException.ThrowIfNull(reconnect); while (true) { try { await Task.Delay(DueIn, _time, ct).ConfigureAwait(false); } catch (OperationCanceledException) { return false; } try { await reconnect(ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { return false; } catch (Exception ex) { Failed(ex); continue; } Restored(); return true; } } /// /// Links the supervisor to the endpoint it reports to: masking and the reconnect count. A loss is not counted in the /// endpoint's errors: it shows in while it lasts, so health is Healthy again at recovery and the /// error rate stays the rate of failed messages. /// internal void AttachTo(Func mask, Action recordReconnect) { _mask = mask; _recordReconnect = recordReconnect; } private string Mask(string text) => _mask is { } mask ? mask(text) : text; private ConnectionEvent Change(ConnectionEventKind kind, Exception cause, TimeSpan nextDelay) => new(kind, Name, State, cause, _attempt, nextDelay, Outage, Reconnects, _time.GetUtcNow()) { ErrorMessage = _lastFailure }; /// A duration for logs, health reasons and errors, in the invariant culture ("1.5 s" under any locale). internal static string FormatDuration(TimeSpan duration) => duration.TotalSeconds < 1 ? string.Create(CultureInfo.InvariantCulture, $"{duration.TotalMilliseconds:0} ms") : duration.TotalMinutes < 1 ? string.Create(CultureInfo.InvariantCulture, $"{duration.TotalSeconds:0.#} s") : duration.TotalHours < 1 ? string.Create(CultureInfo.InvariantCulture, $"{duration.TotalMinutes:0.#} min") : string.Create(CultureInfo.InvariantCulture, $"{duration.TotalHours:0.#} h"); } Path: redb-route/redb.Route/Core/ConsumerTemplate.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/Core/ConsumerTemplate.cs ---- using System.Collections.Concurrent; using System.Threading.Channels; using redb.Route.Abstractions; using redb.Route.Components; namespace redb.Route.Core; /// /// Template for polling messages from endpoints programmatically, as Apache Camel's. /// SEDA endpoints are read straight from their queue. Any other endpoint gets one consumer per /// endpoint, started on first use and kept until : every exchange it produces waits /// in a queue for a Receive, and its source does not commit it (delete or move the file, /// acknowledge the message) until the caller completes it with . Exchanges no /// Receive took stay uncommitted in their source. /// public class ConsumerTemplate : IConsumerTemplate, IDisposable { private readonly ConcurrentDictionary>> _consumers = new(ReferenceEqualityComparer.Instance); // Exchanges handed out and not completed yet; the value is null for a SEDA exchange, which has // no unit of work to complete. private readonly ConcurrentDictionary _open = new(ReferenceEqualityComparer.Instance); private volatile bool _started; private volatile bool _disposed; /// /// Initializes a new instance with the specified route context. /// /// The route context for endpoint resolution. public ConsumerTemplate(IRouteContext context) { Context = context ?? throw new ArgumentNullException(nameof(context)); } /// public IRouteContext Context { get; } /// public bool IsStarted => _started; // ── Receive (blocking) ── /// public Task Receive(string endpointUri, CancellationToken ct = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); return Receive(endpoint, ct); } /// public async Task Receive(IEndpoint endpoint, CancellationToken ct = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); // Optimized path for SEDA — read directly from the channel if (endpoint is SedaEndpoint seda) return HandOut(await seda.Queue.Reader.ReadAsync(ct).ConfigureAwait(false), null); return await ReceiveViaConsumer(endpoint, Timeout.InfiniteTimeSpan, ct).ConfigureAwait(false) ?? throw new OperationCanceledException("Receive was cancelled: the template stopped.", ct); } // ── Receive with timeout ── /// public Task Receive(string endpointUri, TimeSpan timeout, CancellationToken ct = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); return Receive(endpoint, timeout, ct); } /// public async Task Receive(IEndpoint endpoint, TimeSpan timeout, CancellationToken ct = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); // Optimized path for SEDA if (endpoint is SedaEndpoint seda) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(timeout); try { return HandOut(await seda.Queue.Reader.ReadAsync(cts.Token).ConfigureAwait(false), null); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; // Timeout — not caller cancellation } } return await ReceiveViaConsumer(endpoint, timeout, ct).ConfigureAwait(false); } // ── ReceiveNoWait ── /// public Task ReceiveNoWait(string endpointUri, CancellationToken ct = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); return ReceiveNoWait(endpoint, ct); } /// public Task ReceiveNoWait(IEndpoint endpoint, CancellationToken ct = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ct.ThrowIfCancellationRequested(); // Optimized path for SEDA if (endpoint is SedaEndpoint seda) { return Task.FromResult( seda.Queue.Reader.TryRead(out var exchange) ? HandOut(exchange, null) : null); } // Generic: whatever the endpoint's consumer has already offered return Receive(endpoint, TimeSpan.Zero, ct); } // ── Typed body convenience ── /// public async Task ReceiveBody(string endpointUri, CancellationToken ct = default) { var exchange = await Receive(endpointUri, ct).ConfigureAwait(false); return await TakeBodyAndComplete(exchange).ConfigureAwait(false); } /// public async Task ReceiveBody(string endpointUri, CancellationToken ct = default) { var exchange = await Receive(endpointUri, ct).ConfigureAwait(false); return ConvertBody(await TakeBodyAndComplete(exchange).ConfigureAwait(false)); } /// public async Task ReceiveBody(string endpointUri, TimeSpan timeout, CancellationToken ct = default) { var exchange = await Receive(endpointUri, timeout, ct).ConfigureAwait(false); return exchange is null ? default : ConvertBody(await TakeBodyAndComplete(exchange).ConfigureAwait(false)); } // ── Unit of work ── /// public Task DoneUoW(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange); if (!_open.TryRemove(exchange, out var offer)) throw new InvalidOperationException( "The exchange is not an open unit of work of this ConsumerTemplate: it was not handed out by it, " + "was already completed, or was rolled back when the template stopped."); // SEDA: nothing waits for the caller. if (offer is null) return Task.CompletedTask; if (!offer.Done.TrySetResult()) throw new InvalidOperationException( "The exchange was rolled back before it was completed: its consumer stopped."); return Task.CompletedTask; } // ── Lifecycle ── /// public void Start() { ObjectDisposedException.ThrowIf(_disposed, this); if (_started) throw new InvalidOperationException("ConsumerTemplate is already started."); _started = true; } /// public void Stop() { if (!_started) throw new InvalidOperationException("ConsumerTemplate is not started."); _started = false; StopConsumersAsync().GetAwaiter().GetResult(); } /// Disposes the consumer template, stopping its consumers. public void Dispose() { if (_disposed) return; _disposed = true; if (_started) { _started = false; StopConsumersAsync().GetAwaiter().GetResult(); } GC.SuppressFinalize(this); } // ── Private helpers ── private IExchange HandOut(IExchange exchange, Offer? offer) { _open[exchange] = offer; return exchange; } /// /// Takes the next exchange the endpoint's consumer offers. The consumer is started on first use /// and kept; an offer abandoned by a stopping consumer is skipped. /// private async Task ReceiveViaConsumer(IEndpoint endpoint, TimeSpan timeout, CancellationToken ct) { var cached = await GetOrStart(endpoint, ct).ConfigureAwait(false); var reader = cached.Queue.Reader; while (reader.TryRead(out var ready)) if (!ready.Done.Task.IsCompleted) return HandOut(ready.Exchange, ready); if (timeout == TimeSpan.Zero) return null; using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct, cached.Stopping.Token); if (timeout != Timeout.InfiniteTimeSpan) cts.CancelAfter(timeout); try { while (true) { var offer = await reader.ReadAsync(cts.Token).ConfigureAwait(false); if (!offer.Done.Task.IsCompleted) return HandOut(offer.Exchange, offer); } } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; // Timeout, or the template stopped — not caller cancellation } } private async Task GetOrStart(IEndpoint endpoint, CancellationToken ct) { var lazy = _consumers.GetOrAdd(endpoint, e => new Lazy>(() => StartConsumer(e))); try { return await lazy.Value.WaitAsync(ct).ConfigureAwait(false); } catch (Exception) when (lazy.Value.IsFaulted) { // A consumer that failed to start is not cached: the next Receive tries again. _consumers.TryRemove(new KeyValuePair>>(endpoint, lazy)); throw; } } private static async Task StartConsumer(IEndpoint endpoint) { var cached = new CachedConsumer(); cached.Consumer = endpoint.CreateConsumerOnItsSide(new BridgeProcessor(cached)); await cached.Consumer.Start(CancellationToken.None).ConfigureAwait(false); return cached; } private async Task StopConsumersAsync() { _open.Clear(); var consumers = _consumers.Values.ToList(); _consumers.Clear(); foreach (var lazy in consumers) { if (!lazy.IsValueCreated || !lazy.Value.IsCompletedSuccessfully) continue; var cached = lazy.Value.Result; if (cached.Consumer is DrainableConsumer drainable) { // Every exchange in flight here waits for a caller, and none will come: no drain, // straight to cancelling the processing token, so the consumer rolls them back on // its own shutdown path. drainable.DrainTimeout = TimeSpan.Zero; await cached.Consumer.Stop(CancellationToken.None).ConfigureAwait(false); await cached.Stopping.CancelAsync().ConfigureAwait(false); } else { // A consumer without a processing token may wait for its handlers while stopping: // release them once the stop has begun, so no new work is accepted in between. var stop = cached.Consumer!.Stop(CancellationToken.None); await cached.Stopping.CancelAsync().ConfigureAwait(false); await stop.ConfigureAwait(false); } cached.Stopping.Dispose(); } } /// /// ReceiveBody hands the exchange to no one, so it completes the unit of work itself once the /// body is taken — or rolls it back when the body cannot be read. /// private async Task TakeBodyAndComplete(IExchange exchange) { object? body; try { body = exchange.In.Body; // The source releases the exchange's resources once the unit of work is done, and a // streamed body goes with them: it is read into memory first. if (body is Stream stream) { var copy = new MemoryStream(); await stream.CopyToAsync(copy).ConfigureAwait(false); copy.Position = 0; body = copy; } } catch (Exception ex) { exchange.Exception ??= ex; await DoneUoW(exchange).ConfigureAwait(false); throw; } await DoneUoW(exchange).ConfigureAwait(false); return body; } private static T? ConvertBody(object? body) => TypedValue.Convert(body, "received body"); private void EnsureStarted() { ObjectDisposedException.ThrowIf(_disposed, this); if (!_started) throw new InvalidOperationException( "ConsumerTemplate is not started. Call Start() before use."); } /// An exchange a consumer offered, and the signal that releases the consumer. private sealed record Offer(IExchange Exchange) { public TaskCompletionSource Done { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); } /// One endpoint's consumer, its queue of offers, and the token that abandons them. private sealed class CachedConsumer { public IConsumer? Consumer { get; set; } public Channel Queue { get; } = Channel.CreateUnbounded(); public CancellationTokenSource Stopping { get; } = new(); } /// /// Offers each exchange to the template and holds the consumer until the caller completes it, so /// the source commits only what a caller finished. Cancelled by the consumer's processing token /// or by the template stopping, it throws and the /// consumer rolls the exchange back. /// private sealed class BridgeProcessor(CachedConsumer cached) : IProcessor { public async Task Process(IExchange exchange, CancellationToken ct = default) { var offer = new Offer(exchange); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, cached.Stopping.Token); await using var registration = linked.Token.Register(() => offer.Done.TrySetCanceled(linked.Token)); await cached.Queue.Writer.WriteAsync(offer, linked.Token).ConfigureAwait(false); await offer.Done.Task.ConfigureAwait(false); } } } Path: redb-route/redb.Route/Core/CountedSend.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/Core/CountedSend.cs ---- using System.Diagnostics; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// The single producer-side statistics funnel. Every core-owned send — a routed .To() /// (), a template send (), and /// the EIPs that drive a producer directly (RecipientList, Enrich/PollEnrich, DeadLetterChannel, /// RoutingSlip, DynamicRouter) — records MessagesOut / Errors / ProcessingTime on the target /// endpoint through this helper, exactly once. Connectors do not self-record these numbers; they /// record only what the core cannot see (wire bytes, transport-level failures, producer-side /// inbound operations). /// internal static class CountedSend { internal static async Task Process(IEndpoint endpoint, IProducer producer, IExchange exchange, CancellationToken ct = default) { var stats = endpoint as IEndpointStatistics; var sw = stats is not null ? Stopwatch.StartNew() : null; try { await producer.Process(exchange, ct).ConfigureAwait(false); stats?.RecordMessageOut(); } catch (Exception ex) { // Same reading as the consumer-side wrapper (BR-10): the caller cancelling its own // send is not the target endpoint's failure. if (StatisticsProcessor.IsCooperativeCancellation(ex, ct)) stats?.RecordCancelled(); else stats?.RecordError(ex); throw; } finally { if (sw is not null) { sw.Stop(); stats!.RecordProcessingTime(sw.Elapsed); } } } } Path: redb-route/redb.Route/Core/DefaultHeaderFilterStrategy.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/Core/DefaultHeaderFilterStrategy.cs ---- using System.Text.RegularExpressions; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// The general-purpose , Apache Camel's DefaultHeaderFilterStrategy: for /// each direction a list of names, a regular expression and name prefixes; a header that matches any of them is /// dropped — or, with set to false, only a header that matches is kept. /// /// Send only Correlation-ID (a whitelist on the outgoing side): /// /// context.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy /// { /// OutFilter = ["Correlation-ID"], /// FilterOnMatch = false, /// }); /// From("direct://order").To("http://sap/orders?headerFilterStrategy=#correlationOnly"); /// /// In markup the same object is a <bean> with the properties of this class. /// /// /// With false a direction with nothing configured drops every header: a whitelist /// with no names lets nothing through. A header with a null value is dropped unless /// is set. Names in the lists are compared without regard to case unless /// is turned off. /// /// public class DefaultHeaderFilterStrategy : IHeaderFilterStrategy { // One reference per direction: the pattern and its source change together, so a thread never pairs a new // source with an old compiled pattern (the strategy is shared by every exchange of every route using it). private CompiledPattern? _outPattern; private CompiledPattern? _inPattern; /// Names matched in the outgoing direction (exchange → message). public IList OutFilter { get; set; } = new List(); /// A regular expression matched against the whole name in the outgoing direction. public string? OutFilterPattern { get; set; } /// Name prefixes matched in the outgoing direction. public IList OutFilterStartsWith { get; set; } = new List(); /// Names matched in the incoming direction (message → exchange). public IList InFilter { get; set; } = new List(); /// A regular expression matched against the whole name in the incoming direction. public string? InFilterPattern { get; set; } /// Name prefixes matched in the incoming direction. public IList InFilterStartsWith { get; set; } = new List(); /// /// What a match means. true (the default): a matching header is dropped — a blacklist. false: only /// a matching header is kept — a whitelist. /// public bool FilterOnMatch { get; set; } = true; /// /// Compare names in the lists without regard to case; true by default, as in Camel (header names of most /// protocols are case-insensitive). The prefixes and the pattern are not affected. /// public bool CaseInsensitive { get; set; } = true; /// /// Also match the lower-cased name against the prefixes and, when is off, the lists. /// The pattern is matched against the name as it is, as in Camel. /// public bool LowerCase { get; set; } /// Let a header with a null value through; by default it is dropped. public bool AllowNullValues { get; set; } /// public virtual bool FilterOutgoing(string name, object? value, IExchange exchange) => Filter(name, value, OutFilter, OutFilterStartsWith, OutRegex()); /// public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => Filter(name, value, InFilter, InFilterStartsWith, InRegex()); private bool Filter(string name, object? value, IList names, IList prefixes, Regex? pattern) { if (string.IsNullOrEmpty(name)) return true; if (value is null && !AllowNullValues) return true; var lower = LowerCase ? name.ToLowerInvariant() : null; foreach (var prefix in prefixes) { if (string.IsNullOrEmpty(prefix)) continue; if (name.StartsWith(prefix, StringComparison.Ordinal) || (lower is not null && lower.StartsWith(prefix, StringComparison.Ordinal))) return FilterOnMatch; } if (pattern is not null && pattern.IsMatch(name)) return FilterOnMatch; var comparison = CaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; foreach (var candidate in names) { if (string.Equals(candidate, name, comparison) || (lower is not null && string.Equals(candidate, lower, comparison))) return FilterOnMatch; } // Nothing matched: a blacklist lets the header through, a whitelist drops it. return !FilterOnMatch; } private Regex? OutRegex() => Compiled(OutFilterPattern, ref _outPattern); private Regex? InRegex() => Compiled(InFilterPattern, ref _inPattern); /// The pattern compiled once per value of the property; matched against the whole name, as in Camel. private static Regex? Compiled(string? source, ref CompiledPattern? cache) { if (string.IsNullOrEmpty(source)) return null; var current = Volatile.Read(ref cache); if (current is null || !string.Equals(current.Source, source, StringComparison.Ordinal)) { current = new CompiledPattern(source, new Regex($"^(?:{source})$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1))); Volatile.Write(ref cache, current); } return current.Pattern; } private sealed record CompiledPattern(string Source, Regex Pattern); } Path: redb-route/redb.Route/Core/DefaultInflightRepository.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/Core/DefaultInflightRepository.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Thread-safe in-memory implementation of . /// Uses ConcurrentDictionary for O(1) register/unregister and per-route counting. /// /// /// An exchange is registered once per entry into a route, and a copy keeps the exchange id: an exchange entering a /// route again (a route calling itself, parallel branches through one sub-route) registers the same id more than once. /// The entries are counted, so the exchange stays in flight until the last of them has finished; the entry shown is /// the first one. /// public sealed class DefaultInflightRepository : IInflightRepository { private sealed record Tracked(InflightExchange Entry, int Entries); private readonly ConcurrentDictionary _entries = new(); /// public void Register(InflightExchange entry) { ArgumentNullException.ThrowIfNull(entry); _entries.AddOrUpdate(entry.ExchangeId, static (_, added) => new Tracked(added, 1), static (_, tracked, _) => tracked with { Entries = tracked.Entries + 1 }, entry); } /// public void Unregister(string exchangeId) { while (_entries.TryGetValue(exchangeId, out var tracked)) { if (tracked.Entries <= 1) { if (_entries.TryRemove(new KeyValuePair(exchangeId, tracked))) return; } else if (_entries.TryUpdate(exchangeId, tracked with { Entries = tracked.Entries - 1 }, tracked)) { return; } // Raced with another entry of the same exchange: read it again. } } /// public IReadOnlyList Browse() => _entries.Values.Select(t => t.Entry).ToList(); /// public IReadOnlyList Browse(string routeId) => _entries.Values.Select(t => t.Entry).Where(e => e.RouteId == routeId).ToList(); /// public int Count => _entries.Count; /// public int CountByRoute(string routeId) => _entries.Values.Count(t => t.Entry.RouteId == routeId); /// public IDisposable BeginWait(string exchangeId, TimeSpan delay) { ArgumentNullException.ThrowIfNull(exchangeId); var until = DateTime.UtcNow + delay; Update(exchangeId, e => e with { WaitingUntil = until }); return new Wait(this, exchangeId); } private void Update(string exchangeId, Func change) { while (_entries.TryGetValue(exchangeId, out var tracked)) { if (_entries.TryUpdate(exchangeId, tracked with { Entry = change(tracked.Entry) }, tracked)) return; // Raced with another entry of the same exchange: read it again. } } private sealed class Wait(DefaultInflightRepository owner, string exchangeId) : IDisposable { private int _disposed; public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.Update(exchangeId, e => e with { WaitingUntil = null, LastWaitEndedAt = DateTime.UtcNow }); } } } Path: redb-route/redb.Route/Core/DrainAwaiter.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/Core/DrainAwaiter.cs ---- using Microsoft.Extensions.Logging; namespace redb.Route.Core; /// /// Utility for waiting until in-flight exchange count drops to zero. /// Used by consumers during graceful Stop() to drain processing before shutdown. /// public static class DrainAwaiter { private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(100); private static readonly TimeSpan LogInterval = TimeSpan.FromSeconds(1); /// /// Waits until returns 0, or elapses. /// /// true if drained successfully, false if timed out. public static async Task WaitAsync( Func getInflightCount, TimeSpan timeout, CancellationToken ct, ILogger? logger = null, string? consumerName = null) { var count = getInflightCount(); if (count <= 0) return true; using var timeoutCts = new CancellationTokenSource(timeout); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token); var linkedToken = linked.Token; var lastLogTime = DateTime.UtcNow; logger?.LogInformation( "[{Consumer}] Waiting for {Count} in-flight exchange(s) to complete (timeout={Timeout}s)...", consumerName ?? "unknown", count, timeout.TotalSeconds); while (!linkedToken.IsCancellationRequested) { try { await Task.Delay(PollInterval, linkedToken).ConfigureAwait(false); } catch (OperationCanceledException) { break; } count = getInflightCount(); if (count <= 0) { logger?.LogInformation("[{Consumer}] All in-flight exchanges drained.", consumerName ?? "unknown"); return true; } var now = DateTime.UtcNow; if (now - lastLogTime >= LogInterval) { logger?.LogInformation( "[{Consumer}] Still waiting for {Count} in-flight exchange(s)...", consumerName ?? "unknown", count); lastLogTime = now; } } count = getInflightCount(); if (count <= 0) return true; logger?.LogWarning( "[{Consumer}] Drain timed out after {Timeout}s with {Count} in-flight exchange(s) remaining.", consumerName ?? "unknown", timeout.TotalSeconds, count); return false; } } Path: redb-route/redb.Route/Core/DrainableConsumer.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/Core/DrainableConsumer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Base class for consumers with Two-CTS graceful shutdown. /// Handles: CTS lifecycle, inflight tracking, drain-on-stop, force-cancel. /// Subclasses only implement and optionally override hooks. /// public abstract class DrainableConsumer : IConsumer { private CancellationTokenSource? _pollCts; private readonly InflightDrainGuard _drain = new(); private Task? _runTask; private ILogger? _logger; /// The endpoint this consumer is attached to. protected abstract IEndpoint ConsumerEndpoint { get; } /// The processor to execute on each exchange. protected IProcessor Processor { get; } /// public IEndpoint Endpoint => ConsumerEndpoint; /// Logger resolved from the component. protected ILogger? Logger => _logger ??= (ConsumerEndpoint.Component as ComponentBase)?.Logger; /// Drain timeout for graceful stop. internal TimeSpan DrainTimeout { get => _drain.DrainTimeout; set => _drain.DrainTimeout = value; } /// Display name for logging (e.g. "kafka:orders", "file:/tmp/in"). protected abstract string ConsumerName { get; } /// Creates a drainable consumer. protected DrainableConsumer(IProcessor processor) { Processor = processor ?? throw new ArgumentNullException(nameof(processor)); } // ── IConsumer lifecycle ── /// public async Task Start(CancellationToken ct = default) { _pollCts?.Dispose(); _pollCts = new CancellationTokenSource(); _drain.Start(ct); try { await OnStarting(ct).ConfigureAwait(false); } catch { _pollCts.Dispose(); _pollCts = null; _drain.Dispose(); throw; } _runTask = RunAsync(_pollCts.Token, _drain.ProcessingToken); Logger?.LogInformation("{Consumer} started.", EndpointUri.ForLog(ConsumerName, Logger)); } /// public async Task Stop(CancellationToken ct = default) { if (_pollCts != null) { try { // Step 1: stop accepting new work await OnStopAccepting().ConfigureAwait(false); await _pollCts.CancelAsync().ConfigureAwait(false); // Step 2: drain in-flight await _drain.DrainAsync(ct, Logger, ConsumerName).ConfigureAwait(false); // Step 3: await run task(s) await AwaitRunTask().ConfigureAwait(false); } finally { // Step 4: cleanup — guaranteed even if drain/await throws _pollCts.Dispose(); _pollCts = null; _drain.Dispose(); } await OnStopped().ConfigureAwait(false); } Logger?.LogInformation("{Consumer} stopped.", EndpointUri.ForLog(ConsumerName, Logger)); } // ── Abstract / virtual hooks ── /// /// Main consumer loop. Receives (stop accepting new work) /// and (cancel in-flight processing). /// Use for automatic inflight tracking. /// protected abstract Task RunAsync(CancellationToken pollCt, CancellationToken processingCt); /// Called during Start() before RunAsync. Override for async setup (topology, subscriptions). protected virtual Task OnStarting(CancellationToken ct) => Task.CompletedTask; /// Called at the beginning of Stop() before poll cancel. Override for protocol-level unsubscribe. protected virtual Task OnStopAccepting() => Task.CompletedTask; /// Called at the end of Stop() after CTS disposal. Override for resource cleanup. protected virtual Task OnStopped() => Task.CompletedTask; /// /// Awaits the run task. Override for consumers with multiple workers (e.g. Task.WhenAll). /// protected virtual async Task AwaitRunTask() { if (_runTask != null) { try { await _runTask.ConfigureAwait(false); } catch (OperationCanceledException) { } } } // ── Inflight tracking helper ── /// /// Processes an exchange with automatic inflight count tracking. /// Increments before, decrements in finally. Disposes the exchange after processing. /// protected Task ProcessWithTracking(IExchange exchange, CancellationToken processingCt) => ProcessWithTracking(exchange, default, processingCt); /// /// inside the receive span of the exchange, opened by /// the consumer (). A failed route marks /// the span, whether its failure stayed on the exchange or escaped the pipeline; the consumer's own stop does not, /// any other cancellation (an HttpClient timeout inside the route) does. The span stays the consumer's to dispose. /// protected async Task ProcessWithTracking(IExchange exchange, Telemetry.TransportSpan span, CancellationToken processingCt) { _drain.Increment(); try { // What escapes the pipeline goes on the exchange (a consumer that decides on the outcome, delete after read // or move on failure, sees a failed route); it is logged and dropped: a single failure must NOT terminate the // worker and silently stop the consumer draining the queue. The consumer's stop is rethrown. if (await ExchangeProcessing.RunAsync(Processor, exchange, processingCt).ConfigureAwait(false) is { } escaped) Logger?.LogError(escaped, "{Consumer} dropped an exchange after an unhandled failure; continuing.", ConsumerName); ExchangeProcessing.RecordFailure(exchange, span, processingCt); } finally { _drain.Decrement(); await exchange.DisposeAsync().ConfigureAwait(false); } } /// /// Increments the inflight counter. Must be paired with . /// Use when you need custom logic between increment and process (e.g. ack/nack). /// protected void IncrementInflight() => _drain.Increment(); /// Decrements the inflight counter. protected void DecrementInflight() => _drain.Decrement(); } Path: redb-route/redb.Route/Core/DynamicValue.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/Core/DynamicValue.cs ---- using redb.Route.Abstractions; namespace redb.Route.Core; /// /// A value that is either static (resolved at endpoint creation) /// or dynamic (resolved per-message from exchange via ${...} expressions). /// The property type itself is the contract: DynamicValue{T} = "may be an expression". /// /// The resolved value type. public readonly struct DynamicValue { private readonly T? _static; private readonly Func? _resolver; private DynamicValue(T? staticValue, Func? resolver) { _static = staticValue; _resolver = resolver; } /// Whether this value contains a dynamic expression. public bool IsDynamic => _resolver != null; /// /// Resolves the value. Static = instant return, dynamic = evaluates compiled expression. /// /// The current exchange (used only for dynamic values). /// Resolved value. public T? Resolve(IExchange exchange) => _resolver != null ? _resolver(exchange) : _static; /// Creates a static (constant) value. /// The constant value. /// A DynamicValue wrapping the constant. public static DynamicValue FromStatic(T value) => new(value, null); /// Creates a dynamic value from a compiled expression resolver. /// Compiled expression function, cached after first parse. /// A DynamicValue that evaluates per-message. public static DynamicValue FromExpression(Func resolver) => new(default, resolver ?? throw new ArgumentNullException(nameof(resolver))); /// Creates a dynamic value from an . /// The expression to evaluate per-message. /// A DynamicValue that evaluates the expression on each resolve. public static DynamicValue FromExpression(IExpression expression) { ArgumentNullException.ThrowIfNull(expression); return new(default, exchange => expression.Evaluate(exchange)); } /// Implicit conversion from a plain value to a static DynamicValue. /// The value to wrap. public static implicit operator DynamicValue(T value) => FromStatic(value); /// public override string ToString() => IsDynamic ? "${expression}" : _static?.ToString() ?? "null"; } Path: redb-route/redb.Route/Core/EndpointBase.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/Core/EndpointBase.cs ---- using System.Collections.Concurrent; using System.Text; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Base class for endpoints with built-in lightweight statistics tracking. /// All counters use for thread safety with zero lock contention. /// Consumers call // /// to update counters; external code reads via . /// /// Typed options for this endpoint. public abstract class EndpointBase : IEndpoint, IEndpointStatistics, ISupervisingEndpoint where TOptions : EndpointOptions { /// public EndpointUri Uri { get; } /// public IComponent Component { get; } /// Typed options bound from URI parameters. protected TOptions Options { get; } /// Scope factory for per-exchange DI scope creation. Set by RouteContext. public IServiceScopeFactory? ScopeFactory { get; set; } // ── Statistics fields (Interlocked-based, zero lock contention) ── private long _messagesIn; private long _messagesOut; private long _errors; private long _bytesIn; private long _bytesOut; private long _rejected; private long _cancelled; private long _refused; private long _lastRefusalTicks; private volatile string _lastRefusalMessage = ""; private long _lastActivityTicks; private readonly DateTime _startTime = DateTime.UtcNow; // ── Error tracking ── private long _lastErrorTicks; private volatile string _lastErrorMessage = ""; // ── Warning tracking ── private long _warnings; private long _lastWarningTicks; private volatile string _lastWarningMessage = ""; // The values this endpoint knows to be secret, longest first; read on the first recorded text. private string[]? _secretValues; // A secret this short would mask ordinary words and numbers of the text; it is left to the key=value masking. private const int MinSecretLength = 4; // ── Processing time (sliding window of last 100 durations in ticks) ── private readonly ConcurrentQueue _processingTimes = new(); private const int MaxProcessingTimesHistory = 100; // ── Throughput (sliding window of message timestamps in ticks, 60s) ── private readonly ConcurrentQueue _messageTimestamps = new(); private const int ThroughputWindowSeconds = 60; /// Creates an endpoint with parsed URI, owning component, and bound options. /// Parsed endpoint URI. /// The component that created this endpoint. /// Options already bound via BindFromUri and validated. protected EndpointBase(EndpointUri uri, IComponent component, TOptions options) { Uri = uri ?? throw new ArgumentNullException(nameof(uri)); Component = component ?? throw new ArgumentNullException(nameof(component)); Options = options ?? throw new ArgumentNullException(nameof(options)); } /// public abstract IProducer CreateProducer(); /// public abstract IConsumer CreateConsumer(IProcessor processor); /// public virtual Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public virtual Task Stop(CancellationToken ct = default) => Task.CompletedTask; /// public override string ToString() => Uri.NormalizedKey; // ── IEndpointStatistics — read properties ── /// public long MessagesIn => Interlocked.Read(ref _messagesIn); /// public long MessagesOut => Interlocked.Read(ref _messagesOut); /// public long Errors => Interlocked.Read(ref _errors); /// public long Warnings => Interlocked.Read(ref _warnings); /// public long BytesIn => Interlocked.Read(ref _bytesIn); /// public long BytesOut => Interlocked.Read(ref _bytesOut); /// public long Rejected => Interlocked.Read(ref _rejected); /// public long Cancelled => Interlocked.Read(ref _cancelled); /// public long Refused => Interlocked.Read(ref _refused); /// public long Reconnects => Interlocked.Read(ref _reconnects); // ── Connection supervision ── // The supervisors whose condition this endpoint's health takes into account; replaced as a whole (copy on write). private ConnectionSupervisor[] _supervisors = []; private readonly object _supervisorsLock = new(); private long _reconnects; /// /// Creates a for one connection or link of this endpoint, with the context's /// (RedbRoute:Reconnect; their defaults when the endpoint has no /// context), and registers it (). A consumer creates one per connection /// or worker when it starts and removes it with when it stops. /// /// What is supervised, for logs and the health reason, such as wmq:ORDERS consumer worker 2. /// Logger for the loss and recovery lines. public ConnectionSupervisor Supervise(string name, Microsoft.Extensions.Logging.ILogger? logger) { var options = ((Component as ComponentBase)?.Context as RouteContext)?.ReconnectOptions ?? new Configuration.ReconnectOptions(); var supervisor = new ConnectionSupervisor(name, options, logger); Supervise(supervisor); return supervisor; } /// /// Registers a supervisor: its becomes part of this endpoint's health (the /// worst of all registered supervisors and ) and its recoveries count in /// . Its losses are not counted in : the supervisor's condition shows a loss /// while it lasts, so health is Healthy again when the connection is back, and the error rate stays the rate of failed /// messages. /// public void Supervise(ConnectionSupervisor supervisor) { ArgumentNullException.ThrowIfNull(supervisor); supervisor.AttachTo(Masked, () => Interlocked.Increment(ref _reconnects)); if ((Component as ComponentBase)?.Context is RouteContext context) supervisor.EventSink ??= new EndpointConnectionEventSink(context, this, EndpointUri.Sanitize(Uri.BaseKey)); lock (_supervisorsLock) { if (Array.IndexOf(_supervisors, supervisor) < 0) _supervisors = [.. _supervisors, supervisor]; } } /// Removes a supervisor registered with ; its condition no longer counts. public void Unsupervise(ConnectionSupervisor supervisor) { ArgumentNullException.ThrowIfNull(supervisor); lock (_supervisorsLock) _supervisors = _supervisors.Where(s => !ReferenceEquals(s, supervisor)).ToArray(); } /// The worst condition of the registered supervisors and , or null when none has one. private (EndpointHealthStatus Status, string Reason)? WorstCondition() { (EndpointHealthStatus Status, string Reason)? worst = null; foreach (var supervisor in Volatile.Read(ref _supervisors)) { if (supervisor.Condition is { } condition && (worst is null || condition.Status > worst.Value.Status)) worst = condition; } if (TransportCondition is { } transport && (worst is null || transport.Status > worst.Value.Status)) worst = transport; return worst; } /// public DateTime? LastRefusalTime { get { var ticks = Interlocked.Read(ref _lastRefusalTicks); return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc); } } /// public string LastRefusalMessage => _lastRefusalMessage; /// public DateTime? LastActivity { get { var ticks = Interlocked.Read(ref _lastActivityTicks); return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc); } } /// public DateTime StartTime => _startTime; /// public TimeSpan Uptime => DateTime.UtcNow - _startTime; /// public TimeSpan AverageProcessingTime { get { // Snapshot the queue — ConcurrentQueue enumerator is safe var items = _processingTimes.ToArray(); if (items.Length == 0) return TimeSpan.Zero; var avgTicks = items.Sum() / items.Length; return new TimeSpan(avgTicks); } } /// public double ThroughputPerSecond { get { var nowTicks = DateTime.UtcNow.Ticks; var cutoff = nowTicks - TimeSpan.TicksPerSecond * ThroughputWindowSeconds; // Drain stale entries while (_messageTimestamps.TryPeek(out var oldest) && oldest < cutoff) _messageTimestamps.TryDequeue(out _); var count = _messageTimestamps.Count; if (count == 0) return 0.0; // Time span from oldest remaining to now if (!_messageTimestamps.TryPeek(out var oldestRemaining)) return 0.0; var windowSeconds = (double)(nowTicks - oldestRemaining) / TimeSpan.TicksPerSecond; return windowSeconds > 0 ? count / windowSeconds : 0.0; } } /// public DateTime? LastErrorTime { get { var ticks = Interlocked.Read(ref _lastErrorTicks); return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc); } } /// public string LastErrorMessage => _lastErrorMessage; /// public DateTime? LastWarningTime { get { var ticks = Interlocked.Read(ref _lastWarningTicks); return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc); } } /// public string LastWarningMessage => _lastWarningMessage; /// public EndpointHealthStatus HealthStatus => GetHealthStatus().Status; /// public string HealthReason => GetHealthStatus().Reason; /// /// A state the endpoint knows from its transport and the counters cannot show, such as a broker that blocks the /// connection the endpoint sends over. While it is not null it is the endpoint's health status and reason, /// unless a registered reports a worse one; when both are null the status is /// computed from the counters again. /// /// Health checks read it on every probe: an override returns a state the endpoint already holds, and never opens a /// connection, takes a lock a send holds or does I/O. /// /// protected virtual (EndpointHealthStatus Status, string Reason)? TransportCondition => null; private (EndpointHealthStatus Status, string Reason) GetHealthStatus() { if (WorstCondition() is { } condition) return condition; var lastErr = LastErrorTime; var msgs = MessagesIn; var errs = Errors; // Recent errors (last 5 min) if (lastErr.HasValue && (DateTime.UtcNow - lastErr.Value).TotalMinutes < 5) { var rate = msgs > 0 ? errs * 100.0 / msgs : 0; if (rate > 10) return (EndpointHealthStatus.Critical, $"High error rate: {rate:F1}% ({errs}/{msgs})"); return (EndpointHealthStatus.Warning, $"Recent errors (last 5 min): {errs} error(s)"); } // No activity for > 10 min (only if there was any activity at all) var last = LastActivity; if (last.HasValue && (DateTime.UtcNow - last.Value).TotalMinutes > 10) { var idle = DateTime.UtcNow - last.Value; return (EndpointHealthStatus.Warning, $"No activity for {idle.TotalMinutes:F0} min"); } return (EndpointHealthStatus.Healthy, "OK"); } /// public void ResetStatistics() { Interlocked.Exchange(ref _messagesIn, 0); Interlocked.Exchange(ref _messagesOut, 0); Interlocked.Exchange(ref _errors, 0); Interlocked.Exchange(ref _bytesIn, 0); Interlocked.Exchange(ref _bytesOut, 0); Interlocked.Exchange(ref _rejected, 0); Interlocked.Exchange(ref _cancelled, 0); Interlocked.Exchange(ref _refused, 0); Interlocked.Exchange(ref _reconnects, 0); Interlocked.Exchange(ref _lastRefusalTicks, 0); _lastRefusalMessage = ""; Interlocked.Exchange(ref _lastActivityTicks, 0); Interlocked.Exchange(ref _lastErrorTicks, 0); _lastErrorMessage = ""; Interlocked.Exchange(ref _warnings, 0); Interlocked.Exchange(ref _lastWarningTicks, 0); _lastWarningMessage = ""; while (_processingTimes.TryDequeue(out _)) { } while (_messageTimestamps.TryDequeue(out _)) { } } // ── Recording helpers (thread-safe) ── /// Record an incoming message (consumed). Thread-safe. public void RecordMessageIn() { Interlocked.Increment(ref _messagesIn); var nowTicks = DateTime.UtcNow.Ticks; Interlocked.Exchange(ref _lastActivityTicks, nowTicks); // Throughput sliding window _messageTimestamps.Enqueue(nowTicks); var cutoff = nowTicks - TimeSpan.TicksPerSecond * ThroughputWindowSeconds; while (_messageTimestamps.TryPeek(out var oldest) && oldest < cutoff) _messageTimestamps.TryDequeue(out _); } /// Record an outgoing message (produced). Thread-safe. public void RecordMessageOut() { Interlocked.Increment(ref _messagesOut); Interlocked.Exchange(ref _lastActivityTicks, DateTime.UtcNow.Ticks); } /// Record a processing error. Thread-safe. public void RecordError() { Interlocked.Increment(ref _errors); var nowTicks = DateTime.UtcNow.Ticks; Interlocked.Exchange(ref _lastActivityTicks, nowTicks); Interlocked.Exchange(ref _lastErrorTicks, nowTicks); } /// Record a processing error with exception details. Thread-safe. public void RecordError(Exception exception) { _lastErrorMessage = Masked(exception.Message); RecordError(); } /// Record a processing warning. Thread-safe. public void RecordWarning() { Interlocked.Increment(ref _warnings); Interlocked.Exchange(ref _lastActivityTicks, DateTime.UtcNow.Ticks); Interlocked.Exchange(ref _lastWarningTicks, DateTime.UtcNow.Ticks); } /// Record a processing warning with message. Thread-safe. public void RecordWarning(string message) { _lastWarningMessage = Masked(message); RecordWarning(); } /// Record processing time of a single message. Thread-safe. public void RecordProcessingTime(TimeSpan duration) { _processingTimes.Enqueue(duration.Ticks); // Trim beyond history limit — approximate, no lock needed while (_processingTimes.Count > MaxProcessingTimesHistory) _processingTimes.TryDequeue(out _); } /// Record incoming bytes (message body size). Thread-safe. public void RecordBytesIn(long bytes) { Interlocked.Add(ref _bytesIn, bytes); } /// Record outgoing bytes (message body size). Thread-safe. public void RecordBytesOut(long bytes) { Interlocked.Add(ref _bytesOut, bytes); } /// public void RecordRejected() { Interlocked.Increment(ref _rejected); } /// /// /// Bumps activity but neither the error counter nor the last-error stamp: cancellation must /// not feed the health calculation, whose "recent errors" window would otherwise mark an /// endpoint degraded for five minutes per closed dashboard tab. /// public void RecordCancelled() { Interlocked.Increment(ref _cancelled); Interlocked.Exchange(ref _lastActivityTicks, DateTime.UtcNow.Ticks); } /// /// /// Bumps activity and its own stamp, never the error counter or the last-error stamp: a caller's bad request is not /// a failure of the endpoint, and must not mark it degraded in the health calculation. /// public void RecordRefused(string reason) { _lastRefusalMessage = Masked(reason); Interlocked.Increment(ref _refused); var nowTicks = DateTime.UtcNow.Ticks; Interlocked.Exchange(ref _lastActivityTicks, nowTicks); Interlocked.Exchange(ref _lastRefusalTicks, nowTicks); } /// /// as the endpoint statistics keep it: secret key=value pairs and URI passwords masked /// (), and every value this endpoint knows to be secret masked wherever it /// stands, plain or URL-escaped, such as a bot token in the path of a request URL. The secrets are the /// options of the endpoint and the URI parameters whose names are sensitive. /// internal string Masked(string? text) { var masked = EndpointUri.RedactSecrets(text); if (masked.Length == 0) return masked; foreach (var secret in _secretValues ??= SecretValues()) masked = masked.Replace(secret, EndpointUri.Redacted, StringComparison.Ordinal); return masked; } private string[] SecretValues() { var values = Options.SensitiveValues() .Concat(Uri.RawParameters.Where(p => EndpointUri.IsSensitiveKey(p.Key)).Select(p => p.Value)) .Where(v => v.Length >= MinSecretLength); return values .SelectMany(v => new[] { v, System.Uri.EscapeDataString(v) }) .Distinct(StringComparer.Ordinal) .OrderByDescending(v => v.Length) .ToArray(); } // ── Utility ── /// Estimate size of exchange body in bytes (for byte-volume tracking). internal static int EstimateBodySize(object? body) { if (body is null) return 0; if (body is string str) return Encoding.UTF8.GetByteCount(str); if (body is byte[] bytes) return bytes.Length; if (body is ReadOnlyMemory rom) return rom.Length; if (body is ArraySegment seg) return seg.Count; // A stream is measured by its length when it has one; a forward-only stream cannot be measured without reading // it, and serializing the stream object would count its properties, not its content. if (body is Stream stream) return stream.CanSeek ? (int)Math.Min(stream.Length, int.MaxValue) : 0; // Any other object counts as 0, as Camel counts no bytes at all: serializing it on every exchange only to count // the bytes of the result doubled the serialization cost of an object route. return 0; } } Path: redb-route/redb.Route/Core/EndpointHeaderFilter.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/Core/EndpointHeaderFilter.cs ---- using redb.Route.Abstractions; namespace redb.Route.Core; /// /// The header filter strategy of one endpoint: the one its headerFilterStrategy=#name option names, resolved from /// the context registry once (by whichever producer or consumer of the endpoint is built first, on whatever thread), /// or the transport's default. A transport keeps one per endpoint. /// public sealed class EndpointHeaderFilter { private readonly Lazy _configured; /// Creates the filter of from its option value. /// The endpoint whose component's context holds the registry. /// The value of the endpoint's headerFilterStrategy option; null when unset. public EndpointHeaderFilter(IEndpoint endpoint, string? reference) { ArgumentNullException.ThrowIfNull(endpoint); // A failed resolution is not cached: a bean registered afterwards is found on the next attempt. _configured = new Lazy(() => HeaderFilterStrategies.Resolve( (endpoint.Component as ComponentBase)?.Context, reference, $"{endpoint.Uri.Scheme} endpoint '{EndpointUri.Sanitize(endpoint.Uri.NormalizedKey)}'"), LazyThreadSafetyMode.PublicationOnly); } /// /// The strategy the endpoint names, or when it names none. A name the registry /// does not hold fails here. /// public IHeaderFilterStrategy Or(IHeaderFilterStrategy transportDefault) => _configured.Value ?? transportDefault; /// /// The strategy the endpoint names, or null when it names none: for a component with no default strategy /// (direct-vm:, vm:), which then carries every header as it always has. A name the registry does not /// hold fails here. /// public IHeaderFilterStrategy? Configured => _configured.Value; } Path: redb-route/redb.Route/Core/EndpointOptions.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/Core/EndpointOptions.cs ---- using System.Collections.Concurrent; using System.Reflection; using System.Text.RegularExpressions; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Core; /// /// Base class for all endpoint options. Handles URI parameter binding via reflection. /// Subclass per component with typed properties. BindFromUri maps string params to properties. /// public abstract class EndpointOptions { private Dictionary? _unmapped; // Options types whose [Sensitive] properties have already been registered. Reflection runs // once per type, not per endpoint. Weak per type: the options of a component an unloadable module // (collectible load context) declares do not stay alive here. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable _sensitiveScanned = new(); private static readonly object Scanned = new(); /// /// Feeds every -marked property name of /// into , so the URI renderer redacts those parameters /// by declaration instead of by name-guessing. Runs once per options type. /// /// This is the .NET equivalent of the Camel build plugin that generates /// SensitiveUtils.SENSITIVE_KEYS from @UriParam(secret = true): the keyword set is /// derived from the declarations, never hand-written. Note the harvest is lazy — it happens when /// an options type is first bound — so the name-keyword backstop in /// still matters for a URI rendered before any endpoint /// of that scheme exists. /// /// private static void RegisterSensitiveKeys(Type type) { if (!_sensitiveScanned.TryAdd(type, Scanned)) return; // A member of an option group is written group.member: that is the key to mask. var names = BindableOptions(type) .Where(o => o.Member.IsDefined(typeof(SensitiveAttribute), inherit: true)) .Select(o => o.Name) .ToArray(); if (names.Length > 0) EndpointUri.AddSensitiveKeys(names); } /// /// The values of this instance's -marked string properties that are set: what the /// endpoint knows to be secret, so a text that quotes one (a token in a request URL, a key in a driver message) can /// be masked by value. /// internal IEnumerable SensitiveValues() => BindableOptions(GetType()) .Where(o => o.Member.PropertyType == typeof(string) && o.Member.GetIndexParameters().Length == 0 && o.Member.IsDefined(typeof(SensitiveAttribute), inherit: true)) .Select(o => (o.Group is null ? this : o.Group.GetValue(this)) is { } owner ? o.Member.GetValue(owner) as string : null) .OfType() .Where(v => v.Length > 0); /// /// One option as a URI writes it: is the parameter name (the property's name, or /// Group.Member for a member of an option group, or Group for its /// value member); is the property the value goes /// into; is the group property that holds it, null for an option of the endpoint itself. /// public sealed record BindableOption(string Name, PropertyInfo Member, PropertyInfo? Group); // Weak per options type, as _sensitiveScanned. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable> _bindable = new(); /// /// The options a URI can set on , by the parameter name it writes: each settable /// property, and for an option group each of its members as /// Group.Member (and its value member as Group). The binder, the masking of [Sensitive] options and the /// Route-XML catalog all read this one list. Read by reflection, without an endpoint. /// public static IReadOnlyList BindableOptions(Type optionsType) { ArgumentNullException.ThrowIfNull(optionsType); return _bindable.GetValue(optionsType, static type => { var options = new List(); foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite)) { if (!property.IsDefined(typeof(OptionGroupAttribute), inherit: true)) { options.Add(new BindableOption(property.Name, property, null)); continue; } var groupType = property.PropertyType; if (!groupType.IsClass || groupType == typeof(string) || groupType.GetConstructor(Type.EmptyTypes) is null) throw new InvalidOperationException( $"{type.Name}.{property.Name} is an [OptionGroup]: its type must be a class with a public " + "parameterless constructor."); var members = groupType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite).ToArray(); var values = members.Where(m => m.IsDefined(typeof(OptionGroupValueAttribute), inherit: true)).ToArray(); if (values.Length > 1) throw new InvalidOperationException( $"{groupType.Name} marks {values.Length} members [OptionGroupValue]; the bare {property.Name}= binds one."); foreach (var member in members) options.Add(new BindableOption( member == values.FirstOrDefault() ? property.Name : $"{property.Name}.{member.Name}", member, property)); } return options; }); } /// Parameters from URI that were not mapped to typed properties. public IReadOnlyDictionary UnmappedParameters => _unmapped ?? (IReadOnlyDictionary)new Dictionary(0); /// /// Binds raw string parameters from URI to typed properties. /// - string/int/bool properties: standard conversion. /// - DynamicValue{T} properties with ${...}: compiled expression (one time). /// - DynamicValue{T} properties without ${...}: static wrap. /// - Unmatched parameters go to UnmappedParameters; unless the options type is /// lenient, they are then refused with /// , each one named with the nearest option. /// - A known option whose value does not convert to its type is refused with /// : the option must not silently keep its default. /// /// Raw string parameters from EndpointUriParser. public void BindFromUri(IReadOnlyDictionary parameters) { // Harvest [Sensitive] declarations before anything else, so the set is populated even for // an endpoint whose URI carries no parameters at all. RegisterSensitiveKeys(GetType()); if (parameters.Count == 0) return; _unmapped = new Dictionary(StringComparer.OrdinalIgnoreCase); var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); var options = BindableOptions(GetType()); foreach (var (key, rawValue) in parameters) { var option = options.FirstOrDefault(o => o.Name.Equals(key, StringComparison.OrdinalIgnoreCase)); if (option is null) { if (GroupOf(options, key) is { } group) throw UnknownGroupMember(options, group, key); if (options.Any(o => o.Group is { } g && g.Name.Equals(key, StringComparison.OrdinalIgnoreCase))) throw BareGroup(options, key); _unmapped[key] = rawValue; continue; } var prop = option.Member; var target = option.Group is { } groupProperty ? GroupInstance(groupProperty) : this; var propType = prop.PropertyType; if (IsDynamicValueType(propType, out var innerType)) { if (!BindDynamicValue(prop, target, rawValue, innerType!)) throw Unconvertible(prop, key, rawValue, innerType!, acceptsExpressions: true); } else { var converted = ConvertValue(rawValue, propType); if (converted == null) throw Unconvertible(prop, key, rawValue, propType, acceptsExpressions: false); prop.SetValue(target, converted); } } if (WrittenBesideConnectionFactory(GetType(), parameters) is { Count: > 0 } beside) throw BesideConnectionFactory(parameters, beside); if (_unmapped.Count > 0 && !IsLenient(GetType())) throw UnknownParameters(props); } /// /// Whether takes parameters it has no property for /// (). Read by reflection, without an endpoint. /// public static bool IsLenient(Type optionsType) { ArgumentNullException.ThrowIfNull(optionsType); return optionsType.IsDefined(typeof(LenientPropertiesAttribute), inherit: true); } // Weak per options type, as _sensitiveScanned. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable _connectionDeclarations = new(); private sealed record ConnectionDeclaration(PropertyInfo? Reference, HashSet Parameters); /// /// The parameters wrote, as written, that a connection factory sets /// (), when the URI also names a factory /// (). Empty when it names none. The core refuses them when the /// options are bound; tooling asks the same question without an endpoint. /// /// The type declares connection parameters but no factory reference, or more than one. public static IReadOnlyList WrittenBesideConnectionFactory(Type optionsType, EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); return WrittenBesideConnectionFactory(optionsType, uri.RawParameters); } private static IReadOnlyList WrittenBesideConnectionFactory(Type optionsType, IReadOnlyDictionary parameters) { ArgumentNullException.ThrowIfNull(optionsType); var (reference, connectionParameters) = ConnectionDeclarations(optionsType); if (reference is null || !parameters.Any(p => p.Key.Equals(reference.Name, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(p.Value))) return []; return parameters.Keys.Where(connectionParameters.Contains).ToList(); } private static ConnectionDeclaration ConnectionDeclarations(Type optionsType) => _connectionDeclarations.GetValue(optionsType, static type => { var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); var parameters = props.Where(p => p.IsDefined(typeof(ConnectionParameterAttribute), inherit: true)) .Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); var references = props.Where(p => p.IsDefined(typeof(ConnectionFactoryReferenceAttribute), inherit: true)).ToArray(); if (references.Length > 1) throw new InvalidOperationException( $"{type.Name} marks {references.Length} options [ConnectionFactoryReference]; one option names the factory."); if (parameters.Count > 0 && references.Length == 0) throw new InvalidOperationException( $"{type.Name} declares [ConnectionParameter] options but no [ConnectionFactoryReference] option: the core " + "does not guess which option names the connection factory."); return new ConnectionDeclaration(references.FirstOrDefault(), parameters); }); private ArgumentException BesideConnectionFactory(IReadOnlyDictionary parameters, IReadOnlyList beside) { var reference = ConnectionDeclarations(GetType()).Reference!; var factory = parameters.First(p => p.Key.Equals(reference.Name, StringComparison.OrdinalIgnoreCase)); // By name only: the values are connection settings, credentials among them. return new ArgumentException( $"{EndpointName(GetType())} endpoint: {factory.Key} '{factory.Value}' sets the whole connection, so " + $"{string.Join(", ", beside)} cannot be given on the URI as well. Set them on the factory, or drop " + $"{factory.Key} and give the connection on the URI.", beside[0]); } private static string EndpointName(Type optionsType) { var name = optionsType.Name; foreach (var suffix in new[] { "EndpointOptions", "Options" }) if (name.EndsWith(suffix, StringComparison.Ordinal) && name.Length > suffix.Length) return name[..^suffix.Length]; return name; } /// The side of an endpoint that reads (); null for both. public static EndpointRole? RoleOf(PropertyInfo option) { ArgumentNullException.ThrowIfNull(option); return option.GetCustomAttribute(inherit: true)?.Role; } /// /// The parameters wrote, as written, whose option only the other side of an endpoint reads: /// a consumer being created ( = ) gets the /// producer-only ones, and the other way round. The connector refuses them, naming the parameters and never their /// values. /// /// The endpoint's options type. /// The endpoint URI as written. /// The side being created. public static IReadOnlyList WrittenForOtherRole(Type optionsType, EndpointUri uri, EndpointRole creating) { ArgumentNullException.ThrowIfNull(optionsType); ArgumentNullException.ThrowIfNull(uri); // A member of an option group belongs to the side its group belongs to. var otherSide = BindableOptions(optionsType) .Where(o => RoleOf(o.Group ?? o.Member) is { } role && role != creating) .Select(o => o.Name) .ToHashSet(StringComparer.OrdinalIgnoreCase); return uri.RawParameters.Keys.Where(otherSide.Contains).ToList(); } /// /// A connector's own words for a parameter name it does not know — typically a name it used to /// take and what replaced it — appended to the core refusal, which already names the nearest /// option. null = nothing to add. /// /// The parameter as the URI wrote it. protected virtual string? UnknownParameterHint(string name) => null; private ArgumentException UnknownParameters(PropertyInfo[] props) { var endpoint = EndpointName(GetType()); var names = props.Where(p => p.CanWrite).Select(p => char.ToLowerInvariant(p.Name[0]) + p.Name[1..]).ToArray(); // By name only: the value may be a secret. var parts = _unmapped!.Keys.Select(key => { var text = $"'{key}' is not an option of the {endpoint} endpoint."; if (UnknownParameterHint(key) is { Length: > 0 } hint) return text + " " + hint; return Nearest(key, names) is { } nearest ? $"{text} Did you mean '{nearest}'?" : text; }); return new ArgumentException(string.Join(" ", parts), _unmapped.Keys.First()); } /// The option name closest to a misspelt one, or null when none is close. private static string? Nearest(string name, string[] candidates) { string? best = null; var bestDistance = int.MaxValue; foreach (var candidate in candidates) { var distance = EditDistance(name.ToLowerInvariant(), candidate.ToLowerInvariant()); if (distance < bestDistance) { best = candidate; bestDistance = distance; } } // A third of the name, at least two edits: "tll" finds "ttl", "foo" finds nothing. return bestDistance <= Math.Max(2, name.Length / 3) ? best : null; } private static int EditDistance(string a, string b) { var previous = new int[b.Length + 1]; var current = new int[b.Length + 1]; for (var j = 0; j <= b.Length; j++) previous[j] = j; for (var i = 1; i <= a.Length; i++) { current[0] = i; for (var j = 1; j <= b.Length; j++) current[j] = Math.Min(Math.Min(current[j - 1] + 1, previous[j] + 1), previous[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1)); (previous, current) = (current, previous); } return previous[b.Length]; } /// /// A connector's own words for an option whose value was refused (what the modes mean, which /// one to pick), appended to the core message that already names the value and what the option /// takes. null = nothing to add. /// /// The option's property name. protected virtual string? OptionValueHint(string optionName) => null; private ArgumentException Unconvertible(PropertyInfo prop, string key, string rawValue, Type type, bool acceptsExpressions) { var shown = prop.IsDefined(typeof(SensitiveAttribute), inherit: true) ? "***" : rawValue; var message = $"'{key}={shown}' is not a valid value: {key} takes {Describe(key, type)}."; if (!acceptsExpressions && rawValue.Contains("${", StringComparison.Ordinal)) message += " This option does not accept ${...} expressions; use a constant or a {{property}} placeholder."; if (OptionValueHint(prop.Name) is { Length: > 0 } hint) message += " " + hint; return new ArgumentException(message, key); } private static string Describe(string key, Type type) { type = Nullable.GetUnderlyingType(type) ?? type; if (type.IsEnum) // Written the way the URI takes them, so the message can be copied back as is. return "one of " + string.Join(", ", Enum.GetNames(type).Select(n => $"{key}={n.ToLowerInvariant()}")); if (type == typeof(bool)) return "true or false"; if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte) || type == typeof(uint) || type == typeof(ulong) || type == typeof(ushort) || type == typeof(sbyte)) return $"a whole number ({type.Name})"; if (type == typeof(double) || type == typeof(float) || type == typeof(decimal)) return "a number with a '.' decimal point"; if (type == typeof(TimeSpan)) return "a time span (hh:mm:ss)"; return type.Name; } /// Validates required parameters and constraints. Called after BindFromUri. public abstract void Validate(); private ConcurrentDictionary>? _expressionCache; /// /// Resolves a string option value per message. /// If the value contains ${...} expressions, compiles it once and evaluates per exchange. /// Static values pass through with only a fast Contains check. /// /// Option value (may contain ${...} expressions). /// Current exchange for expression resolution. /// Resolved value, or the original value if no expressions found. public string? ResolveOption(string? value, IExchange exchange) { if (value is null || !value.Contains("${")) return value; _expressionCache ??= new(); var resolver = _expressionCache.GetOrAdd(value, static v => ExpressionResolver.GetCompiledTemplate(v)); return resolver(exchange); } private static bool IsDynamicValueType(Type type, out Type? innerType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(DynamicValue<>)) { innerType = type.GenericTypeArguments[0]; return true; } // Nullable> var underlying = Nullable.GetUnderlyingType(type); if (underlying != null && underlying.IsGenericType && underlying.GetGenericTypeDefinition() == typeof(DynamicValue<>)) { innerType = underlying.GenericTypeArguments[0]; return true; } innerType = null; return false; } /// Binds a dynamic option; false when a plain value does not convert. /// The option group a group.member key names by its prefix; null when the key names none. private static PropertyInfo? GroupOf(IReadOnlyList options, string key) { var dot = key.IndexOf('.'); if (dot <= 0) return null; var prefix = key[..dot]; return options.Select(o => o.Group).FirstOrDefault(g => g is not null && g.Name.Equals(prefix, StringComparison.OrdinalIgnoreCase)); } /// The group object of on this instance, created on first use. private object GroupInstance(PropertyInfo group) { if (group.GetValue(this) is { } existing) return existing; var created = Activator.CreateInstance(group.PropertyType)!; group.SetValue(this, created); return created; } // The name as a URI writes it: each segment camelCase (searchTerm.fromSentDate). private static string OptionName(string name) => string.Join('.', name.Split('.').Select(part => part.Length == 0 ? part : char.ToLowerInvariant(part[0]) + part[1..])); private static string MembersOf(IReadOnlyList options, PropertyInfo group) => string.Join(", ", options.Where(o => o.Group == group).Select(o => OptionName(o.Name))); private ArgumentException UnknownGroupMember(IReadOnlyList options, PropertyInfo group, string key) { // By name only: the value may be a secret. var text = $"'{key}' is not an option of the {EndpointName(GetType())} endpoint: the group {OptionName(group.Name)} " + $"takes {MembersOf(options, group)}."; var names = options.Where(o => o.Group == group).Select(o => OptionName(o.Name)).ToArray(); return new ArgumentException(Nearest(key, names) is { } nearest ? $"{text} Did you mean '{nearest}'?" : text, key); } private ArgumentException BareGroup(IReadOnlyList options, string key) { var group = options.First(o => o.Group is { } g && g.Name.Equals(key, StringComparison.OrdinalIgnoreCase)).Group!; return new ArgumentException( $"'{key}' is a group of options of the {EndpointName(GetType())} endpoint, written {OptionName(group.Name)}.member: " + $"{MembersOf(options, group)}.", key); } private static bool BindDynamicValue(PropertyInfo prop, object target, string rawValue, Type innerType) { var dvType = typeof(DynamicValue<>).MakeGenericType(innerType); // Detect ${...} expression → create dynamic value via StringExpression if (Expressions.TemplateScanner.HasPlaceholder(rawValue)) { var expression = new StringExpression(rawValue); var fromExpr = dvType.GetMethod("FromExpression", [typeof(Abstractions.IExpression)])!; var dv = fromExpr.Invoke(null, [expression]); prop.SetValue(target, dv); return true; } // Plain value → static wrap var converted = ConvertValue(rawValue, innerType); if (converted == null) return false; var fromStatic = dvType.GetMethod("FromStatic")!; var dv2 = fromStatic.Invoke(null, [converted]); prop.SetValue(target, dv2); return true; } private static object? ConvertValue(string rawValue, Type targetType) { var converted = OptionValueConverter.Convert(rawValue, targetType); // Enum.Parse also takes a number, which may name no member at all. A [Flags] enum is left // alone: its valid values are combinations, not members. var enumType = Nullable.GetUnderlyingType(targetType) ?? targetType; if (converted is not null && enumType.IsEnum && !enumType.IsDefined(typeof(FlagsAttribute), inherit: false) && !Enum.IsDefined(enumType, converted)) return null; return converted; } /// /// Registers the -marked property names of an arbitrary type /// with the URI redaction set — the same harvest performs for options /// types, reusable by components that bind URI parameters onto user objects (bean:). /// internal static void RegisterSensitiveKeysFor(Type type) => RegisterSensitiveKeys(type); } /// /// The one string-to-typed-value converter behind , /// extracted for reuse (bean: property binding, the XML loader's value /// conversion). Invariant culture throughout; an unconvertible value yields null and the caller /// decides whether that is an error or an unmapped parameter. /// internal static class OptionValueConverter { /// Converts a raw URI/attribute string to , or null. internal static object? Convert(string rawValue, Type targetType) { try { if (targetType == typeof(string)) return rawValue; if (targetType == typeof(int)) return int.Parse(rawValue, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(long)) return long.Parse(rawValue, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(bool)) return bool.Parse(rawValue); // Float, not the default Float | AllowThousands: "1,5" is a comma typed for a decimal // point, and reading it as 15 would be a silent wrong value. if (targetType == typeof(double)) return double.Parse(rawValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(float)) return float.Parse(rawValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(decimal)) return decimal.Parse(rawValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(TimeSpan)) return TimeSpan.Parse(rawValue, System.Globalization.CultureInfo.InvariantCulture); if (targetType.IsEnum) return Enum.Parse(targetType, rawValue, ignoreCase: true); // Nullable var underlying = Nullable.GetUnderlyingType(targetType); if (underlying != null) return Convert(rawValue, underlying); return System.Convert.ChangeType(rawValue, targetType, System.Globalization.CultureInfo.InvariantCulture); } catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException or ArgumentException) { // Not convertible to the requested type: the caller treats null as "unmapped" (options) // or as a declaration error (bean:). Anything else — reflection failures, type-load // errors — keeps flying. return null; } } } Path: redb-route/redb.Route/Core/EndpointRoleAttribute.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/Core/EndpointRoleAttribute.cs ---- namespace redb.Route.Core; /// The side of an endpoint that reads an option, or the only side a component has. public enum EndpointRole { /// Read only by the consumer (from(...)). Consumer, /// Read only by the producer (to(...)). Producer, } /// /// Declares that only one side of an endpoint reads this option — Camel's @UriParam(label = "consumer") / /// label = "producer". An options class shared by producer and consumer otherwise gives no sign that an option /// written on the other side does nothing: username on an http: consumer looked like protection and checked /// nobody. The connector refuses such an option by this declaration /// (), and tooling — the Route-XML catalog, the editor schema, /// check — reads the same declaration by reflection. An option both sides read carries no role. /// /// On a component class it declares the only side the component has: Apache Camel's producerOnly / /// consumerOnly. [EndpointRole(EndpointRole.Producer)] on smtp means a route cannot start from it; /// the context refuses such a route, and the catalog, the editor schema and check read the same declaration /// (). A component with both sides carries none. /// /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class EndpointRoleAttribute(EndpointRole role) : Attribute { /// The side that reads the option, or the only side of the component. public EndpointRole Role { get; } = role; /// /// On a component: what to use instead, appended to the refusal of the missing side /// ("Use imap: or pop3: to receive mail."). Not read on an option. /// public string? Hint { get; init; } } Path: redb-route/redb.Route/Core/EndpointSides.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/Core/EndpointSides.cs ---- using System.Reflection; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// The sides of a component: both, unless its class declares the only one it has with /// (Apache Camel's producerOnly / consumerOnly). The context, the /// Route-XML catalog, the editor schema and check all read this one declaration, and refuse the missing side /// in the one message builds. /// public static class EndpointSides { /// The declaration on ; null for both sides. public static EndpointRoleAttribute? Declaration(Type componentType) { ArgumentNullException.ThrowIfNull(componentType); return componentType.GetCustomAttribute(inherit: true); } /// The only side has; null for both. public static EndpointRole? Of(IComponent component) { ArgumentNullException.ThrowIfNull(component); return Declaration(component.GetType())?.Role; } /// /// The refusal of the side does not have, given the only one it has, with the /// component's hint when there is one. /// public static string MissingSide(string scheme, EndpointRole only, string? hint) { var text = only == EndpointRole.Producer ? $"{scheme} has no consumer side: a route cannot start from it ({scheme} is producer-only)." : $"{scheme} has no producer side: a route cannot send to it ({scheme} is consumer-only)."; return string.IsNullOrWhiteSpace(hint) ? text : text + " " + hint; } /// /// Throws , the exception the components throw themselves, when /// 's component has no side. /// public static void Refuse(IEndpoint endpoint, EndpointRole creating) { ArgumentNullException.ThrowIfNull(endpoint); if (Declaration(endpoint.Component.GetType()) is not { } declaration || declaration.Role == creating) return; throw new NotSupportedException(MissingSide(endpoint.Uri.Scheme, declaration.Role, declaration.Hint)); } /// The producer of , once found that it has one. public static IProducer CreateProducerOnItsSide(this IEndpoint endpoint) { Refuse(endpoint, EndpointRole.Producer); return endpoint.CreateProducer(); } /// The consumer of , once found that it has one. public static IConsumer CreateConsumerOnItsSide(this IEndpoint endpoint, IProcessor processor) { Refuse(endpoint, EndpointRole.Consumer); return endpoint.CreateConsumer(processor); } } Path: redb-route/redb.Route/Core/EndpointUriParser.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/Core/EndpointUriParser.cs ---- using System.Linq; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Single URI parser for the entire framework. Handles all endpoint URI formats: /// - Standard: scheme://path?key=value&key=value /// - Colon-path: redis:GET:user:123?ttl=60 /// - Topic: kafka://my-topic?brokers=localhost:9092 /// public static class EndpointUriParser { /// Parses a route URI into normalized parts. /// Raw endpoint URI string. /// Parsed EndpointUri with scheme, path, cache key, and parameters. /// If the URI format is invalid. public static EndpointUri Parse(string uri) { if (string.IsNullOrWhiteSpace(uri)) throw new ArgumentException("Endpoint URI cannot be null or empty.", nameof(uri)); // Split query string var queryIndex = uri.IndexOf('?'); var basePart = queryIndex >= 0 ? uri[..queryIndex] : uri; var queryPart = queryIndex >= 0 ? uri[(queryIndex + 1)..] : null; // Parse scheme and path string scheme; string path; var doubleSlashIndex = basePart.IndexOf("://", StringComparison.Ordinal); if (doubleSlashIndex > 0) { // Standard format: scheme://path scheme = basePart[..doubleSlashIndex].ToLowerInvariant(); path = basePart[(doubleSlashIndex + 3)..]; } else { // Colon format: scheme:path (e.g., redis:GET:user:123) var colonIndex = basePart.IndexOf(':'); if (colonIndex <= 0) throw new ArgumentException($"Invalid endpoint URI format: '{EndpointUri.Sanitize(uri)}'. Expected scheme://path or scheme:path.", nameof(uri)); scheme = basePart[..colonIndex].ToLowerInvariant(); path = basePart[(colonIndex + 1)..]; } if (string.IsNullOrEmpty(scheme)) throw new ArgumentException($"Empty scheme in URI: '{EndpointUri.Sanitize(uri)}'.", nameof(uri)); // Parse query parameters var parameters = ParseQueryString(queryPart); // Normalize key: scheme://path?sorted_params (includes params for unique endpoint identity) var normalizedKey = parameters.Count == 0 ? $"{scheme}://{path}" : $"{scheme}://{path}?{string.Join("&", parameters.OrderBy(p => p.Key, StringComparer.OrdinalIgnoreCase).Select(p => $"{p.Key}={p.Value}"))}"; return new EndpointUri(scheme, path, normalizedKey, parameters); } private static IReadOnlyDictionary ParseQueryString(string? query) { if (string.IsNullOrEmpty(query)) return new Dictionary(0); var result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var eqIndex = pair.IndexOf('='); if (eqIndex > 0) { var key = Uri.UnescapeDataString(pair[..eqIndex]); var value = Uri.UnescapeDataString(pair[(eqIndex + 1)..]); result[key] = value; } else if (pair.Length > 0) { // Flag parameter without value result[Uri.UnescapeDataString(pair)] = string.Empty; } } return result; } } Path: redb-route/redb.Route/Core/Exchange.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/Core/Exchange.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Default implementation of IExchange. /// In is always present, Out is lazy (null by default for InOnly routes). /// public class Exchange : IExchange { private readonly Dictionary _properties = new(StringComparer.OrdinalIgnoreCase); private volatile bool _stopped; private IServiceScope? _scope; private IServiceScopeFactory? _scopeFactory; private bool _ownsScope = true; private int _scopesReleased; // 0 = not released, 1 = released (Interlocked) // Body ownership, as a Camel unit of work: the exchange that owns a body disposes it, once, when it is done. A copy // shares its origin's body by reference, so it disposes only a body no ancestor carries or lent it; one an ancestor // carries (the aggregated result, a merged-back body) goes on that ancestor's account instead. private Exchange? _origin; private HashSet? _lent; // disposable bodies this exchange lent to its copies or took over from them private readonly object _bodiesLock = new(); private bool _bodiesReleased; // under _bodiesLock /// public IMessage In { get; set; } /// public IMessage? Out { get; set; } /// public bool HasOut => Out != null; /// public ExchangePattern Pattern { get; set; } = ExchangePattern.InOnly; /// public IDictionary Properties => _properties; /// public Exception? Exception { get; set; } /// public bool ExceptionHandled { get; set; } /// public string? RouteId { get; set; } /// /// /// Set by the route wrapper on entry and restored on exit; the setter is internal so only the /// pipeline stamps it. /// public IRouteContext? Context { get; internal set; } /// /// The inbound span of the transport that delivered this exchange — kept by the route wrapper for /// .SpanTag(..., SpanTarget.Inbound), restored on exit. Not part of , and not carried /// by a : a replayed checkpoint runs long after that span ended. Copies made while the route /// runs (split, multicast, a detached branch) carry it; one that outlives it finds it stopped and writes nothing. /// internal System.Diagnostics.Activity? InboundSpan { get; set; } /// public string ExchangeId { get; private set; } = Guid.NewGuid().ToString("N"); /// public bool IsStopped => _stopped; /// public IServiceProvider? ServiceProvider => _scope?.ServiceProvider; /// Creates an exchange with a new empty In message. public Exchange() : this(new Message()) { } /// Creates an exchange with the specified In message. /// The primary message. public Exchange(IMessage inMessage) { In = inMessage ?? throw new ArgumentNullException(nameof(inMessage)); } /// Creates an exchange with DI scope support. /// The primary message. /// Factory for creating the scoped service provider. public Exchange(IMessage inMessage, IServiceScopeFactory scopeFactory) : this(inMessage) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _scope = _scopeFactory.CreateScope(); } /// Creates an exchange, optionally with a per-exchange DI scope. public static Exchange Create(IMessage message, IServiceScopeFactory? scopeFactory) { ArgumentNullException.ThrowIfNull(message); return scopeFactory != null ? new Exchange(message, scopeFactory) : new Exchange(message); } /// public T? GetProperty(string key) => _properties.TryGetValue(key, out var value) ? TypedValue.Convert(value, $"property '{key}'") : default; /// public void Stop() => _stopped = true; /// public IExchange Clone() { var clone = new Exchange((Message)In.Clone()) { Pattern = Pattern, RouteId = RouteId, Context = Context, InboundSpan = InboundSpan, Exception = Exception, ExceptionHandled = ExceptionHandled }; // preserve the same ExchangeId for clones clone.ExchangeId = ExchangeId; if (Out != null) clone.Out = Out.Clone(); LendBodiesTo(clone); foreach (var kvp in _properties) { // Named redb scopes are per-exchange; child will create its own on first access. if (ExchangeResources.IsOwnedByExchange(kvp.Key)) continue; clone._properties[kvp.Key] = kvp.Value; } if (_scopeFactory != null) { clone._scopeFactory = _scopeFactory; clone._scope = _scopeFactory.CreateScope(); } return clone; } /// public IExchange Snapshot() { // Same shape as Clone but the message body is deep-copied (In.Snapshot / Out.Snapshot), // so the captured state is frozen against later in-place mutation of the payload. var snapshot = new Exchange((Message)In.Snapshot()) { Pattern = Pattern, RouteId = RouteId, Context = Context, Exception = Exception, ExceptionHandled = ExceptionHandled }; snapshot.ExchangeId = ExchangeId; if (Out != null) snapshot.Out = Out.Snapshot(); LendBodiesTo(snapshot); foreach (var kvp in _properties) { // Named redb scopes are per-exchange; the snapshot creates its own on first access. if (ExchangeResources.IsOwnedByExchange(kvp.Key)) continue; // Property values are shared (route metadata, not payload) — see Snapshot doc. snapshot._properties[kvp.Key] = kvp.Value; } // NO DI scope is created here. A checkpoint snapshot is dormant data captured on every // marker pass and usually never replayed — minting a scope per capture would leak one per // message (the exact class of leak the 3.3.4 connection-leak work closed). The factory // reference is kept so a replay can mint (and dispose) a scope on demand; a snapshot that is // never replayed owns no scope and leaks nothing. snapshot._scopeFactory = _scopeFactory; snapshot._ownsScope = false; // _scope stays null return snapshot; } /// public IExchange CreateChild(IMessage message) { ArgumentNullException.ThrowIfNull(message); var child = new Exchange(message) { Pattern = Pattern, RouteId = RouteId, Context = Context, InboundSpan = InboundSpan }; foreach (var kvp in _properties) { // Named redb scopes are per-exchange; child will create its own on first access. if (ExchangeResources.IsOwnedByExchange(kvp.Key)) continue; child._properties[kvp.Key] = kvp.Value; } if (_scopeFactory != null) { child._scopeFactory = _scopeFactory; child._scope = _scopeFactory.CreateScope(); } // Its message is its own; a body it hands back to this exchange stays on this exchange's account. child._origin = this; return child; } /// public IExchange CreateLinkedChild(IMessage message) { ArgumentNullException.ThrowIfNull(message); var child = new Exchange(message) { Pattern = Pattern, RouteId = RouteId, Context = Context, InboundSpan = InboundSpan, _ownsScope = false, _scope = _scope, _scopeFactory = _scopeFactory }; foreach (var kvp in _properties) { if (ExchangeResources.IsOwnedByExchange(kvp.Key)) continue; child._properties[kvp.Key] = kvp.Value; } child._origin = this; return child; } /// public IExchange CloneLinked() { var clone = new Exchange((Message)In.Clone()) { Pattern = Pattern, RouteId = RouteId, Context = Context, InboundSpan = InboundSpan, Exception = Exception, ExceptionHandled = ExceptionHandled, _ownsScope = false, _scope = _scope, _scopeFactory = _scopeFactory }; // preserve the same ExchangeId for clones clone.ExchangeId = ExchangeId; if (Out != null) clone.Out = Out.Clone(); LendBodiesTo(clone); foreach (var kvp in _properties) { if (ExchangeResources.IsOwnedByExchange(kvp.Key)) continue; clone._properties[kvp.Key] = kvp.Value; } return clone; } /// public IExchange CorrelatedCopy() => Correlate((Exchange)Clone()); /// public IExchange CorrelatedCopyLinked() => Correlate((Exchange)CloneLinked()); /// /// Gives an id of its own and points it back at this exchange, as Camel's /// createCorrelatedCopy does: the correlation id is this exchange's id, the immediate parent's. /// private Exchange Correlate(Exchange copy) { copy.ExchangeId = Guid.NewGuid().ToString("N"); copy._properties[ExchangePropertyKeys.CorrelationId] = ExchangeId; return copy; } /// public async ValueTask ReleaseScopes() { // In-progress guard, not a one-shot latch. This method is public API and downstream code // calls it manually in error handlers; a latch spent on that call would leave any scope // cached on the exchange AFTERWARDS — an error handler's tail touching redb again does // exactly that — invisible to DisposeAsync forever. Re-arming after each sweep keeps every // guarantee the latch gave (concurrent calls don't double-sweep, nothing is disposed // twice — entries leave the property bag as they are released and the owned scope nulls // out) without the mine. if (Interlocked.CompareExchange(ref _scopesReleased, 1, 0) != 0) return; try { await ReleaseScopesCore().ConfigureAwait(false); } finally { // The re-arm lives in a finally so that a throw mid-sweep cannot leave the guard // stuck — that would be this method's old defect made permanent. Interlocked.Exchange(ref _scopesReleased, 0); } } private async ValueTask ReleaseScopesCore() { // Grab a logger up front — ILoggerFactory is a singleton, so it survives disposing the scope // it's resolved from. A dispose fault below (e.g. a broken DB transaction that throws when // disposed) must be observable — logged, not silently eaten — and must NOT abort disposal of // the remaining scopes: each disposal is isolated in its own try so one throw can't strand // sibling scopes (which would re-introduce the very connection leak this guards against). ILogger? logger = null; // An exchange without a DI scope (a ProducerTemplate, a test) still has its context to log through. try { logger = (_scope?.ServiceProvider?.GetService() ?? Context?.GetService()) ?.CreateLogger("redb.Route.Exchange"); } catch { /* logger is best-effort; disposal proceeds regardless */ } // An exchange that entered no route of its own (a Split or Multicast branch, the copy .Threads() continues on, one // processed outside any route) ends its unit of work here, with the outcome it carries, while its scopes are still // alive. A unit of work a route opened is that route's to end — a release in the middle of it leaves it alone. if (_properties.TryGetValue(ExchangeUnitOfWork.PropertyKey, out var unitOfWorkValue) && unitOfWorkValue is ExchangeUnitOfWork { OwnedByRoute: false } unitOfWork) await unitOfWork.End(this, this.EndedInFailure(), logger).ConfigureAwait(false); // Release resources registered through ExchangeResources (a streamed query result holding its connection) first: // most recent first, while the DI scopes that may own their factories are still alive. Each release is isolated, // like the scopes below, so one failure cannot strand the others. var resourceKeys = _properties.Keys .Where(k => k.StartsWith(ExchangeResources.PropertyPrefix, StringComparison.Ordinal)) .OrderByDescending(k => k, StringComparer.Ordinal) .ToList(); foreach (var key in resourceKeys) { try { if (_properties.TryGetValue(key, out var val) && val is IAsyncDisposable resource) await resource.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { logger?.LogError(ex, "Releasing resource '{ResourceKey}' failed on exchange {ExchangeId} (route '{RouteId}'); remaining resources and scopes are still released.", key, ExchangeId, RouteId); } finally { _properties.Remove(key); } } // Dispose named IRedbService scopes cached by RedbRouteExtensions // and remove them from Properties, so a repeated release has nothing to dispose twice. (The aggregation merge-back // of Multicast / Splitter / Scatter-Gather / Loop skips owned keys — ExchangeResources.IsOwnedByExchange.) var namedKeys = _properties.Keys .Where(k => k.StartsWith("__redb_scope:", StringComparison.Ordinal)) .ToList(); foreach (var key in namedKeys) { try { if (_properties.TryGetValue(key, out var val) && val is IServiceScope namedScope) { if (namedScope is IAsyncDisposable asyncScope) await asyncScope.DisposeAsync().ConfigureAwait(false); else namedScope.Dispose(); } } catch (Exception ex) { logger?.LogError(ex, "Disposing cached IRedbService scope '{ScopeKey}' failed on exchange {ExchangeId} (route '{RouteId}'); remaining scopes are still released.", key, ExchangeId, RouteId); } finally { _properties.Remove(key); } } if (_ownsScope) { try { if (_scope is IAsyncDisposable ad) await ad.DisposeAsync().ConfigureAwait(false); else _scope?.Dispose(); } catch (Exception ex) { logger?.LogError(ex, "Disposing the per-exchange DI scope failed on exchange {ExchangeId} (route '{RouteId}').", ExchangeId, RouteId); } finally { _scope = null; } } } /// public async ValueTask DisposeAsync() { // The bodies this exchange owns (Stream, StreamCache, etc.): once, and not one an ancestor still carries. await ReleaseBodies().ConfigureAwait(false); // Release DI scopes if not already released via ReleaseScopes() await ReleaseScopes().ConfigureAwait(false); GC.SuppressFinalize(this); } /// /// Hands the bodies of this exchange over to , a copy that carries on with them after this /// exchange is done (.Threads()): this exchange then disposes none, the successor disposes them as their owner. /// internal void HandOverBodiesTo(Exchange successor) { HashSet bodies; lock (_bodiesLock) { bodies = OwnedBodies(); _lent = null; _bodiesReleased = true; } lock (successor._bodiesLock) { successor._origin = null; successor._bodiesReleased = false; foreach (var body in bodies) (successor._lent ??= new HashSet(ReferenceEqualityComparer.Instance)).Add(body); } } /// /// A copy that carries on with this exchange after its caller is done with it (an aggregation group): it takes the /// bodies over and keeps the DI scope factory, without a scope of its own until . /// internal Exchange TakeOver() { var copy = (Exchange)Clone(); copy._scopeFactory = _scopeFactory; HandOverBodiesTo(copy); return copy; } /// Gives the exchange a DI scope of its own when it has none and a factory to make one. internal void EnsureOwnScope() { if (_scope is not null || _scopeFactory is null) return; _scope = _scopeFactory.CreateScope(); _ownsScope = true; } private static bool IsDisposable(object? body) => body is IAsyncDisposable or IDisposable; // The disposable payload the exchange carries right now: the In and Out bodies and the content sources of their // attachments (a StreamCache, a file to delete). Attachments are payload like the body, so they follow its ownership. private IEnumerable CarriedDisposables() { if (IsDisposable(In.Body)) yield return In.Body!; if (IsDisposable(Out?.Body)) yield return Out!.Body!; foreach (var content in DisposableAttachmentContents(In)) yield return content; if (Out is not null) foreach (var content in DisposableAttachmentContents(Out)) yield return content; } private static IEnumerable DisposableAttachmentContents(IMessage message) { if (message is not Message { AttachmentsOrNull: { } attachments }) yield break; foreach (var attachment in attachments) if (IsDisposable(attachment.Content)) yield return attachment.Content; } // Called under _bodiesLock: the current disposable bodies and the ones on this exchange's account. private HashSet OwnedBodies() { var bodies = new HashSet(CarriedDisposables(), ReferenceEqualityComparer.Instance); if (_lent is not null) bodies.UnionWith(_lent); return bodies; } // A copy shares this exchange's bodies by reference: they stay on this exchange's account. private void LendBodiesTo(Exchange copy) { copy._origin = this; lock (_bodiesLock) { if (_bodiesReleased) return; foreach (var body in CarriedDisposables()) (_lent ??= new HashSet(ReferenceEqualityComparer.Instance)).Add(body); } } // Takes a body on this exchange's account when it carries it or lent it and has not been released yet. private bool TryKeep(object body) { lock (_bodiesLock) { if (_bodiesReleased) return false; if (!(_lent?.Contains(body) == true || CarriedDisposables().Any(b => ReferenceEquals(b, body)))) return false; (_lent ??= new HashSet(ReferenceEqualityComparer.Instance)).Add(body); return true; } } private async ValueTask ReleaseBodies() { HashSet bodies; lock (_bodiesLock) { if (_bodiesReleased) return; _bodiesReleased = true; bodies = OwnedBodies(); _lent = null; } foreach (var body in bodies) { // A body an ancestor still carries or lent is the ancestor's to dispose (a copy's result aggregated into it, // a body merged back, the body this copy shares with it). var kept = false; for (var ancestor = _origin; ancestor is not null && !kept; ancestor = ancestor._origin) kept = ancestor.TryKeep(body); if (kept) continue; try { if (body is IAsyncDisposable asyncDisposable) await asyncDisposable.DisposeAsync().ConfigureAwait(false); else ((IDisposable)body).Dispose(); } catch (Exception ex) { // Like the scopes: one body failing to dispose must not strand the others or the DI scopes after them. ResolveLogger()?.LogError(ex, "Disposing a message body ({BodyType}) failed on exchange {ExchangeId} (route '{RouteId}'); remaining bodies and scopes are still released.", body.GetType().Name, ExchangeId, RouteId); } } } private ILogger? ResolveLogger() { try { return (_scope?.ServiceProvider?.GetService() ?? Context?.GetService()) ?.CreateLogger("redb.Route.Exchange"); } catch (ObjectDisposedException) { return null; // the scope is gone; nothing left to log through } } } Path: redb-route/redb.Route/Core/ExchangeFailureExtensions.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/Core/ExchangeFailureExtensions.cs ---- using System.Runtime.ExceptionServices; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Consumer-side view of an exchange's terminal state. A route whose OnException has no /// Handled(true) returns normally with the exception still on the exchange; for a /// consumer that decides ack/nack by "did Process throw", that failure would be acknowledged. /// public static class ExchangeFailureExtensions { /// /// Exchange property set by .RollbackAll(), Camel's markRollbackOnly(): the unit of work is rolled /// back without an exception. /// public const string RollbackOnlyPropertyKey = "RollbackOnly"; /// Marks the unit of work for rollback: the enclosing transaction rolls back and the consumer does not acknowledge. public static void MarkRollbackOnly(this IExchange exchange) => exchange.Properties[RollbackOnlyPropertyKey] = true; /// Whether the route marked the unit of work for rollback (.RollbackAll()). public static bool IsRollbackOnly(this IExchange exchange) => exchange.Properties.TryGetValue(RollbackOnlyPropertyKey, out var value) && value is true; /// /// Exchange property set by an OnException handler that ran with Handled(true) — Apache Camel's /// ExchangeHelper.setFailureHandled. The exchange completes successfully (the consumer acknowledges), but the /// failure WAS handled by an error handler, so a dedup key guarding the failed work (the idempotent consumer) must /// not be confirmed. Cleared on continued and before every redelivery attempt. /// public const string FailureHandledPropertyKey = "FailureHandled"; /// Marks the failure an error handler handled (Camel's setFailureHandled(true)). public static void MarkFailureHandled(this IExchange exchange) => exchange.Properties[FailureHandledPropertyKey] = true; /// Clears the failure-handled marker: a redelivery, or a continued handler (Camel's setFailureHandled(false)). public static void ClearFailureHandled(this IExchange exchange) => exchange.Properties.Remove(FailureHandledPropertyKey); /// Whether an error handler handled the failure on this exchange (Camel's ExchangeHelper.isFailureHandled). public static bool IsFailureHandled(this IExchange exchange) => exchange.Properties.TryGetValue(FailureHandledPropertyKey, out var value) && value is true; /// /// Whether the unit of work did not succeed: an unhandled failure is left on the exchange, or the route marked it /// rollback-only. A consumer does not acknowledge such an exchange. /// public static bool EndedInFailure(this IExchange exchange) => (exchange.Exception is not null && !exchange.ExceptionHandled) || exchange.IsRollbackOnly(); /// /// Rethrows the exchange's unhandled failure (stack preserved) so the consumer's existing /// failure path — nack / rollback / no-ack — handles it exactly like a thrown failure. /// A handled failure () is a completed exchange and is left alone. /// A rollback-only exchange throws too: its work was rolled back, so the message must be delivered again. /// public static void ThrowIfUnhandledFailure(this IExchange exchange) { if (exchange.Exception is { } failure && !exchange.ExceptionHandled) ExceptionDispatchInfo.Capture(failure).Throw(); if (exchange.IsRollbackOnly()) throw RollbackOnlyFailure(); } /// /// The failure an exchange that returned normally ended in, as sees it: the unhandled /// exception left on it, or, for a rollback-only exchange, an exception saying so; when it /// succeeded. /// internal static Exception? FailureOf(IExchange exchange) { if (exchange.Exception is { } failure && !exchange.ExceptionHandled) return failure; return exchange.IsRollbackOnly() ? RollbackOnlyFailure() : null; } private static InvalidOperationException RollbackOnlyFailure() => new( "The route marked the exchange rollback-only (.RollbackAll()): its work was rolled back, so the message " + "is not acknowledged and the broker will deliver it again."); } Path: redb-route/redb.Route/Core/ExchangeProcessing.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/Core/ExchangeProcessing.cs ---- using redb.Route.Abstractions; using redb.Route.Telemetry; namespace redb.Route.Core; /// /// How a consumer base runs one exchange through its route, shared by and /// : what escapes the pipeline goes on the exchange, the consumer's own stop passes through, /// and a failure marks the receive span. /// internal static class ExchangeProcessing { /// /// Runs through . The route's own error handling /// (OnException, DeadLetterChannel) runs inside the pipeline, and a failure it did not handle stays on the exchange; /// what escapes is put on the exchange too, so the consumer decides on a failed route rather than a clean one, and is /// returned for the consumer's log line. A cancellation of (the consumer's stop) is /// rethrown. /// /// The exception that escaped the pipeline, or null. internal static async Task RunAsync(IProcessor processor, IExchange exchange, CancellationToken processingCt) { try { await processor.Process(exchange, processingCt).ConfigureAwait(false); return null; } catch (OperationCanceledException) when (processingCt.IsCancellationRequested) { throw; // shutdown: the consumer ends this delivery } catch (Exception ex) { exchange.Exception ??= ex; return ex; } } /// /// Whether the route failed: a failure is on the exchange, not handled, and it is not the cancellation of the /// consumer's own stop (any other cancellation, an HttpClient timeout inside the route, is a failure). /// internal static bool Failed(IExchange exchange, CancellationToken processingCt) => exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !processingCt.IsCancellationRequested); /// Marks failed when says the route failed. internal static void RecordFailure(IExchange exchange, TransportSpan span, CancellationToken processingCt) { if (Failed(exchange, processingCt)) RouteTelemetryExtensions.RecordFailure(span.Activity, exchange.Exception!); } } Path: redb-route/redb.Route/Core/ExchangeTimedOutException.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/Core/ExchangeTimedOutException.cs ---- namespace redb.Route.Core; /// /// Thrown when exchange processing exceeds the configured timeout. /// Can be caught in error handlers via OnException<ExchangeTimedOutException>(). /// public sealed class ExchangeTimedOutException : TimeoutException { /// The route where the timeout occurred. public string RouteId { get; } /// The configured timeout that was exceeded. public TimeSpan Timeout { get; } /// Actual elapsed time before cancellation. public TimeSpan Elapsed { get; } /// Creates a new instance. public ExchangeTimedOutException(string routeId, TimeSpan timeout, TimeSpan elapsed) : base($"Exchange processing timed out after {elapsed.TotalSeconds}s on route '{routeId}'.") { RouteId = routeId; Timeout = timeout; Elapsed = elapsed; } } Path: redb-route/redb.Route/Core/HeaderFilterStrategies.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/Core/HeaderFilterStrategies.cs ---- using redb.Route.Abstractions; namespace redb.Route.Core; /// /// What a transport needs to honour the headerFilterStrategy option of its endpoints. /// public static class HeaderFilterStrategies { /// /// The strategy an endpoint names by registry reference (headerFilterStrategy=#name; the # is /// optional), or null when the endpoint names none and the transport's default applies. A name the /// context registry does not hold as an is an error, raised where the endpoint /// is built: an endpoint must not run with a filter other than the one it asked for. /// /// The context whose registry holds the strategy. /// The option value. /// The endpoint, as the error names it. public static IHeaderFilterStrategy? Resolve(IRouteContext? context, string? reference, string endpoint) { if (string.IsNullOrWhiteSpace(reference)) return null; var name = reference.Trim().TrimStart('#'); if (context is null) throw new InvalidOperationException( $"{endpoint}: headerFilterStrategy '#{name}' cannot be resolved, the endpoint has no route context."); return context.GetFromRegistry(name) ?? throw new InvalidOperationException( $"{endpoint}: headerFilterStrategy '#{name}' is not an IHeaderFilterStrategy in the context registry. " + "Register it with AddToRegistry (or a in markup) before the route starts."); } } Path: redb-route/redb.Route/Core/IStopAwareProcessor.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/Core/IStopAwareProcessor.cs ---- namespace redb.Route.Core; /// /// A processor that holds exchanges of its own across calls (aggregation groups) and settles them when the context /// stops: after the consumers have stopped — nothing more arrives — and before the producers stop, so what it sends on /// still goes out. /// internal interface IStopAwareProcessor { /// Completes or releases what the processor still holds. /// The shutdown token. Task OnConsumersStoppedAsync(CancellationToken ct); } Path: redb-route/redb.Route/Core/ISupervisingEndpoint.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/Core/ISupervisingEndpoint.cs ---- using Microsoft.Extensions.Logging; namespace redb.Route.Core; /// /// An endpoint that takes connection supervisors into its health (), seen without its /// options type, as sees its endpoint. /// internal interface ISupervisingEndpoint { /// Creates a supervisor with the context's reconnect options and registers it. ConnectionSupervisor Supervise(string name, ILogger? logger); /// Removes a registered supervisor. void Unsupervise(ConnectionSupervisor supervisor); } Path: redb-route/redb.Route/Core/InflightDrainGuard.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/Core/InflightDrainGuard.cs ---- using Microsoft.Extensions.Logging; namespace redb.Route.Core; /// /// Encapsulates inflight tracking and drain-on-stop logic. /// Used by both poll-based () and callback-based consumers /// (RabbitMQ, MQTT, AMQP, TCP) to avoid duplicating CTS lifecycle + drain + force-cancel boilerplate. /// public sealed class InflightDrainGuard : IDisposable { private CancellationTokenSource? _processingCts; private int _inflightCount; /// Drain timeout for graceful stop (default 30s). public TimeSpan DrainTimeout { get; set; } = TimeSpan.FromSeconds(30); /// Current number of in-flight exchanges. public int InflightCount => Volatile.Read(ref _inflightCount); /// The processing cancellation token. Valid after . public CancellationToken ProcessingToken => _processingCts?.Token ?? CancellationToken.None; /// /// Initializes the processing CTS linked to the application shutdown token. /// Safe to call multiple times — disposes the previous CTS if any. /// public void Start(CancellationToken ct = default) { _processingCts?.Dispose(); _processingCts = CancellationTokenSource.CreateLinkedTokenSource(ct); } /// Increments the inflight counter. Must be paired with . public void Increment() => Interlocked.Increment(ref _inflightCount); /// Decrements the inflight counter. public void Decrement() => Interlocked.Decrement(ref _inflightCount); /// /// Drains in-flight exchanges and force-cancels if drain times out. /// Call in consumer Stop() after stopping acceptance of new work. /// public async Task DrainAsync(CancellationToken ct, ILogger? logger = null, string? consumerName = null) { if (Volatile.Read(ref _inflightCount) > 0) { var drained = await DrainAwaiter.WaitAsync( () => Volatile.Read(ref _inflightCount), DrainTimeout, ct, logger, consumerName).ConfigureAwait(false); if (!drained && _processingCts != null) { logger?.LogWarning("[{Consumer}] Force-cancelling in-flight processing.", consumerName); await _processingCts.CancelAsync().ConfigureAwait(false); } } } /// public void Dispose() { _processingCts?.Dispose(); _processingCts = null; } } Path: redb-route/redb.Route/Core/LenientPropertiesAttribute.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/Core/LenientPropertiesAttribute.cs ---- namespace redb.Route.Core; /// /// Declares that an endpoint options class takes URI parameters it has no property for, and reads /// them itself from (http: and sql: /// pass param.* on, bean: sets them on the bean). Without it an unknown parameter is /// refused when the endpoint is created: a misspelt option name would otherwise be dropped without a /// word and the option would keep its default. /// /// The counterpart of Apache Camel's Component.isLenientProperties(), which is also /// false unless a component says otherwise. It is an attribute on the options type, not a /// property of an endpoint instance, so tooling (the Route-XML catalog, the XSD, check) reads /// it by reflection without creating an endpoint — see . /// /// [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class LenientPropertiesAttribute : Attribute; Path: redb-route/redb.Route/Core/LimitedXmlReader.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/Core/LimitedXmlReader.cs ---- using System.Xml; using System.Xml.Schema; namespace redb.Route.Core; /// /// An over another one that checks on every element it reads and /// throws at the first one over a limit. Everything else is the inner reader's: /// the wrapper adds no buffering, so a loader on top builds no more of a hostile document than up to the offending /// element. Line information passes through for LoadOptions.SetLineInfo. /// internal sealed class LimitedXmlReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver { private const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private readonly XmlReader _inner; private readonly XmlLimits _limits; private long _elements; private long _namespaceDeclarations; internal LimitedXmlReader(XmlReader inner, XmlLimits limits) { _inner = inner; _limits = limits; } /// public override bool Read() { if (!_inner.Read()) return false; if (_inner.NodeType == XmlNodeType.Element) CheckElement(); return true; } private void CheckElement() { var depth = _inner.Depth + 1; if (_limits.MaxDepth is { } maxDepth && depth > maxDepth) throw Over(nameof(XmlLimits.MaxDepth), maxDepth, $"Element '{_inner.Name}' is nested {depth} levels deep"); if (_limits.MaxElements is { } maxElements && ++_elements > maxElements) throw Over(nameof(XmlLimits.MaxElements), maxElements, $"The document has more than {maxElements} elements"); var attributes = _inner.AttributeCount; if (_limits.MaxAttributesPerElement is { } maxAttributes && attributes > maxAttributes) throw Over(nameof(XmlLimits.MaxAttributesPerElement), maxAttributes, $"Element '{_inner.Name}' has {attributes} attributes"); if (attributes == 0 || (_limits.MaxNamespaceDeclarationsPerElement is null && _limits.MaxNamespaceDeclarations is null)) return; var declarations = 0; for (var i = 0; i < attributes; i++) { _inner.MoveToAttribute(i); if (_inner.NamespaceURI == XmlnsNamespace) declarations++; } _inner.MoveToElement(); if (_limits.MaxNamespaceDeclarationsPerElement is { } maxPerElement && declarations > maxPerElement) throw Over(nameof(XmlLimits.MaxNamespaceDeclarationsPerElement), maxPerElement, $"Element '{_inner.Name}' declares {declarations} namespaces"); _namespaceDeclarations += declarations; if (_limits.MaxNamespaceDeclarations is { } maxTotal && _namespaceDeclarations > maxTotal) throw Over(nameof(XmlLimits.MaxNamespaceDeclarations), maxTotal, $"The document declares more than {maxTotal} namespaces"); } private XmlLimitException Over(string limit, long maximum, string what) { var line = _inner as IXmlLineInfo; var (number, position) = line is { } info && info.HasLineInfo() ? (info.LineNumber, info.LinePosition) : (0, 0); return new XmlLimitException(limit, maximum, $"{what}: over the XML limit {limit} = {maximum}.", number, position); } // ── Everything else is the inner reader's ─────────────────────────────── /// public override XmlNodeType NodeType => _inner.NodeType; /// public override string LocalName => _inner.LocalName; /// public override string NamespaceURI => _inner.NamespaceURI; /// public override string Prefix => _inner.Prefix; /// public override string Name => _inner.Name; /// public override bool HasValue => _inner.HasValue; /// public override string Value => _inner.Value; /// public override int Depth => _inner.Depth; /// public override string BaseURI => _inner.BaseURI; /// public override bool IsEmptyElement => _inner.IsEmptyElement; /// public override bool IsDefault => _inner.IsDefault; /// public override char QuoteChar => _inner.QuoteChar; /// public override XmlSpace XmlSpace => _inner.XmlSpace; /// public override string XmlLang => _inner.XmlLang; /// public override IXmlSchemaInfo? SchemaInfo => _inner.SchemaInfo; /// public override Type ValueType => _inner.ValueType; /// public override int AttributeCount => _inner.AttributeCount; /// public override bool EOF => _inner.EOF; /// public override ReadState ReadState => _inner.ReadState; /// public override XmlNameTable NameTable => _inner.NameTable; /// public override XmlReaderSettings? Settings => _inner.Settings; /// public override bool CanResolveEntity => _inner.CanResolveEntity; /// public override bool CanReadBinaryContent => _inner.CanReadBinaryContent; /// public override bool CanReadValueChunk => _inner.CanReadValueChunk; /// public override bool HasAttributes => _inner.HasAttributes; /// public override string? GetAttribute(string name) => _inner.GetAttribute(name); /// public override string? GetAttribute(string name, string? namespaceURI) => _inner.GetAttribute(name, namespaceURI); /// public override string GetAttribute(int i) => _inner.GetAttribute(i); /// public override bool MoveToAttribute(string name) => _inner.MoveToAttribute(name); /// public override bool MoveToAttribute(string name, string? ns) => _inner.MoveToAttribute(name, ns); /// public override void MoveToAttribute(int i) => _inner.MoveToAttribute(i); /// public override bool MoveToFirstAttribute() => _inner.MoveToFirstAttribute(); /// public override bool MoveToNextAttribute() => _inner.MoveToNextAttribute(); /// public override bool MoveToElement() => _inner.MoveToElement(); /// public override bool ReadAttributeValue() => _inner.ReadAttributeValue(); /// public override string? LookupNamespace(string prefix) => _inner.LookupNamespace(prefix); /// public override void ResolveEntity() => _inner.ResolveEntity(); /// public override int ReadValueChunk(char[] buffer, int index, int count) => _inner.ReadValueChunk(buffer, index, count); /// public override void Close() => _inner.Close(); /// protected override void Dispose(bool disposing) { if (disposing) _inner.Dispose(); base.Dispose(disposing); } // ── IXmlLineInfo, IXmlNamespaceResolver ───────────────────────────────── bool IXmlLineInfo.HasLineInfo() => _inner is IXmlLineInfo info && info.HasLineInfo(); int IXmlLineInfo.LineNumber => (_inner as IXmlLineInfo)?.LineNumber ?? 0; int IXmlLineInfo.LinePosition => (_inner as IXmlLineInfo)?.LinePosition ?? 0; IDictionary IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) => (_inner as IXmlNamespaceResolver)?.GetNamespacesInScope(scope) ?? new Dictionary(); string? IXmlNamespaceResolver.LookupNamespace(string prefix) => _inner.LookupNamespace(prefix); string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) => (_inner as IXmlNamespaceResolver)?.LookupPrefix(namespaceName); } Path: redb-route/redb.Route/Core/ListBody.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/Core/ListBody.cs ---- using System.Collections; using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// A body that is a list, at a producer. A list of (a batch consumer's body, for one) is sent /// element by element, each element its own outgoing message with its own body and headers, as camel-kafka sends an /// Iterable body; a connector that has no wire form for a plain list (a list of other values whose text would be /// its type name) refuses it instead of sending that name. One implementation for every producer: the connector /// supplies only the send. /// public static class ListBody { private static readonly ConcurrentDictionary OwnToString = new(); /// The elements when is a collection of ; otherwise null. public static IReadOnlyList? Messages(object? body) => body is IEnumerable messages ? messages as IReadOnlyList ?? messages.ToList() : null; /// /// Whether is a plain list: a collection that is not a list of , not /// text or bytes, and has no text form of its own (its ToString() is the type name). A JSON array or another /// collection that writes itself as text is not one. /// public static bool IsPlainList(object? body) => body is IEnumerable and not string and not byte[] and not IEnumerable && !OwnToString.GetOrAdd(body.GetType(), static type => type.GetMethod(nameof(ToString), Type.EmptyTypes)?.DeclaringType != typeof(object)); /// /// The exchange one element is sent from, a linked child of (its properties, its scope): /// an element is the child's message, a copy with its own headers and none of the parent's; /// any other element is the body under a copy of the parent's headers and attachments, as a Split part is. Dispose /// it once the element is sent. /// public static IExchange ElementExchange(IExchange parent, object? element) { ArgumentNullException.ThrowIfNull(parent); IMessage message; if (element is IMessage own) { message = own.Clone(); } else { message = new Message(element) { ContentType = parent.In.ContentType }; foreach (var header in parent.In.Headers) message.Headers[header.Key] = header.Value; MessageAttachments.CopyInto(parent.In, message); } return parent.CreateLinkedChild(message); } /// The refusal of a list at a request-reply producer: one request cannot wait for many replies. public static InvalidOperationException RequestReplyRefusal(string endpoint, int count) => new( $"Endpoint '{endpoint}' is request-reply and the body is a list of {count} messages: one request cannot wait for " + "many replies. Split the list for request-reply."); /// The refusal of a plain list at a producer that has no wire form for it. public static InvalidOperationException PlainListRefusal(string endpoint, object body) => new( $"Endpoint '{endpoint}' cannot send a body of type {body.GetType().Name}: a list has no wire form here, and its " + "text would be the type name. Serialize the list (to JSON, for example), or make its elements IMessage to send " + "each as its own message."); } Path: redb-route/redb.Route/Core/LoggingLifecycleListener.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/Core/LoggingLifecycleListener.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Built-in lifecycle listener that logs all route state transitions via . /// public sealed class LoggingLifecycleListener : IRouteLifecycleListener { private readonly ILogger _logger; /// Creates a logging lifecycle listener. public LoggingLifecycleListener(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// public Task OnRouteStarted(string routeId, CancellationToken ct) { _logger.LogInformation("[Lifecycle] Route '{RouteId}' started.", routeId); return Task.CompletedTask; } /// public Task OnRouteStopped(string routeId, CancellationToken ct) { _logger.LogInformation("[Lifecycle] Route '{RouteId}' stopped.", routeId); return Task.CompletedTask; } /// public Task OnRouteSuspending(string routeId, CancellationToken ct) { _logger.LogInformation("[Lifecycle] Route '{RouteId}' suspending (drain starting).", routeId); return Task.CompletedTask; } /// public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { _logger.LogError(ex, "[Lifecycle] Route '{RouteId}' errored.", routeId); return Task.CompletedTask; } /// public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { _logger.LogWarning( "[Lifecycle] Exchange '{ExchangeId}' timed out on route '{RouteId}' after {Elapsed}s.", exchangeId, routeId, elapsed.TotalSeconds); return Task.CompletedTask; } } Path: redb-route/redb.Route/Core/Message.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/Core/Message.cs ---- using System.Collections.ObjectModel; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Default implementation of IMessage. /// Holds a payload Body and a dictionary of Headers. /// public class Message : IMessage { private readonly Dictionary _headers = new(StringComparer.OrdinalIgnoreCase); private MessageAttachments? _attachments; /// public object? Body { get; set; } /// public IMessageAttachments Attachments => _attachments ??= new MessageAttachments(); /// The attachment list when one was created and holds something; null otherwise (no allocation). internal MessageAttachments? AttachmentsOrNull => _attachments is { Count: > 0 } a ? a : null; /// public string? ContentType { get; set; } /// public IDictionary Headers => _headers; /// Creates an empty message. public Message() { } /// Creates a message with the specified body. /// Initial payload. public Message(object? body) => Body = body; /// public T? GetHeader(string key) => _headers.TryGetValue(key, out var value) ? TypedValue.Convert(value, $"header '{key}'") : default; /// public IMessage Clone() { var clone = new Message(Body) { ContentType = ContentType }; foreach (var kvp in _headers) clone._headers[kvp.Key] = kvp.Value; // A new list over the same content sources, as the body reference is shared. clone._attachments = AttachmentsOrNull?.Copy(); return clone; } /// public IMessage Snapshot() { var snapshot = new Message(DeepCopyBody(Body)) { ContentType = ContentType }; // Header values are shared like Clone — they carry immutable metadata, not payload. foreach (var kvp in _headers) snapshot._headers[kvp.Key] = kvp.Value; // Attachments are payload: their content is copied, like the body. snapshot._attachments = AttachmentsOrNull?.DeepCopy(); return snapshot; } /// /// Deep-copies a message body for a checkpoint snapshot. Handles the faithful, non-lossy cases /// only: null / / value types are immutable and shared as-is; /// byte[] is copied; anything implementing is cloned via its own /// contract (the author is responsible for that clone being deep). Everything else throws — we /// never silently share a mutable reference behind a "snapshot", nor round-trip through a /// serializer (which would be lossy for many types). A serializer-based deep clone can be added /// as an opt-in strategy later without changing this contract. /// internal static object? DeepCopyBody(object? body) => body switch { null => null, string => body, // immutable ValueType => body, // int/bool/DateTime/Guid/decimal/enum/tuples/structs — boxed copy is safe to share byte[] bytes => bytes.Clone(), // must precede ICloneable (byte[] is ICloneable but we copy the array) ICloneable cloneable => cloneable.Clone(), _ => throw new NotSupportedException( $"Checkpoint snapshot cannot deep-copy a message body of type '{body.GetType().FullName}'. " + "A replayable body must be immutable, a byte[], or implement ICloneable (with deep semantics). " + "Materialize it into a snapshot-able form before the .Replayable() marker.") }; } Path: redb-route/redb.Route/Core/MessageAttachments.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/Core/MessageAttachments.cs ---- using System.Collections; using redb.Route.Abstractions; namespace redb.Route.Core; /// The attachment list of a . internal sealed class MessageAttachments : IMessageAttachments { /// /// What a message that does not implement attachments answers with: it carries none, and adding one fails instead of /// being dropped. /// internal static readonly IMessageAttachments Unsupported = new UnsupportedAttachments(); private readonly List _items; public MessageAttachments() => _items = []; private MessageAttachments(List items) => _items = items; public int Count => _items.Count; public Attachment this[int index] => _items[index]; public Attachment? Find(string name) { ArgumentNullException.ThrowIfNull(name); foreach (var item in _items) if (string.Equals(item.Name, name, StringComparison.Ordinal)) return item; return null; } public IReadOnlyList FindAll(string name) { ArgumentNullException.ThrowIfNull(name); return _items.Where(i => string.Equals(i.Name, name, StringComparison.Ordinal)).ToArray(); } public void Add(Attachment attachment) { ArgumentNullException.ThrowIfNull(attachment); _items.Add(attachment); } public void Set(Attachment attachment) { ArgumentNullException.ThrowIfNull(attachment); var first = _items.FindIndex(i => string.Equals(i.Name, attachment.Name, StringComparison.Ordinal)); if (first < 0) { _items.Add(attachment); return; } _items[first] = attachment; for (var i = _items.Count - 1; i > first; i--) if (string.Equals(_items[i].Name, attachment.Name, StringComparison.Ordinal)) _items.RemoveAt(i); } public int Remove(string name) { ArgumentNullException.ThrowIfNull(name); return _items.RemoveAll(i => string.Equals(i.Name, name, StringComparison.Ordinal)); } public void Clear() => _items.Clear(); /// Same attachments in a new list (the content sources are shared), as shares the body. public MessageAttachments Copy() => new([.. _items]); /// Same attachments with isolated content, as deep-copies the body. public MessageAttachments DeepCopy() => new(_items.Select(i => i.WithContent(i.Content.DeepCopy())).ToList()); /// Appends the attachments of to , sharing their content. internal static void CopyInto(IMessage source, IMessage target) { if (source is not Message { AttachmentsOrNull: { } items }) return; var into = target.Attachments; foreach (var item in items) into.Add(item); } /// /// The pipeline's Out-to-In rule: when carries attachments they replace those of /// ; a step that set no attachments on its Out leaves the In ones in place. /// internal static void ReplaceWhenPresent(IMessage source, IMessage target) { if (source is not Message { AttachmentsOrNull: { } items }) return; var into = target.Attachments; into.Clear(); foreach (var item in items) into.Add(item); } /// Total length of the attachment content of ; 0 without attachments. internal static long TotalLength(IMessage message) => message is Message { AttachmentsOrNull: { } items } ? items.TotalLength() : 0; /// Total length of the content of all attachments. public long TotalLength() => _items.Sum(i => i.Content.Length); public IEnumerator GetEnumerator() => _items.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private sealed class UnsupportedAttachments : IMessageAttachments { public int Count => 0; public Attachment this[int index] => throw new ArgumentOutOfRangeException(nameof(index)); public Attachment? Find(string name) => null; public IReadOnlyList FindAll(string name) => []; public void Add(Attachment attachment) => throw NotSupported(); public void Set(Attachment attachment) => throw NotSupported(); public int Remove(string name) => 0; public void Clear() { } public IEnumerator GetEnumerator() => Enumerable.Empty().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private static NotSupportedException NotSupported() => new("This message type does not carry attachments; use redb.Route.Core.Message."); } } Path: redb-route/redb.Route/Core/MessageHistory.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/Core/MessageHistory.cs ---- using System.Collections.Concurrent; using System.Text; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// One entry in an exchange's message history: which route/node processed it and how long that took /// (Apache Camel org.apache.camel.MessageHistory). /// public sealed record MessageHistoryEntry(string RouteId, string NodeId, string Label, double ElapsedMs); /// /// Access and formatting for the per-exchange message history (Apache Camel Message History EIP). /// /// When enabled (globally via RouteEngineOptions.EnableMessageHistory or per route via /// .MessageHistory()), each node is wrapped so it appends a /// as the exchange passes through, stored on the exchange under in a /// thread-safe queue (Split/Multicast append concurrently). The trail is dumped on failure. /// /// public static class MessageHistory { /// Exchange property key holding the message history (Camel: Exchange.MESSAGE_HISTORY). public const string PropertyKey = "CamelMessageHistory"; /// Returns the recorded history for the exchange (empty if none / disabled). public static IReadOnlyList GetEntries(IExchange exchange) => exchange.Properties.TryGetValue(PropertyKey, out var raw) && raw is ConcurrentQueue q ? q.ToArray() : Array.Empty(); /// Appends an entry, creating the queue on first use. internal static void Append(IExchange exchange, MessageHistoryEntry entry) { // The route's first node runs single-threaded, so the queue exists before any parallel // (Split/Multicast) section appends to it concurrently — hence a plain check-then-add here and // a thread-safe ConcurrentQueue for the appends. if (exchange.Properties.TryGetValue(PropertyKey, out var raw) && raw is ConcurrentQueue q) { q.Enqueue(entry); return; } var created = new ConcurrentQueue(); created.Enqueue(entry); exchange.Properties[PropertyKey] = created; } /// /// Renders the history as a table (columns: RouteId · Id · Processor · Elapsed/ms), the way Camel /// prints it when an exchange fails. Returns an empty string when there is no history. /// public static string Format(IExchange exchange) { var entries = GetEntries(exchange); if (entries.Count == 0) return string.Empty; var sb = new StringBuilder(); sb.AppendLine("Message History (routeId · id · processor · elapsed/ms):"); foreach (var e in entries) sb.AppendLine($" {e.RouteId} · {e.NodeId} · {e.Label} · {e.ElapsedMs:F3}"); return sb.ToString().TrimEnd(); } } Path: redb-route/redb.Route/Core/OptionGroupAttribute.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/Core/OptionGroupAttribute.cs ---- namespace redb.Route.Core; /// /// Marks an endpoint option as a group of options, written group.member=value on the URI: Apache Camel's prefixed /// options, such as the mail component's searchTerm.subject=.... The property's type is a class with a public /// parameterless constructor whose public settable properties are the members; the binder creates the group when the /// URI names one of them. A member the group does not have is refused when the endpoint is created, naming the group and /// its members. A [] member is masked as group.member. /// [AttributeUsage(AttributeTargets.Property, Inherited = true)] public sealed class OptionGroupAttribute : Attribute; /// /// Marks the one member of an option group that the bare group=value binds: /// Camel's searchTerm=#bean beside searchTerm.subject=.... Without such a member the bare name is refused. /// [AttributeUsage(AttributeTargets.Property, Inherited = true)] public sealed class OptionGroupValueAttribute : Attribute; Path: redb-route/redb.Route/Core/ProducerTemplate.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/Core/ProducerTemplate.cs ---- using System.Diagnostics; using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Default implementation of . /// Provides a client API for sending messages to endpoints outside of route pipelines. /// Must be started via before use. /// Thread-safe: all public methods check started state, endpoint resolution is delegated /// to which uses concurrent collections. /// Caches producers per endpoint for performance (avoids CreateProducer on every call). /// public class ProducerTemplate : IProducerTemplate, IDisposable, IAsyncDisposable { private readonly ConcurrentDictionary _producerCache = new(StringComparer.OrdinalIgnoreCase); private volatile bool _started; private volatile bool _disposed; // Captured once at construction; null when context has no DI provider (e.g. unit-test routes). // When non-null, every Exchange we create owns a fresh DI scope so per-request scoped // services (IRedbService and its NpgsqlConnection, OpenIddict stores, ...) are isolated // between concurrent ProducerTemplate calls. Each Send/RequestBody method below MUST // dispose the exchange in finally so the scope (and connection) is released promptly. private readonly IServiceScopeFactory? _scopeFactory; /// /// Initializes a new instance with the specified route context. /// /// The route context for endpoint resolution. /// Thrown when is null. public ProducerTemplate(IRouteContext context) { Context = context ?? throw new ArgumentNullException(nameof(context)); _scopeFactory = context.GetServiceProvider()?.GetService(); } /// public IRouteContext Context { get; } /// public bool IsStarted => _started; // ── Synchronous Send ── /// public void Send(string endpointUri, object body) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); Send(endpoint, body); } /// public void Send(IEndpoint endpoint, object body) { EnsureStarted(); var exchange = CreateExchange(body); try { Send(endpoint, exchange); } finally { exchange.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } /// public void Send(IEndpoint endpoint, IExchange exchange) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(exchange); var producer = GetOrCreateProducer(endpoint); ProcessCounted(endpoint, producer, exchange).GetAwaiter().GetResult(); } /// public void Send(string endpointUri, IExchange exchange) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); Send(endpoint, exchange); } /// public void Send(IEndpoint endpoint, IMessage message) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(message); var exchange = Exchange.Create(message, _scopeFactory); try { Send(endpoint, exchange); } finally { exchange.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } /// public void Send(string endpointUri, IMessage message) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); Send(endpoint, message); } /// public void Send(IEndpoint endpoint, IProcessor processor) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(processor); var exchange = CreateExchange(null); try { processor.Process(exchange).GetAwaiter().GetResult(); var producer = GetOrCreateProducer(endpoint); ProcessCounted(endpoint, producer, exchange).GetAwaiter().GetResult(); } finally { exchange.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } // ── Async Send ── /// public async Task SendAsync(IEndpoint endpoint, object body) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); var exchange = CreateExchange(body); try { var producer = GetOrCreateProducer(endpoint); // ConnectableProducer-based transports demand Start() before Process(); // idempotent — the started flag short-circuits subsequent calls. await producer.Start().ConfigureAwait(false); await ProcessCounted(endpoint, producer, exchange).ConfigureAwait(false); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// public async Task SendAsync(string endpointUri, object body) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); await SendAsync(endpoint, body).ConfigureAwait(false); } /// public async Task SendAsync(IEndpoint endpoint, IMessage message) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(message); var exchange = Exchange.Create(message, _scopeFactory); try { var producer = GetOrCreateProducer(endpoint); // ConnectableProducer-based transports (http, kafka, amqp, …) // demand Start() before Process(); idempotent — second Start is // a no-op on the started flag. await producer.Start().ConfigureAwait(false); await ProcessCounted(endpoint, producer, exchange).ConfigureAwait(false); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// public async Task SendAsync(string endpointUri, IMessage message) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); await SendAsync(endpoint, message).ConfigureAwait(false); } // ── Async Send / Request of a pre-built exchange (caller-owned) ── /// public async Task SendAsync(IEndpoint endpoint, IExchange exchange, CancellationToken cancellationToken = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(exchange); // Caller-owned exchange: unlike the body/message overloads we do NOT create, clone or // dispose it, and we attach no DI scope — whatever scope the exchange carries (or lacks) // is the caller's responsibility. A snapshot cloned from a completed exchange may reference // a disposed scope; the caller must give it a live scope before replay if it needs one. var producer = GetOrCreateProducer(endpoint); await producer.Start(cancellationToken).ConfigureAwait(false); await ProcessCounted(endpoint, producer, exchange, cancellationToken).ConfigureAwait(false); } /// public async Task SendAsync(string endpointUri, IExchange exchange, CancellationToken cancellationToken = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); await SendAsync(endpoint, exchange, cancellationToken).ConfigureAwait(false); } /// public async Task RequestAsync(IEndpoint endpoint, IExchange exchange, CancellationToken cancellationToken = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(exchange); // Caller-owned (see SendAsync(IExchange) above): not cloned or disposed here. exchange.Pattern = ExchangePattern.InOut; var producer = GetOrCreateProducer(endpoint); await producer.Start(cancellationToken).ConfigureAwait(false); await ProcessCounted(endpoint, producer, exchange, cancellationToken).ConfigureAwait(false); return exchange; } /// public async Task RequestAsync(string endpointUri, IExchange exchange, CancellationToken cancellationToken = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); return await RequestAsync(endpoint, exchange, cancellationToken).ConfigureAwait(false); } // ── Request/Reply ── /// public async Task RequestBody(IEndpoint endpoint, object body, CancellationToken cancellationToken = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); var exchange = CreateExchange(body); try { exchange.Pattern = ExchangePattern.InOut; var producer = GetOrCreateProducer(endpoint); // ConnectableProducer-based transports demand Start() before Process(). await producer.Start(cancellationToken).ConfigureAwait(false); await ProcessCounted(endpoint, producer, exchange, cancellationToken).ConfigureAwait(false); return ReplyBody(exchange, endpoint); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// public async Task RequestBody(string endpointUri, object body, CancellationToken cancellationToken = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); return await RequestBody(endpoint, body, cancellationToken).ConfigureAwait(false); } /// public async Task RequestBody(IEndpoint endpoint, IMessage message, CancellationToken cancellationToken = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(message); var exchange = Exchange.Create(message, _scopeFactory); try { exchange.Pattern = ExchangePattern.InOut; var producer = GetOrCreateProducer(endpoint); // ConnectableProducer-based transports demand Start() before Process(). await producer.Start(cancellationToken).ConfigureAwait(false); await ProcessCounted(endpoint, producer, exchange, cancellationToken).ConfigureAwait(false); return ReplyBody(exchange, endpoint); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// public async Task RequestBody(string endpointUri, IMessage message, CancellationToken cancellationToken = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); return await RequestBody(endpoint, message, cancellationToken).ConfigureAwait(false); } /// public async Task RequestBody(IEndpoint endpoint, object body, CancellationToken cancellationToken = default) { var result = await RequestBody(endpoint, body, cancellationToken).ConfigureAwait(false); if (result is null) return default; if (result is T typed) return typed; // A nullable target converts to its underlying type; a reply that does not convert is an error, not a default. var target = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); try { return (T)RouteDecimal.ChangeType(result, target); } catch (Exception ex) when (ex is InvalidCastException or FormatException or OverflowException) { throw new InvalidCastException( $"The reply of '{endpoint.Uri}' is a {result.GetType().Name} and does not convert to {target.Name}.", ex); } } /// /// The reply body of a request whose exchange ends when the caller returns. A body that reads from resources of the /// exchange () would be dead by then, so it is refused here, at the call, instead of /// failing at its first read. /// private static object? ReplyBody(IExchange exchange, IEndpoint endpoint) { var body = exchange.Out?.Body ?? exchange.In.Body; if (body is IExchangeBoundBody) throw new InvalidOperationException( $"The reply of '{endpoint.Uri}' is a {ReadableName(body.GetType())} that reads from resources of its exchange, and " + "RequestBody ends the exchange before it returns, so the body could not be read. Use " + "RequestAsync(endpoint, exchange), read the body, then dispose the exchange."); return body; } /// StreamedQueryResult<Order> rather than the runtime name StreamedQueryResult`1. private static string ReadableName(Type type) => type.IsGenericType ? $"{type.Name[..type.Name.IndexOf('`')]}<{string.Join(", ", type.GetGenericArguments().Select(ReadableName))}>" : type.Name; /// public async Task RequestBody(string endpointUri, object body, CancellationToken cancellationToken = default) { EnsureStarted(); var endpoint = Context.GetEndpoint(endpointUri); return await RequestBody(endpoint, body, cancellationToken).ConfigureAwait(false); } // ── Lifecycle ── /// public void Start() { ObjectDisposedException.ThrowIf(_disposed, this); if (_started) throw new InvalidOperationException("ProducerTemplate is already started."); _started = true; } /// /// Stops the template and the producers it created — they flush and close, as a Camel template stops its producer /// cache. A later creates new ones. /// public void Stop() { if (!_started) throw new InvalidOperationException("ProducerTemplate is not started."); _started = false; StopProducersAsync().GetAwaiter().GetResult(); } /// Stops the producers the template created (they flush and close) and releases them. public void Dispose() { if (_disposed) return; _disposed = true; _started = false; GC.SuppressFinalize(this); StopProducersAsync().GetAwaiter().GetResult(); } /// Stops the producers the template created (they flush and close) and releases them. public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; _started = false; GC.SuppressFinalize(this); await StopProducersAsync().ConfigureAwait(false); } // A producer is on the context's shutdown list from its creation, so the host stopping flushes it even with the // template left open; whoever stops it first takes it off, so it is stopped once. private async Task StopProducersAsync() { var producers = _producerCache.Values.ToArray(); _producerCache.Clear(); var context = Context as RouteContext; List? failures = null; foreach (var producer in producers) { if (context is not null && !context.UntrackProducer(producer)) continue; // the context stopped it already try { await producer.Stop().ConfigureAwait(false); } catch (Exception ex) { (failures ??= []).Add(ex); } } if (failures is not null) throw new AggregateException("Stopping the producers of a ProducerTemplate failed.", failures); } // ── Private helpers ── private IProducer GetOrCreateProducer(IEndpoint endpoint) { var key = endpoint.Uri.NormalizedKey; if (_producerCache.TryGetValue(key, out var cached)) return cached; var created = endpoint.CreateProducerOnItsSide(); var producer = _producerCache.GetOrAdd(key, created); // Only the instance that won the race is used, so only it goes on the context's shutdown list. if (ReferenceEquals(producer, created)) (Context as RouteContext)?.TrackProducer(created); return producer; } private Exchange CreateExchange(object? body) { var message = new Message(); if (body is not null) message.Body = body; return Exchange.Create(message, _scopeFactory); } private void EnsureStarted() { ObjectDisposedException.ThrowIf(_disposed, this); if (!_started) throw new InvalidOperationException( "ProducerTemplate is not started. Call Start() before use."); } /// /// Runs the producer with the same endpoint statistics /// keeps for a routed .To(): MessagesOut, Errors, ProcessingTime. The template used to /// bypass them, so a template send was invisible unless the connector self-recorded — and a /// self-recording connector then double-counted in routes. One owner now: the core records /// pipeline statistics on both paths, connectors record only what the core cannot see /// (wire bytes, transport-level failures, producer-side inbound operations). /// private static Task ProcessCounted(IEndpoint endpoint, IProducer producer, IExchange exchange, CancellationToken ct = default) => CountedSend.Process(endpoint, producer, exchange, ct); } Path: redb-route/redb.Route/Core/PropertyPlaceholderResolver.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/Core/PropertyPlaceholderResolver.cs ---- using System.Text.RegularExpressions; namespace redb.Route.Core; /// /// Resolves Apache Camel-style property placeholders inside a string — typically an endpoint URI — /// at route-compile time. Supports {{key}} (required) and {{key:default}} (with a fallback /// value). This is the redb.Route analogue of Camel's PropertiesComponent: it lets endpoint URIs /// (and any other DSL string routed through it) externalise their configuration instead of hard-coding /// hosts, queue names, ports or paths. /// /// The value lookup is supplied by the caller as a , keeping this type pure /// and testable. wires the lookup to IConfiguration (which already layers /// environment variables, appsettings and user-secrets with the container's own precedence — so no /// Camel-style env:/sys: prefix functions are needed) and, as a container-free fallback, /// the context's own properties. /// /// /// Deliberately minimal: no nested placeholders ({{a{{b}}}}), no optional-parameter removal /// ({{?key}}), no encryption or multi-location precedence. Resolution is single-pass, so it can /// never loop. A placeholder with neither a value nor a default fails fast at compile time. /// /// public static class PropertyPlaceholderResolver { // {{ key }} or {{ key : default }}. The key excludes braces and the ':' separator; the optional // default (everything up to the closing braces) may contain ':' so URLs work as defaults. Lazy so // the first "}}" terminates the match — a nested inner placeholder simply isn't matched as one. private static readonly Regex Pattern = new( @"\{\{\s*([^{}:]+?)\s*(?::\s*([^{}]*?)\s*)?\}\}", RegexOptions.Compiled); /// /// Fast pre-check: true only if could contain a placeholder. Lets callers /// skip resolution (and the regex) for the overwhelming majority of URIs that have none — which is also /// why the feature never touches existing routes: {{ is not legal in a bare URI. /// public static bool HasPlaceholder(string? text) => text is not null && text.Contains("{{", StringComparison.Ordinal); /// /// Replaces every {{key}} / {{key:default}} in with the value /// returned by for that key (or the default when the lookup yields none). /// /// The string to resolve (e.g. an endpoint URI). /// Returns the configured value for a key, or null/empty if unknown. /// The resolved string, or unchanged when it has no placeholders. /// /// A placeholder had no resolvable value and no default — surfaced at compile time so a misconfigured /// deployment fails loudly rather than building a broken endpoint URI. /// public static string Resolve(string text, Func lookup) { ArgumentNullException.ThrowIfNull(lookup); if (!HasPlaceholder(text)) return text; return Pattern.Replace(text, match => { var key = match.Groups[1].Value; var value = lookup(key); if (!string.IsNullOrEmpty(value)) return value; if (match.Groups[2].Success) return match.Groups[2].Value; throw new InvalidOperationException( $"Unresolved property placeholder '{{{{{key}}}}}': no value was found for key '{key}' " + $"and no default was given (use '{{{{{key}:default}}}}'). Provide the value via IConfiguration " + $"(appsettings/environment) or context.SetProperty(\"{key}\", ...)."); }); } } Path: redb-route/redb.Route/Core/PushConsumer.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/Core/PushConsumer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Telemetry; namespace redb.Route.Core; /// What became of one message a push consumer handed to . public enum PushOutcome { /// The route ended well (and the work after it, if any): settle the message as consumed. Accepted, /// /// The route failed every attempt: settle the message by the connector's failure rule (reject to a dead letter /// queue, or requeue). holds the failure. /// Rejected, /// The message arrived after the consumer began to stop: it was not run; give it back to the broker. Refused, /// /// The message was given up without a verdict on the route: the consumer's stop ended it (the drain window ran out, /// or the pause before its next attempt was cut short), or the work after the route failed. Give it back. /// Returned, } /// The outcome of one dispatch, with the failure behind or a failed follow-up. /// What became of the message. /// The route's failure (Rejected) or the follow-up's (Returned); null otherwise. public readonly record struct PushDispatch(PushOutcome Outcome, Exception? Failure) { /// Converts to the outcome alone. public static implicit operator PushOutcome(PushDispatch dispatch) => dispatch.Outcome; } /// How often a push consumer tries a failed message before it is . /// Attempts in all, at least 1; each attempt runs on a fresh exchange. /// Pause between attempts; a stop of the consumer cuts it short (the message is Returned). public readonly record struct PushRetry(int Attempts, TimeSpan Delay) { /// One attempt, no retry. public static PushRetry None => new(1, TimeSpan.Zero); } /// /// Base class for consumers whose client library calls a handler for every message (RabbitMQ /// AsyncEventingBasicConsumer, MQTT, a service bus processor): the counterpart of , /// which runs its own receive loop. The base keeps the order of a graceful stop, so a connector does not repeat it: /// new messages are refused once a stop begins, the messages in work drain within , then their /// processing is cancelled, and only then is the subscription released. /// /// The connector gives three steps: (open and subscribe), /// (cancel the subscription so nothing new arrives) and (release what Subscribe opened). /// Its message handler calls and settles the message by the : the /// base never acknowledges, the rules of that differ per broker. /// /// /// A subscription the broker ends while the route runs (a closed channel, a dropped link) is reported to a /// (), and brings it /// back on the supervisor's schedule while the endpoint's health says so. /// /// public abstract class PushConsumer : IConsumer { private readonly InflightDrainGuard _drain = new(); private readonly SemaphoreSlim? _slots; private readonly object _resubscribeGate = new(); private readonly List _supervisors = []; private CancellationTokenSource _stopRequested = new(); private Task? _resubscribe; private volatile bool _stopping; private ILogger? _logger; /// Creates a push consumer. /// The route the messages run through. /// /// How many messages run through the route at once; a message over the limit waits for a slot, counted as in work. /// null: no limit beyond what the client hands over. /// protected PushConsumer(IProcessor processor, int? maxConcurrency = null) { Processor = processor ?? throw new ArgumentNullException(nameof(processor)); if (maxConcurrency is { } max) { ArgumentOutOfRangeException.ThrowIfLessThan(max, 1, nameof(maxConcurrency)); _slots = new SemaphoreSlim(max, max); } } /// The endpoint this consumer is attached to. protected abstract IEndpoint ConsumerEndpoint { get; } /// Display name for logging (rabbitmq:orders). protected abstract string ConsumerName { get; } /// public IEndpoint Endpoint => ConsumerEndpoint; /// The route the messages run through. protected IProcessor Processor { get; } /// Logger resolved from the component. protected ILogger? Logger => _logger ??= (ConsumerEndpoint.Component as ComponentBase)?.Logger; /// How long a stop waits for the messages in work before it cancels their processing (default 30 s). protected TimeSpan DrainTimeout { get => _drain.DrainTimeout; set => _drain.DrainTimeout = value; } /// Set once a stop begins: from then on a cancelled subscription or a closed channel is the stop's, not news. protected bool IsStopping => _stopping; /// Cancelled when a stop begins, before the drain; a pause or a wait of the connector's own ends with it. protected CancellationToken StopToken => _stopRequested.Token; /// The processing token of the messages in work; cancelled when the drain window of a stop runs out. protected CancellationToken ProcessingToken => _drain.ProcessingToken; /// Messages in work now. protected int InflightCount => _drain.InflightCount; // ── IConsumer lifecycle ── /// public async Task Start(CancellationToken ct = default) { _stopping = false; _stopRequested.Dispose(); _stopRequested = new CancellationTokenSource(); _drain.Start(ct); try { await SubscribeAsync(ct).ConfigureAwait(false); } catch { ReleaseSupervisors(); _drain.Dispose(); throw; } Logger?.LogInformation("{Consumer} started.", EndpointUri.ForLog(ConsumerName, Logger)); } /// public async Task Stop(CancellationToken ct = default) { _stopping = true; await _stopRequested.CancelAsync().ConfigureAwait(false); try { // Step 1: a resubscribe in flight ends (the stop token ends its loop), then nothing new arrives on the // subscription that is current now. await AwaitResubscribeAsync().ConfigureAwait(false); try { await StopAcceptingAsync(ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: error cancelling the subscription", ConsumerName); } // Step 2: drain the messages in work, then cancel what is left. await _drain.DrainAsync(ct, Logger, ConsumerName).ConfigureAwait(false); // Step 3: release what Subscribe opened. await UnsubscribeAsync(ct).ConfigureAwait(false); } finally { ReleaseSupervisors(); _drain.Dispose(); } Logger?.LogInformation("{Consumer} stopped.", EndpointUri.ForLog(ConsumerName, Logger)); } // ── The connector's steps ── /// Opens what the subscription needs and subscribes; a failure fails the start. protected abstract Task SubscribeAsync(CancellationToken ct); /// Cancels the subscription so that no new message arrives (a broker-side cancel); errors are logged. protected abstract Task StopAcceptingAsync(CancellationToken ct); /// Releases what opened; runs after the drain. protected abstract Task UnsubscribeAsync(CancellationToken ct); // ── Messages ── /// /// Runs one message through the route and says what became of it; the connector settles it by the outcome. Refused /// when a stop has begun (also when the stop began while the message waited for a slot); counted as in work until it /// returns, so a stop's drain waits for it. Each attempt runs on a fresh exchange from /// and is disposed after it. A route that failed is tried again by ; after the last attempt the /// failure marks and the outcome is . /// /// Creates the exchange of one attempt from the message. /// The receive span the consumer opened (and disposes); a failure marks it. /// Attempts and the pause between them; when null. /// /// Work after a route that ended well and before the message is settled (an RPC reply). If it fails, the message is /// , the failure marks the span and is returned in . /// protected async Task DispatchAsync(Func createExchange, TransportSpan span, PushRetry? retry = null, Func? afterRoute = null) { ArgumentNullException.ThrowIfNull(createExchange); var plan = retry ?? PushRetry.None; if (_stopping) return new PushDispatch(PushOutcome.Refused, null); // Counted before the wait for a slot, so a stop's drain waits for a message still waiting: it must not start // after the drain gave up and disposed the processing token. _drain.Increment(); var slot = false; IExchange? exchange = null; try { if (_slots is not null) { await _slots.WaitAsync().ConfigureAwait(false); slot = true; } if (_stopping) return new PushDispatch(PushOutcome.Refused, null); // This message's processing token, taken now: the drain disposes its source when a stop gives up waiting. var token = _drain.ProcessingToken; for (var attempt = 1; ; attempt++) { exchange = createExchange(); await ExchangeProcessing.RunAsync(Processor, exchange, token).ConfigureAwait(false); if (ExchangeFailureExtensions.FailureOf(exchange) is not { } failure) break; if (IsOwnStop(failure, token)) return new PushDispatch(PushOutcome.Returned, null); if (attempt >= Math.Max(1, plan.Attempts)) { RouteTelemetryExtensions.RecordFailure(span.Activity, failure); return new PushDispatch(PushOutcome.Rejected, failure); } Logger?.LogWarning(failure, "{Consumer}: attempt {Attempt} of {Max} failed; the next in {Delay} ms", ConsumerName, attempt, plan.Attempts, (long)plan.Delay.TotalMilliseconds); if (plan.Delay > TimeSpan.Zero) { using var pause = CancellationTokenSource.CreateLinkedTokenSource(token, StopToken); await Task.Delay(plan.Delay, pause.Token).ConfigureAwait(false); } await exchange.DisposeAsync().ConfigureAwait(false); exchange = null; } if (afterRoute is not null) { try { await afterRoute(exchange, token).ConfigureAwait(false); } catch (Exception ex) when (!IsOwnStop(ex, token)) { RouteTelemetryExtensions.RecordFailure(span.Activity, ex); return new PushDispatch(PushOutcome.Returned, ex); } } return new PushDispatch(PushOutcome.Accepted, null); } catch (OperationCanceledException ex) when (IsOwnStop(ex, _drain.ProcessingToken)) { return new PushDispatch(PushOutcome.Returned, null); } finally { if (exchange is not null) await exchange.DisposeAsync().ConfigureAwait(false); if (slot) _slots!.Release(); _drain.Decrement(); } } /// /// Counts one unit of work the connector runs itself (a batch) as in work, so a stop's drain waits for it; dispose /// the result when the unit is done. /// protected InflightScope TrackInflight() { _drain.Increment(); return new InflightScope(_drain); } /// A cancellation the consumer's own stop caused; any other one, a timeout inside the route included, is a failure. protected bool IsOwnStop(Exception exception, CancellationToken processingToken) => exception is OperationCanceledException && (processingToken.IsCancellationRequested || _stopRequested.IsCancellationRequested); // ── Losing the subscription ── /// /// Creates a supervisor for one subscription of this consumer and registers it with the endpoint, whose health then /// follows it; it is removed when the consumer stops. The endpoint must derive from . /// /// What is supervised, for the log and the health reason: rabbitmq:orders consumer channel. protected ConnectionSupervisor SuperviseConnection(string name) { if (ConsumerEndpoint is not ISupervisingEndpoint endpoint) throw new InvalidOperationException( $"{ConsumerName}: the endpoint {ConsumerEndpoint.GetType().Name} does not take connection supervisors."); var supervisor = endpoint.Supervise(name, Logger); lock (_supervisors) _supervisors.Add(supervisor); return supervisor; } /// /// Brings a lost subscription back: runs on the supervisor's schedule /// () until it succeeds or the consumer stops. Call it once, for the /// report of that returned true; while one runs, a second call returns /// the running one. A stop waits for it before the subscription is released, and its token ends it. /// /// The supervisor the loss was reported to. /// Opens a new subscription in place of the lost one; a failure counts as a failed attempt. /// The loop; true once resubscribed, false when the stop ended it. protected Task ResubscribeAsync(ConnectionSupervisor supervisor, Func resubscribe) { ArgumentNullException.ThrowIfNull(supervisor); ArgumentNullException.ThrowIfNull(resubscribe); lock (_resubscribeGate) { if (_resubscribe is Task { IsCompleted: false } running) return running; if (_stopping) return Task.FromResult(false); var stop = StopToken; var loop = Task.Run(() => supervisor.ReconnectAsync(resubscribe, stop), CancellationToken.None); _resubscribe = loop; return loop; } } private async Task AwaitResubscribeAsync() { Task? loop; lock (_resubscribeGate) loop = _resubscribe; if (loop is null) return; try { await loop.ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: the resubscribe ended with an error", ConsumerName); } } private void ReleaseSupervisors() { ConnectionSupervisor[] supervisors; lock (_supervisors) { supervisors = [.. _supervisors]; _supervisors.Clear(); } if (ConsumerEndpoint is ISupervisingEndpoint endpoint) foreach (var supervisor in supervisors) endpoint.Unsupervise(supervisor); } /// One unit of work counted by ; disposing it ends the count. protected readonly struct InflightScope : IDisposable { private readonly InflightDrainGuard? _drain; internal InflightScope(InflightDrainGuard drain) => _drain = drain; /// public void Dispose() => _drain?.Decrement(); } } Path: redb-route/redb.Route/Core/RejectedExecutionException.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/Core/RejectedExecutionException.cs ---- namespace redb.Route.Core; /// /// A detached step (a WireTap, an asynchronous OnCompletion) found its pool and the pool's queue full /// under a thread pool profile whose rejected policy is Abort; the branch did not run. Apache Camel's /// RejectedExecutionException. /// public sealed class RejectedExecutionException : Exception { /// Creates the exception for a rejected branch. public RejectedExecutionException(string message) : base(message) { } } Path: redb-route/redb.Route/Core/RouteBuilder.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/Core/RouteBuilder.cs ---- using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Expressions; namespace redb.Route.Core; /// /// Abstract base class for defining routes using the new DSL. /// Subclass and implement to define routes with the canonical /// ProcessorDefinition model. /// /// /// public class MyRoutes : RouteBuilder /// { /// protected override void Configure() /// { /// From("direct://input") /// .SetBody("hello") /// .To("direct://output"); /// /// From("timer://heartbeat?period=5000") /// .Log("tick"); /// } /// } /// /// context.AddRoutes(new MyRoutes()); /// /// /// public abstract class RouteBuilder : IRouteBuilder { private readonly List _definitions = []; private readonly List _exceptionDefinitions = []; private readonly List _intercepts = []; private readonly List _onCompletions = []; private readonly List _routeConfigurations = []; /// /// Route configurations declared on this builder (, a /// <routeConfiguration> of a markup file) — unlike the builder's own handlers they apply to the routes /// of every builder of the context. /// public IReadOnlyList RouteConfigurations => _routeConfigurations; /// /// Starts a route configuration (Apache Camel's Route Configuration): error handling for the routes of every /// builder of the context, not only of this one. Without an it is the default one: it /// applies to every route that has no configurations assigned. With an id it applies to the routes that name it /// with .RouteConfigurationId("id"); an id is unique within a context. A class that holds nothing but /// configurations reads best as a . /// /// The id of the configuration, or null for the default one. protected RouteConfigurationDefinition RouteConfiguration(string? id = null) => AddRouteConfiguration(id); /// Declares a route configuration on this builder from outside it (the markup loader). internal RouteConfigurationDefinition AddRouteConfiguration(string? id) { var configuration = new RouteConfigurationDefinition(id); _routeConfigurations.Add(configuration); return configuration; } /// What the builder is called in a log line: its type, or the document a markup builder was loaded from. internal virtual string SourceName => GetType().Name; /// Gets the route definitions created during . public IReadOnlyList Definitions => _definitions; /// Exception handlers declared on this builder via — they apply to every route it defines, and to no route of another builder. public IReadOnlyList ExceptionDefinitions => _exceptionDefinitions; /// Intercepts declared on this builder — they apply to every route it defines, and to no route of another builder. public IReadOnlyList Intercepts => _intercepts; /// OnCompletion blocks declared on this builder — they apply to every route it defines, and to no route of another builder. public IReadOnlyList OnCompletions => _onCompletions; /// Steps that run before every step of every route in this builder (Camel intercept()). public InterceptDefinition Intercept() => Register(new InterceptDefinition(InterceptKind.EveryStep, null)); /// Steps that run when a message enters any route of this builder whose From matches the mask (all routes when null). public InterceptDefinition InterceptFrom(string? uriPattern = null) => Register(new InterceptDefinition(InterceptKind.From, uriPattern)); /// Steps that run before any To / ToD in this builder whose target matches the mask; .SkipSendToOriginalEndpoint() replaces the send. public InterceptDefinition InterceptSendToEndpoint(string uriPattern) => Register(new InterceptDefinition(InterceptKind.SendToEndpoint, uriPattern)); /// Steps that run after any route of this builder finished with an exchange (on a copy, outside the route's transaction). public OnCompletionDefinition OnCompletion() { var def = new OnCompletionDefinition(); _onCompletions.Add(def); return def; } private InterceptDefinition Register(InterceptDefinition def) { _intercepts.Add(def); return def; } /// /// Override this method to define routes using . /// protected abstract void Configure(); /// /// Starts a new route definition with the given source endpoint. Public so that DSL layers built /// on top of routes (the REST DSL, generators) can add routes to a builder from outside /// ; inside a subclass it reads as before. /// /// Source endpoint URI (e.g., "direct://input", "timer://ping?period=1000"). /// The new route definition for fluent chaining. public IRouteDefinition From(string uri) { var def = new RouteDefinition(); def._context = Context; def.From(uri); _definitions.Add(def); return def; } /// /// Defines an exception handler for all routes of this builder (Apache Camel's RouteBuilder scope) — not for /// the routes of another builder of the same context; for those, see . Between /// this handler and a route's own the one whose exception type is nearest to the failure wins, the route's own /// on a tie. /// /// /// OnException<IOException>() /// .MaximumRedeliveries(3) /// .Handled() /// .Log("IO error: ${exception.message}"); /// /// /// /// Exception type to handle. /// Definition for fluent chaining of handler steps and configuration. public OnExceptionDefinition OnException() where TException : Exception { var def = new OnExceptionDefinition(new[] { typeof(TException) }); _exceptionDefinitions.Add(def); return def; } /// /// Defines an exception handler for multiple exception types at once, for all routes of this builder. /// /// Exception types to handle. /// Definition for fluent chaining. public OnExceptionDefinition OnException(params Type[] exceptionTypes) { if (exceptionTypes is not { Length: > 0 }) throw new ArgumentException("At least one exception type must be specified.", nameof(exceptionTypes)); foreach (var t in exceptionTypes) if (!typeof(Exception).IsAssignableFrom(t)) throw new ArgumentException($"Type '{t.Name}' is not an Exception type.", nameof(exceptionTypes)); var def = new OnExceptionDefinition(exceptionTypes); _exceptionDefinitions.Add(def); return def; } /// Gets the route context, available inside after registration. protected IRouteContext? Context { get; private set; } /// /// Called by to populate by running . /// internal void InternalBuild(IRouteContext? context = null) { _definitions.Clear(); _exceptionDefinitions.Clear(); _intercepts.Clear(); _onCompletions.Clear(); _routeConfigurations.Clear(); Context = context; Configure(); IsBuilt = true; } /// Whether has run at least once (AdviceWith builds early; a builder added later has not been built yet). internal bool IsBuilt { get; private set; } /// void IRouteBuilder.Configure(IRouteContext context) => InternalBuild(context); // ── Expression DSL helpers ────────────────────────────────────────────── /// Creates a JsonPath expression for extracting data from the message body. /// JsonPath expression (e.g., "$.store.books[0].title"). protected static JsonPathExpression JPath(string path) => new(path); /// Creates a typed JsonPath expression that converts the result to . protected static TypedJsonPathExpression JPath(string path) => new(path); /// /// Java-style alias. protected static JsonPathExpression jpath(string path) => new(path); /// /// Java-style alias. protected static TypedJsonPathExpression jpath(string path) => new(path); /// Creates an XPath expression for extracting data from an XML message body. /// XPath 1.0 expression. /// /// In a condition the result is a node-set, so the expression asks whether the path matched /// rather than what the matched node says. Use or /// to ask the other question. /// protected static XPathExpression XPath(string path) => new(path); /// Creates an XPath expression with an explicit XPath-level result type. /// XPath 1.0 expression. /// The XPath-level type of the result: node-set, node, string, number or boolean. protected static XPathExpression XPath(string path, XPathResult result) => new(path, result); /// Creates a typed XPath expression that converts the result to . protected static TypedXPathExpression XPath(string path) => new(path); /// /// Java-style alias. protected static XPathExpression xpath(string path) => new(path); /// /// Java-style alias. protected static XPathExpression xpath(string path, XPathResult result) => new(path, result); /// /// Java-style alias. protected static TypedXPathExpression xpath(string path) => new(path); /// Creates an expression that reads the exchange message body. protected static BodyExpression Body() => new(); /// Creates an expression that reads a message header value. /// Header name. protected static HeaderExpression Header(string name) => new(name); /// Creates an expression that reads an exchange property value. /// Property name. protected static PropertyExpression Property(string name) => new(name); /// Creates a constant expression that always returns the specified value. /// The constant value. protected static ConstantExpression Constant(object value) => new(value); /// Creates an expression evaluated from the exchange using a delegate. /// Function that accepts an and returns a value. protected static ExchangeExpression Exchange(Func func) => new(func); /// /// Creates a string expression that evaluates a ${...} template or raw expression. /// .SetBody(Expr("${header.source}")) /// /// Expression string with ${...} placeholders or raw expression. /// /// A ${...} template (or any expression text) as an : /// SetBody(Expr("Hello ${header.name}")). Public and static, so it also reads well from the /// lambda style, where a protected member of the builder would be out of reach: /// ctx.AddRoutes(b => b.From("...").SetBody(RouteBuilder.Expr("${header.x}"))). /// Equivalent to new StringExpression(template). /// public static StringExpression Expr(string template) => new(template); /// /// Apache Camel's method(ref, "name"): a registry bean's method as an expression or a condition, for /// Filter, When, Validate, SetBody, Split and every other expression slot. /// .Filter(Method("#loyalty", "IsGold(${header.name})")) is the typed form of /// ${bean:loyalty.IsGold(header.name)}: the same bean, binding and resolution. In a condition a method may /// return Task<bool>, which the engine awaits; in a value position the call is synchronous. /// /// The registry name, #name or name. /// /// The method in the bean: URI spelling: Name, or Name(arg, ...) with route-language arguments /// (IsGold(${header.name}), Gross(${header.qty}, 2.5)). /// public static IPredicateExpression Method(string reference, string methodSpec) => new BeanMethodExpression(reference, methodSpec); /// /// A value from configuration: {{key}} / {{key:default}} resolved through the route context, as in an /// endpoint URI: SetHeader("redbLdap.AuthDn", Placeholder("{{ldap.user}}")). Equivalent to /// new PlaceholderExpression(text); what value="{{key}}" of a markup step becomes. /// public static PlaceholderExpression Placeholder(string text) => new(text); // ── Streaming tokenizer helpers ───────────────────────────────────────── /// Creates a splitter function that splits the body into lines. /// Line separator (default: newline). /// Whether to skip empty/whitespace lines. protected static Func> SplitLines( string separator = "\n", bool skipEmpty = false) => exchange => Expressions.Tokenizers.LineTokenizer.Tokenize(exchange.In.Body, separator, skipEmpty); /// Creates a splitter function that extracts XML elements by local name. /// Local name of elements to extract. /// Optional parent element whose namespaces should be injected. protected static Func> SplitXml( string elementName, string? inheritNamespaceFrom = null) => exchange => Expressions.Tokenizers.XmlTokenizer.Tokenize(exchange.In.Body, elementName, inheritNamespaceFrom); /// Creates a splitter function that splits a JSON array body into individual elements. protected static Func> SplitJsonArray() => exchange => Expressions.Tokenizers.JsonArrayTokenizer.Tokenize(exchange.In.Body); } /// /// Route builder that accepts an inline configure action, for use with /// . /// public sealed class InlineRouteBuilder : RouteBuilder { private readonly Action _configure; /// Creates an inline route builder. public InlineRouteBuilder(Action configure) { _configure = configure ?? throw new ArgumentNullException(nameof(configure)); } /// protected override void Configure() => _configure(this); } Path: redb-route/redb.Route/Core/RouteBuilderDiscovery.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/Core/RouteBuilderDiscovery.cs ---- using System.Reflection; namespace redb.Route.Core; /// /// Finds the types of a set of assemblies — the one place both /// and /// go through. /// /// A candidate is a public, non-abstract, closed class deriving from — a nested public type /// included, excluded. Which of them to take is the caller's filter, as Apache /// Camel's include/exclude patterns: there is no attribute, a type stays out by its filter or by being non-public /// or abstract. The order is by full name, for a reproducible log; it carries no meaning, since a builder's /// OnException, Intercept* and OnCompletion apply to its own routes only. /// /// /// Nothing is skipped silently: an assembly whose types cannot all be loaded is an error, not a partial scan — /// a route builder among the types that failed would otherwise vanish without a word. /// /// internal static class RouteBuilderDiscovery { /// The route builder types of that pass , by full name. /// Assemblies to scan; at least one. /// Which candidates to take; null takes them all. internal static IReadOnlyList FindBuilderTypes(IEnumerable assemblies, Func? filter) { ArgumentNullException.ThrowIfNull(assemblies); var distinct = assemblies.Distinct().ToList(); if (distinct.Count == 0) throw new ArgumentException("At least one assembly is required to discover route builders.", nameof(assemblies)); if (distinct.Any(a => a is null)) throw new ArgumentException("The assemblies to discover route builders in must not contain null.", nameof(assemblies)); return distinct .SelectMany(LoadTypes) .Where(IsCandidate) .Where(t => filter?.Invoke(t) ?? true) .OrderBy(t => t.FullName, StringComparer.Ordinal) .ToList(); } /// /// Creates a discovered builder through its public parameterless constructor — the context path, which has no /// container to inject from. /// internal static RouteBuilder Create(Type builderType) { if (builderType.GetConstructor(Type.EmptyTypes) is null) throw new InvalidOperationException( $"Route builder '{builderType.FullName}' has no public parameterless constructor, so it cannot be " + "created by assembly discovery on the context. Register it through dependency injection " + "(RedbRouteBuilder.AddRouteBuilders), add an instance with AddRoutes(builder), or leave it out with the filter."); try { return (RouteBuilder)Activator.CreateInstance(builderType)!; } catch (TargetInvocationException ex) { throw new InvalidOperationException( $"Route builder '{builderType.FullName}' threw from its constructor during assembly discovery.", ex.InnerException ?? ex); } } private static bool IsCandidate(Type type) => type.IsClass && !type.IsAbstract && !type.ContainsGenericParameters && type.IsVisible && type != typeof(InlineRouteBuilder) && typeof(RouteBuilder).IsAssignableFrom(type); private static Type[] LoadTypes(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { var reasons = ex.LoaderExceptions .Where(e => e is not null) .Select(e => e!.Message) .Distinct() .ToList(); throw new InvalidOperationException( $"Not every type of assembly '{assembly.FullName}' could be loaded, so its route builders cannot be " + $"discovered reliably: {string.Join("; ", reasons)}", ex); } } } Path: redb-route/redb.Route/Core/RouteCancellation.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/Core/RouteCancellation.cs ---- namespace redb.Route.Core; /// /// The one rule that tells a cancellation from a failure, and the one place an owned timeout is named as /// one. Shared by error handling and by every component that runs under a deadline. /// /// A cancellation is what the caller's asked for. An /// raised while that token is still live is NOT a cancellation: it /// is a timeout (an HttpClient deadline, a component's own guard) or an internal abort, and error handling /// must see it like any other failure. Keying the pass-through on the exception type alone was the bug: an /// HTTP producer's timeout is a , so TryCatch/Catch, OnException, Retry /// and DeadLetterChannel all treated it as cancellation and skipped it, and the exchange died whole. /// /// /// Error handling normalizes such an exception to (the original kept as /// ) so a route can name it — Catch<TimeoutException>, /// OnException<TimeoutException>, <catch exceptions="System.TimeoutException"> — /// instead of the symptom type . A genuine cancellation is never /// normalized and never handled. /// /// public static class RouteCancellation { /// /// True when the exception is the cancellation asked for. Everything else — /// including an raised while is still /// live — is a failure error handling must see. /// public static bool IsCancellation(Exception ex, CancellationToken ct) => ex is OperationCanceledException && ct.IsCancellationRequested; /// /// True when the exception is an that is NOT the caller's /// cancellation: a timeout or an internal abort that error handling must treat as a failure. /// public static bool IsOwnedTimeout(Exception ex, CancellationToken ct) => ex is OperationCanceledException && !ct.IsCancellationRequested; /// /// True when is or a subtype /// (). Error handling never handles such a type — a genuine /// cancellation is filtered out and a timeout arrives as — so a /// Catch<T> / OnException<T> on one is a branch that can never fire. /// public static bool IsCancellationType(Type exceptionType) => typeof(OperationCanceledException).IsAssignableFrom(exceptionType); /// /// Names an owned timeout as one for error handling: an raised /// while is still live becomes a carrying the /// original as . Anything else, a genuine cancellation included, is /// returned unchanged. The result is what to act on — assign to , match /// handlers against, or rethrow. /// /// The caught exception. /// The token the operation ran under — the caller's. /// Message for the produced ; a generic one by default. public static Exception Normalize(Exception ex, CancellationToken ct, string? message = null) => IsOwnedTimeout(ex, ct) ? new TimeoutException( message ?? "The operation timed out: it was cancelled by a deadline, not by the caller's token.", ex) : ex; } Path: redb-route/redb.Route/Core/RouteConfigurationBuilder.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/Core/RouteConfigurationBuilder.cs ---- namespace redb.Route.Core; /// /// Base class for route configurations (Apache Camel's RouteConfigurationBuilder): error handling declared /// once, apart from the routes, for the routes of every builder of the context. It is a route builder, so it is added /// to a context the same way — context.AddRoutes(...), or found by assembly discovery. /// /// /// public sealed class IntegrationErrors : RouteConfigurationBuilder /// { /// protected override void Configuration() /// { /// // No id: the default, for every route that has no configurations assigned. /// RouteConfiguration() /// .OnException<Exception>() /// .MaximumRedeliveries(3) /// .Handled() /// .Log("failed: ${exception.message}"); /// /// // By id: for the routes that say .RouteConfigurationId("audit"). /// RouteConfiguration("audit") /// .OnException<IOException>().Handled().To("direct://audit-failed"); /// } /// } /// /// context.AddRoutes(new IntegrationErrors()); /// /// /// public abstract class RouteConfigurationBuilder : RouteBuilder { /// Override this method to declare the configurations with . protected abstract void Configuration(); /// Runs . A configuration builder may also define routes by overriding this and calling the base. protected override void Configure() => Configuration(); } Path: redb-route/redb.Route/Core/RouteContext.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/Core/RouteContext.cs ---- using System.Collections.Concurrent; using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Configuration; using redb.Route.Definitions; using redb.Route.Processors; using redb.Route.Serialization; using redb.Route.Telemetry; namespace redb.Route.Core; /// /// Central runtime context: component registry, endpoint cache, route compilation and lifecycle, /// properties, service locator, and three-tier exception handling. /// Replaces the former RouteEngine — like Apache Camel's CamelContext, this is the single /// entry point that owns routes from definition through execution. /// public class RouteContext : IRouteContext, IAsyncDisposable { private readonly ConcurrentDictionary _components = new(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); private readonly List _consumers = []; private readonly List _producers = []; // Producers are tracked from route compilation, from processors on first use and from producer templates, which // may run on several threads at once. private readonly object _producersLock = new(); // Context-level properties private readonly ConcurrentDictionary _properties = new(StringComparer.OrdinalIgnoreCase); // Named object registry private readonly ConcurrentDictionary _registry = new(StringComparer.OrdinalIgnoreCase); // Type-based service locator private readonly ConcurrentDictionary _services = new(); // DI container private IServiceProvider? _serviceProvider; // Global exception handlers: ExceptionType → Processor private readonly ConcurrentDictionary _globalExceptionHandlers = new(); // Local exception handlers: RouteId → (ExceptionType → Processor) private readonly ConcurrentDictionary> _localExceptionHandlers = new(); // The two tables above hold what the user registered and outlive a restart. The error scope of each route — its // own OnException blocks, its builder's, the context layer — is rebuilt on every compile (RouteErrorScope). private readonly ConcurrentDictionary _errorScopes = new(); // The error scope of the route being compiled, for a detached body (.Threads()) to be wrapped by. Null while a // handler body or a detached block (OnCompletion) compiles: those run outside the route's error handling. private RouteErrorScope? _compilingErrorScope; // Route compilation // Not readonly: AddService(ILoggerFactory, ...) adopts a factory registered after construction // and back-fills component loggers, so a context created without one still logs consumer failures. private ILoggerFactory? _loggerFactory; private ILogger? _logger; private readonly RouteEngineOptions _options; /// The engine's stream caching options (). internal Configuration.StreamCacheOptions StreamCacheOptions => _options.StreamCaching; /// The engine's attachment options (). internal Configuration.AttachmentOptions AttachmentOptions => _options.Attachments; /// The engine's reconnect options (), read by connection supervisors. internal Configuration.ReconnectOptions ReconnectOptions => _options.Reconnect; // The static targets of the route being compiled (To, WireTap, Enrich, load-balancer targets, fixed recipients): // their endpoints are created once the route compiles, as Camel resolves a static to(...) at route startup. private List? _compilingStaticEndpoints; // Resolved static targets an intercept with skipSendToOriginalEndpoint matches: the original may never be sent to // (a dry run whose real component is absent), so their endpoints are not created up front. private HashSet? _compilingSkippedStaticEndpoints; /// /// A processor with a fixed target notes it while its route compiles; the endpoint is then created before the route /// starts, so an unknown scheme, an unknown URI parameter or a missing {{key}} fails the start. Outside a /// compilation (a processor made while messages flow) nothing is noted. /// internal void NoteStaticEndpoint(string uri) => _compilingStaticEndpoints?.Add(uri); /// The engine's , read by transport spans too. internal bool TelemetryEnabled => _options.EnableTelemetry; /// /// Whether an Errored route of this context makes health Unhealthy rather than Degraded /// ( while a start retry waits for it, /// otherwise). A route that is not Errored: false. /// public bool IsErroredRouteUnhealthy(CompiledRoute route) { ArgumentNullException.ThrowIfNull(route); return route.Status == RouteStatus.Errored && _options.ConsumerStartRetry.ErroredRouteIsUnhealthy(_startRetryRoutes.ContainsKey(route)); } private readonly List _builders = []; // Builder types added by AddRoutes(Assembly[]); an explicit AddRoutes(builder) of one of them is a duplicate. private readonly HashSet _discoveredBuilderTypes = []; /// Registered builders (test-kit seam for AdviceWith; definitions are built on demand). internal IReadOnlyList RouteBuilders => _builders; /// /// Set by AdviceWith after it has run every builder's Configure() ahead of /// and rewritten the definitions; then compiles them as-is /// instead of rebuilding (which would discard the advice). /// internal bool DefinitionsPrebuilt { get; set; } private readonly List _routes = []; private readonly IInflightRepository _inflightRepository = new DefaultInflightRepository(); // Copy-on-write: the array is replaced on registration and read as a snapshot per notification, so a // listener registered while exchanges flow (NotifyBuilder on a running context, a listener adding // another listener from a callback) never races an enumeration. private IRouteLifecycleListener[] _lifecycleListeners = []; private readonly object _lifecycleListenersLock = new(); private ConnectionEventDispatcher? _connectionEvents; private readonly List _policyFactories = []; private readonly SemaphoreSlim _routeLock = new(1, 1); // Replay checkpoints: compiled marker body per (routeId, markerName). Populated at compile time // so ReplayAsync can re-run the tail directly (no synthetic endpoint) and Tsak can list markers // before any traffic. private readonly Dictionary<(string RouteId, string Marker), (IProcessor Body, bool Exposed)> _checkpoints = new(); // Route currently being compiled — set around definition.CreateProcessor so a nested // ReplayableDefinition can register itself against the right routeId. private string? _compilingRouteId; /// The route being compiled, for the steps that name it in their metrics. internal string? CompilingRouteId => _compilingRouteId; // Message-history state for the route currently being compiled (set alongside _compilingRouteId). private bool _compilingMessageHistory; private int _compilingNodeCounter; private readonly List _disposableProcessors = new(); /// The compiled processors the context owns, for tests. internal IReadOnlyList DisposableProcessors => _disposableProcessors; private volatile bool _started; // Cancels the background start retries of consumers that failed with the context (ConsumerStartRetry). private CancellationTokenSource? _startRetryCts; // The routes a start retry still owns. A start, stop or resume by hand takes the route out of it. private readonly ConcurrentDictionary _startRetryRoutes = new(); /// /// Optional callback invoked after routes are compiled but before consumers are started. /// Allows external code (e.g., Tsak StateStore) to override /// for individual routes before the context decides which consumers to skip. /// public Func, Task>? OnBeforeRoutesStart { get; set; } /// /// Creates a new route context with built-in components (Direct, Timer, Seda, Mock, Log) /// and registers the provided for DI resolution. /// /// DI service provider. /// Optional context identifier. If null, a new GUID is generated. /// Optional logger factory for route compilation diagnostics. /// Engine options (telemetry, metrics, shutdown, etc.). public RouteContext(IServiceProvider serviceProvider, string? contextId = null, ILoggerFactory? loggerFactory = null, RouteEngineOptions? options = null) : this(contextId, loggerFactory, options) { ArgumentNullException.ThrowIfNull(serviceProvider); SetServiceProvider(serviceProvider); } /// /// Creates a new route context with built-in components (Direct, Timer, Seda, Mock, Log). /// /// Optional context identifier. If null, a new GUID is generated. /// Optional logger factory for route compilation diagnostics. /// Engine options (telemetry, metrics, shutdown, etc.). public RouteContext(string? contextId = null, ILoggerFactory? loggerFactory = null, RouteEngineOptions? options = null) { ContextId = contextId ?? Guid.NewGuid().ToString("N"); IsContextIdGenerated = contextId is null; _loggerFactory = loggerFactory; _logger = loggerFactory?.CreateLogger(); _options = options ?? new RouteEngineOptions(); _options.ConsumerStartRetry.Validate(); _options.Reconnect.Validate(); _options.DefaultThreadPoolProfile.Validate("default"); foreach (var (name, profile) in _options.ThreadPoolProfiles) AddThreadPoolProfile(name, profile); // A collectible load context of a host's module unloads only once the .NET library caches let its types go. CollectibleContextCleanup.EnsureWatching(_logger); if (_logger is not null) _services[typeof(ILogger)] = _logger; // Expose the logger factory via the service locator so definitions // (the Log* definitions and RichLogScopeDefinition, etc.) can resolve it // through IRouteContext.GetService() without reaching for DI. if (loggerFactory is not null) _services[typeof(ILoggerFactory)] = loggerFactory; // Register built-in components _components["direct"] = SetComponentContext(new DirectComponent()); _components["timer"] = SetComponentContext(new TimerComponent()); _components["seda"] = SetComponentContext(new SedaComponent()); _components["mock"] = SetComponentContext(new MockComponent()); _components["log"] = SetComponentContext(new LogComponent(loggerFactory)); _components["direct-vm"] = SetComponentContext(new DirectVmComponent()); _components["vm"] = SetComponentContext(new VmComponent()); _components["xslt"] = SetComponentContext(new Xslt.XsltComponent()); _components["controlbus"] = SetComponentContext(new ControlBus.ControlBusComponent()); _components["bean"] = SetComponentContext(new Components.Bean.BeanComponent()); // Register built-in services _services[typeof(IDataFormatRegistry)] = new DataFormatRegistry(); } private IComponent SetComponentContext(IComponent component) { if (component is ComponentBase baseComponent) { baseComponent.Context = this; baseComponent.Logger ??= _loggerFactory?.CreateLogger(component.GetType()); } return component; } // ── Identity ── /// public string ContextId { get; } /// /// Whether was generated (a new GUID) rather than given: then it differs on every start and /// on every node, so nothing persisted under it — a job store's scheduler name — can be found again. /// public bool IsContextIdGenerated { get; } /// public bool IsStarted => _started; /// Repository tracking all in-flight exchanges across routes in this context. public IInflightRepository InflightRepository => _inflightRepository; // ── Properties ── /// public object? this[string key] { get => _properties.TryGetValue(key, out var value) ? value : null; set => _properties[key] = value; } /// public T? GetProperty(string key) { if (!_properties.TryGetValue(key, out var value) || value is null) return default; if (value is T typed) return typed; try { return (T)RouteDecimal.ChangeType(value, typeof(T)); } catch { return default; } } /// public IRouteContext SetProperty(string key, T value) { _properties[key] = value; return this; } // ── Registry ── /// public IRouteContext AddToRegistry(string key, object value) { ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(value); _registry[key] = value; return this; } // ── Replay checkpoints ── /// /// Registers a compiled .Replayable marker body for the route currently being compiled. /// Called by ; keyed on the /// route being compiled () plus the marker name. /// internal void RegisterCheckpoint(string markerName, IProcessor body, bool exposed) { ArgumentException.ThrowIfNullOrWhiteSpace(markerName); ArgumentNullException.ThrowIfNull(body); var routeId = _compilingRouteId ?? throw new InvalidOperationException( "RegisterCheckpoint called outside route compilation — no route id in scope."); if (!_checkpoints.TryAdd((routeId, markerName), (body, exposed))) throw new InvalidOperationException( $"Duplicate replay marker '{markerName}' on route '{routeId}'. Marker names must be unique within a route."); // exposed:true → make the marker addressable as a direct: endpoint so other routes can // .To(...) it (and ProducerTemplate can Send to it). Internal (default) markers register no // endpoint — they are reachable only via ReplayAsync. Wired at compile time so the body is // ready before any producer sends at runtime. if (exposed) { var uri = RouteCheckpoint.EndpointUri(routeId, markerName); if (GetEndpoint(uri) is Components.DirectEndpoint endpoint) endpoint.RegisterConsumerProcessor(body); else throw new InvalidOperationException( $"Could not register exposed replay endpoint '{uri}' — direct component missing?"); } } /// public async Task ReplayAsync(string routeId, string markerName, IExchange snapshot, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(routeId); ArgumentException.ThrowIfNullOrWhiteSpace(markerName); ArgumentNullException.ThrowIfNull(snapshot); if (!_checkpoints.TryGetValue((routeId, markerName), out var entry)) throw new InvalidOperationException( $"No replay checkpoint '{markerName}' on route '{routeId}'. " + $"Ensure the route declares .Replayable(\"{markerName}\") and has been compiled."); // The tail creates its OWN scoped SQL/redb services lazily from the context provider (fresh // connections — old ones from the failed run are dead/rolled-back, so re-creating is correct): // nothing to pre-mint or "capture" here. But because we invoke the body directly, bypassing // the normal consumer→dispose lifecycle, WE must dispose whatever scopes the tail cached on // the snapshot — else every replay leaks a connection. Exchange.ReleaseScopes does exactly // that, and it re-arms itself after every sweep, so a snapshot released before this replay // needs no special preparation. try { // Run the marker's tail directly from the frozen snapshot — same compiled body as inline // execution (processors are re-entrant). No synthetic endpoint. await entry.Body.Process(snapshot, ct).ConfigureAwait(false); } finally { if (snapshot is Exchange ex) await ex.ReleaseScopes().ConfigureAwait(false); } } /// public IReadOnlyCollection<(string RouteId, string MarkerName)> GetReplayMarkers() => _checkpoints.Keys.Select(k => (k.RouteId, k.Marker)).ToArray(); /// public T? GetFromRegistry(string key) { if (key.StartsWith('#')) key = key[1..]; if (_registry.TryGetValue(key, out var value) && value is T typed) return typed; return default; } // ── Service Locator ── /// public void AddService(Type serviceType, object service) { ArgumentNullException.ThrowIfNull(serviceType); ArgumentNullException.ThrowIfNull(service); _services[serviceType] = service; // A logger factory registered after construction must actually reach components: adopt it as // the context's factory (used by SetComponentContext for components added later and by the // route compiler for OnException/statistics loggers) and back-fill loggers onto components that // were registered before it. Without this, a context created with no factory logs nothing — // consumer failures pass silently. if (service is ILoggerFactory factory) AdoptLoggerFactory(factory); } /// /// Adopts as the context logger factory and back-fills a logger onto /// every already-registered component that does not have one. /// private void AdoptLoggerFactory(ILoggerFactory factory) { _loggerFactory = factory; _logger ??= factory.CreateLogger(); if (!_services.ContainsKey(typeof(ILogger)) && _logger is not null) _services[typeof(ILogger)] = _logger; foreach (var component in _components.Values) { if (component is ComponentBase baseComponent) baseComponent.Logger ??= factory.CreateLogger(component.GetType()); } } /// public T? GetService() where T : class { return _services.TryGetValue(typeof(T), out var service) && service is T typed ? typed : default; } // ── DI ── /// public IRouteContext SetServiceProvider(IServiceProvider serviceProvider) { ArgumentNullException.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; return this; } /// public IServiceProvider? GetServiceProvider() => _serviceProvider; // ── Component Management ── /// public void AddComponent(IComponent component) { ArgumentNullException.ThrowIfNull(component); var configured = SetComponentContext(component); _components[component.Scheme] = configured; foreach (var alias in component.AlternateSchemes) _components[alias] = configured; } /// public T? GetComponent(string? scheme = null) where T : class, IComponent { if (!string.IsNullOrEmpty(scheme)) { return _components.TryGetValue(scheme, out var c) && c is T typed ? typed : default; } foreach (var component in _components.Values) { if (component is T match) return match; } return default; } /// public bool HasComponent(string scheme) => _components.ContainsKey(scheme); /// public IReadOnlyList GetComponentNames() => _components.Keys.ToList().AsReadOnly(); /// public bool RemoveComponent(string scheme) { ArgumentException.ThrowIfNullOrEmpty(scheme); return _components.TryRemove(scheme, out _); } // ── Endpoint Management ── /// public IEndpoint GetEndpoint(string uri) { var resolved = ResolvePlaceholders(uri); var parsed = EndpointUriParser.Parse(resolved); return _endpoints.GetOrAdd(parsed.NormalizedKey, _ => CreateEndpoint(parsed)); } /// /// Expands Camel-style {{key}} / {{key:default}} property placeholders in an endpoint URI /// before it is parsed, so every connector's URIs externalise their configuration for free. Values come /// from IConfiguration (environment, appsettings, user-secrets) first, then the context's own /// properties as a container-free fallback. No-op for the common case of a URI without placeholders. /// // Internal (not private): the XML loader resolves {{...}} in through the // context's own lookup chain instead of keeping a second copy of it. internal string ResolvePlaceholders(string uri) { if (!PropertyPlaceholderResolver.HasPlaceholder(uri)) return uri; return PropertyPlaceholderResolver.Resolve(uri, LookupPlaceholderValue); } private string? LookupPlaceholderValue(string key) { // IConfiguration already layers env vars + appsettings + user-secrets with its own precedence, // so a single indexer lookup covers what Camel needs env:/sys: prefix functions for. var config = GetService() ?? _serviceProvider?.GetService(); var fromConfig = config?[key]; if (!string.IsNullOrEmpty(fromConfig)) return fromConfig; // Container-free fallback: values set via context.SetProperty(...). var fromProperties = GetProperty(key); if (!string.IsNullOrEmpty(fromProperties) || config is not null) return fromProperties; // No IConfiguration at all (a plain console app): the OS environment. With an IConfiguration the host decides // whether the environment takes part, so it is never read past it. A placeholder key never holds ':' (it // separates the default), so the "a__b" spelling of IConfiguration's environment provider does not arise. var fromEnvironment = Environment.GetEnvironmentVariable(key); return string.IsNullOrEmpty(fromEnvironment) ? null : fromEnvironment; } // ── Exception Handling ── /// public IErrorHandler? ErrorHandler { get; set; } /// public bool HasExceptionRoute() where TException : Exception { var exType = typeof(TException); // Check global handlers if (FindHandler(_globalExceptionHandlers, exType) is not null) return true; // Check all local handler sets foreach (var localHandlers in _localExceptionHandlers.Values) { if (FindHandler(localHandlers, exType) is not null) return true; } // Check the OnException blocks of every route and of its builder foreach (var scope in _errorScopes.Values) { if (scope.Handles(exType)) return true; } return false; } /// public void AddGlobalExceptionHandler(IProcessor processor) where TException : Exception { ArgumentNullException.ThrowIfNull(processor); if (!_globalExceptionHandlers.TryAdd(typeof(TException), processor)) throw new InvalidOperationException( $"Global exception handler for {typeof(TException).Name} is already registered."); } /// public void AddGlobalExceptionHandler(Type exceptionType, IProcessor processor) { ArgumentNullException.ThrowIfNull(exceptionType); ArgumentNullException.ThrowIfNull(processor); if (!_globalExceptionHandlers.TryAdd(exceptionType, processor)) throw new InvalidOperationException( $"Global exception handler for {exceptionType.Name} is already registered."); } /// public void AddLocalExceptionHandler(string routeId, Type exceptionType, IProcessor processor) { ArgumentException.ThrowIfNullOrEmpty(routeId); ArgumentNullException.ThrowIfNull(exceptionType); ArgumentNullException.ThrowIfNull(processor); var handlers = _localExceptionHandlers.GetOrAdd(routeId, _ => new ConcurrentDictionary()); handlers[exceptionType] = processor; } /// public async Task HandleException(IExchange exchange, Exception exception, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); ArgumentNullException.ThrowIfNull(exception); // Tier 4: No handler found — throw if (!await HandleWithContextHandlers(exchange, exception, exchange.RouteId, ct).ConfigureAwait(false)) throw new InvalidOperationException( $"No exception handler found for {exception.GetType().Name} in route '{exchange.RouteId}'.", exception); } /// /// The context's error handling, in its order: a local handler of (tier 1), a global /// handler (tier 2), (tier 3). Runs the first that matches and returns true; /// false when none does. The one lookup behind and the outermost layer of /// every route's error scope (). /// internal async Task HandleWithContextHandlers(IExchange exchange, Exception exception, string? routeId, CancellationToken ct) { // Tier 1: Local route handler if (!string.IsNullOrEmpty(routeId) && _localExceptionHandlers.TryGetValue(routeId, out var localHandlers) && FindHandler(localHandlers, exception.GetType()) is { } local) { Caught(exchange, exception); await local.Process(exchange, ct).ConfigureAwait(false); return true; } // Tier 2: Global handler if (FindHandler(_globalExceptionHandlers, exception.GetType()) is { } global) { Caught(exchange, exception); await global.Process(exchange, ct).ConfigureAwait(false); return true; } // Tier 3: ErrorHandler fallback if (ErrorHandler is { } errorHandler) { Caught(exchange, exception); await errorHandler.HandleError(exchange, exception, ct).ConfigureAwait(false); return true; } return false; // A handler takes the failure: it is on the exchange, and kept for predicate/expression usage. A failure no // handler took leaves the exchange as it was. static void Caught(IExchange exchange, Exception exception) { exchange.Properties["ExceptionCaught"] = exception; exchange.Exception = exception; } } // ── Route Management ── /// Gets the compiled routes (available after Start). public IReadOnlyList Routes => _routes; /// Adds a route builder containing route definitions. /// Route builder to add. /// This context for fluent chaining. /// The builder's type was already added by assembly discovery. public RouteContext AddRoutes(RouteBuilder builder) { ArgumentNullException.ThrowIfNull(builder); if (_discoveredBuilderTypes.Contains(builder.GetType())) throw new InvalidOperationException( $"Route builder '{builder.GetType().FullName}' was already added by assembly discovery. " + "Leave it out of the discovery with the filter, or do not add it again."); _builders.Add(builder); return this; } /// /// Adds every route builder of : each public, non-abstract, closed class deriving from /// , created through its public parameterless constructor (Apache Camel's routes /// discovery). For constructor injection use RedbRouteBuilder.AddRouteBuilders in the host. /// /// Assemblies to scan; at least one. /// This context for fluent chaining. /// /// A builder cannot be created, its type is already added, or an assembly's types cannot all be loaded. Nothing is /// added then. /// public RouteContext AddRoutes(params Assembly[] assemblies) => AddDiscoveredRoutes(assemblies, filter: null); /// /// with a filter choosing which builders to take — the place for a condition /// (environment, configuration) and for leaving a builder out. /// /// Assemblies to scan; at least one. /// Returns true for a builder type to add. /// This context for fluent chaining. /// As . public RouteContext AddRoutes(IEnumerable assemblies, Func filter) { ArgumentNullException.ThrowIfNull(filter); return AddDiscoveredRoutes(assemblies, filter); } private RouteContext AddDiscoveredRoutes(IEnumerable assemblies, Func? filter) { var types = RouteBuilderDiscovery.FindBuilderTypes(assemblies, filter); // A type already here — added explicitly or by an earlier discovery — would compile its routes twice and fail // only at Start with a duplicate route id; said now, with the type's name. var present = _builders.Select(b => b.GetType()).ToHashSet(); foreach (var type in types) { if (present.Contains(type)) throw new InvalidOperationException( $"Route builder '{type.FullName}' is already added to this context. " + "Leave it out of the discovery with the filter, or do not add it explicitly."); } // Every builder is created before any is added: a failure leaves the context as it was. var builders = types.Select(RouteBuilderDiscovery.Create).ToList(); foreach (var builder in builders) { _builders.Add(builder); _discoveredBuilderTypes.Add(builder.GetType()); } _logger?.LogInformation("Discovered {Count} route builder(s): {Builders}", builders.Count, string.Join(", ", types.Select(t => t.FullName))); return this; } /// Adds routes using an inline configure action. /// Action to configure routes. /// This context for fluent chaining. public RouteContext AddRoutes(Action configure) { ArgumentNullException.ThrowIfNull(configure); var builder = new InlineRouteBuilder(configure); _builders.Add(builder); return this; } /// /// Adds the default route configuration with an inline action — the inline form of a /// : error handling for every route of the context that has no /// configurations assigned. /// /// /// context.AddRouteConfiguration(c => c /// .OnException<Exception>().MaximumRedeliveries(3).Handled().Log("failed: ${exception.message}")); /// /// /// /// Action that declares the handlers of the configuration. /// This context for fluent chaining. public RouteContext AddRouteConfiguration(Action configure) { ArgumentNullException.ThrowIfNull(configure); _builders.Add(new InlineRouteConfigurationBuilder(null, configure)); return this; } /// /// Adds a route configuration with an id, for the routes that name it with .RouteConfigurationId("id"). /// /// The id of the configuration, unique within the context. /// Action that declares the handlers of the configuration. /// This context for fluent chaining. public RouteContext AddRouteConfiguration(string id, Action configure) { ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentNullException.ThrowIfNull(configure); _builders.Add(new InlineRouteConfigurationBuilder(id, configure)); return this; } private sealed class InlineRouteConfigurationBuilder(string? id, Action configure) : RouteConfigurationBuilder { protected override void Configuration() => configure(RouteConfiguration(id)); } /// Registers a lifecycle listener for route state change notifications. /// This context for fluent chaining. public IRouteContext AddLifecycleListener(IRouteLifecycleListener listener) { ArgumentNullException.ThrowIfNull(listener); lock (_lifecycleListenersLock) _lifecycleListeners = [.. _lifecycleListeners, listener]; return this; } /// public IRouteContext AddRoutePolicyFactory(IRoutePolicyFactory factory) { ArgumentNullException.ThrowIfNull(factory); _policyFactories.Add(factory); return this; } /// public RoutePolicyDescriptor GetRoutePolicy(string routeId) { ArgumentNullException.ThrowIfNull(routeId); var route = GetRoute(routeId); if (route is null) return new RoutePolicyDescriptor(false, "AllNodes", null, "Route not found"); return route.PolicyDescriptor; } /// /// Gets a compiled route by its route ID. /// Returns null if not found. /// public CompiledRoute? GetRoute(string routeId) { ArgumentNullException.ThrowIfNull(routeId); return _routes.Find(r => r.RouteId.Equals(routeId, StringComparison.OrdinalIgnoreCase)); } /// /// Starts an individual route by its route ID. /// The route must have been previously compiled and stopped. /// public async Task StartRoute(string routeId, CancellationToken ct = default) { await _routeLock.WaitAsync(ct).ConfigureAwait(false); try { var route = GetRoute(routeId) ?? throw new InvalidOperationException($"Route '{routeId}' not found."); if (route.Status == RouteStatus.Started) throw new InvalidOperationException($"Route '{routeId}' is already started."); _startRetryRoutes.TryRemove(route, out _); route.Status = RouteStatus.Starting; _logger?.LogInformation("Starting route '{RouteId}'...", routeId); try { if (route.Policy is { } policy) await policy.OnStart(this, route, ct).ConfigureAwait(false); await route.Consumer.Start(ct).ConfigureAwait(false); route.Status = RouteStatus.Started; _logger?.LogInformation("Route '{RouteId}' started.", routeId); await NotifyRouteStarted(routeId, ct).ConfigureAwait(false); } catch (Exception ex) { route.Status = RouteStatus.Errored; _logger?.LogError(ex, "Route '{RouteId}' failed to start.", routeId); await NotifyRouteErrored(routeId, ex, ct).ConfigureAwait(false); throw; } } finally { _routeLock.Release(); } } /// /// Stops an individual route by its route ID. /// public Task StopRoute(string routeId, CancellationToken ct = default) => StopRoute(routeId, null, ct); /// /// Resumes a previously stopped/suspended route. /// If the route has a policy (e.g., clustered), delegates to /// so the policy can restart its background lifecycle (e.g., lock acquisition loop). /// The consumer is NOT started directly — the policy will call when ready. /// For routes without a policy, falls through to . /// public async Task ResumeRoute(string routeId, CancellationToken ct = default) { var ownsLock = true; await _routeLock.WaitAsync(ct).ConfigureAwait(false); try { var route = GetRoute(routeId) ?? throw new InvalidOperationException($"Route '{routeId}' not found."); if (route.Status == RouteStatus.Started) return; _startRetryRoutes.TryRemove(route, out _); if (route.Policy is not { } policy) { // No policy — release lock and delegate to normal StartRoute ownsLock = false; _routeLock.Release(); await StartRoute(routeId, ct).ConfigureAwait(false); return; } route.Status = RouteStatus.Starting; _logger?.LogInformation("Resuming route '{RouteId}' via policy...", routeId); try { await policy.OnResume(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { route.Status = RouteStatus.Errored; _logger?.LogError(ex, "Route '{RouteId}' failed to resume.", routeId); throw; } } finally { if (ownsLock) _routeLock.Release(); } } /// /// Stops an individual route by its route ID with an optional timeout override. /// /// The route identifier. /// Timeout for graceful drain. If null, uses . /// Cancellation token. public async Task StopRoute(string routeId, TimeSpan? timeout, CancellationToken ct = default) { await _routeLock.WaitAsync(ct).ConfigureAwait(false); try { var route = GetRoute(routeId) ?? throw new InvalidOperationException($"Route '{routeId}' not found."); _startRetryRoutes.TryRemove(route, out _); if (route.Status == RouteStatus.Stopped) throw new InvalidOperationException($"Route '{routeId}' is already stopped."); var effectiveTimeout = timeout ?? _options.ShutdownTimeout; route.Status = RouteStatus.Suspending; _logger?.LogInformation("Stopping route '{RouteId}' (timeout={Timeout}s)...", routeId, effectiveTimeout.TotalSeconds); await NotifyRouteSuspending(routeId, ct).ConfigureAwait(false); if (route.Policy is { } policy) { try { await policy.OnSuspend(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RoutePolicy.OnSuspend failed for route '{RouteId}'", routeId); } } route.Status = RouteStatus.Suspended; using var timeoutCts = new CancellationTokenSource(effectiveTimeout); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token); try { await route.Consumer.Stop(linked.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested) { route.Status = RouteStatus.Stopping; _logger?.LogWarning( "Route '{RouteId}' stop timed out after {Timeout}s, forced shutdown", routeId, effectiveTimeout.TotalSeconds); } if (route.Policy is { } stopPolicy) { try { await stopPolicy.OnStop(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RoutePolicy.OnStop failed for route '{RouteId}'", routeId); } } route.Status = RouteStatus.Stopped; _logger?.LogInformation("Route '{RouteId}' stopped.", routeId); await NotifyRouteStopped(routeId, ct).ConfigureAwait(false); } finally { _routeLock.Release(); } } // ── Lifecycle ── /// public async Task Start(CancellationToken ct = default) { await _routeLock.WaitAsync(ct).ConfigureAwait(false); try { if (_started) return; await NotifyContextStarting(ct).ConfigureAwait(false); await StartCore(ct).ConfigureAwait(false); await NotifyContextStarted(ct).ConfigureAwait(false); } finally { _routeLock.Release(); } } private async Task StartCore(CancellationToken ct) { var logger = GetService() ?? _logger; if (_builders.Count > 0) CompileRoutesFromBuilders(logger); if (OnBeforeRoutesStart is not null) await OnBeforeRoutesStart(_routes).ConfigureAwait(false); if (_builders.Count > 0) await InitializeRoutePolicies(logger, ct).ConfigureAwait(false); await StartEndpointsAndConsumers(logger, ct).ConfigureAwait(false); } /// /// The route configurations of a route, as Apache Camel assigns them. A route without /// .RouteConfigurationId(...) gets the nameless ones — the default. A route with ids gets the configurations /// whose id matches one of them (an exact id, a wildcard ending in *, or a regular expression) and none of the /// nameless. An exact id no configuration has is an error: a route left without the handlers it asked for would fail /// in production instead of at Start(). /// private static List RouteConfigurationsOf(RouteDefinition definition, string routeId, List all) { if (definition.GetRouteConfigurationId() is not { } assigned) return all.Where(c => c.Id is null).ToList(); var patterns = assigned.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var pattern in patterns) { if (IsExactConfigurationId(pattern) && !all.Any(c => c.Id == pattern)) throw new InvalidOperationException( $"Route '{routeId}': route configuration '{pattern}' is not declared in the context. " + "Declare it in a RouteConfigurationBuilder (or a of the markup) and add it before Start()."); } return all.Where(c => c.Id is { } id && patterns.Any(p => MatchesConfigurationId(id, p))).ToList(); } /// An id made of letters, digits, _, - and . only: a name, not a wildcard or a regular expression. private static bool IsExactConfigurationId(string pattern) => pattern.All(c => char.IsLetterOrDigit(c) || c is '_' or '-' or '.'); /// Camel's pattern match: the exact id, a wildcard ending in *, or a regular expression over the whole id. private static bool MatchesConfigurationId(string id, string pattern) { if (string.Equals(id, pattern, StringComparison.Ordinal)) return true; if (pattern.EndsWith('*') && id.StartsWith(pattern[..^1], StringComparison.Ordinal)) return true; try { return System.Text.RegularExpressions.Regex.IsMatch(id, $"^(?:{pattern})$", System.Text.RegularExpressions.RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1)); } catch (ArgumentException) { return false; // not a regular expression: it was a name, and it did not match } } /// /// Invokes all registered builders, validates definitions, compiles routes, /// and swaps the result into . /// private void CompileRoutesFromBuilders(ILogger? logger) { var compiledRoutes = new List(); logger?.LogInformation("Compiling {Count} route builder(s)...", _builders.Count); // 1. Invoke the builders to collect definitions. AdviceWith may already have built (and // rewritten) them before Start(); re-running Configure() would discard the advice. A builder // added after that advice has never been built and still must be — otherwise its routes // would vanish without a word. foreach (var builder in _builders) { if (!DefinitionsPrebuilt || !builder.IsBuilt) builder.InternalBuild(this); } // 2. Validate route registrations — fail fast before any compilation var usedFromUris = new Dictionary(StringComparer.OrdinalIgnoreCase); var usedRouteIds = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var builder in _builders) { foreach (var definition in builder.Definitions) { var fromUri = definition.GetFromUri() ?? throw new InvalidOperationException( $"Route '{definition.GetRouteId() ?? "(unnamed)"}' has no From() endpoint."); // Expand {{key}} placeholders before the URI is parsed — dedup/identity keys, the route id // and the consumer endpoint (below) must all see the same resolved value. fromUri = ResolvePlaceholders(fromUri); // A ${...} in a consumer URI has no message to resolve against; before 4.0 it was silently // kept as text (or resolved against nothing). Fail at Start(), the same way a malformed // condition does — the silent variant is the class of defect already removed elsewhere. if (fromUri.Contains("${", StringComparison.Ordinal)) throw new InvalidOperationException( $"Route '{definition.GetRouteId() ?? "(unnamed)"}': the consumer URI '{EndpointUri.Sanitize(fromUri)}' contains a ${{...}} " + "placeholder, but a consumer has no message to resolve it against. Use {{key}} configuration placeholders or a constant."); var parsedFrom = EndpointUriParser.Parse(fromUri); var normalizedFrom = parsedFrom.NormalizedKey; // Unnamed routes are named after their endpoint: scheme, path and a deterministic // UUID of the URI (RouteIdFactory) — no separator a dashboard label chokes on and no // query string a secret could ride in. Endpoint dedup below still keys on the raw // normalizedFrom, so identity is unaffected. var routeId = definition.GetRouteId() ?? RouteIdFactory.ForEndpoint(parsedFrom); if (!usedRouteIds.Add(routeId)) throw new InvalidOperationException( $"Duplicate route ID '{routeId}'. Each route must have a unique ID within a context."); if (usedFromUris.TryGetValue(normalizedFrom, out var existingRouteId)) throw new InvalidOperationException( $"Route '{routeId}' has the same From URI '{EndpointUri.Sanitize(fromUri)}' as route '{existingRouteId}'. " + $"Two consumers on the same endpoint within one context is not allowed."); usedFromUris[normalizedFrom] = routeId; } } // 3. Builder-level OnException, Intercept* and OnCompletion apply to the routes of their own builder only // (Apache Camel's RouteBuilder scope); they are attached per route below. Here only what is said once. foreach (var builder in _builders) { // A builder with handlers and no route of its own: the handlers apply to nothing. It is what a class (or a // markup file) of shared handlers becomes when it is not a route configuration — said at every start, // because nothing else would: the routes of the other builders simply run without those handlers. if (builder.Definitions.Count == 0 && (builder.ExceptionDefinitions.Count > 0 || builder.Intercepts.Count > 0 || builder.OnCompletions.Count > 0)) { logger?.LogWarning( "{Builder} declares no routes, so its OnException / Intercept / OnCompletion apply to nothing: a builder's " + "declarations reach the routes of that builder only. For handlers shared by the routes of other builders " + "declare a route configuration — RouteConfiguration().OnException<...>() in a RouteConfigurationBuilder, " + " in markup.", builder.SourceName); } foreach (var exDef in builder.ExceptionDefinitions) { foreach (var exType in exDef.ExceptionTypes) { logger?.LogInformation( "Registered builder exception handler for {ExceptionType} ({Builder})", exType.Name, builder.SourceName); // A handler on an OperationCanceledException can never fire — a genuine cancellation is // never handled and a timeout arrives as TimeoutException. Said once at load. if (Validation.RouteDefinitionValidator.CancellationHandlerWarning(exType) is { } cancellationWarning) logger?.LogWarning("OnException: {Warning}", cancellationWarning); } } } // 3a. Route configurations of every builder, in the order they were added: unlike a builder's own handlers // they reach the routes of other builders. An id is unique within the context. var routeConfigurations = _builders.SelectMany(b => b.RouteConfigurations).ToList(); var configurationIds = new HashSet(StringComparer.Ordinal); foreach (var configuration in routeConfigurations) { if (configuration.Id is { } configurationId && !configurationIds.Add(configurationId)) throw new InvalidOperationException( $"Duplicate route configuration id '{configurationId}'. A route configuration id is unique within a context."); foreach (var exType in configuration.ExceptionDefinitions.SelectMany(d => d.ExceptionTypes)) { logger?.LogInformation( "Registered route configuration exception handler for {ExceptionType} ({Configuration})", exType.Name, configuration.Id ?? "default"); if (Validation.RouteDefinitionValidator.CancellationHandlerWarning(exType) is { } cancellationWarning) logger?.LogWarning("OnException: {Warning}", cancellationWarning); } } // 4. Validate route definitions before compilation foreach (var builder in _builders) { foreach (var definition in builder.Definitions) { var warnings = Validation.RouteDefinitionValidator.Validate(definition); foreach (var warning in warnings) logger?.LogWarning("Route '{RouteId}': {Warning}", definition.GetRouteId() ?? "", warning); } } // 5. Compile each route definition _checkpoints.Clear(); // rebuilt from scratch on every (re)compile _errorScopes.Clear(); foreach (var builder in _builders) { foreach (var definition in builder.Definitions) { var fromUri = ResolvePlaceholders(definition.GetFromUri()!); // Unnamed routes are named after their endpoint (see RouteIdFactory). Kept in sync // with the validation loop above; endpoint identity/dedup still keys on the raw // normalizedFrom. var routeId = definition.GetRouteId() ?? RouteIdFactory.ForEndpoint(EndpointUriParser.Parse(fromUri)); PipelineProcessor pipeline; // The route's error scope: its own OnException (added while its body compiles), its builder's — that // builder's only —, those of its route configurations, and the context layer. var errorScope = new RouteErrorScope(this, routeId, builder.ExceptionDefinitions, RouteConfigurationsOf(definition, routeId, routeConfigurations) .SelectMany(c => c.ExceptionDefinitions).ToList(), _loggerFactory?.CreateLogger()); _errorScopes[routeId] = errorScope; _compilingErrorScope = errorScope; _compilingRouteId = routeId; // so nested ReplayableDefinition registers under this route // Route-level .MessageHistory() overrides the global option; each route restarts node numbering. _compilingMessageHistory = definition.GetMessageHistory() ?? _options.EnableMessageHistory; _compilingNodeCounter = 0; // Intercepts of this route: its builder's plus the route's own; CompileNode decorates every step with them. _compilingIntercepts = builder.Intercepts.Concat(definition.GetIntercepts()).ToList(); _interceptBodies.Clear(); List completionHandlers = []; _compilingStaticEndpoints = []; _compilingSkippedStaticEndpoints = new HashSet(StringComparer.Ordinal); try { var inner = definition.CreateProcessor(this); inner = ApplyInterceptFrom(inner, fromUri); pipeline = inner as PipelineProcessor ?? new PipelineProcessor(); if (inner is not PipelineProcessor) pipeline.Add(inner); // OnCompletion bodies compile here, inside the route's compile frame (route id for // checkpoints, message history), detached from its intercepts; they are attached // further down, outside every error handler. completionHandlers = builder.OnCompletions.Concat(definition.GetOnCompletions()) .Select(c => new CompletionHandler(CompileDetached(c.Outputs), c.Mode, c.Condition, c.BeforeConsumer, c.IsParallelProcessing ? new DetachedExecutor(c.ExecutorServiceName ?? "default", GetThreadPoolProfile(c.ExecutorServiceName), "onCompletion", routeId, _loggerFactory?.CreateLogger()) : null)) .ToList(); // The static targets' endpoints, now: a bad URI fails here like any compile error, not on the // first message. Only the endpoint — its producer is made when a message needs it. A target on a // component without a producer side (timer, imap, ...) fails here too: it never works, and a branch // taken rarely is the worst place to learn it; the XML loader refuses the same step at load. foreach (var staticUri in _compilingStaticEndpoints) if (!_compilingSkippedStaticEndpoints.Contains(ResolvePlaceholders(staticUri))) EndpointSides.Refuse(GetEndpoint(staticUri), EndpointRole.Producer); } catch (Exception ex) when (!_options.ThrowOnCompilationError) { logger?.LogError(ex, "Failed to compile route '{RouteId}'. Skipping.", routeId); // A skipped route keeps no error scope. _errorScopes.TryRemove(routeId, out _); continue; } finally { _compilingErrorScope = null; _compilingStaticEndpoints = null; _compilingSkippedStaticEndpoints = null; _compilingRouteId = null; _compilingMessageHistory = false; _compilingIntercepts = []; _interceptBodies.Clear(); } // Wrap with routeId stamp var wrappedPipeline = new PipelineProcessor(); wrappedPipeline.Add(new DelegateProcessor(exchange => exchange.RouteId = routeId)); // RouteEngineOptions.StreamCaching.Enabled, Camel's context-wide streamCaching: every route caches a // stream body before its first step, so any step can read it again. if (_options.StreamCaching.Enabled) wrappedPipeline.Add(new StreamCachingTransformer(Extensions.RouteContextExtensions.GetStreamCacheOptions(this))); wrappedPipeline.AddRange(pipeline.Processors); // Resolve route policy: explicit definition wins, then a registry name, // then the factory chain. IRoutePolicy? routePolicy = definition.GetRoutePolicy(); if (routePolicy is null && definition.GetRoutePolicyName() is { } policyName) { routePolicy = GetFromRegistry(policyName) ?? throw new InvalidOperationException( $"Route '{routeId}': route policy '{policyName}' is not in the context registry. " + "Register it with AddToRegistry before Start()."); } IRoutePolicyFactory? winningFactory = null; var explicitPolicy = routePolicy is not null; if (routePolicy is null) { foreach (var factory in _policyFactories) { routePolicy = factory.CreateRoutePolicy(this, routeId, definition); if (routePolicy is not null) { winningFactory = factory; break; } } } // Build the policy descriptor (one source of truth for diagnostics + API) var requestedCluster = definition.GetCluster(); RoutePolicyDescriptor descriptor; if (explicitPolicy) { descriptor = new RoutePolicyDescriptor( requestedCluster, "Custom", routePolicy!.GetType().FullName, "Explicit RoutePolicy attached on the route definition"); } else if (routePolicy is not null) { descriptor = new RoutePolicyDescriptor( requestedCluster, "ClusterLeader", winningFactory!.GetType().FullName, $"Policy supplied by {winningFactory.GetType().Name}"); } else { // A registered factory may decline a route (IRoutePolicyFactory returns null) and say why itself. var reason = !requestedCluster ? "No policy attached — runs on all nodes" : _policyFactories.Count == 0 ? "Route requested .Cluster(true) but no IRoutePolicyFactory is registered — running on all nodes" : "Route requested .Cluster(true) but the registered IRoutePolicyFactory declined it — running on all nodes"; descriptor = new RoutePolicyDescriptor(requestedCluster, "AllNodes", null, reason); } // Startup safety: warn when .Cluster(true) is requested without any factory if (_options.StartupChecks && requestedCluster && routePolicy is null && _policyFactories.Count == 0) { logger?.LogWarning( "Route '{RouteId}' declares .Cluster(true) but no IRoutePolicyFactory is registered. " + "The route will execute on every node. Register a clustered route policy factory " + "(e.g. Tsak's ClusteredRoutePolicyFactory) or set RouteEngineOptions.StartupChecks=false to silence.", routeId); } // Wrap with RoutePolicyProcessor for per-exchange hooks if (routePolicy is not null) { var rpProcessor = new RoutePolicyProcessor(wrappedPipeline, routePolicy, this); wrappedPipeline = new PipelineProcessor(); wrappedPipeline.Add(rpProcessor); } // Apply per-exchange processing timeout IProcessor finalProcessor = wrappedPipeline; var routeTimeout = definition.GetProcessingTimeout() ?? _options.DefaultProcessingTimeout; if (routeTimeout != Timeout.InfiniteTimeSpan) finalProcessor = new TimeoutProcessor(finalProcessor, routeTimeout, routeId, this, _loggerFactory?.CreateLogger()); // The rest of the route's error scope, around the route policy and the timeout: the OnException blocks // of this route's builder (that builder's only — Camel's RouteBuilder scope), then the context's error // handling for a failure no OnException took. Also completes the detached bodies of the route. finalProcessor = errorScope.WrapOuter(finalProcessor); // Telemetry / metrics: outside every error handler, as the statistics below, so a redelivered exchange is // one span and one measurement with its final outcome — not one per attempt. Route-level .Tracing() // overrides the global option, so a service route (a health check, a metric summary) opens no span. var routeTracing = definition.GetTracing() ?? _options.EnableTelemetry; if (routeTracing) finalProcessor = new InstrumentedProcessor(finalProcessor, $"route:{routeId}"); if (_options.EnableMetrics) { var endpointScheme = EndpointUriParser.Parse(fromUri).Scheme; finalProcessor = new MeteredProcessor(finalProcessor, routeId, EndpointUri.Sanitize(fromUri), endpointScheme); } // OnCompletion blocks: outside every error handler, so "failure" is the escaping exception // and a handled error is a completion. Their bodies compile detached (no intercepts). if (completionHandlers.Count > 0) { var completions = new OnCompletionProcessor(finalProcessor, completionHandlers, routeId, _loggerFactory?.CreateLogger()); // Its pools drain when the consumers have stopped, as a WireTap's do. if (completionHandlers.Any(h => h.Pool is not null)) _disposableProcessors.Add(completions); finalProcessor = completions; } // The exchange's unit of work: outside every error handler, inside the statistics, inflight tracking and // exchange events, so a completion (an idempotent key confirmed or removed) has run before the consumer // settles the message and before a listener hears the exchange finished. finalProcessor = new UnitOfWorkProcessor(finalProcessor, _loggerFactory?.CreateLogger()); // Create consumer on the From endpoint var endpoint = GetEndpoint(fromUri); finalProcessor = new StatisticsProcessor(finalProcessor, endpoint); // Outermost wrapper: inflight tracking finalProcessor = new InflightTrackingProcessor(finalProcessor, _inflightRepository, routeId, EndpointUri.Sanitize(fromUri)); // Exchange-level lifecycle events (received / completed / failed) for listeners such as // NotifyBuilder — outside every error handler so the reported outcome is the final one. finalProcessor = new ExchangeEventsProcessor(finalProcessor, this, routeId); // Outermost of all: IExchange.Context points at the context whose route is // executing, for exactly as long as it is executing — so even lifecycle listeners // see a stamped exchange, and the caller gets its own view back afterwards. // Beside it, the inbound span of the transport, for .SpanTag(..., SpanTarget.Inbound): on entry it is the // ambient activity, opened by the consumer around this pipeline. No inbound span opens with telemetry off. if (_options.EnableTelemetry) finalProcessor = new InboundSpanProcessor(finalProcessor); finalProcessor = new ContextStampProcessor(finalProcessor, this); var consumer = endpoint.CreateConsumerOnItsSide(finalProcessor); AddConsumer(consumer); compiledRoutes.Add(new CompiledRoute(routeId, EndpointUri.Sanitize(fromUri), definition, wrappedPipeline, consumer, endpoint) { AutoStart = definition.GetAutoStart(), Policy = routePolicy, PolicyDescriptor = descriptor }); logger?.LogInformation("Compiled route '{RouteId}': {FromUri}", routeId, EndpointUri.ForLog(fromUri, logger)); } } // All routes compiled successfully — swap in atomically _routes.Clear(); _routes.AddRange(compiledRoutes); } /// /// Calls on each route that has a policy. /// Must run after so persisted suspended state /// is already applied to . /// private async Task InitializeRoutePolicies(ILogger? logger, CancellationToken ct) { foreach (var route in _routes) { if (route.Policy is { } policy) { try { await policy.OnInit(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { logger?.LogError(ex, "RoutePolicy.OnInit failed for route '{RouteId}'", route.RouteId); route.Status = RouteStatus.Errored; } } } } /// /// Starts endpoints, then consumers (in-process first, external second), /// skipping routes with = false. /// Marks each route's accordingly. /// private async Task StartEndpointsAndConsumers(ILogger? logger, CancellationToken ct) { var failedEndpoints = new List<(string Uri, Exception Error)>(); var startedCount = 0; // Start endpoints foreach (var (key, endpoint) in _endpoints) { try { await endpoint.Start(ct).ConfigureAwait(false); startedCount++; logger?.LogInformation("Endpoint {Uri} started successfully", EndpointUri.ForLog(key, logger)); } catch (Exception ex) { failedEndpoints.Add((key, ex)); logger?.LogError(ex, "Failed to start endpoint {Uri}. Context will continue with remaining endpoints.", EndpointUri.Sanitize(key)); } } // Start in-process consumers first (Direct, Seda) so their processors are registered // before external consumers (Kafka, Timer, etc.) begin sending messages. // Skip consumers for routes with AutoStart=false. var skippedConsumers = new HashSet( _routes.Where(r => !r.AutoStart).Select(r => r.Consumer)); var inProcess = _consumers.Where(c => IsInProcessConsumer(c) && !skippedConsumers.Contains(c)); var external = _consumers.Where(c => !IsInProcessConsumer(c) && !skippedConsumers.Contains(c)); var failedConsumers = new HashSet(); foreach (var consumer in inProcess) { try { await consumer.Start(ct).ConfigureAwait(false); } catch (Exception ex) { failedConsumers.Add(consumer); logger?.LogError(ex, "Failed to start in-process consumer. Context will continue with remaining consumers."); } } foreach (var consumer in external) { try { await consumer.Start(ct).ConfigureAwait(false); } catch (Exception ex) { failedConsumers.Add(consumer); logger?.LogError(ex, "Failed to start consumer. Context will continue with remaining consumers."); } } _started = true; var retryStart = _options.ConsumerStartRetry.Enabled; var toRetry = new List(); // Mark compiled routes based on their AutoStart flag foreach (var route in _routes) { if (failedConsumers.Contains(route.Consumer)) { route.Status = RouteStatus.Errored; logger?.LogWarning("Route '{RouteId}' marked as Errored due to consumer start failure", route.RouteId); await NotifyRouteErrored(route.RouteId, new InvalidOperationException($"Consumer failed to start for route '{route.RouteId}'"), ct) .ConfigureAwait(false); if (retryStart) toRetry.Add(route); } else if (route.AutoStart) { if (route.Policy is { } startPolicy) { try { await startPolicy.OnStart(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { route.Status = RouteStatus.Errored; logger?.LogError(ex, "RoutePolicy.OnStart failed for route '{RouteId}'", route.RouteId); // The consumer started above; a route reported Errored must not go on taking messages. try { await route.Consumer.Stop(ct).ConfigureAwait(false); } catch (Exception stopEx) { logger?.LogWarning(stopEx, "Stopping the consumer of route '{RouteId}' failed", route.RouteId); } await NotifyRouteErrored(route.RouteId, ex, ct).ConfigureAwait(false); continue; } } route.Status = RouteStatus.Started; await NotifyRouteStarted(route.RouteId, ct).ConfigureAwait(false); } else { route.Status = RouteStatus.Stopped; logger?.LogInformation("Route '{RouteId}' has AutoStart=false, remaining stopped", route.RouteId); } } if (failedEndpoints.Count > 0) { var failedUris = string.Join(", ", failedEndpoints.Select(f => EndpointUri.Sanitize(f.Uri))); logger?.LogError( "Context '{ContextId}' started in DEGRADED mode: success={SuccessCount}, FAILED={FailedCount}. " + "Non-operational endpoints: {FailedEndpoints}. IMMEDIATE ATTENTION REQUIRED!", ContextId, startedCount, failedEndpoints.Count, failedUris); } else { var errored = _routes.Where(r => r.Status == RouteStatus.Errored).Select(r => r.RouteId).ToList(); if (errored.Count > 0) logger?.LogWarning( "Context '{ContextId}' started with {ErroredCount} of {RouteCount} route(s) Errored: {ErroredRoutes}. {Retry}", ContextId, errored.Count, _routes.Count, string.Join(", ", errored), toRetry.Count > 0 ? $"The consumers of {toRetry.Count} of them are started again in the background." : "They stay Errored until started by hand."); else logger?.LogInformation("Context '{ContextId}' started successfully: all {Count} endpoints operational", ContextId, startedCount); } StartConsumerRetries(toRetry, logger); } /// /// Starts again, in the background, the consumers that failed to start with the context /// (). Each route waits on its own back-off; it leaves the /// loop when its consumer starts, when the retries run out, when the context stops, or when the route was started, /// stopped or removed by hand meanwhile. /// private void StartConsumerRetries(List routes, ILogger? logger) { if (routes.Count == 0) return; _startRetryCts?.Dispose(); var cts = _startRetryCts = new CancellationTokenSource(); _startRetryRoutes.Clear(); foreach (var route in routes) { _startRetryRoutes[route] = 0; _ = RetryConsumerStartAsync(route, logger, cts.Token); } } private async Task RetryConsumerStartAsync(CompiledRoute route, ILogger? logger, CancellationToken stopToken) { try { await RetryConsumerStartLoopAsync(route, logger, stopToken).ConfigureAwait(false); } catch (Exception ex) { logger?.LogError(ex, "Route '{RouteId}': consumer start retry ended by an error", route.RouteId); } finally { _startRetryRoutes.TryRemove(route, out _); } } private async Task RetryConsumerStartLoopAsync(CompiledRoute route, ILogger? logger, CancellationToken stopToken) { var retry = _options.ConsumerStartRetry; var schedule = retry.Schedule; var delay = schedule.First; for (var attempt = 1; ; attempt++) { try { await Task.Delay(delay, stopToken).ConfigureAwait(false); await _routeLock.WaitAsync(stopToken).ConfigureAwait(false); } catch (OperationCanceledException) { return; } try { // Started, stopped, resumed or removed by hand meanwhile: no longer the retry's to start. if (route.Status != RouteStatus.Errored || !_startRetryRoutes.ContainsKey(route) || !_routes.Contains(route)) return; // The policy first, as StartRoute does: a policy that refuses leaves no consumer running under a // route reported Errored. if (route.Policy is { } policy) { try { await policy.OnStart(this, route, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { logger?.LogError(ex, "RoutePolicy.OnStart failed for route '{RouteId}'; the route stays Errored", route.RouteId); await NotifyRouteErrored(route.RouteId, ex, CancellationToken.None).ConfigureAwait(false); return; } } try { // Not the stop token: a consumer ties its processing to the token it starts with, and the context // stops a started consumer by Stop, draining what it holds. await route.Consumer.Start(CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { if (retry.MaxAttempts > 0 && attempt >= retry.MaxAttempts) { logger?.LogError(ex, "Route '{RouteId}': consumer start retry {Attempt} of {MaxAttempts} failed, no retries left; " + "the route stays Errored", route.RouteId, attempt, retry.MaxAttempts); return; } delay = schedule.Next(delay); logger?.LogWarning( "Route '{RouteId}': consumer start retry {Attempt} failed: {Error}. Next retry in {Delay:F0}s", route.RouteId, attempt, ex.Message, delay.TotalSeconds); continue; } route.Status = RouteStatus.Started; logger?.LogInformation("Route '{RouteId}' started on consumer start retry {Attempt}", route.RouteId, attempt); await NotifyRouteStarted(route.RouteId, CancellationToken.None).ConfigureAwait(false); return; } finally { _routeLock.Release(); } } } /// public async Task Stop(CancellationToken ct = default) { // Before the lock: a start retry waiting for it leaves at once, one holding it finishes and is stopped below. _startRetryCts?.Cancel(); await _routeLock.WaitAsync(ct).ConfigureAwait(false); try { if (!_started) return; await NotifyContextStopping(ct).ConfigureAwait(false); // Mark all active routes as Suspending → Suspended foreach (var route in _routes) { if (route.Status == RouteStatus.Started) { route.Status = RouteStatus.Suspending; await NotifyRouteSuspending(route.RouteId, ct).ConfigureAwait(false); if (route.Policy is { } suspendPolicy) { try { await suspendPolicy.OnSuspend(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RoutePolicy.OnSuspend failed for route '{RouteId}'", route.RouteId); } } route.Status = RouteStatus.Suspended; } } // Apply ShutdownTimeout — gives consumers a bounded window to drain in-flight work. using var timeoutCts = new CancellationTokenSource(_options.ShutdownTimeout); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token); var stopCt = linked.Token; // Shutdown mirrors Start order (in-process first, external last) in reverse. // Dependencies: external → To("kafka:") needs producer alive // external → To("direct:") needs Direct alive // seda drain → To("direct:") needs Direct alive // seda drain → To("kafka:") needs producer alive — NO: producers flush after externals var external = _consumers.Where(c => !IsInProcessConsumer(c)).ToList(); var queued = _consumers.Where(IsQueueConsumer).ToList(); var direct = _consumers.Where(IsDirectConsumer).ToList(); // Phase 1: Stop external consumers in parallel (Kafka, Timer, Quartz, etc.) // Each Stop() internally does: stop-accepting → drain-inflight → cleanup. // During drain, producers and Direct/Seda are still alive for .To() calls. await StopAllAsync(external, c => c.Stop(stopCt), c => c.GetType().Name, "Consumer", timeoutCts, ct) .ConfigureAwait(false); // Phase 1b: processors holding exchanges of their own (open aggregation groups) settle them: nothing more // arrives from outside, and the producers are still alive for what a completion sends on. foreach (var holder in _disposableProcessors.OfType().ToArray()) { try { await holder.OnConsumersStoppedAsync(stopCt).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { _logger?.LogError(ex, "Settling {Processor} on stop failed", holder.GetType().Name); } } // Phase 2: Stop producers in parallel (flush pending sends, close connections). // No more inflight exchanges from external consumers, safe to tear down. IProducer[] producers; lock (_producersLock) producers = [.. _producers]; await StopAllAsync(producers, p => p.Stop(stopCt), p => p.GetType().Name, "Producer", timeoutCts, ct) .ConfigureAwait(false); // Phase 3: Drain Seda/Vm queues in parallel. // External consumers may have enqueued work via .To("seda://"). // During drain, Direct processors are still registered. await StopAllAsync(queued, c => c.Stop(stopCt), c => c.GetType().Name, "Consumer", timeoutCts, ct) .ConfigureAwait(false); // Phase 4: Unregister Direct/DirectVm processors (instant, no drain). // All senders are stopped — no one will call these anymore. await StopAllAsync(direct, c => c.Stop(stopCt), c => c.GetType().Name, "Consumer", timeoutCts, ct) .ConfigureAwait(false); foreach (var endpoint in _endpoints.Values) await endpoint.Stop(ct).ConfigureAwait(false); foreach (var route in _routes) { if (route.Policy is { } stopPolicy) { try { await stopPolicy.OnStop(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RoutePolicy.OnStop failed for route '{RouteId}'", route.RouteId); } } route.Status = RouteStatus.Stopped; await NotifyRouteStopped(route.RouteId, ct).ConfigureAwait(false); } // Notify policies that routes are being removed foreach (var route in _routes) { if (route.Policy is { } policy) { try { await policy.OnRemove(this, route, ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RoutePolicy.OnRemove failed for route '{RouteId}'", route.RouteId); } } } // Clear all runtime resources including compiled routes. // Routes are recompiled from _builders on next Start(). ClearRuntimeState(); _routes.Clear(); _started = false; await NotifyContextStopped(ct).ConfigureAwait(false); } finally { _routeLock.Release(); } } /// Registers a consumer to be started/stopped with the context. /// Consumer instance. internal void AddConsumer(IConsumer consumer) => _consumers.Add(consumer); /// Adds a compiled route directly (for testing). internal void AddRoute(CompiledRoute route) => _routes.Add(route); /// Tracks a producer so it is stopped during context shutdown. /// Producer instance. internal void TrackProducer(IProducer producer) { lock (_producersLock) _producers.Add(producer); } /// /// Takes a producer off the shutdown list, for an owner that stops it itself (a producer template). false /// when the producer is not on it: the context has stopped it already, or never tracked it. /// /// Producer instance. internal bool UntrackProducer(IProducer producer) { lock (_producersLock) return _producers.Remove(producer); } /// public IReadOnlyList GetEndpoints() => _endpoints.Values.ToList(); private readonly ConcurrentDictionary _threadPoolProfiles = new(StringComparer.Ordinal); /// public void AddThreadPoolProfile(string name, ThreadPoolProfile profile) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(profile); profile.Validate(name); var added = _threadPoolProfiles.GetOrAdd(name, _ => profile.Copy()); if (!added.SameAs(profile)) throw new InvalidOperationException( $"Thread pool profile '{name}' is already registered with {added}; it cannot be registered again with " + $"{profile}. Two modules that need different bounds use two names."); } /// public ThreadPoolProfile GetThreadPoolProfile(string? name) { if (name is null) return _options.DefaultThreadPoolProfile; if (_threadPoolProfiles.TryGetValue(name, out var profile)) return profile; var known = _threadPoolProfiles.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray(); throw new InvalidOperationException( $"Unknown thread pool profile '{name}' (executorService). " + (known.Length == 0 ? "No named profile is registered: add it to RouteEngineOptions.ThreadPoolProfiles or with AddThreadPoolProfile." : $"Registered: {string.Join(", ", known)}.")); } /// In-process consumers (Direct, Seda, DirectVm, Vm) that must start first and stop last. private static bool IsInProcessConsumer(IConsumer consumer) => consumer is Components.DirectConsumer or Components.SedaConsumer or Components.DirectVmConsumer or Components.VmConsumer; /// Queue-based in-process consumers (Seda, Vm) that may accumulate work from external consumers. private static bool IsQueueConsumer(IConsumer consumer) => consumer is Components.SedaConsumer or Components.VmConsumer; /// Synchronous in-process consumers (Direct, DirectVm) that only unregister a processor. private static bool IsDirectConsumer(IConsumer consumer) => consumer is Components.DirectConsumer or Components.DirectVmConsumer; /// /// Stops all items in parallel. Each item runs its own stop logic concurrently; /// timeout exceptions are caught per-item without aborting siblings. /// private async Task StopAllAsync( IEnumerable items, Func stopAction, Func nameSelector, string kind, CancellationTokenSource timeoutCts, CancellationToken outerCt) { var tasks = items.Select(async item => { try { await stopAction(item).ConfigureAwait(false); } catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !outerCt.IsCancellationRequested) { _logger?.LogWarning( "{Kind} {Name} stop timed out after {Timeout}s, forcing shutdown", kind, nameSelector(item), _options.ShutdownTimeout.TotalSeconds); } catch (Exception ex) { _logger?.LogWarning(ex, "{Kind} {Name} stop failed, continuing shutdown", kind, nameSelector(item)); } }); await Task.WhenAll(tasks).ConfigureAwait(false); } // ── IDisposable / IAsyncDisposable ── /// public async ValueTask DisposeAsync() { if (_started) { await Stop(CancellationToken.None).ConfigureAwait(false); } await DisposeProcessorsAsync().ConfigureAwait(false); await DisposeComponentsAsync().ConfigureAwait(false); _connectionEvents?.Complete(); ClearAll(); GC.SuppressFinalize(this); } /// public void Dispose() { if (_started) { Stop(CancellationToken.None).GetAwaiter().GetResult(); } DisposeProcessorsAsync().AsTask().GetAwaiter().GetResult(); DisposeComponentsAsync().AsTask().GetAwaiter().GetResult(); _connectionEvents?.Complete(); ClearAll(); GC.SuppressFinalize(this); } /// /// Releases processors that own background resources (aggregation/resequencing timers), /// registered by . Runs before component disposal — a processor may /// still hold component-provided resources. Failures are logged and do not stop the sweep. /// private async ValueTask DisposeProcessorsAsync() { foreach (var processor in _disposableProcessors) { try { await processor.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "Error disposing processor {Processor}", processor.GetType().Name); } } _disposableProcessors.Clear(); } /// /// Releases component-owned resources (connection pools, broker sessions, etc.). /// Each component's is awaited; failures are logged /// but do not prevent disposal of the remaining components. /// private async ValueTask DisposeComponentsAsync() { // Distinct: a component may be registered under both its primary scheme // and one or more aliases — the same instance must only be disposed once. var seen = new HashSet(ReferenceEqualityComparer.Instance); foreach (var component in _components.Values) { if (!seen.Add(component)) continue; if (component is not IAsyncDisposable disposable) continue; try { await disposable.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "Error disposing component {Scheme}", component.Scheme); } } } private void ClearRuntimeState() { _consumers.Clear(); _endpoints.Clear(); lock (_producersLock) _producers.Clear(); // Only what the compiler derived; the handlers the user registered are configuration, like the components, // and a stopped context that is started again must still have them. _errorScopes.Clear(); } private void ClearAll() { ClearRuntimeState(); _globalExceptionHandlers.Clear(); _localExceptionHandlers.Clear(); _routes.Clear(); _components.Clear(); _properties.Clear(); _registry.Clear(); _services.Clear(); _builders.Clear(); _discoveredBuilderTypes.Clear(); } // ── Private helpers ── /// /// Compiles a single child definition into its runtime processor. The one seam every scope's body /// compilation flows through (via ), so per-node compile-time /// decoration has exactly one place to live. When message history is enabled for the route being /// compiled, the node is wrapped in a . /// internal IProcessor CompileNode(IProcessorDefinition definition) { var inner = definition.CreateProcessor(this); if (inner is null) return inner; // Processors owning background resources (the aggregator's and // resequencer's timers) declare IAsyncDisposable, but nothing ever disposed them — the // resequencer's DisposeAsync was dead code and the aggregator's periodic scan timer // outlived the context. This seam is the one place every compiled node flows through, // so ownership is registered here and released when the context is disposed (not on // Stop(): a stopped context may be started again and reuses its compiled processors). if (inner is IAsyncDisposable disposable) _disposableProcessors.Add(disposable); inner = ApplyIntercepts(definition, inner); if (!_compilingMessageHistory) return inner; // The counter is consumed from the TYPE-derived label regardless of StepId/StepDescription, // so naming or describing one node never shifts the generated ids of its neighbours. var typeLabel = MessageHistoryLabel(definition); var sequence = ++_compilingNodeCounter; var step = definition as ProcessorDefinition; var label = step?.StepDescription ?? typeLabel; var nodeId = step?.StepId ?? typeLabel + sequence; return new MessageHistoryProcessor(inner, _compilingRouteId ?? "route", nodeId, label); } // ── Intercepts (phase 07): decorators applied per node at compile time ────────────── private IReadOnlyList _compilingIntercepts = []; private readonly Dictionary _interceptBodies = new(ReferenceEqualityComparer.Instance); private int _detachedCompileDepth; /// Wraps a compiled step with the route's intercepts: send-interception innermost, then every-step interception. private IProcessor ApplyIntercepts(IProcessorDefinition definition, IProcessor inner) { if (_compilingIntercepts.Count == 0 || _detachedCompileDepth > 0) return inner; // A static To may carry {{key}} configuration placeholders: the mask (and the published target) // must see the resolved URI, the one the endpoint is created from. A ToD's own resolver is shared // with its wrappers, so the target is evaluated once per message and the send goes where the // wrapper looked (a non-pure expression would otherwise publish one URI and send to another). var staticUri = definition is ToDefinition to ? ResolvePlaceholders(to.Uri) : null; var dynamicResolver = (inner as ToDynamicProcessor)?.Resolver; // Wrapped last is outermost and runs first, so the list is walked in reverse: the first // declared intercept (builder-level ones first) is the outermost and runs first. foreach (var intercept in _compilingIntercepts.Reverse()) { if (intercept.Kind != InterceptKind.SendToEndpoint) continue; Func? target = staticUri is not null ? _ => staticUri : dynamicResolver is not null ? dynamicResolver.ResolveUri : definition is ToDynamicDefinition toD ? toD.CreateResolver(this).ResolveUri : null; if (target is null) continue; if (staticUri is not null && !UriMask.IsMatch(intercept.UriPattern!, staticUri)) continue; if (staticUri is not null && intercept.SkipsOriginal) _compilingSkippedStaticEndpoints?.Add(staticUri); inner = new InterceptSendProcessor(InterceptBody(intercept), intercept.Condition, intercept.SkipsOriginal, intercept.UriPattern!, target, inner, dynamicResolver); } // Wrapped last is outermost and runs first, so the list is walked in reverse: the first // declared intercept (builder-level ones first) is the outermost and runs first. foreach (var intercept in _compilingIntercepts.Reverse()) { if (intercept.Kind != InterceptKind.EveryStep) continue; inner = new InterceptProcessor(InterceptBody(intercept), intercept.Condition, inner); } return inner; } /// Wraps the route pipeline with the InterceptFrom blocks whose mask matches the consumer URI. private IProcessor ApplyInterceptFrom(IProcessor pipeline, string fromUri) { // Wrapped last is outermost and runs first, so the list is walked in reverse: the first // declared intercept (builder-level ones first) is the outermost and runs first. foreach (var intercept in _compilingIntercepts.Reverse()) { if (intercept.Kind != InterceptKind.From) continue; if (intercept.UriPattern is not null && !UriMask.IsMatch(intercept.UriPattern, fromUri)) continue; pipeline = new InterceptProcessor(InterceptBody(intercept), intercept.Condition, pipeline); } return pipeline; } /// The intercept's own steps, compiled once per route and never intercepted themselves. private IProcessor InterceptBody(InterceptDefinition intercept) { if (!_interceptBodies.TryGetValue(intercept, out var body)) { body = CompileDetached(intercept.Outputs); _interceptBodies[intercept] = body; } return body; } /// Compiles steps outside the route's interception (intercept bodies, OnCompletion bodies). private IProcessor CompileDetached(IList outputs) { _detachedCompileDepth++; try { return NodePipeline.Body(this, outputs); } finally { _detachedCompileDepth--; } } /// Short node label from the definition type (e.g. ToDefinition → to). private static string MessageHistoryLabel(IProcessorDefinition definition) { var name = definition.GetType().Name; const string suffix = "Definition"; if (name.EndsWith(suffix, StringComparison.Ordinal)) name = name[..^suffix.Length]; return name.Length == 0 ? "node" : char.ToLowerInvariant(name[0]) + name[1..]; } private IEndpoint CreateEndpoint(EndpointUri parsed) { if (!_components.TryGetValue(parsed.Scheme, out var component)) throw new InvalidOperationException( $"No component registered for scheme '{parsed.Scheme}'. " + $"Available schemes: {string.Join(", ", _components.Keys)}"); var endpoint = component.CreateEndpoint(parsed); // Propagate scope factory for per-exchange DI scope support if (_serviceProvider != null) endpoint.ScopeFactory = _serviceProvider.GetService(); return endpoint; } /// /// Walks the exception type hierarchy to find the most specific matching handler. /// private static IProcessor? FindHandler( IDictionary handlers, Type exceptionType) { var searchType = exceptionType; while (searchType is not null && searchType != typeof(object)) { if (handlers.TryGetValue(searchType, out var processor)) return processor; searchType = searchType.BaseType; } return null; } /// /// The error scope a detached body compiled now is wrapped by (.Threads() for an in-only exchange): the /// scope of the route being compiled, or null outside a route, inside a handler body and inside a detached /// block (OnCompletion) — those run outside the route's error handling. /// internal RouteErrorScope? DetachedErrorScope => _detachedCompileDepth > 0 ? null : _compilingErrorScope; /// /// Compiles the steps of an OnException handler for . A detached body inside a /// handler is not wrapped by the route's scope again: a failure of the handler is not handled by the handler. /// internal IProcessor CompileHandlerBody(IList outputs) { var scope = _compilingErrorScope; _compilingErrorScope = null; try { return TryCatchDefinition.BuildPipeline(outputs, this); } finally { _compilingErrorScope = scope; } } // ── Lifecycle listener notifications ── // // Policy: // * OnContextStarting → fail-fast. This is the only pre-initialization hook where // listeners perform work required for correctness (seed DataProtection key-ring, // sync redb schemes, etc.). If it fails, the system is half-initialized and must // NOT accept traffic — so we aggregate errors across listeners and re-throw. // * All other phases (OnContextStarted/Stopping/Stopped, OnRouteStarted/Stopped/ // Suspending/Errored, OnExchangeTimedOut) → resilient. These are post-factum // observers. A broken observer must not: // - abort the rest of Start()/Stop() (would leak consumers/producers/connections // on teardown); // - propagate into caller code that only wanted to "notify about a started route". // Errors are logged at Error level (up from the old LogWarning — which hid real // bootstrap bugs silently) and swallowed so downstream listeners + cleanup continue. private async Task InvokeListenersAsync( string phase, Func invoker, bool failFast) { List? errors = null; foreach (var listener in Volatile.Read(ref _lifecycleListeners)) { try { await invoker(listener).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogError(ex, "Lifecycle listener {Listener} failed in {Phase}", listener.GetType().FullName, phase); if (failFast) (errors ??= new List()).Add(ex); } } if (errors is { Count: > 0 }) throw new AggregateException($"One or more lifecycle listeners failed in {phase}", errors); } // ── Connection events ── /// Connection events dropped because lifecycle listeners fell too far behind. internal long DroppedConnectionEvents => Volatile.Read(ref _connectionEvents)?.Dropped ?? 0; /// The background reader of the connection events, if one started; it ends when the context is disposed. internal Task? ConnectionEventReader => Volatile.Read(ref _connectionEvents)?.Reader; /// /// Queues a connection supervisor's event for the lifecycle listeners and returns at once; without listeners it is /// dropped here. The listeners get it from one background reader, in order, after the change. /// internal void PostConnectionEvent(ConnectionEvent change, IEndpoint endpoint) { if (Volatile.Read(ref _lifecycleListeners).Length == 0) return; var dispatcher = Volatile.Read(ref _connectionEvents); if (dispatcher is null) { Interlocked.CompareExchange(ref _connectionEvents, new ConnectionEventDispatcher(DeliverConnectionEvent, _logger), null); dispatcher = _connectionEvents!; } dispatcher.Post(change.RouteId is null ? change with { RouteId = ConsumerRouteOf(endpoint) } : change); } // The route whose consumer reads from the endpoint, when exactly one does; producers and shared endpoints get null. private string? ConsumerRouteOf(IEndpoint endpoint) { string? found = null; foreach (var route in _routes.ToArray()) { if (!ReferenceEquals(route.Consumer?.Endpoint, endpoint)) continue; if (found is not null) return null; found = route.RouteId; } return found; } private Task DeliverConnectionEvent(ConnectionEvent change) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnConnectionEvent), l => l.OnConnectionEvent(change, CancellationToken.None), failFast: false); // Sole fail-fast phase — bootstrap. private Task NotifyContextStarting(CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnContextStarting), l => l.OnContextStarting(this, ct), failFast: true); // All other phases are post-factum observers — resilient (log-and-continue). private Task NotifyContextStarted(CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnContextStarted), l => l.OnContextStarted(this, ct), failFast: false); private Task NotifyContextStopping(CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnContextStopping), l => l.OnContextStopping(this, ct), failFast: false); private Task NotifyContextStopped(CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnContextStopped), l => l.OnContextStopped(this, ct), failFast: false); private Task NotifyRouteStarted(string routeId, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnRouteStarted), l => l.OnRouteStarted(routeId, ct), failFast: false); private Task NotifyRouteStopped(string routeId, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnRouteStopped), l => l.OnRouteStopped(routeId, ct), failFast: false); private Task NotifyRouteSuspending(string routeId, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnRouteSuspending), l => l.OnRouteSuspending(routeId, ct), failFast: false); private Task NotifyRouteErrored(string routeId, Exception error, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnRouteErrored), l => l.OnRouteErrored(routeId, error, ct), failFast: false); internal Task NotifyExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnExchangeTimedOut), l => l.OnExchangeTimedOut(routeId, exchangeId, elapsed, ct), failFast: false); // Exchange-level events — published by ExchangeEventsProcessor (outermost route wrapper). // Hot path: callers skip the call entirely when HasLifecycleListeners is false. internal bool HasLifecycleListeners => Volatile.Read(ref _lifecycleListeners).Length > 0; internal Task NotifyExchangeReceived(string routeId, IExchange exchange, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnExchangeReceived), l => l.OnExchangeReceived(routeId, exchange, ct), failFast: false); internal Task NotifyExchangeCompleted(string routeId, IExchange exchange, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnExchangeCompleted), l => l.OnExchangeCompleted(routeId, exchange, ct), failFast: false); internal Task NotifyExchangeFailed(string routeId, IExchange exchange, Exception exception, CancellationToken ct) => InvokeListenersAsync(nameof(IRouteLifecycleListener.OnExchangeFailed), l => l.OnExchangeFailed(routeId, exchange, exception, ct), failFast: false); } /// /// Possible statuses for a compiled route. /// public enum RouteStatus { /// Route is stopped. Stopped, /// Route is started and processing exchanges. Started, /// Route is starting (consumer.Start() in progress). Starting, /// Route is suspending (Stop() called, notifying lifecycle listeners). Suspending, /// Route is suspended (consumer draining in-flight exchanges, no new messages accepted). Suspended, /// Route is stopping (drain timeout expired, force-cancelling). Stopping, /// Route startup or compilation failed. Errored } Path: redb-route/redb.Route/Core/RouteDecimal.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/Core/RouteDecimal.cs ---- using System.Globalization; namespace redb.Route.Core; /// /// A decimal from a binary floating-point value the way an expression, a JSONPath read or a converted body needs it: the /// decimal of the shortest text that reads back as the same double ("R"), so 19.95 stays 19.95 and round(2.567, 2) /// stays 2.57 on every runtime. The same technique as redb.Core's RedbDecimal, for the packages that do not /// reference redb.Core. /// /// /// The explicit conversion (decimal)double, which and /// use, rounds to 15 significant digits up to .NET 10 /// (12345678901234.56 became 12345678901234.6) and gives the exact binary value from .NET 11 on /// (19.95 became 19.949999999999999289457264240). Neither is the number that was written. /// public static class RouteDecimal { /// The decimal the double stands for. NaN, an infinity or a value outside the decimal range throws /// , as the explicit conversion does. public static decimal FromDouble(double value) { if (double.IsNaN(value) || double.IsInfinity(value)) throw new OverflowException($"{value.ToString(CultureInfo.InvariantCulture)} has no decimal value."); // The shortest text of a double is at most 24 characters ("-1.7976931348623157E+308"): formatted on the stack, // parsed from the span, no string per value. Span text = stackalloc char[32]; value.TryFormat(text, out var written, "R", CultureInfo.InvariantCulture); return decimal.Parse(text[..written], NumberStyles.Float, CultureInfo.InvariantCulture); } /// The decimal the float stands for (the shortest text of the float itself, not of its widening to double). public static decimal FromSingle(float value) { if (float.IsNaN(value) || float.IsInfinity(value)) throw new OverflowException($"{value.ToString(CultureInfo.InvariantCulture)} has no decimal value."); Span text = stackalloc char[32]; value.TryFormat(text, out var written, "R", CultureInfo.InvariantCulture); return decimal.Parse(text[..written], NumberStyles.Float, CultureInfo.InvariantCulture); } /// /// with a double or a float read through /// / . Anything else converts as before. /// public static decimal From(object value) => value switch { decimal d => d, double dbl => FromDouble(dbl), float f => FromSingle(f), _ => Convert.ToDecimal(value, CultureInfo.InvariantCulture), }; /// /// , except that a double or a float asked for as a /// decimal goes through / . Every other pair converts exactly as /// does with the same provider (null: the current /// culture, as ). /// public static object? ChangeType(object? value, Type targetType, IFormatProvider? provider = null) => targetType == typeof(decimal) && value is double or float ? From(value) : Convert.ChangeType(value, targetType, provider); } Path: redb-route/redb.Route/Core/RouteErrorScope.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/Core/RouteErrorScope.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Core; /// /// The error handling of one route, as in Apache Camel, from the inside out: /// /// the route's own OnException blocks (hoisted from its body); /// the OnException blocks the route shares with other routes: those of its builder — that builder's only /// (Camel's RouteBuilder scope) — then those of its route configurations, which are added after the builder's and so /// are used instead of a builder's handler of the same exception type; /// the context's error handling (): AddLocalExceptionHandler of the /// route, AddGlobalExceptionHandler, — for a failure no OnException /// took, as Camel's context error handler. /// /// /// Layers 1 and 2 choose together, as Camel's exception policy does: the handler whose exception type is nearest to /// the failure wins wherever it is declared, and the route's own wins a tie (). /// So a route's OnException<Exception> does not hide a shared OnException<IOException>. /// /// /// An ordinary route is wrapped in two parts, because the route policy and the processing timeout sit between them: /// (layer 1, inside the route body) and (layers 2 and 3, around the /// timeout). A body that runs after its caller has returned — .Threads() for an in-only exchange — is no longer /// inside those wrappers, so it is wrapped by the whole scope (): a failure there gets the same /// handlers with their whole configuration (OnWhen, redeliveries, Handled, UseOriginalBody...). /// /// /// Each handler body is compiled once, where it always was: the route's inside the route's compile frame, the shared /// ones after it. The wrappers are therefore completed only in , by which time every handler /// exists; a detached wrapper refuses to run before that (the route has not finished compiling). /// /// internal sealed class RouteErrorScope { private readonly RouteContext _context; private readonly IReadOnlyList _sharedHandlers; private readonly List _routeHandlers = []; private readonly Dictionary _bodies = new(ReferenceEqualityComparer.Instance); private readonly List _detached = []; private readonly ILogger? _logger; private OnExceptionProcessor? _routeLayer; private bool _sealed; /// The context the route compiles in. /// The route this scope belongs to. /// The OnException blocks of the route's builder. /// The OnException blocks of the route configurations of the route. /// Logger of the handlers. internal RouteErrorScope(RouteContext context, string routeId, IReadOnlyList builderHandlers, IReadOnlyList configurationHandlers, ILogger? logger) { _context = context; RouteId = routeId; _sharedHandlers = [.. builderHandlers, .. configurationHandlers]; _logger = logger; } /// The route this scope belongs to. internal string RouteId { get; } /// Takes the route's own OnException blocks, in declaration order. internal void AddRouteHandlers(IEnumerable handlers) => _routeHandlers.AddRange(handlers); /// Layer 1: the route's own OnException blocks around . internal IProcessor WrapRoute(IProcessor body) { _routeLayer = Layer(body, _routeHandlers); return _routeLayer ?? body; } /// /// Layers 2 and 3 around : the shared OnException blocks, then the context's error /// handling. Links the route's own layer to the shared one and completes the detached wrappers of this route. /// internal IProcessor WrapOuter(IProcessor body) { var shared = Layer(body, _sharedHandlers); if (_routeLayer is not null) _routeLayer.Outer = shared; foreach (var detached in _detached) { var route = Layer(detached.Body, _routeHandlers); var outer = Layer(route ?? detached.Body, _sharedHandlers); if (route is not null) route.Outer = outer; detached.Target = Context(outer ?? route ?? detached.Body); } _sealed = true; return Context(shared ?? body); } /// /// The whole scope around a body that runs after its caller has returned. The wrapper is completed by /// , when every handler body of the route is compiled. /// internal IProcessor WrapDetached(IProcessor body) { if (_sealed) throw new InvalidOperationException($"The error scope of route '{RouteId}' is already complete."); var detached = new DetachedBody(body, RouteId); _detached.Add(detached); return detached; } /// /// Whether an OnException of this route, of its builder or of its route configurations covers /// . /// internal bool Handles(Type exceptionType) => _routeHandlers.Concat(_sharedHandlers) .Any(h => h.ExceptionTypes.Any(t => t.IsAssignableFrom(exceptionType))); private IProcessor Context(IProcessor body) => new ContextErrorLayerProcessor(body, _context, RouteId); /// One processor for all of around ; none when there are no handlers. private OnExceptionProcessor? Layer(IProcessor body, IReadOnlyList handlers) { if (handlers.Count == 0) return null; var layer = new OnExceptionProcessor(body, _logger); foreach (var handler in handlers) handler.AddTo(layer, BodyOf(handler)); return layer; } private IProcessor BodyOf(OnExceptionDefinition handler) { if (!_bodies.TryGetValue(handler, out var body)) { body = _context.CompileHandlerBody(handler.Outputs); _bodies[handler] = body; } return body; } /// A detached body whose error scope is completed when the route's compilation ends. private sealed class DetachedBody(IProcessor body, string routeId) : IProcessor { internal IProcessor Body { get; } = body; internal IProcessor? Target { get; set; } public Task Process(IExchange exchange, CancellationToken ct = default) => (Target ?? throw new InvalidOperationException( $"Route '{routeId}' has not finished compiling: its error scope is not complete.")) .Process(exchange, ct); } } Path: redb-route/redb.Route/Core/RouteIdFactory.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/Core/RouteIdFactory.cs ---- using System.Security.Cryptography; using System.Text; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Builds the id of a route that declared none with RouteId("..."): the endpoint's scheme, /// its path and a deterministic UUID of the whole endpoint URI, joined with - — for example /// kafka-orders-1b4e28ba-2fa1-11d2-883f-0016d3cca427. /// /// The id is stable. The same endpoint yields the same id on every start, in every process and on /// every node of a cluster, so metric series, stored checkpoints and control-bus commands keep /// pointing at the same route across a restart. It holds no URI separator (a / or a : /// breaks dashboard labels and metric tags) and no query string, so a secret in the URI cannot /// surface in a log line; endpoints differing only in a parameter still get different ids, because /// the parameters are hashed rather than shown. /// /// /// The UUID is RFC 4122 version 5 (name-based, SHA-1) in the standard URL namespace over /// , so anyone can recompute a route id from its URI with any /// UUID library, without this code. /// /// public static class RouteIdFactory { /// The RFC 4122 URL namespace, in which a route's UUID is computed. public static readonly Guid UrlNamespace = new("6ba7b811-9dad-11d1-80b4-00c04fd430c8"); /// Longest readable part (scheme and path) kept in front of the UUID. private const int MaxLabelLength = 48; /// Builds the default id of a route consuming from . /// The parsed From() endpoint URI of the route. public static string ForEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var label = Label(uri); var uuid = Uuid5(UrlNamespace, uri.NormalizedKey); return label.Length == 0 ? uuid.ToString() : $"{label}-{uuid}"; } // The readable head: scheme and path, every other character folded into a single '-'. Non-ASCII // letters go the same way — a route id is read by dashboards and metric backends, not by humans // alone. private static string Label(EndpointUri uri) { var text = $"{uri.Scheme}-{StripUserInfo(uri.Path)}"; var sb = new StringBuilder(MaxLabelLength); foreach (var c in text) { if (sb.Length >= MaxLabelLength) break; if (char.IsAsciiLetterOrDigit(c) || c == '_') sb.Append(c); else if (sb.Length > 0 && sb[^1] != '-') sb.Append('-'); } return sb.ToString().TrimEnd('-'); } // "user:password@host:5672/orders" -> "host:5672/orders". Credentials are not part of a name, // and the '@' form hides them from Sanitize's query-parameter masking. private static string StripUserInfo(string path) { var slash = path.IndexOf('/'); var authority = slash < 0 ? path : path[..slash]; var at = authority.LastIndexOf('@'); return at < 0 ? path : path[(at + 1)..]; } /// /// RFC 4122 version 5 UUID: the SHA-1 of the namespace followed by the name, with the version /// and variant bits set. SHA-1 is what the standard prescribes here; this is a name, not a /// signature. /// internal static Guid Uuid5(Guid ns, string name) { var nameBytes = Encoding.UTF8.GetBytes(name); var input = new byte[16 + nameBytes.Length]; ns.TryWriteBytes(input.AsSpan(0, 16), bigEndian: true, out _); nameBytes.CopyTo(input, 16); Span hash = stackalloc byte[20]; SHA1.HashData(input, hash); hash[6] = (byte)((hash[6] & 0x0F) | 0x50); // version 5 hash[8] = (byte)((hash[8] & 0x3F) | 0x80); // RFC 4122 variant return new Guid(hash[..16], bigEndian: true); } } Path: redb-route/redb.Route/Core/RouteResourceResolver.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/Core/RouteResourceResolver.cs ---- using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Default : probes, in order, the reference as an absolute /// path, (when set), , and the /// current working directory. The working directory is deliberately LAST: it preserves the /// pre-resolver behaviour (a bare File.Exists) as the final fallback rather than the rule. /// public sealed class RouteResourceResolver : IRouteResourceResolver { /// The shared instance used when no resolver is registered on the context. public static RouteResourceResolver Default { get; } = new(); /// Optional search base probed first for relative references (e.g. a package root). public string? ResourceRoot { get; init; } /// public string? Resolve(string reference) { ArgumentException.ThrowIfNullOrWhiteSpace(reference); return Candidates(reference).FirstOrDefault(File.Exists); } /// public string DescribeSearch(string reference) => string.Join(", ", Candidates(reference)); private IEnumerable Candidates(string reference) { if (Path.IsPathRooted(reference)) { yield return reference; yield break; } if (!string.IsNullOrWhiteSpace(ResourceRoot)) yield return Path.GetFullPath(Path.Combine(ResourceRoot, reference)); yield return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, reference)); yield return Path.GetFullPath(reference); // current working directory — last on purpose } } /// Shared resolve-or-throw used by the components that read files from endpoint URIs. public static class ResourceResolution { /// /// Resolves through the context's registered /// (or ) and /// returns the absolute path. Throws naming every probed /// location when the resource does not exist. /// public static string Resolve(IRouteContext? context, string reference, string what) { var resolver = context?.GetService() ?? RouteResourceResolver.Default; var resolved = resolver.Resolve(reference); if (resolved is null) throw new FileNotFoundException( $"{what} not found: '{reference}'. Searched: {resolver.DescribeSearch(reference)}."); return resolved; } /// /// Pins a that names a file by a relative path to the file the context /// can actually see: the registered first (a package keeps /// its resources where only the resolver knows), then , which is /// what the consuming package was configured with. Inline text, an embedded resource and an /// absolute path are returned untouched. /// /// The returned source names the resolved file, so a compile cache keyed by it distinguishes two /// packages that ship the same relative name — a hot-reloaded module must not render the previous /// version's text. /// /// /// Route context whose resolver is consulted; null falls back to the default one. /// The source as the route author wrote it. /// The package's own base directory, probed after the resolver. /// Noun for the error message, e.g. "Template". /// Neither place holds the file; the message names both. public static TextSource Locate(IRouteContext? context, TextSource source, string baseDirectory, string what) { ArgumentNullException.ThrowIfNull(source); if (source.FilePath is not { } reference || Path.IsPathRooted(reference)) return source; var resolver = context?.GetService() ?? RouteResourceResolver.Default; if (resolver.Resolve(reference) is { } resolved) return TextSource.Located(reference, resolved); // Not known to the resolver: the package's own base directory is the second place, and the // only one the pre-resolver behaviour ever used. var fromBase = Path.GetFullPath(Path.Combine(baseDirectory, reference)); if (System.IO.File.Exists(fromBase)) return TextSource.Located(reference, fromBase); // Both places in one line, each once: the default resolver already probes the process base // directory, which for most packages is the base directory as well. var searched = resolver.DescribeSearch(reference) .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Append(fromBase) .Distinct(StringComparer.OrdinalIgnoreCase); throw new FileNotFoundException( $"{what} not found: '{reference}'. Searched: {string.Join(", ", searched)}.", fromBase); } } Path: redb-route/redb.Route/Core/SafeXml.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/Core/SafeXml.cs ---- using System.Xml; using System.Xml.Linq; namespace redb.Route.Core; /// /// Reads XML that came from somewhere else. Every loader here goes through an /// with and no resolver, which is the only shape in .NET that /// refuses a document type declaration. /// /// The direct loaders do not. Measured on .NET 10: a 452-byte document whose DTD declares nested /// internal entities expands to 300 000 characters through , /// through and through /// alike — LINQ to XML is no safer than the old DOM here. Setting XmlResolver = null does not /// help either: it closes external entities, while the expansion is driven by internal ones (the /// "billion laughs" shape of an XXE attack). One small message can therefore cost the worker /// gigabytes, which is a denial of service against every route sharing the process. /// /// /// A DTD is refused rather than expanded with a budget: SOAP forbids a document type declaration in /// an envelope outright, and a payload that needs one is rare enough to be an explicit decision /// rather than a default. /// /// /// Every loader also checks the structure of the document while it reads (): depth, /// attributes and namespace declarations per element, and where the caller asks, size, element count and /// namespace declarations in the whole document. A document over a limit is refused with /// before it is built, so whatever reads it next gets a bounded input. The loaders /// without an argument apply , with maxCharacters as /// the size bound. /// /// public static class SafeXml { /// /// Reader settings that refuse a DTD and never resolve anything external. They do not check the structure: a /// reader made from them alone is not bounded by , see . /// /// Upper bound on the whole document, or null for no bound. public static XmlReaderSettings Settings(long? maxCharacters = null) => new() { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = maxCharacters ?? 0, CloseInput = false, }; /// A reader over that refuses a DTD and checks . public static XmlReader CreateReader(Stream stream, XmlLimits limits) => CreateReader(stream, limits, baseUri: null); /// A reader over that refuses a DTD and checks . public static XmlReader CreateReader(TextReader text, XmlLimits limits) { ArgumentNullException.ThrowIfNull(text); ArgumentNullException.ThrowIfNull(limits); limits.Validate(); return new LimitedXmlReader(XmlReader.Create(text, Settings(limits.MaxCharacters)), limits); } private static XmlReader CreateReader(Stream stream, XmlLimits limits, string? baseUri) { ArgumentNullException.ThrowIfNull(stream); ArgumentNullException.ThrowIfNull(limits); limits.Validate(); var inner = baseUri is null ? XmlReader.Create(stream, Settings(limits.MaxCharacters)) : XmlReader.Create(stream, Settings(limits.MaxCharacters), baseUri); return new LimitedXmlReader(inner, limits); } /// /// Reads to the end without building anything, and throws /// or when it is over or not well-formed. For a receiver that /// parses the same bytes several times: one check up front bounds every later parse. /// public static void Check(byte[] xml, XmlLimits limits) { ArgumentNullException.ThrowIfNull(xml); using var stream = new MemoryStream(xml, writable: false); using var reader = CreateReader(stream, limits); while (reader.Read()) { } } /// Loads a document from bytes, within and . public static XDocument Load(byte[] xml, LoadOptions options = LoadOptions.None, long? maxCharacters = null) => Load(xml, Bounded(maxCharacters), options); /// Loads a document from bytes within . public static XDocument Load(byte[] xml, XmlLimits limits, LoadOptions options = LoadOptions.None) { ArgumentNullException.ThrowIfNull(xml); using var stream = new MemoryStream(xml, writable: false); return Load(stream, limits, options); } /// Loads a document from a stream, within and . public static XDocument Load(Stream stream, LoadOptions options = LoadOptions.None, long? maxCharacters = null) => Load(stream, Bounded(maxCharacters), options); /// Loads a document from a stream within . public static XDocument Load(Stream stream, XmlLimits limits, LoadOptions options = LoadOptions.None) { using var reader = CreateReader(stream, limits); return XDocument.Load(reader, options); } /// Loads a document from a file path, within and . public static XDocument LoadFile(string path, LoadOptions options = LoadOptions.None, long? maxCharacters = null) => LoadFile(path, Bounded(maxCharacters), options); /// Loads a document from a file path within . public static XDocument LoadFile(string path, XmlLimits limits, LoadOptions options = LoadOptions.None) { ArgumentException.ThrowIfNullOrWhiteSpace(path); using var stream = System.IO.File.OpenRead(path); // The reader needs the base URI to report a usable location for an error in this file. using var reader = CreateReader(stream, limits, path); return XDocument.Load(reader, options); } /// Parses a document from text, within and . public static XDocument Parse(string xml, LoadOptions options = LoadOptions.None, long? maxCharacters = null) => Parse(xml, Bounded(maxCharacters), options); /// Parses a document from text within . public static XDocument Parse(string xml, XmlLimits limits, LoadOptions options = LoadOptions.None) { ArgumentNullException.ThrowIfNull(xml); using var reader = CreateReader(new StringReader(xml), limits); return XDocument.Load(reader, options); } /// Parses a single element from text, within and . public static XElement ParseElement(string xml, LoadOptions options = LoadOptions.None, long? maxCharacters = null) => ParseElement(xml, Bounded(maxCharacters), options); /// Parses a single element from text within . public static XElement ParseElement(string xml, XmlLimits limits, LoadOptions options = LoadOptions.None) { ArgumentNullException.ThrowIfNull(xml); using var reader = CreateReader(new StringReader(xml), limits); reader.MoveToContent(); return XElement.Load(reader, options); } /// /// Loads an , the shape System.Security.Cryptography.Xml needs for signatures and /// encryption, within and . /// defaults to true because canonicalization of a signed document depends on /// it: dropping whitespace on load makes a valid signature fail to verify. /// public static XmlDocument LoadDocument(byte[] xml, bool preserveWhitespace = true, long? maxCharacters = null) => LoadDocument(xml, Bounded(maxCharacters), preserveWhitespace); /// Loads an from bytes within ; whitespace as in the other overload. public static XmlDocument LoadDocument(byte[] xml, XmlLimits limits, bool preserveWhitespace = true) { ArgumentNullException.ThrowIfNull(xml); using var stream = new MemoryStream(xml, writable: false); return LoadDocument(stream, limits, preserveWhitespace); } /// Loads an from a stream within ; whitespace as in the other overload. public static XmlDocument LoadDocument(Stream stream, XmlLimits limits, bool preserveWhitespace = true) { var document = new XmlDocument { PreserveWhitespace = preserveWhitespace, XmlResolver = null }; using var reader = CreateReader(stream, limits); document.Load(reader); return document; } private static XmlLimits Bounded(long? maxCharacters) => maxCharacters is null ? XmlLimits.Default : XmlLimits.Default with { MaxCharacters = maxCharacters }; } Path: redb-route/redb.Route/Core/SensitiveAttribute.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/Core/SensitiveAttribute.cs ---- namespace redb.Route.Core; /// /// Marks an endpoint option as a credential, so its value is redacted wherever the endpoint URI is /// rendered — logs, OpenTelemetry tags, metric labels, health checks, and the Tsak dashboard. /// /// This is the source of truth for what counts as a secret: masking is driven by an explicit /// declaration on the property rather than by guessing from the parameter name. The name-keyword /// heuristic in remains only as a backstop for /// URIs whose options type has not been bound yet. /// /// /// The mechanism mirrors Apache Camel, where @UriParam(secret = true) on the option field is /// the declaration and the runtime keyword list (SensitiveUtils.SENSITIVE_KEYS) is generated /// from those annotations rather than hand-maintained. Camel harvests them with a build plugin; /// here harvests them by reflection, once per options /// type, and feeds . Either way the list is /// never written by hand, so a new credential option cannot be forgotten. /// /// /// /// public sealed class LdapEndpointOptions : EndpointOptions /// { /// public string Server { get; set; } = "localhost"; // printed in logs /// /// [Sensitive] /// public string? BindPassword { get; set; } // always rendered as **** /// } /// /// /// [AttributeUsage(AttributeTargets.Property, Inherited = true)] public sealed class SensitiveAttribute : Attribute { } Path: redb-route/redb.Route/Core/StatisticsProcessor.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/Core/StatisticsProcessor.cs ---- using System.Diagnostics; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Processor decorator that records consumer-side statistics on the source endpoint. /// Wraps the inner processor: calls before processing /// and on failure; also records processing time, /// body bytes, and retry warnings. MessagesOut is deliberately NOT recorded here — it is /// producer-side only (), so an endpoint that plays both roles /// (direct:, seda:) counts each send once instead of twice. A consumer endpoint's completed /// count is MessagesIn - Errors - Cancelled. /// No-op if the endpoint does not implement . /// internal sealed class StatisticsProcessor : IProcessor { private readonly IProcessor _inner; private readonly IEndpointStatistics? _stats; /// Creates a statistics-recording processor wrapper. /// The processor to wrap. /// The source endpoint (checked for ). public StatisticsProcessor(IProcessor inner, IEndpoint endpoint) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _stats = endpoint as IEndpointStatistics; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { if (_stats is null) { await _inner.Process(exchange, ct).ConfigureAwait(false); return; } _stats.RecordMessageIn(); // Estimate incoming body size var bodySize = EndpointBase.EstimateBodySize(exchange.In.Body); if (bodySize > 0) _stats.RecordBytesIn(bodySize); var sw = Stopwatch.StartNew(); try { await _inner.Process(exchange, ct).ConfigureAwait(false); sw.Stop(); // Check for handled exceptions (set on exchange but not thrown) if (exchange.Exception is not null && !exchange.ExceptionHandled) { if (IsCooperativeCancellation(exchange.Exception, ct)) _stats.RecordCancelled(); else _stats.RecordError(exchange.Exception); } else { // Detect retry attempts: RetryProcessor sets "RetryAttempt" property, // OnExceptionProcessor sets "CamelRedeliveryCounter" header. // If either > 0, the exchange succeeded after retries → record warning. var retryAttempt = exchange.GetProperty("RetryAttempt"); var redeliveryCounter = exchange.In.Headers.TryGetValue("CamelRedeliveryCounter", out var rc) && rc is int rci ? rci : 0; var totalRetries = Math.Max(retryAttempt, redeliveryCounter); if (totalRetries > 0) _stats.RecordWarning($"Succeeded after {totalRetries} retry attempt(s)"); } } catch (Exception ex) { sw.Stop(); // A cancellation the caller asked for is not the route's failure (BR-10): a dashboard // closing mid-poll was turning healthy routes red on the Error-Prone panel and // degrading endpoint health for the five-minute error window. The error-handling layer // has always read OCE this way — retry never retries it, dead-letter never parks it — // and the statistics were the one layer still counting it. An OCE thrown while the // caller's token is live (an internal timeout) is the route failing to answer in time // and stays an error. if (IsCooperativeCancellation(ex, ct)) _stats.RecordCancelled(); else _stats.RecordError(ex); throw; } finally { _stats.RecordProcessingTime(sw.Elapsed); } } /// /// True when the exception is the caller's own cancellation arriving back: an /// while the token the caller handed in is cancelled. /// internal static bool IsCooperativeCancellation(Exception exception, CancellationToken ct) => exception is OperationCanceledException && ct.IsCancellationRequested; } Path: redb-route/redb.Route/Core/StreamCache.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/Core/StreamCache.cs ---- using redb.Route.Configuration; namespace redb.Route.Core; /// /// A stream that holds content in memory up to a threshold and spools the rest to a temporary file, then reads it back /// from the start as often as needed — Camel's StreamCache. The .StreamCaching() step wraps a forward-only /// body in one; a connector uses one to spool what it must not hand to the route before it is complete and checked /// (a decrypted attachment whose tag and signature are verified only at the end). /// /// Two phases. While writing (, , /// ) it cannot be read; rewinds it and turns it /// read-only and seekable. The temporary file is opened with : disposing the /// cache — the exchange does, when it owns the body — removes it. /// /// public sealed class StreamCache : Stream, IAsyncDisposable { /// Default threshold: 128 KB in memory, the rest on disk. public const long DefaultSpoolThreshold = 128 * 1024; private readonly long _spoolThreshold; private readonly string? _tempDirectory; private Stream _inner; private bool _completed; private bool _disposed; // Serialises the reads of this stream and of its readers (OpenReader): they share one inner stream and its position. private readonly SemaphoreSlim _gate = new(1, 1); /// Creates a cache with the threshold and temporary directory of (defaults when null). public StreamCache(StreamCacheOptions? options = null) : this(options?.SpoolThreshold ?? DefaultSpoolThreshold, options?.TempDirectory) { } /// Creates a cache. /// Bytes kept in memory before the content moves to a temporary file. /// Directory of the temporary file; null = the system temp directory. public StreamCache(long spoolThreshold, string? tempDirectory = null) { ArgumentOutOfRangeException.ThrowIfNegative(spoolThreshold); _spoolThreshold = spoolThreshold; _tempDirectory = tempDirectory; _inner = new MemoryStream(); } /// Whether the content went past the threshold and lives in a temporary file. public bool IsSpooled { get; private set; } /// /// Reads all of into the cache and completes writing. The source is not disposed: its /// owner closes it (the .StreamCaching() step does, since the cache replaces it as the body). /// public async Task CacheFromSourceAsync(Stream source, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(source); var buffer = new byte[81920]; int read; while ((read = await source.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) await WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); CompleteWriting(); } /// Ends the writing phase: the cache rewinds and becomes read-only and seekable. public void CompleteWriting() { ObjectDisposedException.ThrowIf(_disposed, this); if (_completed) return; _inner.Flush(); _inner.Position = 0; _completed = true; } /// public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); /// public override void Write(ReadOnlySpan buffer) { EnsureWriting(); _inner.Write(buffer); if (!IsSpooled && _inner.Length > _spoolThreshold) Spool(); } /// public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) => WriteAsync(buffer.AsMemory(offset, count), ct).AsTask(); /// public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken ct = default) { EnsureWriting(); await _inner.WriteAsync(buffer, ct).ConfigureAwait(false); if (!IsSpooled && _inner.Length > _spoolThreshold) await SpoolAsync(ct).ConfigureAwait(false); } private FileStream OpenSpoolFile() => new( Path.Combine(_tempDirectory ?? Path.GetTempPath(), $"redb-stream-{Guid.NewGuid():N}.tmp"), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 81920, FileOptions.Asynchronous | FileOptions.DeleteOnClose); private void Spool() { var file = OpenSpoolFile(); _inner.Position = 0; _inner.CopyTo(file); _inner.Dispose(); _inner = file; IsSpooled = true; } private async Task SpoolAsync(CancellationToken ct) { var file = OpenSpoolFile(); _inner.Position = 0; await _inner.CopyToAsync(file, ct).ConfigureAwait(false); await _inner.DisposeAsync().ConfigureAwait(false); _inner = file; IsSpooled = true; } private void EnsureWriting() { ObjectDisposedException.ThrowIf(_disposed, this); if (_completed) throw new NotSupportedException("StreamCache is read-only once writing completed."); } private void EnsureReadable() { ObjectDisposedException.ThrowIf(_disposed, this); if (!_completed) throw new NotSupportedException("StreamCache is still being written: call CompleteWriting() before reading it."); } /// public override bool CanRead => !_disposed && _completed; /// public override bool CanSeek => !_disposed && _completed; /// public override bool CanWrite => !_disposed && !_completed; /// public override long Length => _inner.Length; /// public override long Position { get => _inner.Position; set { EnsureReadable(); _gate.Wait(); try { _inner.Position = value; } finally { _gate.Release(); } } } /// public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); /// public override int Read(Span buffer) { EnsureReadable(); _gate.Wait(); try { return _inner.Read(buffer); } finally { _gate.Release(); } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken ct) => ReadAsync(buffer.AsMemory(offset, count), ct).AsTask(); /// public override async ValueTask ReadAsync(Memory buffer, CancellationToken ct = default) { EnsureReadable(); await _gate.WaitAsync(ct).ConfigureAwait(false); try { return await _inner.ReadAsync(buffer, ct).ConfigureAwait(false); } finally { _gate.Release(); } } /// public override long Seek(long offset, SeekOrigin origin) { EnsureReadable(); _gate.Wait(); try { return _inner.Seek(offset, origin); } finally { _gate.Release(); } } /// /// Opens an independent read-only view of the completed cache, positioned at the start: it has a position of its own, /// so several readers (and this stream) read the same content without moving each other. Disposing a reader leaves /// the cache open; the cache's owner disposes it. /// public Stream OpenReader() { EnsureReadable(); return new Reader(this); } private int ReadAt(long position, Span buffer) { EnsureReadable(); _gate.Wait(); try { var saved = _inner.Position; _inner.Position = position; try { return _inner.Read(buffer); } finally { _inner.Position = saved; } } finally { _gate.Release(); } } private async ValueTask ReadAtAsync(long position, Memory buffer, CancellationToken ct) { EnsureReadable(); await _gate.WaitAsync(ct).ConfigureAwait(false); try { var saved = _inner.Position; _inner.Position = position; try { return await _inner.ReadAsync(buffer, ct).ConfigureAwait(false); } finally { _inner.Position = saved; } } finally { _gate.Release(); } } private sealed class Reader(StreamCache cache) : Stream { private long _position; private bool _closed; public override bool CanRead => !_closed && cache.CanRead; public override bool CanSeek => CanRead; public override bool CanWrite => false; public override long Length => cache.Length; public override long Position { get => _position; set { ArgumentOutOfRangeException.ThrowIfNegative(value); _position = value; } } public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); public override int Read(Span buffer) { ObjectDisposedException.ThrowIf(_closed, this); var read = cache.ReadAt(_position, buffer); _position += read; return read; } public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken ct) => ReadAsync(buffer.AsMemory(offset, count), ct).AsTask(); public override async ValueTask ReadAsync(Memory buffer, CancellationToken ct = default) { ObjectDisposedException.ThrowIf(_closed, this); var read = await cache.ReadAtAsync(_position, buffer, ct).ConfigureAwait(false); _position += read; return read; } public override long Seek(long offset, SeekOrigin origin) { ObjectDisposedException.ThrowIf(_closed, this); Position = origin switch { SeekOrigin.Begin => offset, SeekOrigin.Current => _position + offset, SeekOrigin.End => Length + offset, _ => throw new ArgumentOutOfRangeException(nameof(origin)) }; return _position; } public override void Flush() { } public override void SetLength(long value) => throw new NotSupportedException("A StreamCache reader is read-only."); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException("A StreamCache reader is read-only."); protected override void Dispose(bool disposing) { _closed = true; base.Dispose(disposing); } } /// public override void SetLength(long value) => throw new NotSupportedException("StreamCache grows by writing only."); /// public override void Flush() { if (!_disposed) _inner.Flush(); } /// protected override void Dispose(bool disposing) { if (_disposed) return; _disposed = true; if (disposing) _inner.Dispose(); base.Dispose(disposing); } /// public override async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; await _inner.DisposeAsync().ConfigureAwait(false); GC.SuppressFinalize(this); } } Path: redb-route/redb.Route/Core/TextSource.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/Core/TextSource.cs ---- using System.Reflection; namespace redb.Route.Core; /// /// Where a piece of configuration text comes from — a Scriban template, a JSONata specification, a /// schema: a file (relative to a base directory), an embedded resource, or inline text. Shared by the /// packages that consume such text so they follow one rule: a plain string in the DSL is always /// a locator ("Templates/order.json.sbn" or "assembly:Acme.Orders/Templates/order.json.sbn"); /// inline text must be marked with . A string never has to be guessed as /// "path or text" — the rule the route expression language follows too. /// public abstract class TextSource { /// Prefix of an embedded-resource locator: assembly:<AssemblyName>/<resource path>. public const string AssemblyPrefix = "assembly:"; /// Human-readable name used in error messages (file path, resource locator, or <inline>). public abstract string Name { get; } /// Stable identity of the source as written: two sources with the same key name the same thing. public abstract string CacheKey { get; } /// /// Identity for compile caches once the base directory is known. A file is keyed by its resolved /// path plus its size and last write time, so two configurations pointing at different directories /// never share a compiled object and an edited file compiles afresh on the next route build (a /// hot-reloaded module in the same process included). Other sources return . /// public virtual string ResolveCacheKey(string baseDirectory) => CacheKey; /// Reads the text. A relative file path is resolved against . public abstract string Read(string baseDirectory); /// /// The file path this source was written with, or null when the text does not come from a /// file. Lets a package look the path up the way the rest of the framework does (see /// ) before falling back to its own base directory. /// public virtual string? FilePath => null; /// Inline text. public static TextSource Inline(string text) { ArgumentNullException.ThrowIfNull(text); return new InlineTextSource(text); } /// A file; a relative path is resolved against the base directory the consuming package is configured with. public static TextSource File(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); return new FileTextSource(path); } /// /// A file that has already been located (see ): read and /// cached by , but still named the way the route author wrote it, so /// an error message says templates/order.sbn and not the unpacked package's temp path. /// internal static TextSource Located(string writtenAs, string fullPath) => new ResolvedFileTextSource(writtenAs, fullPath); /// An embedded resource of ; may use / or . separators and may omit the assembly-name prefix. public static TextSource Embedded(Assembly assembly, string resourcePath) { ArgumentNullException.ThrowIfNull(assembly); ArgumentException.ThrowIfNullOrWhiteSpace(resourcePath); return new EmbeddedTextSource(assembly, resourcePath); } /// Parses a DSL / XML locator: assembly:Name/path → embedded resource, anything else → file path. public static TextSource FromLocator(string locator) { ArgumentException.ThrowIfNullOrWhiteSpace(locator); if (!locator.StartsWith(AssemblyPrefix, StringComparison.OrdinalIgnoreCase)) return File(locator); var rest = locator[AssemblyPrefix.Length..]; var slash = rest.IndexOf('/'); if (slash <= 0 || slash == rest.Length - 1) throw new ArgumentException($"Embedded locator must look like 'assembly:AssemblyName/Path/To/file', got '{locator}'.", nameof(locator)); var assemblyName = rest[..slash]; var assembly = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(a => string.Equals(a.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase)) ?? Assembly.Load(assemblyName); return Embedded(assembly, rest[(slash + 1)..]); } /// public override string ToString() => Name; } internal sealed class InlineTextSource(string text) : TextSource { public override string Name => ""; public override string CacheKey => "inline:" + text; public override string Read(string baseDirectory) => text; } internal sealed class FileTextSource(string path) : TextSource { public override string Name => path; public override string CacheKey => "file:" + path; public override string? FilePath => path; public override string ResolveCacheKey(string baseDirectory) { var full = Resolve(baseDirectory); var info = new FileInfo(full); return info.Exists ? $"file:{full}|{info.Length}|{info.LastWriteTimeUtc.Ticks}" : "file:" + full; } private string Resolve(string baseDirectory) => Path.IsPathRooted(path) ? path : Path.GetFullPath(Path.Combine(baseDirectory, path)); public override string Read(string baseDirectory) { var full = Resolve(baseDirectory); if (!System.IO.File.Exists(full)) throw new FileNotFoundException($"File '{path}' not found (resolved to '{full}'; base directory '{baseDirectory}').", full); return System.IO.File.ReadAllText(full); } } internal sealed class ResolvedFileTextSource(string writtenAs, string fullPath) : TextSource { public override string Name => writtenAs; public override string CacheKey => "file:" + fullPath; public override string? FilePath => fullPath; public override string ResolveCacheKey(string baseDirectory) { var info = new FileInfo(fullPath); return info.Exists ? $"file:{fullPath}|{info.Length}|{info.LastWriteTimeUtc.Ticks}" : "file:" + fullPath; } public override string Read(string baseDirectory) { if (!System.IO.File.Exists(fullPath)) throw new FileNotFoundException($"File '{writtenAs}' not found (resolved to '{fullPath}').", fullPath); return System.IO.File.ReadAllText(fullPath); } } internal sealed class EmbeddedTextSource(Assembly assembly, string resourcePath) : TextSource { public override string Name => $"{AssemblyPrefix}{assembly.GetName().Name}/{resourcePath}"; public override string CacheKey => "embedded:" + Name; public override string Read(string baseDirectory) { var names = assembly.GetManifestResourceNames(); var dotted = resourcePath.Replace('/', '.').Replace('\\', '.'); var candidates = new[] { resourcePath, dotted, $"{assembly.GetName().Name}.{dotted}" }; var match = candidates.FirstOrDefault(c => names.Contains(c, StringComparer.Ordinal)) ?? names.FirstOrDefault(n => n.EndsWith("." + dotted, StringComparison.OrdinalIgnoreCase)) ?? throw new FileNotFoundException( $"Embedded resource '{resourcePath}' not found in assembly '{assembly.GetName().Name}'. Available resources: {string.Join(", ", names)}"); using var stream = assembly.GetManifestResourceStream(match)!; using var reader = new StreamReader(stream); return reader.ReadToEnd(); } } Path: redb-route/redb.Route/Core/TypedValue.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/Core/TypedValue.cs ---- using System.Globalization; namespace redb.Route.Core; /// /// The conversion behind the typed reads of a header, a property and a received body, as Camel converts: a missing /// value, or one with no conversion to the type at all, reads as default; a value the conversion exists for but cannot /// parse is an error naming the key and the type — never the value, which may be a credential. Numbers and dates are /// read in the invariant culture, and a nullable target converts like its underlying type. /// internal static class TypedValue { /// Converts , read under , to . /// The stored value. /// What was read, for the error: header 'orderId'. /// The value cannot be parsed as . public static T? Convert(object? value, string what) { if (value is null) return default; if (value is T typed) return typed; var target = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); // No conversion between the types (not IConvertible, or a pair ChangeType does not map): Camel reads null. if (value is not IConvertible || !typeof(IConvertible).IsAssignableFrom(target)) return default; try { return (T)RouteDecimal.ChangeType(value, target, CultureInfo.InvariantCulture); } catch (InvalidCastException) { return default; // a pair of IConvertible types with no mapping (a char from a DateTime): no conversion } catch (Exception ex) when (ex is FormatException or OverflowException) { throw new FormatException($"The {what} cannot be read as {target.Name}: its value does not parse as one.", ex); } } } Path: redb-route/redb.Route/Core/UriMask.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/Core/UriMask.cs ---- using System.Collections.Concurrent; using System.Text.RegularExpressions; namespace redb.Route.Core; /// /// Endpoint URI mask shared by AdviceWith (MockEndpoints, WeaveByToUri), endpoint /// interception and the header / property masks. Three pattern forms, checked in order: /// /// regex: prefix — a .NET regular expression (case-insensitive, culture-invariant, /// one-second timeout, compiled once per pattern) matched against the URI as written, without its query /// string, and with scheme:// collapsed to scheme:; /// trailing * — case-insensitive prefix match; /// otherwise — exact case-insensitive match. /// /// A pattern without a query string ignores the candidate's query ("kafka://orders" matches /// "kafka://orders?acks=all"); a pattern that carries one matches only that query /// ("kafka://orders?acks=all" does not match "?acks=none"). Both scheme://path /// and scheme:path spellings are tried on either side, so a pattern written one way matches an /// endpoint written the other. /// public static class UriMask { /// Prefix selecting the regular-expression pattern form. public const string RegexPrefix = "regex:"; private static readonly ConcurrentDictionary Regexes = new(StringComparer.Ordinal); /// /// Checks that is a usable mask and throws an /// naming the problem otherwise (a blank mask, an invalid regular expression). Called where a mask is /// declared, so a mistake fails there and not inside route compilation. /// public static void Validate(string? pattern, string? paramName = null) { if (string.IsNullOrWhiteSpace(pattern)) throw new ArgumentException("The URI mask is blank.", paramName ?? nameof(pattern)); if (!pattern.StartsWith(RegexPrefix, StringComparison.OrdinalIgnoreCase)) return; try { _ = CompiledRegex(pattern[RegexPrefix.Length..]); } catch (ArgumentException ex) { throw new ArgumentException($"The URI mask '{pattern}' is not a valid regular expression: {ex.Message}", paramName ?? nameof(pattern), ex); } } /// Returns true when matches . /// Mask: exact URI, prefix ending in *, or regex:<expression>. /// Candidate endpoint URI. public static bool IsMatch(string pattern, string uri) { ArgumentException.ThrowIfNullOrWhiteSpace(pattern); ArgumentException.ThrowIfNullOrWhiteSpace(uri); if (pattern.StartsWith(RegexPrefix, StringComparison.OrdinalIgnoreCase)) { var regex = CompiledRegex(pattern[RegexPrefix.Length..]); return RegexCandidates(uri).Any(regex.IsMatch); } if (pattern.EndsWith('*')) { // The full URI is tried, so a prefix that itself carries a query ("kafka://orders?acks=*") // requires that query; a prefix without one matches whatever query the endpoint has. var prefix = pattern[..^1]; return Spellings(prefix).Any(p => Spellings(uri).Any(c => c.StartsWith(p, StringComparison.OrdinalIgnoreCase))); } var candidate = pattern.Contains('?') ? uri : WithoutQuery(uri); return Spellings(pattern).Any(p => Spellings(candidate).Any(c => string.Equals(c, p, StringComparison.OrdinalIgnoreCase))); } private static Regex CompiledRegex(string expression) => Regexes.GetOrAdd(expression, static e => new Regex(e, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1))); /// What a regular expression is tried against: as written, query-stripped, and the stripped form with scheme:// collapsed. private static IEnumerable RegexCandidates(string uri) { yield return uri; var stripped = WithoutQuery(uri); if (stripped.Length != uri.Length) yield return stripped; var collapsed = stripped.Replace("://", ":", StringComparison.Ordinal); if (!string.Equals(collapsed, stripped, StringComparison.Ordinal)) yield return collapsed; } /// The two spellings of one URI: as written, and with scheme:// collapsed to scheme:. private static IEnumerable Spellings(string uri) { yield return uri; var collapsed = uri.Replace("://", ":", StringComparison.Ordinal); if (!string.Equals(collapsed, uri, StringComparison.Ordinal)) yield return collapsed; } private static string WithoutQuery(string uri) { var queryIndex = uri.IndexOf('?'); return queryIndex >= 0 ? uri[..queryIndex] : uri; } } Path: redb-route/redb.Route/Core/XmlLimitException.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/Core/XmlLimitException.cs ---- using System.Xml; namespace redb.Route.Core; /// /// A document went over one of its . It is an : whoever already /// answers malformed XML as the sender's fault answers this one the same way, with the position in the document. /// public sealed class XmlLimitException : XmlException { /// Creates the exception. /// The name of the property that was exceeded. /// Its value. /// What went over it. /// Line of the offending node, or 0 when unknown. /// Position of the offending node in its line, or 0 when unknown. public XmlLimitException(string limit, long maximum, string message, int lineNumber, int linePosition) : base(message, null, lineNumber, linePosition) { Limit = limit; Maximum = maximum; } /// The name of the property that was exceeded, for example MaxDepth. public string Limit { get; } /// The value of that limit. public long Maximum { get; } } Path: redb-route/redb.Route/Core/XmlLimits.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/Core/XmlLimits.cs ---- namespace redb.Route.Core; /// /// Structure limits for XML read through : how deep, how wide and how large a document may be. /// The reader checks them while it reads, so a document over a limit is refused before it is built, and whatever /// comes after the read (canonicalization, signature checks, XPath, XSLT, a deserializer) only ever sees a bounded /// document, whatever version of the XML libraries the application runs on. /// /// A null limit is not checked. bounds the structure only, generously enough that no ordinary /// document meets it; a receiver that knows the shape of what it reads (an AS4 envelope) sets tighter ones. /// /// public sealed record XmlLimits { /// Default : 256 levels of nested elements. public const int DefaultMaxDepth = 256; /// Default : 1024, namespace declarations included. public const int DefaultMaxAttributesPerElement = 1024; /// Default : 256. public const int DefaultMaxNamespaceDeclarationsPerElement = 256; /// /// The limits every loader applies when the caller names none: depth, attributes and /// namespace declarations per element. Size and element count are not bounded here; the caller that knows a sane /// size passes one. /// public static XmlLimits Default { get; } = new(); /// /// Nesting depth of elements, the root counting as 1. Deep nesting is what recursive processing of a document /// (canonicalization, XPath, a serializer) pays for with its stack. Default . /// public int? MaxDepth { get; init; } = DefaultMaxDepth; /// /// Attributes on one element, namespace declarations included. Default . /// public int? MaxAttributesPerElement { get; init; } = DefaultMaxAttributesPerElement; /// /// Namespace declarations (xmlns, xmlns:p) on one element: canonicalization works through the /// namespaces in scope of every element. Default . /// public int? MaxNamespaceDeclarationsPerElement { get; init; } = DefaultMaxNamespaceDeclarationsPerElement; /// Namespace declarations in the whole document. Default: not bounded. public long? MaxNamespaceDeclarations { get; init; } /// Elements in the whole document. Default: not bounded. public long? MaxElements { get; init; } /// /// Characters in the whole document, after entity references are resolved (). /// Default: not bounded. /// public long? MaxCharacters { get; init; } /// Throws when a limit is set to zero or less: such a limit would refuse every document. public void Validate() { Positive(MaxDepth, nameof(MaxDepth)); Positive(MaxAttributesPerElement, nameof(MaxAttributesPerElement)); Positive(MaxNamespaceDeclarationsPerElement, nameof(MaxNamespaceDeclarationsPerElement)); Positive(MaxNamespaceDeclarations, nameof(MaxNamespaceDeclarations)); Positive(MaxElements, nameof(MaxElements)); Positive(MaxCharacters, nameof(MaxCharacters)); } private static void Positive(long? value, string name) { if (value is <= 0) throw new ArgumentOutOfRangeException(name, value, $"XML limit {name} must be positive when set."); } } Path: redb-route/redb.Route/Definitions/AggregateDefinition.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/Definitions/AggregateDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Aggregator EIP. /// Collects exchanges sharing the same correlation key, merges them via the aggregation strategy, /// and forwards the completed aggregate to the body pipeline when the completion predicate is satisfied. /// Inherits the leaf DSL from ; /// child steps build the target pipeline executed on completed aggregates. /// Close with . /// public class AggregateDefinition : RouteDefinitionBase, IRouteScope { private readonly Func _correlationKey; private readonly Func _aggregationStrategy; private readonly Func _completionPredicate; internal AggregateDefinition( Func correlationKey, Func aggregationStrategy, Func completionPredicate) { _correlationKey = correlationKey ?? throw new ArgumentNullException(nameof(correlationKey)); _aggregationStrategy = aggregationStrategy ?? throw new ArgumentNullException(nameof(aggregationStrategy)); _completionPredicate = completionPredicate ?? throw new ArgumentNullException(nameof(completionPredicate)); } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes the Aggregate scope and returns the parent route definition. public IRouteDefinition EndAggregate() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndAggregate() called without a parent route.")); /// public IRouteDefinition End() => EndAggregate(); /// /// Optional inactivity timeout (Apache Camel completionTimeout): a group that receives /// nothing for this long completes with what it has. Set by the string-overload sugar; /// null keeps the predicate-only behaviour. /// public TimeSpan? CompletionTimeout { get; internal set; } /// /// Optional Apache Camel completionSize: a group completes once it has combined this many exchanges. Set by /// the string-overload sugar; null keeps the predicate-only behaviour. /// public int? CompletionSize { get; internal set; } /// /// Apache Camel forceCompletionOnStop: a group still open when the context stops completes with what it has, /// once the consumers have stopped and while the producers are still alive. Without it an open group is dropped on /// stop, with a warning naming how many. /// internal bool? ForceCompletionOnStopEnabled { get; private set; } /// Completes the open groups when the context stops (Apache Camel forceCompletionOnStop). public AggregateDefinition ForceCompletionOnStop(bool value = true) { ForceCompletionOnStopEnabled = value; return this; } // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor target = NodePipeline.Body(context, Outputs); return new AggregatorProcessor(_correlationKey, _aggregationStrategy, _completionPredicate, target, CompletionTimeout) { CompletionSize = CompletionSize, ForceCompletionOnStop = ForceCompletionOnStopEnabled == true, Logger = context.GetService()?.CreateLogger(), // A group completed by the timeout or on stop runs after its exchanges left the route's error wrappers. DetachedTarget = (context as Core.RouteContext)?.DetachedErrorScope?.WrapDetached(target), }; } } Path: redb-route/redb.Route/Definitions/AttachmentDefinitions.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/Definitions/AttachmentDefinitions.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Where an attachment step takes its content from: an expression, the body, or a file. The body and file forms are /// the common cases spelled out so a route needs no expression for them. /// public enum AttachmentSource { /// The value of an expression. Expression, /// The message body; the body itself stays. Body, /// A file, read from disk on every send. File } /// /// Leaf definition that adds an attachment to the In message. The name and the content type are literal; the file /// name and the file path are literal or an expression, chosen by the overload (never guessed from the text). /// /// /// Content of an expression or the body: byte[] as is, string as UTF-8, a completed /// shared (re-readable), another read into memory, an /// as is. A file is not read here: the attachment opens it on every read. /// public sealed class AddAttachmentDefinition : ProcessorDefinition { /// The content source. public AttachmentSource Source { get; } /// The attachment name; for a file it may be null, the file name then. public string? Name { get; } /// Content () or file path (). public IExpression? Content { get; } /// File name, or null (a file attachment uses the file's name). public IExpression? FileName { get; } /// Content type, or null for the default of the source. public string? ContentType { get; } private AddAttachmentDefinition(AttachmentSource source, string? name, IExpression? content, IExpression? fileName, string? contentType) { if (name is not null) ArgumentException.ThrowIfNullOrWhiteSpace(name); if (contentType is not null) ArgumentException.ThrowIfNullOrWhiteSpace(contentType); Source = source; Name = name; Content = content; FileName = fileName; ContentType = contentType; } /// An attachment with the value of . public static AddAttachmentDefinition FromExpression(string name, IExpression content, IExpression? fileName = null, string? contentType = null) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(content); return new(AttachmentSource.Expression, name, content, fileName, contentType); } /// An attachment with the message body as content. public static AddAttachmentDefinition FromBody(string name, IExpression? fileName = null, string? contentType = null) { ArgumentException.ThrowIfNullOrWhiteSpace(name); return new(AttachmentSource.Body, name, null, fileName, contentType); } /// An attachment with the content of the file at . public static AddAttachmentDefinition FromFile(IExpression path, string? name = null, string? contentType = null) { ArgumentNullException.ThrowIfNull(path); return new(AttachmentSource.File, name, path, null, contentType); } /// A literal as an expression: what the string overloads of the DSL pass. internal static IExpression? Literal(string? text) => text is null ? null : new ConstantExpression(text); /// public override IProcessor CreateProcessor(IRouteContext context) { var name = Name; var fileName = FileName; var contentType = ContentType; var source = Source; var content = Content; return new DelegateProcessor(async (exchange, ct) => { var message = exchange.In; AttachmentContent attachmentContent; string defaultType; var resolvedName = name; var resolvedFileName = fileName is null ? null : Evaluate(fileName, exchange, "file name"); switch (source) { case AttachmentSource.File: { var path = Evaluate(content!, exchange, "file path"); attachmentContent = AttachmentContent.FromFile(path); var bare = Path.GetFileName(path); resolvedName ??= bare; resolvedFileName ??= bare; defaultType = Attachment.DefaultContentType; break; } case AttachmentSource.Body: (attachmentContent, defaultType) = await ToContent(message.Body, "the body", ct).ConfigureAwait(false); defaultType = message.ContentType ?? defaultType; break; default: (attachmentContent, defaultType) = await ToContent(content!.Evaluate(exchange), $"attachment '{resolvedName}'", ct) .ConfigureAwait(false); break; } message.Attachments.Add(new Attachment { Name = resolvedName!, FileName = resolvedFileName, ContentType = contentType ?? defaultType, Content = attachmentContent }); }); } private static async Task<(AttachmentContent Content, string DefaultType)> ToContent(object? value, string what, CancellationToken ct) { switch (value) { case null: throw new InvalidOperationException($"Cannot attach {what}: it is null."); case AttachmentContent ready: return (ready, Attachment.DefaultContentType); case byte[] bytes: return (AttachmentContent.FromBytes(bytes), Attachment.DefaultContentType); case string text: return (AttachmentContent.FromBytes(System.Text.Encoding.UTF8.GetBytes(text)), "text/plain; charset=utf-8"); case StreamCache { CanRead: true } cache: return (AttachmentContent.FromStreamCache(cache), Attachment.DefaultContentType); case Stream stream: { using var buffer = new MemoryStream(); await stream.CopyToAsync(buffer, ct).ConfigureAwait(false); return (AttachmentContent.FromBytes(buffer.ToArray()), Attachment.DefaultContentType); } default: throw new InvalidOperationException( $"Cannot attach {what} of type '{value.GetType().FullName}': use byte[], string, Stream or AttachmentContent."); } } private static string Evaluate(IExpression expression, IExchange exchange, string field) => expression.Evaluate(exchange)?.ToString() is { Length: > 0 } value ? value : throw new InvalidOperationException($"The attachment {field} evaluated to nothing."); } /// Leaf definition that removes the attachments with a name from the In message. public sealed class RemoveAttachmentDefinition : ProcessorDefinition { /// The name of the attachments to remove. public string Name { get; } /// Creates the definition. public RemoveAttachmentDefinition(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); Name = name; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Attachments.Remove(Name)); } /// Leaf definition that removes every attachment of the In message. public sealed class RemoveAttachmentsDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Attachments.Clear()); } Path: redb-route/redb.Route/Definitions/ChoiceDefinition.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/Definitions/ChoiceDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Expressions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Content-based router scope opener (Choice EIP). /// Add branches with / . /// Close with . /// /// Inherits the entire leaf DSL from ; /// however, leaf calls placed directly on a Choice scope are not part of the /// standard EIP shape — use When / Otherwise branches instead. /// /// public class ChoiceDefinition : RouteDefinitionBase, IRouteScope, ICompositeScope, IBranchingDefinition { private readonly List _whens = []; private OtherwiseDefinition? _otherwise; /// All registered When branches, in declaration order. public IReadOnlyList Whens => _whens; /// The Otherwise branch (null if not declared). public OtherwiseDefinition? OtherwiseBranch => _otherwise; /// /// The When/Otherwise branches — logical children that live outside , so a /// generic tree-walk (validation) can reach steps nested inside a branch. /// public IEnumerable Branches { get { foreach (var when in _whens) yield return when; if (_otherwise is not null) yield return _otherwise; } } // ── Branch builders ─────────────────────────────────────────────────────── /// Opens a When branch with a bool predicate. public WhenDefinition When(Func predicate) { ArgumentNullException.ThrowIfNull(predicate); var when = new WhenDefinition(predicate, this); _whens.Add(when); return when; } /// Opens a When branch with an predicate. public WhenDefinition When(IExpression expression) { ArgumentNullException.ThrowIfNull(expression); var when = new WhenDefinition(Predicates.PredicateFactory.FromExpression(expression), this); _whens.Add(when); when.SourceExpression = expression; return when; } /// Opens a When branch guarded by an ; the predicate is /// stored as the branch condition and awaited per message. public WhenDefinition When(IPredicate predicate) { ArgumentNullException.ThrowIfNull(predicate); var when = new WhenDefinition(predicate, this); _whens.Add(when); when.SourcePredicate = predicate; return when; } /// Apache Camel nested-lambda overload: opens a When branch with the given predicate, /// populates it via , and returns this /// so further When/Otherwise branches can be chained. public ChoiceDefinition When(Func predicate, Action branch) { ArgumentNullException.ThrowIfNull(branch); var w = When(predicate); branch(w); return this; } /// Nested-lambda overload accepting an predicate. public ChoiceDefinition When(IExpression expression, Action branch) { ArgumentNullException.ThrowIfNull(branch); var w = When(expression); branch(w); return this; } /// Nested-lambda overload accepting an , as does: /// .When(Header("type").isEqualTo("order"), r => r.To(...)). public ChoiceDefinition When(IPredicate predicate, Action branch) { ArgumentNullException.ThrowIfNull(branch); var w = When(predicate); branch(w); return this; } /// Nested-lambda Otherwise overload. public ChoiceDefinition Otherwise(Action branch) { ArgumentNullException.ThrowIfNull(branch); branch(Otherwise()); return this; } /// Opens the Otherwise (fallback) branch. /// Thrown if Otherwise was already set. public OtherwiseDefinition Otherwise() { if (_otherwise != null) throw new InvalidOperationException("Otherwise() can only be called once per Choice scope."); _otherwise = new OtherwiseDefinition(this); return _otherwise; } /// Closes this choice scope and returns the parent route definition. public IRouteDefinition EndChoice() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndChoice() called without a parent route.")); /// public IRouteDefinition End() => EndChoice(); // ── IProcessorDefinition ────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { var choice = new ChoiceProcessor(); foreach (var when in _whens) { IProcessor body = BuildPipeline(when.Outputs, context); choice.When(when.Condition, body); } if (_otherwise != null) { choice.SetOtherwise(BuildPipeline(_otherwise.Outputs, context)); } return choice; } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } /// /// A single When branch inside a . /// Inherits the leaf DSL from ; close with /// , , or . /// public class WhenDefinition : RouteDefinitionBase, IRouteScope, ICompositeScope, IConditionSource { internal readonly IPredicate Condition; private readonly ChoiceDefinition _choice; /// public IPredicate? SourcePredicate { get; internal set; } /// public IExpression? SourceExpression { get; internal set; } /// public string? SourceTemplate { get; internal set; } internal WhenDefinition(IPredicate condition, ChoiceDefinition choice) { Condition = condition ?? throw new ArgumentNullException(nameof(condition)); _choice = choice; Parent = choice; } internal WhenDefinition(Func predicate, ChoiceDefinition choice) : this(new Predicates.LambdaPredicate(predicate ?? throw new ArgumentNullException(nameof(predicate))), choice) { } // ── Navigation ──────────────────────────────────────────────────────────── /// Closes this When branch and returns the parent choice. public ChoiceDefinition EndWhen() => _choice; /// Opens another When branch on the parent choice. public WhenDefinition When(Func predicate) => _choice.When(predicate); /// Opens another When branch with an expression predicate. public WhenDefinition When(IExpression expression) => _choice.When(expression); /// Opens another When branch guarded by an . public WhenDefinition When(IPredicate predicate) => _choice.When(predicate); /// Opens the Otherwise fallback branch on the parent choice. public OtherwiseDefinition Otherwise() => _choice.Otherwise(); /// Closes the entire Choice scope and returns the parent route definition. public IRouteDefinition EndChoice() => _choice.EndChoice(); /// public IRouteDefinition End() => EndChoice(); // ── IProcessorDefinition ────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) => throw new InvalidOperationException( "WhenDefinition is compiled via its parent ChoiceDefinition.CreateProcessor."); } /// /// The Otherwise (fallback) branch inside a . /// Inherits the leaf DSL from ; close with /// or . /// public class OtherwiseDefinition : RouteDefinitionBase, IRouteScope, ICompositeScope { private readonly ChoiceDefinition _choice; internal OtherwiseDefinition(ChoiceDefinition choice) { _choice = choice; Parent = choice; } // ── Navigation ──────────────────────────────────────────────────────────── /// Closes this Otherwise branch and returns the parent choice. public ChoiceDefinition EndOtherwise() => _choice; /// Closes the entire Choice scope and returns the parent route definition. public IRouteDefinition EndChoice() => _choice.EndChoice(); /// public IRouteDefinition End() => EndChoice(); // ── IProcessorDefinition ────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) => throw new InvalidOperationException( "OtherwiseDefinition is compiled via its parent ChoiceDefinition.CreateProcessor."); } Path: redb-route/redb.Route/Definitions/CircuitBreakerDefinition.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/Definitions/CircuitBreakerDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the CircuitBreaker EIP. /// Wraps the downstream pipeline with circuit-breaker protection. /// Optionally define a fallback branch with . /// Inherits the leaf DSL from ; /// child steps build the main downstream pipeline. /// Close with . /// public class CircuitBreakerDefinition : RouteDefinitionBase, IRouteScope, IBranchingDefinition { private int _failureThreshold = 5; private TimeSpan? _resetTimeout; private int _halfOpenMaxCalls = 1; internal FallbackDefinition? FallbackBlock; /// /// The fallback body — a logical child outside (which holds the main /// pipeline), exposed so a generic tree-walk (validation, AdviceWith) reaches steps nested in it. /// public IEnumerable Branches { get { if (FallbackBlock is not null) yield return FallbackBlock; } } internal CircuitBreakerDefinition() { } // ── Options ───────────────────────────────────────────────────────────────── /// Sets the number of consecutive failures before the circuit opens (default: 5). public CircuitBreakerDefinition FailureThreshold(int threshold) { if (threshold <= 0) throw new ArgumentOutOfRangeException(nameof(threshold)); _failureThreshold = threshold; return this; } /// Sets the time to wait in Open state before probing (default: 30 s). public CircuitBreakerDefinition ResetTimeout(TimeSpan timeout) { _resetTimeout = timeout; return this; } /// Sets the maximum probe calls allowed in HalfOpen state (default: 1). public CircuitBreakerDefinition HalfOpenMaxCalls(int count) { if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); _halfOpenMaxCalls = count; return this; } /// Alias for matching the Apache Camel DSL name. public CircuitBreakerDefinition Threshold(int threshold) => FailureThreshold(threshold); // ── Fallback scope ───────────────────────────────────────────────────────── /// /// Opens the fallback scope. Build fallback steps via leaf methods, /// then call or /// . /// /// Thrown if OnFallback was already called. public FallbackDefinition OnFallback() { if (FallbackBlock != null) throw new InvalidOperationException("OnFallback() can only be called once per CircuitBreaker scope."); FallbackBlock = new FallbackDefinition(this); return FallbackBlock; } /// /// Apache Camel nested-lambda style: opens the fallback scope, runs /// against it, and returns the parent so the chain may continue. /// public CircuitBreakerDefinition FallBack(Action configure) { ArgumentNullException.ThrowIfNull(configure); var fb = OnFallback(); configure(fb); return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes the CircuitBreaker scope and returns the parent route definition. public IRouteDefinition EndCircuitBreaker() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndCircuitBreaker() called without a parent route.")); /// public IRouteDefinition End() => EndCircuitBreaker(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor downstream = BuildPipeline(Outputs, context); IProcessor? fallback = FallbackBlock != null ? BuildPipeline(FallbackBlock.Outputs, context) : null; var loggerFactory = context.GetService(); var logger = loggerFactory?.CreateLogger(); return new CircuitBreakerProcessor(downstream, _failureThreshold, _resetTimeout, _halfOpenMaxCalls, fallback, logger); } internal static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } /// /// The fallback branch inside a . /// Inherits the leaf DSL from ; child steps /// build the fallback pipeline executed when the circuit is open. /// Close with or . /// public class FallbackDefinition : RouteDefinitionBase, IRouteScope { private readonly CircuitBreakerDefinition _circuitBreaker; internal FallbackDefinition(CircuitBreakerDefinition circuitBreaker) { _circuitBreaker = circuitBreaker; Parent = circuitBreaker; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes the fallback branch and returns to the parent CircuitBreaker definition. public CircuitBreakerDefinition EndFallback() => _circuitBreaker; /// Closes the entire CircuitBreaker scope. public IRouteDefinition EndCircuitBreaker() => _circuitBreaker.EndCircuitBreaker(); /// public IRouteDefinition End() => EndCircuitBreaker(); /// public override IProcessor CreateProcessor(IRouteContext context) => throw new InvalidOperationException( "FallbackDefinition is compiled via its parent CircuitBreakerDefinition.CreateProcessor."); } Path: redb-route/redb.Route/Definitions/EnrichWireTapDefinition.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/Definitions/EnrichWireTapDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that wires a copy of the exchange to a secondary endpoint (wire tap pattern). /// public sealed class WireTapDefinition : ProcessorDefinition { private readonly string _uri; private readonly Action? _onPrepare; private readonly Func? _newBodyFactory; private readonly string? _executorService; /// Creates a wire tap definition. /// URI of the tap endpoint. /// Optional action to prepare the tapped exchange copy. /// Optional factory to set a different body on the copy. /// /// The thread pool profile the tap builds its pool from; the context's default profile when null. /// public WireTapDefinition( string uri, Action? onPrepare = null, Func? newBodyFactory = null, string? executorService = null) { ArgumentException.ThrowIfNullOrWhiteSpace(uri); _uri = uri; _onPrepare = onPrepare; _newBodyFactory = newBodyFactory; _executorService = executorService; } /// The named thread pool profile, or null for the default one. public string? ExecutorService => _executorService; /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); return new WireTapProcessor(new ToProcessor(_uri, context), _onPrepare, _newBodyFactory, logger, context.GetThreadPoolProfile(_executorService), _executorService, (context as RouteContext)?.CompilingRouteId); } } /// /// Leaf definition that calls an external endpoint and merges the result into the exchange (content enricher). /// public sealed class EnrichDefinition : ProcessorDefinition { private readonly string _resourceUri; private readonly Func _mergeStrategy; /// Creates an enrich definition. /// URI of the enrichment endpoint. /// Merge function: (original, enriched) → merged. public EnrichDefinition( string resourceUri, Func mergeStrategy) { ArgumentException.ThrowIfNullOrWhiteSpace(resourceUri); ArgumentNullException.ThrowIfNull(mergeStrategy); _resourceUri = resourceUri; _mergeStrategy = mergeStrategy; } /// public override IProcessor CreateProcessor(IRouteContext context) => new EnrichProcessor(context, _resourceUri, _mergeStrategy); } /// /// Leaf definition that polls an endpoint and merges the response (poll enricher pattern). /// public sealed class PollEnrichDefinition : ProcessorDefinition { private readonly string _resourceUri; private readonly Func _mergeStrategy; private readonly TimeSpan? _timeout; /// Creates a poll enrich definition. /// URI of the polling endpoint. /// Merge function: (original, polled?) → merged. /// Optional poll timeout. public PollEnrichDefinition( string resourceUri, Func mergeStrategy, TimeSpan? timeout = null) { ArgumentException.ThrowIfNullOrWhiteSpace(resourceUri); ArgumentNullException.ThrowIfNull(mergeStrategy); _resourceUri = resourceUri; _mergeStrategy = mergeStrategy; _timeout = timeout; } /// public override IProcessor CreateProcessor(IRouteContext context) => new PollEnrichProcessor(context, _resourceUri, _mergeStrategy, _timeout); } /// /// Wire-tap definition whose target endpoint URI is computed per message (Camel toD semantics for wire-tap). /// public sealed class WireTapDynamicDefinition : ProcessorDefinition { private readonly Func _uriFactory; private readonly Action? _onPrepare; private readonly Func? _newBodyFactory; private readonly string? _executorService; /// Creates a dynamic-URI wire-tap definition. /// Computes the tap endpoint's URI per message. /// Optional action to prepare the tapped exchange copy. /// Optional factory to set a different body on the copy. /// /// The thread pool profile the tap builds its pool from; the context's default profile when null. /// public WireTapDynamicDefinition( Func uriFactory, Action? onPrepare = null, Func? newBodyFactory = null, string? executorService = null) { _uriFactory = uriFactory ?? throw new ArgumentNullException(nameof(uriFactory)); _onPrepare = onPrepare; _newBodyFactory = newBodyFactory; _executorService = executorService; } /// The named thread pool profile, or null for the default one. public string? ExecutorService => _executorService; /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); var resolver = new DynamicEndpointResolver(context, _uriFactory); return new WireTapProcessor(new ToDynamicProcessor(resolver), _onPrepare, _newBodyFactory, logger, context.GetThreadPoolProfile(_executorService), _executorService, (context as RouteContext)?.CompilingRouteId); } } /// /// Enrich definition whose source endpoint URI is computed per message. /// public sealed class EnrichDynamicDefinition : ProcessorDefinition { private readonly Func _uriFactory; private readonly Func _mergeStrategy; /// Creates a dynamic-URI enrich definition. public EnrichDynamicDefinition( Func uriFactory, Func mergeStrategy) { _uriFactory = uriFactory ?? throw new ArgumentNullException(nameof(uriFactory)); _mergeStrategy = mergeStrategy ?? throw new ArgumentNullException(nameof(mergeStrategy)); } /// public override IProcessor CreateProcessor(IRouteContext context) => new EnrichProcessor(context, new DynamicEndpointResolver(context, _uriFactory), _mergeStrategy); } /// /// Poll-enrich definition whose source endpoint URI is computed per message. /// public sealed class PollEnrichDynamicDefinition : ProcessorDefinition { private readonly Func _uriFactory; private readonly Func _mergeStrategy; private readonly TimeSpan? _timeout; /// Creates a dynamic-URI poll-enrich definition. public PollEnrichDynamicDefinition( Func uriFactory, Func mergeStrategy, TimeSpan? timeout = null) { _uriFactory = uriFactory ?? throw new ArgumentNullException(nameof(uriFactory)); _mergeStrategy = mergeStrategy ?? throw new ArgumentNullException(nameof(mergeStrategy)); _timeout = timeout; } /// public override IProcessor CreateProcessor(IRouteContext context) => new PollEnrichProcessor(context, new DynamicEndpointResolver(context, _uriFactory), _mergeStrategy, _timeout); } /// /// Leaf definition that routes to recipient URIs computed at runtime (recipient list pattern). /// public sealed class RecipientListDefinition : ProcessorDefinition { private readonly Func> _recipientListFactory; private readonly bool _parallelProcessing; private readonly bool _stopOnException; private readonly Func? _aggregationStrategy; /// Creates a recipient list definition. public RecipientListDefinition( Func> recipientListFactory, bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null) { ArgumentNullException.ThrowIfNull(recipientListFactory); _recipientListFactory = recipientListFactory; _parallelProcessing = parallelProcessing; _stopOnException = stopOnException; _aggregationStrategy = aggregationStrategy; } /// public override IProcessor CreateProcessor(IRouteContext context) => new RecipientListProcessor(context, _recipientListFactory, _parallelProcessing, _stopOnException, _aggregationStrategy); } /// /// Leaf definition that routes iteratively to URIs provided by a routing function (dynamic router pattern). /// public sealed class DynamicRouterDefinition : ProcessorDefinition { private readonly Func _routingFunction; /// Creates a dynamic router definition. /// Function returning next URI, or null to stop routing. public DynamicRouterDefinition(Func routingFunction) { ArgumentNullException.ThrowIfNull(routingFunction); _routingFunction = routingFunction; } /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); return new DynamicRouterProcessor(context, _routingFunction, logger); } } /// /// Leaf definition that stores or retrieves the exchange body via a claim check repository. /// public sealed class ClaimCheckDefinition : ProcessorDefinition { private readonly IClaimCheckRepository? _repository; private readonly string? _repositoryName; private readonly ClaimCheckOperation _operation; private readonly string? _key; private readonly TimeSpan? _ttl; /// Creates a claim check definition bound to an explicit repository. public ClaimCheckDefinition( IClaimCheckRepository repository, ClaimCheckOperation operation, string? key = null, TimeSpan? ttl = null) { ArgumentNullException.ThrowIfNull(repository); _repository = repository; _operation = operation; _key = key; _ttl = ttl; } /// /// Creates a claim check definition whose repository is resolved from the route context /// at compile time: by if given, otherwise the context /// default (see ). /// public ClaimCheckDefinition( ClaimCheckOperation operation, string? key = null, TimeSpan? ttl = null, string? repositoryName = null) { _operation = operation; _key = key; _ttl = ttl; _repositoryName = repositoryName; } /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); var repository = _repository ?? context.ResolveClaimCheckRepository(_repositoryName); return new ClaimCheckProcessor(repository, _operation, _key, _ttl, logger); } } Path: redb-route/redb.Route/Definitions/FilterDefinition.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/Definitions/FilterDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Expressions; using redb.Route.Predicates; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Filter EIP. /// When is called, compiles all child /// into an inner pipeline wrapped by a . /// Close the scope with . /// /// Inherits the entire fluent leaf-DSL from /// with = ; calls like /// To(...), Process(...), SetBody(...) therefore return /// directly without locally-redeclared overloads. /// /// public class FilterDefinition : RouteDefinitionBase, IRouteScope, ICompositeScope, IConditionSource { private readonly IPredicate _predicate; /// public IPredicate? SourcePredicate { get; internal set; } /// public IExpression? SourceExpression { get; internal set; } /// public string? SourceTemplate { get; internal set; } internal FilterDefinition(IPredicate predicate) { ArgumentNullException.ThrowIfNull(predicate); _predicate = predicate; } internal FilterDefinition(Func predicate) : this(new LambdaPredicate(predicate ?? throw new ArgumentNullException(nameof(predicate)))) { } /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor body = NodePipeline.Body(context, Outputs); return new FilterProcessor(_predicate, body); } /// Closes this filter scope and returns the parent route definition. /// Thrown if no parent route is set. public IRouteDefinition EndFilter() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndFilter() called without a parent route. Ensure Filter() was called on a route definition.")); /// public IRouteDefinition End() => EndFilter(); } Path: redb-route/redb.Route/Definitions/IdempotentConsumerDefinition.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/Definitions/IdempotentConsumerDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Expressions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Idempotent Consumer EIP. /// When is called, compiles all child /// into an inner pipeline wrapped by an . /// Inherits the leaf DSL from ; /// close the scope with . /// public class IdempotentConsumerDefinition : RouteDefinitionBase, IRouteScope { private readonly IIdempotentRepository? _repository; private readonly string? _repositoryName; private readonly Func _keyExtractor; private readonly bool _skipDuplicate; internal IdempotentConsumerDefinition( IIdempotentRepository repository, Func keyExtractor, bool skipDuplicate = true) { ArgumentNullException.ThrowIfNull(repository); ArgumentNullException.ThrowIfNull(keyExtractor); _repository = repository; _keyExtractor = keyExtractor; _skipDuplicate = skipDuplicate; } internal IdempotentConsumerDefinition( string repositoryName, Func keyExtractor, bool skipDuplicate = true) { ArgumentException.ThrowIfNullOrEmpty(repositoryName); ArgumentNullException.ThrowIfNull(keyExtractor); _repositoryName = repositoryName; _keyExtractor = keyExtractor; _skipDuplicate = skipDuplicate; } /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor inner = NodePipeline.Body(context, Outputs); var loggerFactory = context.GetService(); var logger = loggerFactory?.CreateLogger(); var repo = _repository ?? context .GetIdempotentRepositoryProvider() .Get(_repositoryName!); return new IdempotentConsumerProcessor(inner, repo, _keyExtractor, _skipDuplicate, logger); } /// Closes this idempotent consumer scope and returns the parent route definition. /// Thrown if no parent route is set. public IRouteDefinition EndIdempotentConsumer() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndIdempotentConsumer() called without a parent route. Ensure IdempotentConsumer() was called on a route definition.")); /// public IRouteDefinition End() => EndIdempotentConsumer(); } Path: redb-route/redb.Route/Definitions/InterceptDefinition.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/Definitions/InterceptDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Predicates; namespace redb.Route.Definitions; /// Where an fires. public enum InterceptKind { /// Before every step of the route (Camel intercept()). EveryStep, /// Once, when a message enters the route (Camel interceptFrom()). From, /// Before a To / ToD whose target URI matches the mask (Camel interceptSendToEndpoint()). SendToEndpoint, } /// /// An interception scope: its steps run before the intercepted point, optionally only when a /// condition holds. Declared on a route (From(...).Intercept()...EndIntercept()) or on the /// RouteBuilder for every route it defines. Intercepts are not steps of the route — they are /// decorators applied when the route is compiled, so they reach steps nested in Choice, /// Split, Multicast, TryCatch and every other scope. /// /// For the target URI is available to the intercept steps /// in the exchange property CamelToEndpoint (), as in Apache Camel; /// /// makes the interception replace the send (dry runs, test doubles). A Stop() inside the /// intercept stops the exchange as anywhere else. /// /// public sealed class InterceptDefinition : RouteDefinitionBase, IRouteScope { internal InterceptDefinition(InterceptKind kind, string? uriPattern) { if (kind == InterceptKind.SendToEndpoint) ArgumentException.ThrowIfNullOrWhiteSpace(uriPattern); // A blank From mask is a mistake, not "every consumer": refused here, where the author sees it, // instead of failing the mask match at compile and silently dropping the whole route. if (kind == InterceptKind.From && uriPattern is not null && string.IsNullOrWhiteSpace(uriPattern)) throw new ArgumentException("InterceptFrom(mask): the mask is blank. Omit it to intercept every consumer, or give a URI mask.", nameof(uriPattern)); // An invalid regex: mask fails here, where the author sees it, not inside route compilation. if (uriPattern is not null) redb.Route.Core.UriMask.Validate(uriPattern, nameof(uriPattern)); Kind = kind; UriPattern = uriPattern; } /// Where the intercept fires. public InterceptKind Kind { get; } /// URI mask (exact, trailing *, or regex:); null for and an unrestricted . public string? UriPattern { get; } /// Optional condition; when it does not hold the intercepted point runs untouched. public IPredicate? Condition { get; private set; } /// For : the original send is not performed. public bool SkipsOriginal { get; private set; } /// Applies the intercept only when the route-language condition holds ("property.dryRun"). public InterceptDefinition When(string condition) { ArgumentException.ThrowIfNullOrWhiteSpace(condition); return When(PredicateFactory.FromString(condition)); } /// Applies the intercept only when holds. public InterceptDefinition When(IPredicate predicate) { Condition = predicate ?? throw new ArgumentNullException(nameof(predicate)); return this; } /// Applies the intercept only when holds. public InterceptDefinition When(Func predicate) { ArgumentNullException.ThrowIfNull(predicate); return When(new LambdaPredicate(predicate)); } /// Do not send to the original endpoint after the intercept steps (only for ). public InterceptDefinition SkipSendToOriginalEndpoint() { if (Kind != InterceptKind.SendToEndpoint) throw new InvalidOperationException("SkipSendToOriginalEndpoint() applies to InterceptSendToEndpoint(...) only."); SkipsOriginal = true; return this; } /// Closes the scope and returns to the route it was declared on. public IRouteDefinition EndIntercept() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndIntercept() on a builder-level intercept: it has no parent route — stop chaining instead.")); /// public IRouteDefinition End() => EndIntercept(); /// Compiles the intercept body (its steps as a pipeline). The context wraps route steps with it. public override IProcessor CreateProcessor(IRouteContext context) => NodePipeline.Body(context, Outputs); } Path: redb-route/redb.Route/Definitions/LoadBalancerDefinition.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/Definitions/LoadBalancerDefinition.cs ---- using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Processors.LoadBalancer; namespace redb.Route.Definitions; /// /// Definition for a Load Balancer step. Collects configuration and creates a /// at route-build time. /// public sealed class LoadBalancerDefinition : ProcessorDefinition, ILoadBalancerDefinition { /// Target endpoint URIs to balance across. public string[]? Endpoints { get; private set; } /// The load balancer strategy. public ILoadBalancerStrategy? Strategy { get; private set; } // ── ILoadBalancerDefinition — explicit to avoid name conflicts with properties ── ILoadBalancerDefinition ILoadBalancerDefinition.Endpoints(params string[] uris) { Endpoints = uris ?? throw new ArgumentNullException(nameof(uris)); return this; } ILoadBalancerDefinition ILoadBalancerDefinition.Strategy(ILoadBalancerStrategy strategy) { Strategy = strategy ?? throw new ArgumentNullException(nameof(strategy)); return this; } /// public ILoadBalancerDefinition UseRoundRobin() { Strategy = new RoundRobinStrategy(); return this; } /// public ILoadBalancerDefinition UseRandom() { Strategy = new RandomStrategy(); return this; } /// public ILoadBalancerDefinition UseFailover() { Strategy = new FailoverStrategy(); return this; } /// public ILoadBalancerDefinition UseSticky(Func correlationKeyExtractor) { ArgumentNullException.ThrowIfNull(correlationKeyExtractor); Strategy = new StickyStrategy(correlationKeyExtractor!); return this; } /// public ILoadBalancerDefinition UseWeighted(Dictionary weights) { ArgumentNullException.ThrowIfNull(weights); var entries = weights.Select(kv => (kv.Key, kv.Value)).ToList(); Strategy = new WeightedStrategy(entries); return this; } /// public override IProcessor CreateProcessor(IRouteContext context) { if (Strategy is null) throw new InvalidOperationException( "Strategy is required for LoadBalance. Use UseRoundRobin(), UseFailover(), etc."); if (Endpoints is null || Endpoints.Length == 0) throw new InvalidOperationException("At least one endpoint is required for LoadBalance."); var logger = context.GetService()?.CreateLogger(); return new LoadBalancerProcessor(context, Endpoints, Strategy, logger); } } Path: redb-route/redb.Route/Definitions/LogDefinition.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/Definitions/LogDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that logs a static message. /// public sealed class LogStaticDefinition : ProcessorDefinition { private readonly string _message; private readonly LogLevel _level; /// The static log message (may contain ${...} placeholders). public string Message => _message; /// The log level. public LogLevel Level => _level; /// Creates a static log definition. public LogStaticDefinition(string message, LogLevel level = LogLevel.Information) { ArgumentException.ThrowIfNullOrWhiteSpace(message); _message = message; _level = level; } /// public override IProcessor CreateProcessor(IRouteContext context) { var loggerFactory = context.GetService(); var logger = loggerFactory?.CreateLogger("redb.Route"); // If the message contains ${...} placeholders, route through the template // processor so .Log("...${header.x}...") in DSL just works — the placeholder // form and the plain form share this one definition. if (_message.Contains("${", StringComparison.Ordinal)) return new TemplateLogProcessor(_message, _level, logger); if (logger != null) return new LogProcessor(logger, _message, _level); return new DelegateProcessor(_ => { }); } } /// /// Leaf definition that logs a message produced by a factory function. /// public sealed class LogDynamicDefinition : ProcessorDefinition { private readonly Func _messageFactory; private readonly LogLevel _level; /// Creates a dynamic log definition. public LogDynamicDefinition(Func messageFactory, LogLevel level = LogLevel.Information) { ArgumentNullException.ThrowIfNull(messageFactory); _messageFactory = messageFactory; _level = level; } /// public override IProcessor CreateProcessor(IRouteContext context) { var loggerFactory = context.GetService(); if (loggerFactory != null) { var logger = loggerFactory.CreateLogger("redb.Route"); return new LogProcessor(logger, _messageFactory, _level); } return new DelegateProcessor(_ => { }); } } /// /// Scope-opener definition for rich log output. Collects messages, headers, properties, /// and log level. Build content with , /// , , , /// then close with or . /// public sealed class RichLogScopeDefinition : ProcessorDefinition, IRouteScope { private readonly List _messages = []; private readonly List> _messageFuncs = []; private readonly List _headerNames = []; private readonly List _propertyNames = []; private bool _showRouteId; /// The log level for all output from this scope. public LogLevel Level { get; } /// Static log messages added via . public IReadOnlyList Messages => _messages; /// Dynamic log message factories added via . public IReadOnlyList> MessageFuncs => _messageFuncs; /// Header names to include in log output. public IReadOnlyList HeaderNames => _headerNames; /// Property names to include in log output. public IReadOnlyList PropertyNames => _propertyNames; /// Whether the route ID is included in log output. public bool IncludeRouteId => _showRouteId; internal RichLogScopeDefinition(LogLevel level) { Level = level; } // ── Configuration ───────────────────────────────────────────────────────── /// Adds a static message to the log output. public RichLogScopeDefinition Message(string message) { ArgumentException.ThrowIfNullOrWhiteSpace(message); _messages.Add(message); return this; } /// Adds a dynamic message factory to the log output. public RichLogScopeDefinition Message(Func messageFactory) { ArgumentNullException.ThrowIfNull(messageFactory); _messageFuncs.Add(messageFactory); return this; } /// Includes the specified header value in log output. public RichLogScopeDefinition Header(string headerName) { ArgumentException.ThrowIfNullOrWhiteSpace(headerName); _headerNames.Add(headerName); return this; } /// Includes the specified exchange property in log output. public RichLogScopeDefinition Property(string propertyName) { ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); _propertyNames.Add(propertyName); return this; } /// Includes the route ID in log output. public RichLogScopeDefinition ShowRouteId(bool value = true) { _showRouteId = value; return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this rich-log scope and returns the parent route definition. public IRouteDefinition EndLog() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndLog() called without a parent route.")); /// public IRouteDefinition End() => EndLog(); // ── IProcessorDefinition ────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { var loggerFactory = context.GetService(); if (loggerFactory != null) { var logger = loggerFactory.CreateLogger("redb.Route"); return new RichLogProcessor(logger, Level, _messages, _messageFuncs, _headerNames, _propertyNames, _showRouteId); } return new DelegateProcessor(_ => { }); } } Path: redb-route/redb.Route/Definitions/LoopDefinition.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/Definitions/LoopDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Loop EIP. /// Repeats the body pipeline either a fixed number of times, a dynamic number of times /// resolved from the exchange, or while a predicate holds. Inherits the leaf DSL from /// ; close with . /// public class LoopDefinition : RouteDefinitionBase, IRouteScope { private enum LoopMode { Count, CountFactory, While } private readonly LoopMode _mode; private readonly int _count; private readonly Func? _countFactory; private readonly IPredicate? _condition; private readonly bool _copy; private readonly bool _shareScope; /// Creates a count-based loop definition. internal LoopDefinition(int count, bool copy, bool shareScope) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), "Must be non-negative."); _mode = LoopMode.Count; _count = count; _copy = copy; _shareScope = shareScope; } /// Creates a dynamic-count loop definition. internal LoopDefinition(Func countFactory, bool copy, bool shareScope) { ArgumentNullException.ThrowIfNull(countFactory); _mode = LoopMode.CountFactory; _countFactory = countFactory; _copy = copy; _shareScope = shareScope; } /// Creates a while-condition loop definition. internal LoopDefinition(IPredicate condition, bool copy, bool shareScope) { ArgumentNullException.ThrowIfNull(condition); _mode = LoopMode.While; _condition = condition; _copy = copy; _shareScope = shareScope; } internal LoopDefinition(Func condition, bool copy, bool shareScope) : this(new Predicates.LambdaPredicate(condition ?? throw new ArgumentNullException(nameof(condition))), copy, shareScope) { } /// Whether each iteration receives an independent clone of the exchange. public bool Copy => _copy; // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this loop scope and returns the parent route definition. public IRouteDefinition EndLoop() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndLoop() called without a parent route.")); /// public IRouteDefinition End() => EndLoop(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { var body = BuildPipeline(Outputs, context); if (_mode == LoopMode.Count) return new LoopProcessor(body, _count, _copy, _shareScope); if (_mode == LoopMode.CountFactory) return new LoopProcessor(body, _countFactory!, _copy, _shareScope); return new LoopProcessor(body, _condition!, _copy, _shareScope); } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } Path: redb-route/redb.Route/Definitions/MeteredDefinition.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/Definitions/MeteredDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.Definitions; /// /// Scope-opener definition for per-step metrics collection. /// All child steps run inside a single that records /// redb.route.step.processed, redb.route.step.failed, /// and redb.route.step.duration tagged with . /// Inherits the leaf DSL from ; /// close with or the universal . /// public class MeteredDefinition : RouteDefinitionBase, IRouteScope { /// Step name used as a metric tag value for redb.route.step. public string StepName { get; } private readonly List<(string Name, Func Resolver)> _tagProviders = new(); /// Tag providers evaluated per message to enrich the recorded metrics with low-cardinality dimensions. public IReadOnlyList<(string Name, Func Resolver)> TagProviders => _tagProviders; internal MeteredDefinition(string stepName) { ArgumentException.ThrowIfNullOrWhiteSpace(stepName); StepName = stepName; } /// /// Adds a dimension/label evaluated per message. Use only with bounded value domains /// (status codes, tenant ids from a small set, etc.) to keep cardinality under control. /// public MeteredDefinition Tag(string name, Func resolver) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(resolver); _tagProviders.Add((name, resolver)); return this; } /// Convenience: tag the metric with the value of a header. public MeteredDefinition TagFromHeader(string tagName, string headerName) { ArgumentException.ThrowIfNullOrWhiteSpace(headerName); return Tag(tagName, e => e.In.Headers.TryGetValue(headerName, out var v) ? v : null); } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this metered scope and returns the parent route definition. /// Thrown if no parent route is set. public IRouteDefinition EndMetered() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndMetered() called without a parent route. Ensure Metered() was called on a route definition.")); /// public IRouteDefinition End() => EndMetered(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor body = BuildPipeline(Outputs, context); return new MeteredStepProcessor(body, StepName, _tagProviders.Count > 0 ? _tagProviders.ToArray() : null); } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } Path: redb-route/redb.Route/Definitions/MiscDefinition.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/Definitions/MiscDefinition.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Definitions; /// /// Leaf definition that begins an imperative transaction scope on the exchange. /// public sealed class BeginTransactionDefinition : ProcessorDefinition { private readonly TransactionPolicy? _policy; /// Creates a begin-transaction definition. /// Transaction policy (null = default Required). public BeginTransactionDefinition(TransactionPolicy? policy = null) { _policy = policy; } /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); return new BeginTransactionProcessor(_policy, logger); } } /// /// Leaf definition that commits the imperative transaction scope and all deferred actions. /// public sealed class CommitTransactionDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); return new CommitTransactionProcessor(logger); } } /// /// Leaf definition that rolls back the imperative transaction scope and all deferred actions. /// public sealed class RollbackTransactionDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); return new RollbackTransactionProcessor(logger); } } /// /// Leaf definition for .RollbackAll(), Camel's markRollbackOnly(): marks the unit of work for rollback, /// rolls back the deferred sends and stops the route. The enclosing .Transacted() block then rolls the database /// back without an exception, and the consumer does not acknowledge the message. /// public sealed class RollbackAllDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); return new DelegateProcessor(async (exchange, ct) => { exchange.MarkRollbackOnly(); // An imperative block is rolled back here: the route stops, so its CommitTransaction never runs. if (exchange.Properties.ContainsKey(BeginTransactionProcessor.ScopePropertyKey)) await new RollbackTransactionProcessor(logger).Process(exchange, ct).ConfigureAwait(false); else await TransactedActions.RollbackAll(exchange, logger, ct).ConfigureAwait(false); exchange.Stop(); }); } } /// /// Leaf definition that sets the exchange pattern. /// public sealed class SetPatternDefinition : ProcessorDefinition { private readonly ExchangePattern _pattern; /// Creates a set-pattern definition. public SetPatternDefinition(ExchangePattern pattern) { _pattern = pattern; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.Pattern = _pattern); } /// /// Leaf definition that creates an Out response by applying a factory to the exchange. /// public sealed class RespondDefinition : ProcessorDefinition { private readonly Func _factory; /// Creates a respond definition. public RespondDefinition(Func factory) { ArgumentNullException.ThrowIfNull(factory); _factory = factory; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => { var responseBody = _factory(exchange); exchange.Out = exchange.In.Clone(); exchange.Out.Body = responseBody; }); } /// /// Leaf definition that resolves a DI service and invokes a method on it (service activator/bean). /// public sealed class BeanDefinition : ProcessorDefinition { private readonly Type _serviceType; private readonly Func _method; /// Service type resolved from DI. public Type ServiceType => _serviceType; /// Normalized delegate invoked with (service, exchange, ct). public Func Method => _method; /// Creates a bean definition. /// Service type to resolve from the exchange's ServiceProvider. /// Normalized delegate: (service, exchange, ct) → Task. public BeanDefinition(Type serviceType, Func method) { ArgumentNullException.ThrowIfNull(serviceType); ArgumentNullException.ThrowIfNull(method); _serviceType = serviceType; _method = method; } /// public override IProcessor CreateProcessor(IRouteContext context) { var serviceType = _serviceType; var method = _method; return new DelegateProcessor(async (exchange, ct) => { var provider = exchange.ServiceProvider ?? throw new InvalidOperationException( $"Bean<{serviceType.Name}> requires a ServiceProvider on the exchange. " + "Ensure the route context is configured with DI."); var service = provider.GetRequiredService(serviceType); await method(service, exchange, ct).ConfigureAwait(false); }); } } /// /// Leaf definition that wraps a forward-only body with a seekable /// -backed cache, enabling multiple re-reads. /// Non-Stream bodies pass through unchanged. /// Equivalent to Apache Camel's streamCaching() inline DSL step. /// public sealed class StreamCachingDefinition : ProcessorDefinition { private readonly long? _spoolThreshold; /// Creates a stream caching definition. /// Bytes threshold before spooling to disk (null = default 128 KB). public StreamCachingDefinition(long? spoolThreshold = null) { _spoolThreshold = spoolThreshold; } /// public override IProcessor CreateProcessor(IRouteContext context) { var globalOptions = Extensions.RouteContextExtensions.GetStreamCacheOptions(context); var options = _spoolThreshold.HasValue ? new Configuration.StreamCacheOptions { SpoolThreshold = _spoolThreshold.Value, TempDirectory = globalOptions.TempDirectory, } : globalOptions; return new Processors.StreamCachingTransformer(options); } } Path: redb-route/redb.Route/Definitions/NodePipeline.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/Definitions/NodePipeline.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// The single place where a scope definition's child steps are compiled into a body processor. /// /// Previously every scope definition (Choice, Filter, CircuitBreaker, TryCatch, Loop, Metered, /// Replayable, Aggregate, IdempotentConsumer, Resequence, Threads, Traced, Transaction, Throttle, /// Debounce, …) carried its own identical copy of the "0 → no-op / 1 → the single child / N → a /// pipeline" logic. Routing them all through removes that duplication and — because /// every child now compiles through — gives one seam to decorate each node (e.g. /// Message History) at compile time. /// /// /// Behaviour is identical to the old per-definition builders: the empty body is a no-op /// ; a single child is returned unwrapped; multiple children form a /// . This does not touch the DSL — the Outputs/scope tree /// the builders walk is built entirely by the fluent API and its End* closers. /// /// public static class NodePipeline { /// /// Compiles one child definition into its runtime processor — the per-node seam. Routes through /// when the context is a (so a /// node can be decorated), falling back to a plain compile otherwise (e.g. a test double). /// public static IProcessor Node(IRouteContext context, IProcessorDefinition definition) => context is RouteContext rc ? rc.CompileNode(definition) : definition.CreateProcessor(context); /// Compiles a list of child definitions into a body processor (0 → no-op, 1 → the child, N → pipeline). public static IProcessor Body(IRouteContext context, IList outputs) => outputs.Count switch { 0 => new DelegateProcessor(_ => { }), 1 => Node(context, outputs[0]), _ => BuildMulti(context, outputs), }; private static PipelineProcessor BuildMulti(IRouteContext context, IList outputs) { var pipeline = new PipelineProcessor(); foreach (var output in outputs) pipeline.Add(Node(context, output)); return pipeline; } } Path: redb-route/redb.Route/Definitions/NormalizerDefinition.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/Definitions/NormalizerDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Definition for a Normalizer step. Collects when-clauses and builds a /// with transform branches at route-build time. /// public sealed class NormalizerDefinition : ProcessorDefinition, INormalizerDefinition { private readonly List<(Func Predicate, Func Transform)> _clauses = new(); private Func? _otherwise; /// public INormalizerDefinition When( Func predicate, Func transform) { ArgumentNullException.ThrowIfNull(predicate); ArgumentNullException.ThrowIfNull(transform); _clauses.Add((predicate, transform)); return this; } /// public INormalizerDefinition WhenContentType( string contentType, Func transform) { ArgumentNullException.ThrowIfNull(contentType); ArgumentNullException.ThrowIfNull(transform); Func predicate = e => string.Equals( e.In.Headers.TryGetValue("ContentType", out var ct) ? ct?.ToString() : null, contentType, StringComparison.OrdinalIgnoreCase); _clauses.Add((predicate, transform)); return this; } /// public INormalizerDefinition Otherwise(Func transform) { ArgumentNullException.ThrowIfNull(transform); _otherwise = transform; return this; } /// True when no When-clauses have been added yet (used for eager validation in v2 DSL). internal bool IsEmpty => _clauses.Count == 0; /// public override IProcessor CreateProcessor(IRouteContext context) { if (_clauses.Count == 0) throw new InvalidOperationException("Normalizer requires at least one When clause."); var choice = new ChoiceProcessor(); foreach (var (predicate, transform) in _clauses) { var t = transform; choice.When(predicate, new DelegateProcessor(e => { e.In.Body = t(e); })); } if (_otherwise is not null) { var otherwise = _otherwise; choice.SetOtherwise(new DelegateProcessor(e => { e.In.Body = otherwise(e); })); } return choice; } } Path: redb-route/redb.Route/Definitions/OfTypeDefinition.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/Definitions/OfTypeDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; using redb.Route.Serialization; namespace redb.Route.Definitions; /// /// Typed scope-opener that converts the exchange body to /// (via ) and then runs the contained child outputs /// with the body strongly typed as . Apache Camel parity: /// .OfType<T>() equivalent of choice().when(body().isInstanceOf(T.class)) /// combined with a transparent unmarshal step. /// public class OfTypeDefinition : RouteDefinitionBase> { internal OfTypeDefinition() { } /// public override IProcessor CreateProcessor(IRouteContext context) { var pipeline = new PipelineProcessor(); // Skip ConvertBody when target type is string and body may not be string — // ConvertBodyProcessor handles the "already-of-target-type" pass-through itself, // but we elide it for the trivial string passthrough to match Camel semantics. if (typeof(T) != typeof(string)) pipeline.Add(new ConvertBodyProcessor(typeof(T), context.GetService())); foreach (var output in Outputs) pipeline.Add(NodePipeline.Node(context, output)); return pipeline; } // ── Typed overloads ──────────────────────────────────────────────────────── /// Typed Process: invoked with the body cast to . public OfTypeDefinition Process(Action action) { ArgumentNullException.ThrowIfNull(action); AddOutput(new ProcessActionDefinition(e => { if (e.In.Body is T typed) action(typed); })); return this; } /// Typed Transform: receives the body as and assigns the result back. public OfTypeDefinition Transform(Func transform) { ArgumentNullException.ThrowIfNull(transform); AddOutput(new TransformDefinition(e => e.In.Body is T typed ? transform(typed) : e.In.Body)); return this; } /// Typed inline Filter: keep only exchanges whose body matches the typed predicate. public OfTypeFilterDefinition Filter(Func predicate) { ArgumentNullException.ThrowIfNull(predicate); var def = new OfTypeFilterDefinition(e => e.In.Body is T typed && predicate(typed)); AddOutput(def); return def; } } /// /// Typed filter scope used inside an . Re-exposes typed /// and overloads. /// public sealed class OfTypeFilterDefinition : FilterDefinition { internal OfTypeFilterDefinition(Func predicate) : base(predicate) { } /// Typed Process inside the filter scope. public new OfTypeFilterDefinition Process(Action action) { ArgumentNullException.ThrowIfNull(action); AddOutput(new ProcessActionDefinition(e => { if (e.In.Body is T typed) action(typed); })); return this; } /// Typed Transform inside the filter scope. public new OfTypeFilterDefinition Transform(Func transform) { ArgumentNullException.ThrowIfNull(transform); AddOutput(new TransformDefinition(e => e.In.Body is T typed ? transform(typed) : e.In.Body)); return this; } } Path: redb-route/redb.Route/Definitions/OnCompletionDefinition.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/Definitions/OnCompletionDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Predicates; namespace redb.Route.Definitions; /// When an runs. public enum CompletionMode { /// After success and after failure. Always, /// Only when the exchange completed without a propagated exception (a handled error counts as complete). OnCompleteOnly, /// Only when the exchange escaped the route with an exception. OnFailureOnly, } /// /// Steps that run after the route has finished with an exchange (Camel onCompletion): audit, /// notifications, cleanup. They receive a copy of the exchange, run outside the route's /// transaction and error handlers, and never change the route's own result. As in Camel, they run in the /// caller once the route has finished, and the caller waits for them; or /// runs them on a bounded pool of their own instead, and /// runs them before the consumer gets the reply (HTTP / SOAP, where the reply /// is the consumer's job). A block after the consumer never gets the caller's cancellation: an aborted request /// does not cut it half way. /// Declared on a route or on the RouteBuilder for every route it defines. /// public sealed class OnCompletionDefinition : RouteDefinitionBase, IRouteScope { internal OnCompletionDefinition() { } /// Success, failure or both. Default . public CompletionMode Mode { get; private set; } = CompletionMode.Always; /// Optional condition evaluated on the copy; when it does not hold the steps are skipped. public IPredicate? Condition { get; private set; } /// Run before the consumer receives the reply instead of asynchronously after it. public bool BeforeConsumer { get; private set; } /// Run only after a successful exchange. public OnCompletionDefinition OnCompleteOnly() { Mode = CompletionMode.OnCompleteOnly; return this; } /// Run only after a failed exchange (the exception is on the copy). public OnCompletionDefinition OnFailureOnly() { Mode = CompletionMode.OnFailureOnly; return this; } /// Run only when the route-language condition holds ("header.audit"). public OnCompletionDefinition When(string condition) { ArgumentException.ThrowIfNullOrWhiteSpace(condition); return When(PredicateFactory.FromString(condition)); } /// Run only when holds. public OnCompletionDefinition When(IPredicate predicate) { Condition = predicate ?? throw new ArgumentNullException(nameof(predicate)); return this; } /// Run only when holds. public OnCompletionDefinition When(Func predicate) { ArgumentNullException.ThrowIfNull(predicate); return When(new LambdaPredicate(predicate)); } /// Run synchronously before the consumer receives the reply. public OnCompletionDefinition ModeBeforeConsumer() { BeforeConsumer = true; return this; } /// Whether the block runs on a pool of its own instead of in the caller (Camel parallelProcessing). public bool IsParallelProcessing { get; private set; } /// The thread pool profile the block's pool is built from; null for the default profile. public string? ExecutorServiceName { get; private set; } /// /// Run the block on a pool of its own built from the context's default thread pool profile, so the caller does not /// wait for it (Camel parallelProcessing). Without it the block runs in the caller once the route has finished. /// public OnCompletionDefinition ParallelProcessing() { IsParallelProcessing = true; return this; } /// /// Run the block on a pool of its own built from the named thread pool profile (Camel executorService, which /// implies parallelProcessing). An unknown name fails when the route is built. /// public OnCompletionDefinition ExecutorService(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ExecutorServiceName = name; IsParallelProcessing = true; return this; } /// Closes the scope and returns to the route it was declared on. public IRouteDefinition EndOnCompletion() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndOnCompletion() on a builder-level OnCompletion: it has no parent route — stop chaining instead.")); /// public IRouteDefinition End() => EndOnCompletion(); /// Compiles the completion steps as a pipeline; the context runs it after the route. public override IProcessor CreateProcessor(IRouteContext context) => NodePipeline.Body(context, Outputs); } Path: redb-route/redb.Route/Definitions/OnExceptionDefinition.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/Definitions/OnExceptionDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Predicates; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for route-level exception handling. /// Wraps the child pipeline with an that /// retries, handles, or continues on the configured exception types. /// Configure redelivery settings with , /// , etc., then close with or /// . Inherits the leaf DSL from ; /// child steps build the handler body. /// public class OnExceptionDefinition : RouteDefinitionBase, IRouteScope { private readonly List _exceptionTypes; private int _maxRedeliveries; private TimeSpan? _redeliveryDelay; private double _backoffMultiplier = 1.0; private bool _useExponentialBackoff; private bool _handled; private bool _continued; // ── Public properties for test/inspection ───────────────────────────────── /// Exception types this handler applies to. public IReadOnlyList ExceptionTypes => _exceptionTypes; /// Maximum number of redelivery (retry) attempts. public int MaxRedeliveries => _maxRedeliveries; /// Delay between retry attempts (null = default 1 second). Inspection accessor. public TimeSpan? RedeliveryDelayValue => _redeliveryDelay; /// Backoff multiplier applied to the delay after each retry. public double BackoffMultiplierValue => _backoffMultiplier; /// Whether exponential backoff is enabled. public bool UseExponentialBackoffValue => _useExponentialBackoff; /// Whether the exception is marked as handled (suppresses propagation). public bool IsHandled => _handled; /// Whether exchange processing continues after the handler runs. public bool IsContinued => _continued; internal OnExceptionDefinition(IEnumerable exceptionTypes) { _exceptionTypes = [.. exceptionTypes]; } // ── Configuration ───────────────────────────────────────────────────────── /// Applies all settings from a pre-built . public OnExceptionDefinition RedeliveryPolicy(RedeliveryPolicy policy) { ArgumentNullException.ThrowIfNull(policy); _maxRedeliveries = policy.MaximumRedeliveries; _redeliveryDelay = policy.RedeliveryDelay; _backoffMultiplier = policy.BackOffMultiplier; _useExponentialBackoff = policy.UseExponentialBackOff; return this; } /// Sets the maximum number of redelivery attempts. public OnExceptionDefinition MaximumRedeliveries(int count) { _maxRedeliveries = count; return this; } /// Marks the exception as handled (suppresses further propagation). public OnExceptionDefinition Handled(bool value = true) { _handled = value; return this; } /// /// Suppresses the failure and picks the route up at the step after the one that failed (Apache Camel's /// continued(true)), where ends the route where it failed. A step inside a scope /// resumes that scope first and then the steps after it; work a transaction rolled back is not replayed, and routing /// picks up after the block. A failure among the resumed steps is matched against the handlers anew, but not /// redelivered: a redelivery re-runs the route from its first step. /// public OnExceptionDefinition Continued(bool value = true) { _continued = value; return this; } /// Sets the delay between retry attempts. public OnExceptionDefinition RedeliveryDelay(TimeSpan delay) { _redeliveryDelay = delay; return this; } /// Sets the backoff multiplier applied to the delay after each retry. public OnExceptionDefinition BackOffMultiplier(double multiplier) { _backoffMultiplier = multiplier; return this; } /// Enables (or disables) exponential backoff between retries. public OnExceptionDefinition UseExponentialBackOff(bool value = true) { _useExponentialBackoff = value; return this; } /// Apache Camel alias for . public OnExceptionDefinition BackoffMultiplier(double multiplier) => BackOffMultiplier(multiplier); /// Apache Camel alias for . public OnExceptionDefinition UseExponentialBackoff(bool value = true) => UseExponentialBackOff(value); /// Marks that the original (pre-exception) body should be restored for the handler. public OnExceptionDefinition UseOriginalBody() { _useOriginalBody = true; return this; } private bool _useOriginalBody; /// Whether the original body restoration is enabled. public bool IsUseOriginalBody => _useOriginalBody; /// Conditional predicate — only handle when predicate returns true. public OnExceptionDefinition OnWhen(Func predicate) { _onWhen = predicate ?? throw new ArgumentNullException(nameof(predicate)); return this; } /// /// Conditional predicate written as a route expression, the spelling a declarative route /// needs (${header.retryable} == 'true') — the string form /// already takes. /// public OnExceptionDefinition OnWhen(string condition) { ArgumentException.ThrowIfNullOrWhiteSpace(condition); var predicate = PredicateFactory.FromString(condition); return OnWhen(predicate.Matches); } /// Conditional predicate as an (Header("retryable").isEqualTo("true")). public OnExceptionDefinition OnWhen(IPredicate predicate) => OnWhen((predicate ?? throw new ArgumentNullException(nameof(predicate))).Matches); private Func? _onWhen; /// Optional predicate gating handler activation. public Func? OnWhenPredicate => _onWhen; /// Retry while the predicate returns true. public OnExceptionDefinition RetryWhile(Func predicate) { _retryWhile = predicate ?? throw new ArgumentNullException(nameof(predicate)); return this; } /// Retry while the route expression holds — the string form of . public OnExceptionDefinition RetryWhile(string condition) { ArgumentException.ThrowIfNullOrWhiteSpace(condition); var predicate = PredicateFactory.FromString(condition); return RetryWhile(predicate.Matches); } /// Retry while the holds. public OnExceptionDefinition RetryWhile(IPredicate predicate) => RetryWhile((predicate ?? throw new ArgumentNullException(nameof(predicate))).Matches); private Func? _retryWhile; /// Optional predicate controlling retry continuation. public Func? RetryWhilePredicate => _retryWhile; /// Callback invoked when the handler itself fails. public OnExceptionDefinition OnPrepareFailure(Action action) { _onPrepareFailure = action ?? throw new ArgumentNullException(nameof(action)); return this; } private Action? _onPrepareFailure; /// Optional pre-failure callback. public Action? OnPrepareFailureAction => _onPrepareFailure; /// /// Processor invoked before the handler runs, once the redeliveries are exhausted (Apache Camel's /// onPrepareFailure, which takes a Processor too). The markup form of a route can only name a processor — /// a bean from the registry — so the callbacks take one beside the delegate. /// public OnExceptionDefinition OnPrepareFailure(IProcessor processor) { _onPrepareFailureProcessor = processor ?? throw new ArgumentNullException(nameof(processor)); return this; } private IProcessor? _onPrepareFailureProcessor; /// Optional pre-failure processor. public IProcessor? OnPrepareFailureProcessor => _onPrepareFailureProcessor; /// Callback invoked on each redelivery attempt. public OnExceptionDefinition OnRedelivery(Action action) { _onRedelivery = action ?? throw new ArgumentNullException(nameof(action)); return this; } private Action? _onRedelivery; /// Optional redelivery callback. public Action? OnRedeliveryAction => _onRedelivery; /// Processor invoked before each redelivery attempt (Apache Camel's onRedelivery). public OnExceptionDefinition OnRedelivery(IProcessor processor) { _onRedeliveryProcessor = processor ?? throw new ArgumentNullException(nameof(processor)); return this; } private IProcessor? _onRedeliveryProcessor; /// Optional redelivery processor. public IProcessor? OnRedeliveryProcessor => _onRedeliveryProcessor; /// Callback invoked when the exception occurs (before any retry). public OnExceptionDefinition OnExceptionOccurred(Action action) { _onExceptionOccurred = action ?? throw new ArgumentNullException(nameof(action)); return this; } private Action? _onExceptionOccurred; /// Optional exception-occurred callback. public Action? OnExceptionOccurredAction => _onExceptionOccurred; /// /// Processor invoked every time the exception occurs, before any retry (Apache Camel's onExceptionOccurred). /// public OnExceptionDefinition OnExceptionOccurred(IProcessor processor) { _onExceptionOccurredProcessor = processor ?? throw new ArgumentNullException(nameof(processor)); return this; } private IProcessor? _onExceptionOccurredProcessor; /// Optional exception-occurred processor. public IProcessor? OnExceptionOccurredProcessor => _onExceptionOccurredProcessor; /// Log level used for retry-attempt log entries. public OnExceptionDefinition RetryAttemptedLogLevel(LogLevel level) { _retryAttemptedLogLevel = level; return this; } private LogLevel _retryAttemptedLogLevel = LogLevel.Debug; /// Log level for retry-attempt log entries (default Debug). public LogLevel RetryAttemptedLogLevelValue => _retryAttemptedLogLevel; /// Log level used when retries are exhausted. public OnExceptionDefinition RetriesExhaustedLogLevel(LogLevel level) { _retriesExhaustedLogLevel = level; return this; } private LogLevel _retriesExhaustedLogLevel = LogLevel.Error; /// Log level used when retries are exhausted (default Error). public LogLevel RetriesExhaustedLogLevelValue => _retriesExhaustedLogLevel; /// Whether to include the full stack trace in retry log messages (default: true). public OnExceptionDefinition LogStackTrace(bool value = true) { _logStackTrace = value; return this; } private bool _logStackTrace = true; /// Current LogStackTrace value (default true). public bool LogStackTraceValue => _logStackTrace; /// Whether to emit a log entry when retries are exhausted (default: true). public OnExceptionDefinition LogExhausted(bool value = true) { _logExhausted = value; return this; } private bool _logExhausted = true; /// Current LogExhausted value (default true). public bool LogExhaustedValue => _logExhausted; /// Whether the exhausted-failure log entry is written for a failure the handler handled (default: false, as in Camel). public OnExceptionDefinition LogHandled(bool value = true) { _logHandled = value; return this; } private bool _logHandled; /// Current LogHandled value (default false). public bool LogHandledValue => _logHandled; /// Whether the exhausted-failure log entry is written for a failure the handler continued (default: false, as in Camel). public OnExceptionDefinition LogContinued(bool value = true) { _logContinued = value; return this; } private bool _logContinued; /// Current LogContinued value (default false). public bool LogContinuedValue => _logContinued; // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this OnException scope and returns the parent route definition. public IRouteDefinition EndOnException() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndOnException() called without a parent route.")); /// public IRouteDefinition End() => EndOnException(); // ── IProcessorDefinition ────────────────────────────────────────────────── /// /// Whether this definition was hoisted by /// to wrap the route body (Camel parity: OnException is route-scoped regardless of /// where it is declared, including inside nested scopes). /// internal bool IsHoisted { get; private set; } /// Marks this definition as hoisted by the route compiler. internal void MarkHoisted() => IsHoisted = true; /// /// /// OnException is compiled exclusively through the hoisting pass in /// , which calls . /// When hoisted, the declaration site compiles to a pass-through no-op. /// When NOT hoisted (e.g., declared inside a Catch/Finally block or another /// OnException handler pipeline — placements that the route compiler does not /// hoist), this throws instead of silently emitting the handler chain as an /// inline pipeline step, which would corrupt every passing exchange. /// public override IProcessor CreateProcessor(IRouteContext context) { if (IsHoisted) return new DelegateProcessor(_ => { }); throw new InvalidOperationException( "OnException is route-scoped and is compiled via RouteDefinition hoisting. " + "This OnException block was declared at a location the route compiler cannot hoist " + "(e.g., inside a Catch/Finally block or another exception handler pipeline). " + "Declare OnException in the route body (any scope) or at the RouteBuilder level."); } /// /// Wraps the supplied processor with one for all of /// , each with its own pipeline of child . /// Used for a route compiled outside a ; the route compiler of a context goes through /// the route's , which compiles a handler once and reuses it. /// internal static IProcessor WrapBody(IProcessor body, IReadOnlyList handlers, IRouteContext context) { ArgumentNullException.ThrowIfNull(body); ArgumentNullException.ThrowIfNull(context); var logger = context.GetService()?.CreateLogger(); var scope = new OnExceptionProcessor(body, logger); foreach (var handler in handlers) handler.AddTo(scope, TryCatchDefinition.BuildPipeline(handler.Outputs, context)); return scope; } /// /// The one place an is configured from this definition. Registers it in /// , the processor of a whole scope: every exception type with /// (this definition's compiled steps) and every setting of the definition. /// internal void AddTo(OnExceptionProcessor oeProc, IProcessor handlerBody) { ArgumentNullException.ThrowIfNull(oeProc); ArgumentNullException.ThrowIfNull(handlerBody); foreach (var type in _exceptionTypes) { oeProc.Handle(type, handlerBody, maxRedeliveries: _maxRedeliveries, redeliveryDelay: _redeliveryDelay, backoffMultiplier: _backoffMultiplier, useExponentialBackoff: _useExponentialBackoff, handled: _handled, continued: _continued, onWhenPredicate: _onWhen, retryAttemptedLogLevel: _retryAttemptedLogLevel, retriesExhaustedLogLevel: _retriesExhaustedLogLevel, onExceptionOccurred: _onExceptionOccurred, retryWhile: _retryWhile, onRedelivery: _onRedelivery, onPrepareFailure: _onPrepareFailure, useOriginalBody: _useOriginalBody, logStackTrace: _logStackTrace, logExhausted: _logExhausted, logHandled: _logHandled, logContinued: _logContinued, onExceptionOccurredProcessor: _onExceptionOccurredProcessor, onRedeliveryProcessor: _onRedeliveryProcessor, onPrepareFailureProcessor: _onPrepareFailureProcessor); } } } Path: redb-route/redb.Route/Definitions/ProcessActionDefinition.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/Definitions/ProcessActionDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that executes a synchronous delegate on the exchange. /// public sealed class ProcessActionDefinition : ProcessorDefinition { private readonly Action _action; /// Creates a definition for a synchronous processing action. /// Synchronous action to execute on each exchange. public ProcessActionDefinition(Action action) { ArgumentNullException.ThrowIfNull(action); _action = action; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(_action); } /// /// Leaf definition that executes an asynchronous delegate on the exchange. /// public sealed class ProcessAsyncDefinition : ProcessorDefinition { private readonly Func _action; /// Creates a definition for an asynchronous processing action. /// Async action to execute on each exchange. public ProcessAsyncDefinition(Func action) { ArgumentNullException.ThrowIfNull(action); _action = action; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(_action); } /// /// Leaf definition that returns a pre-built instance directly. /// public sealed class ProcessInstanceDefinition : ProcessorDefinition { private readonly IProcessor _processor; /// Creates a definition wrapping an existing processor instance. /// Pre-built processor to use. public ProcessInstanceDefinition(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); _processor = processor; } /// public override IProcessor CreateProcessor(IRouteContext context) => _processor; } Path: redb-route/redb.Route/Definitions/ProcessorDefinition.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/Definitions/ProcessorDefinition.cs ---- using redb.Route.Abstractions; namespace redb.Route.Definitions; /// /// Base class for all processor definitions in the canonical Camel ProcessorDefinition model. /// Every EIP node derives from this and overrides to produce /// its runtime . /// public abstract class ProcessorDefinition : IProcessorDefinition { /// /// Optional step id assigned via the Id("...") DSL verb (Apache Camel id()). Used by /// AdviceWith weaving (WeaveById), diagnostics and the XML form; null when unnamed. /// When set, it becomes the node id in message history instead of the generated label+counter one. /// public string? StepId { get; internal set; } /// /// Optional human-readable step label assigned via the Description("...") DSL verb (Apache /// Camel description()) or the XML description attribute. When set, it replaces the /// type-derived label in message history; the node id is unaffected. null when unset. /// public string? StepDescription { get; internal set; } /// public IList Outputs { get; } = new List(); /// public IProcessorDefinition? Parent { get; set; } /// public abstract IProcessor CreateProcessor(IRouteContext context); /// /// Appends to and sets its /// to this node. /// protected void AddOutput(IProcessorDefinition output) { output.Parent = this; Outputs.Add(output); } } Path: redb-route/redb.Route/Definitions/RedeliveryPolicy.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/Definitions/RedeliveryPolicy.cs ---- namespace redb.Route.Definitions; /// /// Pre-configured redelivery policy that can be shared across multiple OnException handlers. /// Store in properties for reuse. /// public sealed class RedeliveryPolicy { /// Maximum number of redelivery (retry) attempts. Default: 0 (no retries). public int MaximumRedeliveries { get; init; } /// Delay between retry attempts. Default: 1 second. public TimeSpan RedeliveryDelay { get; init; } = TimeSpan.FromSeconds(1); /// Backoff multiplier applied to the delay after each retry. Default: 1.0 (fixed delay). public double BackOffMultiplier { get; init; } = 1.0; /// Whether to use exponential backoff. Default: false. public bool UseExponentialBackOff { get; init; } /// Collision avoidance factor (jitter). 0.0 = no jitter, 0.15 = ±15%. Default: 0. public double CollisionAvoidanceFactor { get; init; } /// Delay pattern string overriding standard delay. Format: "attempt:delayMs;...". public string? DelayPattern { get; init; } /// Whether to include stack trace in retry log messages. Default: true. public bool LogStackTrace { get; init; } = true; /// Whether to log when retries are exhausted. Default: true. public bool LogExhausted { get; init; } = true; /// Allow redelivery while the route is stopping. Default: false. public bool AllowRedeliveryWhileStopping { get; init; } } Path: redb-route/redb.Route/Definitions/RemoveByMaskDefinition.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/Definitions/RemoveByMaskDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// Which store cleans. public enum RemoveTarget { /// Message headers. Headers, /// Exchange properties. Properties, } /// /// Removes every header (or property) whose name matches a mask — exact, trailing * /// (X-Internal-*) or regex: — except the names listed. The usual last step before a /// message leaves for an external system. /// public sealed class RemoveByMaskDefinition : ProcessorDefinition { /// Creates the node. public RemoveByMaskDefinition(RemoveTarget target, string pattern, IReadOnlyList except) { UriMask.Validate(pattern, nameof(pattern)); ArgumentNullException.ThrowIfNull(except); Target = target; Pattern = pattern; Except = except; } /// Headers or properties. public RemoveTarget Target { get; } /// Name mask. public string Pattern { get; } /// Names kept even when they match. public IReadOnlyList Except { get; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => { var store = Target == RemoveTarget.Headers ? exchange.In.Headers : exchange.Properties; // The exchange keeps its DI scopes (__redb_scope:*) and registered resources (__redb_resource:*) as // properties; they are bookkeeping, not user data, and dropping them would leave ReleaseScopes nothing to // dispose — a scope or connection leak. var doomed = store.Keys .Where(key => UriMask.IsMatch(Pattern, key) && !Except.Contains(key, StringComparer.OrdinalIgnoreCase) && !(Target == RemoveTarget.Properties && ExchangeResources.IsOwnedByExchange(key))) .ToList(); foreach (var key in doomed) store.Remove(key); }); } Path: redb-route/redb.Route/Definitions/ReplayableDefinition.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/Definitions/ReplayableDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for a replay checkpoint (save-point) — .Replayable("name"). /// Its are the body of the marker (the tail /// after it). wraps that body in a /// (which snapshots the exchange on each pass) and registers the compiled body in the context's /// checkpoint registry so /// can re-run it — no synthetic endpoint. /// /// At the very start of a route the body is the whole pipeline and no End is needed (an /// unclosed scope is structurally valid); in the middle or when several markers are used, close with /// / the universal , or use the lambda-body DSL overload. /// /// public class ReplayableDefinition : RouteDefinitionBase, IRouteScope, IScopeNestingRule { private readonly string _markerName; private readonly bool _exposed; /// The save-point name (unique within the route; key of the checkpoint registry). public string MarkerName => _markerName; /// /// When true, the marker is also an addressable public entry (for .To(...) from /// other routes and tests) — the direct:__replay:{routeId}:{name} endpoint is registered /// lazily. Default false: internal replay only, via ReplayAsync. /// public bool Exposed => _exposed; internal ReplayableDefinition(string markerName, bool exposed) { _markerName = markerName; _exposed = exposed; } /// Closes this replay scope and returns the parent route definition. /// Thrown if no parent route is set. public IRouteDefinition EndReplayable() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndReplayable() called without a parent route. Ensure Replayable() was called on a route definition.")); /// public IRouteDefinition End() => EndReplayable(); /// /// Nesting policy (see ): a checkpoint's tail cannot span a /// branching scope (§6 — build error), and inside a durable transaction a manual replay runs /// outside it (§10 — warning). Every other nesting is allowed (including nested checkpoints). /// public NestingVerdict CheckAncestor(IProcessorDefinition ancestor) => ancestor switch { ICompositeScope => NestingVerdict.Forbid( $"checkpoint '{_markerName}' cannot cross a {ancestor.GetType().Name} boundary; " + "extract the segment into a direct: sub-route."), IDurableScope => NestingVerdict.Warn( $"checkpoint '{_markerName}' is inside a {ancestor.GetType().Name}: a manual replay runs " + "OUTSIDE that transaction and may duplicate processing — ensure idempotency (§10)."), _ => NestingVerdict.Allowed }; /// public override IProcessor CreateProcessor(IRouteContext context) { var body = BuildPipeline(Outputs, context); var logger = context.GetService()?.CreateLogger(); // Register the compiled body so ReplayAsync re-runs it directly (no synthetic endpoint). // The context knows which route it is compiling right now. (context as RouteContext)?.RegisterCheckpoint(_markerName, body, _exposed); return new CheckpointProcessor(_markerName, body, logger); } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } Path: redb-route/redb.Route/Definitions/ResequenceDefinition.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/Definitions/ResequenceDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Resequencer EIP. Buffers and reorders incoming /// exchanges by a sequence key before delivering them to its child outputs. /// Apache Camel parity: .resequence(...).process(...).end(). /// Inherits the leaf DSL from . /// public sealed class ResequenceDefinition : RouteDefinitionBase, IRouteScope { private readonly Func _keySelector; private readonly int _batchSize; private readonly TimeSpan? _timeout; /// Creates a resequence definition. internal ResequenceDefinition(Func keySelector, int batchSize, TimeSpan? timeout) { ArgumentNullException.ThrowIfNull(keySelector); if (batchSize <= 0) throw new ArgumentOutOfRangeException(nameof(batchSize)); _keySelector = keySelector; _batchSize = batchSize; _timeout = timeout; } /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor inner = NodePipeline.Body(context, Outputs); // Every delivery comes out of the buffer — on a timer, or with exchanges of callers that have already returned — // and a failure is kept on its exchange, never thrown to the route's error wrappers: the body is wrapped by the // route's error scope. inner = (context as Core.RouteContext)?.DetachedErrorScope?.WrapDetached(inner) ?? inner; return new ResequencerProcessor(inner, _keySelector, _batchSize, _timeout); } /// Closes the Resequence scope and returns to the parent route. public IRouteDefinition EndResequence() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndResequence() called without a parent route. Ensure Resequence() was called on a route definition.")); /// public IRouteDefinition End() => EndResequence(); } Path: redb-route/redb.Route/Definitions/RouteConfigurationDefinition.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/Definitions/RouteConfigurationDefinition.cs ---- namespace redb.Route.Definitions; /// /// A route configuration (Apache Camel's Route Configuration): error handling declared once, apart from the routes, /// and applied to the routes of any builder of the context. /// /// A configuration without an id is the default: it applies to every route that has no configurations assigned. A /// configuration with an id applies to the routes that name it with .RouteConfigurationId("id"). /// /// Declared in a . /// public sealed class RouteConfigurationDefinition { private readonly List _exceptionDefinitions = []; internal RouteConfigurationDefinition(string? id) { if (id is not null) ArgumentException.ThrowIfNullOrWhiteSpace(id); Id = id; } /// The id routes name the configuration by; null for the default configuration. public string? Id { get; } /// The exception handlers of the configuration, in declaration order. public IReadOnlyList ExceptionDefinitions => _exceptionDefinitions; /// /// Defines an exception handler of the configuration: every setting and every step an OnException of a /// builder has (redeliveries, OnWhen, Handled, the handler's steps). For a failure of a route the /// handler nearest to the exception type wins, wherever it is declared; the route's own handler wins a tie, and /// the configuration's handler is used instead of a handler of the same type on the route's builder. /// /// Exception type to handle. /// Definition for fluent chaining of handler steps and configuration. public OnExceptionDefinition OnException() where TException : Exception => OnException(typeof(TException)); /// Defines an exception handler of the configuration for several exception types at once. /// Exception types to handle. /// Definition for fluent chaining. public OnExceptionDefinition OnException(params Type[] exceptionTypes) { if (exceptionTypes is not { Length: > 0 }) throw new ArgumentException("At least one exception type must be specified.", nameof(exceptionTypes)); foreach (var t in exceptionTypes) if (!typeof(Exception).IsAssignableFrom(t)) throw new ArgumentException($"Type '{t.Name}' is not an Exception type.", nameof(exceptionTypes)); var def = new OnExceptionDefinition(exceptionTypes); _exceptionDefinitions.Add(def); return def; } } Path: redb-route/redb.Route/Definitions/RouteDefinition.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/Definitions/RouteDefinition.cs ---- #pragma warning disable CS0619 using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Concrete root route definition. Inherits the entire fluent leaf-DSL from /// with = ; /// adds root-only behavior — namely with declarative /// hoisting (Apache Camel parity). /// public class RouteDefinition : RouteDefinitionBase, IBranchingDefinition { /// Route-level intercepts (declared anywhere inside the route; applied to the whole route at compile). internal readonly List Intercepts = []; /// Route-level OnCompletion blocks. internal readonly List OnCompletions = []; /// /// Intercept and OnCompletion bodies: logical children kept outside , exposed so a /// generic tree walk (the route validator, AdviceWith's MockEndpoints / Weave*) reaches /// the steps nested in them. /// public IEnumerable Branches => Intercepts.Concat(OnCompletions); /// Intercepts declared on this route (read by the context at compile and by tooling). public IReadOnlyList GetIntercepts() => Intercepts; /// OnCompletion blocks declared on this route. public IReadOnlyList GetOnCompletions() => OnCompletions; /// public override IProcessor CreateProcessor(IRouteContext context) { if (Outputs.Count == 0) return new DelegateProcessor(_ => { }); // Detect inline OnException blocks declared inside the route body. In Apache Camel // these are route-scoped — they wrap the entire route pipeline regardless of where // they appear textually, INCLUDING inside nested scopes (Transacted, Traced, // Metered, Throttle, ...). We collect them recursively, mark them hoisted (so their // CreateProcessor compiles to a no-op at the declaration site), then wrap the // remaining body with the handler envelopes. var onExceptions = new List(); CollectAndMarkOnExceptions(Outputs, onExceptions); // Under a context's route compiler the handlers belong to the route's error scope, which a detached body of // this route (.Threads()) is wrapped by too; known before the body compiles. var errorScope = (context as RouteContext)?.DetachedErrorScope; errorScope?.AddRouteHandlers(onExceptions); if (onExceptions.Count == 0) { if (Outputs.Count == 1) return NodePipeline.Node(context, Outputs[0]); var pipeline = new PipelineProcessor(); foreach (var output in Outputs) { var p = NodePipeline.Node(context, output); if (p != null) pipeline.Add(p); } return pipeline; } var bodySteps = new List(); foreach (var output in Outputs) { if (output is OnExceptionDefinition) continue; var p = NodePipeline.Node(context, output); if (p != null) bodySteps.Add(p); } IProcessor body; if (bodySteps.Count == 0) { body = new DelegateProcessor(_ => { }); } else if (bodySteps.Count == 1) { body = bodySteps[0]; } else { var pl = new PipelineProcessor(); foreach (var s in bodySteps) pl.Add(s); body = pl; } // One scope for all of the route's handlers, so the nearest exception type wins whatever the declaration // order (Camel's exception policy). Outside a context's route compiler there is no shared scope around it. if (errorScope is not null) return errorScope.WrapRoute(body); return OnExceptionDefinition.WrapBody(body, onExceptions, context); } private static void CollectAndMarkOnExceptions( IList outputs, List acc) { foreach (var output in outputs) { if (output is OnExceptionDefinition oe) { // Do not descend into the handler steps — a nested OnException inside a // handler pipeline is unsupported and fails fast at compilation. oe.MarkHoisted(); acc.Add(oe); continue; } if (output.Outputs.Count > 0) CollectAndMarkOnExceptions(output.Outputs, acc); } } } Path: redb-route/redb.Route/Definitions/RouteDefinitionBase.IRouteDefinition.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/Definitions/RouteDefinitionBase.IRouteDefinition.cs ---- #pragma warning disable CS0619 using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Transactions; using redb.Route.Validation; using redb.Route.Xslt; namespace redb.Route.Definitions; /// /// Explicit implementation for . /// Each method delegates to the typed TSelf overload defined in the main partial. /// /// This indirection is required because C# does not accept a generic type parameter /// (constrained to be a subtype of the interface) as a covariant return type for an /// interface method (CS0738). Explicit-impl boilerplate is therefore localised here so /// concrete scope classes never need to repeat it. /// /// public abstract partial class RouteDefinitionBase { // ── Identity ── IRouteDefinition IRouteDefinition.RouteId(string routeId) => RouteId(routeId); IRouteDefinition IRouteDefinition.Id(string id) => Id(id); IRouteDefinition IRouteDefinition.Description(string description) => Description(description); IRouteDefinition IRouteDefinition.SetHeaders(params (string Name, object? Value)[] headers) => SetHeaders(headers); IRouteDefinition IRouteDefinition.SetProperties(params (string Name, object? Value)[] properties) => SetProperties(properties); IRouteDefinition IRouteDefinition.RemoveHeaders(string pattern, params string[] except) => RemoveHeaders(pattern, except); IRouteDefinition IRouteDefinition.RemoveProperties(string pattern, params string[] except) => RemoveProperties(pattern, except); IRouteDefinition IRouteDefinition.Sort(string collectionExpression, string? keyExpression, bool descending) => Sort(collectionExpression, keyExpression, descending); IRouteDefinition IRouteDefinition.Sort(Func> source, Func? key, bool descending, IComparer? comparer) => Sort(source, key, descending, comparer); IRouteDefinition IRouteDefinition.AutoStart(bool value) => AutoStart(value); IRouteDefinition IRouteDefinition.ProcessingTimeout(TimeSpan timeout) => ProcessingTimeout(timeout); // ── Source ── IRouteDefinition IRouteDefinition.From(string uri) => From(uri); // ── Destination ── IRouteDefinition IRouteDefinition.To(string uri) => To(uri); IRouteDefinition IRouteDefinition.ToD(string uriTemplate) => ToD(uriTemplate); IRouteDefinition IRouteDefinition.ToD(IExpression uriExpression) => ToD(uriExpression); IRouteDefinition IRouteDefinition.ToD(Func uriFactory) => ToD(uriFactory); // ── Processing delegates ── IRouteDefinition IRouteDefinition.Process(Action action) => Process(action); IRouteDefinition IRouteDefinition.Process(Func action) => Process(action); IRouteDefinition IRouteDefinition.Process(IProcessor processor) => Process(processor); // ── Body ── IRouteDefinition IRouteDefinition.SetBody(object? value) => SetBody(value); IRouteDefinition IRouteDefinition.SetBody(Func factory) => SetBody(factory); IRouteDefinition IRouteDefinition.SetBody(IExpression expression) => SetBody(expression); IRouteDefinition IRouteDefinition.Transform(Func transform) => Transform(transform); IRouteDefinition IRouteDefinition.Transform(IExpression expression) => Transform(expression); IRouteDefinition IRouteDefinition.RemoveBody() => RemoveBody(); // ── Headers ── IRouteDefinition IRouteDefinition.SetHeader(string key, object? value) => SetHeader(key, value); IRouteDefinition IRouteDefinition.SetHeader(string key, Func factory) => SetHeader(key, factory); IRouteDefinition IRouteDefinition.SetHeader(string name, IExpression expression) => SetHeader(name, expression); IRouteDefinition IRouteDefinition.RemoveHeader(string key) => RemoveHeader(key); // ── Attachments ── IRouteDefinition IRouteDefinition.AddAttachment(string name, IExpression content, string? fileName, string? contentType) => AddAttachment(name, content, fileName, contentType); IRouteDefinition IRouteDefinition.AddAttachment(string name, IExpression content, IExpression fileName, string? contentType) => AddAttachment(name, content, fileName, contentType); IRouteDefinition IRouteDefinition.AddAttachmentFromBody(string name, string? fileName, string? contentType) => AddAttachmentFromBody(name, fileName, contentType); IRouteDefinition IRouteDefinition.AddAttachmentFromBody(string name, IExpression fileName, string? contentType) => AddAttachmentFromBody(name, fileName, contentType); IRouteDefinition IRouteDefinition.AddAttachmentFromFile(string path, string? name, string? contentType) => AddAttachmentFromFile(path, name, contentType); IRouteDefinition IRouteDefinition.AddAttachmentFromFile(IExpression path, string? name, string? contentType) => AddAttachmentFromFile(path, name, contentType); IRouteDefinition IRouteDefinition.RemoveAttachment(string name) => RemoveAttachment(name); IRouteDefinition IRouteDefinition.RemoveAttachments() => RemoveAttachments(); // ── Properties ── IRouteDefinition IRouteDefinition.SetProperty(string key, object? value) => SetProperty(key, value); IRouteDefinition IRouteDefinition.SetProperty(string key, Func factory) => SetProperty(key, factory); IRouteDefinition IRouteDefinition.SetProperty(string key, IExpression expression) => SetProperty(key, expression); IRouteDefinition IRouteDefinition.RemoveProperty(string key) => RemoveProperty(key); // ── Logging ── IRouteDefinition IRouteDefinition.Log(string message, LogLevel level) => Log(message, level); IRouteDefinition IRouteDefinition.Log(Func messageFactory, LogLevel level) => Log(messageFactory, level); // ── Stop / Throw ── IRouteDefinition IRouteDefinition.Stop() => Stop(); IRouteDefinition IRouteDefinition.ThrowException() => ThrowException(); IRouteDefinition IRouteDefinition.ThrowException(string message) => ThrowException(message); IRouteDefinition IRouteDefinition.ThrowException(Exception exception) => ThrowException(exception); IRouteDefinition IRouteDefinition.ThrowException(Type exceptionType, string message) => ThrowException(exceptionType, message); IRouteDefinition IRouteDefinition.ThrowException(string? message) => ThrowException(message); // ── Delay / Sampling ── IRouteDefinition IRouteDefinition.Delay(TimeSpan duration) => Delay(duration); IRouteDefinition IRouteDefinition.Delay(Func factory) => Delay(factory); IRouteDefinition IRouteDefinition.Delay(string durationExpression) => Delay(durationExpression); IRouteDefinition IRouteDefinition.Sample(long messageFrequency) => Sample(messageFrequency); IRouteDefinition IRouteDefinition.Sample(TimeSpan period) => Sample(period); // ── Stream caching ── IRouteDefinition IRouteDefinition.StreamCaching(long? spoolThreshold) => StreamCaching(spoolThreshold); // ── Validation ── IRouteDefinition IRouteDefinition.Validate(IMessageValidator validator, bool throwOnFailure) => Validate(validator, throwOnFailure); IRouteDefinition IRouteDefinition.Validate(Func predicate, string errorMessage, bool throwOnFailure) => Validate(predicate, errorMessage, throwOnFailure); IRouteDefinition IRouteDefinition.Validate(IPredicate predicate, string errorMessage, bool throwOnFailure) => Validate(predicate, errorMessage, throwOnFailure); IRouteDefinition IRouteDefinition.Validate(IExpression condition, string errorMessage, bool throwOnFailure) => Validate(condition, errorMessage, throwOnFailure); IRouteDefinition IRouteDefinition.ValidateJsonSchema(string schemaJson, bool throwOnFailure) => ValidateJsonSchema(schemaJson, throwOnFailure); IRouteDefinition IRouteDefinition.ValidateJsonSchema(Json.Schema.JsonSchema schema, bool throwOnFailure) => ValidateJsonSchema(schema, throwOnFailure); IRouteDefinition IRouteDefinition.ValidateXsd(string xsdContent, bool throwOnFailure) => ValidateXsd(xsdContent, throwOnFailure); IRouteDefinition IRouteDefinition.ValidateXsd(string? targetNamespace, string xsdContent, bool throwOnFailure) => ValidateXsd(targetNamespace, xsdContent, throwOnFailure); IRouteDefinition IRouteDefinition.ValidateXsd(System.Xml.Schema.XmlSchemaSet schemaSet, bool throwOnFailure) => ValidateXsd(schemaSet, throwOnFailure); IRouteDefinition IRouteDefinition.ValidateXsdFile(string schemaPath, string? targetNamespace, string? schemaRoot, bool throwOnFailure) => ValidateXsdFile(schemaPath, targetNamespace, schemaRoot, throwOnFailure); IRouteDefinition IRouteDefinition.Xslt(string stylesheetPath, XsltOutput output, bool failOnNullBody, bool allowTemplateFromHeader) => Xslt(stylesheetPath, output, failOnNullBody, allowTemplateFromHeader); IRouteDefinition IRouteDefinition.XsltContent(string stylesheetXml, XsltOutput output, bool failOnNullBody, bool allowTemplateFromHeader) => XsltContent(stylesheetXml, output, failOnNullBody, allowTemplateFromHeader); IRouteDefinition IRouteDefinition.ControlBus(redb.Route.ControlBus.ControlBusAction action, string routeId, bool async) => ControlBus(action, routeId, async); // ── Serialization ── IRouteDefinition IRouteDefinition.Marshal(Type serializerType) => Marshal(serializerType); IRouteDefinition IRouteDefinition.Marshal() => Marshal(); IRouteDefinition IRouteDefinition.Unmarshal(Type serializerType, Type targetType) => Unmarshal(serializerType, targetType); IRouteDefinition IRouteDefinition.Unmarshal() => Unmarshal(); IRouteDefinition IRouteDefinition.Marshal(string contentType) => Marshal(contentType); IRouteDefinition IRouteDefinition.Marshal(IMessageSerializer serializer) => Marshal(serializer); IRouteDefinition IRouteDefinition.Unmarshal(string contentType) => Unmarshal(contentType); IRouteDefinition IRouteDefinition.Unmarshal(string contentType, Type targetType) => Unmarshal(contentType, targetType); IRouteDefinition IRouteDefinition.Unmarshal(IMessageSerializer serializer) => Unmarshal(serializer); IRouteDefinition IRouteDefinition.Unmarshal(IMessageSerializer serializer, Type targetType) => Unmarshal(serializer, targetType); IRouteDefinition IRouteDefinition.Unmarshal() => Unmarshal(); IRouteDefinition IRouteDefinition.ConvertBody() => ConvertBody(); IRouteDefinition IRouteDefinition.ConvertBody(Type targetType) => ConvertBody(targetType); // ── Transactions ── IRouteDefinition IRouteDefinition.BeginTransaction() => BeginTransaction(); IRouteDefinition IRouteDefinition.BeginTransaction(TransactionPolicy policy) => BeginTransaction(policy); IRouteDefinition IRouteDefinition.CommitTransaction() => CommitTransaction(); IRouteDefinition IRouteDefinition.RollbackTransaction() => RollbackTransaction(); // ── Replay checkpoints ── // The non-lambda Replayable returns ReplayableDefinition (matches the interface exactly, no // explicit impl needed); the lambda overload returns TSelf and needs this bridge. IRouteDefinition IRouteDefinition.Replayable(string name, Action body, bool exposed) => Replayable(name, body, exposed); // ── Telemetry (inline overloads) ── IRouteDefinition IRouteDefinition.Traced(string operationName, Action action) => Traced(operationName, action); IRouteDefinition IRouteDefinition.Traced(string operationName, Func action) => Traced(operationName, action); IRouteDefinition IRouteDefinition.Traced(string operationName, IProcessor processor) => Traced(operationName, processor); IRouteDefinition IRouteDefinition.Metered(string stepName, Action action) => Metered(stepName, action); IRouteDefinition IRouteDefinition.Metered(string stepName, Func action) => Metered(stepName, action); IRouteDefinition IRouteDefinition.Metered(string stepName, IProcessor processor) => Metered(stepName, processor); IRouteDefinition IRouteDefinition.SpanTag(string key, string value, Telemetry.SpanTarget target) => SpanTag(key, value, target); IRouteDefinition IRouteDefinition.SpanTag(string key, IExpression value, Telemetry.SpanTarget target) => SpanTag(key, value, target); // ── Enrichment ── IRouteDefinition IRouteDefinition.WireTap(string uri, string? executorService) => WireTap(uri, executorService); IRouteDefinition IRouteDefinition.WireTap(string uri, Action onPrepare, string? executorService) => WireTap(uri, onPrepare, executorService); IRouteDefinition IRouteDefinition.WireTap(string uri, Func newBodyFactory, string? executorService) => WireTap(uri, newBodyFactory, executorService); IRouteDefinition IRouteDefinition.WireTap(string uri, Action onPrepare, Func newBodyFactory, string? executorService) => WireTap(uri, onPrepare, newBodyFactory, executorService); IRouteDefinition IRouteDefinition.WireTap(Func uriFactory, string? executorService) => WireTap(uriFactory, executorService); IRouteDefinition IRouteDefinition.WireTap(Func uriFactory, Action onPrepare, string? executorService) => WireTap(uriFactory, onPrepare, executorService); IRouteDefinition IRouteDefinition.WireTap(Func uriFactory, Func newBodyFactory, string? executorService) => WireTap(uriFactory, newBodyFactory, executorService); IRouteDefinition IRouteDefinition.WireTap(Func uriFactory, Action onPrepare, Func newBodyFactory, string? executorService) => WireTap(uriFactory, onPrepare, newBodyFactory, executorService); IRouteDefinition IRouteDefinition.Enrich(string resourceUri, Func mergeStrategy) => Enrich(resourceUri, mergeStrategy); IRouteDefinition IRouteDefinition.Enrich(Func uriFactory, Func mergeStrategy) => Enrich(uriFactory, mergeStrategy); IRouteDefinition IRouteDefinition.PollEnrich(string resourceUri, Func mergeStrategy, TimeSpan? timeout) => PollEnrich(resourceUri, mergeStrategy, timeout); IRouteDefinition IRouteDefinition.PollEnrich(Func uriFactory, Func mergeStrategy, TimeSpan? timeout) => PollEnrich(uriFactory, mergeStrategy, timeout); IRouteDefinition IRouteDefinition.Enrich(string resourceUri) => Enrich(resourceUri); IRouteDefinition IRouteDefinition.Enrich(Func uriFactory) => Enrich(uriFactory); IRouteDefinition IRouteDefinition.PollEnrich(string resourceUri, TimeSpan? timeout) => PollEnrich(resourceUri, timeout); IRouteDefinition IRouteDefinition.PollEnrich(Func uriFactory, TimeSpan? timeout) => PollEnrich(uriFactory, timeout); IRouteDefinition IRouteDefinition.RecipientList(Func> recipientListFactory, bool parallelProcessing, bool stopOnException, Func? aggregationStrategy) => RecipientList(recipientListFactory, parallelProcessing, stopOnException, aggregationStrategy); IRouteDefinition IRouteDefinition.DynamicRouter(Func routingFunction) => DynamicRouter(routingFunction); IRouteDefinition IRouteDefinition.Enrich(IExpression uri, Func mergeStrategy) => Enrich(uri, mergeStrategy); IRouteDefinition IRouteDefinition.Enrich(IExpression uri) => Enrich(uri); IRouteDefinition IRouteDefinition.PollEnrich(IExpression uri, Func mergeStrategy, TimeSpan? timeout) => PollEnrich(uri, mergeStrategy, timeout); IRouteDefinition IRouteDefinition.PollEnrich(IExpression uri, TimeSpan? timeout) => PollEnrich(uri, timeout); IRouteDefinition IRouteDefinition.RecipientList(IExpression recipients, bool parallelProcessing, bool stopOnException, Func? aggregationStrategy, string uriDelimiter) => RecipientList(recipients, parallelProcessing, stopOnException, aggregationStrategy, uriDelimiter); IRouteDefinition IRouteDefinition.DynamicRouter(IExpression routingExpression) => DynamicRouter(routingExpression); IRouteDefinition IRouteDefinition.RoutingSlip(Func> slipFactory, bool ignoreInvalidEndpoints) => RoutingSlip(slipFactory, ignoreInvalidEndpoints); IRouteDefinition IRouteDefinition.RoutingSlip(IExpression slip, string uriDelimiter, bool ignoreInvalidEndpoints) => RoutingSlip(slip, uriDelimiter, ignoreInvalidEndpoints); IRouteDefinition IRouteDefinition.RoutingSlip(string slipTemplate, string uriDelimiter, bool ignoreInvalidEndpoints) => RoutingSlip(slipTemplate, uriDelimiter, ignoreInvalidEndpoints); // ── Bean / Service Activator ── IRouteDefinition IRouteDefinition.Bean(Func method) => Bean(method); IRouteDefinition IRouteDefinition.Bean(Func method) => Bean(method); IRouteDefinition IRouteDefinition.Bean(Action method) => Bean(method); IRouteDefinition IRouteDefinition.Bean(string reference, string? method) => Bean(reference, method); // ── Scatter-Gather ── IRouteDefinition IRouteDefinition.ScatterGather(Func aggregationStrategy, params string[] recipients) => ScatterGather(aggregationStrategy, recipients); IRouteDefinition IRouteDefinition.ScatterGather(Action configure) => ScatterGather(configure); // ── Saga ── IRouteDefinition IRouteDefinition.Saga(Action configure) => Saga(configure); // ── LoadBalance ── IRouteDefinition IRouteDefinition.LoadBalance(ILoadBalancerStrategy strategy, params string[] uris) => LoadBalance(strategy, uris); IRouteDefinition IRouteDefinition.LoadBalance(Action configure) => LoadBalance(configure); // ── Normalizer ── IRouteDefinition IRouteDefinition.Normalize(Action configure) => Normalize(configure); // ── Exception handling ── IRouteDefinition IRouteDefinition.ExceptionHandled() => ExceptionHandled(); IRouteDefinition IRouteDefinition.RollbackAll() => RollbackAll(); // ── Route-level policy ── IRouteDefinition IRouteDefinition.Cluster(bool value) => Cluster(value); IRouteDefinition IRouteDefinition.MessageHistory(bool value) => MessageHistory(value); IRouteDefinition IRouteDefinition.Tracing(bool value) => Tracing(value); IRouteDefinition IRouteDefinition.RoutePolicy(IRoutePolicy policy) => RoutePolicy(policy); IRouteDefinition IRouteDefinition.RoutePolicy(string policyName) => RoutePolicy(policyName); IRouteDefinition IRouteDefinition.RouteConfigurationId(string ids) => RouteConfigurationId(ids); } Path: redb-route/redb.Route/Definitions/RouteDefinitionBase.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/Definitions/RouteDefinitionBase.cs ---- #pragma warning disable CS0619 using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Processors; using redb.Route.Telemetry; using redb.Route.Transactions; using redb.Route.Validation; using redb.Route.Xslt; namespace redb.Route.Definitions; /// /// Generic CRTP base for every route / scope definition. All leaf-DSL methods are declared here /// exactly once and return for fluent chaining inside the concrete /// scope. The class implements ; covariant return types let the /// typed leaf-DSL satisfy the interface contract whose declared return type is /// . /// /// Apache Camel parity: this mirrors ProcessorDefinition<Type extends ProcessorDefinition<Type>> /// from camel-core-model. Scope-opener methods (Filter, Choice, Split, ...) /// return concrete scope types; child are populated /// via the inherited typed DSL. /// /// public abstract partial class RouteDefinitionBase : ProcessorDefinition, IRouteDefinition where TSelf : RouteDefinitionBase { /// Typed self-reference for fluent chaining; safe because is constrained to this class. protected TSelf Self => (TSelf)(object)this; // ── Route-level state (carried by the root RouteDefinition; scope instances inherit the // fields but only the root reads them) ─────────────────────────────────────────────── private string? _routeId; private string? _fromUri; private bool _autoStart = true; private TimeSpan? _processingTimeout; private bool _cluster; private bool? _messageHistory; private bool? _tracing; private IRoutePolicy? _routePolicy; private string? _routePolicyName; private string? _routeConfigurationId; internal IRouteContext? _context; /// Route context captured during compile (null until the route is added to a context). public IRouteContext? Context { get { if (_context is not null) return _context; // Walk up the parent chain to find the root RouteDefinition (which carries the context). for (var p = Parent; p is not null; p = (p as ProcessorDefinition)?.Parent) { if (p is RouteDefinition rd && rd._context is not null) return rd._context; } return null; } } /// Flag controlling whether the route id is shown in log/telemetry output (default false). public bool ShowRouteIdValue { get; internal set; } /// /// True when this route's compiled pipeline opens an explicit declarative /// scope at the top level (Apache Camel parity). /// public bool IsTransacted => Outputs.Any(o => o is TransactionDefinition); // ── Route-level identity ────────────────────────────────────────────────── /// public TSelf RouteId(string routeId) { ArgumentException.ThrowIfNullOrWhiteSpace(routeId); _routeId = routeId; return Self; } /// public string? GetRouteId() => _routeId; /// public TSelf Id(string id) { ArgumentException.ThrowIfNullOrWhiteSpace(id); if (Outputs.Count == 0) return RouteId(id); if (Outputs[^1] is ProcessorDefinition step) step.StepId = id; return Self; } /// public TSelf Description(string description) { ArgumentException.ThrowIfNullOrWhiteSpace(description); if (Outputs.Count == 0) { StepDescription = description; return Self; } if (Outputs[^1] is ProcessorDefinition step) step.StepDescription = description; return Self; } // ── Interception / completion: registered on the root route, applied at compile ────────── /// public InterceptDefinition Intercept() => RegisterIntercept(new InterceptDefinition(InterceptKind.EveryStep, null)); /// public InterceptDefinition InterceptFrom(string? uriPattern = null) => RegisterIntercept(new InterceptDefinition(InterceptKind.From, uriPattern)); /// public InterceptDefinition InterceptSendToEndpoint(string uriPattern) => RegisterIntercept(new InterceptDefinition(InterceptKind.SendToEndpoint, uriPattern)); /// public OnCompletionDefinition OnCompletion() { var def = new OnCompletionDefinition { Parent = this }; RootRoute("OnCompletion()").OnCompletions.Add(def); return def; } private InterceptDefinition RegisterIntercept(InterceptDefinition def) { def.Parent = this; var verb = def.Kind switch { InterceptKind.From => "InterceptFrom()", InterceptKind.SendToEndpoint => "InterceptSendToEndpoint()", _ => "Intercept()", }; RootRoute(verb).Intercepts.Add(def); return def; } /// The root this scope belongs to; intercepts and completions are route-wide, so they live there. private RouteDefinition RootRoute(string verb) { for (IProcessorDefinition? node = this; node is not null; node = node.Parent) if (node is RouteDefinition root) return root; throw new InvalidOperationException($"{verb} must be declared on a route (From(...)) or on the RouteBuilder for all its routes."); } // ── Header / property / body sugar ──────────────────────────────────────── /// public TSelf SetHeaders(params (string Name, object? Value)[] headers) { AddOutput(new SetHeadersDefinition(headers)); return Self; } /// public TSelf SetProperties(params (string Name, object? Value)[] properties) { AddOutput(new SetPropertiesDefinition(properties)); return Self; } /// public TSelf RemoveHeaders(string pattern, params string[] except) { AddOutput(new RemoveByMaskDefinition(RemoveTarget.Headers, pattern, except ?? [])); return Self; } /// public TSelf RemoveProperties(string pattern, params string[] except) { AddOutput(new RemoveByMaskDefinition(RemoveTarget.Properties, pattern, except ?? [])); return Self; } /// public TSelf Sort(string collectionExpression, string? keyExpression = null, bool descending = false) { ArgumentException.ThrowIfNullOrWhiteSpace(collectionExpression); var collection = new StringExpression(collectionExpression); var key = keyExpression is null ? null : new StringExpression(keyExpression); AddOutput(new SortDefinition( exchange => collection.Evaluate(exchange) as System.Collections.IEnumerable, key is null ? null : item => key.Evaluate(Exchange.Create(new Message(item), null)), comparer: null, descending)); return Self; } /// public TSelf Sort(Func> source, Func? key = null, bool descending = false, IComparer? comparer = null) { ArgumentNullException.ThrowIfNull(source); AddOutput(new SortDefinition( exchange => source(exchange), key is null ? null : item => key((T)item!), comparer, descending, items => items.Cast().ToList())); return Self; } /// public TSelf AutoStart(bool value = true) { _autoStart = value; return Self; } /// public bool GetAutoStart() => _autoStart; /// public TSelf ProcessingTimeout(TimeSpan timeout) { if (timeout <= TimeSpan.Zero && timeout != System.Threading.Timeout.InfiniteTimeSpan) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive or Infinite."); _processingTimeout = timeout; return Self; } /// Gets the per-route processing timeout, or null if not set. public TimeSpan? GetProcessingTimeout() => _processingTimeout; // ── Source ─────────────────────────────────────────────────────────────── /// public TSelf From(string uri) { ArgumentException.ThrowIfNullOrWhiteSpace(uri); _fromUri = uri; return Self; } /// public string? GetFromUri() => _fromUri; // ── Destination ────────────────────────────────────────────────────────── /// public TSelf To(string uri) { AddOutput(new ToDefinition(uri)); return Self; } /// public TSelf ToD(string uriTemplate) { AddOutput(new ToDynamicDefinition(uriTemplate)); return Self; } /// public TSelf ToD(IExpression uriExpression) { AddOutput(new ToDynamicDefinition(uriExpression)); return Self; } /// public TSelf ToD(Func uriFactory) { AddOutput(new ToDynamicDefinition(uriFactory)); return Self; } // ── Processing delegates ────────────────────────────────────────────────── /// public TSelf Process(Action action) { AddOutput(new ProcessActionDefinition(action)); return Self; } /// public TSelf Process(Func action) { AddOutput(new ProcessAsyncDefinition(action)); return Self; } /// public TSelf Process(IProcessor processor) { AddOutput(new ProcessInstanceDefinition(processor)); return Self; } // ── Transform / body ───────────────────────────────────────────────────── /// public TSelf SetBody(object? value) { AddOutput(new SetBodyStaticDefinition(value)); return Self; } /// public TSelf SetBody(Func factory) { AddOutput(new SetBodyFactoryDefinition(factory)); return Self; } /// public TSelf SetBody(IExpression expression) { AddOutput(new SetBodyExpressionDefinition(expression)); return Self; } /// public TSelf Transform(Func transform) { AddOutput(new TransformDefinition(transform)); return Self; } /// public TSelf Transform(IExpression expression) { AddOutput(new TransformExpressionDefinition(expression)); return Self; } /// public TSelf RemoveBody() { AddOutput(new RemoveBodyDefinition()); return Self; } // ── Headers ────────────────────────────────────────────────────────────── /// public TSelf SetHeader(string key, object? value) { AddOutput(new SetHeaderStaticDefinition(key, value)); return Self; } /// public TSelf SetHeader(string key, Func factory) { AddOutput(new SetHeaderFactoryDefinition(key, factory)); return Self; } /// public TSelf SetHeader(string name, IExpression expression) { AddOutput(new SetHeaderExpressionDefinition(name, expression)); return Self; } /// public TSelf RemoveHeader(string key) { AddOutput(new RemoveHeaderDefinition(key)); return Self; } // ── Attachments ────────────────────────────────────────────────────────── /// public TSelf AddAttachment(string name, IExpression content, string? fileName = null, string? contentType = null) { AddOutput(AddAttachmentDefinition.FromExpression(name, content, AddAttachmentDefinition.Literal(fileName), contentType)); return Self; } /// public TSelf AddAttachment(string name, IExpression content, IExpression fileName, string? contentType = null) { ArgumentNullException.ThrowIfNull(fileName); AddOutput(AddAttachmentDefinition.FromExpression(name, content, fileName, contentType)); return Self; } /// public TSelf AddAttachmentFromBody(string name, string? fileName = null, string? contentType = null) { AddOutput(AddAttachmentDefinition.FromBody(name, AddAttachmentDefinition.Literal(fileName), contentType)); return Self; } /// public TSelf AddAttachmentFromBody(string name, IExpression fileName, string? contentType = null) { ArgumentNullException.ThrowIfNull(fileName); AddOutput(AddAttachmentDefinition.FromBody(name, fileName, contentType)); return Self; } /// public TSelf AddAttachmentFromFile(string path, string? name = null, string? contentType = null) { ArgumentException.ThrowIfNullOrWhiteSpace(path); AddOutput(AddAttachmentDefinition.FromFile(AddAttachmentDefinition.Literal(path)!, name, contentType)); return Self; } /// public TSelf AddAttachmentFromFile(IExpression path, string? name = null, string? contentType = null) { AddOutput(AddAttachmentDefinition.FromFile(path, name, contentType)); return Self; } /// public TSelf RemoveAttachment(string name) { AddOutput(new RemoveAttachmentDefinition(name)); return Self; } /// public TSelf RemoveAttachments() { AddOutput(new RemoveAttachmentsDefinition()); return Self; } // ── Properties ─────────────────────────────────────────────────────────── /// public TSelf SetProperty(string key, object? value) { AddOutput(new SetPropertyStaticDefinition(key, value)); return Self; } /// public TSelf SetProperty(string key, Func factory) { AddOutput(new SetPropertyFactoryDefinition(key, factory)); return Self; } /// public TSelf SetProperty(string key, IExpression expression) { AddOutput(new SetPropertyExpressionDefinition(key, expression)); return Self; } /// public TSelf RemoveProperty(string key) { AddOutput(new RemovePropertyDefinition(key)); return Self; } // ── Logging ────────────────────────────────────────────────────────────── /// public TSelf Log(string message, LogLevel level = LogLevel.Information) { AddOutput(new LogStaticDefinition(message, level)); return Self; } /// public TSelf Log(Func messageFactory, LogLevel level = LogLevel.Information) { AddOutput(new LogDynamicDefinition(messageFactory, level)); return Self; } // ── Stop / Throw ────────────────────────────────────────────────────────── /// public TSelf Stop() { AddOutput(new StopDefinition()); return Self; } /// public TSelf ThrowException() { AddOutput(new RethrowExceptionDefinition()); return Self; } /// public TSelf ThrowException(string message) { AddOutput(new ThrowMessageDefinition(message)); return Self; } /// public TSelf ThrowException(Exception exception) { AddOutput(new ThrowExceptionDefinition(exception)); return Self; } /// public TSelf ThrowException(Type exceptionType, string message) { AddOutput(new ThrowExceptionTypeDefinition(exceptionType, message)); return Self; } /// public TSelf ThrowException(string? message = null) where TException : Exception, new() { AddOutput(new ThrowExceptionTypeDefinition(typeof(TException), message)); return Self; } // ── Delay / Sampling ───────────────────────────────────────────────────── /// public TSelf Delay(TimeSpan duration) { AddOutput(new DelayDefinition(duration)); return Self; } /// public TSelf Delay(Func factory) { AddOutput(new DelayFactoryDefinition(factory)); return Self; } /// public TSelf Delay(string durationExpression) { ArgumentException.ThrowIfNullOrWhiteSpace(durationExpression); var expression = new StringExpression(durationExpression); return Delay(exchange => DelayExpressionDefinition.ConvertToTimeSpan(expression.Evaluate(exchange))); } /// public TSelf Sample(long messageFrequency) { AddOutput(new SampleCountDefinition(messageFrequency)); return Self; } /// public TSelf Sample(TimeSpan period) { AddOutput(new SamplePeriodDefinition(period)); return Self; } // ── Stream caching ─────────────────────────────────────────────────────── /// public TSelf StreamCaching(long? spoolThreshold = null) { AddOutput(new StreamCachingDefinition(spoolThreshold)); return Self; } // ── Validation ─────────────────────────────────────────────────────────── /// public TSelf Validate(IMessageValidator validator, bool throwOnFailure = true) { AddOutput(new ValidateInstanceDefinition(validator, throwOnFailure)); return Self; } /// public TSelf Validate(Func predicate, string errorMessage = "Validation failed", bool throwOnFailure = true) { AddOutput(new ValidatePredicateDefinition(predicate, errorMessage, throwOnFailure)); return Self; } /// public TSelf Validate(IPredicate predicate, string errorMessage = "Validation failed", bool throwOnFailure = true) { ArgumentNullException.ThrowIfNull(predicate); AddOutput(new ValidatePredicateDefinition(predicate, errorMessage, throwOnFailure)); return Self; } /// public TSelf Validate(IExpression condition, string errorMessage = "Validation failed", bool throwOnFailure = true) { ArgumentNullException.ThrowIfNull(condition); return Validate(Predicates.PredicateFactory.FromExpression(condition), errorMessage, throwOnFailure); } /// public TSelf ValidateJsonSchema(string schemaJson, bool throwOnFailure = true) { AddOutput(new ValidateJsonSchemaStringDefinition(schemaJson, throwOnFailure)); return Self; } /// public TSelf ValidateJsonSchema(Json.Schema.JsonSchema schema, bool throwOnFailure = true) { AddOutput(new ValidateJsonSchemaObjectDefinition(schema, throwOnFailure)); return Self; } /// public TSelf ValidateXsd(string xsdContent, bool throwOnFailure = true) { AddOutput(new ValidateXsdStringDefinition(xsdContent, throwOnFailure)); return Self; } /// public TSelf ValidateXsd(string? targetNamespace, string xsdContent, bool throwOnFailure = true) { AddOutput(new ValidateXsdNamespaceDefinition(targetNamespace, xsdContent, throwOnFailure)); return Self; } /// public TSelf ValidateXsd(System.Xml.Schema.XmlSchemaSet schemaSet, bool throwOnFailure = true) { AddOutput(new ValidateXsdSchemaSetDefinition(schemaSet, throwOnFailure)); return Self; } /// public TSelf ValidateXsdFile(string schemaPath, string? targetNamespace = null, string? schemaRoot = null, bool throwOnFailure = true) { AddOutput(new ValidateXsdFileDefinition(schemaPath, targetNamespace, schemaRoot, throwOnFailure)); return Self; } // ── XSLT ───────────────────────────────────────────────────────────────── /// /// Apache Camel xslt: parity: transform the exchange body through an XSLT stylesheet loaded /// from a file (compiled once, reused; xsl:import/xsl:include resolve relative /// to the file). BCL XslCompiledTransform engine (XSLT 1.0). /// public TSelf Xslt(string stylesheetPath, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false) { AddOutput(new XsltFileDefinition(stylesheetPath, output, failOnNullBody, allowTemplateFromHeader)); return Self; } /// /// Transform the exchange body through an inline XSLT stylesheet document (self-contained; /// no xsl:import/xsl:include). /// public TSelf XsltContent(string stylesheetXml, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false) { AddOutput(new XsltContentDefinition(stylesheetXml, output, failOnNullBody, allowTemplateFromHeader)); return Self; } // ── Control Bus ────────────────────────────────────────────────────────── /// /// Apache Camel controlbus: parity: manage a route at runtime by sending a control message. /// Sugar over .To("controlbus:route?routeId=...&action=..."). Use routeId "current" /// to target the sending route. Stopping the current route uses async dispatch to avoid a self-deadlock. /// public TSelf ControlBus(redb.Route.ControlBus.ControlBusAction action, string routeId, bool async = false) { ArgumentException.ThrowIfNullOrWhiteSpace(routeId); var uri = $"controlbus:route?routeId={System.Uri.EscapeDataString(routeId)}&action={action.ToString().ToLowerInvariant()}"; if (async) uri += "&async=true"; return To(uri); } // ── Serialization ──────────────────────────────────────────────────────── /// public TSelf Marshal(Type serializerType) { AddOutput(new MarshalDefinition(serializerType)); return Self; } /// public TSelf Marshal() where TSerializer : class { AddOutput(new MarshalDefinition(typeof(TSerializer))); return Self; } /// public TSelf Unmarshal(Type serializerType, Type targetType) { AddOutput(new UnmarshalDefinition(serializerType, targetType)); return Self; } /// public TSelf Unmarshal() where TSerializer : class { AddOutput(new UnmarshalDefinition(typeof(TSerializer), typeof(TTarget))); return Self; } /// public TSelf Marshal(string contentType) { AddOutput(new MarshalDefinition(contentType)); return Self; } /// public TSelf Marshal(IMessageSerializer serializer) { AddOutput(new MarshalDefinition(serializer)); return Self; } /// public TSelf Unmarshal(string contentType) { AddOutput(new UnmarshalDefinition(contentType, typeof(T))); return Self; } /// public TSelf Unmarshal(string contentType, Type targetType) { AddOutput(new UnmarshalDefinition(contentType, targetType)); return Self; } /// public TSelf Unmarshal(IMessageSerializer serializer) { AddOutput(new UnmarshalDefinition(serializer, typeof(T))); return Self; } /// public TSelf Unmarshal(IMessageSerializer serializer, Type targetType) { AddOutput(new UnmarshalDefinition(serializer, targetType)); return Self; } /// /// Converts the body to via the registered type converters — /// an alias of . This does not decode by format/ContentType; /// for JSON/XML/etc. decoding use with /// an explicit serializer. /// public TSelf Unmarshal() { AddOutput(new ConvertBodyDefinition(typeof(T))); return Self; } /// Apache Camel parity: convert the exchange body to . public TSelf ConvertBody() { AddOutput(new ConvertBodyDefinition(typeof(T))); return Self; } /// Apache Camel parity: convert the exchange body to . public TSelf ConvertBody(Type targetType) { AddOutput(new ConvertBodyDefinition(targetType)); return Self; } /// /// Apache Camel parity: open a typed scope. Auto-converts the body to /// and exposes typed Process/Filter/Transform overloads to its children. /// public OfTypeDefinition OfType() { var def = new OfTypeDefinition(); AddOutput(def); return def; } // ── Transactions ───────────────────────────────────────────────────────── /// public TSelf BeginTransaction() { AddOutput(new BeginTransactionDefinition()); return Self; } /// public TSelf BeginTransaction(Transactions.TransactionPolicy policy) { AddOutput(new BeginTransactionDefinition(policy)); return Self; } /// public TSelf CommitTransaction() { AddOutput(new CommitTransactionDefinition()); return Self; } /// public TSelf RollbackTransaction() { AddOutput(new RollbackTransactionDefinition()); return Self; } /// public TransactionDefinition Transaction(TransactionPolicy? policy = null) { var def = new TransactionDefinition(policy); AddOutput(def); return def; } // ── Replay checkpoints ────────────────────────────────────────────────── /// /// Opens a replay checkpoint (save-point). The steps that follow become the marker's body /// (the tail re-run on replay). On each pass the exchange is snapshotted into /// route.checkpoint. At the very start of a route no /// is needed (the body is the whole pipeline); in the middle or with several markers, close with /// or use the lambda-body overload. /// /// Save-point name, unique within the route. /// /// When true, the marker is also an addressable public entry (.To(...) / tests); /// default false = internal replay only via . /// public ReplayableDefinition Replayable(string name, bool exposed = false) { ArgumentException.ThrowIfNullOrWhiteSpace(name); var def = new ReplayableDefinition(name, exposed); AddOutput(def); return def; // opener returns the child — subsequent steps fall into its body } /// /// Lambda-body form of — unambiguous at any nesting level. /// The configures the marker's tail; the chain stays on the current /// definition (no explicit End). /// public TSelf Replayable(string name, Action body, bool exposed = false) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(body); var def = new ReplayableDefinition(name, exposed); AddOutput(def); body(def); return Self; } // ── Telemetry ──────────────────────────────────────────────────────────── /// public TracedDefinition Traced(string operationName) { var def = new TracedDefinition(operationName); AddOutput(def); return def; } /// public TSelf Traced(string operationName, Action action) { ArgumentException.ThrowIfNullOrWhiteSpace(operationName); AddOutput(new ProcessInstanceDefinition( new Telemetry.InstrumentedProcessor(new Processors.DelegateProcessor(action), operationName))); return Self; } /// public TSelf Traced(string operationName, Func action) { ArgumentException.ThrowIfNullOrWhiteSpace(operationName); ArgumentNullException.ThrowIfNull(action); AddOutput(new ProcessInstanceDefinition( new Telemetry.InstrumentedProcessor(new Processors.DelegateProcessor(action), operationName))); return Self; } /// public TSelf Traced(string operationName, IProcessor processor) { ArgumentException.ThrowIfNullOrWhiteSpace(operationName); ArgumentNullException.ThrowIfNull(processor); AddOutput(new ProcessInstanceDefinition( new Telemetry.InstrumentedProcessor(processor, operationName))); return Self; } /// public MeteredDefinition Metered(string stepName) { ArgumentException.ThrowIfNullOrWhiteSpace(stepName); if (stepName.Contains("${")) throw new ArgumentException( $"Metered() step name must be a constant to avoid metric cardinality explosion (got dynamic template '{stepName}'). " + "Use tags on the activity instead of templating the name.", nameof(stepName)); var def = new MeteredDefinition(stepName); AddOutput(def); return def; } /// public TSelf Metered(string stepName, Action action) { ArgumentException.ThrowIfNullOrWhiteSpace(stepName); ArgumentNullException.ThrowIfNull(action); if (stepName.Contains("${")) throw new ArgumentException( $"Metered() step name must be a constant to avoid metric cardinality explosion (got dynamic template '{stepName}').", nameof(stepName)); AddOutput(new ProcessInstanceDefinition( new Telemetry.MeteredStepProcessor(new Processors.DelegateProcessor(action), stepName))); return Self; } /// public TSelf Metered(string stepName, Func action) { ArgumentException.ThrowIfNullOrWhiteSpace(stepName); ArgumentNullException.ThrowIfNull(action); AddOutput(new ProcessInstanceDefinition( new Telemetry.MeteredStepProcessor(new Processors.DelegateProcessor(action), stepName))); return Self; } /// public TSelf Metered(string stepName, IProcessor processor) { ArgumentException.ThrowIfNullOrWhiteSpace(stepName); ArgumentNullException.ThrowIfNull(processor); AddOutput(new ProcessInstanceDefinition( new Telemetry.MeteredStepProcessor(processor, stepName))); return Self; } /// public TSelf SpanTag(string key, string value, Telemetry.SpanTarget target = Telemetry.SpanTarget.Enclosing) { // A constant tag that is never set is a mistake in the route, not a value to skip per message. ArgumentException.ThrowIfNullOrEmpty(value); return SpanTag(key, new Expressions.ConstantExpression(value), target); } /// public TSelf SpanTag(string key, IExpression value, Telemetry.SpanTarget target = Telemetry.SpanTarget.Enclosing) { AddOutput(new SpanTagDefinition(key, value, target)); return Self; } // ── Enrichment ─────────────────────────────────────────────────────────── /// public TSelf WireTap(string uri, string? executorService = null) { AddOutput(new WireTapDefinition(uri, executorService: executorService)); return Self; } /// public TSelf WireTap(string uri, Action onPrepare, string? executorService = null) { AddOutput(new WireTapDefinition(uri, onPrepare: onPrepare, executorService: executorService)); return Self; } /// public TSelf WireTap(string uri, Func newBodyFactory, string? executorService = null) { AddOutput(new WireTapDefinition(uri, newBodyFactory: newBodyFactory, executorService: executorService)); return Self; } /// public TSelf WireTap(string uri, Action onPrepare, Func newBodyFactory, string? executorService = null) { AddOutput(new WireTapDefinition(uri, onPrepare, newBodyFactory, executorService: executorService)); return Self; } /// public TSelf WireTap(Func uriFactory, string? executorService = null) { AddOutput(new WireTapDynamicDefinition(uriFactory, executorService: executorService)); return Self; } /// public TSelf WireTap(Func uriFactory, Action onPrepare, string? executorService = null) { AddOutput(new WireTapDynamicDefinition(uriFactory, onPrepare: onPrepare, executorService: executorService)); return Self; } /// public TSelf WireTap(Func uriFactory, Func newBodyFactory, string? executorService = null) { AddOutput(new WireTapDynamicDefinition(uriFactory, newBodyFactory: newBodyFactory, executorService: executorService)); return Self; } /// public TSelf WireTap(Func uriFactory, Action onPrepare, Func newBodyFactory, string? executorService = null) { AddOutput(new WireTapDynamicDefinition(uriFactory, onPrepare, newBodyFactory, executorService: executorService)); return Self; } /// public TSelf Enrich(string resourceUri, Func mergeStrategy) { AddOutput(new EnrichDefinition(resourceUri, mergeStrategy)); return Self; } /// public TSelf Enrich(Func uriFactory, Func mergeStrategy) { AddOutput(new EnrichDynamicDefinition(uriFactory, mergeStrategy)); return Self; } /// Apache Camel parity: poll an external endpoint and merge the polled result. public TSelf PollEnrich( string resourceUri, Func mergeStrategy, TimeSpan? timeout = null) { AddOutput(new PollEnrichDefinition(resourceUri, mergeStrategy, timeout)); return Self; } /// public TSelf PollEnrich( Func uriFactory, Func mergeStrategy, TimeSpan? timeout = null) { AddOutput(new PollEnrichDynamicDefinition(uriFactory, mergeStrategy, timeout)); return Self; } /// public TSelf Enrich(string resourceUri) => Enrich(resourceUri, Aggregation.AggregationStrategies.UseLatest()); /// public TSelf Enrich(Func uriFactory) => Enrich(uriFactory, Aggregation.AggregationStrategies.UseLatest()); /// public TSelf Enrich(IExpression uri, Func mergeStrategy) => Enrich(Expressions.ExpressionValues.Required(uri, nameof(Enrich)), mergeStrategy); /// public TSelf Enrich(IExpression uri) => Enrich(uri, Aggregation.AggregationStrategies.UseLatest()); /// public TSelf PollEnrich(string resourceUri, TimeSpan? timeout = null) => PollEnrich(resourceUri, static (original, polled) => polled ?? original, timeout); /// public TSelf PollEnrich(Func uriFactory, TimeSpan? timeout = null) => PollEnrich(uriFactory, static (original, polled) => polled ?? original, timeout); /// public TSelf PollEnrich( IExpression uri, Func mergeStrategy, TimeSpan? timeout = null) => PollEnrich(Expressions.ExpressionValues.Required(uri, nameof(PollEnrich)), mergeStrategy, timeout); /// public TSelf PollEnrich(IExpression uri, TimeSpan? timeout = null) => PollEnrich(uri, static (original, polled) => polled ?? original, timeout); /// Apache Camel parity: route to a list of recipient URIs computed at runtime. public TSelf RecipientList( Func> recipientListFactory, bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null) { AddOutput(new RecipientListDefinition( recipientListFactory, parallelProcessing, stopOnException, aggregationStrategy)); return Self; } /// public TSelf RecipientList( IExpression recipients, bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null, string uriDelimiter = ",") => RecipientList( Expressions.ExpressionValues.UriList(recipients, uriDelimiter), parallelProcessing, stopOnException, aggregationStrategy); /// Apache Camel parity: iteratively route to URIs returned by a routing function. public TSelf DynamicRouter(Func routingFunction) { AddOutput(new DynamicRouterDefinition(routingFunction)); return Self; } /// public TSelf DynamicRouter(IExpression routingExpression) => DynamicRouter(Expressions.ExpressionValues.Optional(routingExpression)); /// /// Apache Camel parity: Routing Slip — pipe the exchange through a list of endpoints computed /// once up front by (contrast Dynamic Router, which recomputes /// per hop). The same exchange is threaded through the endpoints in sequence (Out→In between hops). /// public TSelf RoutingSlip(Func> slipFactory, bool ignoreInvalidEndpoints = false) { AddOutput(new RoutingSlipDefinition(slipFactory, ignoreInvalidEndpoints)); return Self; } /// /// Apache Camel parity: Routing Slip from an yielding a delimited URI /// string (e.g. .RoutingSlip(Header("mySlip"))). Default delimiter is ,. /// public TSelf RoutingSlip(IExpression slip, string uriDelimiter = ",", bool ignoreInvalidEndpoints = false) { AddOutput(new RoutingSlipDefinition(slip, uriDelimiter, ignoreInvalidEndpoints)); return Self; } /// /// Apache Camel parity: Routing Slip from a ${...} template (or a literal like /// "direct:a,direct:b") resolving to a delimited URI string. Default delimiter is ,. /// public TSelf RoutingSlip(string slipTemplate, string uriDelimiter = ",", bool ignoreInvalidEndpoints = false) { AddOutput(new RoutingSlipDefinition(slipTemplate, uriDelimiter, ignoreInvalidEndpoints)); return Self; } /// /// Apache Camel parity: open a Resequencer scope. The contained child outputs receive /// exchanges in the order determined by . /// public ResequenceDefinition Resequence( Func keySelector, int batchSize = 100, TimeSpan? timeout = null) { var def = new ResequenceDefinition(keySelector, batchSize, timeout); AddOutput(def); return def; } // ── Scope openers ──────────────────────────────────────────────────────── /// public FilterDefinition Filter(Func predicate) { var def = new FilterDefinition(predicate); AddOutput(def); return def; } /// public FilterDefinition Filter(IExpression expression) { ArgumentNullException.ThrowIfNull(expression); var def = new FilterDefinition(Predicates.PredicateFactory.FromExpression(expression)) { SourceExpression = expression, }; AddOutput(def); return def; } /// public FilterDefinition Filter(IPredicate predicate) { ArgumentNullException.ThrowIfNull(predicate); var def = new FilterDefinition(predicate) { SourcePredicate = predicate, }; AddOutput(def); return def; } /// public IdempotentConsumerDefinition IdempotentConsumer( IIdempotentRepository repository, Func keyExtractor, bool skipDuplicate = true) { var def = new IdempotentConsumerDefinition(repository, keyExtractor, skipDuplicate); AddOutput(def); return def; } /// /// Apache Camel parity overload that looks up the repository by registered name from the /// route context's . /// public IdempotentConsumerDefinition IdempotentConsumer( Func keyExtractor, string repositoryName, bool skipDuplicate = true) { var def = new IdempotentConsumerDefinition(repositoryName, keyExtractor, skipDuplicate); AddOutput(def); return def; } /// public IdempotentConsumerDefinition IdempotentConsumer( IIdempotentRepository repository, IExpression messageId, bool skipDuplicate = true) => IdempotentConsumer( repository, Expressions.ExpressionValues.Required(messageId, nameof(IdempotentConsumer)), skipDuplicate); /// public IdempotentConsumerDefinition IdempotentConsumer( IExpression messageId, string repositoryName, bool skipDuplicate = true) => IdempotentConsumer( Expressions.ExpressionValues.Required(messageId, nameof(IdempotentConsumer)), repositoryName, skipDuplicate); /// public TSelf ClaimCheck( ClaimCheckOperation operation, string? key = null, TimeSpan? ttl = null, string? repositoryName = null) { AddOutput(new ClaimCheckDefinition(operation, key, ttl, repositoryName)); return Self; } /// public TSelf ClaimCheck( IClaimCheckRepository repository, ClaimCheckOperation operation, string? key = null, TimeSpan? ttl = null) { ArgumentNullException.ThrowIfNull(repository); AddOutput(new ClaimCheckDefinition(repository, operation, key, ttl)); return Self; } IRouteDefinition IRouteDefinition.ClaimCheck( ClaimCheckOperation operation, string? key, TimeSpan? ttl, string? repositoryName) => ClaimCheck(operation, key, ttl, repositoryName); IRouteDefinition IRouteDefinition.ClaimCheck( IClaimCheckRepository repository, ClaimCheckOperation operation, string? key, TimeSpan? ttl) => ClaimCheck(repository, operation, key, ttl); /// public ChoiceDefinition Choice() { var def = new ChoiceDefinition(); AddOutput(def); return def; } /// public SplitDefinition Split(Func> splitter) { var def = new SplitDefinition(splitter); AddOutput(def); return def; } /// public SplitDefinition Split(IExpression expression) { var def = new SplitDefinition(expression); AddOutput(def); return def; } /// public SplitDefinition Split(Func> splitter) { var def = new SplitDefinition(splitter); AddOutput(def); return def; } /// public MulticastDefinition Multicast() { var def = new MulticastDefinition(); AddOutput(def); return def; } /// public ThreadsDefinition Threads(int poolSize) { var def = new ThreadsDefinition(poolSize); AddOutput(def); return def; } /// public TryCatchDefinition TryCatch() { var def = new TryCatchDefinition(); AddOutput(def); return def; } /// public AggregateDefinition Aggregate( Func correlationKey, Func aggregationStrategy, Func completionPredicate) { var def = new AggregateDefinition(correlationKey, aggregationStrategy, completionPredicate); AddOutput(def); return def; } /// public AggregateDefinition Aggregate( IExpression correlationKey, Func aggregationStrategy, Func completionPredicate) => Aggregate( Expressions.ExpressionValues.Required(correlationKey, nameof(Aggregate)), aggregationStrategy, completionPredicate); /// public ThrottleDefinition Throttle(int maxPerPeriod) { var def = new ThrottleDefinition(maxPerPeriod); AddOutput(def); return def; } /// public ThrottleDefinition Throttle(Func maxPerPeriodFactory) { var def = new ThrottleDefinition(maxPerPeriodFactory); AddOutput(def); return def; } /// public ThrottleDefinition Throttle(string maxPerPeriodExpression, TimeSpan? period = null) { ArgumentException.ThrowIfNullOrWhiteSpace(maxPerPeriodExpression); var expression = new StringExpression(maxPerPeriodExpression); var def = Throttle(exchange => expression.Evaluate(exchange)); return period is null ? def : def.Period(period.Value); } /// public KeyedThrottleDefinition Throttle( Func keyExtractor, int maxPerPeriod, TimeSpan? period = null) { var def = new KeyedThrottleDefinition(keyExtractor, maxPerPeriod, period); AddOutput(def); return def; } /// public KeyedThrottleDefinition Throttle( Func keyExtractor, Func maxPerPeriodFactory, TimeSpan? period = null) { var def = new KeyedThrottleDefinition(keyExtractor, maxPerPeriodFactory, period); AddOutput(def); return def; } /// public KeyedThrottleDefinition Throttle( string keyExpression, string maxPerPeriodExpression, TimeSpan? period = null) { ArgumentException.ThrowIfNullOrWhiteSpace(keyExpression); ArgumentException.ThrowIfNullOrWhiteSpace(maxPerPeriodExpression); var key = new StringExpression(keyExpression); var limit = new StringExpression(maxPerPeriodExpression); return Throttle( e => key.Evaluate(e)?.ToString() ?? string.Empty, e => limit.Evaluate(e), period); } /// public CircuitBreakerDefinition CircuitBreaker() { var def = new CircuitBreakerDefinition(); AddOutput(def); return def; } /// public DebounceDefinition Debounce(Func keyExtractor, TimeSpan quietPeriod) { var def = new DebounceDefinition(keyExtractor, quietPeriod); AddOutput(def); return def; } /// public LoopDefinition Loop(int count, bool copy = false, bool shareScope = true) { var def = new LoopDefinition(count, copy, shareScope); AddOutput(def); return def; } /// public LoopDefinition Loop(Func condition, bool copy = false, bool shareScope = true) { var def = new LoopDefinition(condition, copy, shareScope); AddOutput(def); return def; } /// public LoopDefinition Loop(IPredicate condition, bool copy = false, bool shareScope = true) { ArgumentNullException.ThrowIfNull(condition); var def = new LoopDefinition(condition, copy, shareScope); AddOutput(def); return def; } /// public LoopDefinition Loop(Func countFactory, bool copy = false, bool shareScope = true) { var def = new LoopDefinition(countFactory, copy, shareScope); AddOutput(def); return def; } /// public LoopDefinition Loop(string countExpression, bool copy = false, bool shareScope = true) { ArgumentException.ThrowIfNullOrWhiteSpace(countExpression); var expression = new StringExpression(countExpression); return Loop(exchange => expression.Evaluate(exchange), copy, shareScope); } // ── Bean / Service Activator ────────────────────────────────────────────── /// public TSelf Bean(Func method) { ArgumentNullException.ThrowIfNull(method); AddOutput(new BeanDefinition( typeof(TService), (svc, exchange, ct) => method((TService)svc, exchange, ct))); return Self; } /// public TSelf Bean(Func method) { ArgumentNullException.ThrowIfNull(method); AddOutput(new BeanDefinition( typeof(TService), (svc, exchange, _) => method((TService)svc, exchange))); return Self; } /// public TSelf Bean(Action method) { ArgumentNullException.ThrowIfNull(method); AddOutput(new BeanDefinition( typeof(TService), (svc, exchange, _) => { method((TService)svc, exchange); return Task.CompletedTask; })); return Self; } /// public TSelf Bean(string reference, string? method = null) => To(Components.Bean.BeanComponent.UriFor(reference, method)); // ── Scatter-Gather ──────────────────────────────────────────────────────── /// public TSelf ScatterGather( Func aggregationStrategy, params string[] recipients) { ArgumentNullException.ThrowIfNull(aggregationStrategy); if (recipients is null || recipients.Length == 0) throw new ArgumentException("At least one recipient is required.", nameof(recipients)); var def = new ScatterGatherDefinition(); ((IScatterGatherDefinition)def).Recipients(recipients); ((IScatterGatherDefinition)def).AggregationStrategy(aggregationStrategy); AddOutput(def); return Self; } /// public TSelf ScatterGather(Action configure) { ArgumentNullException.ThrowIfNull(configure); var def = new ScatterGatherDefinition(); configure(def); if (def.AggregationStrategy is null) throw new InvalidOperationException("AggregationStrategy is required for ScatterGather."); if (def.StaticRecipients is null && def.DynamicRecipients is null) throw new InvalidOperationException("Recipients are required for ScatterGather."); AddOutput(def); return Self; } // ── Saga ────────────────────────────────────────────────────────────────── /// public TSelf Saga(Action configure) { ArgumentNullException.ThrowIfNull(configure); var def = new SagaDefinition(); configure(def); if (def.Entries.Count == 0) throw new InvalidOperationException("Saga must have at least one step."); AddOutput(def); return Self; } /// public SagaDefinition Saga() { var def = new SagaDefinition(); AddOutput(def); return def; } // ── LoadBalance ─────────────────────────────────────────────────────────── /// public TSelf LoadBalance(ILoadBalancerStrategy strategy, params string[] uris) { ArgumentNullException.ThrowIfNull(strategy); if (uris is null || uris.Length == 0) throw new ArgumentException("At least one endpoint URI is required.", nameof(uris)); var def = new LoadBalancerDefinition(); ((ILoadBalancerDefinition)def).Endpoints(uris); ((ILoadBalancerDefinition)def).Strategy(strategy); AddOutput(def); return Self; } /// public TSelf LoadBalance(Action configure) { ArgumentNullException.ThrowIfNull(configure); var def = new LoadBalancerDefinition(); configure(def); if (def.Strategy is null) throw new InvalidOperationException( "Strategy is required for LoadBalance. Use UseRoundRobin(), UseFailover(), etc."); if (def.Endpoints is null || def.Endpoints.Length == 0) throw new InvalidOperationException("At least one endpoint is required for LoadBalance."); AddOutput(def); return Self; } // ── Normalizer ──────────────────────────────────────────────────────────── /// public TSelf Normalize(Action configure) { ArgumentNullException.ThrowIfNull(configure); var def = new NormalizerDefinition(); configure(def); if (def.IsEmpty) throw new InvalidOperationException("Normalizer requires at least one When clause."); AddOutput(def); return Self; } // ── Exception handling ──────────────────────────────────────────────────── /// public TSelf ExceptionHandled() { AddOutput(new ExceptionHandledDefinition()); return Self; } /// public TSelf RollbackAll() { AddOutput(new RollbackAllDefinition()); return Self; } /// public OnExceptionDefinition OnException() where TException : Exception => OnException(typeof(TException)); /// public OnExceptionDefinition OnException(params Type[] exceptionTypes) { if (exceptionTypes is null || exceptionTypes.Length == 0) throw new ArgumentException("At least one exception type is required.", nameof(exceptionTypes)); foreach (var type in exceptionTypes) { if (!typeof(Exception).IsAssignableFrom(type)) throw new ArgumentException( $"{type.Name} is not an Exception type.", nameof(exceptionTypes)); } var def = new OnExceptionDefinition(exceptionTypes); AddOutput(def); return def; } // ── Route-level policy ──────────────────────────────────────────────────── /// public TSelf Cluster(bool value = true) { _cluster = value; return Self; } /// public bool GetCluster() => _cluster; /// public TSelf MessageHistory(bool value = true) { _messageHistory = value; return Self; } /// public bool? GetMessageHistory() => _messageHistory; /// public TSelf Tracing(bool value = true) { _tracing = value; return Self; } /// public bool? GetTracing() => _tracing; /// public TSelf RoutePolicy(IRoutePolicy policy) { _routePolicy = policy ?? throw new ArgumentNullException(nameof(policy)); return Self; } /// public TSelf RoutePolicy(string policyName) { ArgumentException.ThrowIfNullOrWhiteSpace(policyName); _routePolicyName = policyName.TrimStart('#'); return Self; } /// public IRoutePolicy? GetRoutePolicy() => _routePolicy; /// public string? GetRoutePolicyName() => _routePolicyName; /// public TSelf RouteConfigurationId(string ids) { ArgumentException.ThrowIfNullOrWhiteSpace(ids); _routeConfigurationId = ids; return Self; } /// public string? GetRouteConfigurationId() => _routeConfigurationId; // ── Rich logging scope ──────────────────────────────────────────────────── /// public RichLogScopeDefinition Log() => Log(LogLevel.Information); /// public RichLogScopeDefinition Log(LogLevel level) { var def = new RichLogScopeDefinition(level); AddOutput(def); return def; } /// /// The DSL truthiness rule, shared with every string-condition path through /// . /// private protected static bool ConvertToBoolean(object? value) => Predicates.RouteTruthiness.ToBoolean(value); } Path: redb-route/redb.Route/Definitions/RoutingSlipDefinition.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/Definitions/RoutingSlipDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Expressions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Routing Slip EIP (Apache Camel parity): routes the exchange through a list of endpoints computed /// once up front. The slip may be supplied as a factory delegate, an /// that yields a delimited URI string, or a ${...} template string. Leaf node — no /// . /// /// Unlike (which recomputes the next hop per step) the slip is /// evaluated a single time; unlike (which fans out a copy to /// each recipient) the slip pipes the same exchange through the endpoints in sequence. /// /// public sealed class RoutingSlipDefinition : ProcessorDefinition { private const string DefaultDelimiter = ","; private readonly Func> _slipFactory; private readonly bool _ignoreInvalidEndpoints; /// Creates a routing slip from a factory that returns the endpoint URIs per exchange. public RoutingSlipDefinition(Func> slipFactory, bool ignoreInvalidEndpoints = false) { _slipFactory = slipFactory ?? throw new ArgumentNullException(nameof(slipFactory)); _ignoreInvalidEndpoints = ignoreInvalidEndpoints; } /// /// Creates a routing slip from an that evaluates to a delimited URI /// string (Camel form routingSlip(header("..."))). /// public RoutingSlipDefinition(IExpression slip, string uriDelimiter = DefaultDelimiter, bool ignoreInvalidEndpoints = false) { ArgumentNullException.ThrowIfNull(slip); var delimiter = string.IsNullOrEmpty(uriDelimiter) ? DefaultDelimiter : uriDelimiter; _slipFactory = ex => Split(slip.Evaluate(ex), delimiter); _ignoreInvalidEndpoints = ignoreInvalidEndpoints; } /// /// Creates a routing slip from a ${...} template that resolves to a delimited URI string /// (a literal like "direct:a,direct:b" works too). /// public RoutingSlipDefinition(string slipTemplate, string uriDelimiter = DefaultDelimiter, bool ignoreInvalidEndpoints = false) { ArgumentException.ThrowIfNullOrWhiteSpace(slipTemplate); var delimiter = string.IsNullOrEmpty(uriDelimiter) ? DefaultDelimiter : uriDelimiter; _slipFactory = ex => Split(ExpressionResolver.ProcessTemplate(slipTemplate, ex), delimiter); _ignoreInvalidEndpoints = ignoreInvalidEndpoints; } /// public override IProcessor CreateProcessor(IRouteContext context) { var logger = context.GetService()?.CreateLogger(); return new RoutingSlipProcessor(context, _slipFactory, _ignoreInvalidEndpoints, logger); } private static IEnumerable Split(string? slip, string delimiter) => string.IsNullOrEmpty(slip) ? Array.Empty() : slip.Split(delimiter, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); } Path: redb-route/redb.Route/Definitions/SagaDefinition.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/Definitions/SagaDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Definition for a Saga step. Collects saga step entries and builds a /// at route-build time. /// Supports both callback-style (via ) and /// fluent-scope-style (via / ). /// Inherits the leaf DSL from . /// public class SagaDefinition : RouteDefinitionBase, ISagaDefinition, IRouteScope { private readonly List _entries = []; /// The collected saga step entries (forward action + optional compensation). public IReadOnlyList Entries => _entries; /// Optional callback invoked after all steps complete successfully. public Func? CompletionCallback { get; private set; } // ── ISagaDefinition (callback-style builder) ────────────────────────────── /// public ISagaDefinition Step(Action action, Action compensate) { ArgumentNullException.ThrowIfNull(action); ArgumentNullException.ThrowIfNull(compensate); _entries.Add(new SagaStepEntry( (e, _) => { action(e); return Task.CompletedTask; }, (e, _) => { compensate(e); return Task.CompletedTask; })); return this; } /// public ISagaDefinition Step( Func action, Func compensate) { ArgumentNullException.ThrowIfNull(action); ArgumentNullException.ThrowIfNull(compensate); _entries.Add(new SagaStepEntry(action, compensate)); return this; } /// public ISagaDefinition Step(Action action) { ArgumentNullException.ThrowIfNull(action); _entries.Add(new SagaStepEntry( (e, _) => { action(e); return Task.CompletedTask; }, null)); return this; } /// public ISagaDefinition Step(Func action) { ArgumentNullException.ThrowIfNull(action); _entries.Add(new SagaStepEntry(action, null)); return this; } /// public ISagaDefinition Step(IProcessor action, IProcessor? compensate = null) { ArgumentNullException.ThrowIfNull(action); _entries.Add(new SagaStepEntry( action.Process, compensate is null ? null : compensate.Process)); return this; } /// public ISagaDefinition OnCompletion(Action callback) { ArgumentNullException.ThrowIfNull(callback); CompletionCallback = (e, _) => { callback(e); return Task.CompletedTask; }; return this; } /// public ISagaDefinition OnCompletion(Func callback) { ArgumentNullException.ThrowIfNull(callback); CompletionCallback = callback; return this; } // ── Scope / fluent-chain DSL ────────────────────────────────────────────── /// Adds a synchronous saga step with both action and compensation. public SagaDefinition SagaStep(Action action, Action compensate) { Step(action, compensate); return this; } /// Adds a synchronous saga step with no compensation. public SagaDefinition SagaStep(Action action) { Step(action); return this; } /// Adds an asynchronous saga step with both action and compensation. public SagaDefinition SagaStep( Func action, Func compensate) { Step(action, compensate); return this; } /// Adds an asynchronous saga step with no compensation. public SagaDefinition SagaStep(Func action) { Step(action); return this; } /// Sets the saga completion callback (synchronous). public SagaDefinition OnSagaCompletion(Action callback) { OnCompletion(callback); return this; } /// Sets the saga completion callback (asynchronous). public SagaDefinition OnSagaCompletion(Func callback) { OnCompletion(callback); return this; } /// Closes this saga scope and returns the parent route definition. public IRouteDefinition EndSaga() { return (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndSaga() can only be called on a saga scope opened via RouteDefinition.Saga().")); } /// public IRouteDefinition End() => EndSaga(); // ── ProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { if (_entries.Count == 0) throw new InvalidOperationException("Saga must have at least one step."); var logger = context.GetService()?.CreateLogger(); return new SagaProcessor(_entries.ToArray(), CompletionCallback, logger); } } /// A single saga step entry: forward action + optional compensation. /// Forward action to execute. /// Compensation to run on rollback (null = no compensation). public sealed record SagaStepEntry( Func Action, Func? Compensate); Path: redb-route/redb.Route/Definitions/ScatterGatherDefinition.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/Definitions/ScatterGatherDefinition.cs ---- using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Definition for a Scatter-Gather step. Collects configuration and creates a /// at route-build time. /// public sealed class ScatterGatherDefinition : ProcessorDefinition, IScatterGatherDefinition { /// Fixed recipient URIs (null when dynamic recipients are configured). public string[]? StaticRecipients { get; private set; } /// Runtime recipient factory (null when static recipients are configured). public Func>? DynamicRecipients { get; private set; } /// Mandatory pair-wise aggregation: (accumulated, current) → merged. public Func? AggregationStrategy { get; private set; } /// Maximum duration to wait for all responses (default: zero = no timeout). public TimeSpan Timeout { get; private set; } /// Whether recipients are processed in parallel (default: true). public bool ParallelProcessing { get; private set; } = true; /// Maximum degree of parallelism (0 = processor count). public int MaxDegreeOfParallelism { get; private set; } /// Whether to stop immediately on first exception (default: false). public bool StopOnException { get; private set; } // ── IScatterGatherDefinition — explicit to avoid name conflicts with properties ── IScatterGatherDefinition IScatterGatherDefinition.Recipients(params string[] uris) { StaticRecipients = uris ?? throw new ArgumentNullException(nameof(uris)); DynamicRecipients = null; return this; } IScatterGatherDefinition IScatterGatherDefinition.Recipients(Func> factory) { DynamicRecipients = factory ?? throw new ArgumentNullException(nameof(factory)); StaticRecipients = null; return this; } IScatterGatherDefinition IScatterGatherDefinition.AggregationStrategy(Func strategy) { AggregationStrategy = strategy ?? throw new ArgumentNullException(nameof(strategy)); return this; } IScatterGatherDefinition IScatterGatherDefinition.Timeout(TimeSpan timeout) { Timeout = timeout >= TimeSpan.Zero ? timeout : throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be non-negative."); return this; } IScatterGatherDefinition IScatterGatherDefinition.ParallelProcessing(bool parallel) { ParallelProcessing = parallel; return this; } IScatterGatherDefinition IScatterGatherDefinition.MaxDegreeOfParallelism(int maxDop) { MaxDegreeOfParallelism = maxDop >= 0 ? maxDop : throw new ArgumentOutOfRangeException(nameof(maxDop), "Max DOP must be non-negative."); return this; } IScatterGatherDefinition IScatterGatherDefinition.StopOnException(bool stop) { StopOnException = stop; return this; } /// public override IProcessor CreateProcessor(IRouteContext context) { if (AggregationStrategy is null) throw new InvalidOperationException("AggregationStrategy is required for ScatterGather."); if (StaticRecipients is null && DynamicRecipients is null) throw new InvalidOperationException("Recipients are required for ScatterGather."); var logger = context.GetService()?.CreateLogger(); return StaticRecipients is not null ? new ScatterGatherProcessor(context, StaticRecipients, AggregationStrategy, ParallelProcessing, MaxDegreeOfParallelism, StopOnException, Timeout, logger) : new ScatterGatherProcessor(context, DynamicRecipients!, AggregationStrategy, ParallelProcessing, MaxDegreeOfParallelism, StopOnException, Timeout, logger); } } Path: redb-route/redb.Route/Definitions/SerializationDefinition.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/Definitions/SerializationDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Serialization; namespace redb.Route.Definitions; /// /// Resolves the serializer of a Marshal / Unmarshal node from whichever form the DSL /// used: an instance (options per node), a content type (looked up in /// at route build — an unregistered format fails Start()), or a serializer type (instantiated /// with its parameterless constructor). /// internal static class DataFormatResolution { public static IMessageSerializer Resolve(IRouteContext context, Type? serializerType, IMessageSerializer? serializer, string? contentType) { if (serializer is not null) return serializer; if (contentType is not null) { var registry = context.GetService() ?? throw new InvalidOperationException("IDataFormatRegistry is not available on the route context."); return registry.GetSerializer(contentType) ?? throw new InvalidOperationException( $"Data format '{contentType}' is not registered. Register it with context.AddDataFormat(...) " + "(a format package offers e.g. AddCsvDataFormat()) or pass the serializer instance: Marshal(new CsvDataFormat(...))."); } return (IMessageSerializer)Activator.CreateInstance(serializerType!)!; } } /// /// Leaf definition that serializes the exchange body with an : /// by type (Marshal<JsonMessageSerializer>()), by instance (Marshal(new CsvDataFormat(o))) /// or by registered content type (Marshal("text/csv")). /// public sealed class MarshalDefinition : ProcessorDefinition { private readonly Type? _serializerType; private readonly IMessageSerializer? _serializer; /// Serializer created from its parameterless constructor at route build. public MarshalDefinition(Type serializerType) { ArgumentNullException.ThrowIfNull(serializerType); _serializerType = serializerType; } /// A configured serializer instance (per-node options). public MarshalDefinition(IMessageSerializer serializer) { ArgumentNullException.ThrowIfNull(serializer); _serializer = serializer; } /// A content type resolved in the context's at route build. public MarshalDefinition(string contentType) { ArgumentException.ThrowIfNullOrWhiteSpace(contentType); ContentType = contentType; } /// Content type used for registry resolution, when the node was declared that way (XML form format=). public string? ContentType { get; } /// public override IProcessor CreateProcessor(IRouteContext context) => new MarshalProcessor(DataFormatResolution.Resolve(context, _serializerType, _serializer, ContentType)); } /// /// Leaf definition that deserializes the exchange body to with an /// chosen by type, by instance or by registered content type. /// public sealed class UnmarshalDefinition : ProcessorDefinition { private readonly Type? _serializerType; private readonly IMessageSerializer? _serializer; /// Serializer created from its parameterless constructor at route build. public UnmarshalDefinition(Type serializerType, Type targetType) { ArgumentNullException.ThrowIfNull(serializerType); ArgumentNullException.ThrowIfNull(targetType); _serializerType = serializerType; TargetType = targetType; } /// A configured serializer instance (per-node options). public UnmarshalDefinition(IMessageSerializer serializer, Type targetType) { ArgumentNullException.ThrowIfNull(serializer); ArgumentNullException.ThrowIfNull(targetType); _serializer = serializer; TargetType = targetType; } /// A content type resolved in the context's at route build. public UnmarshalDefinition(string contentType, Type targetType) { ArgumentException.ThrowIfNullOrWhiteSpace(contentType); ArgumentNullException.ThrowIfNull(targetType); ContentType = contentType; TargetType = targetType; } /// Content type used for registry resolution, when the node was declared that way (XML form format=). public string? ContentType { get; } /// CLR type the body is deserialized to. public Type TargetType { get; } /// public override IProcessor CreateProcessor(IRouteContext context) => new UnmarshalProcessor(DataFormatResolution.Resolve(context, _serializerType, _serializer, ContentType), TargetType); } /// /// Leaf definition that converts the exchange body to a target type via /// (resolved from the message content type) or the built-in conversions. /// public sealed class ConvertBodyDefinition : ProcessorDefinition { private readonly Type _targetType; /// Creates the node. public ConvertBodyDefinition(Type targetType) { ArgumentNullException.ThrowIfNull(targetType); _targetType = targetType; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ConvertBodyProcessor(_targetType, context.GetService()); } Path: redb-route/redb.Route/Definitions/SetBodyDefinition.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/Definitions/SetBodyDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that sets the exchange body to a static value. /// public sealed class SetBodyStaticDefinition : ProcessorDefinition { private readonly object? _value; /// Creates a set-body definition with a static value. public SetBodyStaticDefinition(object? value) { _value = value; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Body = _value); } /// /// Leaf definition that sets the exchange body using a factory function. /// public sealed class SetBodyFactoryDefinition : ProcessorDefinition { private readonly Func _factory; /// Creates a set-body definition using a factory. public SetBodyFactoryDefinition(Func factory) { ArgumentNullException.ThrowIfNull(factory); _factory = factory; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Body = _factory(exchange)); } /// /// Leaf definition that sets the exchange body using an . /// public sealed class SetBodyExpressionDefinition : ProcessorDefinition { private readonly IExpression _expression; /// The expression producing the body value. public IExpression Expression => _expression; /// Creates a set-body definition from an expression. public SetBodyExpressionDefinition(IExpression expression) { ArgumentNullException.ThrowIfNull(expression); _expression = expression; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ExpressionBodyProcessor(_expression); } Path: redb-route/redb.Route/Definitions/SetHeaderDefinition.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/Definitions/SetHeaderDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that sets a header on the exchange to a static value. /// public sealed class SetHeaderStaticDefinition : ProcessorDefinition { private readonly string _key; private readonly object? _value; /// Creates a set-header definition with a static value. public SetHeaderStaticDefinition(string key, object? value) { ArgumentException.ThrowIfNullOrWhiteSpace(key); _key = key; _value = value; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Headers[_key] = _value); } /// /// Leaf definition that sets a header on the exchange using a factory function. /// public sealed class SetHeaderFactoryDefinition : ProcessorDefinition { private readonly string _key; private readonly Func _factory; /// Creates a set-header definition using a factory. public SetHeaderFactoryDefinition(string key, Func factory) { ArgumentException.ThrowIfNullOrWhiteSpace(key); ArgumentNullException.ThrowIfNull(factory); _key = key; _factory = factory; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Headers[_key] = _factory(exchange)); } /// /// Leaf definition that sets a header on the exchange using an . /// public sealed class SetHeaderExpressionDefinition : ProcessorDefinition { private readonly string _name; private readonly IExpression _expression; /// The header name to set. public string Name => _name; /// The expression producing the header value. public IExpression Expression => _expression; /// Creates a set-header definition from an expression. public SetHeaderExpressionDefinition(string name, IExpression expression) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(expression); _name = name; _expression = expression; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ExpressionHeaderProcessor(_name, _expression); } /// /// Leaf definition that removes a header from the exchange. /// public sealed class RemoveHeaderDefinition : ProcessorDefinition { private readonly string _key; /// Creates a remove-header definition. public RemoveHeaderDefinition(string key) { ArgumentException.ThrowIfNullOrWhiteSpace(key); _key = key; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Headers.Remove(_key)); } /// /// Leaf definition that removes the body of the exchange (sets it to null). /// public sealed class RemoveBodyDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Body = null); } Path: redb-route/redb.Route/Definitions/SetHeadersDefinition.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/Definitions/SetHeadersDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Sets several headers in one step (one Message History entry). A value that is an /// is evaluated per message, a Func<IExchange, object?> is invoked, /// anything else is a constant. /// public sealed class SetHeadersDefinition : ProcessorDefinition { /// Creates the node. public SetHeadersDefinition(IReadOnlyList<(string Name, object? Value)> headers) { ArgumentNullException.ThrowIfNull(headers); if (headers.Count == 0) throw new ArgumentException("At least one header is required.", nameof(headers)); foreach (var (name, _) in headers) ArgumentException.ThrowIfNullOrWhiteSpace(name); Headers = headers; } /// Header names and value sources. public IReadOnlyList<(string Name, object? Value)> Headers { get; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => { foreach (var (name, value) in Headers) exchange.In.Headers[name] = value switch { IExpression expression => expression.Evaluate(exchange), Func factory => factory(exchange), _ => value, }; }); } Path: redb-route/redb.Route/Definitions/SetPropertiesDefinition.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/Definitions/SetPropertiesDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Sets several exchange properties in one step (one Message History entry), the property twin of /// . A value that is an is evaluated per /// message, a Func<IExchange, object?> is invoked, anything else is a constant. The /// properties are set in order, so a later value may read an earlier one. /// public sealed class SetPropertiesDefinition : ProcessorDefinition { /// Creates the node. public SetPropertiesDefinition(IReadOnlyList<(string Name, object? Value)> properties) { ArgumentNullException.ThrowIfNull(properties); if (properties.Count == 0) throw new ArgumentException("At least one property is required.", nameof(properties)); foreach (var (name, _) in properties) ArgumentException.ThrowIfNullOrWhiteSpace(name); Properties = properties; } /// Property names and value sources. public IReadOnlyList<(string Name, object? Value)> Properties { get; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => { foreach (var (name, value) in Properties) exchange.Properties[name] = value switch { IExpression expression => expression.Evaluate(exchange), Func factory => factory(exchange), _ => value, }; }); } Path: redb-route/redb.Route/Definitions/SetPropertyDefinition.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/Definitions/SetPropertyDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that sets an exchange property to a static value. /// public sealed class SetPropertyStaticDefinition : ProcessorDefinition { private readonly string _key; private readonly object? _value; /// Creates a set-property definition with a static value. public SetPropertyStaticDefinition(string key, object? value) { ArgumentException.ThrowIfNullOrWhiteSpace(key); _key = key; _value = value; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.Properties[_key] = _value); } /// /// Leaf definition that sets an exchange property using a factory function. /// public sealed class SetPropertyFactoryDefinition : ProcessorDefinition { private readonly string _key; private readonly Func _factory; /// Creates a set-property definition using a factory. public SetPropertyFactoryDefinition(string key, Func factory) { ArgumentException.ThrowIfNullOrWhiteSpace(key); ArgumentNullException.ThrowIfNull(factory); _key = key; _factory = factory; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.Properties[_key] = _factory(exchange)); } /// /// Leaf definition that sets an exchange property using an . /// public sealed class SetPropertyExpressionDefinition : ProcessorDefinition { private readonly string _key; private readonly IExpression _expression; /// Creates a set-property definition from an expression. public SetPropertyExpressionDefinition(string key, IExpression expression) { ArgumentException.ThrowIfNullOrWhiteSpace(key); ArgumentNullException.ThrowIfNull(expression); _key = key; _expression = expression; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ExpressionPropertyProcessor(_key, _expression); } /// /// Leaf definition that removes a property from the exchange. /// public sealed class RemovePropertyDefinition : ProcessorDefinition { private readonly string _key; /// Creates a remove-property definition. public RemovePropertyDefinition(string key) { ArgumentException.ThrowIfNullOrWhiteSpace(key); _key = key; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.Properties.Remove(_key)); } Path: redb-route/redb.Route/Definitions/SortDefinition.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/Definitions/SortDefinition.cs ---- using System.Collections; using System.Globalization; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Sorts a collection taken from the exchange and puts the sorted list back into the body /// (Camel sort()). The optional key selector is evaluated per element; in the string form /// (Sort("body.items", "body.priority")) the key expression sees the element as body. /// Numbers compare numerically across CLR types, strings ordinally, null first. /// public sealed class SortDefinition : ProcessorDefinition { private readonly Func _source; private readonly Func? _key; private readonly IComparer _comparer; private readonly bool _descending; private readonly Func, object> _materialize; /// Creates the node. /// Collection to sort (evaluated on the exchange). /// Optional per-element key; null sorts the elements themselves. /// Optional comparer of keys; default compares numbers numerically, strings ordinally. /// Reverse order. /// Builds the body from the sorted elements (a typed List<T> for the generic DSL form). public SortDefinition(Func source, Func? key, IComparer? comparer, bool descending, Func, object>? materialize = null) { _source = source ?? throw new ArgumentNullException(nameof(source)); _key = key; _comparer = comparer ?? ValueComparer.Instance; _descending = descending; _materialize = materialize ?? (items => items.ToList()); } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => { var source = _source(exchange); if (source is null) return; if (source is string) throw new InvalidOperationException("Sort: the expression evaluated to a string, not a collection."); var items = source.Cast(); var keyed = _key is null ? items.Select(i => (Key: i, Item: i)) : items.Select(i => (Key: _key(i), Item: i)); var ordered = _descending ? keyed.OrderByDescending(p => p.Key, _comparer) : keyed.OrderBy(p => p.Key, _comparer); exchange.In.Body = _materialize(ordered.Select(p => p.Item)); }); /// Default key comparison: nulls first, numbers numerically, strings ordinally, then . public sealed class ValueComparer : IComparer { /// Shared instance. public static readonly ValueComparer Instance = new(); /// public int Compare(object? x, object? y) { if (ReferenceEquals(x, y)) return 0; if (x is null) return -1; if (y is null) return 1; if (IsNumber(x) && IsNumber(y)) return RouteDecimal.From(x).CompareTo(RouteDecimal.From(y)); if (x is string sx && y is string sy) return string.CompareOrdinal(sx, sy); if (x is IComparable cx && x.GetType() == y.GetType()) return cx.CompareTo(y); return string.CompareOrdinal(Convert.ToString(x, CultureInfo.InvariantCulture), Convert.ToString(y, CultureInfo.InvariantCulture)); } private static bool IsNumber(object value) => value is sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal; } } Path: redb-route/redb.Route/Definitions/SpanTagDefinition.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/Definitions/SpanTagDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Telemetry; namespace redb.Route.Definitions; /// /// Leaf definition of .SpanTag(key, value, target): one attribute on a span of the engine, so a trace can be /// found by a business key. The key is checked when the route is built (SpanTagPolicy); the value is an /// , a literal being a constant one. /// public sealed class SpanTagDefinition : ProcessorDefinition { /// Creates a span-tag definition. /// Attribute name: a constant, lowercase, dot-separated, outside the reserved namespaces. /// Expression producing the value, evaluated per message. /// Which span receives the attribute. /// is refused by the policy. public SpanTagDefinition(string key, IExpression value, SpanTarget target) { SpanTagPolicy.ValidateKey(key); ArgumentNullException.ThrowIfNull(value); if (!Enum.IsDefined(target)) throw new ArgumentOutOfRangeException(nameof(target), target, "Unknown span target."); Key = key; Value = value; Target = target; } /// The attribute name. public string Key { get; } /// The expression producing the attribute value. public IExpression Value { get; } /// Which span receives the attribute. public SpanTarget Target { get; } /// public override IProcessor CreateProcessor(IRouteContext context) => new SpanTagProcessor(Key, Value, Target, context.GetService()?.CreateLogger()); } Path: redb-route/redb.Route/Definitions/SplitMulticastDefinition.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/Definitions/SplitMulticastDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Expressions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Splitter EIP. /// Splits an exchange into sub-exchanges via a splitter function, /// then passes each sub-exchange through the child pipeline (Outputs). /// Inherits the leaf DSL from ; /// close with . /// public class SplitDefinition : RouteDefinitionBase, IRouteScope, ICompositeScope { private readonly Func>? _splitter; private readonly Func>? _asyncSplitter; private bool _parallel; private bool _stopOnException = true; private TimeSpan _timeout; private int _maxDegreeOfParallelism; private Func? _aggregationStrategy; /// Captured source when the splitter was built from an expression instance; null otherwise. public IExpression? SourceExpression { get; } internal SplitDefinition(Func> splitter) { ArgumentNullException.ThrowIfNull(splitter); _splitter = splitter; } internal SplitDefinition(IExpression expression) : this(ex => { var val = expression.Evaluate(ex); return val switch { IEnumerable e => e, System.Collections.IEnumerable e => e.Cast(), _ => throw new InvalidOperationException( $"Expression did not evaluate to an enumerable; got {val?.GetType().Name ?? "null"}."), }; }) { SourceExpression = expression; } internal SplitDefinition(Func> asyncSplitter) { ArgumentNullException.ThrowIfNull(asyncSplitter); _asyncSplitter = asyncSplitter; } // ── Options ──────────────────────────────────────────────────────────────── /// Enables parallel processing of split parts. public SplitDefinition Parallel(bool value = true) { _parallel = value; return this; } /// Apache Camel alias for . public SplitDefinition ParallelProcessing(bool value = true) => Parallel(value); /// Sets stop-on-exception behaviour (default: true). public SplitDefinition StopOnException(bool value = true) { _stopOnException = value; return this; } /// Sets maximum degree of parallelism (0 = cpu count). public SplitDefinition MaxParallelism(int value) { _maxDegreeOfParallelism = value; return this; } /// Sets a timeout for the entire split operation. public SplitDefinition Timeout(TimeSpan timeout) { _timeout = timeout; return this; } /// Sets the pair-wise aggregation strategy. public SplitDefinition AggregationStrategy(Func strategy) { _aggregationStrategy = strategy; return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this split scope and returns the parent route definition. public IRouteDefinition EndSplit() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndSplit() called without a parent route.")); /// public IRouteDefinition End() => EndSplit(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor body = NodePipeline.Body(context, Outputs); if (_asyncSplitter is not null) return new StreamingSplitterProcessor(_asyncSplitter, body, _stopOnException); return new SplitterProcessor( _splitter!, body, parallelProcessing: _parallel, maxDegreeOfParallelism: _maxDegreeOfParallelism, aggregationStrategy: _aggregationStrategy, stopOnException: _stopOnException, timeout: _timeout); } } /// /// Scope-opener definition for the Multicast EIP. /// Sends the exchange to all child endpoints (fan-out). /// Each output is compiled as one target processor for . /// Inherits the leaf DSL from ; /// close with . /// public class MulticastDefinition : RouteDefinitionBase, IRouteScope, ICompositeScope { private bool _parallel = true; private bool _stopOnException; private TimeSpan _timeout; private int _maxDegreeOfParallelism; private Func? _aggregationStrategy; internal MulticastDefinition() { } // ── Options ──────────────────────────────────────────────────────────────── /// Sets sequential processing (parallel = false). public MulticastDefinition Sequential() { _parallel = false; return this; } /// Enables parallel processing (default). public MulticastDefinition Parallel(bool value = true) { _parallel = value; return this; } /// Apache Camel alias for . public MulticastDefinition ParallelProcessing(bool value = true) => Parallel(value); /// Sets stop-on-exception behaviour (default: false). public MulticastDefinition StopOnException(bool value = true) { _stopOnException = value; return this; } /// Sets maximum degree of parallelism. public MulticastDefinition MaxParallelism(int value) { _maxDegreeOfParallelism = value; return this; } /// Sets a timeout for the entire multicast operation. public MulticastDefinition Timeout(TimeSpan timeout) { _timeout = timeout; return this; } /// Sets the pair-wise aggregation strategy. public MulticastDefinition AggregationStrategy(Func strategy) { _aggregationStrategy = strategy; return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this multicast scope and returns the parent route definition. public IRouteDefinition EndMulticast() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndMulticast() called without a parent route.")); /// public IRouteDefinition End() => EndMulticast(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { var multicast = new MulticastProcessor( parallelProcessing: _parallel, aggregationStrategy: _aggregationStrategy, stopOnException: _stopOnException, timeout: _timeout, maxDegreeOfParallelism: _maxDegreeOfParallelism); foreach (var output in Outputs) multicast.AddTarget(NodePipeline.Node(context, output)); return multicast; } } Path: redb-route/redb.Route/Definitions/StopDelayDefinition.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/Definitions/StopDelayDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that stops exchange processing (sets exchange.Stop()). /// public sealed class StopDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.Stop()); } /// /// Leaf definition that delays processing by a fixed . /// public sealed class DelayDefinition : ProcessorDefinition { private readonly TimeSpan _duration; /// Creates a delay definition with a fixed duration. public DelayDefinition(TimeSpan duration) { _duration = duration; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelayProcessor(_duration); } /// /// Leaf definition that delays processing by a duration computed from the exchange. /// public sealed class DelayFactoryDefinition : ProcessorDefinition { private readonly Func _durationFactory; /// Creates a delay definition using a factory. public DelayFactoryDefinition(Func durationFactory) { ArgumentNullException.ThrowIfNull(durationFactory); _durationFactory = durationFactory; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(async (exchange, ct) => { var delay = _durationFactory(exchange); if (delay > TimeSpan.Zero) await Task.Delay(delay, ct).ConfigureAwait(false); }); } /// /// Leaf definition that delays processing by a duration resolved from a string expression template. /// public sealed class DelayExpressionDefinition : ProcessorDefinition { private readonly string _expression; /// Creates a delay definition from a string expression template. public DelayExpressionDefinition(string expression) { ArgumentException.ThrowIfNullOrWhiteSpace(expression); _expression = expression; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(async (exchange, ct) => { var raw = Expressions.ExpressionResolver.ProcessTemplate(_expression, exchange); var delay = ConvertToTimeSpan(raw); if (delay > TimeSpan.Zero) await Task.Delay(delay, ct).ConfigureAwait(false); }); /// Delay value → : a , a number of milliseconds, or hh:mm:ss text. internal static TimeSpan ConvertToTimeSpan(object? value) => value switch { TimeSpan ts => ts, int ms => TimeSpan.FromMilliseconds(ms), long ms => TimeSpan.FromMilliseconds(ms), double ms => TimeSpan.FromMilliseconds(ms), string s when double.TryParse(s, System.Globalization.CultureInfo.InvariantCulture, out var ms) => TimeSpan.FromMilliseconds(ms), string s when TimeSpan.TryParse(s, out var ts) => ts, _ => throw new InvalidOperationException($"Cannot convert '{value}' to TimeSpan for delay.") }; } /// /// Leaf definition that samples messages by passing every N-th message (count-based). /// public sealed class SampleCountDefinition : ProcessorDefinition { private readonly long _messageFrequency; /// Gets the message frequency — every N-th message passes. public long MessageFrequency => _messageFrequency; /// Creates a sampling definition that allows every Nth message through. public SampleCountDefinition(long messageFrequency) { if (messageFrequency <= 0) throw new ArgumentOutOfRangeException(nameof(messageFrequency), "Must be > 0."); _messageFrequency = messageFrequency; } /// public override IProcessor CreateProcessor(IRouteContext context) => new SamplingProcessor(_messageFrequency); } /// /// Leaf definition that samples messages by period (at most one message per period). /// public sealed class SamplePeriodDefinition : ProcessorDefinition { private readonly TimeSpan _period; /// Gets the minimum period between forwarded messages. public TimeSpan Period => _period; /// Creates a sampling definition with a period gate. public SamplePeriodDefinition(TimeSpan period) { if (period <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(period), "Must be positive."); _period = period; } /// public override IProcessor CreateProcessor(IRouteContext context) => new SamplingProcessor(_period); } Path: redb-route/redb.Route/Definitions/ThreadsDefinition.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/Definitions/ThreadsDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Threads EIP (Camel-style concurrency stage). /// Wraps the child pipeline () and runs it on a bounded pool /// of poolSize persistent workers via , so a serial polling /// consumer can process up to poolSize exchanges concurrently. /// Inherits the leaf DSL from ; close with . /// /// Adaptive by exchange pattern: InOnly is a fire-and-forget hand-off (the exchange is cloned and /// run on the worker pool — a transaction boundary, like .To("seda://")); InOut runs the /// body inline on the same exchange under a SemaphoreSlim gate (≤ poolSize concurrent), so /// the reply — on Out or In — is preserved losslessly and request/reply works across it /// (InOut is NOT a transaction boundary — the ambient transaction flows into the inline body). /// Ordering is not preserved when poolSize > 1. /// /// public class ThreadsDefinition : RouteDefinitionBase, IRouteScope { private readonly int _poolSize; private int _maxQueueSize; // 0 = default (== poolSize) private TimeSpan? _enqueueTimeout; // null = wait indefinitely for a free slot internal ThreadsDefinition(int poolSize) { if (poolSize < 1) throw new ArgumentOutOfRangeException(nameof(poolSize), poolSize, "poolSize must be at least 1."); _poolSize = poolSize; } // ── Options ──────────────────────────────────────────────────────────────── /// /// Sets the bounded hand-off queue capacity (backpressure). 0 = default (== pool size). /// A larger queue lets the poll loop run further ahead of the pool before it throttles. /// public ThreadsDefinition MaxQueueSize(int value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, "maxQueueSize cannot be negative."); _maxQueueSize = value; return this; } /// /// Bounds how long a caller waits for a free worker slot when the pool + queue are saturated. /// Default (unset) = wait indefinitely (backpressure). When set and the window elapses, the enqueue /// fails with ; for an InOut/RPC exchange that becomes the reply fault /// (surfaced to the caller) instead of an unbounded wait. /// public ThreadsDefinition EnqueueTimeout(TimeSpan value) { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(value), value, "enqueueTimeout must be positive."); _enqueueTimeout = value; return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this threads scope and returns the parent route definition. public IRouteDefinition EndThreads() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndThreads() called without a parent route.")); /// public IRouteDefinition End() => EndThreads(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor body = NodePipeline.Body(context, Outputs); // An in-only exchange runs on a pool worker after its caller has returned, outside the route's error handlers: // that body is wrapped by the route's whole error scope. In-out runs inline, inside them, as it is. var detachedBody = (context as RouteContext)?.DetachedErrorScope?.WrapDetached(body) ?? body; var logger = context.GetService()?.CreateLogger(); return new ThreadsProcessor(body, detachedBody, _poolSize, _maxQueueSize, context, logger) { EnqueueTimeout = _enqueueTimeout }; } } Path: redb-route/redb.Route/Definitions/ThrottleDebounceDefinition.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/Definitions/ThrottleDebounceDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the Throttle EIP. /// Limits the rate at which the downstream pipeline processes exchanges. /// Inherits the leaf DSL from ; /// child steps build the downstream pipeline. /// Close with . /// public class ThrottleDefinition : RouteDefinitionBase, IRouteScope { private readonly Func _maxPerPeriod; private TimeSpan? _period; private bool _rejectOnOverflow; internal ThrottleDefinition(int maxPerPeriod) : this(_ => maxPerPeriod) { if (maxPerPeriod <= 0) throw new ArgumentOutOfRangeException(nameof(maxPerPeriod), "Must be > 0."); } /// Creates a throttle whose limit is computed per exchange by . internal ThrottleDefinition(Func maxPerPeriodFactory) { _maxPerPeriod = maxPerPeriodFactory ?? throw new ArgumentNullException(nameof(maxPerPeriodFactory)); } // ── Options ───────────────────────────────────────────────────────────────── /// Sets the time period for the rate limit (default: 1 second). public ThrottleDefinition Period(TimeSpan period) { _period = period; return this; } /// /// Opt into RFC 6585 §4 rejection semantics: overflow exchanges are short-circuited with /// HTTP 429 + Retry-After (RFC 7231 §7.1.3) instead of semaphore-waiting until a /// slot frees. Recommended for any HTTP-facing endpoint — silent waits look like a hung /// server to clients and break liveness probes. Default is false (legacy wait). /// public ThrottleDefinition RejectOnOverflow(bool reject = true) { _rejectOnOverflow = reject; return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes the Throttle scope and returns the parent route definition. public IRouteDefinition EndThrottle() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndThrottle() called without a parent route.")); /// public IRouteDefinition End() => EndThrottle(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor downstream = BuildPipeline(Outputs, context); var loggerFactory = context.GetService(); var logger = loggerFactory?.CreateLogger(); return new ThrottleProcessor(downstream, _maxPerPeriod, _period, _rejectOnOverflow, logger); } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } /// /// Scope-opener definition for the Debounce EIP. /// Suppresses rapid-fire exchanges per key, forwarding only the last exchange after /// a configurable quiet period. /// Inherits the leaf DSL from ; /// child steps build the downstream pipeline. /// Close with . /// public class DebounceDefinition : RouteDefinitionBase, IRouteScope { private readonly Func _keyExtractor; private readonly TimeSpan _quietPeriod; /// Gets the key extractor function used to correlate exchanges. public Func KeyExtractor => _keyExtractor; /// Gets the quiet period after which the last buffered exchange is forwarded. public TimeSpan QuietPeriod => _quietPeriod; internal DebounceDefinition(Func keyExtractor, TimeSpan quietPeriod) { _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); if (quietPeriod <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(quietPeriod), "Must be positive."); _quietPeriod = quietPeriod; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes the Debounce scope and returns the parent route definition. public IRouteDefinition EndDebounce() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndDebounce() called without a parent route.")); /// public IRouteDefinition End() => EndDebounce(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor downstream = BuildPipeline(Outputs, context); // The body only ever runs on a flush, after the exchange that fed it has left the route's error wrappers: it is // wrapped by the route's error scope (its OnException, its builder's, the context's handlers). downstream = (context as Core.RouteContext)?.DetachedErrorScope?.WrapDetached(downstream) ?? downstream; var loggerFactory = context.GetService(); var logger = loggerFactory?.CreateLogger(); return new DebounceProcessor(downstream, _keyExtractor, _quietPeriod, logger); } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } /// /// Scope-opener definition for the keyed (per-key) Throttle EIP. /// Limits the rate at which each unique key can enter the downstream pipeline. /// Inherits the leaf DSL from . /// Close with . /// public class KeyedThrottleDefinition : RouteDefinitionBase, IRouteScope { private readonly Func _keyExtractor; private readonly int _maxPerPeriod; private readonly TimeSpan? _period; private bool _rejectOnOverflow; /// Gets the key extractor function. public Func KeyExtractor => _keyExtractor; /// Gets the max exchanges per period per key. public int MaxPerPeriod => _maxPerPeriod; /// Gets the time period for the rate limit (null = 1 second default). public TimeSpan? Period => _period; internal KeyedThrottleDefinition(Func keyExtractor, int maxPerPeriod, TimeSpan? period) { _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); if (maxPerPeriod <= 0) throw new ArgumentOutOfRangeException(nameof(maxPerPeriod), "Must be > 0."); _maxPerPeriod = maxPerPeriod; MaxPerPeriodFactory = _ => maxPerPeriod; _period = period; } internal KeyedThrottleDefinition(Func keyExtractor, Func maxPerPeriodFactory, TimeSpan? period) { _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); MaxPerPeriodFactory = maxPerPeriodFactory ?? throw new ArgumentNullException(nameof(maxPerPeriodFactory)); _maxPerPeriod = 0; // dynamic: read per message _period = period; } /// /// Limit per key evaluated on each message (key and limit come from the message: /// "gold customers 100 per second, others 10, each under its own key"). The fixed int /// form is the constant factory; is 0 when the limit is dynamic. /// public Func MaxPerPeriodFactory { get; } // ── Options ───────────────────────────────────────────────────────────────── /// /// Opt into RFC 6585 §4 rejection semantics: overflow exchanges are short-circuited with /// HTTP 429 + Retry-After (RFC 7231 §7.1.3) instead of semaphore-waiting until a /// slot frees. Recommended for any HTTP-facing endpoint — silent waits look like a hung /// server to clients and break liveness probes. Default is false (legacy wait). /// public KeyedThrottleDefinition RejectOnOverflow(bool reject = true) { _rejectOnOverflow = reject; return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes the KeyedThrottle scope and returns the parent route definition. public IRouteDefinition EndKeyedThrottle() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndKeyedThrottle() called without a parent route.")); /// public IRouteDefinition End() => EndKeyedThrottle(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor downstream = BuildPipeline(Outputs, context); var loggerFactory = context.GetService(); var logger = loggerFactory?.CreateLogger(); return new KeyedThrottleProcessor(downstream, _keyExtractor, MaxPerPeriodFactory, _period, _rejectOnOverflow, logger); } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } Path: redb-route/redb.Route/Definitions/ThrowDefinition.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/Definitions/ThrowDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that rethrows the exception stored on the exchange. /// public sealed class RethrowExceptionDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => throw exchange.Exception ?? new InvalidOperationException("No exception on exchange to rethrow.")); } /// /// Leaf definition that throws a new with a static message. /// public sealed class ThrowMessageDefinition : ProcessorDefinition { private readonly string _message; /// Creates a throw definition with a static message. public ThrowMessageDefinition(string message) { ArgumentException.ThrowIfNullOrWhiteSpace(message); _message = message; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(_ => throw new Exception(_message)); } /// /// Leaf definition that throws a specific pre-built exception instance. /// public sealed class ThrowExceptionDefinition : ProcessorDefinition { private readonly Exception _exception; /// Creates a throw definition from an exception instance. public ThrowExceptionDefinition(Exception exception) { ArgumentNullException.ThrowIfNull(exception); _exception = exception; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(_ => throw _exception); } /// /// Leaf definition that instantiates and throws an exception by type. /// public sealed class ThrowExceptionTypeDefinition : ProcessorDefinition { private readonly Type _exceptionType; private readonly string? _message; /// Creates a throw definition for a specific exception type. /// Exception type to instantiate and throw. /// Optional message to pass to the exception constructor. public ThrowExceptionTypeDefinition(Type exceptionType, string? message = null) { ArgumentNullException.ThrowIfNull(exceptionType); if (!typeof(Exception).IsAssignableFrom(exceptionType)) throw new ArgumentException($"Type '{exceptionType.Name}' does not inherit from Exception.", nameof(exceptionType)); _exceptionType = exceptionType; _message = message; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(_ => throw (Exception)(_message is not null ? Activator.CreateInstance(_exceptionType, _message) : Activator.CreateInstance(_exceptionType))!); } /// /// Leaf definition that marks the exchange exception as handled. /// public sealed class ExceptionHandledDefinition : ProcessorDefinition { /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => { exchange.ExceptionHandled = true; exchange.Exception = null; }); } Path: redb-route/redb.Route/Definitions/ToDefinition.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/Definitions/ToDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Sends the exchange to the given endpoint URI. /// Leaf node — no . /// public sealed class ToDefinition : ProcessorDefinition { private readonly string _uri; /// Creates a new for the given endpoint URI. public ToDefinition(string uri) { ArgumentException.ThrowIfNullOrWhiteSpace(uri); _uri = uri; } /// The target endpoint URI. Read by AdviceWith weaving (MockEndpoints, WeaveByToUri). public string Uri => _uri; /// public override IProcessor CreateProcessor(IRouteContext context) => new ToProcessor(_uri, context); } Path: redb-route/redb.Route/Definitions/ToDynamicDefinition.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/Definitions/ToDynamicDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Camel-style dynamic toD(): sends the exchange to an endpoint whose URI is /// resolved per message. Accepts a ${...} template, an , /// or a factory delegate. /// /// Example: .ToD("kafka://orders-${header.region}"). /// /// public sealed class ToDynamicDefinition : ProcessorDefinition { private readonly string? _template; private readonly IExpression? _expression; private readonly Func? _uriFactory; /// Creates a dynamic-to definition from a ${...} URI template. public ToDynamicDefinition(string template) { ArgumentException.ThrowIfNullOrWhiteSpace(template); _template = template; } /// Creates a dynamic-to definition from an producing the URI. public ToDynamicDefinition(IExpression expression) { _expression = expression ?? throw new ArgumentNullException(nameof(expression)); } /// Creates a dynamic-to definition from a factory delegate producing the URI. public ToDynamicDefinition(Func uriFactory) { _uriFactory = uriFactory ?? throw new ArgumentNullException(nameof(uriFactory)); } /// public override IProcessor CreateProcessor(IRouteContext context) => new ToDynamicProcessor(CreateResolver(context)); /// The URI template, when the node was declared with one (diagnostics, XML form). public string? Template => _template; /// Builds the per-message URI resolver of this node (also used by InterceptSendToEndpoint to learn the target URI). internal DynamicEndpointResolver CreateResolver(IRouteContext context) => _template is not null ? DynamicEndpointResolver.FromTemplate(context, _template) : _expression is not null ? DynamicEndpointResolver.FromExpression(context, _expression) : new DynamicEndpointResolver(context, _uriFactory!); } Path: redb-route/redb.Route/Definitions/TracedDefinition.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/Definitions/TracedDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.Definitions; /// /// Scope-opener definition for OpenTelemetry tracing. /// All child steps run inside a single span /// named . Transports (AMQP, RabbitMQ, etc.) create child spans /// automatically from the parent activity propagated on the exchange. /// Inherits the leaf DSL from ; /// close with or the universal . /// public class TracedDefinition : RouteDefinitionBase, IRouteScope { /// Operation name used as the Activity span name. public string OperationName { get; } internal TracedDefinition(string operationName) { ArgumentException.ThrowIfNullOrWhiteSpace(operationName); OperationName = operationName; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this traced scope and returns the parent route definition. /// Thrown if no parent route is set. public IRouteDefinition EndTraced() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndTraced() called without a parent route. Ensure Traced() was called on a route definition.")); /// public IRouteDefinition End() => EndTraced(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor body = BuildPipeline(Outputs, context); return new InstrumentedProcessor(body, OperationName); } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } Path: redb-route/redb.Route/Definitions/TransactionDefinition.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/Definitions/TransactionDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.ErrorHandling; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Definitions; /// /// Scope-opener definition for declarative transaction management. /// All child steps execute inside a which: /// /// Wraps the inner pipeline in a . /// Auto-commits all instances on success. /// Auto-rolls-back on exception or cancellation. /// /// No explicit CommitTransaction() / RollbackTransaction() needed. /// Inherits the leaf DSL from ; /// close with or the universal . /// public class TransactionDefinition : RouteDefinitionBase, IRouteScope, IDurableScope { private readonly TransactionPolicy? _policy; private int _retryAttempts; private TimeSpan _retryDelay; private string? _deadLetterUri; /// The transaction policy this scope will use (null = default Required). public TransactionPolicy? Policy => _policy; internal TransactionDefinition(TransactionPolicy? policy = null) { _policy = policy; } // ── Camel-parity error handler hooks ─────────────────────────────────────── /// /// Apache Camel parity: errorHandler(defaultErrorHandler().maximumRedeliveries(n).redeliveryDelay(d)). /// Retries the inner transactional body up to times before letting /// the exception propagate to the transaction (which will then roll back). /// public TransactionDefinition Retry(int attempts, TimeSpan delay) { if (attempts <= 0) throw new ArgumentOutOfRangeException(nameof(attempts)); _retryAttempts = attempts; _retryDelay = delay; return this; } /// /// Apache Camel parity: errorHandler(deadLetterChannel("...")). /// On failure the exchange is sent to after the transaction /// has rolled back. /// public TransactionDefinition DeadLetterChannel(string deadLetterUri) { ArgumentException.ThrowIfNullOrWhiteSpace(deadLetterUri); _deadLetterUri = deadLetterUri; return this; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes this transaction scope and returns the parent route definition. /// Thrown if no parent route is set. public IRouteDefinition EndTransaction() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndTransaction() called without a parent route. Ensure Transaction() was called on a route definition.")); /// public IRouteDefinition End() => EndTransaction(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor body = BuildPipeline(Outputs, context); var policy = _policy ?? new TransactionPolicy(); var logger = context.GetService()?.CreateLogger(); IProcessor txProcessor = new TransactedProcessor(body, policy, logger); // Retry wraps the transaction instead of living inside it: one attempt is one unit of work. A failed attempt // rolls back its own database work and its own deferred sends, so the attempt that succeeds sends only its own // messages, and no transaction stays open across the retry delays. if (_retryAttempts > 0) { var retryLogger = context.GetService()?.CreateLogger(); txProcessor = new RetryProcessor(txProcessor, RetryPolicy.Fixed(_retryAttempts, _retryDelay), retryLogger); } if (_deadLetterUri is not null) { var dlcLogger = context.GetService()?.CreateLogger(); txProcessor = new DeadLetterChannelProcessor(context, txProcessor, _deadLetterUri, rethrow: false, logger: dlcLogger); } return txProcessor; } private static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } Path: redb-route/redb.Route/Definitions/TransformDefinition.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/Definitions/TransformDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Leaf definition that transforms the exchange body using a factory function. /// public sealed class TransformDefinition : ProcessorDefinition { private readonly Func _transform; /// Creates a transform definition from a factory. public TransformDefinition(Func transform) { ArgumentNullException.ThrowIfNull(transform); _transform = transform; } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => exchange.In.Body = _transform(exchange)); } /// /// Leaf definition that transforms the exchange body using an . /// public sealed class TransformExpressionDefinition : ProcessorDefinition { private readonly IExpression _expression; /// The expression producing the transformed body. public IExpression Expression => _expression; /// Creates a transform definition from an expression. public TransformExpressionDefinition(IExpression expression) { ArgumentNullException.ThrowIfNull(expression); _expression = expression; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ExpressionBodyProcessor(_expression); } Path: redb-route/redb.Route/Definitions/TryCatchDefinition.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/Definitions/TryCatchDefinition.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Definitions; /// /// Scope-opener definition for the TryCatch EIP. /// Inherits the leaf DSL from ; child steps /// build the try body. Open catch branches with , /// optionally add a finally block with , close the scope with /// . /// public class TryCatchDefinition : RouteDefinitionBase, IRouteScope, IBranchingDefinition { internal readonly List Catches = []; internal FinallyDefinition? FinallyBlock; /// /// The catch/finally handler bodies — logical children outside (which /// holds the try body), so a generic tree-walk (validation) reaches steps nested in a handler. /// public IEnumerable Branches { get { foreach (var c in Catches) yield return c; if (FinallyBlock is not null) yield return FinallyBlock; } } internal TryCatchDefinition() { } // ── Navigation ───────────────────────────────────────────────────────────── /// Opens a typed catch branch. public CatchDefinition Catch() where TException : Exception => Catch(typeof(TException)); /// Opens a catch branch for the given exception type. public CatchDefinition Catch(Type exceptionType) { ArgumentNullException.ThrowIfNull(exceptionType); if (!typeof(Exception).IsAssignableFrom(exceptionType)) throw new ArgumentException($"Type must be an Exception, got {exceptionType.Name}", nameof(exceptionType)); var def = new CatchDefinition(exceptionType, this); Catches.Add(def); return def; } /// Opens the Finally block. /// Thrown if Finally was already set. public FinallyDefinition Finally() { if (FinallyBlock != null) throw new InvalidOperationException("Finally() can only be called once per TryCatch scope."); FinallyBlock = new FinallyDefinition(this); return FinallyBlock; } /// Closes this TryCatch scope and returns the parent route definition. public IRouteDefinition EndTryCatch() => (IRouteDefinition)(Parent ?? throw new InvalidOperationException( "EndTryCatch() called without a parent route.")); /// public IRouteDefinition End() => EndTryCatch(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) { IProcessor body = BuildPipeline(Outputs, context); var loggerFactory = context.GetService(); var logger = loggerFactory?.CreateLogger(); var proc = new TryCatchProcessor(body, logger); foreach (var catchDef in Catches) { IProcessor handler = BuildPipeline(catchDef.Outputs, context); proc.Catch(new CatchClause(catchDef.ExceptionType, handler, catchDef.WhenPredicate)); } if (FinallyBlock != null) proc.SetFinally(BuildPipeline(FinallyBlock.Outputs, context)); return proc; } internal static IProcessor BuildPipeline(IList outputs, IRouteContext context) => NodePipeline.Body(context, outputs); } /// /// A catch branch inside a . /// Inherits the leaf DSL from ; child steps /// build the catch handler pipeline. Navigate back with , /// open another catch with , open finally with /// , or close the entire scope with . /// public class CatchDefinition : RouteDefinitionBase, IRouteScope { internal readonly Type ExceptionType; internal Func? WhenPredicate; private readonly TryCatchDefinition _tryCatch; internal CatchDefinition(Type exceptionType, TryCatchDefinition tryCatch) { ExceptionType = exceptionType; _tryCatch = tryCatch; Parent = tryCatch; } // ── Navigation ───────────────────────────────────────────────────────────── /// Adds an additional guard predicate to this catch clause. public CatchDefinition When(Func predicate) { WhenPredicate = predicate; return this; } /// Closes this catch branch and returns to the parent TryCatch. public TryCatchDefinition EndCatch() => _tryCatch; /// Opens another catch branch. public CatchDefinition Catch() where TException : Exception => _tryCatch.Catch(); /// Opens the Finally block. public FinallyDefinition Finally() => _tryCatch.Finally(); /// Closes the entire TryCatch scope. public IRouteDefinition EndTryCatch() => _tryCatch.EndTryCatch(); /// public IRouteDefinition End() => EndTryCatch(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) => throw new InvalidOperationException( "CatchDefinition is compiled via its parent TryCatchDefinition.CreateProcessor."); } /// /// The Finally block inside a . /// Inherits the leaf DSL from ; child steps /// build the finally pipeline. Close with or /// . /// public class FinallyDefinition : RouteDefinitionBase, IRouteScope { private readonly TryCatchDefinition _tryCatch; internal FinallyDefinition(TryCatchDefinition tryCatch) { _tryCatch = tryCatch; Parent = tryCatch; } // ── Navigation ───────────────────────────────────────────────────────────── /// Closes the Finally block and returns to the parent TryCatch. public TryCatchDefinition EndFinally() => _tryCatch; /// Closes the entire TryCatch scope. public IRouteDefinition EndTryCatch() => _tryCatch.EndTryCatch(); /// public IRouteDefinition End() => EndTryCatch(); // ── IProcessorDefinition ─────────────────────────────────────────────────── /// public override IProcessor CreateProcessor(IRouteContext context) => throw new InvalidOperationException( "FinallyDefinition is compiled via its parent TryCatchDefinition.CreateProcessor."); } Path: redb-route/redb.Route/Definitions/ValidateDefinition.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/Definitions/ValidateDefinition.cs ---- using Json.Schema; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Validation; using System.Xml.Schema; namespace redb.Route.Definitions; /// /// Leaf definition that validates the exchange using an instance. /// public sealed class ValidateInstanceDefinition : ProcessorDefinition { private readonly IMessageValidator _validator; private readonly bool _throwOnFailure; /// Gets the validator instance. public IMessageValidator Validator => _validator; /// Gets whether a validation failure throws an exception. public bool ThrowOnFailure => _throwOnFailure; /// Creates a validate definition from a validator instance. public ValidateInstanceDefinition(IMessageValidator validator, bool throwOnFailure = true) { ArgumentNullException.ThrowIfNull(validator); _validator = validator; _throwOnFailure = throwOnFailure; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor(_validator, _throwOnFailure); } /// /// Leaf definition that validates the exchange using a predicate function. /// public sealed class ValidatePredicateDefinition : ProcessorDefinition { private readonly IPredicate _predicate; private readonly string _errorMessage; private readonly bool _throwOnFailure; /// Gets the error message used when validation fails. public string ErrorMessage => _errorMessage; /// Gets whether a validation failure throws an exception. public bool ThrowOnFailure => _throwOnFailure; /// Creates a validate definition from a predicate. public ValidatePredicateDefinition(IPredicate predicate, string errorMessage, bool throwOnFailure = true) { ArgumentNullException.ThrowIfNull(predicate); ArgumentException.ThrowIfNullOrWhiteSpace(errorMessage); _predicate = predicate; _errorMessage = errorMessage; _throwOnFailure = throwOnFailure; } /// Creates a validate definition from a delegate, wrapped as a . public ValidatePredicateDefinition(Func predicate, string errorMessage, bool throwOnFailure = true) : this(new Predicates.LambdaPredicate(predicate ?? throw new ArgumentNullException(nameof(predicate))), errorMessage, throwOnFailure) { } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor(new PredicateValidator(_predicate, _errorMessage), _throwOnFailure); } /// /// Leaf definition that validates the exchange body against a JSON Schema specified as a string. /// public sealed class ValidateJsonSchemaStringDefinition : ProcessorDefinition { private readonly string _schemaJson; private readonly bool _throwOnFailure; /// Gets the JSON Schema string. public string SchemaJson => _schemaJson; /// Gets whether a validation failure throws an exception. public bool ThrowOnFailure => _throwOnFailure; /// Creates a validate definition from a JSON Schema string. public ValidateJsonSchemaStringDefinition(string schemaJson, bool throwOnFailure = true) { ArgumentException.ThrowIfNullOrWhiteSpace(schemaJson); _schemaJson = schemaJson; _throwOnFailure = throwOnFailure; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor(new JsonSchemaValidator(_schemaJson), _throwOnFailure); } /// /// Leaf definition that validates the exchange body against a object. /// public sealed class ValidateJsonSchemaObjectDefinition : ProcessorDefinition { private readonly JsonSchema _schema; private readonly bool _throwOnFailure; /// Creates a validate definition from a JsonSchema object. public ValidateJsonSchemaObjectDefinition(JsonSchema schema, bool throwOnFailure = true) { ArgumentNullException.ThrowIfNull(schema); _schema = schema; _throwOnFailure = throwOnFailure; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor(new JsonSchemaValidator(_schema), _throwOnFailure); } /// /// Leaf definition that validates the exchange body against an XSD schema string. /// public sealed class ValidateXsdStringDefinition : ProcessorDefinition { private readonly string _xsdContent; private readonly bool _throwOnFailure; /// Gets the XSD content string. public string XsdContent => _xsdContent; /// Gets whether a validation failure throws an exception. public bool ThrowOnFailure => _throwOnFailure; /// Creates a validate definition from an XSD content string. public ValidateXsdStringDefinition(string xsdContent, bool throwOnFailure = true) { ArgumentException.ThrowIfNullOrWhiteSpace(xsdContent); _xsdContent = xsdContent; _throwOnFailure = throwOnFailure; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor(new XsdValidator(_xsdContent), _throwOnFailure); } /// /// Leaf definition that validates the exchange body against an XSD schema with a target namespace. /// public sealed class ValidateXsdNamespaceDefinition : ProcessorDefinition { private readonly string? _targetNamespace; private readonly string _xsdContent; private readonly bool _throwOnFailure; /// Gets the target XML namespace (may be null). public string? TargetNamespace => _targetNamespace; /// Gets the XSD content string. public string XsdContent => _xsdContent; /// Gets whether a validation failure throws an exception. public bool ThrowOnFailure => _throwOnFailure; /// Creates a validate definition with a namespace-qualified XSD. public ValidateXsdNamespaceDefinition(string? targetNamespace, string xsdContent, bool throwOnFailure = true) { ArgumentException.ThrowIfNullOrWhiteSpace(xsdContent); _targetNamespace = targetNamespace; _xsdContent = xsdContent; _throwOnFailure = throwOnFailure; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor(new XsdValidator(_targetNamespace, _xsdContent), _throwOnFailure); } /// /// Leaf definition that validates the exchange body against a pre-built . /// public sealed class ValidateXsdSchemaSetDefinition : ProcessorDefinition { private readonly XmlSchemaSet _schemaSet; private readonly bool _throwOnFailure; /// Creates a validate definition from an XmlSchemaSet. public ValidateXsdSchemaSetDefinition(XmlSchemaSet schemaSet, bool throwOnFailure = true) { ArgumentNullException.ThrowIfNull(schemaSet); _schemaSet = schemaSet; _throwOnFailure = throwOnFailure; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor(new XsdValidator(_schemaSet), _throwOnFailure); } /// /// Leaf definition that validates the exchange body against an XSD file, its imports and includes read /// relative to it (see ). The path resolves through the /// context's resource resolver when the route is built, as the xslt step's file does, so a schema inside a /// package is found where the package keeps its resources. /// public sealed class ValidateXsdFileDefinition : ProcessorDefinition { /// Creates a validate definition from an XSD file. public ValidateXsdFileDefinition(string schemaPath, string? targetNamespace = null, string? schemaRoot = null, bool throwOnFailure = true) { ArgumentException.ThrowIfNullOrWhiteSpace(schemaPath); SchemaPath = schemaPath; TargetNamespace = targetNamespace; SchemaRoot = schemaRoot; ThrowOnFailure = throwOnFailure; } /// Gets the schema file as written. public string SchemaPath { get; } /// Gets the target namespace; null takes the schema's own. public string? TargetNamespace { get; } /// Gets the directory imports stay under, relative to the schema's directory; null is that directory. public string? SchemaRoot { get; } /// Gets whether a validation failure throws an exception. public bool ThrowOnFailure { get; } /// public override IProcessor CreateProcessor(IRouteContext context) => new ValidateProcessor( XsdValidator.FromFile(ResourceResolution.Resolve(context, SchemaPath, "XSD schema"), TargetNamespace, SchemaRoot), ThrowOnFailure); } Path: redb-route/redb.Route/Definitions/XsltDefinition.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/Definitions/XsltDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xslt; namespace redb.Route.Definitions; /// /// Leaf definition that transforms the exchange body through an XSLT stylesheet loaded from a /// file (Apache Camel xslt: parity). The stylesheet is compiled once when the route is /// built and reused for every message. xsl:import/xsl:include resolve relative to the file. /// public sealed class XsltFileDefinition : ProcessorDefinition { private readonly string _stylesheetPath; private readonly XsltOutput _output; private readonly bool _failOnNullBody; private readonly bool _allowTemplateFromHeader; /// Creates a file-based XSLT definition. public XsltFileDefinition( string stylesheetPath, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false) { ArgumentException.ThrowIfNullOrWhiteSpace(stylesheetPath); _stylesheetPath = stylesheetPath; _output = output; _failOnNullBody = failOnNullBody; _allowTemplateFromHeader = allowTemplateFromHeader; } /// public override IProcessor CreateProcessor(IRouteContext context) { var engines = context.GetXsltEngineFactory(); // Through the context's resource resolver, as the xslt: endpoint and validateXsd do: a stylesheet inside a package // is found where the package keeps its resources, not under the worker's working directory. string Resolve(string path) => ResourceResolution.Resolve(context, path, "XSLT stylesheet"); return new XsltProcessor( engines.FromFile(Resolve(_stylesheetPath)), _output, _failOnNullBody, allowTemplateFromHeader: _allowTemplateFromHeader, fileEngineFactory: path => engines.FromFile(Resolve(path)), contentEngineFactory: engines.FromContent); } } /// /// Leaf definition that transforms the exchange body through an inline XSLT stylesheet document /// (self-contained; no xsl:import/xsl:include base URI). Compiled once at route build. /// public sealed class XsltContentDefinition : ProcessorDefinition { private readonly string _stylesheetXml; private readonly XsltOutput _output; private readonly bool _failOnNullBody; private readonly bool _allowTemplateFromHeader; /// Creates an inline-stylesheet XSLT definition. public XsltContentDefinition( string stylesheetXml, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false) { ArgumentException.ThrowIfNullOrWhiteSpace(stylesheetXml); _stylesheetXml = stylesheetXml; _output = output; _failOnNullBody = failOnNullBody; _allowTemplateFromHeader = allowTemplateFromHeader; } /// public override IProcessor CreateProcessor(IRouteContext context) { var engines = context.GetXsltEngineFactory(); return new XsltProcessor( engines.FromContent(_stylesheetXml), _output, _failOnNullBody, allowTemplateFromHeader: _allowTemplateFromHeader, fileEngineFactory: engines.FromFile, contentEngineFactory: engines.FromContent); } } Path: redb-route/redb.Route/Diagnostics/MermaidRenderer.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/Diagnostics/MermaidRenderer.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Diagnostics; /// /// Renders definition trees as a Mermaid flowchart — documentation diagrams /// generated from the same source as the running route, so they cannot go stale. Works over the /// definition tree, which means both spellings of a route — XML and fluent C# — draw /// identically. Deliberately simple: horizontal flow, node categories differ by shape, /// conditions carry their authored text; it is not a visual editor and not its prototype. /// public static class MermaidRenderer { /// /// Renders the routes as one flowchart. Top-down by default: Mermaid cannot wrap a long /// chain (its layout owns the ranks), so a vertical flow is the honest way to keep a big /// route on screen — it scrolls like text (live finding on mermaid.live, 2026-09-09); /// pass "LR" for the horizontal spelling. /// public static string Render(IEnumerable roots, string direction = "TD") { ArgumentNullException.ThrowIfNull(roots); var builder = new StringBuilder("flowchart ").Append(direction).Append('\n'); var counter = 0; foreach (var root in roots) { var entry = NextId(ref counter); builder.Append(" ").Append(entry).Append("[\"").Append(Escape(RouteLabel(root))).Append("\"]\n"); RenderChildren(root, entry, builder, ref counter); } return builder.ToString(); } private static void RenderChildren(IProcessorDefinition node, string previous, StringBuilder builder, ref int counter) { IReadOnlyList exits = [previous]; foreach (var child in node.Outputs) exits = RenderNode(child, exits, builder, ref counter, dotted: false); if (node is IBranchingDefinition branching) foreach (var branch in branching.Branches) RenderNode(branch, exits, builder, ref counter, dotted: true); } private static IReadOnlyList RenderNode(IProcessorDefinition node, IReadOnlyList previous, StringBuilder builder, ref int counter, bool dotted) { var id = NextId(ref counter); var (open, close) = Shape(node); builder.Append(" ").Append(id).Append(open).Append(Escape(Label(node))).Append(close).Append('\n'); foreach (var from in previous) builder.Append(" ").Append(from).Append(dotted ? " -.-> " : " --> ").Append(id).Append('\n'); // A branching node (choice) draws its branches as dotted fan-out from itself; the // continuation then merges from every branch TAIL — a solid edge out of the diamond // itself would read as one more branch (owner finding on mermaid.live, 2026-09-08). if (node is IBranchingDefinition branching) { var tails = new List(); foreach (var branch in branching.Branches) tails.AddRange(RenderNode(branch, [id], builder, ref counter, dotted: true)); IReadOnlyList exits = tails.Count > 0 ? tails : [id]; foreach (var child in node.Outputs) exits = RenderNode(child, exits, builder, ref counter, dotted: false); return exits; } IReadOnlyList inner = [id]; foreach (var child in node.Outputs) inner = RenderNode(child, inner, builder, ref counter, dotted: false); return inner; } private static string NextId(ref int counter) => $"n{counter++}"; private static string RouteLabel(IProcessorDefinition root) { var kind = Kind(root); if (root is IRouteDefinition route) { var id = route.GetRouteId(); var from = route.GetFromUri(); var label = id ?? kind; return from is { Length: > 0 } ? $"{label}: {from}" : label; } return kind; } private static string Label(IProcessorDefinition node) { var kind = Kind(node); if (node is IConditionSource { } source) { var condition = source.SourceTemplate ?? source.SourceExpression?.ToTemplateString(); if (!string.IsNullOrEmpty(condition)) return $"{kind}: {condition}"; } if (node is Definitions.ToDefinition to) return to.Uri; return kind; } private static string Kind(IProcessorDefinition node) { var name = node.GetType().Name; var tick = name.IndexOf('`'); if (tick >= 0) name = name[..tick]; if (name.EndsWith("Definition", StringComparison.Ordinal)) name = name[..^"Definition".Length]; return name.Length > 0 ? char.ToLowerInvariant(name[0]) + name[1..] : name; } // Every label is QUOTED: inside "…" Mermaid reads the text literally, so URIs with // {{placeholders}}, colons and parentheses survive (an unquoted ((…)) parses as a circle // shape — the live finding on mermaid.live, 2026-09-09). private static (string Open, string Close) Shape(IProcessorDefinition node) => node switch { Definitions.ToDefinition => ("[[\"", "\"]]"), // endpoint IConditionSource => ("{{\"", "\"}}"), // condition IBranchingDefinition => ("{\"", "\"}"), // branching _ when node.Outputs.Count > 0 => ("([\"", "\"])"), // scope _ => ("[\"", "\"]"), // leaf step }; private static string Escape(string label) { var cleaned = label .Replace("\r", "", StringComparison.Ordinal) .Replace("\n", " ", StringComparison.Ordinal) // Mermaid entities: a literal # starts one, a quote would end the label. .Replace("#", "#35;", StringComparison.Ordinal) .Replace("\"", "#quot;", StringComparison.Ordinal); return cleaned.Length > 60 ? cleaned[..57] + "..." : cleaned; } } Path: redb-route/redb.Route/Diagnostics/RouteDescriber.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/Diagnostics/RouteDescriber.cs ---- using System.Globalization; using System.Reflection; using System.Text; using redb.Route.Abstractions; namespace redb.Route.Diagnostics; /// /// Renders a definition tree as stable, diffable, human-readable text: one /// line per node — the node kind and its significant parameters — children indented beneath. /// Three consumers share it: XML-vs-C# equivalence tests, the code generator's round-trip /// check, and the Mermaid renderer, so it is deliberately generic: parameters come from the /// definition's own fields by reflection (cold path), never from a hand-kept switch that would /// drift from the definition set. /// /// /// What a line shows: strings, numbers, booleans, enums, s, types, /// expressions (their template text) and string collections — sorted by name for determinism. /// What it never shows: delegates, live objects, hash codes — things that legitimately differ /// between two constructions of the same route. A condition is rendered through /// , the text the author wrote. /// public static class RouteDescriber { /// Describes one definition tree. Two equal trees produce byte-equal text. public static string Describe(IProcessorDefinition root) { ArgumentNullException.ThrowIfNull(root); var builder = new StringBuilder(); Append(root, builder, 0); return builder.ToString(); } /// Describes every route of a context, in registration order. public static string Describe(IEnumerable roots) { ArgumentNullException.ThrowIfNull(roots); var builder = new StringBuilder(); foreach (var root in roots) Append(root, builder, 0); return builder.ToString(); } private static void Append(IProcessorDefinition node, StringBuilder builder, int depth) { builder.Append(' ', depth * 2).Append(Line(node)).Append('\n'); foreach (var child in node.Outputs) Append(child, builder, depth + 1); if (node is IBranchingDefinition branching) foreach (var branch in branching.Branches) Append(branch, builder, depth + 1); } private static string Line(IProcessorDefinition node) { var type = node.GetType(); var line = new StringBuilder(Label(type)); if (node is IConditionSource source) { var condition = source.SourceTemplate ?? source.SourceExpression?.ToTemplateString(); if (!string.IsNullOrEmpty(condition)) line.Append(" condition=").Append(Escape(condition)); } foreach (var (name, value) in Parameters(node, type)) line.Append(' ').Append(name).Append('=').Append(Escape(value)); return line.ToString(); } /// The node kind: the type name without the Definition suffix, camelCased; generic arguments by name. private static string Label(Type type) { var name = type.Name; var tick = name.IndexOf('`'); if (tick >= 0) name = name[..tick]; if (name.EndsWith("Definition", StringComparison.Ordinal)) name = name[..^"Definition".Length]; if (name.Length > 0 && char.IsUpper(name[0])) name = char.ToLowerInvariant(name[0]) + name[1..]; if (type.IsGenericType) name += "<" + string.Join(",", type.GetGenericArguments().Select(a => a.Name)) + ">"; return name; } private static IEnumerable<(string Name, string Value)> Parameters(object node, Type type) { var seen = new SortedDictionary(StringComparer.Ordinal); var isRoute = node is Definitions.RouteDefinition; for (var current = type; current is not null && current != typeof(object); current = current.BaseType) { // Route-level knobs (autoStart, cluster, …) are declared on the shared base every // scope inherits; on a scope node they are constant noise — only the route line // carries them. var isSharedBase = current.IsGenericType && current.GetGenericTypeDefinition().Name == "RouteDefinitionBase`1"; if (isSharedBase && !isRoute) continue; foreach (var field in current.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) { var name = NormalizeName(field.Name); if (name is null || seen.ContainsKey(name)) continue; var rendered = Render(field.GetValue(node)); if (rendered is not null) seen[name] = rendered; } } return seen.Select(p => (p.Key, p.Value)); } /// /// _uri → uri, <StepId>k__BackingField → stepId; /// null for names that carry no configuration. /// private static string? NormalizeName(string fieldName) { var name = fieldName; if (name.StartsWith('<')) { var close = name.IndexOf('>'); if (close <= 1) return null; name = name[1..close]; } name = name.TrimStart('_'); if (name.Length == 0) return null; name = char.ToLowerInvariant(name[0]) + name[1..]; // Structure, not configuration: children and back-links are the tree itself; the // source* trio is already rendered once as condition= through IConditionSource. return name is "outputs" or "parent" or "context" or "sourceTemplate" or "sourceExpression" or "sourcePredicate" ? null : name; } /// A stable rendering of one value, or null for what must not be compared. private static string? Render(object? value) => value switch { null => null, string text => text, bool flag => flag ? "true" : "false", Enum member => member.ToString(), TimeSpan span => span.ToString("c", CultureInfo.InvariantCulture), Type type => type.FullName ?? type.Name, IExpression expression => expression.ToTemplateString(), IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), IReadOnlyDictionary weights => string.Join(",", weights.OrderBy(w => w.Key, StringComparer.Ordinal).Select(w => $"{w.Key}={w.Value.ToString(CultureInfo.InvariantCulture)}")), IEnumerable items => string.Join(",", items), Delegate => null, _ => null, // live instances (predicates, repositories, processors) legitimately differ }; private static string Escape(string value) => value.Replace("\r", "", StringComparison.Ordinal).Replace("\n", "\\n", StringComparison.Ordinal); } Path: redb-route/redb.Route/ErrorHandling/DeadLetterErrorHandler.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/ErrorHandling/DeadLetterErrorHandler.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.ErrorHandling; /// /// The context's dead letter channel — Apache Camel's errorHandler(deadLetterChannel("direct:errors")) at the /// CamelContext level: set as , it takes every failure of every route that no /// OnException took, stamps it with the CamelDeadLetter* headers and sends it to the dead letter endpoint /// (usually a route of its own, direct:errors). A delivered exchange is handled — the failure does not go on to /// the caller, as with Camel's dead letter channel. A failed delivery is logged and the failure goes on. /// /// Redeliveries are the business of OnException (MaximumRedeliveries, RetryWhile): an error /// handler receives a failure after the step that threw has returned and has nothing to run again. /// /// public sealed class DeadLetterErrorHandler : IErrorHandler { private readonly IProcessor _deadLetter; private readonly ILogger? _logger; /// Creates the dead letter channel of . /// The context whose endpoint receives the dead letters. /// The dead letter endpoint, e.g. direct://errors. /// Optional logger. public DeadLetterErrorHandler(IRouteContext context, string deadLetterUri, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrWhiteSpace(deadLetterUri); DeadLetterUri = deadLetterUri; _deadLetter = new ToProcessor(deadLetterUri, context); _logger = logger; } /// The dead letter endpoint. public string DeadLetterUri { get; } /// public async Task HandleError(IExchange exchange, Exception exception, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); ArgumentNullException.ThrowIfNull(exception); DeadLetterHeaders.Stamp(exchange, exception, 0); _logger?.LogError(exception, "Dead-lettering exchange {ExchangeId} to {Uri}.", exchange.ExchangeId, EndpointUri.Sanitize(DeadLetterUri)); try { await _deadLetter.Process(exchange, ct).ConfigureAwait(false); ProcessorMetrics.DeadLetterSent.Add(1); exchange.ExceptionHandled = true; } catch (Exception sendFailure) when (!RouteCancellation.IsCancellation(sendFailure, ct)) { // The dead letter is lost: the original failure goes on to the caller rather than being swallowed. _logger?.LogError(sendFailure, "Dead-letter delivery to {Uri} failed.", EndpointUri.Sanitize(DeadLetterUri)); } } } Path: redb-route/redb.Route/ErrorHandling/DeadLetterHeaders.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/ErrorHandling/DeadLetterHeaders.cs ---- using redb.Route.Abstractions; namespace redb.Route.ErrorHandling; /// /// The headers a dead-lettered exchange carries (Apache Camel's CamelDeadLetter* family): why, what, when and /// after how many redeliveries. One place for every dead letter channel of the engine. /// internal static class DeadLetterHeaders { /// Stamps with before it goes to a dead letter endpoint. /// The failed exchange. /// What failed it. /// Redeliveries made before giving up; not written when zero. internal static void Stamp(IExchange exchange, Exception failure, int redeliveries) { exchange.In.Headers["CamelDeadLetterReason"] = failure.Message; exchange.In.Headers["CamelDeadLetterExceptionType"] = failure.GetType().FullName; exchange.In.Headers["CamelDeadLetterTimestamp"] = DateTimeOffset.UtcNow; if (redeliveries > 0) exchange.In.Headers["CamelDeadLetterRedeliveryCount"] = redeliveries; } } Path: redb-route/redb.Route/ErrorHandling/DeadLetterProcessor.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/ErrorHandling/DeadLetterProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.ErrorHandling; /// /// Processor that routes failed exchanges to a dead letter channel. /// When the inner processor throws and all retries are exhausted, /// the exchange is forwarded to a configurable dead-letter endpoint. /// Supports an optional for redelivery attempts before dead-lettering. /// public sealed class DeadLetterProcessor : IProcessor { private readonly IProcessor _inner; private readonly IProcessor _deadLetterTarget; private readonly RetryPolicy? _retryPolicy; private readonly ILogger? _logger; /// Creates a dead letter channel processor. /// Primary processing pipeline. /// Processor to handle dead-lettered exchanges (typically a ToProcessor). /// Optional retry policy — retries before dead-lettering. /// Optional logger. public DeadLetterProcessor(IProcessor inner, IProcessor deadLetterTarget, RetryPolicy? retryPolicy = null, ILogger? logger = null) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _deadLetterTarget = deadLetterTarget ?? throw new ArgumentNullException(nameof(deadLetterTarget)); _retryPolicy = retryPolicy; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var maxRetries = _retryPolicy?.MaxRetries ?? 0; var attempt = 0; while (true) { try { await _inner.Process(exchange, ct).ConfigureAwait(false); return; // Success — no dead letter needed } // A downstream timeout is an OperationCanceledException whose token (ours) is still live — a // failure to retry and dead-letter, not a cancellation. Named a TimeoutException. catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct)) { var failure = RouteCancellation.Normalize(ex, ct); if (attempt < maxRetries && _retryPolicy != null && _retryPolicy.ShouldRetry(failure)) { attempt++; _logger?.LogWarning(failure, "DeadLetterChannel: retry {Attempt}/{Max} for {ExceptionType}", attempt, maxRetries, failure.GetType().Name); var delay = _retryPolicy.GetDelay(attempt - 1); if (delay > TimeSpan.Zero) await InflightWaits.DelayAsync(exchange, delay, ct).ConfigureAwait(false); exchange.Exception = null; exchange.ExceptionHandled = false; continue; // Retry } // Stamp the exchange with the failure info exchange.Exception = failure; DeadLetterHeaders.Stamp(exchange, failure, attempt); _logger?.LogError(failure, "DeadLetterChannel: routing to DLQ after {Attempts} attempts for {ExceptionType}", attempt, failure.GetType().Name); // Route to dead letter channel ProcessorMetrics.DeadLetterSent.Add(1); await _deadLetterTarget.Process(exchange, ct).ConfigureAwait(false); exchange.ExceptionHandled = true; return; } } } } Path: redb-route/redb.Route/ErrorHandling/RetryPolicy.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/ErrorHandling/RetryPolicy.cs ---- namespace redb.Route.ErrorHandling; /// /// Defines a policy for retrying failed exchange processing. /// public sealed class RetryPolicy { /// Maximum number of retry attempts. 0 means no retries. public int MaxRetries { get; init; } /// Initial delay between retries. public TimeSpan InitialDelay { get; init; } = TimeSpan.FromMilliseconds(100); /// /// Multiplier for exponential backoff between retries. /// 1.0 = fixed delay, 2.0 = double each time. /// public double BackoffMultiplier { get; init; } = 2.0; /// Maximum delay cap between retries. public TimeSpan MaxDelay { get; init; } = TimeSpan.FromSeconds(30); /// /// Collision avoidance factor for adding random jitter to delays. /// 0.0 = no jitter, 0.15 = ±15% of the calculated delay (Camel default). /// Jitter is applied after exponential/fixed calculation but before the max-delay cap. /// Uses for thread safety. /// public double CollisionAvoidanceFactor { get; init; } /// /// Delay pattern string that overrides exponential/fixed calculation for specific attempt ranges. /// Format: "attempt1:delayMs;attempt2:delayMs;..." (e.g., "1:1000;5:5000;10:30000"). /// If the current attempt matches or exceeds a key, that delay is used. /// The highest matching key wins. When no key matches, standard calculation is used. /// public string? DelayPattern { get; init; } /// /// Predicate to determine if an exception is retryable. /// When null, all exceptions (except ) are retried. /// public Func? RetryableExceptionPredicate { get; init; } /// Creates a retry policy for no retries (fail immediately). public static RetryPolicy None => new() { MaxRetries = 0 }; /// Creates a fixed-delay retry policy. /// Maximum retry attempts. /// Fixed delay between retries. public static RetryPolicy Fixed(int maxRetries, TimeSpan delay) => new() { MaxRetries = maxRetries, InitialDelay = delay, BackoffMultiplier = 1.0, MaxDelay = delay }; /// Creates an exponential backoff retry policy. /// Maximum retry attempts. /// Initial delay. /// Backoff multiplier (default: 2.0). /// Maximum delay cap. public static RetryPolicy Exponential( int maxRetries, TimeSpan initialDelay, double multiplier = 2.0, TimeSpan? maxDelay = null) => new() { MaxRetries = maxRetries, InitialDelay = initialDelay, BackoffMultiplier = multiplier, MaxDelay = maxDelay ?? TimeSpan.FromSeconds(60) }; /// Calculates the delay for the given attempt number (0-based). /// Attempt number (0 = first retry). /// Delay duration for this attempt. public TimeSpan GetDelay(int attempt) { // DelayPattern takes priority when set and a matching key exists if (DelayPattern is not null) { var patternDelay = ResolveDelayPattern(attempt); if (patternDelay.HasValue) return patternDelay.Value; } double delayMs; if (attempt <= 0) delayMs = InitialDelay.TotalMilliseconds; else delayMs = InitialDelay.TotalMilliseconds * Math.Pow(BackoffMultiplier, attempt); // Apply jitter before cap if (CollisionAvoidanceFactor > 0) { var jitterRange = delayMs * CollisionAvoidanceFactor; delayMs += (Random.Shared.NextDouble() * 2 - 1) * jitterRange; delayMs = Math.Max(0, delayMs); } var capped = Math.Min(delayMs, MaxDelay.TotalMilliseconds); return TimeSpan.FromMilliseconds(capped); } private TimeSpan? ResolveDelayPattern(int attempt) { // Format: "1:1000;5:5000;10:30000" // Find the highest key <= attempt+1 (1-based in the pattern) var oneBasedAttempt = attempt + 1; double? bestDelay = null; int bestKey = -1; foreach (var part in DelayPattern!.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var colonIdx = part.IndexOf(':'); if (colonIdx <= 0) continue; if (!int.TryParse(part.AsSpan(0, colonIdx), out var key)) continue; if (!double.TryParse(part.AsSpan(colonIdx + 1), out var delayMs)) continue; if (key <= oneBasedAttempt && key > bestKey) { bestKey = key; bestDelay = delayMs; } } return bestDelay.HasValue ? TimeSpan.FromMilliseconds(bestDelay.Value) : null; } /// Returns whether the exception is eligible for retry. /// The exception to evaluate. /// true if the exception should be retried. public bool ShouldRetry(Exception ex) { if (ex is OperationCanceledException) return false; return RetryableExceptionPredicate?.Invoke(ex) ?? true; } } Path: redb-route/redb.Route/ErrorHandling/RetryProcessor.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/ErrorHandling/RetryProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.ErrorHandling; /// /// Processor that retries the inner processor according to a . /// Uses exponential backoff with jitter. Respects cancellation at all points. /// public sealed class RetryProcessor : IProcessor { private readonly IProcessor _inner; private readonly RetryPolicy _policy; private readonly ILogger? _logger; /// Creates a retry processor. /// Processor to retry on failure. /// Retry policy configuration. /// Optional logger for retry events. public RetryProcessor(IProcessor inner, RetryPolicy policy, ILogger? logger = null) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var attempt = 0; while (true) { exchange.Properties["RetryAttempt"] = attempt; try { await _inner.Process(exchange, ct).ConfigureAwait(false); if (attempt > 0) ProcessorMetrics.RetrySuccess.Add(1); return; // Success } // A downstream timeout is an OperationCanceledException whose token (ours) is still live — a // failure to retry, not a cancellation. Named a TimeoutException so the policy sees it as one. // A genuine cancellation (the caller's token fired) is filtered out: never retried. catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct)) { var failure = RouteCancellation.Normalize(ex, ct); if (attempt >= _policy.MaxRetries || !_policy.ShouldRetry(failure)) { ProcessorMetrics.RetryExhausted.Add(1); _logger?.LogError(failure, "Exchange processing failed after {Attempts} attempt(s). No more retries.", attempt + 1); if (ReferenceEquals(failure, ex)) throw; // a plain failure — keep its original stack throw failure; // a named timeout (TimeoutException) } ProcessorMetrics.RetryAttempts.Add(1); // The policy's delay as it is: jitter only when the policy asks for it (CollisionAvoidanceFactor, off by // default as Camel's collision avoidance), already capped by MaxDelay. var actualDelay = _policy.GetDelay(attempt); _logger?.LogWarning( "Exchange processing failed (attempt {Attempt}/{MaxRetries}): {Error}. Retrying in {Delay:F0}ms.", attempt + 1, _policy.MaxRetries, failure.Message, actualDelay.TotalMilliseconds); await InflightWaits.DelayAsync(exchange, actualDelay, ct).ConfigureAwait(false); // Reset exchange error state before retry exchange.Exception = null; exchange.ExceptionHandled = false; attempt++; } } } } Path: redb-route/redb.Route/Expressions/Ast/AstNode.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/Expressions/Ast/AstNode.cs ---- using System; using System.Collections.Generic; using System.Linq; using redb.Route.Abstractions; namespace redb.Route.Expressions.Ast; /// /// Abstract base class for all AST (Abstract Syntax Tree) nodes. /// public abstract class AstNode { private Func? _compiled; /// /// Evaluates this AST node against the given exchange context. The tree under the node is compiled once, by the same /// compiler every expression of the engine goes through, and the compiled delegate is evaluated: there is one /// evaluator, and a node evaluated directly gives what the engine gives (findings register row 27). /// /// The exchange context used for expression resolution. /// The result of evaluating this node. public virtual object? Evaluate(IExchange exchange) => (_compiled ??= ExpressionResolver.CompileAstTree(this))(exchange); } /// /// AST node representing a literal (constant) value. /// public class LiteralNode : AstNode { /// /// Gets the literal value held by this node. /// public object? Value { get; } /// /// Initializes a new instance of the class. /// /// The literal value. public LiteralNode(object? value) { Value = value; } /// public override string ToString() => Value?.ToString() ?? "null"; } /// /// AST node representing an identifier (variable reference). /// public class IdentifierNode : AstNode { /// /// Gets the name of the identifier. /// public string Name { get; } /// /// Initializes a new instance of the class. /// /// The identifier name. public IdentifierNode(string name) { Name = name; } /// public override string ToString() => Name; } /// /// AST node representing a binary operation (e.g. addition, comparison, logical operations). /// public class BinaryOperationNode : AstNode { /// /// Gets the left operand of the binary operation. /// public AstNode Left { get; } /// /// Gets the operator symbol (e.g. "+", "==", "AND"). /// public string Operator { get; } /// /// Gets the right operand of the binary operation. /// public AstNode Right { get; } /// /// Initializes a new instance of the class. /// /// The left operand node. /// The operator string. /// The right operand node. public BinaryOperationNode(AstNode left, string op, AstNode right) { Left = left; Operator = op; Right = right; } /// public override string ToString() => $"({Left} {Operator} {Right})"; } /// /// AST node representing a unary (prefix) operation (e.g. negation, logical NOT, prefix increment/decrement). /// public class UnaryOperationNode : AstNode { /// /// Gets the unary operator symbol (e.g. "+", "-", "!", "NOT", "++", "--"). /// public string Operator { get; } /// /// Gets the operand of the unary operation. /// public AstNode Operand { get; } /// /// Initializes a new instance of the class. /// /// The unary operator string. /// The operand node. public UnaryOperationNode(string op, AstNode operand) { Operator = op; Operand = operand; } /// public override string ToString() => $"{Operator}({Operand})"; } /// /// AST node representing a function call with arguments. /// public class FunctionCallNode : AstNode { /// /// Gets the name of the function being called. /// public string Name { get; } /// /// Gets the list of argument nodes passed to the function. /// public List Arguments { get; } /// /// Initializes a new instance of the class. /// /// The function name. /// The list of argument AST nodes. public FunctionCallNode(string name, List arguments) { Name = name; Arguments = arguments; } /// public override string ToString() => $"{Name}({string.Join(", ", Arguments)})"; } /// /// AST node representing property access on an object (e.g. obj.PropertyName). /// public class PropertyAccessNode : AstNode { /// /// Gets the AST node representing the object being accessed. /// public AstNode Object { get; } /// /// Gets the name of the property being accessed. /// public string PropertyName { get; } /// /// Initializes a new instance of the class. /// /// The object node whose property is accessed. /// The name of the property to access. public PropertyAccessNode(AstNode obj, string propertyName) { Object = obj; PropertyName = propertyName; } /// public override string ToString() => $"{Object}.{PropertyName}"; } /// /// A namespaced call, bean:name.Method(arg, ...): the bean from the context registry /// and its with the argument expressions. Compiled by the AST compiler, which resolves it. /// internal sealed class BeanCallNode(string ns, string reference, string method, List arguments, int position) : AstNode { /// The namespace, bean. public string Namespace { get; } = ns; /// The registry name, without #. public string Reference { get; } = reference; /// The method name. public string Method { get; } = method; /// The argument expressions, in order. public List Arguments { get; } = arguments; /// Zero-based position of the namespace within the expression. public int Position { get; } = position; /// public override string ToString() => $"{Namespace}:{Reference}.{Method}({string.Join(", ", Arguments)})"; } /// /// value range 'from..to' and value not range 'from..to': a numeric value within both ends, inclusive, as /// in Apache Camel's Simple. The ends are read when the expression is compiled. /// internal sealed class RangeNode(AstNode value, string literal, decimal from, decimal to, bool negated) : AstNode { /// The value tested. public AstNode Value { get; } = value; /// The literal as written, without its quotes. public string Literal { get; } = literal; /// The lower end, inclusive. public decimal From { get; } = from; /// The upper end, inclusive. public decimal To { get; } = to; /// True for not range. public bool Negated { get; } = negated; /// public override string ToString() => $"{Value} {(Negated ? "not range" : "range")} '{Literal}'"; } /// /// value.method(args): a method called on a value, a built-in dot helper (length, contains, ...) or a /// public method of the value's type. /// internal sealed class MethodCallNode(AstNode target, string method, List arguments, string written, int position) : AstNode { /// The value the method is called on. public AstNode Target { get; } = target; /// The method's name as written. public string Method { get; } = method; /// The argument expressions, in order. public List Arguments { get; } = arguments; /// The call as written, for error messages (header.o.Boom()). public string Written { get; } = written; /// Zero-based position of the call within the expression. public int Position { get; } = position; /// public override string ToString() => $"{Target}.{Method}({string.Join(", ", Arguments)})"; } /// env:NAME: the OS environment variable of that name, read when the expression is evaluated. internal sealed class EnvNode(string name, int position) : AstNode { /// The variable's name. public string Name { get; } = name; /// Zero-based position of the namespace within the expression. public int Position { get; } = position; /// public override string ToString() => $"env:{Name}"; } /// ref:name: the object registered under that name in the route context's registry. internal sealed class RegistryRefNode(string reference, int position) : AstNode { /// The registry name, without #. public string Reference { get; } = reference; /// Zero-based position of the namespace within the expression. public int Position { get; } = position; /// public override string ToString() => $"ref:{Reference}"; } Path: redb-route/redb.Route/Expressions/Ast/InOperationNode.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/Expressions/Ast/InOperationNode.cs ---- using redb.Route.Abstractions; namespace redb.Route.Expressions.Ast; /// /// A list literal after in: ('gold','silver'), (1, 2, 3), or (). /// Evaluates every item against the exchange, so an item can be any expression. /// public sealed class ListLiteralNode : AstNode { /// The items in source order. public IReadOnlyList Items { get; } /// Creates the node. public ListLiteralNode(IReadOnlyList items) => Items = items ?? throw new ArgumentNullException(nameof(items)); /// public override string ToString() => "(" + string.Join(", ", Items) + ")"; } /// /// value in list and value not in list — Camel Simple's membership operators. /// /// Elements are compared with the equality == uses (), /// so in cannot disagree with == about whether 2 equals 2L. A missing /// collection (null) is an empty one: nothing is a member of it, which is the SQL reading of an empty /// IN and the one a missing header should have. A string is refused rather than split — Camel /// reads 'a,b' as a list, but here a comma inside a string already means something else, and /// iterating a string would quietly test membership among its characters. /// /// public sealed class InOperationNode : AstNode { /// The value tested for membership. public AstNode Value { get; } /// The list: a or an expression yielding a collection. public AstNode List { get; } /// True for not in. public bool Negated { get; } /// Creates the node. public InOperationNode(AstNode value, AstNode list, bool negated) { Value = value ?? throw new ArgumentNullException(nameof(value)); List = list ?? throw new ArgumentNullException(nameof(list)); Negated = negated; } } Path: redb-route/redb.Route/Expressions/Ast/IndexAccessNode.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/Expressions/Ast/IndexAccessNode.cs ---- using redb.Route.Abstractions; namespace redb.Route.Expressions.Ast; /// /// AST node representing index access on a collection/array (e.g. items[0]). /// public class IndexAccessNode : AstNode { /// /// Gets the AST node representing the object being indexed. /// public AstNode Object { get; } /// /// Gets the AST node representing the index expression. /// public AstNode Index { get; } /// /// Initializes a new instance of the class. /// /// The object node being indexed. /// The index expression node. public IndexAccessNode(AstNode obj, AstNode index) { Object = obj; Index = index; } /// public override string ToString() => $"{Object}[{Index}]"; } Path: redb-route/redb.Route/Expressions/Ast/Parser.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/Expressions/Ast/Parser.cs ---- using System; using System.Globalization; using System.Collections.Generic; namespace redb.Route.Expressions.Ast; /// /// Recursive descent parser that builds an AST (Abstract Syntax Tree) from a list of tokens. /// public class Parser { /// /// The list of tokens to parse. /// private readonly List _tokens; /// /// The current position in the token list. /// private int _position; /// /// The token at the current position. /// private Token _currentToken; /// /// Initializes a new instance of the class. /// /// The list of tokens produced by the tokenizer. public Parser(List tokens) { _tokens = tokens; _position = 0; _currentToken = tokens.Count > 0 ? tokens[0] : new Token(TokenType.Eof, string.Empty, 0); } /// /// Parses the token list and builds an AST. The expression must take the whole text: a token after a complete /// expression (header.b == 3 garbage) is an error naming it and its position (findings register row 32). /// /// The root of the parsed expression. /// The text does not parse, or text follows the complete expression. public AstNode Parse() { var root = ParseReportingRest(out var rest); if (rest is not null) throw new InvalidOperationException( $"unexpected '{rest.Value}' at position {rest.Position + 1} within the expression: the expression ends before it."); return root; } /// /// Parses the complete expression at the start of the text and reports the first token after it, null when /// the expression ends where the text ends. The rule for bare text (row 29) and the package gate read the rest; /// refuses it. /// internal AstNode ParseReportingRest(out Token? rest) { var root = Expression(); rest = _currentToken.Type == TokenType.Eof ? null : _currentToken; return root; } /// /// Advances the parser to the next token. /// private void Advance() { _position++; if (_position < _tokens.Count) { _currentToken = _tokens[_position]; } else { _currentToken = new Token(TokenType.Eof, string.Empty, -1); } } /// /// Consumes the current token if it matches the expected type; otherwise throws an exception. /// /// The expected token type. /// The consumed token. /// Thrown when the current token does not match the expected type. private Token Eat(TokenType tokenType) { if (_currentToken.Type == tokenType) { var token = _currentToken; Advance(); return token; } throw new InvalidOperationException($"Expected token of type {tokenType}, but found {_currentToken.Type} ({_currentToken.Value})"); } /// /// Parses a full expression (entry point for the recursive descent). /// /// The parsed AST node. private AstNode Expression() { return TernaryExpression(); } /// /// Parses a ternary conditional expression (condition ? ifTrue : ifFalse) with the lowest precedence. /// /// The parsed AST node. private AstNode TernaryExpression() { var node = NullCoalescingExpression(); if (_currentToken.Type == TokenType.Operator && _currentToken.Value == "?") { Advance(); // consume '?' var ifTrue = Expression(); Eat(TokenType.Colon); var ifFalse = Expression(); return new TernaryNode(node, ifTrue, ifFalse); } return node; } /// /// Parses a null-coalescing expression (??) with the lowest precedence. /// /// The parsed AST node. private AstNode NullCoalescingExpression() { var node = LogicalExpression(); while (_currentToken.Type == TokenType.Operator && _currentToken.Value == "??") { var op = _currentToken.Value; Advance(); node = new BinaryOperationNode(node, op, LogicalExpression()); } return node; } /// /// Parses a logical expression (AND, OR, XOR). /// /// The parsed AST node. private AstNode LogicalExpression() { var node = ComparisonExpression(); while (_currentToken.Type == TokenType.Operator && (_currentToken.Value == "AND" || _currentToken.Value == "OR" || _currentToken.Value == "XOR")) { var op = _currentToken.Value; Advance(); node = new BinaryOperationNode(node, op, ComparisonExpression()); } return node; } /// /// Parses a comparison expression (==, !=, >, <, >=, <=). /// /// The parsed AST node. private AstNode ComparisonExpression() { var node = AdditiveExpression(); while (true) { if (TryRangeOperator(out var negated)) { node = new RangeNode(node, RangeLiteral(out var from, out var to), from, to, negated); continue; } if (!(_currentToken.Type == TokenType.Operator && (_currentToken.Value == "==" || _currentToken.Value == "!=" || _currentToken.Value == "=~" || _currentToken.Value == ">" || _currentToken.Value == "<" || _currentToken.Value == ">=" || _currentToken.Value == "<=" || _currentToken.Value == "IN" || _currentToken.Value == "NOT IN"))) break; var op = _currentToken.Value; Advance(); node = op is "IN" or "NOT IN" ? new InOperationNode(node, MembershipTarget(), negated: op == "NOT IN") : new BinaryOperationNode(node, op, AdditiveExpression()); } return node; } /// /// range and not range right after a complete operand, as in Apache Camel's Simple. The words are /// operators only here: anywhere else range is an ordinary name (header.range, a variable /// range), because after an operand neither a name nor a unary not could follow. /// private bool TryRangeOperator(out bool negated) { negated = false; if (IsWord(_currentToken, "range")) { Advance(); return true; } if (_currentToken.Type == TokenType.Operator && _currentToken.Value == "NOT" && _position + 1 < _tokens.Count && IsWord(_tokens[_position + 1], "range")) { Advance(); Advance(); negated = true; return true; } return false; } private static bool IsWord(Token token, string word) => token.Type == TokenType.Identifier && token.Value.Equals(word, StringComparison.OrdinalIgnoreCase); /// /// The right side of range: a quoted 'from..to' literal of two numbers, inclusive, read when the /// expression is compiled. Returns the literal as written, for the node's text. /// private string RangeLiteral(out decimal from, out decimal to) { var token = _currentToken; if (token.Type != TokenType.String) throw new InvalidOperationException( $"range takes a quoted 'from..to' literal, as in header.n range '1..10' " + $"(position {(token.Position < 0 ? "end" : (token.Position + 1).ToString(CultureInfo.InvariantCulture))} within the expression)."); Advance(); var text = token.Value[1..^1]; var dots = text.IndexOf("..", StringComparison.Ordinal); if (dots < 0 || !decimal.TryParse(text[..dots].Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out from) || !decimal.TryParse(text[(dots + 2)..].Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out to)) throw new InvalidOperationException( $"range '{text}' is not 'from..to' with two numbers, as in '1..10' " + $"(position {token.Position + 1} within the expression)."); if (from > to) throw new InvalidOperationException( $"range '{text}' starts above its end: write the smaller number first " + $"(position {token.Position + 1} within the expression)."); return text; } /// /// The right-hand side of in: a list literal when a parenthesis follows — ('a','b'), /// () for none — and otherwise an ordinary operand that must evaluate to a collection /// (header.codes). Parentheses after in always mean a literal, so a collection is /// written without them. /// private AstNode MembershipTarget() { if (_currentToken.Type != TokenType.LeftParen) return AdditiveExpression(); Advance(); var items = new List(); if (_currentToken.Type != TokenType.RightParen) { items.Add(Expression()); while (_currentToken.Type == TokenType.Comma) { Advance(); items.Add(Expression()); } } Eat(TokenType.RightParen); return new ListLiteralNode(items); } /// /// Parses an additive expression (+ and -). /// /// The parsed AST node. private AstNode AdditiveExpression() { var node = MultiplicativeExpression(); while (_currentToken.Type == TokenType.Operator && (_currentToken.Value == "+" || _currentToken.Value == "-")) { var op = _currentToken.Value; Advance(); node = new BinaryOperationNode(node, op, MultiplicativeExpression()); } return node; } /// /// Parses a multiplicative expression (* and /). /// /// The parsed AST node. private AstNode MultiplicativeExpression() { var node = UnaryExpression(); while (_currentToken.Type == TokenType.Operator && (_currentToken.Value == "*" || _currentToken.Value == "/" || _currentToken.Value == "%")) { var op = _currentToken.Value; Advance(); node = new BinaryOperationNode(node, op, UnaryExpression()); } return node; } /// /// Parses a unary expression (prefix +, -, NOT, !, ++, --) and checks for postfix ++ / --. /// /// The parsed AST node. private AstNode UnaryExpression() { if (_currentToken.Type == TokenType.Operator && (_currentToken.Value == "+" || _currentToken.Value == "-" || _currentToken.Value == "NOT" || _currentToken.Value == "!" || _currentToken.Value == "++" || _currentToken.Value == "--")) { var op = _currentToken.Value; Advance(); return new UnaryOperationNode(op, UnaryExpression()); } var expr = PrimaryExpression(); // Check for postfix ++ and -- operations if (_currentToken.Type == TokenType.Operator && (_currentToken.Value == "++" || _currentToken.Value == "--")) { var op = _currentToken.Value; Advance(); return new PostfixOperationNode(expr, op); } return expr; } /// /// Parses a primary expression: numbers, strings, identifiers, booleans, null, function calls, or parenthesized expressions. /// /// The parsed AST node. /// Thrown when an unexpected token is encountered. private AstNode PrimaryExpression() { var token = _currentToken; switch (token.Type) { case TokenType.Number: Advance(); if (token.Value.Contains('.')) { // Source text is culture-invariant: "2.5" is two and a half on every machine. // Until 2026-08-29 this parsed with the ambient culture, so a route with a // decimal literal compiled on en-US and failed to compile on ru-RU. return new LiteralNode(double.Parse(token.Value, System.Globalization.CultureInfo.InvariantCulture)); } return new LiteralNode(int.Parse(token.Value, System.Globalization.CultureInfo.InvariantCulture)); case TokenType.String: Advance(); // Remove quotes and handle escape sequences var str = token.Value.Substring(1, token.Value.Length - 2) .Replace("\\\"", "\"") .Replace("\\'", "'") .Replace("\\\\", "\\"); return new LiteralNode(str); case TokenType.Identifier: Advance(); if (token.Value.Equals("null", StringComparison.OrdinalIgnoreCase)) { return new LiteralNode(null); } if (token.Value.Equals("true", StringComparison.OrdinalIgnoreCase)) { return new LiteralNode(true); } if (token.Value.Equals("false", StringComparison.OrdinalIgnoreCase)) { return new LiteralNode(false); } // Handle property access via dot notation or index access AstNode result = new IdentifierNode(token.Value); result = PostfixAccess(result); return result; case TokenType.Function: var funcResult = FunctionCall(); return PostfixAccess(funcResult); case TokenType.Namespace when token.Value == "ref": return RegistryReference(); case TokenType.Namespace when token.Value == "env": { Advance(); var name = Eat(TokenType.Identifier).Value; if (_currentToken.Type == TokenType.LeftParen) throw new InvalidOperationException( $"env:{name} names an environment variable and calls nothing (position {token.Position + 1} within the expression)."); return new EnvNode(name, token.Position); } case TokenType.Namespace: return PostfixAccess(NamespacedCall()); case TokenType.PlaceholderOpen: if (_namespacedArgumentDepth == 0) throw new InvalidOperationException( $"${{...}} inside an expression is supported only in the arguments of a bean: call " + $"(position {token.Position + 1} within the expression)."); Advance(); var inner = Expression(); Eat(TokenType.RightBrace); return inner; case TokenType.LeftParen: Advance(); var expr = Expression(); Eat(TokenType.RightParen); return expr; default: throw new InvalidOperationException($"Unexpected token: {token.Type} ({token.Value})"); } } /// /// Parses chained postfix access operations: property access (.prop) and index access ([n]). /// /// The base AST node to apply postfix operations to. /// The resulting AST node with all chained accesses applied. private AstNode PostfixAccess(AstNode node) { while (true) { if (_currentToken.Type == TokenType.Dot) { Eat(TokenType.Dot); if (_currentToken.Type == TokenType.Function) { // A method of the value before the dot: upper(header.s).length() var methodToken = Eat(TokenType.Function); Eat(TokenType.LeftParen); var args = Arguments(); node = new MethodCallNode(node, methodToken.Value, args, $"{node}.{methodToken.Value}" + (args.Count == 0 ? "()" : "(...)"), methodToken.Position); continue; } var propertyName = Eat(TokenType.Identifier).Value; node = new PropertyAccessNode(node, propertyName); } else if (_currentToken.Type == TokenType.LeftBracket) { Eat(TokenType.LeftBracket); var indexExpr = Expression(); Eat(TokenType.RightBracket); node = new IndexAccessNode(node, indexExpr); } else { break; } } return node; } /// /// How many namespaced-call argument lists enclose the current position: a ${...} is a primary there, the /// typed value of the expression inside it, and nowhere else. /// private int _namespacedArgumentDepth; /// /// Parses ref:name: the registry object itself. Nothing is called on it and nothing is read from it; a /// parenthesis after the name points to bean:. /// private AstNode RegistryReference() { var ns = Eat(TokenType.Namespace); var name = Eat(TokenType.Identifier).Value; if (_currentToken.Type == TokenType.LeftParen) throw new InvalidOperationException( $"ref:{name} names a registry object and calls nothing; call a method with bean:{name}.Method(...) " + $"(position {ns.Position + 1} within the expression)."); return new RegistryRefNode(name, ns.Position); } /// /// Parses bean:name.Method(arg, ...) or bean:name.Method (no arguments). The method is required: /// in an expression there is no exchange-shaped call to pick one from. /// private AstNode NamespacedCall() { var ns = Eat(TokenType.Namespace); var target = _currentToken; var hasTarget = target.Type is TokenType.Function or TokenType.Identifier; var dot = hasTarget ? target.Value.LastIndexOf('.') : -1; if (dot <= 0 || dot == target.Value.Length - 1) throw new InvalidOperationException( $"a {ns.Value}: call names its method: {ns.Value}:{(hasTarget ? target.Value.TrimEnd('.') : "svc")}.Method(...) " + $"(position {ns.Position + 1} within the expression)."); var reference = target.Value[..dot]; var method = target.Value[(dot + 1)..]; var arguments = new List(); if (target.Type == TokenType.Identifier) { Advance(); return new BeanCallNode(ns.Value, reference, method, arguments, ns.Position); } Eat(TokenType.Function); Eat(TokenType.LeftParen); _namespacedArgumentDepth++; try { if (_currentToken.Type != TokenType.RightParen) { arguments.Add(Expression()); while (_currentToken.Type == TokenType.Comma) { Advance(); arguments.Add(Expression()); } } } finally { _namespacedArgumentDepth--; } Eat(TokenType.RightParen); return new BeanCallNode(ns.Value, reference, method, arguments, ns.Position); } /// /// Parses a function call expression, including its arguments. /// /// The parsed . private AstNode FunctionCall() { var functionToken = Eat(TokenType.Function); var functionName = functionToken.Value; Eat(TokenType.LeftParen); var arguments = new List(); // A dotted name is a method of a value, header.o.Boom(...): the path before the last dot is the value. var lastDot = functionName.LastIndexOf('.'); if (lastDot > 0 && lastDot < functionName.Length - 1) { var args = Arguments(); var method = functionName[(lastDot + 1)..]; return new MethodCallNode(new IdentifierNode(functionName[..lastDot]), method, args, functionName + (args.Count == 0 ? "()" : "(...)"), functionToken.Position); } // Parse arguments if (_currentToken.Type != TokenType.RightParen) { arguments.Add(Expression()); while (_currentToken.Type == TokenType.Comma) { Advance(); // Skip the comma arguments.Add(Expression()); } } Eat(TokenType.RightParen); return new FunctionCallNode(functionName, arguments); } /// The arguments after an opening parenthesis already eaten, and the closing one. private List Arguments() { var arguments = new List(); if (_currentToken.Type != TokenType.RightParen) { arguments.Add(Expression()); while (_currentToken.Type == TokenType.Comma) { Advance(); arguments.Add(Expression()); } } Eat(TokenType.RightParen); return arguments; } } Path: redb-route/redb.Route/Expressions/Ast/PostfixOperationNode.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/Expressions/Ast/PostfixOperationNode.cs ---- using System; using redb.Route.Abstractions; namespace redb.Route.Expressions.Ast; /// /// AST node for postfix operations (e.g. x++, x--). /// Returns the original value before the increment/decrement is applied. /// public class PostfixOperationNode : AstNode { /// /// Gets the operand (the expression being incremented or decremented). /// public AstNode Operand { get; } /// /// Gets the postfix operator ("++" or "--"). /// public string Operator { get; } /// /// Initializes a new instance of the class. /// /// The operand node. /// The postfix operator string ("++" or "--"). /// Thrown when is null. public PostfixOperationNode(AstNode operand, string @operator) { Operand = operand ?? throw new ArgumentNullException(nameof(operand)); Operator = @operator; } /// public override string ToString() { return $"({Operand}){Operator}"; } } Path: redb-route/redb.Route/Expressions/Ast/TernaryNode.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/Expressions/Ast/TernaryNode.cs ---- using redb.Route.Abstractions; namespace redb.Route.Expressions.Ast; /// /// AST node representing a ternary conditional expression (condition ? ifTrue : ifFalse). /// public class TernaryNode : AstNode { /// /// Gets the condition expression. /// public AstNode Condition { get; } /// /// Gets the expression evaluated when the condition is true. /// public AstNode IfTrue { get; } /// /// Gets the expression evaluated when the condition is false. /// public AstNode IfFalse { get; } /// /// Initializes a new instance of the class. /// /// The condition node. /// The node evaluated when condition is true. /// The node evaluated when condition is false. public TernaryNode(AstNode condition, AstNode ifTrue, AstNode ifFalse) { Condition = condition; IfTrue = ifTrue; IfFalse = ifFalse; } /// public override string ToString() => $"({Condition} ? {IfTrue} : {IfFalse})"; } Path: redb-route/redb.Route/Expressions/Ast/Token.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/Expressions/Ast/Token.cs ---- using System; namespace redb.Route.Expressions.Ast; /// /// Enumerates the types of tokens recognized by the expression tokenizer. /// public enum TokenType { /// Numeric literal (integer or floating-point). Number, /// String literal (single- or double-quoted). String, /// Identifier such as a variable name or keyword. Identifier, /// Operator symbol (arithmetic, comparison, or logical). Operator, /// Left parenthesis (. LeftParen, /// Right parenthesis ). RightParen, /// Comma separator ,. Comma, /// Dot (property access) .. Dot, /// Left bracket [. LeftBracket, /// Right bracket ]. RightBracket, /// Function name (identifier followed by an opening parenthesis). Function, /// Colon : used in ternary expressions. Colon, /// End-of-input marker. Eof, // Appended, not inserted: the numeric values above stay as they were. /// A function namespace with its colon, bean:: the target and the call follow. Namespace, /// ${ inside an expression, allowed in the arguments of a namespaced call. PlaceholderOpen, /// }, closing a . RightBrace, } /// /// Represents a single token produced by lexical analysis. /// public class Token { /// /// Gets the type of this token. /// public TokenType Type { get; } /// /// Gets the textual value of this token. /// public string Value { get; } /// /// Gets the position (zero-based index) of this token in the input string. /// public int Position { get; } /// /// Initializes a new instance of the class. /// /// The token type. /// The textual value of the token. /// The position of the token in the input string. public Token(TokenType type, string value, int position) { Type = type; Value = value; Position = position; } /// public override string ToString() => $"{Type}({Value})"; } Path: redb-route/redb.Route/Expressions/Ast/Tokenizer.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/Expressions/Ast/Tokenizer.cs ---- using System; using System.Collections.Generic; namespace redb.Route.Expressions.Ast; /// /// Tokenizer (lexer) that splits an input expression string into a list of instances. /// public class Tokenizer { /// /// The input expression string. /// private readonly string _input; /// /// The current character position in the input. /// private int _position; /// /// The total length of the input string. /// private int _length; /// /// The character at the current position. /// private char _currentChar; /// /// Set of recognized keywords (case-insensitive). /// /// The namespaces of the language: bean: (a method call), ref: (a registry object), env: (an environment variable). internal static readonly HashSet FunctionNamespaces = new(StringComparer.Ordinal) { "bean", "ref", "env" }; /// Set after a namespace token: the next word is the call's target, read by . private bool _namespaceTargetNext; /// The namespace whose target is read next. private string _namespace = ""; private static readonly HashSet _keywords = new HashSet(StringComparer.OrdinalIgnoreCase) { "body", "header", "property", "jpath", "xpath", "logical", "null", "true", "false" }; /// /// Mapping of operator symbols and textual representations to their canonical forms. /// private static readonly Dictionary _operators = new Dictionary { { "+", "+" }, { "-", "-" }, { "*", "*" }, { "/", "/" }, { "%", "%" }, { "==", "==" }, { "!=", "!=" }, { ">", ">" }, { "<", "<" }, { ">=", ">=" }, { "<=", "<=" }, { "&&", "AND" }, { "||", "OR" }, { "!", "NOT" }, { "AND", "AND" }, { "OR", "OR" }, { "NOT", "NOT" }, { "XOR", "XOR" }, { "++", "++" }, { "--", "--" }, { "??", "??" }, { "?", "?" }, }; /// /// Initializes a new instance of the class. /// /// The expression string to tokenize. public Tokenizer(string input) { _input = input ?? string.Empty; _length = _input.Length; _position = 0; if (_length > 0) _currentChar = _input[0]; } /// /// Tokenizes the entire input string and returns all tokens including the trailing EOF token. /// /// A list of all tokens parsed from the input. public List GetAllTokens() { var tokens = new List(); Token token; do { token = GetNextToken(); tokens.Add(token); } while (token.Type != TokenType.Eof); return tokens; } /// /// Reads and returns the next token from the input. /// /// The next from the input stream. public Token GetNextToken() { // Skip whitespace while (_position < _length && char.IsWhiteSpace(_currentChar)) { Advance(); } // End of input reached if (_position >= _length) { return new Token(TokenType.Eof, string.Empty, _position); } // Handle numbers if (char.IsDigit(_currentChar)) { return Number(); } // The target of a namespaced call: a registry name may carry dashes (seen-orders.Check) if (_namespaceTargetNext) { _namespaceTargetNext = false; if (char.IsLetter(_currentChar) || _currentChar == '_') return NamespaceTarget(); } // Handle identifiers and keywords if (char.IsLetter(_currentChar) || _currentChar == '_') { return Identifier(); } // Handle string literals if (_currentChar == '\'' || _currentChar == '\"') { return String(); } // A placeholder inside an expression (the arguments of a bean: call); the parser decides where it is allowed. if (_currentChar == '$' && _position + 1 < _length && _input[_position + 1] == '{') { var start = _position; Advance(); Advance(); return new Token(TokenType.PlaceholderOpen, "${", start); } // Handle single-character tokens switch (_currentChar) { case '}': return CreateToken(TokenType.RightBrace, Advance().ToString()); case '(': return CreateToken(TokenType.LeftParen, Advance().ToString()); case ')': return CreateToken(TokenType.RightParen, Advance().ToString()); case '[': return CreateToken(TokenType.LeftBracket, Advance().ToString()); case ']': return CreateToken(TokenType.RightBracket, Advance().ToString()); case ',': return CreateToken(TokenType.Comma, Advance().ToString()); case '.': return CreateToken(TokenType.Dot, Advance().ToString()); case ':': return CreateToken(TokenType.Colon, Advance().ToString()); case '+': case '-': case '*': case '/': case '%': case '!': case '=': case '<': case '>': case '&': case '|': case '?': return Operator(); } // Unknown character — return as an operator token var ch = _currentChar; Advance(); return new Token(TokenType.Operator, ch.ToString(), _position - 1); } /// /// Advances the position by one character and returns the new current character. /// /// The character at the new position, or '\0' if the end of input is reached. /// /// If the next word after optional whitespace is exactly (case-insensitive, /// ending at a non-identifier character), consumes it and returns true; otherwise leaves the /// position untouched. Lets "NOT IN" become one token while "NOT inStock" stays NOT + identifier. /// private bool TryConsumeFollowingWord(string word) { var probe = _position; while (probe < _length && char.IsWhiteSpace(_input[probe])) probe++; if (probe == _position) return false; // "NOTIN" is one identifier, not two words if (probe + word.Length > _length || string.Compare(_input, probe, word, 0, word.Length, StringComparison.OrdinalIgnoreCase) != 0) return false; var end = probe + word.Length; if (end < _length && (char.IsLetterOrDigit(_input[end]) || _input[end] == '_' || _input[end] == '.')) return false; // "NOT inStock", "NOT in.x": a longer identifier, not the IN operator while (_position < end) Advance(); return true; } private char Advance() { _position++; if (_position < _length) { _currentChar = _input[_position]; return _currentChar; } // End of input reached — set null character _currentChar = '\0'; return _currentChar; } /// /// Reads a numeric token (integer or floating-point). /// /// A of type . private Token Number() { var startPos = _position; var result = string.Empty; var hasDot = false; while (_position < _length && (char.IsDigit(_currentChar) || (_currentChar == '.' && !hasDot))) { if (_currentChar == '.') hasDot = true; result += _currentChar; Advance(); } return new Token(TokenType.Number, result, startPos); } /// /// Reads an identifier or keyword token. If the identifier is immediately followed by /// an opening parenthesis, it is classified as a . /// /// A of type or . private Token Identifier() { var startPos = _position; var result = string.Empty; while (_position < _length && (char.IsLetterOrDigit(_currentChar) || _currentChar == '_' || _currentChar == '.')) { result += _currentChar; Advance(); } // A function namespace: a registered name written directly against its colon and its target (bean:svc.M). // With a space or without a target the colon stays the ternary's, so "c ? bean : other" reads as before. if (FunctionNamespaces.Contains(result) && _currentChar == ':' && _position + 1 < _length && (char.IsLetter(_input[_position + 1]) || _input[_position + 1] == '_')) { Advance(); // the colon _namespaceTargetNext = true; _namespace = result; return new Token(TokenType.Namespace, result, startPos); } var upper = result.ToUpperInvariant(); // IN is an operator even with a parenthesis right after it: "x in('a','b')" is a list // literal, not a call to a function named "in". Checked before the function rule for that // reason; the other word operators keep their order, so nothing they parse changes. if (upper == "IN") { return new Token(TokenType.Operator, "IN", startPos); } // If the identifier is followed by an opening parenthesis, treat it as a function call if (_position < _length && _currentChar == '(') { return new Token(TokenType.Function, result, startPos); } // "NOT IN" is one binary operator, not a unary NOT in front of a stray IN. if (upper == "NOT" && TryConsumeFollowingWord("IN")) { return new Token(TokenType.Operator, "NOT IN", startPos); } // Check for word-operators (NOT, AND, OR, XOR) if (upper == "NOT" || upper == "AND" || upper == "OR" || upper == "XOR") { return new Token(TokenType.Operator, upper, startPos); } // Check for keywords if (_keywords.Contains(result)) { return new Token(TokenType.Identifier, result, startPos); } return new Token(TokenType.Identifier, result, startPos); } /// /// Reads the target of a namespaced call, name.Method: the name may hold dashes, as registry names do /// (seen-orders); the method after the last dot is an identifier, so a dash after it is the minus operator /// again (bean:svc.Count-1 reads the method Count, then minus one). A function token when a /// parenthesis follows, an identifier token otherwise. /// /// The target of ref: is a registry name only, so the whole run is the name, dots and dashes included /// (ref:chat.settings), as in Apache Camel; a trailing dot or dash is not part of it. /// /// private Token NamespaceTarget() { var startPos = _position; var end = _position; while (end < _length && (char.IsLetterOrDigit(_input[end]) || _input[end] is '_' or '.' or '-')) end++; var run = _input[startPos..end]; if (_namespace is "ref" or "env") { run = run.TrimEnd('.', '-'); while (_position < startPos + run.Length) Advance(); return new Token(TokenType.Identifier, run, startPos); } var lastDot = run.LastIndexOf('.'); var methodStart = lastDot + 1; var methodDash = run.IndexOf('-', methodStart); if (methodDash >= 0) run = run[..methodDash]; run = run.TrimEnd('-'); while (_position < startPos + run.Length) Advance(); return _position < _length && _currentChar == '(' ? new Token(TokenType.Function, run, startPos) : new Token(TokenType.Identifier, run, startPos); } /// /// Reads a string literal token (single- or double-quoted), handling escape sequences. /// /// A of type . private Token String() { var startPos = _position; var quoteChar = _currentChar; var result = quoteChar.ToString(); Advance(); // Skip the opening quote // Read until the closing quote while (_position < _length && _currentChar != quoteChar) { // Handle escape sequences if (_currentChar == '\\' && _position + 1 < _length) { result += _currentChar; Advance(); } result += _currentChar; Advance(); } if (_position < _length) // Append the closing quote { result += _currentChar; Advance(); } else { // A literal that never ends: the parser would read it truncated by one character ('abc gave "ab") or, for // a lone quote, fail with an internal "length -1" (findings rows 14 and 17). Name it where the author can // find it. throw new InvalidOperationException( $"unterminated string literal starting at position {startPos + 1} within the expression \"{_input}\"."); } return new Token(TokenType.String, result, startPos); } /// /// Reads an operator token, handling both single-character and two-character operators. /// Normalizes the operator to its canonical form (e.g. && becomes AND). /// /// A of type . private Token Operator() { var startPos = _position; var op = _currentChar.ToString(); Advance(); // Handle two-character operators if (_position < _length) { var twoCharOp = op + _currentChar; if (twoCharOp == "==" || twoCharOp == "!=" || twoCharOp == ">=" || twoCharOp == "<=" || twoCharOp == "&&" || twoCharOp == "||" || twoCharOp == "++" || twoCharOp == "--" || twoCharOp == "??" || twoCharOp == "=~") { op = twoCharOp; Advance(); } } // Normalize to canonical form if (_operators.TryGetValue(op, out var standardOp)) { op = standardOp; } return new Token(TokenType.Operator, op, startPos); } /// /// Creates a token at the current position minus one (used after a single-character advance). /// /// The token type. /// The token value. /// A new instance. private Token CreateToken(TokenType type, string value) { return new Token(type, value, _position - 1); } } Path: redb-route/redb.Route/Expressions/BeanCallSite.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/Expressions/BeanCallSite.cs ---- using System.Runtime.CompilerServices; using redb.Route.Abstractions; using redb.Route.Components.Bean; namespace redb.Route.Expressions; /// /// One bean:name.Method(args) call in a compiled expression. The expression is compiled once and shared by every /// context that evaluates it, so the bean is resolved per route context: from that context's registry, on the first /// evaluation there, with the method bound once through (the selection and /// conversion rules of the bean: URI). A weak table keeps no context alive. /// /// Synchronous only, as in Apache Camel's Simple language: an expression has no await, so a method returning a task /// is refused when it is first resolved, pointing to the bean step. Refused under : a /// template's data never runs code. /// /// internal sealed class BeanCallSite(string reference, string method, int argumentCount) { private readonly ConditionalWeakTable _resolved = new(); private sealed record Resolved(object Instance, BeanInvoker.BoundMethod Bound, bool Awaitable, Func? TaskResult, Func? ToTask); /// /// Calls the bean with the evaluated and returns the method's result. Synchronous: a /// task-returning method is refused (). /// public object? Invoke(IExchange exchange, object?[] values) { var resolved = ResolveFor(exchange); if (resolved.Awaitable) throw new InvalidOperationException(AwaitableRefused(reference, method, resolved.Bound.Method.ReturnType)); return resolved.Bound.Call(resolved.Instance, values, exchange, CancellationToken.None); } /// /// Calls the bean and awaits a task-returning method (Method() in a condition, where the engine awaits /// ); a plain method's result is returned as it is. /// public async Task InvokeAsync(IExchange exchange, object?[] values, CancellationToken cancellationToken) { var resolved = ResolveFor(exchange); var raw = resolved.Bound.Call(resolved.Instance, values, exchange, cancellationToken); if (!resolved.Awaitable) return raw; var task = resolved.ToTask is { } toTask ? (Task)toTask(raw)! : (Task)raw!; await task.ConfigureAwait(false); return resolved.TaskResult?.Invoke(task); } private Resolved ResolveFor(IExchange exchange) { var context = exchange.Context ?? throw new InvalidOperationException( $"bean:{reference}.{method}: the exchange has no route context, so there is no registry to find the bean in."); var resolved = _resolved.GetValue(context, Resolve); if (ExpressionSandbox.IsActive) throw new ExpressionSandboxViolationException(method, resolved.Instance.GetType()); return resolved; } private Resolved Resolve(IRouteContext context) { var instance = context.GetFromRegistry(reference) ?? throw new InvalidOperationException( $"bean:{reference}.{method}: '{reference}' is not in the context registry. " + "Register it with AddToRegistry or a declaration."); var bound = BeanInvoker.ForValues(instance.GetType(), method, argumentCount, "#" + reference); var (_, taskResult, toTask) = BeanInvoker.ClassifyReturn(bound.Method.ReturnType); return new Resolved(instance, bound, BeanInvoker.IsAwaitable(bound.Method.ReturnType), taskResult, toTask); } /// The refusal of a task-returning method, worded once for the call and for the package gate. internal static string AwaitableRefused(string reference, string method, Type returnType) => $"bean:{reference}.{method} returns {returnType.Name}: a bean: call in an expression is " + $"synchronous. Call an asynchronous method as a step: " + $"or .Bean(\"#{reference}\", \"{method}(...)\")."; /// /// The bean: calls of one expression, as the engine parses it: the tool's view of what an expression will /// call (the package gate). Throws with the parser's positioned message /// when the expression does not parse. /// internal static IReadOnlyList CallsIn(string expression) => NodesIn(expression); /// /// The ref: names of one expression, as the engine parses it (the package gate). Throws /// with the parser's positioned message when the expression does not parse. /// internal static IReadOnlyList RefsIn(string expression) => NodesIn(expression); private static List NodesIn(string expression) where T : Ast.AstNode { var root = new Ast.Parser(new Ast.Tokenizer(expression).GetAllTokens()).Parse(); var nodes = new List(); Collect(root, nodes); return nodes; } private static void Collect(Ast.AstNode node, List calls) where T : Ast.AstNode { if (node is T call) calls.Add(call); foreach (var property in node.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { if (property.GetIndexParameters().Length > 0) continue; switch (property.GetValue(node)) { case Ast.AstNode child: Collect(child, calls); break; case IEnumerable children: foreach (var child in children) Collect(child, calls); break; } } } } Path: redb-route/redb.Route/Expressions/BeanMethodExpression.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/Expressions/BeanMethodExpression.cs ---- using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Predicates; using redb.Route.Core; namespace redb.Route.Expressions; /// /// What builds: a registry bean's method as an expression and a condition, /// Apache Camel's method(ref, "name"). The same call as ${bean:name.Method(args)}, typed and written in /// the bean: URI spelling (IsGold(${header.name})), through the same binding and the same per-context /// resolution. One difference: in a condition the engine awaits , so a method /// returning Task<bool> works there; a value position () is synchronous and refuses /// it as the function does. /// /// Exposed as , so Filter(Method(...)) picks the expression overload /// without ambiguity; the condition path finds the it also is. /// /// internal sealed class BeanMethodExpression : Expression, IPredicateExpression, IPredicate { private readonly string _reference; private readonly string _spec; private readonly StringExpression[] _arguments; private readonly BeanCallSite _site; internal BeanMethodExpression(string reference, string methodSpec) { ArgumentException.ThrowIfNullOrWhiteSpace(reference); ArgumentException.ThrowIfNullOrWhiteSpace(methodSpec); var name = reference.Trim(); if (name.Contains(',', StringComparison.Ordinal) || (!name.StartsWith('#') && name.Contains('.', StringComparison.Ordinal))) throw new ArgumentException( $"Method(\"{reference}\", ...): in an expression the bean is a registry name (\"#name\"). " + "Declare an instance of a type with or AddToRegistry first.", nameof(reference)); _reference = name.TrimStart('#'); _spec = methodSpec.Trim(); var (method, arguments) = BeanInvoker.ParseMethodSpec(_spec, "#" + _reference); _arguments = [.. arguments.Select(a => new StringExpression(a))]; _site = new BeanCallSite(_reference, method, _arguments.Length); } private object?[] Values(IExchange exchange) => [.. _arguments.Select(a => a.Evaluate(exchange))]; /// public override T Evaluate(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange); var result = _site.Invoke(exchange, Values(exchange)); if (result is null) return default!; if (result is T typed) return typed; if (typeof(T) == typeof(string)) return (T)(object)ExpressionResolver.TemplateText(result); return (T)RouteDecimal.ChangeType(result, typeof(T), System.Globalization.CultureInfo.InvariantCulture); } /// public bool Matches(IExchange exchange) => RouteTruthiness.ToBoolean(Evaluate(exchange)); /// public async Task MatchesAsync(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange); return RouteTruthiness.ToBoolean(await _site.InvokeAsync(exchange, Values(exchange), CancellationToken.None).ConfigureAwait(false)); } /// public override void SetValue(IExchange exchange, object value) => throw new NotSupportedException($"Method(\"#{_reference}\", \"{_spec}\") is a call; it cannot be assigned."); /// public override string ToTemplateString() => $"${{bean:{_reference}.{_spec}}}"; /// public override string ToString() => $"Method(\"#{_reference}\", \"{_spec}\")"; } Path: redb-route/redb.Route/Expressions/BodyExpression.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/Expressions/BodyExpression.cs ---- using System; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Expression for accessing the message body in an . /// /// /// Allows extracting and converting the message body /// for use in predicates and routing logic. /// public class BodyExpression : Expression { /// /// Initializes a new instance of the class. /// public BodyExpression() { } /// /// Thrown when is null. /// Thrown when the body type is not compatible with . public override T Evaluate(IExchange exchange) { if (exchange == null) throw new ArgumentNullException(nameof(exchange)); return exchange.In.getBody(); } /// /// Thrown when is null. public override void SetValue(IExchange exchange, object value) { if (exchange == null) throw new ArgumentNullException(nameof(exchange)); exchange.In.setBody(value); } /// public override string ToTemplateString() => "${body}"; } Path: redb-route/redb.Route/Expressions/CompiledJPathExpression.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/Expressions/CompiledJPathExpression.cs ---- using System; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// A compiled JPath expression that evaluates a dynamic JSON path using a delegate /// and then delegates the actual JSON path evaluation to . /// public class CompiledJPathExpression { private readonly Func _pathDelegate; /// /// Initializes a new instance of the class. /// /// A delegate that computes the JSON path string from an . public CompiledJPathExpression(Func pathDelegate) { _pathDelegate = pathDelegate; } /// /// Evaluates the dynamic JSON path expression against the exchange. /// /// The type of the return value. /// The exchange containing the message data. /// The value extracted by the computed JSON path, converted to . public T Evaluate(IExchange exchange) { // Compute the path using the delegate var path = _pathDelegate(exchange)?.ToString(); if (string.IsNullOrEmpty(path)) { return default(T); } // Create a JsonPathExpression with the computed path var jsonPathExpression = new JsonPathExpression(path); // Evaluate the value at the path return jsonPathExpression.Evaluate(exchange); } } Path: redb-route/redb.Route/Expressions/CompiledXPathExpression.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/Expressions/CompiledXPathExpression.cs ---- using System; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// An XPath expression whose path is computed per message, delegating the evaluation itself /// to . /// /// /// /// The ordinary case is a fixed path over a varying document. This is the other one: a route that /// decides which path to run from the message — a rule id in a header, a per-tenant selector in an /// exchange property. It costs an XPath compilation per message, which is why it is a separate type /// rather than the default behaviour. /// /// /// Until 2026-09-03 it did not implement , so despite being public and /// tested there was nowhere in the DSL to put it: every position that takes an expression takes /// that interface. It now is one, which makes it usable in the value, condition, routing and stream /// positions, and in the EIPs that accept an expression. /// /// public class CompiledXPathExpression : Expression { private readonly Func _pathDelegate; /// /// Initializes a new instance of the class. /// /// A delegate that computes the XPath string from an . public CompiledXPathExpression(Func pathDelegate) { _pathDelegate = pathDelegate ?? throw new ArgumentNullException(nameof(pathDelegate)); } /// /// Evaluates the dynamic XPath expression against the exchange. /// /// The type of the return value. /// The exchange containing the message data. /// /// The value extracted by the computed XPath, converted to , or the /// default when the delegate produced no path. /// public override T Evaluate(IExchange exchange) { var path = _pathDelegate(exchange)?.ToString(); if (string.IsNullOrEmpty(path)) return default(T); var xpathExpression = new XPathExpression(path); return xpathExpression.Evaluate(exchange); } /// public override void SetValue(IExchange exchange, object value) => throw new NotSupportedException("CompiledXPathExpression does not support setting values."); /// /// /// Always thrown: the path exists only per message, so there is no fixed text to serialize. /// public override string ToTemplateString() => throw new NotSupportedException( "CompiledXPathExpression computes its path per message and has no template form."); } Path: redb-route/redb.Route/Expressions/ConstantExpression.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/Expressions/ConstantExpression.cs ---- using System; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// A constant expression that always returns the same value regardless of the exchange. /// public class ConstantExpression : Expression { private readonly object _value; /// /// Gets the constant value held by this expression. /// public object Value => _value; /// /// Initializes a new instance of the class with the specified value. /// /// The constant value. public ConstantExpression(object value) { _value = value; } /// /// /// Thrown when the constant value cannot be converted to . /// public override K Evaluate(IExchange exchange) { if (_value is K typedValue) { return typedValue; } if (_value == null) { return default; } try { return (K)RouteDecimal.ChangeType(_value, typeof(K)); } catch (Exception ex) { throw new InvalidCastException( $"Cannot convert constant value of type {_value.GetType().Name} to {typeof(K).Name}", ex); } } /// /// Always thrown because a constant expression is read-only. public override void SetValue(IExchange exchange, object value) { throw new NotSupportedException("Cannot set value on a constant expression"); } /// public override string ToTemplateString() => _value?.ToString() ?? ""; } Path: redb-route/redb.Route/Expressions/DelegateExpression.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/Expressions/DelegateExpression.cs ---- using System; using System.Collections.Generic; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// An expression based on a delegate (function) that evaluates its value from an . /// /// The return type of the delegate. public class DelegateExpression : Expression { private readonly Func _delegate; /// /// Initializes a new instance of the class with the specified delegate. /// /// A function that accepts an and returns a value of type . /// Thrown when is null. public DelegateExpression(Func @delegate) { _delegate = @delegate ?? throw new ArgumentNullException(nameof(@delegate)); } /// /// Thrown when the delegate result cannot be cast to . /// Thrown when the delegate execution fails. public override K Evaluate(IExchange exchange) { try { var result = _delegate(exchange); // If the result is null, return default(K) if (result == null) { return default; } if (result is K typedResult) { return typedResult; } // If K is some IEnumerable<> and result is a collection of another type, // try converting via reflection if (typeof(K).IsGenericType && typeof(K).GetGenericTypeDefinition() == typeof(IEnumerable<>) && result is System.Collections.IEnumerable collection) { // Element type of the target collection var targetElementType = typeof(K).GetGenericArguments()[0]; // Convert collection elements and return as IEnumerable var convertedList = Activator.CreateInstance(typeof(List<>).MakeGenericType(targetElementType)); if (convertedList != null) { var addMethod = convertedList.GetType().GetMethod("Add"); if (addMethod != null) { foreach (var item in collection) { if (item != null && item.GetType().IsAssignableTo(targetElementType)) { addMethod.Invoke(convertedList, new[] { item }); } } } if (convertedList is K listAsK) { return listAsK; } } } // Try standard type conversion return (K)RouteDecimal.ChangeType(result, typeof(K)); } catch (InvalidCastException) { throw; } catch (Exception ex) { // Wrap exceptions originating from inside the delegate throw new InvalidOperationException($"Error executing delegate expression: {ex.Message}", ex); } } /// /// Always thrown because a delegate expression is read-only. public override void SetValue(IExchange exchange, object value) { throw new NotSupportedException("Cannot set value on a delegate expression"); } } Path: redb-route/redb.Route/Expressions/ExchangeExpression.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/Expressions/ExchangeExpression.cs ---- using System; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// An expression that evaluates a value from an exchange using a provided function delegate. /// public class ExchangeExpression : Expression { private readonly Func _expressionFunc; /// /// Initializes a new instance of the class. /// /// A function that accepts an and returns a result. /// Thrown when is null. public ExchangeExpression(Func expressionFunc) { _expressionFunc = expressionFunc ?? throw new ArgumentNullException(nameof(expressionFunc)); } /// /// Thrown when is null. /// Thrown when the result cannot be cast to . /// Thrown when the result cannot be converted to due to format issues. /// Thrown when an unexpected conversion error occurs. public override T Evaluate(IExchange exchange) { if (exchange == null) throw new ArgumentNullException(nameof(exchange)); var result = _expressionFunc(exchange); if (result is T typedResult) { return typedResult; } try { return (T)RouteDecimal.ChangeType(result, typeof(T)); } catch (InvalidCastException) { throw new InvalidCastException($"Cannot cast or convert result to type {typeof(T).Name}."); } catch (FormatException) { throw new FormatException($"Result cannot be converted to type {typeof(T).Name} due to format issues."); } catch (Exception ex) { throw new InvalidOperationException($"An error occurred while converting result to type {typeof(T).Name}.", ex); } } /// /// Always thrown because does not support setting values. public override void SetValue(IExchange exchange, object value) { throw new NotSupportedException("ExchangeExpression does not support setting values."); } } Path: redb-route/redb.Route/Expressions/Expression.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/Expressions/Expression.cs ---- using redb.Route.Abstractions; using redb.Route.Predicates; namespace redb.Route.Expressions; /// /// Abstract base class for expressions that implements the interface. /// Provides a standard set of predicate factory methods for building routing conditions. /// public abstract class Expression : IExpression { /// public abstract T Evaluate(IExchange exchange); /// public abstract void SetValue(IExchange exchange, object value); /// Creates a predicate that checks whether the expression value equals the specified value. /// The value to compare against. /// An representing the equality check. public IPredicate isEqualTo(object value) => new EqualsPredicate(this, value); /// Creates a predicate that checks whether the expression value is greater than the specified value. /// The value to compare against. /// An representing the greater-than check. public IPredicate isGreaterThan(object value) => new GreaterThanPredicate(this, value); /// Creates a predicate that checks whether the expression value is less than the specified value. /// The value to compare against. /// An representing the less-than check. public IPredicate isLessThan(object value) => new LessThanPredicate(this, value); /// Creates a predicate that checks whether the expression value is greater than or equal to the specified value. /// The value to compare against. /// An representing the greater-than-or-equal check. public IPredicate isGreaterThanOrEqualTo(object value) => new GreaterThanOrEqualPredicate(this, value); /// Creates a predicate that checks whether the expression value is less than or equal to the specified value. /// The value to compare against. /// An representing the less-than-or-equal check. public IPredicate isLessThanOrEqualTo(object value) => new LessThanOrEqualPredicate(this, value); /// Creates a predicate that checks whether the expression value falls between two boundaries (inclusive). /// The lower boundary. /// The upper boundary. /// An representing the between check. public IPredicate isBetween(object low, object high) => new BetweenPredicate(this, low, high); /// Creates a predicate that checks whether the expression value contains the specified value (for strings/collections). /// The value to search for. /// An representing the contains check. public IPredicate contains(object value) => new ContainsPredicate(this, value); /// Creates a predicate that checks whether the expression value starts with the specified value. /// The prefix value to check. /// An representing the starts-with check. public IPredicate startsWith(object value) => new StartsWithPredicate(this, value); /// Creates a predicate that checks whether the expression value ends with the specified value. /// The suffix value to check. /// An representing the ends-with check. public IPredicate endsWith(object value) => new EndsWithPredicate(this, value); /// Creates a predicate that checks whether the expression value matches the specified regular expression pattern. /// The regular expression pattern. /// An representing the regex match check. public IPredicate regex(string pattern) => new RegexPredicate(this, pattern); /// Creates a predicate that checks whether the expression value is contained in the specified set of values. /// The set of values to check against. /// An representing the membership check. public IPredicate In(params object[] values) => new InPredicate(this, values); /// Creates a predicate that checks whether the expression value does not equal the specified value. /// The value to compare against. /// An representing the inequality check. public IPredicate isNotEqualTo(object value) => new NotEqualsPredicate(this, value); /// Creates a predicate that checks whether the expression value is null. /// An representing the null check. public IPredicate isNull() => new IsNullPredicate(this); /// Creates a predicate that checks whether the expression value is not null. /// An representing the not-null check. public IPredicate isNotNull() => new IsNotNullPredicate(this); /// Creates a predicate that combines the current condition with another using logical AND. /// The predicate to combine with. /// An representing the AND combination. public IPredicate and(IPredicate predicate) => new AndPredicate(this, predicate); /// Creates a predicate that combines the current condition with another using logical OR. /// The predicate to combine with. /// An representing the OR combination. public IPredicate or(IPredicate predicate) => new OrPredicate(this, predicate); /// Creates a predicate that negates the current condition. /// An representing the negated condition. public IPredicate not() => new NotPredicate(this); /// public virtual string ToTemplateString() => throw new NotSupportedException($"{GetType().Name} cannot be serialized to a template string."); } Path: redb-route/redb.Route/Expressions/ExpressionEvaluationException.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/Expressions/ExpressionEvaluationException.cs ---- using System; namespace redb.Route.Expressions; /// /// Thrown when an expression fails to evaluate against an exchange. /// public sealed class ExpressionEvaluationException : Exception { /// /// Initializes a new instance of the class. /// /// The error message. /// The inner exception that caused this failure. public ExpressionEvaluationException(string message, Exception innerException) : base(message, innerException) { } /// /// Initializes a new instance of the class. /// /// The error message. public ExpressionEvaluationException(string message) : base(message) { } } Path: redb-route/redb.Route/Expressions/ExpressionFormatting.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/Expressions/ExpressionFormatting.cs ---- using System.Globalization; namespace redb.Route.Expressions; /// /// The culture lookup behind the language's format(value, pattern[, culture]) function, shared /// by the compiled and the interpreted branch of the engine so both answer alike. /// internal static class ExpressionFormatting { /// /// The culture named by ; no name means invariant. An unknown name is an /// error rather than a silent fall back to invariant: a route that formats money for the wrong /// locale must say so at once, not ship plausible-looking text. /// public static CultureInfo Culture(string? name) { if (string.IsNullOrWhiteSpace(name)) return CultureInfo.InvariantCulture; try { // predefinedOnly: ICU (Linux, macOS) builds a culture from any well-formed tag, 'kl-INGON' included, with // the formats of its language or of none; only the list of known cultures turns such a name down. return CultureInfo.GetCultureInfo(name, predefinedOnly: true); } catch (CultureNotFoundException ex) { throw new ArgumentException( $"format(): '{name}' is not a known culture name (use an IETF tag such as 'ru-RU', or omit the argument for the invariant culture).", nameof(name), ex); } } } Path: redb-route/redb.Route/Expressions/ExpressionResolver.AstIntegration.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/Expressions/ExpressionResolver.AstIntegration.cs ---- using System; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using redb.Route.Abstractions; using redb.Route.Telemetry; using redb.Route.Expressions.Ast; using SysExpression = System.Linq.Expressions.Expression; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver — AST parsing, compilation, and integration. /// public static partial class ExpressionResolver { #region AST public wrappers for use in CompileAstNode // Make private methods accessible for use in AST. // Use different names to avoid recursion. /// /// Applies addition via AST delegation. /// /// Left operand. /// Right operand. /// Result of the addition. public static object? Ast_ApplyAddition(object? left, object? right) => _applyAddition(left, right); /// /// Applies subtraction via AST delegation. /// /// Left operand. /// Right operand. /// Result of the subtraction. public static object? Ast_ApplySubtraction(object? left, object? right) => _applySubtraction(left, right); /// /// Applies multiplication via AST delegation. /// /// Left operand. /// Right operand. /// Result of the multiplication. public static object? Ast_ApplyMultiplication(object? left, object? right) => _applyMultiplication(left, right); /// /// Applies division via AST delegation. /// /// Left operand. /// Right operand. /// Result of the division. public static object? Ast_ApplyDivision(object? left, object? right) => _applyDivision(left, right); /// /// Applies unary plus via AST delegation. /// /// The operand value. /// Result of unary plus. public static object? Ast_ApplyUnaryPlus(object? value) => _applyUnaryPlus(value); /// /// Applies unary minus via AST delegation. /// /// The operand value. /// Result of unary minus. public static object? Ast_ApplyUnaryMinus(object? value) => _applyUnaryMinus(value); /// /// Applies unary NOT via AST delegation. /// /// The operand value. /// Result of unary NOT. public static object? Ast_ApplyUnaryNot(object? value) => _applyUnaryNot(value); /// /// Checks equality of two values via AST delegation. /// /// Left operand. /// Right operand. /// true if the values are equal; otherwise false. public static bool Ast_AreEqual(object? left, object? right) => _areEqual(left, right); /// /// Returns true if the values are NOT equal. /// public static bool Ast_AreNotEqual(object? left, object? right) => !_areEqual(left, right); /// /// Returns true if left is greater than right. /// public static bool Ast_GreaterThan(object? left, object? right) => _compareNumeric(left, right) > 0; /// /// Returns true if left is less than right. /// public static bool Ast_LessThan(object? left, object? right) => _compareNumeric(left, right) < 0; /// /// Returns true if left is greater than or equal to right. /// public static bool Ast_GreaterThanOrEqual(object? left, object? right) => _compareNumeric(left, right) >= 0; /// /// Returns true if left is less than or equal to right. /// public static bool Ast_LessThanOrEqual(object? left, object? right) => _compareNumeric(left, right) <= 0; /// /// Evaluates logical AND between two values. /// public static bool Ast_LogicalAnd(object? left, object? right) { if (_TryConvertToBool(left, out var l) && _TryConvertToBool(right, out var r)) return l && r; return false; } /// /// Evaluates logical OR between two values. /// public static bool Ast_LogicalOr(object? left, object? right) { if (_TryConvertToBool(left, out var l) && _TryConvertToBool(right, out var r)) return l || r; return false; } /// /// Evaluates logical XOR between two values. /// public static bool Ast_LogicalXor(object? left, object? right) { if (_TryConvertToBool(left, out var l) && _TryConvertToBool(right, out var r)) return l ^ r; return false; } /// /// Returns the left operand if it is not null; otherwise returns the right operand (null-coalescing). /// public static object? Ast_NullCoalesce(object? left, object? right) => left ?? right; /// /// Concatenates the string representations of all arguments. /// /// The values to concatenate. /// The concatenated string. public static object? Ast_Concat(params object?[] args) => string.Concat(args.Select(a => a?.ToString() ?? string.Empty)); /// Converts a string to upper case. public static object? Ast_Upper(object? value) => value?.ToString()?.ToUpperInvariant(); /// Converts a string to lower case. public static object? Ast_Lower(object? value) => value?.ToString()?.ToLowerInvariant(); /// Trims whitespace from a string. public static object? Ast_Trim(object? value) => value?.ToString()?.Trim(); /// Returns the length of a string or collection. public static object? Ast_Length(object? value) { if (value == null) return null; if (value is string s) return s.Length; if (value is System.Collections.ICollection col) return col.Count; if (value is System.Collections.IEnumerable en) return System.Linq.Enumerable.Count(System.Linq.Enumerable.Cast(en)); return value.ToString()?.Length; } /// Extracts a substring. public static object? Ast_Substring(object? value, object? start, object? length) { var str = value?.ToString(); if (str == null) return null; if (!TryConvertToDouble(start, out var startIdx)) return str; var s = (int)startIdx; if (s < 0) s = 0; if (s >= str.Length) return string.Empty; if (length != null && TryConvertToDouble(length, out var lenVal)) { var len = (int)lenVal; if (len <= 0) return string.Empty; return str.Substring(s, Math.Min(len, str.Length - s)); } return str.Substring(s); } /// Returns the absolute value. public static object? Ast_Abs(object? value) { if (TryConvertToDouble(value, out var d)) return d == (int)d ? (object)(int)Math.Abs(d) : Math.Abs(d); return null; } /// Rounds a number to the specified number of digits. public static object? Ast_Round(object? value, object? digits) { if (!TryConvertToDouble(value, out var v)) return null; int d = 0; if (digits != null && TryConvertToDouble(digits, out var dv)) d = (int)dv; return Math.Round(v, d); } /// Returns the minimum of two values. public static object? Ast_Min(object? a, object? b) => Ast_Extremum(a, b, Math.Min); /// Returns the maximum of two values, or of every numeric value in a collection. public static object? Ast_Max(object? a, object? b) => Ast_Extremum(a, b, Math.Max); /// /// Shared body of min / max: two scalars compare directly; a single collection /// argument folds over its numeric items the way sum and avg already did. Until /// 2026-08-29 the collection form returned null, so min(property.nums) silently read as /// "no value" while sum(property.nums) worked. /// private static object? Ast_Extremum(object? a, object? b, Func pick) { if (b is null && a is System.Collections.IEnumerable items && a is not string) { double? result = null; foreach (var item in items) { if (!TryConvertToDouble(item, out var v)) continue; result = result is null ? v : pick(result.Value, v); } return result; } if (TryConvertToDouble(a, out var va) && TryConvertToDouble(b, out var vb)) return pick(va, vb); return null; } /// Checks if a string contains a substring (case-insensitive). public static object? Ast_Contains(object? value, object? search) { var s = value?.ToString(); var q = search?.ToString(); if (s == null || q == null) return false; return s.Contains(q, StringComparison.OrdinalIgnoreCase); } /// Checks if a string starts with a prefix (case-insensitive). public static object? Ast_StartsWith(object? value, object? prefix) { var s = value?.ToString(); var p = prefix?.ToString(); if (s == null || p == null) return false; return s.StartsWith(p, StringComparison.OrdinalIgnoreCase); } /// Checks if a string ends with a suffix (case-insensitive). public static object? Ast_EndsWith(object? value, object? suffix) { var s = value?.ToString(); var x = suffix?.ToString(); if (s == null || x == null) return false; return s.EndsWith(x, StringComparison.OrdinalIgnoreCase); } /// Replaces all occurrences of a substring. public static object? Ast_Replace(object? value, object? oldStr, object? newStr) { var s = value?.ToString(); var o = oldStr?.ToString(); if (s == null || o == null) return s; return s.Replace(o, newStr?.ToString() ?? string.Empty); } /// Returns the current UTC date/time. public static object? Ast_Now() => DateTime.UtcNow; /// Formats a date value using the specified format string. public static object? Ast_DateFormat(object? value, object? format) { var fmt = format?.ToString() ?? "yyyy-MM-dd"; if (value is DateTime dt) return dt.ToString(fmt, System.Globalization.CultureInfo.InvariantCulture); if (value is DateTimeOffset dto) return dto.ToString(fmt, System.Globalization.CultureInfo.InvariantCulture); if (DateTime.TryParse(value?.ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var parsed)) return parsed.ToString(fmt, System.Globalization.CultureInfo.InvariantCulture); return value?.ToString(); } /// /// Formats a value with a .NET format string and an optional culture name: /// format(header.price, 'N2') is invariant, format(header.price, 'N2', 'ru-RU') is /// the named locale. This is the explicit way to get locale-specific text now that ${...} /// renders culture-invariant; a string that holds a number or a date is parsed invariantly first, /// anything else is returned as its own text. /// public static object? Ast_Format(object? value, object? format, object? culture) { if (value is null) return null; var formatString = format?.ToString(); var cultureInfo = ExpressionFormatting.Culture(culture?.ToString()); if (string.IsNullOrEmpty(formatString)) return value is IFormattable plain ? plain.ToString(null, cultureInfo) : value.ToString(); if (value is IFormattable formattable) return formattable.ToString(formatString, cultureInfo); var text = value.ToString(); if (decimal.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var number)) return number.ToString(formatString, cultureInfo); if (DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) return date.ToString(formatString, cultureInfo); return text; } /// Adds a time interval to a date value. public static object? Ast_DateAdd(object? value, object? amount, object? unit) { DateTime baseDate; if (value is DateTime d1) baseDate = d1; else if (value is DateTimeOffset d2) baseDate = d2.UtcDateTime; else if (DateTime.TryParse(value?.ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var p)) baseDate = p; else return null; if (!TryConvertToDouble(amount, out var amt)) return null; var u = unit?.ToString()?.ToLowerInvariant() ?? "days"; return u switch { "days" or "day" => baseDate.AddDays(amt), "hours" or "hour" => baseDate.AddHours(amt), "minutes" or "minute" => baseDate.AddMinutes(amt), "seconds" or "second" => baseDate.AddSeconds(amt), "months" or "month" => baseDate.AddMonths((int)amt), "years" or "year" => baseDate.AddYears((int)amt), _ => null }; } /// /// Modulo over the same numeric coercion as division: both operands convert /// invariantly, a zero divisor yields null (as division does), a whole result collapses to int. /// public static object? Ast_ApplyModulo(object? left, object? right) { if (left is null || right is null) return null; if (!TryConvertToNumber(left, out var leftNumber) || !TryConvertToNumber(right, out var rightNumber)) return null; if (Math.Abs(rightNumber) < double.Epsilon) return null; var result = leftNumber % rightNumber; if (Math.Abs(result - Math.Floor(result)) < double.Epsilon) return Convert.ToInt32(result); return result; } /// /// A fresh GUID as text. Impure by design: every evaluation yields a new value /// (the expression cache stores compiled delegates, never results). The optional argument is the /// standard GUID format specifier ('D' default, 'N' compact, 'B', 'P'); /// an unknown specifier throws rather than falling back silently. /// public static object? Ast_Uuid(object? format) => Guid.NewGuid().ToString(format?.ToString() ?? "D"); /// /// Difference between two dates, first minus second, in the requested unit. /// Dates coerce exactly as does (DateTime, DateTimeOffset, or an /// invariantly parsed string); the unit vocabulary is 's plus /// milliseconds (ms); an unknown unit yields null, matching . /// A whole result collapses to int, matching division. /// public static object? Ast_DateDiff(object? left, object? right, object? unit) { if (!TryCoerceDate(left, out var a) || !TryCoerceDate(right, out var b)) return null; var span = a - b; var u = unit?.ToString()?.ToLowerInvariant() ?? "days"; double result = u switch { "days" or "day" => span.TotalDays, "hours" or "hour" => span.TotalHours, "minutes" or "minute" => span.TotalMinutes, "seconds" or "second" => span.TotalSeconds, "milliseconds" or "millisecond" or "ms" => span.TotalMilliseconds, _ => double.NaN }; if (double.IsNaN(result)) return null; if (Math.Abs(result - Math.Floor(result)) < double.Epsilon) return Convert.ToInt32(result); return result; } private static bool TryCoerceDate(object? value, out DateTime date) { switch (value) { case DateTime d: date = d; return true; case DateTimeOffset o: date = o.UtcDateTime; return true; default: return DateTime.TryParse(value?.ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date); } } /// Sums all numeric values in a collection. public static object? Ast_Sum(object? value) { if (value is System.Collections.IEnumerable en && value is not string) { double total = 0; foreach (var item in en) if (TryConvertToDouble(item, out var v)) total += v; return total; } return null; } /// Averages all numeric values in a collection. public static object? Ast_Avg(object? value) { if (value is System.Collections.IEnumerable en && value is not string) { double total = 0; int count = 0; foreach (var item in en) if (TryConvertToDouble(item, out var v)) { total += v; count++; } return count > 0 ? total / count : (object?)null; } return null; } /// Counts elements in a collection. public static object? Ast_Count(object? value) { if (value == null) return 0; if (value is System.Collections.ICollection col) return col.Count; if (value is System.Collections.IEnumerable en && value is not string) return System.Linq.Enumerable.Count(System.Linq.Enumerable.Cast(en)); return 1; } /// Evaluates a logical() function — converts a value to bool. public static object? Ast_Logical(object? value, IExchange exchange) { if (TryConvertToBool(value, out var result)) return result; return false; } /// Evaluates a jpath() function via AST delegation. public static object? Ast_JPath(object? path, IExchange exchange) { var pathStr = path?.ToString(); if (pathStr == null) return null; return ApplyJPath(exchange, pathStr); } /// /// Evaluates the two-argument jpath(path, source), which reads the source instead of the /// message body. The source arrives already evaluated, as a value. /// public static object? Ast_JPathFrom(object? path, object? source, IExchange exchange) { var pathStr = path?.ToString(); if (pathStr == null) return null; // The language is lenient about missing data: the one-argument form yields null on a null // body, and a named source that produced nothing is the same situation with the data // missing from somewhere else. The strict reading lives on the object form, where // From(...) still fails loudly. if (source is null) return null; // Same per-call-site cache as the one-argument form: the path is constant, the input is not. var expression = JsonPathExpressions.GetOrAdd(pathStr, static p => new JsonPathExpression(p)); return expression.EvaluateOn(source, fromSource: true); } /// Evaluates an xpath() function via AST delegation. public static object? Ast_XPath(object? path, IExchange exchange) { var pathStr = path?.ToString(); if (pathStr == null) return null; return ApplyXPath(exchange, pathStr); } /// /// Evaluates stats(target, metric) — endpoint statistics as a value in the expression /// language, so a route can branch on its own measurements: /// Filter("stats('direct:target', 'health') != 'Critical'"). /// /// /// target is an endpoint URI or 'current' (the route processing the exchange); /// metric names an reading, /// case-insensitive. Unlike a missing data source in xpath(), every failure here is an /// authoring error — a route that asks for measurements it cannot get should say so loudly, /// not route messages on a silent null. /// public static object? Ast_Stats(object? target, object? metric, IExchange exchange) { var targetText = target?.ToString(); var metricText = metric?.ToString(); if (string.IsNullOrWhiteSpace(targetText) || string.IsNullOrWhiteSpace(metricText)) throw new InvalidOperationException("stats() needs a target ('current' or an endpoint URI) and a metric name."); var context = exchange.Context ?? throw new InvalidOperationException( "stats(): the exchange carries no route context. Only an exchange that entered a " + "route can read statistics; one built by hand cannot."); // The OpenTelemetry layer, addressed as otel:instrument[@route][/step]. Its EIP counters and // .Metered() durations exist nowhere else, and a markup route has no other way to reach them. if (targetText.StartsWith(OtelPrefix, StringComparison.OrdinalIgnoreCase)) return ReadOtelPoint(targetText[OtelPrefix.Length..], metricText, exchange, context); IEndpointStatistics? stats; if (targetText.Equals("current", StringComparison.OrdinalIgnoreCase)) { var routeId = exchange.RouteId ?? throw new InvalidOperationException("stats('current'): the exchange has no route id."); stats = (context as Core.RouteContext)?.GetRoute(routeId)?.Endpoint as IEndpointStatistics; if (stats is null) throw new InvalidOperationException( $"stats('current'): route '{routeId}' was not found or its endpoint keeps no statistics."); } else { stats = context.GetEndpoint(targetText) as IEndpointStatistics; if (stats is null) throw new InvalidOperationException( $"stats(): endpoint '{targetText}' keeps no statistics."); } return ReadStatistic(stats, metricText); } /// Prefix that sends stats() to the OpenTelemetry layer instead of endpoint statistics. internal const string OtelPrefix = "otel:"; /// /// Evaluates stats('otel:instrument[@route][/step]', field) — one reading of one instrument of the /// redb.Route meter (METRICS_IN_ROUTE_PLAN, question 2). Without @route the instrument is read /// for the route processing the exchange; field is count, sum, min, max or last. /// /// /// The in-process subscriber stays opt-in, so a missing one is an authoring error and says which call turns /// it on. An instrument nobody has measured yet reads as zero: that is an answer, not a failure. /// internal static object? ReadOtelPoint(string spec, string field, IExchange exchange, IRouteContext context) { var snapshot = context.GetMetricsSnapshot() ?? throw new InvalidOperationException( "stats('otel:…'): the in-process metrics subscriber is not running. Call context.UseMetricsSnapshot() " + "(or services.AddMetricsSnapshot()) before a route reads the OpenTelemetry layer."); string? step = null; var slash = spec.IndexOf('/'); if (slash >= 0) { step = spec[(slash + 1)..]; spec = spec[..slash]; } string? routeId = null; var at = spec.IndexOf('@'); if (at >= 0) { routeId = spec[(at + 1)..]; spec = spec[..at]; } var instrument = spec.Trim(); if (instrument.Length == 0) throw new InvalidOperationException( "stats('otel:…'): the instrument name is empty. Write otel:instrument[@route][/step], " + "e.g. otel:redb.route.step.duration/enrich."); routeId ??= exchange.RouteId; var point = snapshot.Point(instrument, routeId, step); return ReadOtelField(point, field); } /// The fields of a snapshot point stats('otel:…') understands. internal static object? ReadOtelField(MetricSnapshotPoint? point, string field) => field.ToLowerInvariant() switch { "count" => point?.Count ?? 0L, "sum" => point?.Sum ?? 0d, "min" => point?.Min ?? 0d, "max" => point?.Max ?? 0d, "last" => point?.Last ?? 0d, _ => throw new ArgumentException( $"stats('otel:…'): unknown field '{field}'. Known: count, sum, min, max, last.") }; /// Whether names a reading of a snapshot point. internal static bool IsKnownOtelField(string field) => field.ToLowerInvariant() is "count" or "sum" or "min" or "max" or "last"; /// /// Evaluates messageHistory(kind) — the trail the exchange left through the route, as a value. /// table (the default) is the dump Camel prints on failure, compact one line, json an /// array; count, totalMs and slowestMs are numbers, so markup can branch on cost, and /// slowest / lastNode name a step. /// /// /// Message history is opt-in (RouteEngineOptions.EnableMessageHistory, .MessageHistory()), so an /// exchange that recorded none reads as an empty string and zero — the one place this language answers a /// missing measurement instead of failing. An unknown kind is still an authoring error. /// public static object? Ast_MessageHistory(object? kind, IExchange exchange) { var kindText = kind?.ToString(); if (string.IsNullOrWhiteSpace(kindText)) kindText = "table"; kindText = kindText.Trim(); if (!IsKnownHistoryKind(kindText)) throw new ArgumentException(HistoryKindMessage(kindText)); var entries = Core.MessageHistory.GetEntries(exchange); return kindText.ToLowerInvariant() switch { "table" => Core.MessageHistory.Format(exchange), "compact" => string.Join(" > ", entries.Select(e => e.Label)), "json" => System.Text.Json.JsonSerializer.Serialize(entries.Select(e => new { routeId = e.RouteId, nodeId = e.NodeId, label = e.Label, elapsedMs = e.ElapsedMs, })), "count" => entries.Count, "totalms" => entries.Sum(e => e.ElapsedMs), "slowestms" => entries.Count == 0 ? 0d : entries.Max(e => e.ElapsedMs), "slowest" => entries.Count == 0 ? string.Empty : entries.OrderByDescending(e => e.ElapsedMs).First().Label, "lastnode" => entries.Count == 0 ? string.Empty : entries[^1].Label, _ => throw new ArgumentException(HistoryKindMessage(kindText)), }; } /// Whether names a shape of the message history. internal static bool IsKnownHistoryKind(string kind) => kind.ToLowerInvariant() is "table" or "compact" or "json" or "count" or "totalms" or "slowestms" or "slowest" or "lastnode"; private static string HistoryKindMessage(string kind) => $"messageHistory(): unknown kind '{kind}'. Known: table, compact, json, count, totalMs, slowestMs, " + "slowest, lastNode."; /// Whether the first argument of stats() is a literal that names the OpenTelemetry layer. private static bool IsOtelTarget(AstNode target) => target is LiteralNode { Value: string literalTarget } && literalTarget.StartsWith(OtelPrefix, StringComparison.OrdinalIgnoreCase); /// The statistic names stats() understands, and their readings. internal static object? ReadStatistic(IEndpointStatistics stats, string metric) => metric.ToLowerInvariant() switch { "messagesin" => stats.MessagesIn, "messagesout" => stats.MessagesOut, "errors" => stats.Errors, "warnings" => stats.Warnings, "rejected" => stats.Rejected, "cancelled" => stats.Cancelled, "refused" => stats.Refused, "bytesin" => stats.BytesIn, "bytesout" => stats.BytesOut, "throughputpersecond" => stats.ThroughputPerSecond, // Milliseconds rather than a TimeSpan: the language compares numbers. "averageprocessingtimems" => stats.AverageProcessingTime.TotalMilliseconds, "health" => stats.HealthStatus.ToString(), "healthreason" => stats.HealthReason, "lasterror" => stats.LastErrorMessage, "lastrefusal" => stats.LastRefusalMessage, _ => throw new ArgumentException( $"stats(): unknown statistic '{metric}'. Known: messagesIn, messagesOut, errors, " + "warnings, rejected, cancelled, refused, bytesIn, bytesOut, throughputPerSecond, " + "averageProcessingTimeMs, health, healthReason, lastError, lastRefusal.") }; /// True when is a name accepts. internal static bool IsKnownStatistic(string metric) => metric.ToLowerInvariant() is "messagesin" or "messagesout" or "errors" or "warnings" or "rejected" or "cancelled" or "refused" or "bytesin" or "bytesout" or "throughputpersecond" or "averageprocessingtimems" or "health" or "healthreason" or "lasterror" or "lastrefusal"; /// /// Evaluates the two-argument xpath(path, source), which reads the source instead of the /// message body. The source arrives already evaluated, as a value. /// public static object? Ast_XPathFrom(object? path, object? source, IExchange exchange) { var pathStr = path?.ToString(); if (pathStr == null) return null; // Lenient like the one-argument form on a null body — see Ast_JPathFrom. if (source is null) return null; return new XPathExpression(pathStr).EvaluateOn(source, fromSource: true); } /// /// Accesses an element by index in a collection, array, or dictionary-like object. /// /// The collection or array object. /// The index value (integer or string key). /// The element at the given index, or null if access fails. public static object? Ast_IndexAccess(object? obj, object? index) { if (obj == null || index == null) return null; // Try numeric indexing if (index is int intIndex || (index is string s && int.TryParse(s, out intIndex))) { if (obj is System.Collections.IList list) { if (intIndex >= 0 && intIndex < list.Count) return list[intIndex]; return null; } if (obj is Array arr) { if (intIndex >= 0 && intIndex < arr.Length) return arr.GetValue(intIndex); return null; } // Try IEnumerable via ElementAt if (obj is System.Collections.IEnumerable enumerable) { int i = 0; foreach (var item in enumerable) { if (i == intIndex) return item; i++; } return null; } } // Try string key (for dictionaries) var keyStr = index.ToString(); if (keyStr != null) { if (obj is System.Collections.IDictionary dict) { if (dict.Contains(keyStr)) return dict[keyStr]; return null; } // Try generic IDictionary if (obj is IDictionary genDict) { genDict.TryGetValue(keyStr, out var value); return value; } } return null; } /// /// Compares two numeric values via AST delegation. /// /// Left operand. /// Right operand. /// A negative, zero, or positive integer indicating the comparison result. public static int Ast_CompareNumeric(object? left, object? right) => _compareNumeric(left, right); /// /// Attempts to convert a value to a boolean via AST delegation. /// /// The value to convert. /// The boolean result if conversion succeeds. /// true if conversion succeeded; otherwise false. public static bool Ast_TryConvertToBool(object? value, out bool result) { return _TryConvertToBool(value, out result); } /// /// Converts a value to boolean. Returns false for null, empty strings, zero, and "false"; /// returns true for non-null/non-empty values that can't be parsed as a known boolean format. /// /// The value to convert. /// The boolean interpretation of the value. public static bool Ast_ConvertToBool(object? value) => Predicates.RouteTruthiness.ToBoolean(value); /// /// Resolves a property path on an object via AST delegation. /// /// The source object. /// The dot-separated property path. /// The resolved property value. public static object? Ast_ResolvePropertyPath(object? obj, string path) => _resolvePropertyPath(obj, path); // Store references to the original methods. private static readonly Func _applyAddition = ApplyAddition; private static readonly Func _applySubtraction = ApplySubtraction; private static readonly Func _applyMultiplication = ApplyMultiplication; private static readonly Func _applyDivision = ApplyDivision; private static readonly Func _applyUnaryPlus = ApplyUnaryPlus; private static readonly Func _applyUnaryMinus = ApplyUnaryMinus; private static readonly Func _applyUnaryNot = ApplyUnaryNot; private static readonly Func _areEqual = AreEqual; private static readonly Func _compareNumeric = CompareNumeric; // Cannot use an out parameter in a Func delegate, so we do not store a reference to TryConvertToBool. private static readonly Func _resolvePropertyPath = ResolvePropertyPath; #endregion #region Caching helper methods #endregion #region Compilation via AST /// /// Compiles an expression using the AST pipeline. /// /// The expression string to compile. /// A compiled delegate that evaluates the expression against an . private static Func CompileExpressionWithAst(string expression) { try { DebugLog($"Compiling expression via AST: '{expression}'"); // Use Tokenizer and Parser to build the AST var tokenizer = new Ast.Tokenizer(expression); var tokens = tokenizer.GetAllTokens(); var parser = new Ast.Parser(tokens); var ast = parser.Parse(); DebugLog($"Built AST: {ast}"); return CompileTree(ast); } catch (Exception ex) when (ex is not ExpressionSandboxViolationException) { throw new ExpressionCompilationException($"Error compiling expression '{expression}' using AST: {ex.Message}", ex); } } /// /// Compiles an already parsed tree into the engine's delegate: what runs, so a /// node evaluated directly and an expression compiled from text share one evaluator. /// internal static Func CompileAstTree(Ast.AstNode node) { ArgumentNullException.ThrowIfNull(node); try { return CompileTree(node); } catch (Exception ex) when (ex is not ExpressionSandboxViolationException and not ExpressionCompilationException) { throw new ExpressionCompilationException($"Error compiling expression '{node}' using AST: {ex.Message}", ex); } } private static Func CompileTree(Ast.AstNode ast) { var exchangeParam = SysExpression.Parameter(typeof(IExchange), "exchange"); var body = CompileAstNode(ast, exchangeParam); // Ensure the body is boxed to object? (comparison operators return bool/int) if (body.Type != typeof(object) && body.Type.IsValueType) body = SysExpression.Convert(body, typeof(object)); var lambda = SysExpression.Lambda>(body, exchangeParam); DebugLog($"Compiled lambda expression: {lambda}"); return lambda.Compile(); } /// /// Compiles an AST node into a . /// /// The AST node to compile. /// The exchange parameter expression. /// The compiled . private static SysExpression CompileAstNode(AstNode node, ParameterExpression exchangeParam) { if (node == null) throw new ArgumentNullException(nameof(node)); DebugLog($"Compiling AST node: {node.GetType().Name}"); switch (node) { case LiteralNode literalNode: return SysExpression.Constant(literalNode.Value); case IdentifierNode identifierNode: // Get property from the exchange var getPropertyMethod = typeof(ExpressionResolver).GetMethod( nameof(GetExchangeProperty), BindingFlags.NonPublic | BindingFlags.Static); return SysExpression.Call( getPropertyMethod, exchangeParam, SysExpression.Constant(identifierNode.Name)); case PropertyAccessNode propertyAccessNode: // Get the object and its property var objExpr = CompileAstNode(propertyAccessNode.Object, exchangeParam); var resolvePropertyMethod = typeof(ExpressionResolver).GetMethod( nameof(ResolvePropertyPathWithExchange), BindingFlags.NonPublic | BindingFlags.Static); return SysExpression.Call( resolvePropertyMethod, objExpr, SysExpression.Constant(propertyAccessNode.PropertyName), exchangeParam); case IndexAccessNode indexNode: var indexObjExpr = CompileAstNode(indexNode.Object, exchangeParam); var indexExpr = CompileAstNode(indexNode.Index, exchangeParam); // Ensure both are object? if (indexObjExpr.Type != typeof(object)) indexObjExpr = SysExpression.Convert(indexObjExpr, typeof(object)); if (indexExpr.Type != typeof(object)) indexExpr = SysExpression.Convert(indexExpr, typeof(object)); var indexAccessMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_IndexAccess), BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(indexAccessMethod, indexObjExpr, indexExpr); case UnaryOperationNode unaryNode: if (unaryNode.Operator == "++" || unaryNode.Operator == "--") { // Get the property name for increment/decrement string propertyName = GetPropertyNameFromNode(unaryNode.Operand); if (string.IsNullOrEmpty(propertyName)) { throw new ExpressionCompilationException( $"Failed to get property name for operation {unaryNode.Operator}"); } // Select the appropriate method for prefix increment/decrement MethodInfo method = unaryNode.Operator == "++" ? typeof(ExpressionResolver).GetMethod( nameof(ApplyPrefixIncrement), BindingFlags.NonPublic | BindingFlags.Static) : typeof(ExpressionResolver).GetMethod( nameof(ApplyPrefixDecrement), BindingFlags.NonPublic | BindingFlags.Static); return SysExpression.Call( method, exchangeParam, SysExpression.Constant(propertyName)); } else { // Compile the operand, ensuring it is boxed to object? var operandExpr = CompileAstNode(unaryNode.Operand, exchangeParam); if (operandExpr.Type != typeof(object)) operandExpr = SysExpression.Convert(operandExpr, typeof(object)); // Select the appropriate method for the unary operation MethodInfo method; switch (unaryNode.Operator) { case "+": method = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplyUnaryPlus), BindingFlags.Public | BindingFlags.Static); break; case "-": method = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplyUnaryMinus), BindingFlags.Public | BindingFlags.Static); break; case "NOT": case "!": method = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplyUnaryNot), BindingFlags.Public | BindingFlags.Static); break; default: throw new ExpressionCompilationException( $"Unsupported unary operator: {unaryNode.Operator}"); } return SysExpression.Call(method, operandExpr); } case BinaryOperationNode binaryNode: // Compile the left and right operands, ensuring they are boxed to object? var leftExpr = CompileAstNode(binaryNode.Left, exchangeParam); var rightExpr = CompileAstNode(binaryNode.Right, exchangeParam); if (leftExpr.Type != typeof(object)) leftExpr = SysExpression.Convert(leftExpr, typeof(object)); if (rightExpr.Type != typeof(object)) rightExpr = SysExpression.Convert(rightExpr, typeof(object)); // AND / OR short-circuit over the truthiness rule (findings register row 25): the right side runs only // when the left one does not decide. The values are what Ast_LogicalAnd / Ast_LogicalOr gave, since // their conversion never refuses; only a side effect or a fault on the right stops happening. // ?? evaluates its right side only when the left one is null (findings register row 26), as the // interpreted form always did; the value is Ast_NullCoalesce's, left ?? right. if (binaryNode.Operator == "??") return SysExpression.Coalesce(leftExpr, rightExpr); if (binaryNode.Operator is "AND" or "OR") { var toBool = typeof(ExpressionResolver).GetMethod(nameof(Ast_ConvertToBool), BindingFlags.Public | BindingFlags.Static)!; var leftBool = SysExpression.Call(toBool, leftExpr); var rightBool = SysExpression.Call(toBool, rightExpr); return binaryNode.Operator == "AND" ? SysExpression.AndAlso(leftBool, rightBool) : SysExpression.OrElse(leftBool, rightBool); } // Select the appropriate method for the binary operation MethodInfo binaryMethod; switch (binaryNode.Operator) { case "+": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplyAddition), BindingFlags.Public | BindingFlags.Static); break; case "-": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplySubtraction), BindingFlags.Public | BindingFlags.Static); break; case "*": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplyMultiplication), BindingFlags.Public | BindingFlags.Static); break; case "/": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplyDivision), BindingFlags.Public | BindingFlags.Static); break; case "%": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_ApplyModulo), BindingFlags.Public | BindingFlags.Static); break; case "==": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_AreEqual), BindingFlags.Public | BindingFlags.Static); break; case "!=": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_AreNotEqual), BindingFlags.Public | BindingFlags.Static); break; case "=~": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(EqualsIgnoreCase), BindingFlags.NonPublic | BindingFlags.Static); break; case ">": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_GreaterThan), BindingFlags.Public | BindingFlags.Static); break; case "<": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_LessThan), BindingFlags.Public | BindingFlags.Static); break; case ">=": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_GreaterThanOrEqual), BindingFlags.Public | BindingFlags.Static); break; case "<=": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_LessThanOrEqual), BindingFlags.Public | BindingFlags.Static); break; case "AND": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_LogicalAnd), BindingFlags.Public | BindingFlags.Static); break; case "OR": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_LogicalOr), BindingFlags.Public | BindingFlags.Static); break; case "XOR": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_LogicalXor), BindingFlags.Public | BindingFlags.Static); break; case "??": binaryMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_NullCoalesce), BindingFlags.Public | BindingFlags.Static); break; default: throw new ExpressionCompilationException( $"Unsupported binary operator: {binaryNode.Operator}"); } return SysExpression.Call(binaryMethod, leftExpr, rightExpr); case PostfixOperationNode postfixNode: // Get the property name for increment/decrement string postfixPropertyName = GetPropertyNameFromNode(postfixNode.Operand); if (string.IsNullOrEmpty(postfixPropertyName)) { throw new ExpressionCompilationException( $"Failed to get property name for postfix operation {postfixNode.Operator}"); } // Select the appropriate method for postfix increment/decrement MethodInfo postfixMethod = postfixNode.Operator == "++" ? typeof(ExpressionResolver).GetMethod( nameof(ApplyPostfixIncrement), BindingFlags.NonPublic | BindingFlags.Static) : typeof(ExpressionResolver).GetMethod( nameof(ApplyPostfixDecrement), BindingFlags.NonPublic | BindingFlags.Static); return SysExpression.Call( postfixMethod, exchangeParam, SysExpression.Constant(postfixPropertyName)); case Ast.BeanCallNode beanCall: { var site = new BeanCallSite(beanCall.Reference, beanCall.Method, beanCall.Arguments.Count); var values = beanCall.Arguments.Select(a => { var compiled = CompileAstNode(a, exchangeParam); return compiled.Type == typeof(object) ? compiled : SysExpression.Convert(compiled, typeof(object)); }); return SysExpression.Call( SysExpression.Constant(site), typeof(BeanCallSite).GetMethod(nameof(BeanCallSite.Invoke))!, exchangeParam, SysExpression.NewArrayInit(typeof(object), values)); } case Ast.MethodCallNode methodCall: { var targetExpr = CompileAstNode(methodCall.Target, exchangeParam); if (targetExpr.Type != typeof(object)) targetExpr = SysExpression.Convert(targetExpr, typeof(object)); var argumentExprs = methodCall.Arguments.Select(a => { var compiled = CompileAstNode(a, exchangeParam); return compiled.Type == typeof(object) ? compiled : SysExpression.Convert(compiled, typeof(object)); }); return SysExpression.Call( typeof(ExpressionResolver).GetMethod(nameof(Ast_CallMethod), BindingFlags.NonPublic | BindingFlags.Static)!, targetExpr, SysExpression.Constant(methodCall.Method), SysExpression.NewArrayInit(typeof(object), argumentExprs), SysExpression.Constant(methodCall.Written), SysExpression.Constant(methodCall.Position)); } case Ast.EnvNode envNode: return SysExpression.Call( typeof(ExpressionResolver).GetMethod(nameof(ReadEnvironment), BindingFlags.NonPublic | BindingFlags.Static)!, SysExpression.Constant(envNode.Name)); case Ast.RegistryRefNode registryRef: return SysExpression.Call( SysExpression.Constant(new RegistryRefSite(registryRef.Reference)), typeof(RegistryRefSite).GetMethod(nameof(RegistryRefSite.Get))!, exchangeParam); case FunctionCallNode functionNode: switch (functionNode.Name.ToLowerInvariant()) { case "concat": // Compile all arguments and call Ast_Concat var concatArgs = functionNode.Arguments .Select(arg => CompileAstNode(arg, exchangeParam)) .ToArray(); // Create an array of object? from the compiled arguments var arrayInit = SysExpression.NewArrayInit(typeof(object), concatArgs.Select(a => a.Type == typeof(object) ? a : SysExpression.Convert(a, typeof(object)))); var concatMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_Concat), BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(concatMethod, arrayInit); case "upper": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Upper)); case "lower": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Lower)); case "trim": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Trim)); case "length": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Length)); case "abs": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Abs)); case "substring": { var args = functionNode.Arguments.Select(a => CompileAstNode(a, exchangeParam)).ToArray(); var val = args.Length > 0 ? BoxToObject(args[0]) : SysExpression.Constant(null, typeof(object)); var start = args.Length > 1 ? BoxToObject(args[1]) : SysExpression.Constant(null, typeof(object)); var len = args.Length > 2 ? BoxToObject(args[2]) : SysExpression.Constant(null, typeof(object)); var m = typeof(ExpressionResolver).GetMethod(nameof(Ast_Substring), BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(m, val, start, len); } case "round": { var args = functionNode.Arguments.Select(a => CompileAstNode(a, exchangeParam)).ToArray(); var val = args.Length > 0 ? BoxToObject(args[0]) : SysExpression.Constant(null, typeof(object)); var digits = args.Length > 1 ? BoxToObject(args[1]) : SysExpression.Constant(null, typeof(object)); var m = typeof(ExpressionResolver).GetMethod(nameof(Ast_Round), BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(m, val, digits); } case "min": return CompileTwoArgFunction(functionNode, exchangeParam, nameof(Ast_Min)); case "max": return CompileTwoArgFunction(functionNode, exchangeParam, nameof(Ast_Max)); case "contains": return CompileTwoArgFunction(functionNode, exchangeParam, nameof(Ast_Contains)); case "startswith": return CompileTwoArgFunction(functionNode, exchangeParam, nameof(Ast_StartsWith)); case "endswith": return CompileTwoArgFunction(functionNode, exchangeParam, nameof(Ast_EndsWith)); case "replace": return CompileThreeArgFunction(functionNode, exchangeParam, nameof(Ast_Replace)); case "now": { var nowMethod = typeof(ExpressionResolver).GetMethod(nameof(Ast_Now), BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(nowMethod); } case "format": return CompileThreeArgFunction(functionNode, exchangeParam, nameof(Ast_Format)); case "uuid": { var uuidArgs = functionNode.Arguments.Select(a => CompileAstNode(a, exchangeParam)).ToArray(); var fmt = uuidArgs.Length > 0 ? BoxToObject(uuidArgs[0]) : SysExpression.Constant(null, typeof(object)); var m = typeof(ExpressionResolver).GetMethod(nameof(Ast_Uuid), BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(m, fmt); } case "datediff": return CompileThreeArgFunction(functionNode, exchangeParam, nameof(Ast_DateDiff)); case "dateformat": return CompileTwoArgFunction(functionNode, exchangeParam, nameof(Ast_DateFormat)); case "dateadd": return CompileThreeArgFunction(functionNode, exchangeParam, nameof(Ast_DateAdd)); case "sum": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Sum)); case "avg": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Avg)); case "count": return CompileSingleArgFunction(functionNode, exchangeParam, nameof(Ast_Count)); case "logical": return CompileSingleArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_Logical)); case "messagehistory": { // A literal kind is checked while the route is being built, as stats() checks its metric. if (functionNode.Arguments.Count > 0 && functionNode.Arguments[0] is LiteralNode { Value: string literalKind } && !IsKnownHistoryKind(literalKind)) { Ast_MessageHistory(literalKind, null!); // throws the ArgumentException with the known kinds } var historyArgs = functionNode.Arguments.Select(a => CompileAstNode(a, exchangeParam)).ToArray(); var historyKind = historyArgs.Length > 0 ? BoxToObject(historyArgs[0]) : SysExpression.Constant(null, typeof(object)); var historyMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_MessageHistory), BindingFlags.Public | BindingFlags.Static)!; return SysExpression.Call(historyMethod, historyKind, exchangeParam); } case "attachmentcontent": return CompileSingleArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_AttachmentContent)); case "attachmentcontentastext": return CompileSingleArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_AttachmentContentAsText)); case "attachmentcontenttype": return CompileSingleArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_AttachmentContentType)); case "attachmentheader": return CompileTwoArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_AttachmentHeader)); case "stats": // A literal metric name is checked while the route is being built — the // V4 rule: a condition that can never work fails at build, not on the // first message. A dynamic metric argument is checked at evaluation. if (functionNode.Arguments.Count > 1 && functionNode.Arguments[1] is LiteralNode { Value: string literalMetric } && !IsOtelTarget(functionNode.Arguments[0]) && !IsKnownStatistic(literalMetric)) { ReadStatistic(null!, literalMetric); // throws the ArgumentException with the known-names list } // The otel: branch has fields of its own, checked at build the same way. if (functionNode.Arguments.Count > 1 && functionNode.Arguments[1] is LiteralNode { Value: string literalField } && IsOtelTarget(functionNode.Arguments[0]) && !IsKnownOtelField(literalField)) { ReadOtelField(null, literalField); // throws the ArgumentException with the known fields } return CompileTwoArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_Stats)); // A second argument names what to read instead of the body. Dispatching on // arity to a separate method keeps "no source given" distinguishable from "the // source evaluated to null", which one nullable parameter could not express. case "jpath": return functionNode.Arguments.Count >= 2 ? CompileTwoArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_JPathFrom)) : CompileSingleArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_JPath)); case "xpath": return functionNode.Arguments.Count >= 2 ? CompileTwoArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_XPathFrom)) : CompileSingleArgFunctionWithExchange(functionNode, exchangeParam, nameof(Ast_XPath)); default: throw new NotImplementedException( $"Compilation of function '{functionNode.Name}' is not yet implemented."); } case TernaryNode ternaryNode: var conditionExpr = CompileAstNode(ternaryNode.Condition, exchangeParam); var ifTrueExpr = CompileAstNode(ternaryNode.IfTrue, exchangeParam); var ifFalseExpr = CompileAstNode(ternaryNode.IfFalse, exchangeParam); // Ensure condition is boxed to object? for Ast_ConvertToBool if (conditionExpr.Type != typeof(object)) conditionExpr = SysExpression.Convert(conditionExpr, typeof(object)); var toBoolMethod = typeof(ExpressionResolver).GetMethod( nameof(Ast_ConvertToBool), BindingFlags.Public | BindingFlags.Static); var conditionBool = SysExpression.Call(toBoolMethod, conditionExpr); // Ensure both branches return object? if (ifTrueExpr.Type != typeof(object)) ifTrueExpr = SysExpression.Convert(ifTrueExpr, typeof(object)); if (ifFalseExpr.Type != typeof(object)) ifFalseExpr = SysExpression.Convert(ifFalseExpr, typeof(object)); return SysExpression.Condition(conditionBool, ifTrueExpr, ifFalseExpr); case ListLiteralNode listNode: { var items = listNode.Items .Select(item => { var compiled = CompileAstNode(item, exchangeParam); return compiled.Type == typeof(object) ? compiled : SysExpression.Convert(compiled, typeof(object)); }) .ToArray(); return SysExpression.NewArrayInit(typeof(object), items); } case InOperationNode inNode: { var valueExpr = CompileAstNode(inNode.Value, exchangeParam); var listExpr = CompileAstNode(inNode.List, exchangeParam); if (valueExpr.Type != typeof(object)) valueExpr = SysExpression.Convert(valueExpr, typeof(object)); if (listExpr.Type != typeof(object)) listExpr = SysExpression.Convert(listExpr, typeof(object)); var inMethod = typeof(ExpressionResolver).GetMethod(nameof(Ast_In), BindingFlags.Public | BindingFlags.Static)!; return SysExpression.Convert( SysExpression.Call(inMethod, valueExpr, listExpr, SysExpression.Constant(inNode.Negated), SysExpression.Constant(inNode.ToString())), typeof(object)); } case Ast.RangeNode rangeNode: { var valueExpr = CompileAstNode(rangeNode.Value, exchangeParam); if (valueExpr.Type != typeof(object)) valueExpr = SysExpression.Convert(valueExpr, typeof(object)); var rangeMethod = typeof(ExpressionResolver).GetMethod(nameof(InRange), BindingFlags.NonPublic | BindingFlags.Static)!; return SysExpression.Convert( SysExpression.Call(rangeMethod, valueExpr, SysExpression.Constant(rangeNode.From), SysExpression.Constant(rangeNode.To), SysExpression.Constant(rangeNode.Negated), SysExpression.Constant(rangeNode.ToString())), typeof(object)); } default: throw new ExpressionCompilationException( $"Unsupported AST node type: {node.GetType().Name}"); } } /// /// value in list / value not in list, shared by the interpreted and the compiled /// path so the two can never disagree. Elements compare with — the /// equality == uses. A null list is empty (nothing is a member of it), a string is refused /// rather than split into characters, anything else that is not a collection is refused. /// /// The value tested for membership. /// The collection, or null. /// True for not in. /// The expression as written, for the error message. public static bool Ast_In(object? value, object? list, bool negated, string display) { bool found; switch (list) { case null: found = false; break; case string: throw new InvalidOperationException( $"'{display}': the right side of in is a string, and a string is not split into a list. " + "Reference a collection the message carries (header.codes) or write a list literal ('a','b')."); case System.Collections.IEnumerable items: found = false; foreach (var item in items) { if (Ast_AreEqual(value, item)) { found = true; break; } } break; default: throw new InvalidOperationException( $"'{display}': the right side of in is a {list.GetType().Name}, not a collection. " + "Reference a collection the message carries (header.codes) or write a list literal ('a','b')."); } return negated ? !found : found; } /// /// Extracts the property name from an AST node. /// /// The AST node to extract the property name from. /// The extracted property name, or an empty string if extraction fails. private static string GetPropertyNameFromNode(AstNode node) { DebugLog($"Extracting property name from node {node?.GetType().Name ?? "null"}"); switch (node) { case IdentifierNode identifierNode: return identifierNode.Name; case PropertyAccessNode propertyAccessNode: var objName = GetObjectNameFromNode(propertyAccessNode.Object); return string.IsNullOrEmpty(objName) ? propertyAccessNode.PropertyName : $"{objName}.{propertyAccessNode.PropertyName}"; default: return string.Empty; } } /// /// Gets the object name from an AST node. /// /// The AST node to extract the object name from. /// The extracted object name, or an empty string if extraction fails. private static string GetObjectNameFromNode(AstNode node) { if (node is IdentifierNode idNode) { return idNode.Name; } else if (node is PropertyAccessNode propNode) { var objName = GetObjectNameFromNode(propNode.Object); return string.IsNullOrEmpty(objName) ? propNode.PropertyName : $"{objName}.{propNode.PropertyName}"; } return string.Empty; } /// /// Boxes an expression to typeof(object) if needed. /// private static SysExpression BoxToObject(SysExpression expr) => expr.Type == typeof(object) ? expr : SysExpression.Convert(expr, typeof(object)); /// /// Compiles a single-argument function call (e.g. upper, lower, trim, length, abs). /// private static SysExpression CompileSingleArgFunction(FunctionCallNode node, ParameterExpression exchangeParam, string methodName) { var arg = node.Arguments.Count > 0 ? BoxToObject(CompileAstNode(node.Arguments[0], exchangeParam)) : SysExpression.Constant(null, typeof(object)); var method = typeof(ExpressionResolver).GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(method, arg); } /// /// Compiles a two-argument function call (e.g. min, max, contains, startsWith, endsWith). /// private static SysExpression CompileTwoArgFunction(FunctionCallNode node, ParameterExpression exchangeParam, string methodName) { var args = node.Arguments.Select(a => CompileAstNode(a, exchangeParam)).ToArray(); var a = args.Length > 0 ? BoxToObject(args[0]) : SysExpression.Constant(null, typeof(object)); var b = args.Length > 1 ? BoxToObject(args[1]) : SysExpression.Constant(null, typeof(object)); var method = typeof(ExpressionResolver).GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(method, a, b); } /// /// Compiles a three-argument function call (e.g. replace, dateAdd). /// private static SysExpression CompileThreeArgFunction(FunctionCallNode node, ParameterExpression exchangeParam, string methodName) { var args = node.Arguments.Select(a => CompileAstNode(a, exchangeParam)).ToArray(); var a = args.Length > 0 ? BoxToObject(args[0]) : SysExpression.Constant(null, typeof(object)); var b = args.Length > 1 ? BoxToObject(args[1]) : SysExpression.Constant(null, typeof(object)); var c = args.Length > 2 ? BoxToObject(args[2]) : SysExpression.Constant(null, typeof(object)); var method = typeof(ExpressionResolver).GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(method, a, b, c); } /// /// Compiles a single-argument function that also needs the exchange parameter. /// private static SysExpression CompileSingleArgFunctionWithExchange(FunctionCallNode node, ParameterExpression exchangeParam, string methodName) { var arg = node.Arguments.Count > 0 ? BoxToObject(CompileAstNode(node.Arguments[0], exchangeParam)) : SysExpression.Constant(null, typeof(object)); var method = typeof(ExpressionResolver).GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(method, arg, exchangeParam); } /// /// Compiles a two-argument function that also needs the exchange parameter. /// private static SysExpression CompileTwoArgFunctionWithExchange(FunctionCallNode node, ParameterExpression exchangeParam, string methodName) { var first = node.Arguments.Count > 0 ? BoxToObject(CompileAstNode(node.Arguments[0], exchangeParam)) : SysExpression.Constant(null, typeof(object)); var second = node.Arguments.Count > 1 ? BoxToObject(CompileAstNode(node.Arguments[1], exchangeParam)) : SysExpression.Constant(null, typeof(object)); var method = typeof(ExpressionResolver).GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); return SysExpression.Call(method, first, second, exchangeParam); } #endregion #region AST helper methods — increment/decrement operations /// /// Applies prefix increment (++x) via AST. /// /// The current value (unused; operation reads from exchange). /// The property name to increment. /// The exchange containing the property. /// The incremented value. internal static object? Ast_ApplyPrefixIncrement(object? value, string propertyName, IExchange exchange) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PrefixIncrement); /// /// Applies prefix decrement (--x) via AST. /// /// The current value (unused; operation reads from exchange). /// The property name to decrement. /// The exchange containing the property. /// The decremented value. internal static object? Ast_ApplyPrefixDecrement(object? value, string propertyName, IExchange exchange) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PrefixDecrement); /// /// Applies postfix increment (x++) via AST. /// /// The current value (unused; operation reads from exchange). /// The property name to increment. /// The exchange containing the property. /// The original value before incrementing. internal static object? Ast_ApplyPostfixIncrement(object? value, string propertyName, IExchange exchange) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PostfixIncrement); /// /// Applies postfix decrement (x--) via AST. /// /// The current value (unused; operation reads from exchange). /// The property name to decrement. /// The exchange containing the property. /// The original value before decrementing. internal static object? Ast_ApplyPostfixDecrement(object? value, string propertyName, IExchange exchange) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PostfixDecrement); #endregion } Path: redb-route/redb.Route/Expressions/ExpressionResolver.Attachments.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/Expressions/ExpressionResolver.Attachments.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver: the message attachments in the language, with the names of Camel Simple. /// attachments is the list of the In message (attachments.size, attachments[0].fileName); /// attachmentContent(name), attachmentContentAsText(name), attachmentContentType(name) and /// attachmentHeader(name, header) read the first attachment with that name, null when there is none. /// /// /// Expressions are evaluated synchronously, so the content functions read the whole content synchronously: they suit /// small parts (a text note, a short XML). Large files are for the attachment steps and the connectors. /// public static partial class ExpressionResolver { private const string AttachmentsRoot = "attachments"; /// Whether is the attachments root or a path under it. private static bool IsAttachmentsPath(string name) => name.StartsWith(AttachmentsRoot, StringComparison.Ordinal) && (name.Length == AttachmentsRoot.Length || name[AttachmentsRoot.Length] is '.' or '['); /// /// Resolves attachments and a path under it: .size / .count, an index [i], and the /// members of an attachment (name, fileName, contentType, contentId, length). /// private static object? ResolveAttachmentsPath(IExchange exchange, string name) { var attachments = exchange.In.Attachments; var rest = name[AttachmentsRoot.Length..]; if (rest.Length == 0) return attachments; if (rest is ".size" or ".count" or ".Size" or ".Count") return attachments.Count; return ResolvePropertyPath(attachments.ToArray(), rest.TrimStart('.')); } private static Attachment? FirstAttachment(object? name, IExchange exchange, string function) { var text = name?.ToString(); if (string.IsNullOrEmpty(text)) throw new InvalidOperationException($"{function}() needs the name of an attachment."); return exchange.In.Attachments.Find(text); } /// attachmentContent(name): the content of the first attachment with that name as bytes, or null. public static object? Ast_AttachmentContent(object? name, IExchange exchange) => FirstAttachment(name, exchange, "attachmentContent")?.Content.ReadAllBytes(); /// /// attachmentContentAsText(name): the content of the first attachment with that name as text, decoded with /// the charset of its content type (UTF-8 when it has none), or null. /// public static object? Ast_AttachmentContentAsText(object? name, IExchange exchange) { var attachment = FirstAttachment(name, exchange, "attachmentContentAsText"); return attachment is null ? null : CharsetOf(attachment.ContentType).GetString(attachment.Content.ReadAllBytes()); } /// attachmentContentType(name): the content type of the first attachment with that name, or null. public static object? Ast_AttachmentContentType(object? name, IExchange exchange) => FirstAttachment(name, exchange, "attachmentContentType")?.ContentType; /// /// attachmentHeader(name, header): a MIME header of the first attachment with that name (case-insensitive), /// or null. /// public static object? Ast_AttachmentHeader(object? name, object? header, IExchange exchange) { var headerName = header?.ToString(); if (string.IsNullOrEmpty(headerName)) throw new InvalidOperationException("attachmentHeader() needs the name of an attachment and the name of a header."); var attachment = FirstAttachment(name, exchange, "attachmentHeader"); return attachment is not null && attachment.Headers.TryGetValue(headerName, out var value) ? value : null; } private static Encoding CharsetOf(string contentType) { if (System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(contentType, out var parsed) && parsed.CharSet is { Length: > 0 } charset) { try { return Encoding.GetEncoding(charset.Trim('"')); } catch (ArgumentException ex) { throw new InvalidOperationException( $"attachmentContentAsText(): the attachment declares charset '{charset}', which this runtime does not know.", ex); } } return Encoding.UTF8; } } Path: redb-route/redb.Route/Expressions/ExpressionResolver.Compilation.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/Expressions/ExpressionResolver.Compilation.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using redb.Route.Abstractions; using SysExpression = System.Linq.Expressions.Expression; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver — Expression Tree compilation methods /// public static partial class ExpressionResolver { #region Resolver compilation /// /// Compiles a property resolver /// private static Func CompilePropertyResolver(string expression) { DebugLog($"Compiling property resolver: '{expression}'"); var objParam = SysExpression.Parameter(typeof(object), "obj"); var pathParam = SysExpression.Parameter(typeof(string), "path"); // For simplicity, use reflection in compiled code var resolveMethod = typeof(ExpressionResolver).GetMethod(nameof(ResolvePropertyPath), BindingFlags.NonPublic | BindingFlags.Static); var callExpression = SysExpression.Call(resolveMethod, objParam, pathParam); var lambda = SysExpression.Lambda>(callExpression, objParam, pathParam); DebugLog($"Property resolver compiled: '{expression}'"); return lambda.Compile(); } #endregion #region Property access compilation #endregion #region Value expression compilation /// /// Compiles an expression for value retrieval. Every expression is the AST's (findings register row 28); text that /// is not one is the text itself (row 29), and arithmetic that breaks off is an error. /// private static Func CompileValueExpression(string expression) { DebugLog($"Compiling value expression: '{expression}'"); { // Operators, calls and the other expression shapes: the AST, with nothing to decide about text. if (ContainsNamespacedCall(expression) || PostfixIncrementDecrementRegex.IsMatch(expression) || PrefixIncrementDecrementRegex.IsMatch(expression) || expression.Contains("??") || ContainsTernary(expression) || HasFunctionCalls(expression) || HasIndexAccess(expression) // Whitespace around an operator carries no meaning here either: an explicit // expression ("Expr(...)") is an expression whatever its spacing. Until // 2026-08-28 this was the last dialect that required single spaces. || ContainsComparisonOrWordLogicOperator(expression) // Modulo is new, so no legacy path ever learned it — route it to // the AST. Deliberately narrow (only '%', literals masked) so no existing form // changes its compilation path. || ContainsModuloOperator(expression) || expression.StartsWith("NOT ", StringComparison.OrdinalIgnoreCase) || expression.StartsWith("!", StringComparison.Ordinal) || expression.StartsWith("-", StringComparison.Ordinal) || expression.StartsWith("+", StringComparison.Ordinal)) { DebugLog($"Detected operators/functions, using AST parser"); return CompileExpressionWithAst(expression); } // Arithmetic that starts to parse and breaks off is an error, not text (findings register row 29). if (BrokenArithmetic(expression) is { } broken) throw new BrokenExpressionException($"{broken} within the expression \"{expression}\"."); // Text that is not an expression is the text itself (row 29), as the older compiler gave it. if (IsBareText(expression)) return _ => expression; // Every other value expression is the AST's (findings register row 28, step 28b). return CompileExpressionWithAst(expression); } } #endregion #region Operation compilation /// /// Compiles postfix increment/decrement (x++ or x--) /// private static SysExpression CompilePostfixIncrementDecrement(string op, string innerExpression, ParameterExpression exchangeParam) { DebugLog($"Compiling postfix {op} for '{innerExpression}'"); // Do not strip property, header, or body prefixes since they are now handled // in the Apply* methods string actualPropertyName = innerExpression; DebugLog($"Using full property name: '{actualPropertyName}'"); // Method for handling postfix increment/decrement var method = op == "++" ? typeof(ExpressionResolver).GetMethod(nameof(ApplyPostfixIncrement), BindingFlags.NonPublic | BindingFlags.Static) : typeof(ExpressionResolver).GetMethod(nameof(ApplyPostfixDecrement), BindingFlags.NonPublic | BindingFlags.Static); return SysExpression.Call(method, exchangeParam, SysExpression.Constant(actualPropertyName)); } #endregion #region Operator search helper methods /// /// Finds the index of the first comparison operator in the string /// private static int FindFirstOperator(string expression) { string[] operators = { "==", "!=", ">=", "<=", ">", "<", "&&", "||", " AND ", " OR ", " XOR " }; int minIndex = int.MaxValue; foreach (var op in operators) { int index = expression.IndexOf(op); if (index >= 0 && index < minIndex) { minIndex = index; } } return minIndex == int.MaxValue ? -1 : minIndex; } /// /// Checks for increment/decrement operations /// private static bool HasIncrementDecrementOps(string expression) => PostfixIncrementDecrementRegex.IsMatch(expression) || PrefixIncrementDecrementRegex.IsMatch(expression); /// /// Checks for standalone function calls (e.g. upper(...), concat(...)), /// but NOT method calls on properties (e.g. property.text.toLower()). /// private static readonly System.Text.RegularExpressions.Regex FunctionCallPattern = new(@"(? FunctionCallPattern.IsMatch(expression); /// /// Checks for index access /// private static bool HasIndexAccess(string expression) => expression.Contains("[") && expression.Contains("]"); /// /// Comparison and word-logic operators, looked for outside quoted literals. /// Whitespace between tokens carries no meaning, so detection must not depend on it: /// a>1, a > 1 and a tab- or newline-separated form are one expression. /// Word operators are matched the way the tokenizer matches them, case-insensitively. /// Arithmetic is deliberately absent: the value path already handles + - * / without /// requiring whitespace, and a bare literal must not be mistaken for a subtraction. /// // "in" / "not in" need whitespace before them and whitespace or "(" after: an operator stands // between operands, while "header.in" is a header called "in" and must keep its compilation path. // "range" / "not range" the same way, with whitespace on both sides: its right side is a quoted literal. private static readonly Regex ComparisonOrWordLogicRegex = new(@"==|!=|=~|>=|<=|>|<|\b(AND|OR|XOR)\b|(?<=\s)IN(?=[\s(])|(?<=\s)RANGE(?=\s)", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// /// Reports whether the expression contains a comparison or word-logic operator that is not /// part of a quoted literal. Used at the condition boundary to decide whether a string is a /// boolean expression, which has to be parsed, or a value to be read for truthiness. /// /// The expression to inspect. /// true when an operator is present outside every quoted literal. internal static bool ContainsComparisonOrWordLogicOperator(string expression) { ArgumentNullException.ThrowIfNull(expression); return ComparisonOrWordLogicRegex.IsMatch(MaskQuotedLiterals(expression)); } // A namespace written against its target, outside quotes: what the tokenizer reads as a Namespace token. // Built from the tokenizer's set, so the two cannot drift when a namespace is added. private static readonly Regex NamespacedCallRegex = new( @"(? /// Reports whether the expression holds a namespaced call (bean:svc.Check(...)) outside every quoted /// literal. Such an expression belongs to the AST, deterministically: no other path knows the namespace. /// internal static bool ContainsNamespacedCall(string expression) => expression.Contains(':', StringComparison.Ordinal) && NamespacedCallRegex.IsMatch(MaskQuotedLiterals(expression)); /// /// What the package gate says about one expression, computed as the engine compiles it (findings register row 32): /// an error with the engine's words when it does not compile (text after a complete expression included), or a /// warning when a bare expression starts as a value (header.b 3) but the bare-text rule (row 29) makes it the /// text itself, which in a condition is always true. Both null when the expression is fine. /// /// A bare expression, or the inner text of one ${...}. /// true for the inner text of a ${...}. /// true for a bare expression in a condition attribute. internal static (string? Error, string? Warning) GateCheck(string expression, bool placeholder, bool condition) { // {{key}} is configuration, resolved before the engine sees the text where it is resolved at all. if (string.IsNullOrWhiteSpace(expression) || expression.Contains("{{", StringComparison.Ordinal)) return (null, null); try { if (placeholder) CompilePlaceholder(expression); else if (condition) Predicates.PredicateFactory.FromString(expression); else GetCompiledValueExpression(expression); } catch (ExpressionCompilationException ex) { return (ex.Message, null); } return placeholder ? (null, null) : (null, BareTextAfterValue(expression)); } /// The gate's warning for a bare expression that starts with a root of the exchange and becomes text. private static string? BareTextAfterValue(string expression) { if (!IsBareText(expression)) return null; try { var tokens = new Ast.Tokenizer(expression).GetAllTokens(); if (tokens is not [{ Type: Ast.TokenType.Identifier } first, ..] || !IsValueWord(first.Value) || first.Value is "true" or "false" or "null") return null; new Ast.Parser(tokens).ParseReportingRest(out var rest); return rest is null ? null : $"\"{expression}\" reads as the text itself, not as an expression: '{rest.Value}' at position " + $"{rest.Position + 1} does not continue it; in a condition the text is always true."; } catch (Exception ex) when (ex is InvalidOperationException or FormatException or ArgumentException) { return null; } } // A scheme at the start (direct:x, kafka://t) or "://" anywhere: the text names endpoints. private static readonly Regex EndpointLikeRegex = new(@"^\s*[A-Za-z][A-Za-z0-9+.\-]*:|://", RegexOptions.Compiled); /// A bare text that starts as arithmetic and breaks off: a positioned error, never rendered as text. private sealed class BrokenExpressionException(string message) : ExpressionCompilationException(message); /// /// The value path's rule for bare text (findings register row 29). A text with no arithmetic operator outside quotes /// is what it was: a lookup, a literal, or the text itself (hello, plain text, key=value). A text /// with one is arithmetic, and it must be whole: it parses to its end, and each bare word in it is a value (a root /// such as header.a, property.x, body, exception.Message, a number or a quoted text). /// Otherwise the old compiler computed nonsense from the pieces (1 + gave 1, header.a+b gave /// 2b); now the problem is named with its position. null when the text is fine. /// internal static string? BrokenArithmetic(string expression) { if (!HasBinaryOperatorsInExpression(expression) || HasIncrementDecrementOps(expression)) return null; // An endpoint URI, or a list of them, is text where an expression names a destination // (): its slashes are not division. if (EndpointLikeRegex.IsMatch(expression)) return null; List tokens; try { tokens = new Ast.Tokenizer(expression).GetAllTokens(); } catch (InvalidOperationException ex) { return ex.Message; } if (!tokens.Any(t => t.Type == Ast.TokenType.Operator && t.Value is "+" or "-" or "*" or "/")) return null; // the detector saw an operator the language does not read as arithmetic try { new Ast.Parser(tokens).ParseReportingRest(out var rest); if (rest is not null) return $"unexpected '{rest.Value}' at position {rest.Position + 1}"; } catch (InvalidOperationException ex) { return tokens.LastOrDefault(t => t.Type != Ast.TokenType.Eof) is { } last && ex.Message.Contains("Eof", StringComparison.Ordinal) ? $"the expression ends after '{last.Value}' at position {last.Position + 1}, where a value is expected" : ex.Message; } // A name with a dash read as a subtraction: header.Content-Type is header.Content minus Type. for (var i = 0; i + 2 < tokens.Count; i++) { var (name, minus, next) = (tokens[i], tokens[i + 1], tokens[i + 2]); if (name.Type == Ast.TokenType.Identifier && minus is { Type: Ast.TokenType.Operator, Value: "-" } && next.Type == Ast.TokenType.Identifier && IsValueWord(name.Value) && name.Value.Contains('.') && name.Position + name.Value.Length == minus.Position && minus.Position + 1 == next.Position) { var end = i + 2; while (end + 2 < tokens.Count && tokens[end + 1] is { Type: Ast.TokenType.Operator, Value: "-" } && tokens[end + 2].Type == Ast.TokenType.Identifier && tokens[end].Position + tokens[end].Value.Length == tokens[end + 1].Position) end += 2; var whole = expression.Substring(name.Position, tokens[end].Position + tokens[end].Value.Length - name.Position); return $"'{whole}' at position {name.Position + 1} reads as a subtraction: a name with a dash is written ${{{whole}}}"; } } foreach (var token in tokens.Where(t => t.Type == Ast.TokenType.Identifier)) if (!IsValueWord(token.Value)) return $"'{token.Value}' at position {token.Position + 1} is not a value: write header.{token.Value}, " + $"property.{token.Value} or the text '{token.Value}' in quotes"; return null; } /// /// Text in a value position that is not an expression, kept as the text itself (findings register row 29, as in /// Apache Camel): it does not tokenize or parse (((((, 'unterminated, ${}), it parses only /// in part (plain text, key=value), or it is one bare word that names no root (hello). Called /// once arithmetic and the operators that route to the AST are ruled out. /// internal static bool IsBareText(string expression) { List tokens; try { tokens = new Ast.Tokenizer(expression).GetAllTokens(); } catch (InvalidOperationException) { return true; } Ast.AstNode root; try { root = new Ast.Parser(tokens).ParseReportingRest(out var rest); if (rest is not null) return true; } catch (InvalidOperationException) { return true; } return root is Ast.IdentifierNode identifier && !IsValueWord(identifier.Name); } /// /// The rule of a key that may be a constant (the cache key, after findings register row 29): text without /// ${...} that does not start with a root of the exchange (header.x, property.x, body, /// exception.x), a namespace (bean:, ref:, env:), a function call, a quoted literal, a /// parenthesis or a sign is the key as written: orders-all, k-out, b:c. Anything else is an /// expression and compiles as one, so header.customerId is evaluated and header.a+b stays the row 29 /// error. Not a relaxation of row 29 for expressions in general: only a key that names itself a template calls it. /// internal static bool IsConstantKey(string text) { if (string.IsNullOrWhiteSpace(text) || TemplateScanner.HasPlaceholder(text)) return false; List tokens; try { tokens = new Ast.Tokenizer(text).GetAllTokens(); } catch (InvalidOperationException) { return true; // not even tokens: no expression starts here } return tokens[0] switch { { Type: Ast.TokenType.Identifier } first => !IsRoot(first.Value), { Type: Ast.TokenType.Function or Ast.TokenType.Namespace or Ast.TokenType.String or Ast.TokenType.LeftParen } => false, { Type: Ast.TokenType.Operator, Value: "!" or "-" or "+" } => false, _ => true, }; // A dotted root (header.x, exception.Message) or a root word the language reads alone. static bool IsRoot(string word) => IsValueWord(word) && (word.Contains('.') || word is "body" or "contentType" or "exchange" or "attachments" || word.Equals("true", StringComparison.OrdinalIgnoreCase) || word.Equals("false", StringComparison.OrdinalIgnoreCase) || word.Equals("null", StringComparison.OrdinalIgnoreCase)); } /// A bare word arithmetic can read: a root of the exchange, or a keyword literal. private static bool IsValueWord(string word) { var root = word.Contains('.') ? word[..word.IndexOf('.')] : word; return root is "header" or "headers" or "property" or "properties" or "body" or "exception" or "in" or "out" or "contentType" or "attachments" or "exchange" || word.Equals("null", StringComparison.OrdinalIgnoreCase) || word.Equals("true", StringComparison.OrdinalIgnoreCase) || word.Equals("false", StringComparison.OrdinalIgnoreCase); } /// /// Reports whether the expression holds the namespace (bean, ref) written /// against its target outside every quoted literal: one namespace of . /// internal static bool ContainsNamespace(string expression, string ns) => expression.Contains(ns + ":", StringComparison.Ordinal) && Regex.IsMatch(MaskQuotedLiterals(expression), @"(? /// Reports whether the expression contains the modulo operator outside every quoted literal. /// Narrow on purpose: the value dialect routes '%' to the AST through this, /// and nothing else, so existing forms keep their compilation path. /// private static bool ContainsModuloOperator(string expression) => MaskQuotedLiterals(expression).Contains('%'); /// /// Replaces every quoted literal, quotes included, with a run of filler characters of the same /// length, so an operator inside a literal cannot be seen by a scan over the result. Literals /// are delimited the same way the tokenizer delimits them: a matching quote character, with a /// backslash escaping the next character, and an unterminated literal running to the end. /// private static string MaskQuotedLiterals(string expression) { if (expression.IndexOf('\'') < 0 && expression.IndexOf('"') < 0) return expression; const char filler = '#'; var masked = new StringBuilder(expression.Length); var position = 0; while (position < expression.Length) { var current = expression[position]; if (current is not ('\'' or '"')) { masked.Append(current); position++; continue; } var quote = current; masked.Append(filler); position++; while (position < expression.Length && expression[position] != quote) { if (expression[position] == '\\' && position + 1 < expression.Length) { masked.Append(filler); position++; } masked.Append(filler); position++; } if (position < expression.Length) { masked.Append(filler); position++; } } return masked.ToString(); } /// /// Checks for binary operators outside quoted strings /// private static bool HasBinaryOperatorsInExpression(string expression) { bool inQuotes = false; char quoteChar = '\0'; int bracketDepth = 0; for (int i = 0; i < expression.Length; i++) { char c = expression[i]; // Handle quotes if ((c == '\'' || c == '"') && (i == 0 || expression[i-1] != '\\')) { if (!inQuotes) { inQuotes = true; quoteChar = c; continue; } else if (c == quoteChar) { inQuotes = false; continue; } } // If not inside quotes, check for operators and parentheses else if (!inQuotes) { // Account for parentheses for nesting level tracking if (c == '(') { bracketDepth++; return true; // Presence of parentheses already indicates expression complexity } else if (c == ')') { bracketDepth--; return true; // Presence of parentheses already indicates expression complexity } // Check for null-coalescing operator else if (c == '?' && i + 1 < expression.Length && expression[i + 1] == '?') { return true; } // Check for ternary operator (single ? not followed by ?) else if (c == '?' && (i + 1 >= expression.Length || expression[i + 1] != '?')) { return true; } // Check for binary operators else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '%') { // For unary operations (e.g. +1 or -2), verify this is not a unary operator if (c == '+' || c == '-') { // If this is the first character or follows another operator, it is unary if (i == 0 || expression[i-1] == '+' || expression[i-1] == '-' || expression[i-1] == '*' || expression[i-1] == '/' || expression[i-1] == '%' || expression[i-1] == '(' || expression[i-1] == '[' || expression[i-1] == ',') { // This is a unary operator, continue continue; } // Check increment/decrement operations (++ and --) if (i < expression.Length - 1 && (c == '+' || c == '-') && expression[i+1] == c) { DebugLog($"HasOperations: Detected increment/decrement operation in '{expression}'"); return true; // This is an increment or decrement operation } } return true; // This is a binary operator } } } return false; } /// /// Checks whether the expression contains a ternary operator (single ? not part of ??). /// private static bool ContainsTernary(string expression) { for (int i = 0; i < expression.Length; i++) { if (expression[i] == '?') { // Skip ?? (null-coalescing) if (i + 1 < expression.Length && expression[i + 1] == '?') { i++; // skip second ? continue; } return true; } } return false; } #endregion } Path: redb-route/redb.Route/Expressions/ExpressionResolver.Converters.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/Expressions/ExpressionResolver.Converters.cs ---- using System; using System.Globalization; using System.Reflection; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver - type conversion and comparison methods /// public static partial class ExpressionResolver { #region Comparison methods /// /// Checks equality of two values considering their types /// private static bool AreEqual(object? left, object? right) { DebugLog($"Equality check: '{left}' (type: {left?.GetType().Name ?? "null"}) == '{right}' (type: {right?.GetType().Name ?? "null"})"); // Handling null values if (left == null && right == null) { DebugLog("Both values are null - equal"); return true; } if (left == null || right == null) { DebugLog($"One of the values is null: left={left ?? "null"}, right={right ?? "null"} - not equal"); return false; } // If both values are of the same type, use standard comparison if (left.GetType() == right.GetType()) { var result = left.Equals(right); DebugLog($"Direct comparison of same types: {left} == {right} = {result}"); return result; } // Numbers of different types, or a number and a numeric string: equal only when the values are equal if (TryNumbersEqual(left, right, out var numbersEqual)) { DebugLog($"Numeric equality comparison: {left} == {right} = {numbersEqual}"); return numbersEqual; } // Try boolean comparison — STRICT conversion only. Truthiness must not leak into // equality: under the total rule "x" and 42 are both truthy, which would make // 42 == 'x' true. Only explicit boolean words, bools and numbers take part here. if (TryConvertToBoolStrict(left, out var leftBool) && TryConvertToBoolStrict(right, out var rightBool)) { var result = leftBool == rightBool; DebugLog($"Converted boolean comparison: {leftBool} == {rightBool} = {result}"); return result; } // If neither numeric nor boolean comparison worked, compare as strings if (left is bool || right is bool) { var result = left.Equals(right); DebugLog($"Boolean comparison: {left} == {right} = {result}"); return result; } // String comparison var leftStr = left.ToString(); var rightStr = right.ToString(); var stringResult = string.Equals(leftStr, rightStr, StringComparison.OrdinalIgnoreCase); DebugLog($"String comparison: '{leftStr}' == '{rightStr}' = {stringResult}"); return stringResult; } /// /// Compares numeric values /// private static int CompareNumeric(object? left, object? right) { DebugLog($"Numeric comparison: '{left}' vs '{right}'"); if (TryConvertToNumber(left, out double leftNum) && TryConvertToNumber(right, out double rightNum)) { var result = leftNum.CompareTo(rightNum); DebugLog($"Numeric comparison: {leftNum} vs {rightNum} = {result}"); return result; } // If not numbers, compare as strings var leftStr = left?.ToString() ?? string.Empty; var rightStr = right?.ToString() ?? string.Empty; var stringResult = string.Compare(leftStr, rightStr, StringComparison.OrdinalIgnoreCase); DebugLog($"String comparison: '{leftStr}' vs '{rightStr}' = {stringResult}"); return stringResult; } #endregion #region Type conversion methods /// /// Converts a value to a boolean by the single DSL truthiness rule /// (). The conversion is total, so this always /// returns true; the Try-shape is kept because the word-logic operators and /// logical() call it, and their call sites predate the unification. /// public static bool TryConvertToBool(object? value, out bool result) { return _TryConvertToBool(value, out result); } // Method with _ prefix to break recursion private static bool _TryConvertToBool(object? value, out bool result) { result = Predicates.RouteTruthiness.ToBoolean(value); return true; } /// /// Strict partial boolean conversion for equality coercion: a bool is itself, an explicit /// boolean word parses, a number is non-zero. Anything else — an arbitrary string, an /// object — refuses to convert, so equality falls through to its string comparison instead /// of comparing truthiness. /// private static bool TryConvertToBoolStrict(object? value, out bool result) { switch (value) { case null: result = false; return true; case bool b: result = b; return true; case string s: return Predicates.RouteTruthiness.TryParseBooleanWord(s, out result); case sbyte or byte or short or ushort or int or uint or long or ulong: result = Convert.ToInt64(value) != 0; return true; case float f: result = f != 0f; return true; case double d: result = d != 0d; return true; case decimal m: result = m != 0m; return true; default: result = false; return false; } } /// /// Attempts to convert a value to a number /// private static bool TryConvertToNumber(object? value, out double result) { result = 0; if (value == null) return false; if (value is int intValue) { result = intValue; return true; } if (value is long longValue) { result = longValue; return true; } if (value is double doubleValue) { result = doubleValue; return true; } if (value is decimal decimalValue) { result = (double)decimalValue; return true; } if (value is float floatValue) { result = floatValue; return true; } if (value is string strValue && double.TryParse(strValue, NumberStyles.Any, CultureInfo.InvariantCulture, out double parsedValue)) { result = parsedValue; return true; } return false; } /// /// env:NAME, as Apache Camel's ${env:NAME}: the variable's value, null when it is not set. Read on /// every evaluation, so a changed variable is seen. Refused under the template sandbox: a template's data must not /// read the process environment. /// internal static object? ReadEnvironment(string name) { if (ExpressionSandbox.IsActive) throw new ExpressionSandboxViolationException("env:" + name); return Environment.GetEnvironmentVariable(name); } /// /// a =~ b, Apache Camel's equals-ignoring-case: two strings compare with /// ; any other pair compares exactly as ==. /// internal static bool EqualsIgnoreCase(object? left, object? right) => left is string l && right is string r ? string.Equals(l, r, StringComparison.OrdinalIgnoreCase) : AreEqual(left, right); /// /// value range 'from..to' / value not range 'from..to': inclusive at both ends. A null value is in no /// range; a value that is not a number is an error naming it, in the words an increment uses. /// internal static bool InRange(object? value, decimal from, decimal to, bool negated, string written) { if (value is null) return negated; decimal number; switch (value) { case double d when !double.IsNaN(d) && !double.IsInfinity(d) && Math.Abs(d) < (double)decimal.MaxValue: number = RouteDecimal.FromDouble(d); break; case float f when !float.IsNaN(f) && !float.IsInfinity(f) && Math.Abs(f) < (float)decimal.MaxValue: number = RouteDecimal.FromSingle(f); break; case not (bool or double or float) when TryConvertToDecimal(value, out var converted): number = converted; break; default: throw new InvalidOperationException( $"{written}: the value '{value}' ({value.GetType().Name}) is not a number."); } return (number >= from && number <= to) != negated; } /// /// Equality of two values of different types that are both numbers (or numeric strings). Without a /// double or float on either side both convert to decimal and compare exactly, so a /// long beyond double precision keeps its value; with one, both compare as double. /// private static bool TryNumbersEqual(object left, object right, out bool equal) { if (left is not (double or float) && right is not (double or float) && TryConvertToDecimal(left, out var leftDecimal) && TryConvertToDecimal(right, out var rightDecimal)) { equal = leftDecimal == rightDecimal; return true; } if (TryConvertToNumber(left, out var leftNumber) && TryConvertToNumber(right, out var rightNumber)) { equal = leftNumber == rightNumber; return true; } equal = false; return false; } /// The integral, decimal and numeric-string values of , as a decimal. private static bool TryConvertToDecimal(object value, out decimal result) { switch (value) { case int i: result = i; return true; case long l: result = l; return true; case decimal d: result = d; return true; case string s: return decimal.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out result); default: result = 0; return false; } } /// /// Attempts to convert a value to a double. Public wrapper for AST function implementations. /// public static bool TryConvertToDouble(object? value, out double result) => TryConvertToNumber(value, out result); /// /// Attempts to convert a value to int /// private static bool TryConvertToInt(object? value, out int result) { result = 0; if (value is int intValue) { result = intValue; return true; } if (value is double doubleValue && doubleValue == Math.Floor(doubleValue)) { result = (int)doubleValue; return true; } return int.TryParse(value?.ToString(), out result); } #endregion #region Literal parsing /// /// Parses a literal value /// public static object? ParseLiteral(string value) { if (string.IsNullOrEmpty(value)) return value; // Null literal if (string.Equals(value, "null", StringComparison.OrdinalIgnoreCase)) { DebugLog($"Null literal detected: '{value}'"); return null; } // String literals if ((value.StartsWith("'") && value.EndsWith("'")) || (value.StartsWith("\"") && value.EndsWith("\""))) { var stringLiteral = value.Substring(1, value.Length - 2); DebugLog($"String literal detected: '{value}' -> '{stringLiteral}'"); return stringLiteral; } // Numeric literals if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var intValue)) { DebugLog($"Integer literal detected: {intValue}"); return intValue; } if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var doubleValue)) { DebugLog($"Floating-point literal detected: {doubleValue}"); return doubleValue; } // Boolean literals if (bool.TryParse(value, out var boolValue)) { DebugLog($"Boolean literal detected: {boolValue}"); return boolValue; } DebugLog($"Value '{value}' returned as string"); return value; } #endregion } Path: redb-route/redb.Route/Expressions/ExpressionResolver.Members.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/Expressions/ExpressionResolver.Members.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace redb.Route.Expressions; public static partial class ExpressionResolver { private const BindingFlags MemberFlags = BindingFlags.Public | BindingFlags.Instance; /// /// The public instance property a path step names. The exact-case name wins; the case-insensitive match is used /// only when it is the one name that fits. body.Id on a type with both Id and id (a redb /// object) reads Id; body.ID there is ambiguous and fails naming both. /// private static PropertyInfo? FindProperty(Type type, string name) => Pick(type, name, type.GetProperties(MemberFlags).Where(p => p.GetIndexParameters().Length == 0), "property"); /// The public instance field a path step names, by the rule of . private static FieldInfo? FindField(Type type, string name) => Pick(type, name, type.GetFields(MemberFlags), "field"); private static T? Pick(Type type, string name, IEnumerable members, string kind) where T : MemberInfo { var matches = members.Where(m => string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)).ToList(); if (matches.Count == 0) return null; var exact = matches.Where(m => m.Name == name).ToList(); if (exact.Count > 0) return MostDerived(exact); var names = matches.Select(m => m.Name).Distinct(StringComparer.Ordinal).ToList(); if (names.Count == 1) return MostDerived(matches); throw new ExpressionEvaluationException( $"'{name}' matches more than one {kind} of {type.FullName} when case is ignored: {string.Join(", ", names)}. " + "Write the member name in its exact case."); } /// A member a derived type redeclares (new) is listed once per declaring type: the derived one wins. private static T MostDerived(List members) where T : MemberInfo => members.Count == 1 ? members[0] : members.First(m => members.All(o => o == m || m.DeclaringType!.IsSubclassOf(o.DeclaringType!))); } Path: redb-route/redb.Route/Expressions/ExpressionResolver.MethodCalls.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/Expressions/ExpressionResolver.MethodCalls.cs ---- using System.Reflection; using redb.Route.Core; namespace redb.Route.Expressions; public static partial class ExpressionResolver { /// /// value.method(args) in the AST (findings register row 28): a built-in dot helper of the language /// (length / count / size, contains, substring, trim, toUpper, /// toLower, replace, startsWith, endsWith, indexOf), else a public method of the /// value's type with that many arguments, refused under the template sandbox. A null value gives null, /// as reading a member of one does. A method that throws, or one the type does not have, is an error naming the call /// and its position: nothing reads as null silently. /// internal static object? Ast_CallMethod(object? target, string method, object?[] arguments, string written, int position) { if (target is null) return null; var parameters = arguments.Select(a => a!).ToArray(); try { switch (method.ToLowerInvariant()) { case "length" or "count" or "size": return ResolveLength(target); case "contains": return ResolveContains(target, parameters); case "substring": return ResolveSubstring(target, parameters); case "trim": return ResolveTrim(target, parameters); case "toupper": return ResolveToUpper(target, parameters); case "tolower": return ResolveToLower(target, parameters); case "replace": return ResolveReplace(target, parameters); case "startswith": return ResolveStartsWith(target, parameters); case "endswith": return ResolveEndsWith(target, parameters); case "indexof": return ResolveIndexOf(target, parameters); } } catch (Exception ex) when (ex is not (ExpressionSandboxViolationException or ExpressionEvaluationException)) { throw Threw(written, position, ex); } // Anything beyond the helpers runs code of the value's type: refused where an expression may only read members. if (ExpressionSandbox.IsActive) throw new ExpressionSandboxViolationException(method, target.GetType()); var type = target.GetType(); var candidates = type.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => string.Equals(m.Name, method, StringComparison.OrdinalIgnoreCase)) .ToList(); if (candidates.Count == 0) throw new ExpressionEvaluationException( $"'{method}' is not a method of {type.Name} at position {position + 1} (in {written})."); var chosen = candidates.FirstOrDefault(m => m.GetParameters().Length == arguments.Length) ?? throw new ExpressionEvaluationException( $"'{method}' of {type.Name} takes {string.Join(" or ", candidates.Select(m => m.GetParameters().Length).Distinct().Order())} " + $"argument(s), not {arguments.Length}, at position {position + 1} (in {written})."); try { return chosen.Invoke(target, ConvertArguments(chosen, arguments)); } catch (TargetInvocationException ex) when (ex.InnerException is { } inner) { throw Threw(written, position, inner); } catch (ArgumentException ex) { throw Threw(written, position, ex); } } private static ExpressionEvaluationException Threw(string written, int position, Exception ex) => new($"{written} at position {position + 1} threw {ex.GetType().Name}: {ex.Message}", ex); /// The arguments converted to the method's parameter types where they differ (an int literal for a long). private static object?[] ConvertArguments(MethodInfo method, object?[] arguments) { var parameters = method.GetParameters(); var converted = new object?[arguments.Length]; for (var i = 0; i < arguments.Length; i++) { var target = Nullable.GetUnderlyingType(parameters[i].ParameterType) ?? parameters[i].ParameterType; converted[i] = arguments[i] is { } value && !target.IsInstanceOfType(value) && value is IConvertible && typeof(IConvertible).IsAssignableFrom(target) ? RouteDecimal.ChangeType(value, target, System.Globalization.CultureInfo.InvariantCulture) : arguments[i]; } return converted; } } Path: redb-route/redb.Route/Expressions/ExpressionResolver.Operations.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/Expressions/ExpressionResolver.Operations.cs ---- using System; using System.Linq; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver - operations (unary, binary, increment/decrement, JSONPath) /// public static partial class ExpressionResolver { /// Parsed jpath expressions by path text: the path is constant per call site, the body is parsed per evaluation. private static readonly System.Collections.Concurrent.ConcurrentDictionary JsonPathExpressions = new(StringComparer.Ordinal); #region Types and helper methods for working with properties /// /// Property location type /// private enum PropertyLocation { Property, // exchange.Properties Header, // exchange.In.Headers Body, // exchange.In.body Direct // direct access to exchange.Properties (without prefix) } /// /// Increment/decrement operation type /// private enum OperationType { PrefixIncrement, // ++x - returns the new value PrefixDecrement, // --x - returns the new value PostfixIncrement, // x++ - returns the old value PostfixDecrement // x-- - returns the old value } /// /// Determines the type and actual name of the property /// private static (PropertyLocation location, string actualName) ParsePropertyLocation(string propertyName) { if (propertyName.StartsWith(PROPERTY_PREFIX)) return (PropertyLocation.Property, propertyName.Substring(PROPERTY_PREFIX.Length)); if (propertyName.StartsWith(HEADER_PREFIX)) return (PropertyLocation.Header, propertyName.Substring(HEADER_PREFIX.Length)); if (propertyName.StartsWith(BODY_PREFIX) || propertyName == "body") return (PropertyLocation.Body, propertyName); return (PropertyLocation.Direct, propertyName); } /// /// Gets the property value from exchange depending on its location /// private static object? GetPropertyValue(IExchange exchange, PropertyLocation location, string name) { return location switch { PropertyLocation.Property => exchange.getProperty(name), PropertyLocation.Header => exchange.In.getHeader(name), PropertyLocation.Body => exchange.In.getBody(), PropertyLocation.Direct => exchange.getProperty(name), _ => null }; } /// /// Sets the property value in exchange depending on its location /// private static void SetPropertyValue(IExchange exchange, PropertyLocation location, string name, object? value) { switch (location) { case PropertyLocation.Property: exchange.setProperty(name, value); break; case PropertyLocation.Header: exchange.In.setHeader(name, value); break; case PropertyLocation.Direct: exchange.setProperty(name, value); break; // Body does not support setting values } } /// /// Unified method for increment and decrement operations /// private static object? ApplyIncrementDecrementOperation( IExchange exchange, string propertyName, OperationType operation) { DebugLog($"Applying operation {operation} to property: '{propertyName}'"); // Determine the type and name of the property var (location, actualName) = ParsePropertyLocation(propertyName); // Body does not support increment/decrement if (location == PropertyLocation.Body) { DebugLog($"Body prefix detected. Increment/decrement operations are not supported for message body."); return exchange.In.getBody(); } // Get the current value var currentValue = GetPropertyValue(exchange, location, actualName); // If value is null, initialize with zero if (currentValue == null) { DebugLog($"Property '{actualName}' not found, initializing with value 0"); currentValue = 0; } // Convert to number if (!TryConvertToNumber(currentValue, out double numValue)) { DebugLog($"Value '{currentValue}' is not a number, attempting conversion"); if (int.TryParse(currentValue?.ToString(), out int parsedInt)) numValue = parsedInt; else { // A missing value starts at 0 (a counter); a value that is there but not a number used to become 0 // silently and be overwritten (findings register row 23). var symbol = operation is OperationType.PrefixIncrement or OperationType.PostfixIncrement ? "++" : "--"; var written = operation is OperationType.PrefixIncrement or OperationType.PrefixDecrement ? symbol + propertyName : propertyName + symbol; throw new InvalidOperationException( $"{written}: the value '{currentValue}' ({currentValue?.GetType().Name}) is not a number."); } } // Determine the new value and return value depending on the operation var (newValue, returnValue) = operation switch { OperationType.PrefixIncrement => (numValue + 1, numValue + 1), OperationType.PrefixDecrement => (numValue - 1, numValue - 1), OperationType.PostfixIncrement => (numValue + 1, numValue), OperationType.PostfixDecrement => (numValue - 1, numValue), _ => (numValue, numValue) }; DebugLog($"Operation {operation}: current={numValue}, new={newValue}, returning={returnValue}"); // Convert to int if possible var valueToSet = newValue == Math.Floor(newValue) ? (object)(int)newValue : newValue; var valueToReturn = returnValue == Math.Floor(returnValue) ? (object)(int)returnValue : returnValue; // Update the value in exchange SetPropertyValue(exchange, location, actualName, valueToSet); // Verify the update for debugging if (_debugEnabled) { var updatedValue = GetPropertyValue(exchange, location, actualName); DebugLog($"Update verification: new value in {location}: {updatedValue}"); } // Return the corresponding value (old for postfix, new for prefix) return valueToReturn; } #endregion #region Unary operations /// /// Applies unary logical negation to a value /// private static object? ApplyUnaryNot(object? value) { DebugLog($"Applying unary logical negation to: {value}"); if (value == null) return true; // null is treated as false, negation is true // Try to convert to bool if (TryConvertToBool(value, out bool boolValue)) { DebugLog($"Value converted to bool: {boolValue}, negation: {!boolValue}"); return !boolValue; } // If conversion to bool failed, return the original value DebugLog($"Failed to convert to bool, returning original value"); return value; } /// /// Applies unary plus to numbers or performs concatenation for strings and collections /// private static object? ApplyUnaryPlus(object? value) { DebugLog($"Applying unary plus to: {value}"); if (value == null) return null; // For numeric types - return the number itself if (TryConvertToNumber(value, out double num)) { return num; } // For strings - return the string as-is if (value is string str) { return str; } // For collections - return the collection as-is if (value is System.Collections.IEnumerable) { return value; } // By default return the value as-is return value; } /// /// Applies unary minus to numbers /// private static object? ApplyUnaryMinus(object? value) { DebugLog($"Applying unary minus to: {value}"); if (value == null) return null; // For numeric types - negate the sign if (TryConvertToNumber(value, out double num)) { return -num; } // For other types return as-is return value; } #endregion #region Prefix increment/decrement operations /// /// Applies prefix increment (++x) for numeric values and updates the value in exchange /// private static object? ApplyPrefixIncrement(IExchange exchange, string propertyName) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PrefixIncrement); /// /// Applies prefix decrement (--x) for numeric values and updates the value in exchange /// private static object? ApplyPrefixDecrement(IExchange exchange, string propertyName) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PrefixDecrement); #endregion #region Postfix increment/decrement operations /// /// Applies postfix increment (x++) for numeric values and updates the value in exchange /// private static object? ApplyPostfixIncrement(IExchange exchange, string propertyName) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PostfixIncrement); /// /// Applies postfix decrement (x--) for numeric values and updates the value in exchange /// private static object? ApplyPostfixDecrement(IExchange exchange, string propertyName) => ApplyIncrementDecrementOperation(exchange, propertyName, OperationType.PostfixDecrement); #endregion #region Binary operations /// /// Applies the addition operation for different data types /// private static object? ApplyAddition(object? left, object? right) { DebugLog($"Applying addition operation: '{left}' + '{right}'"); if (left == null || right == null) { DebugLog("One of the operands is null"); return left ?? right; // Return the non-null operand, or null if both are null } // If both operands are numeric, perform arithmetic addition if (TryConvertToNumber(left, out double leftNum) && TryConvertToNumber(right, out double rightNum)) { var result = leftNum + rightNum; DebugLog($"Numeric addition: {leftNum} + {rightNum} = {result}"); // Return an integer if the result is whole if (result == Math.Floor(result)) { return (int)result; } return result; } // For strings and other types, perform concatenation var leftStr = left.ToString() ?? string.Empty; var rightStr = right.ToString() ?? string.Empty; var strResult = leftStr + rightStr; DebugLog($"String concatenation: '{leftStr}' + '{rightStr}' = '{strResult}'"); return strResult; } /// /// Applies the subtraction operation for numeric types /// private static object? ApplySubtraction(object? left, object? right) { DebugLog($"Applying subtraction operation: '{left}' - '{right}'"); if (left == null || right == null) { DebugLog("One of the operands is null"); return left; // For subtraction, return the left operand if one of them is null } // Perform subtraction only for numeric types if (TryConvertToNumber(left, out double leftNum) && TryConvertToNumber(right, out double rightNum)) { var result = leftNum - rightNum; DebugLog($"Numeric subtraction: {leftNum} - {rightNum} = {result}"); // Return an integer if the result is whole if (result == Math.Floor(result)) { return (int)result; } return result; } DebugLog("Operands are not numbers, subtraction is not possible"); return left; // For non-numeric types, return the left operand } /// /// Applies the multiplication operation for numeric types /// private static object? ApplyMultiplication(object? left, object? right) { DebugLog($"Applying multiplication operation: '{left}' * '{right}'"); if (left == null || right == null) { DebugLog("One of the operands is null"); return null; // For multiplication, return null if one of the operands is null } // Perform multiplication only for numeric types if (TryConvertToNumber(left, out double leftNum) && TryConvertToNumber(right, out double rightNum)) { var result = leftNum * rightNum; DebugLog($"Numeric multiplication: {leftNum} * {rightNum} = {result}"); // Return an integer if the result is whole if (result == Math.Floor(result)) { return (int)result; } return result; } // Support for string multiplication by number (repetition) if (left is string str && TryConvertToNumber(right, out double rightNumber) && rightNumber >= 0 && rightNumber == Math.Floor(rightNumber)) { var count = (int)rightNumber; var result = string.Concat(Enumerable.Repeat(str, count)); DebugLog($"String multiplication: '{str}' * {count} = '{result}'"); return result; } // Support for number multiplication by string (repetition) if (right is string str2 && TryConvertToNumber(left, out double leftNumber) && leftNumber >= 0 && leftNumber == Math.Floor(leftNumber)) { var count = (int)leftNumber; var result = string.Concat(Enumerable.Repeat(str2, count)); DebugLog($"String multiplication: '{str2}' * {count} = '{result}'"); return result; } DebugLog("Operands do not support multiplication"); return null; } /// /// Applies the division operation for numeric types /// private static object? ApplyDivision(object? left, object? right) { DebugLog($"Applying division operation: {left} / {right}"); if (left == null || right == null) { DebugLog("One of the operands is null, returning null"); return null; } // Convert both values to numbers if (TryConvertToNumber(left, out double leftNumber) && TryConvertToNumber(right, out double rightNumber)) { if (Math.Abs(rightNumber) < double.Epsilon) { DebugLog("Division by zero, returning null"); return null; } var result = leftNumber / rightNumber; DebugLog($"Division result: {result}"); // Check if we can return an integer result if (Math.Abs(result - Math.Floor(result)) < double.Epsilon) { return Convert.ToInt32(result); } return result; } DebugLog("Cannot perform division for non-numeric types"); return null; } #endregion #region JSONPath operations /// /// Applies JSONPath to the message body. /// Returns null when the path selects nothing; propagates real errors. /// private static object? ApplyJPath(IExchange exchange, string jsonPath) { DebugLog($"Applying JSONPath: '{jsonPath}'"); var body = exchange.In.getBody(); DebugLog($"Message body type: {(body != null ? body.GetType().Name : "null")}"); if (body == null) return null; // The path is constant per call site: parse it once and keep the expression (it holds only the // parsed path and options; the body is parsed per evaluation). var jsonPathExpression = JsonPathExpressions.GetOrAdd(jsonPath, static path => new JsonPathExpression(path)); // JsonPathExpression owns the conversion rules: scalars unwrap, homogeneous arrays become typed // CLR arrays, objects stay JsonObject, filter results come back as arrays (a single scalar unwraps). var result = jsonPathExpression.Evaluate(exchange); DebugLog($"JSONPath result: {result}"); return result; } #endregion #region XPath operations /// /// Applies XPath to the message body. /// Returns null when the body is null; propagates real errors. /// private static object? ApplyXPath(IExchange exchange, string xpath) { DebugLog($"Applying XPath: '{xpath}'"); var body = exchange.In.getBody(); DebugLog($"Message body type: {(body != null ? body.GetType().Name : "null")}"); if (body == null) return null; var xpathExpression = new XPathExpression(xpath); var result = xpathExpression.Evaluate(exchange); DebugLog($"XPath result: {result}"); return result; } #endregion } Path: redb-route/redb.Route/Expressions/ExpressionResolver.PrefixResolvers.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/Expressions/ExpressionResolver.PrefixResolvers.cs ---- using System; using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver — pluggable prefix resolvers for /// extending the expression DSL with domain-specific roots /// (e.g. ${conversation.*}, ${tool.*}) without coupling /// the core resolver to those domains. /// public static partial class ExpressionResolver { private static readonly ConcurrentDictionary> _prefixResolvers = new(StringComparer.OrdinalIgnoreCase); /// /// Registers a resolver for a custom property prefix. The /// must end with a dot (e.g. "conversation."); the resolver receives the /// current exchange and the remainder of the property path after the prefix /// (e.g. "id" for ${conversation.id}). /// /// If multiple registrations target the same prefix, the latest one wins. /// /// public static void RegisterPrefixResolver(string prefix, Func resolver) { ArgumentException.ThrowIfNullOrWhiteSpace(prefix); ArgumentNullException.ThrowIfNull(resolver); if (!prefix.EndsWith('.')) throw new ArgumentException("Prefix must end with a dot, e.g. \"conversation.\"", nameof(prefix)); _prefixResolvers[prefix] = resolver; } /// /// Removes a previously registered prefix resolver. Returns true /// if a resolver was removed. /// public static bool UnregisterPrefixResolver(string prefix) { if (string.IsNullOrWhiteSpace(prefix)) return false; return _prefixResolvers.TryRemove(prefix, out _); } /// /// Resolves the value of a property path against the registered prefix /// resolvers. Returns (handled: true, value) if a resolver matched /// the prefix; otherwise (handled: false, null). /// internal static (bool Handled, object? Value) TryResolveByPrefix(IExchange exchange, string propertyName) { if (string.IsNullOrEmpty(propertyName)) return (false, null); // The exchange's own context first: a prefix a module registered there goes with the context. if (exchange.Context?.GetService() is { } contextResolvers && contextResolvers.TryResolve(exchange, propertyName, out var contextValue)) return (true, contextValue); if (_prefixResolvers.IsEmpty) return (false, null); foreach (var (prefix, resolver) in _prefixResolvers) { if (!propertyName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; var remainder = propertyName.Substring(prefix.Length); DebugLog($"Prefix resolver '{prefix}' matched, remainder='{remainder}'"); return (true, resolver(exchange, remainder)); } return (false, null); } } /// /// The prefix resolvers of one route context: ${prefix.rest} roots that the context's own code (a module /// loaded for it) contributes. They live as a service of the context, so they go when the context is disposed and /// keep no delegate of an unloaded module alive; an expression evaluated on an exchange of the context consults /// them before the process-wide ones of . Register through /// context.RegisterPrefixResolver(prefix, resolver). /// public sealed class ExpressionPrefixResolvers { private static readonly object CreateGate = new(); private readonly ConcurrentDictionary> _resolvers = new(StringComparer.OrdinalIgnoreCase); /// The resolvers of , created on first use. public static ExpressionPrefixResolvers For(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); if (context.GetService() is { } existing) return existing; lock (CreateGate) { if (context.GetService() is { } raced) return raced; var created = new ExpressionPrefixResolvers(); context.AddService(typeof(ExpressionPrefixResolvers), created); return created; } } /// /// Registers for (ending with a dot, e.g. "order."); /// a second registration of the prefix replaces the first. /// public void Register(string prefix, Func resolver) { ArgumentException.ThrowIfNullOrWhiteSpace(prefix); ArgumentNullException.ThrowIfNull(resolver); if (!prefix.EndsWith('.')) throw new ArgumentException("Prefix must end with a dot, e.g. \"order.\"", nameof(prefix)); _resolvers[prefix] = resolver; } /// Removes the resolver of ; true when there was one. public bool Unregister(string prefix) => !string.IsNullOrWhiteSpace(prefix) && _resolvers.TryRemove(prefix, out _); internal bool TryResolve(IExchange exchange, string propertyName, out object? value) { value = null; if (_resolvers.IsEmpty) return false; foreach (var (prefix, resolver) in _resolvers) { if (!propertyName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; value = resolver(exchange, propertyName[prefix.Length..]); return true; } return false; } } Path: redb-route/redb.Route/Expressions/ExpressionResolver.RuntimeResolvers.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/Expressions/ExpressionResolver.RuntimeResolvers.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver - runtime property and method resolution methods /// public static partial class ExpressionResolver { #region Getting properties from Exchange /// /// Gets a property value from exchange /// private static object? GetExchangeProperty(IExchange exchange, string propertyName) { DebugLog($"Getting exchange property: '{propertyName}'"); if (propertyName.StartsWith("exception.")) { var exceptionPropertyName = propertyName.Substring(EXCEPTION_PREFIX.Length); // remove "exception." DebugLog($"Getting exception property: '{exceptionPropertyName}'"); if (exchange.Exception == null) { DebugLog("Exchange.Exception is null"); return null; } return ResolvePropertyPath(exchange.Exception, exceptionPropertyName); } else if (propertyName.Equals("exception")) { DebugLog("Getting full exception object"); return exchange.Exception; } else if (propertyName.StartsWith("property.")) { // Smart resolution: literal name first (dots included), then a nested member path. // This is the same rule the value path has always used; without it the AST branch // answered null for "property.cfg.limit" while the value branch answered 5. var actualPropertyName = propertyName.Substring(PROPERTY_PREFIX.Length); DebugLog($"Getting property: '{actualPropertyName}'"); return actualPropertyName.Contains('.') ? ResolvePropertySmart(exchange, actualPropertyName) : exchange.getProperty(actualPropertyName); } else if (propertyName.StartsWith("header.")) { // Same smart rule for headers: "header.user.Age" is the Age member of the "user" // header unless a header literally named "user.Age" exists. var headerName = propertyName.Substring(HEADER_PREFIX.Length); DebugLog($"Getting header: '{headerName}'"); return headerName.Contains('.') ? ResolveHeaderSmart(exchange, headerName) : exchange.In.getHeader(headerName); } else if (propertyName.StartsWith("body.")) { var bodyPath = propertyName.Substring(BODY_PREFIX.Length); DebugLog($"Getting body path: '{bodyPath}'"); return ResolvePropertyPath(exchange.In.getBody(), bodyPath); } else if (propertyName == "body") { DebugLog($"Getting body"); return exchange.In.getBody(); } else if (propertyName == "contentType") { // The removed hand-written branch resolved contentType; the unified engine has to // keep every accessor the language documents. DebugLog("Getting contentType"); return exchange.In.ContentType; } else if (IsAttachmentsPath(propertyName)) { // The attachments of the In message, as Camel Simple's ${attachments}: before the exchange-property // fallback, so a property named "attachments" no longer answers here. DebugLog($"Getting attachments: '{propertyName}'"); return ResolveAttachmentsPath(exchange, propertyName); } else { // Pluggable prefix resolvers (e.g. conversation., tool.) take precedence // over the default property fallback so that custom roots aren't masked // by a coincidentally-matching exchange property. var (handled, value) = TryResolveByPrefix(exchange, propertyName); if (handled) { DebugLog($"Resolved via prefix resolver: '{propertyName}' -> {value}"); return value; } DebugLog($"Getting default property: '{propertyName}'"); return exchange.getProperty(propertyName); } } /// /// Smart property resolution with support for dots in names /// Priority: literal name → nested path /// private static object? ResolvePropertySmart(IExchange exchange, string fullPath) { DebugLog($"Smart property resolution: '{fullPath}'"); // 1. FIRST: check literal name (with dots) if (exchange.Properties.ContainsKey(fullPath)) { DebugLog($"Found property with literal name: '{fullPath}'"); return exchange.getProperty(fullPath); } // 2. THEN: if no literal name and there's a dot - try nested path if (fullPath.Contains('.')) { var firstDot = fullPath.IndexOf('.'); var rootPropertyName = fullPath.Substring(0, firstDot); var remainingPath = fullPath.Substring(firstDot + 1); DebugLog($"Trying nested path: property='{rootPropertyName}', path='{remainingPath}'"); if (exchange.Properties.ContainsKey(rootPropertyName)) { var propertyValue = exchange.getProperty(rootPropertyName); if (propertyValue != null) { return ResolvePropertyPath(propertyValue, remainingPath); } } } DebugLog($"Property not found: '{fullPath}'"); return null; } /// /// Smart header resolution with support for dots in names /// Priority: literal name → nested path /// private static object? ResolveHeaderSmart(IExchange exchange, string fullPath) { DebugLog($"Smart header resolution: '{fullPath}'"); // 1. FIRST: check literal name (with dots) if (exchange.In.Headers.ContainsKey(fullPath)) { DebugLog($"Found header with literal name: '{fullPath}'"); return exchange.In.getHeader(fullPath); } // 2. THEN: if no literal name and there's a dot - try nested path if (fullPath.Contains('.')) { var firstDot = fullPath.IndexOf('.'); var rootHeaderName = fullPath.Substring(0, firstDot); var remainingPath = fullPath.Substring(firstDot + 1); DebugLog($"Trying nested path: header='{rootHeaderName}', path='{remainingPath}'"); if (exchange.In.Headers.ContainsKey(rootHeaderName)) { var headerValue = exchange.In.getHeader(rootHeaderName); if (headerValue != null) { return ResolvePropertyPath(headerValue, remainingPath); } } } DebugLog($"Header not found: '{fullPath}'"); _logger?.LogDebug("Expression: header '{HeaderName}' not found, resolving to empty", fullPath); return null; } /// /// Gets a property value from body via runtime reflection /// private static object? ResolveBodyProperty(IExchange exchange, string propertyPath) { DebugLog($"ResolveBodyProperty: getting '{propertyPath}' from body via runtime reflection"); try { // Get body as object var body = exchange.In.getBody(); if (body == null) { DebugLog("ResolveBodyProperty: body is null"); return null; } DebugLog($"ResolveBodyProperty: body type = {body.GetType().Name}"); // Use ResolvePropertyPath for runtime property access var result = ResolvePropertyPath(body, propertyPath); DebugLog($"ResolveBodyProperty: result = {result}"); return result; } catch (Exception ex) when (ex is not ExpressionSandboxViolationException) { DebugLog($"ResolveBodyProperty: error - {ex.Message}"); return null; } } #endregion #region Property path resolution /// /// Resolves a property path with exchange passed for dynamic index support /// private static object? ResolvePropertyPathWithExchange(object? obj, string path, IExchange exchange) { DebugLog($"Resolving property path with exchange: obj={obj?.GetType().Name ?? "null"}, path='{path}'"); if (string.IsNullOrEmpty(path)) { DebugLog($"Path is empty, returning: {obj}"); return obj; } if (obj == null) { DebugLog("Source object is null, cannot get nested property"); return null; } // Split path into parts accounting for possible operators int dotIndex = IndexOfPathDot(path); int operatorIndex = FindFirstOperator(path); // If comparison operator found before dot or no dot found if ((operatorIndex >= 0 && (dotIndex == -1 || operatorIndex < dotIndex)) || dotIndex == -1) { string propertyName = operatorIndex >= 0 ? path.Substring(0, operatorIndex).Trim() : path.Trim(); DebugLog($"Getting simple property: '{propertyName}'"); object? result = ResolvePropertyPartWithExchange(obj, propertyName, exchange); DebugLog($"Result of getting property '{propertyName}': {result}"); return result; } // Process path with nested properties string firstPart = path.Substring(0, dotIndex).Trim(); string remainingPath = path.Substring(dotIndex + 1).Trim(); DebugLog($"Processing nested path: first part '{firstPart}', remaining path '{remainingPath}'"); // Get the first part of the nested path object? firstObj = ResolvePropertyPartWithExchange(obj, firstPart, exchange); if (firstObj == null) { DebugLog($"Failed to get object at path '{firstPart}', returning null"); return null; } // Recursively process the remaining path return ResolvePropertyPathWithExchange(firstObj, remainingPath, exchange); } /// /// Resolves a property path on an object with support for dictionary and array access via square brackets /// private static object? ResolvePropertyPath(object? obj, string path) { DebugLog($"Resolving property path: obj={obj?.GetType().Name ?? "null"}, path='{path}'"); if (obj == null || string.IsNullOrEmpty(path)) { DebugLog($"Object is null or path is empty, returning: {obj}"); return obj; } var parts = SplitPathWithBrackets(path); var current = obj; foreach (var part in parts) { if (current == null) { DebugLog($"Current object is null at part: '{part}'"); return null; } current = ResolvePropertyPart(current, part); if (current == null) { DebugLog($"Failed to resolve part '{part}'"); return null; } } DebugLog($"Property path resolution result: {current}"); return current; } /// /// Resolves a single part of a property path with exchange support for dynamic indices /// private static object? ResolvePropertyPartWithExchange(object current, string part, IExchange exchange) { DebugLog($"Resolving part '{part}' in type {current.GetType().Name} with exchange"); // Check if the part is an index or method access if (part.Contains("[") && part.EndsWith("]")) { // Handle index access with support for expressions in indices var indexStart = part.IndexOf("["); var propertyName = part.Substring(0, indexStart); var indexExpression = part.Substring(indexStart + 1, part.Length - indexStart - 2); DebugLog($"Index access: property='{propertyName}', index='{indexExpression}'"); // Get the object to which the index will be applied object? targetObject; if (string.IsNullOrEmpty(propertyName)) { targetObject = current; // If property name is empty, use the current object } else { // Otherwise get property from current object targetObject = ResolvePropertyPart(current, propertyName); if (targetObject == null) { DebugLog($"Failed to get target object for index access: '{propertyName}'"); return null; } } // If index contains an expression, evaluate it if (indexExpression.Contains("${")) { indexExpression = ProcessTemplate(indexExpression, exchange); DebugLog($"Evaluated index expression: '{indexExpression}'"); } // Apply index access return ResolveIndexAccess(targetObject, indexExpression, current); } else if (part.Contains("(") && part.EndsWith(")")) { // Handle method call var methodStart = part.IndexOf("("); var methodName = part.Substring(0, methodStart); var paramsPart = part.Substring(methodStart + 1, part.Length - methodStart - 2); DebugLog($"Method call: method='{methodName}', parameters='{paramsPart}'"); // Parse parameters, supporting possible expressions var parameters = ParseMethodParameters(paramsPart, exchange); // Call the method return ResolveMethod(current, methodName, parameters, exchange); } else { // Standard property access try { // Check special properties/methods if (part == "length" || part == "Length") { return ResolveLength(current); } else if (part == "size" || part == "Size" || part == "count" || part == "Count") { // For collections and strings, return element count return ResolveLength(current); } // Get property info var property = FindProperty(current.GetType(), part); if (property != null) { DebugLog($"Found property '{part}' in type {current.GetType().Name}"); return property.GetValue(current); } // If property not found, check for string key indexer var indexerProperty = current.GetType().GetProperty("Item", BindingFlags.Instance | BindingFlags.Public); if (indexerProperty != null && indexerProperty.GetIndexParameters().Length == 1) { var indexParam = indexerProperty.GetIndexParameters()[0]; if (indexParam.ParameterType == typeof(string)) { DebugLog($"Using string indexer for '{part}'"); try { return indexerProperty.GetValue(current, new object[] { part }); } catch (Exception ex) when (ex is not ExpressionSandboxViolationException) { DebugLog($"Error using string indexer: {ex.Message}"); } } } // Try to find a field var field = FindField(current.GetType(), part); if (field != null) { DebugLog($"Found field '{part}' in type {current.GetType().Name}"); return field.GetValue(current); } // Check IDictionary (non-generic dictionary) if (current is System.Collections.IDictionary dictionary) { foreach (var key in dictionary.Keys) { if (key?.ToString()?.Equals(part, StringComparison.OrdinalIgnoreCase) == true) { DebugLog($"Found key '{part}' in dictionary"); return dictionary[key]; } } } // Check typed dictionaries (IDictionary) var dictionaryType = current.GetType().GetInterfaces() .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>) && i.GetGenericArguments()[0] == typeof(string)); if (dictionaryType != null) { DebugLog($"Object implements IDictionary, trying to get value by key '{part}'"); var containsMethod = dictionaryType.GetMethod("ContainsKey"); var getItemMethod = dictionaryType.GetProperty("Item").GetGetMethod(); if (containsMethod != null && getItemMethod != null && (bool)containsMethod.Invoke(current, new object[] { part })) { return getItemMethod.Invoke(current, new object[] { part }); } } // If nothing found DebugLog($"Failed to find property, field or indexer '{part}' in type {current.GetType().Name}"); return null; } catch (Exception ex) when (ex is not ExpressionSandboxViolationException and not ExpressionEvaluationException) { DebugLog($"Error resolving path part '{part}': {ex.Message}"); return null; } } } /// /// Resolves a single part of a property path, supporting square brackets for element access /// private static object? ResolvePropertyPart(object current, string part) { DebugLog($"Resolving part '{part}' in type {current.GetType().Name}"); // Check if the part contains square brackets var bracketStart = part.IndexOf('['); if (bracketStart >= 0) { var bracketEnd = part.LastIndexOf(']'); if (bracketEnd > bracketStart) { var propertyName = part.Substring(0, bracketStart); var indexExpression = part.Substring(bracketStart + 1, bracketEnd - bracketStart - 1); DebugLog($"Detected element access: property='{propertyName}', index='{indexExpression}'"); // First get the object (dictionary or array) object? targetObject; if (string.IsNullOrEmpty(propertyName)) { // Direct access to current object (e.g., [0] or ['key']) targetObject = current; } else { // Access object's property var property = FindProperty(current.GetType(), propertyName); if (property != null) { targetObject = property.GetValue(current); } else { // Same rule as the plain member step: a public field is a member too. var field = FindField(current.GetType(), propertyName); if (field == null) { DebugLog($"Member '{propertyName}' not found"); return null; } targetObject = field.GetValue(current); } } if (targetObject == null) { DebugLog($"Target object for element access is null"); return null; } return ResolveIndexAccess(targetObject, indexExpression, current); } } // Check for special methods if (part.EndsWith("()")) { var methodName = part.Substring(0, part.Length - 2); return ResolveMethod(current, methodName, new object[0], null); } // Check for methods with parameters (e.g., contains('text') or substring(1,3)) var parenStart = part.IndexOf('('); if (parenStart >= 0 && part.EndsWith(")")) { var methodName = part.Substring(0, parenStart); var paramsPart = part.Substring(parenStart + 1, part.Length - parenStart - 2); DebugLog($" Detected method call: '{methodName}' with parameters '{paramsPart}'"); var parameters = ParseMethodParameters(paramsPart, null); DebugLog($" Parameters parsed: {parameters.Length} items"); var result = ResolveMethod(current, methodName, parameters, null); DebugLog($" Method '{methodName}' result: {result}"); return result; } // Regular property access DebugLog($"Looking for property '{part}' in type {current.GetType().Name}"); var normalProperty = FindProperty(current.GetType(), part); if (normalProperty != null) { var value = normalProperty.GetValue(current); DebugLog($"Found property '{part}', value: {value}"); return value; } // A public field is a member like any other: header.x.Field, property.x.Field and // body.Field must all read it. Until 2026-08-29 only one of the three paths did. var normalField = FindField(current.GetType(), part); if (normalField != null) { var value = normalField.GetValue(current); DebugLog($"Found field '{part}', value: {value}"); return value; } // Check IDictionary (non-generic) if (current is System.Collections.IDictionary dictionary) { foreach (var key in dictionary.Keys) { if (key?.ToString()?.Equals(part, StringComparison.OrdinalIgnoreCase) == true) { DebugLog($"Found key '{part}' in dictionary"); return dictionary[key]; } } } // Check typed dictionaries (IDictionary) var dictionaryType = current.GetType().GetInterfaces() .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>) && i.GetGenericArguments()[0] == typeof(string)); if (dictionaryType != null) { DebugLog($"Object implements IDictionary, trying to get value by key '{part}'"); var containsMethod = dictionaryType.GetMethod("ContainsKey"); var getItemMethod = dictionaryType.GetProperty("Item")?.GetGetMethod(); if (containsMethod != null && getItemMethod != null && (bool)containsMethod.Invoke(current, new object[] { part })!) { return getItemMethod.Invoke(current, new object[] { part }); } } DebugLog($"Property '{part}' not found"); return null; } /// /// Splits a property path at its separators: a dot outside parentheses, square brackets and quotes, so a method /// argument keeps its own dots (list.contains(5.0), name.replace('a.b', 'c')). Empty segments are /// kept, as keeps them: a..b reads nothing. /// private static string[] SplitPathWithBrackets(string path) { var parts = new List(); var start = 0; while (true) { var dot = IndexOfPathDot(path, start); parts.Add(dot < 0 ? path[start..] : path[start..dot]); if (dot < 0) return parts.ToArray(); start = dot + 1; } } /// /// The first path separator of at or after : a dot outside /// parentheses, square brackets and quoted literals; -1 when there is none. /// private static int IndexOfPathDot(string path, int start = 0) { var depth = 0; var quote = '\0'; for (var i = start; i < path.Length; i++) { var ch = path[i]; if (quote != '\0') { if (ch == '\\' && i + 1 < path.Length) i++; else if (ch == quote) quote = '\0'; continue; } switch (ch) { case '\'' or '"': quote = ch; break; case '(' or '[': depth++; break; case ')' or ']': if (depth > 0) depth--; break; case '.' when depth == 0: return i; } } return -1; } #endregion #region Index access resolution /// /// Resolves element access by index or key /// private static object? ResolveIndexAccess(object targetObject, string indexExpression, object rootObject) { DebugLog($"Resolving element access: object={targetObject.GetType().Name}, index='{indexExpression}'"); // Determine the index value object? indexValue = ResolveIndexValue(indexExpression, rootObject); DebugLog($"Index value: {indexValue} (type: {indexValue?.GetType().Name ?? "null"})"); // Dictionary access if (targetObject is IDictionary stringDict) { var key = indexValue?.ToString(); if (key != null && stringDict.TryGetValue(key, out var dictValue)) { DebugLog($"Found dictionary element by key '{key}': {dictValue}"); return dictValue; } DebugLog($"Key '{key}' not found in dictionary"); return null; } // Non-generic dictionary access if (targetObject is System.Collections.IDictionary dict) { var key = indexValue?.ToString(); if (key != null && dict.Contains(key)) { var dictValue = dict[key]; DebugLog($"Found dictionary element by key '{key}': {dictValue}"); return dictValue; } DebugLog($"Key '{key}' not found in dictionary"); return null; } // Array or list access if (targetObject is System.Collections.IList list) { if (indexValue is int intIndex) { if (intIndex >= 0 && intIndex < list.Count) { var listValue = list[intIndex]; DebugLog($"Found list element at index {intIndex}: {listValue}"); return listValue; } DebugLog($"Index {intIndex} out of list bounds (size: {list.Count})"); return null; } // Try to convert to int if (int.TryParse(indexValue?.ToString(), out var parsedIndex)) { if (parsedIndex >= 0 && parsedIndex < list.Count) { var listValue = list[parsedIndex]; DebugLog($"Found list element at index {parsedIndex}: {listValue}"); return listValue; } DebugLog($"Index {parsedIndex} out of list bounds (size: {list.Count})"); return null; } } // Array access if (targetObject is Array array) { if (indexValue is int intIndex) { if (intIndex >= 0 && intIndex < array.Length) { var arrayValue = array.GetValue(intIndex); DebugLog($"Found array element at index {intIndex}: {arrayValue}"); return arrayValue; } DebugLog($"Index {intIndex} out of array bounds (size: {array.Length})"); return null; } // Try to convert to int if (int.TryParse(indexValue?.ToString(), out var parsedIndex)) { if (parsedIndex >= 0 && parsedIndex < array.Length) { var arrayValue = array.GetValue(parsedIndex); DebugLog($"Found array element at index {parsedIndex}: {arrayValue}"); return arrayValue; } DebugLog($"Index {parsedIndex} out of array bounds (size: {array.Length})"); return null; } } DebugLog($"Failed to access element: object type {targetObject.GetType().Name} does not support indexing"); return null; } /// /// Resolves an index value (can be a literal or a property reference) /// private static object? ResolveIndexValue(string indexExpression, object rootObject) { DebugLog($"Resolving index value: '{indexExpression}'"); // Check if this is a property reference if (indexExpression.StartsWith("property.")) { var propertyName = indexExpression.Substring(PROPERTY_PREFIX.Length); DebugLog($"Index is a property reference: '{propertyName}'"); // Get the property value from rootObject (which should be IExchange) if (rootObject is IExchange exchange) { var propertyValue = GetExchangeProperty(exchange, propertyName); DebugLog($"Property '{propertyName}' value: {propertyValue}"); return propertyValue; } else { DebugLog($"Root object is not IExchange, cannot get property"); return null; } } // Otherwise parse as literal var literalValue = ParseLiteral(indexExpression); DebugLog($"Index as literal: '{indexExpression}' -> {literalValue}"); return literalValue; } #endregion #region Method resolution /// /// Resolves a method call on an object /// private static object? ResolveMethod(object current, string methodName, object[] parameters, IExchange? exchange) { DebugLog($"Resolving method '{methodName}' with {parameters.Length} parameters on type {current.GetType().Name}"); try { switch (methodName.ToLowerInvariant()) { case "length": case "count": case "size": return ResolveLength(current); case "contains": return ResolveContains(current, parameters); case "substring": return ResolveSubstring(current, parameters); case "trim": return ResolveTrim(current, parameters); case "toupper": return ResolveToUpper(current, parameters); case "tolower": return ResolveToLower(current, parameters); case "replace": return ResolveReplace(current, parameters); case "startswith": return ResolveStartsWith(current, parameters); case "endswith": return ResolveEndsWith(current, parameters); case "indexof": return ResolveIndexOf(current, parameters); default: // Anything beyond the built-in helpers is a reflection call on the object: refused // inside a sandbox (templates), where an expression reads members but never runs code. if (ExpressionSandbox.IsActive) throw new ExpressionSandboxViolationException(methodName, current.GetType()); return ResolveMethodByReflection(current, methodName, parameters); } } catch (Exception ex) when (ex is not ExpressionSandboxViolationException) { DebugLog($"Error calling method '{methodName}': {ex.Message}"); return null; } } /// /// Resolves the length/size method /// private static object? ResolveLength(object current) { DebugLog($"Resolving length/size for type {current.GetType().Name}"); // For strings if (current is string str) { var result = str.Length; DebugLog($"String length: {result}"); return result; } // For collections if (current is System.Collections.ICollection collection) { var result = collection.Count; DebugLog($"Collection size: {result}"); return result; } // For arrays if (current is Array array) { var result = array.Length; DebugLog($"Array length: {result}"); return result; } // Try to find Length or Count property var lengthProperty = current.GetType().GetProperty("Length", BindingFlags.Public | BindingFlags.Instance); if (lengthProperty != null) { var result = lengthProperty.GetValue(current); DebugLog($"Length property: {result}"); return result; } var countProperty = current.GetType().GetProperty("Count", BindingFlags.Public | BindingFlags.Instance); if (countProperty != null) { var result = countProperty.GetValue(current); DebugLog($"Count property: {result}"); return result; } DebugLog($"Failed to determine length for type {current.GetType().Name}"); return null; } #endregion #region Method parameter parsing /// /// Parses method parameters from a string /// private static object[] ParseMethodParameters(string parametersString, IExchange? exchange) { DebugLog($"ParseMethodParameters: input string='{parametersString}'"); if (string.IsNullOrEmpty(parametersString)) { DebugLog("ParseMethodParameters: empty parameter string, returning empty array"); return Array.Empty(); } var paramStrings = SplitParameters(parametersString); DebugLog($"ParseMethodParameters: split into {paramStrings.Length} parameters: [{string.Join(", ", paramStrings.Select(p => $"'{p}'"))}]"); var parameters = new List(); foreach (var paramStr in paramStrings) { var trimmed = paramStr.Trim(); DebugLog($"ParseMethodParameters: processing parameter '{trimmed}'"); // If parameter starts with property., it's a property reference if (trimmed.StartsWith("property.")) { var propertyName = trimmed.Substring(PROPERTY_PREFIX.Length); DebugLog($"ParseMethodParameters: property reference '{propertyName}'"); if (exchange != null) { var value = GetExchangeProperty(exchange, propertyName); DebugLog($"ParseMethodParameters: property '{propertyName}' value = '{value}' (type: {value?.GetType().Name ?? "null"})"); parameters.Add(value); } else { DebugLog($"ParseMethodParameters: exchange is null, cannot get property '{propertyName}', using string as-is"); parameters.Add(trimmed); // Add as string if exchange is unavailable } } // If parameter is in quotes, it's a string literal else if ((trimmed.StartsWith("'") && trimmed.EndsWith("'")) || (trimmed.StartsWith("\"") && trimmed.EndsWith("\""))) { var stringValue = trimmed.Substring(1, trimmed.Length - 2); DebugLog($"ParseMethodParameters: string literal '{stringValue}'"); parameters.Add(stringValue); } // Try to convert to number else if (TryConvertToInt(trimmed, out int intValue)) { DebugLog($"ParseMethodParameters: integer {intValue}"); parameters.Add(intValue); } // Otherwise treat as string else { DebugLog($"ParseMethodParameters: plain string '{trimmed}'"); parameters.Add(trimmed); } } DebugLog($"ParseMethodParameters: final parameters: [{string.Join(", ", parameters.Select(p => $"'{p}' ({p?.GetType().Name ?? "null"})"))}]"); return parameters.ToArray(); } /// /// Splits a parameter string into individual parameters accounting for quotes /// private static string[] SplitParameters(string paramsPart) { var parameters = new List(); var current = new StringBuilder(); var inQuotes = false; var quoteChar = '\0'; for (int i = 0; i < paramsPart.Length; i++) { var ch = paramsPart[i]; if (!inQuotes && (ch == '\'' || ch == '"')) { inQuotes = true; quoteChar = ch; current.Append(ch); } else if (inQuotes && ch == quoteChar) { inQuotes = false; current.Append(ch); } else if (!inQuotes && ch == ',') { parameters.Add(current.ToString()); current.Clear(); } else { current.Append(ch); } } if (current.Length > 0) { parameters.Add(current.ToString()); } return parameters.ToArray(); } #endregion #region Public method ResolveExpression /// /// Evaluates an expression in the context of an exchange, by the same engine as every other position: a text with /// ${...} placeholders renders as a template, any other text reads exactly as the inside of a ${...} /// hole (a bare path is a lookup, an unquoted jpath/xpath path is allowed). What a payload template's /// expr(...) calls. /// /// /// Until rows 2 and 22 of the 2026-11-05 findings register this was a dispatcher of its own: it sent a text to the /// expression engine only when it saw an operator written with spaces, a function call or an index, and returned any /// other text as it was, so expr('1>0') gave the text "1>0" and a bean: call came back unevaluated. /// public static object? ResolveExpression(string expression, IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); if (string.IsNullOrEmpty(expression)) return null; return TemplateScanner.HasPlaceholder(expression) ? ProcessTemplate(expression, exchange) : string.IsNullOrWhiteSpace(expression) ? null : GetCompiledPlaceholder(expression)(exchange); } #endregion } Path: redb-route/redb.Route/Expressions/ExpressionResolver.StringMethods.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/Expressions/ExpressionResolver.StringMethods.cs ---- using System; using System.Linq; using System.Reflection; namespace redb.Route.Expressions; /// /// Partial class ExpressionResolver - string manipulation methods /// public static partial class ExpressionResolver { /// /// Resolves the contains method for strings and collections /// private static object? ResolveContains(object current, object[] parameters) { DebugLog($"ResolveContains: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (parameters.Length != 1) { DebugLog($"ResolveContains: invalid parameter count: {parameters.Length}"); return null; } var searchValue = parameters[0]; DebugLog($"ResolveContains: searching for value '{searchValue}' in object of type {current?.GetType().Name}"); // For strings if (current is string str) { var searchStr = searchValue?.ToString() ?? ""; var result = str.Contains(searchStr); DebugLog($"ResolveContains: string '{str}' contains '{searchStr}' = {result}"); return result; } // For collections if (current is System.Collections.IEnumerable enumerable && current is not string) { foreach (var item in enumerable) { if (AreEqual(item, searchValue)) { DebugLog($"ResolveContains: collection contains element '{searchValue}' = true"); return true; } } DebugLog($"ResolveContains: collection does NOT contain element '{searchValue}' = false"); return false; } DebugLog($"ResolveContains: unsupported type {current?.GetType().Name}"); return null; } /// /// Resolves the substring method for strings /// private static object? ResolveSubstring(object current, object[] parameters) { DebugLog($"ResolveSubstring: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveSubstring: object is not a string: {current?.GetType().Name}"); return null; } if (parameters.Length == 0 || parameters.Length > 2) { DebugLog($"ResolveSubstring: invalid parameter count: {parameters.Length}"); return null; } // Get startIndex if (!TryConvertToInt(parameters[0], out int startIndex)) { DebugLog($"ResolveSubstring: failed to convert startIndex: {parameters[0]}"); return null; } DebugLog($"ResolveSubstring: string='{str}', startIndex={startIndex}"); // Check bounds if (startIndex < 0 || startIndex >= str.Length) { DebugLog($"ResolveSubstring: startIndex {startIndex} is out of bounds for string of length {str.Length}"); return ""; } // One parameter - substring(startIndex) if (parameters.Length == 1) { var result = str.Substring(startIndex); DebugLog($"ResolveSubstring: substring({startIndex}) = '{result}'"); return result; } // Two parameters - substring(startIndex, length) if (!TryConvertToInt(parameters[1], out int length)) { DebugLog($"ResolveSubstring: failed to convert length: {parameters[1]}"); return null; } DebugLog($"ResolveSubstring: string='{str}', startIndex={startIndex}, length={length}"); // Check bounds for length if (length < 0) { DebugLog($"ResolveSubstring: negative length: {length}"); return ""; } if (startIndex + length > str.Length) { length = str.Length - startIndex; DebugLog($"ResolveSubstring: adjusted length to {length}"); } var result2 = str.Substring(startIndex, length); DebugLog($"ResolveSubstring: substring({startIndex}, {length}) = '{result2}'"); return result2; } /// /// Resolves the trim method for strings /// private static object? ResolveTrim(object current, object[] parameters) { DebugLog($"ResolveTrim: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveTrim: object is not a string: {current?.GetType().Name}"); return null; } // No parameters - regular trim if (parameters.Length == 0) { var result = str.Trim(); DebugLog($"ResolveTrim: trim() = '{result}'"); return result; } // With one parameter - trim specific characters if (parameters.Length == 1) { var trimChars = parameters[0]?.ToString(); if (string.IsNullOrEmpty(trimChars)) { var result = str.Trim(); DebugLog($"ResolveTrim: trim(empty chars) = '{result}'"); return result; } var result2 = str.Trim(trimChars.ToCharArray()); DebugLog($"ResolveTrim: trim('{trimChars}') = '{result2}'"); return result2; } DebugLog($"ResolveTrim: invalid parameter count: {parameters.Length}"); return null; } /// /// Resolves the toupper method for strings /// private static object? ResolveToUpper(object current, object[] parameters) { DebugLog($"ResolveToUpper: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveToUpper: object is not a string: {current?.GetType().Name}"); return null; } var result = str.ToUpper(); DebugLog($"ResolveToUpper: toupper() = '{result}'"); return result; } /// /// Resolves the tolower method for strings /// private static object? ResolveToLower(object current, object[] parameters) { DebugLog($"ResolveToLower: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveToLower: object is not a string: {current?.GetType().Name}"); return null; } var result = str.ToLower(); DebugLog($"ResolveToLower: tolower() = '{result}'"); return result; } /// /// Resolves the replace method for strings /// private static object? ResolveReplace(object current, object[] parameters) { DebugLog($"ResolveReplace: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveReplace: object is not a string: {current?.GetType().Name}"); return null; } if (parameters.Length != 2) { DebugLog($"ResolveReplace: invalid parameter count: {parameters.Length}"); return null; } var searchValue = parameters[0]?.ToString(); var replaceValue = parameters[1]?.ToString(); if (string.IsNullOrEmpty(searchValue)) { DebugLog($"ResolveReplace: empty search pattern"); return str; } var result = str.Replace(searchValue, replaceValue); DebugLog($"ResolveReplace: replace('{searchValue}', '{replaceValue}') = '{result}'"); return result; } /// /// Resolves the startswith method for strings /// private static object? ResolveStartsWith(object current, object[] parameters) { DebugLog($"ResolveStartsWith: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveStartsWith: object is not a string: {current?.GetType().Name}"); return null; } if (parameters.Length != 1) { DebugLog($"ResolveStartsWith: invalid parameter count: {parameters.Length}"); return null; } var searchValue = parameters[0]?.ToString(); if (string.IsNullOrEmpty(searchValue)) { DebugLog($"ResolveStartsWith: empty search pattern"); return true; } var result = str.StartsWith(searchValue); DebugLog($"ResolveStartsWith: startswith('{searchValue}') = {result}"); return result; } /// /// Resolves the endswith method for strings /// private static object? ResolveEndsWith(object current, object[] parameters) { DebugLog($"ResolveEndsWith: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveEndsWith: object is not a string: {current?.GetType().Name}"); return null; } if (parameters.Length != 1) { DebugLog($"ResolveEndsWith: invalid parameter count: {parameters.Length}"); return null; } var searchValue = parameters[0]?.ToString(); if (string.IsNullOrEmpty(searchValue)) { DebugLog($"ResolveEndsWith: empty search pattern"); return true; } var result = str.EndsWith(searchValue); DebugLog($"ResolveEndsWith: endswith('{searchValue}') = {result}"); return result; } /// /// Resolves the indexof method for strings /// private static object? ResolveIndexOf(object current, object[] parameters) { DebugLog($"ResolveIndexOf: object={current?.GetType().Name ?? "null"}, parameters={parameters.Length}"); if (current is not string str) { DebugLog($"ResolveIndexOf: object is not a string: {current?.GetType().Name}"); return null; } if (parameters.Length != 1) { DebugLog($"ResolveIndexOf: invalid parameter count: {parameters.Length}"); return null; } var searchValue = parameters[0]?.ToString(); if (string.IsNullOrEmpty(searchValue)) { DebugLog($"ResolveIndexOf: empty search pattern"); return null; } var result = str.IndexOf(searchValue); DebugLog($"ResolveIndexOf: indexof('{searchValue}') = {result}"); return result; } /// /// Resolves a method via reflection /// private static object? ResolveMethodByReflection(object current, string methodName, object[] parameters) { DebugLog($"Searching for method '{methodName}' via reflection"); var type = current.GetType(); var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => string.Equals(m.Name, methodName, StringComparison.OrdinalIgnoreCase)) .ToArray(); if (methods.Length == 0) { DebugLog($"Method '{methodName}' not found in type {type.Name}"); return null; } // Find a matching method by parameter count var method = methods.FirstOrDefault(m => m.GetParameters().Length == parameters.Length); if (method == null) { DebugLog($"Method '{methodName}' with {parameters.Length} parameters not found"); return null; } try { var result = method.Invoke(current, parameters); DebugLog($"Method '{methodName}' invocation successful: {result}"); return result; } catch (Exception ex) when (ex is not ExpressionSandboxViolationException) { DebugLog($"Error invoking method '{methodName}': {ex.Message}"); return null; } } } Path: redb-route/redb.Route/Expressions/ExpressionResolver.Template.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/Expressions/ExpressionResolver.Template.cs ---- using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// The template engine: the one pipeline that gives a ${...} placeholder its meaning. /// Until 2026-08-28 two independent engines interpreted placeholders — one under /// , another under ResolveTypedOrTemplate — with /// complementary holes: the first understood unspaced comparisons and dashed header names but not /// arithmetic, the second the reverse. Both now route through , /// so a placeholder means the same thing wherever it is written. /// public static partial class ExpressionResolver { /// /// Compiles the inner text of a single ${...} placeholder into a typed evaluator. /// /// The rules, in order: jpath(...) and xpath(...) keep their own syntax (the /// expression tokenizer does not read $ or / paths); body and /// contentType are direct accessors; a header. or property. prefix /// resolves by the literal-name-first rule below; anything else is a full expression compiled /// by the AST engine — arithmetic, comparisons, functions, ternary and index access included. /// /// /// Literal-name-first: header.Content-Type is the header of that exact name when it /// exists; header.user.Age is the member path behind the user header; /// header.a+1, matching neither, is the expression. The name check happens per /// exchange, which is what makes a dash usable in a name at all — no grammar can tell a /// dashed name from a subtraction, but the message can. /// /// /// The text between ${ and }. /// An evaluator returning the CLR-typed value of the placeholder. /// Thrown when the text is not a resolvable placeholder. internal static Func CompilePlaceholder(string placeholder) { ArgumentException.ThrowIfNullOrWhiteSpace(placeholder); var text = placeholder.Trim(); // ${expr:F4}: a format suffix, format(expr, 'F4') with the invariant culture (findings register row 34 point 4). if (TrySplitFormatSuffix(text, out var formatted, out var suffix)) { var value = CompilePlaceholder(formatted); return exchange => Ast_Format(value(exchange), suffix, null); } // ${jsonpath:$.a.b} and ${xpath://a}: Apache Camel's spellings of jpath('...') and xpath('...') (row 34 point 2). // The path is the rest of the placeholder as written; only a whole placeholder, where its end is known. foreach (var (prefix, apply) in PathSpellings) if (text.StartsWith(prefix, StringComparison.Ordinal)) { var path = text[prefix.Length..].Trim(); if (path.Length == 0) throw new ExpressionCompilationException($"${{{text}}} names no path: write ${{{prefix}$.a.b}} or ${{{prefix}//a}}."); return exchange => apply(exchange, path); } // ${file:name}: the file language over the file headers (row 34 point 3). if (text.StartsWith("file:", StringComparison.Ordinal)) return FileKey(text); if (text.StartsWith("file:", StringComparison.OrdinalIgnoreCase)) throw new ExpressionCompilationException( $"${{{text}}}: file keys are lowercase: ${{file:{text["file:".Length..].Trim().ToLowerInvariant()}}}."); // A namespaced call (bean:svc.Check(...)) is the AST's, deterministically: no shortcut below knows it. if (ContainsNamespacedCall(text)) return GetCompiledValueExpressionWithAst(text); var jpath = JPathFunctionRegex.Match(text); if (jpath.Success && jpath.Value.Trim() == text && !HasSecondArgument(jpath.Groups[1].Value)) { var path = Unquote(jpath.Groups[1].Value.Trim()); return exchange => ApplyJPath(exchange, path); } var xpath = XPathFunctionRegex.Match(text); if (xpath.Success && xpath.Value.Trim() == text && !HasSecondArgument(xpath.Groups[1].Value)) { var path = Unquote(xpath.Groups[1].Value.Trim()); return exchange => ApplyXPath(exchange, path); } if (text == "body") return exchange => exchange.In.getBody(); if (text == "contentType") return exchange => exchange.In.ContentType; if (text.StartsWith(HEADER_PREFIX, StringComparison.Ordinal) && text.Length > HEADER_PREFIX.Length) return CompileAccessorPlaceholder(text, text[HEADER_PREFIX.Length..], isHeader: true); if (text.StartsWith(PROPERTY_PREFIX, StringComparison.Ordinal) && text.Length > PROPERTY_PREFIX.Length) return CompileAccessorPlaceholder(text, text[PROPERTY_PREFIX.Length..], isHeader: false); return GetCompiledValueExpressionWithAst(text); } /// /// Tells a one-argument xpath(path) from a two-argument xpath(path, source). /// /// /// The shortcut above exists because a bare path is not something the expression tokenizer can /// read — $.store.book and /order/id are not tokens. A second argument is, /// though, and it has to be evaluated against the exchange, so the placeholder belongs to the /// AST engine instead. Commas inside quotes and inside brackets are part of the path /// ($..book[0,1], /a[@x='1,2']) and do not count. /// private static bool HasSecondArgument(string arguments) { var depth = 0; var quote = '\0'; foreach (var c in arguments) { if (quote != '\0') { if (c == quote) quote = '\0'; continue; } switch (c) { case '\'' or '"': quote = c; break; case '(' or '[' or '{': depth++; break; case ')' or ']' or '}': depth--; break; case ',' when depth == 0: return true; } } return false; } /// /// The literal-name-first evaluator for a header. or property. placeholder: /// the exact name wins, then the smart nested path, then the whole text as an expression. /// The expression leg is compiled eagerly so a placeholder that can be nothing at all still /// fails at build time rather than rendering as emptiness forever. /// private static Func CompileAccessorPlaceholder(string full, string tail, bool isHeader) { // A tail that cannot compile as an expression still works as a pure name lookup when it is one word (a dashed // name is a subtraction of unknowns and compiles anyway). A tail with whitespace is an expression, and one that // does not compile (header.b == 3 garbage) is the error, at build time (findings register row 32). Func? expression; try { expression = GetCompiledValueExpressionWithAst(full); } catch (Exception) when (!tail.Any(char.IsWhiteSpace)) { expression = null; } var nested = tail.Contains('.'); return exchange => { if (isHeader) { if (exchange.In.Headers.ContainsKey(tail)) return exchange.In.getHeader(tail); if (nested) { var value = ResolveHeaderSmart(exchange, tail); if (value is not null) return value; } } else { if (exchange.Properties.ContainsKey(tail)) return exchange.getProperty(tail); if (nested) { var value = ResolvePropertySmart(exchange, tail); if (value is not null) return value; } } return expression?.Invoke(exchange); }; } /// /// Compiles a full template — literal text with ${...} holes — into a string /// producer. Each hole goes through ; the text between holes /// is emitted verbatim, whatever operators it happens to contain. /// private static Func CompileTemplateString(string template) { var holes = TemplateScanner.Holes(template); var segments = new List>(holes.Count * 2 + 1); var position = 0; foreach (var hole in holes) { if (hole.Start > position) { var literal = Unescape(template[position..hole.Start]); segments.Add(_ => literal); } var compiled = CompilePlaceholder(hole.InnerOf(template)); segments.Add(exchange => TemplateText(compiled(exchange))); position = hole.Start + hole.Length; } if (position < template.Length) { var tail = Unescape(template[position..]); segments.Add(_ => tail); } return exchange => { var text = new StringBuilder(); foreach (var segment in segments) text.Append(segment(exchange)); return text.ToString(); }; } /// /// The text between holes with each escape \${ written as the literal ${ it stands for. Outside a /// hole a \${ is always an escape: the scanner never opens a hole there. /// private static string Unescape(string literal) => literal.Contains("\\${", StringComparison.Ordinal) ? literal.Replace("\\${", "${", StringComparison.Ordinal) : literal; /// /// Reports whether the whole string is exactly one ${...} placeholder, in which case /// its value keeps the CLR type instead of being rendered to text. /// /// The template string. /// The inner text when the string is a single placeholder. /// true when the string is one placeholder with nothing around it. internal static bool TryGetSinglePlaceholder(string template, out string placeholder) { if (template.Length > 3 && template.StartsWith("${", StringComparison.Ordinal) && TemplateScanner.Scan(template) is { Unclosed.Count: 0, Holes: [var only] } && only.Length == template.Length) { placeholder = only.InnerOf(template); return true; } placeholder = string.Empty; return false; } /// /// Gets a cached typed evaluator for the inner text of a single placeholder. /// internal static Func GetCompiledPlaceholder(string placeholder, string? contextId = null) { var cacheKey = BuildCacheKey(contextId, "placeholder:" + placeholder); return _valueExpressionCache.GetOrAdd(cacheKey, _ => CompilePlaceholder(placeholder)); } /// /// ${file:key}, Apache Camel's file language (row 34 point 3) over the redbFile.* headers the file /// consumers set, through ; an unknown key is an error listing the keys. /// private static Func FileKey(string text) { var key = text["file:".Length..]; if (!FileLanguage.TryGetFact(key, StringComparison.Ordinal, out var fact)) throw new ExpressionCompilationException($"${{{text}}}: {FileLanguage.UnknownKeyMessage(key)}"); return exchange => FileLanguage.Value(fact, new FileHeaderFacts(exchange.In.Headers)); } /// The Camel path spellings of a whole placeholder and the readers they stand for. private static readonly (string Prefix, Func Apply)[] PathSpellings = [ ("jsonpath:", ApplyJPath), ("xpath:", ApplyXPath), ]; /// /// A placeholder expr:FORMAT whose last colon at the top level (outside quotes, parentheses and brackets, with /// no ? of a ternary before it) is followed by a standard .NET format: one letter and up to two digits /// (F4, N2, D8). The left side must name a value with a dot or a call (total.CostUsd, /// round(x)), so a namespace written against its name (env:X, file:name) is never a format. /// internal static bool TrySplitFormatSuffix(string text, out string expression, out string format) { expression = format = string.Empty; var depth = 0; var quote = '\0'; var colon = -1; for (var i = 0; i < text.Length; i++) { var ch = text[i]; if (quote != '\0') { if (ch == '\\' && i + 1 < text.Length) i++; else if (ch == quote) quote = '\0'; continue; } switch (ch) { case '\'' or '"': quote = ch; break; case '(' or '[': depth++; break; case ')' or ']': if (depth > 0) depth--; break; case '?' when depth == 0: return false; // a ternary's colon, or ?? case ':' when depth == 0: colon = i; break; } } if (colon <= 0) return false; var left = text[..colon].Trim(); var right = text[(colon + 1)..].Trim(); if (!FormatSuffixRegex.IsMatch(right) || left.Length == 0 || BareWordRegex.IsMatch(left)) return false; expression = left; format = right; return true; } private static readonly Regex FormatSuffixRegex = new(@"^[A-Za-z][0-9]{0,2}$", RegexOptions.Compiled); private static readonly Regex BareWordRegex = new(@"^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); private static string Unquote(string text) => text.Length >= 2 && ((text.StartsWith('\'') && text.EndsWith('\'')) || (text.StartsWith('"') && text.EndsWith('"'))) ? text[1..^1] : text; } Path: redb-route/redb.Route/Expressions/ExpressionResolver.TemplateText.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/Expressions/ExpressionResolver.TemplateText.cs ---- using System.Globalization; namespace redb.Route.Expressions; /// Partial class ExpressionResolver — how a ${...} hole becomes text. public static partial class ExpressionResolver { /// /// Renders one substituted value of a ${...} template. Numbers and dates are written /// culture-invariant (dates as ISO 8601), so a route renders the same text on every machine; /// locale-specific formatting is an explicit choice (format(x, 'N2', 'ru-RU')), not the /// server's accident. Strings and booleans are unchanged. /// internal static string TemplateText(object? value) => value switch { null => string.Empty, string s => s, bool b => b.ToString(), DateTime d => d.ToString("o", CultureInfo.InvariantCulture), DateTimeOffset d => d.ToString("o", CultureInfo.InvariantCulture), IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), _ => value.ToString() ?? string.Empty, }; } Path: redb-route/redb.Route/Expressions/ExpressionResolver.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/Expressions/ExpressionResolver.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Expressions.Ast; using SysExpression = System.Linq.Expressions.Expression; namespace redb.Route.Expressions; /// /// Expression resolver with compiled lambda caching for performance optimization. /// public static partial class ExpressionResolver { /// /// Delegate for expressions that resolve a value from an . /// private delegate object? ExpressionDelegate(IExchange exchange); // Caches for compiled expressions private static readonly ConcurrentDictionary> _templateCache = new(); private static readonly ConcurrentDictionary> _propertyResolverCache = new(); private static readonly ConcurrentDictionary> _valueExpressionCache = new(); /// /// Builds a cache key from an optional context ID and expression. /// When contextId is provided, returns "{contextId}:{expression}"; otherwise returns the expression as-is. /// private static string BuildCacheKey(string? contextId, string expression) => contextId is null ? expression : $"{contextId}:{expression}"; // Regular expressions for parsing private static readonly Regex UnaryOperationRegex = new(@"^([!+\-])(.+)$", RegexOptions.Compiled); // Regular expression for prefix increment/decrement private static readonly Regex PrefixIncrementDecrementRegex = new(@"^(\+\+|--)(.+)$", RegexOptions.Compiled); // Regular expression for postfix increment/decrement private static readonly Regex PostfixIncrementDecrementRegex = new(@"^(.+)(\+\+|--)$", RegexOptions.Compiled); // Regular expression for binary operations private static readonly Regex BinaryOperationRegex = new(@"^(.+?)\s*([+\-])\s*(.+)$", RegexOptions.Compiled); // Regular expression for high-priority binary operations private static readonly Regex BinaryHighPriorityOperationRegex = new(@"^(.+?)\s*([*/])\s*(.+)$", RegexOptions.Compiled); // Regular expression for jpath function — lazy quantifier to avoid greedy capture across nested calls private static readonly Regex JPathFunctionRegex = new(@"jpath\((.*?)\)", RegexOptions.Compiled); // Regular expression for xpath function — lazy quantifier to avoid greedy capture across nested calls private static readonly Regex XPathFunctionRegex = new(@"xpath\((.*?)\)", RegexOptions.Compiled); // Prefixes for property types private const string PROPERTY_PREFIX = "property."; private const string HEADER_PREFIX = "header."; private const string BODY_PREFIX = "body."; private const string EXCEPTION_PREFIX = "exception."; // Debug flag private static bool _debugEnabled = false; // Optional logger for expression resolution warnings private static ILogger? _logger; /// /// Sets an optional logger for expression resolution warnings (missing headers, properties, etc.). /// public static void SetLogger(ILogger? logger) => _logger = logger; /// /// Sets an optional logger factory; creates a logger named "redb.Route.Expressions". /// public static void SetLoggerFactory(ILoggerFactory? factory) => _logger = factory?.CreateLogger("redb.Route.Expressions"); /// /// Reports whether a string is a ${...} template rather than a bare expression. /// The two are different positions in the language: a template is interpolated into a string, /// while a bare expression is compiled and evaluated. /// /// The string to inspect. /// true when the string contains at least one ${...} placeholder. public static bool IsTemplate(string expression) { ArgumentNullException.ThrowIfNull(expression); return TemplateScanner.HasPlaceholder(expression); } // Counters for caching metrics private static long _templateHits = 0; private static long _templateMisses = 0; private static long _propertyResolverHits = 0; private static long _propertyResolverMisses = 0; private static long _valueExpressionHits = 0; private static long _valueExpressionMisses = 0; #region Debug methods /// /// Enables or disables debug output. /// /// true to enable debug logging; false to disable it. public static void SetDebugMode(bool enabled) { _debugEnabled = enabled; } /// /// Writes a debug message to the console when debug mode is enabled. /// /// The message to output. public static void DebugLog(string message) { if (_debugEnabled) { Console.WriteLine($"[ExpressionResolver DEBUG] {message}"); } } /// /// Prints an expression tree to the console with indentation reflecting nesting depth. /// /// The expression to visualize. /// Current indentation prefix. /// Whether this is the root expression. public static void DebugPrintExpressionTree(SysExpression expression, string indent = "", bool isRoot = true) { if (!_debugEnabled || expression == null) return; var nodeType = expression.NodeType.ToString(); var expressionType = expression.Type.Name; Console.WriteLine($"[ExprTree] {indent}{(isRoot ? "▶ " : "├─")} {nodeType} ({expressionType})"); // Increase indent for child nodes var childIndent = indent + (isRoot ? " " : "│ "); // Process child expressions depending on the type switch (expression) { case MethodCallExpression methodCall: Console.WriteLine($"[ExprTree] {childIndent}├─ Method: {methodCall.Method.Name}"); Console.WriteLine($"[ExprTree] {childIndent}├─ Object:"); if (methodCall.Object != null) DebugPrintExpressionTree(methodCall.Object, childIndent + "│ ", false); if (methodCall.Arguments.Count > 0) { Console.WriteLine($"[ExprTree] {childIndent}├─ Arguments ({methodCall.Arguments.Count}):"); for (int i = 0; i < methodCall.Arguments.Count; i++) { Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Arg[{i}]:"); DebugPrintExpressionTree(methodCall.Arguments[i], childIndent + "│ │ ", false); } } break; case BinaryExpression binary: Console.WriteLine($"[ExprTree] {childIndent}├─ Left:"); DebugPrintExpressionTree(binary.Left, childIndent + "│ ", false); Console.WriteLine($"[ExprTree] {childIndent}├─ Right:"); DebugPrintExpressionTree(binary.Right, childIndent + "│ ", false); break; case UnaryExpression unary: Console.WriteLine($"[ExprTree] {childIndent}├─ Operand:"); DebugPrintExpressionTree(unary.Operand, childIndent + "│ ", false); break; case System.Linq.Expressions.ConstantExpression constant: var value = constant.Value?.ToString() ?? "null"; Console.WriteLine($"[ExprTree] {childIndent}├─ Value: {value}"); break; case NewExpression newExpr: Console.WriteLine($"[ExprTree] {childIndent}├─ Constructor: {newExpr.Constructor.DeclaringType.Name}"); if (newExpr.Arguments.Count > 0) { Console.WriteLine($"[ExprTree] {childIndent}├─ Arguments ({newExpr.Arguments.Count}):"); for (int i = 0; i < newExpr.Arguments.Count; i++) { Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Arg[{i}]:"); DebugPrintExpressionTree(newExpr.Arguments[i], childIndent + "│ │ ", false); } } break; case LambdaExpression lambda: Console.WriteLine($"[ExprTree] {childIndent}├─ Parameters ({lambda.Parameters.Count}):"); for (int i = 0; i < lambda.Parameters.Count; i++) { var param = lambda.Parameters[i]; Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Param[{i}]: {param.Name} ({param.Type.Name})"); } Console.WriteLine($"[ExprTree] {childIndent}├─ Body:"); DebugPrintExpressionTree(lambda.Body, childIndent + "│ ", false); break; case MemberExpression member: Console.WriteLine($"[ExprTree] {childIndent}├─ Member: {member.Member.Name}"); Console.WriteLine($"[ExprTree] {childIndent}├─ Expression:"); DebugPrintExpressionTree(member.Expression, childIndent + "│ ", false); break; case BlockExpression block: Console.WriteLine($"[ExprTree] {childIndent}├─ Variables ({block.Variables.Count}):"); for (int i = 0; i < block.Variables.Count; i++) { var variable = block.Variables[i]; Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Var[{i}]: {variable.Name} ({variable.Type.Name})"); } Console.WriteLine($"[ExprTree] {childIndent}├─ Expressions ({block.Expressions.Count}):"); for (int i = 0; i < block.Expressions.Count; i++) { Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Expr[{i}]:"); DebugPrintExpressionTree(block.Expressions[i], childIndent + "│ │ ", false); } break; case ConditionalExpression conditional: Console.WriteLine($"[ExprTree] {childIndent}├─ Test:"); DebugPrintExpressionTree(conditional.Test, childIndent + "│ ", false); Console.WriteLine($"[ExprTree] {childIndent}├─ IfTrue:"); DebugPrintExpressionTree(conditional.IfTrue, childIndent + "│ ", false); Console.WriteLine($"[ExprTree] {childIndent}├─ IfFalse:"); DebugPrintExpressionTree(conditional.IfFalse, childIndent + "│ ", false); break; } } #endregion #region Public methods for obtaining compiled delegates /// /// Gets a compiled delegate for processing a template string. /// /// The template string containing ${...} placeholders. /// Optional context identifier for cache isolation. When provided, the cache key is scoped to this context. /// A compiled function that resolves the template against an . public static Func GetCompiledTemplate(string template, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(template, nameof(template)); var cacheKey = BuildCacheKey(contextId, template); DebugLog($"Requesting compiled template: '{template}' (key: '{cacheKey}')"); if (_templateCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _templateHits); DebugLog($" Template found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _templateMisses); DebugLog($" Compiling new template: '{template}'"); var compiled = _templateCache.GetOrAdd(cacheKey, _ => CompileTemplateString(template)); DebugLog($" Template compiled and added to cache: '{cacheKey}'"); return compiled; } /// /// Gets a compiled delegate for resolving properties. /// /// The property expression string. /// Optional context identifier for cache isolation. /// A compiled function that resolves a property value from a source object and expression. public static Func GetCompiledPropertyResolver(string expression, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(expression, nameof(expression)); var cacheKey = BuildCacheKey(contextId, expression); DebugLog($"Requesting compiled property resolver: '{expression}' (key: '{cacheKey}')"); if (_propertyResolverCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _propertyResolverHits); DebugLog($" Property resolver found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _propertyResolverMisses); DebugLog($" Compiling new property resolver: '{expression}'"); var compiled = _propertyResolverCache.GetOrAdd(cacheKey, _ => CompilePropertyResolver(expression)); DebugLog($" Property resolver compiled and added to cache: '{cacheKey}'"); return compiled; } /// /// Gets a compiled delegate for obtaining values from an exchange. /// /// The value expression string. /// Optional context identifier for cache isolation. /// A compiled function that extracts a value from an . public static Func GetCompiledValueExpression(string expression, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(expression, nameof(expression)); DebugLog($"Requesting compiled value expression: '{expression}'"); // For expressions with postfix operations, always use the AST parser if (PostfixIncrementDecrementRegex.IsMatch(expression) || PrefixIncrementDecrementRegex.IsMatch(expression)) { DebugLog($"Increment/decrement operation detected, using AST parser: '{expression}'"); return GetCompiledValueExpressionWithAst(expression, contextId); } var cacheKey = BuildCacheKey(contextId, expression); if (_valueExpressionCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _valueExpressionHits); DebugLog($" Value expression found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _valueExpressionMisses); DebugLog($" Compiling new value expression: '{expression}'"); var compiled = _valueExpressionCache.GetOrAdd(cacheKey, _ => CompileValueExpression(expression)); DebugLog($" Value expression compiled and added to cache: '{cacheKey}'"); return compiled; } /// /// Gets a compiled delegate for obtaining values using the AST parser. /// /// The value expression string. /// Optional context identifier for cache isolation. /// A compiled function that extracts a value from an via AST compilation. public static Func GetCompiledValueExpressionWithAst(string expression, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(expression, nameof(expression)); var cacheKey = BuildCacheKey(contextId, "ast:" + expression); DebugLog($"Requesting compiled value expression with AST: '{expression}' (key: '{cacheKey}')"); if (_valueExpressionCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _valueExpressionHits); DebugLog($" Value expression with AST found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _valueExpressionMisses); DebugLog($" Compiling new value expression with AST: '{expression}'"); var compiled = _valueExpressionCache.GetOrAdd(cacheKey, _ => CompileExpressionWithAst(expression)); DebugLog($" Value expression with AST compiled and added to cache: '{cacheKey}'"); return compiled; } #endregion #region Core public methods /// /// Processes a template using a cached compiled delegate. /// /// The template string containing ${...} placeholders. /// The exchange to resolve values from. /// Optional context identifier for cache isolation. If null, uses exchange.RouteId when available. /// The resolved template string, or the original template if processing fails. public static string ProcessTemplate(string template, IExchange exchange, string? contextId = null) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); DebugLog($"Processing template: '{template}'"); if (string.IsNullOrEmpty(template)) return template; contextId ??= exchange.RouteId; var compiledTemplate = GetCompiledTemplate(template, contextId); try { // Apply the template to get the result var result = compiledTemplate(exchange); DebugLog($"Template processing result: '{result}'"); return result; } catch (Exception ex) when (ex is not ExpressionSandboxViolationException) { // Runtime resolution error — log and rethrow so ErrorHandler can handle it _logger?.LogWarning(ex, "Expression resolution error in template '{Template}'", template); DebugLog($"Template processing error: {ex.Message}"); throw; } } /// /// Resolves a template with type preservation for single expressions. /// If the template is a single ${expr} with no surrounding text, /// resolves via preserving the CLR type (Guid, DateTimeOffset, int, etc.). /// Composite templates (e.g. prefix-${x}-suffix) fall back to returning a string. /// public static object? ResolveTypedOrTemplate(string template, IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); if (string.IsNullOrEmpty(template)) return null; if (TryGetSinglePlaceholder(template, out var placeholder)) { // A whole-string placeholder keeps the CLR type of its value; the shared placeholder // pipeline replaced the private ResolveExpression ladder here on 2026-08-28. return GetCompiledPlaceholder(placeholder)(exchange); } return ProcessTemplate(template, exchange); } #endregion #region Cache management /// /// Clears all caches and resets metric counters. /// public static void ClearAllCaches() { _templateCache.Clear(); _propertyResolverCache.Clear(); _valueExpressionCache.Clear(); // Reset counters System.Threading.Interlocked.Exchange(ref _templateHits, 0); System.Threading.Interlocked.Exchange(ref _templateMisses, 0); System.Threading.Interlocked.Exchange(ref _propertyResolverHits, 0); System.Threading.Interlocked.Exchange(ref _propertyResolverMisses, 0); System.Threading.Interlocked.Exchange(ref _valueExpressionHits, 0); System.Threading.Interlocked.Exchange(ref _valueExpressionMisses, 0); } /// /// Clears the template cache. /// public static void ClearTemplateCache() { _templateCache.Clear(); } /// /// Clears the property resolver cache. /// public static void ClearPropertyResolverCache() { _propertyResolverCache.Clear(); } /// /// Clears the value expression cache. /// public static void ClearValueExpressionCache() { _valueExpressionCache.Clear(); } /// /// Clears all cache entries belonging to the specified context. /// Removes entries whose keys start with "{contextId}:" from all caches. /// /// The context identifier whose cached entries should be removed. public static void ClearCachesForContext(string contextId) { ArgumentException.ThrowIfNullOrEmpty(contextId, nameof(contextId)); var prefix = contextId + ":"; RemoveByPrefix(_templateCache, prefix); RemoveByPrefix(_propertyResolverCache, prefix); RemoveByPrefix(_valueExpressionCache, prefix); } private static void RemoveByPrefix(ConcurrentDictionary cache, string prefix) { foreach (var key in cache.Keys) { if (key.StartsWith(prefix, StringComparison.Ordinal)) cache.TryRemove(key, out _); } } /// /// Returns cache statistics with performance metrics. /// /// A record containing counts, hits, and misses for each cache. public static CacheStatistics GetCacheStatistics() { return new CacheStatistics { TemplateCount = _templateCache.Count, TemplateHits = System.Threading.Interlocked.Read(ref _templateHits), TemplateMisses = System.Threading.Interlocked.Read(ref _templateMisses), PropertyResolverCount = _propertyResolverCache.Count, PropertyResolverHits = System.Threading.Interlocked.Read(ref _propertyResolverHits), PropertyResolverMisses = System.Threading.Interlocked.Read(ref _propertyResolverMisses), ValueExpressionCount = _valueExpressionCache.Count, ValueExpressionHits = System.Threading.Interlocked.Read(ref _valueExpressionHits), ValueExpressionMisses = System.Threading.Interlocked.Read(ref _valueExpressionMisses) }; } #endregion #region Initialization /// /// Sets the console output encoding to UTF-8. /// public static void SetUtf8Output() { Console.OutputEncoding = System.Text.Encoding.UTF8; DebugLog("Console output encoding set to UTF-8"); } /// /// Initializes the environment with UTF-8 output and optional debug mode. /// /// true to enable debug logging; defaults to true. public static void Initialize(bool enableDebug = true) { SetDebugMode(enableDebug); SetUtf8Output(); DebugLog("ExpressionResolver initialized"); } #endregion } /// /// Cache statistics with performance metrics for each expression cache. /// public record CacheStatistics { /// Number of entries in the template cache. public int TemplateCount { get; init; } /// Number of template cache hits. public long TemplateHits { get; init; } /// Number of template cache misses. public long TemplateMisses { get; init; } /// Template cache hit rate as a percentage. public double TemplateHitRate => TemplateHits + TemplateMisses > 0 ? (double)TemplateHits / (TemplateHits + TemplateMisses) * 100 : 0; /// Number of entries in the property resolver cache. public int PropertyResolverCount { get; init; } /// Number of property resolver cache hits. public long PropertyResolverHits { get; init; } /// Number of property resolver cache misses. public long PropertyResolverMisses { get; init; } /// Property resolver cache hit rate as a percentage. public double PropertyResolverHitRate => PropertyResolverHits + PropertyResolverMisses > 0 ? (double)PropertyResolverHits / (PropertyResolverHits + PropertyResolverMisses) * 100 : 0; /// Number of entries in the value expression cache. public int ValueExpressionCount { get; init; } /// Number of value expression cache hits. public long ValueExpressionHits { get; init; } /// Number of value expression cache misses. public long ValueExpressionMisses { get; init; } /// Value expression cache hit rate as a percentage. public double ValueExpressionHitRate => ValueExpressionHits + ValueExpressionMisses > 0 ? (double)ValueExpressionHits / (ValueExpressionHits + ValueExpressionMisses) * 100 : 0; /// Total number of entries across all caches. public int TotalCount => TemplateCount + PropertyResolverCount + ValueExpressionCount; /// Total number of cache hits across all caches. public long TotalHits => TemplateHits + PropertyResolverHits + ValueExpressionHits; /// Total number of cache misses across all caches. public long TotalMisses => TemplateMisses + PropertyResolverMisses + ValueExpressionMisses; /// Overall cache hit rate as a percentage. public double TotalHitRate => TotalHits + TotalMisses > 0 ? (double)TotalHits / (TotalHits + TotalMisses) * 100 : 0; } /// /// Exception thrown when an expression fails to compile. /// public class ExpressionCompilationException : Exception { /// /// Initializes a new instance of the class with a message. /// /// The error message. public ExpressionCompilationException(string message) : base(message) { } /// /// Initializes a new instance of the class with a message and inner exception. /// /// The error message. /// The inner exception that caused this failure. public ExpressionCompilationException(string message, Exception innerException) : base(message, innerException) { } } Path: redb-route/redb.Route/Expressions/ExpressionSandbox.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/Expressions/ExpressionSandbox.cs ---- namespace redb.Route.Expressions; /// /// Restricts what an expression may do while the scope is open: no method invocation through /// reflection on the objects an expression reaches. Built-in functions and the string helpers /// (contains, substring, length, ...) stay available. Opened by hosts that /// evaluate expressions written as data — a payload template's expr() and its arguments — /// so a template can read members but never run code. Flows with the async context and nests. /// public static class ExpressionSandbox { private static readonly AsyncLocal Depth = new(); /// Whether a sandbox scope is open on the current flow. public static bool IsActive => Depth.Value > 0; /// Opens a scope; dispose the result to leave it. public static IDisposable Enter() { Depth.Value++; return new Scope(); } private sealed class Scope : IDisposable { private bool _left; public void Dispose() { if (_left) return; _left = true; Depth.Value--; } } } Path: redb-route/redb.Route/Expressions/ExpressionSandboxViolationException.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/Expressions/ExpressionSandboxViolationException.cs ---- namespace redb.Route.Expressions; /// /// Thrown when an expression tries to run code or read outside the message while an /// scope is open: a method call, a registry object (ref:name) or an environment variable (env:NAME). /// public sealed class ExpressionSandboxViolationException : InvalidOperationException { private const string Where = "the expression runs in a sandbox (a template argument or expr())"; /// Creates the exception for on . public ExpressionSandboxViolationException(string methodName, Type type) : base($"Method '{methodName}' on {type.Name} cannot be called here: {Where}, where objects expose their members but never code.") { MethodName = methodName; Written = methodName; TargetType = type; } /// /// Creates the exception for a read the sandbox refuses, named as written: ref:rules (an object of the /// registry) or env:HOME (the process environment). No method is involved, so the message names the spelling. /// /// The spelling as the expression writes it. public ExpressionSandboxViolationException(string written) : base($"'{written}' cannot be read here: {Where}, which reads the message and its values, not the registry or the process environment.") { ArgumentException.ThrowIfNullOrWhiteSpace(written); MethodName = written; Written = written; } /// The method the expression tried to call; for a refused read, the spelling (). public string MethodName { get; } /// What the expression wrote: the method name, or the spelling of a read (ref:rules, env:HOME). public string Written { get; } /// The type the method was looked up on; null for a refused read, which calls no method. public Type? TargetType { get; } } Path: redb-route/redb.Route/Expressions/ExpressionValues.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/Expressions/ExpressionValues.cs ---- using System; using System.Collections.Generic; using System.Linq; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Adapters that let an stand where an EIP asks for a delegate. /// /// /// Six EIPs — Aggregate, RecipientList, DynamicRouter, IdempotentConsumer, Enrich and PollEnrich — /// were typed on alone, so a route author who wanted a correlation /// key out of an XML body had to write the wrapper by hand: /// e => XPath("/order/id").Evaluate<string>(e). Wrapping is not the problem; writing /// it once per call site is, because each hand-rolled wrapper decides on its own what an expression /// that matched nothing means. These adapters make that decision once, in one place, so every EIP /// answers the same way — and so a language added later inherits the answer instead of restating it. /// internal static class ExpressionValues { internal const string DefaultUriDelimiter = ","; /// /// Resolves what a query language should read: the message body by default, or whatever the /// route named as the source. /// /// /// Kept here rather than in each language so that a language added later inherits the rule /// instead of restating it. Camel spells the source as a string prefix on each language /// (header:payload); an ordinary expression is better, because a typo in /// header.payloadd is then a parse the route can check rather than a string nobody read. /// internal static object? ReadInput(IExpression? source, IExchange exchange) => source is null ? exchange.In.getBody() : source.Evaluate(exchange); /// /// The message a language gives when it has nothing to read — which is a different situation /// depending on whether the route pointed it somewhere. /// internal static string NoInput(bool fromSource, string language) => fromSource ? $"The source expression produced no value, so there is nothing for the {language} " + "expression to read." : $"Exchange body is null. Cannot evaluate {language} expression."; /// /// Adapts an expression to a delegate for a position where a missing value has no sensible /// reading — a correlation key, an idempotency key, an endpoint URI. /// /// /// A query that matched nothing yields nothing, and the alternatives are all worse than /// failing: an empty key silently merges unrelated messages into one aggregate, and an empty /// URI reaches the endpoint resolver as a parse error far from its cause. /// internal static Func Required(IExpression expression, string eip) { ArgumentNullException.ThrowIfNull(expression); return exchange => { var value = expression.Evaluate(exchange); if (string.IsNullOrEmpty(value)) throw new InvalidOperationException( $"{eip}: the expression produced no value for this exchange, and {eip} cannot " + "proceed without one. A path that matched nothing yields nothing — guard the " + "route with a condition, or give the expression a fallback."); return value; }; } /// /// Adapts an expression to a delegate for a position where "no value" is itself an answer. /// /// /// Dynamic Router asks for the next hop and reads null as "no more hops", so an /// expression that matched nothing ends the routing rather than failing it. /// internal static Func Optional(IExpression expression) { ArgumentNullException.ThrowIfNull(expression); return exchange => expression.Evaluate(exchange); } /// /// Adapts an expression to a list of endpoint URIs, accepting either a sequence or a single /// delimited string — the two shapes an expression naturally produces. /// /// /// XPath("/order/recipients/uri") over several nodes gives a sequence; /// Header("recipients") gives "direct:a,direct:b". Both mean the same list, and /// which one arrives is a property of the body rather than of the route, so both are read. /// This mirrors RoutingSlip(IExpression, uriDelimiter), which already made that choice. /// internal static Func> UriList(IExpression expression, string uriDelimiter) { ArgumentNullException.ThrowIfNull(expression); var delimiter = string.IsNullOrEmpty(uriDelimiter) ? DefaultUriDelimiter : uriDelimiter; return exchange => Flatten(expression.Evaluate(exchange), delimiter); } private static IEnumerable Flatten(object? value, string delimiter) => value switch { null => [], // Checked before the sequence cases: a string is a sequence of characters, not of URIs. string text => Split(text, delimiter), IEnumerable many => Clean(many), IEnumerable many => Clean(many.Select(item => item?.ToString())), _ => Split(value.ToString(), delimiter) }; private static IEnumerable Split(string? text, string delimiter) => string.IsNullOrWhiteSpace(text) ? [] : text.Split(delimiter, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); private static IEnumerable Clean(IEnumerable values) => values.Where(uri => !string.IsNullOrWhiteSpace(uri)).Select(uri => uri!.Trim()); } Path: redb-route/redb.Route/Expressions/FileHeaderFacts.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/Expressions/FileHeaderFacts.cs ---- using System; using System.Collections.Generic; using System.Globalization; namespace redb.Route.Expressions; /// /// The file facts of a message: the redbFile.* headers a file consumer sets. The names are redb.Route.File's /// FileHeaders, written out because the core does not reference that package. The extension header holds a /// leading dot (.xml); the fact is without it, as in Camel. /// internal sealed class FileHeaderFacts(IDictionary headers) : IFileFacts { public string? Name => Text("redbFile.Name"); public string? NameOnly => Text("redbFile.NameOnly"); public string? Extension => FileLanguage.WithoutDot(Text("redbFile.Extension")); public string? Parent => Text("redbFile.Parent"); public string? AbsolutePath => Text("redbFile.AbsolutePath"); public string? RelativePath => Text("redbFile.RelativePath"); public long? Length => Read("redbFile.Length") switch { long l => l, int i => i, string s when long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) => parsed, _ => null, }; public DateTimeOffset? LastModified => Read("redbFile.LastModified") switch { DateTimeOffset d => d, DateTime d => new DateTimeOffset(d), string s when DateTimeOffset.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed) => parsed, _ => null, }; private object? Read(string header) => headers.TryGetValue(header, out var value) ? value : null; private string? Text(string header) => Read(header) is { } value ? ExpressionResolver.TemplateText(value) : null; } Path: redb-route/redb.Route/Expressions/FileLanguage.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/Expressions/FileLanguage.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace redb.Route.Expressions; /// What a key of the file language means: one fact about a file. public enum FileFact { /// The file name with its extension. Name, /// The file name without its extension. NameOnly, /// The extension, without the leading dot. Extension, /// The directory that holds the file. Parent, /// The full path of the file. AbsolutePath, /// The path of the file relative to the directory the consumer polls. RelativePath, /// The size in bytes. Length, /// The last write time. LastModified, } /// /// The facts about one file that the file language reads. Each source of files supplies its own: the expression /// engine reads the redbFile.* headers of the message, a file consumer the file it is handling, the S3 consumer /// the object key. A fact the source does not know is null. /// public interface IFileFacts { /// The file name with its extension. string? Name { get; } /// The file name without its extension. string? NameOnly { get; } /// The extension, without the leading dot (xml). string? Extension { get; } /// The directory that holds the file. string? Parent { get; } /// The full path of the file. string? AbsolutePath { get; } /// The path relative to the polled directory. string? RelativePath { get; } /// The size in bytes. long? Length { get; } /// The last write time. DateTimeOffset? LastModified { get; } } /// /// Apache Camel's file language: ${file:name}, ${file:name.noext} and the other keys. One table of keys /// and one resolver serve the expression engine and the components that substitute file keys in their own options /// (moveTo, doneFileName and the like), so a key means the same thing in both. /// /// The expression engine matches keys with , as Camel does; component options /// match with , where ${FILE:NAME} has always worked. /// /// public static class FileLanguage { /// The keys, in the order an error lists them, and the fact each one reads. public static IReadOnlyList> Keys { get; } = [ new("name", FileFact.Name), new("onlyname", FileFact.Name), new("name.noext", FileFact.NameOnly), new("onlyname.noext", FileFact.NameOnly), new("ext", FileFact.Extension), new("name.ext", FileFact.Extension), new("parent", FileFact.Parent), new("path", FileFact.AbsolutePath), new("absolute.path", FileFact.AbsolutePath), new("relative.path", FileFact.RelativePath), new("length", FileFact.Length), new("size", FileFact.Length), new("modified", FileFact.LastModified), ]; private static readonly Regex OrdinalPlaceholder = new(@"\$\{file:(?[^}]*)\}", RegexOptions.Compiled); private static readonly Regex IgnoreCasePlaceholder = new(@"\$\{(?i:file):(?[^}]*)\}", RegexOptions.Compiled); /// The fact a key reads; false when the key is not one of . /// The key as written after file:; surrounding spaces are ignored. /// or . /// The fact, when the key is known. public static bool TryGetFact(string key, StringComparison comparison, out FileFact fact) { ArgumentNullException.ThrowIfNull(key); CheckComparison(comparison); var trimmed = key.Trim(); foreach (var (name, meaning) in Keys) if (string.Equals(name, trimmed, comparison)) { fact = meaning; return true; } fact = default; return false; } /// The value of one fact: a string, a length or a . public static object? Value(FileFact fact, IFileFacts facts) { ArgumentNullException.ThrowIfNull(facts); return fact switch { FileFact.Name => facts.Name, FileFact.NameOnly => facts.NameOnly, FileFact.Extension => facts.Extension, FileFact.Parent => facts.Parent, FileFact.AbsolutePath => facts.AbsolutePath, FileFact.RelativePath => facts.RelativePath, FileFact.Length => facts.Length, FileFact.LastModified => facts.LastModified, _ => throw new ArgumentOutOfRangeException(nameof(fact), fact, null), }; } /// The value a key reads from . /// The key is not one of ; the message lists them. public static object? Resolve(string key, IFileFacts facts, StringComparison comparison) => TryGetFact(key, comparison, out var fact) ? Value(fact, facts) : throw new ArgumentException(UnknownKeyMessage(key), nameof(key)); /// /// Replaces every ${file:key} in with the value it reads, written as a template /// writes it (numbers and dates culture-invariant); a fact the source does not know writes nothing. /// /// A key is not one of . public static string Substitute(string pattern, IFileFacts facts, StringComparison comparison) { ArgumentNullException.ThrowIfNull(pattern); ArgumentNullException.ThrowIfNull(facts); if (!pattern.Contains("${", StringComparison.Ordinal)) return pattern; return Placeholder(comparison).Replace(pattern, m => ExpressionResolver.TemplateText(Resolve(m.Groups["key"].Value, facts, comparison))); } /// /// The first key in that is not one of , or null when every /// ${file:key} in it is known. A component calls it when its endpoint is created. /// public static string? FindUnknownKey(string pattern, StringComparison comparison) { ArgumentNullException.ThrowIfNull(pattern); if (!pattern.Contains("${", StringComparison.Ordinal)) return null; return Placeholder(comparison).Matches(pattern) .Select(m => m.Groups["key"].Value) .FirstOrDefault(key => !TryGetFact(key, comparison, out _)); } /// An extension as the file language gives it: without the leading dot (.xml is xml). public static string? WithoutDot(string? extension) => extension is not null && extension.StartsWith('.') ? extension[1..] : extension; /// The words of the error for a key that is not one of . public static string UnknownKeyMessage(string key) => $"'{key.Trim()}' is not a file key; the keys are {string.Join(", ", Keys.Select(k => k.Key))}."; private static Regex Placeholder(StringComparison comparison) { CheckComparison(comparison); return comparison == StringComparison.Ordinal ? OrdinalPlaceholder : IgnoreCasePlaceholder; } private static void CheckComparison(StringComparison comparison) { if (comparison is not (StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase)) throw new ArgumentOutOfRangeException(nameof(comparison), comparison, "The file language compares keys with Ordinal (the expression engine) or OrdinalIgnoreCase (component options)."); } } Path: redb-route/redb.Route/Expressions/HeaderExpression.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/Expressions/HeaderExpression.cs ---- using System; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Expression for accessing message headers in an . /// /// /// Allows extracting message header values /// for use in predicates and routing logic. /// public class HeaderExpression : Expression { private readonly string _headerName; /// /// Initializes a new instance of the class. /// /// The header name (case-sensitive). /// Thrown when is null. public HeaderExpression(string headerName) { _headerName = headerName ?? throw new ArgumentNullException(nameof(headerName)); } /// /// Thrown when is null. /// Thrown when the header type is not compatible with . /// Thrown when the header is not found. public override T Evaluate(IExchange exchange) { if (exchange == null) throw new ArgumentNullException(nameof(exchange)); return exchange.In.getHeader(_headerName); } /// /// Thrown when is null. public override void SetValue(IExchange exchange, object value) { if (exchange == null) throw new ArgumentNullException(nameof(exchange)); exchange.In.setHeader(_headerName, value); } /// public override string ToTemplateString() => $"${{header.{_headerName}}}"; } Path: redb-route/redb.Route/Expressions/JsonPathExpression.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/Expressions/JsonPathExpression.cs ---- using System.Globalization; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Json.Path; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// Expression for evaluating JSONPath (RFC 9535, JsonPath.Net) queries against the message body. /// /// /// Accepts JSON text, byte[], , a System.Text.Json tree (, /// , ) or a POCO (serialized with its C# member names). /// JSON text may contain comments and trailing commas. Results convert to the requested type the way /// they always did: a scalar to , an array to a typed CLR array / list, an object /// to a POCO or dictionary, anything to string as its text (compact JSON for arrays and objects, /// invariant culture for numbers). Dates stay strings unless a is asked for. /// public class JsonPathExpression : Expression { private static readonly JsonDocumentOptions LenientText = new() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; private static readonly JsonSerializerOptions PocoOptions = new(); // C# member names, as JToken.FromObject kept them private static readonly PathParsingOptions ParsingOptions = new() { AllowMathOperations = true, AllowInOperator = true, AllowJsonConstructs = true, TolerateExtraWhitespace = true }; private readonly string _jsonPath; private readonly JsonPath _compiled; private readonly bool _isFilter; private readonly IExpression? _source; /// /// Initializes a new instance of the class. /// /// The JSONPath expression used to extract data. /// /// What to run the path against. null — the default — means the message body. /// /// Thrown when is null. /// Thrown when the path does not parse (so a route fails at build, not on the first message). public JsonPathExpression(string jsonPath, IExpression? source = null) { _source = source; _jsonPath = jsonPath ?? throw new ArgumentNullException(nameof(jsonPath)); try { _compiled = JsonPath.Parse(jsonPath, ParsingOptions); } catch (PathParseException ex) { throw new ArgumentException($"Invalid JSONPath '{jsonPath}': {ex.Message}", nameof(jsonPath), ex); } _isFilter = jsonPath.Contains("[?", StringComparison.Ordinal); } /// The JSONPath text. public string Path => _jsonPath; /// /// Returns the same expression reading instead of the message body. /// /// /// JPath("$.id").From(Property("original-payload")). Without it, querying JSON that /// arrived in a header or property means moving it into the body first, which damages the body /// for the rest of the route. /// /// The expression producing the JSON to read. /// A new expression; this one is unchanged. public JsonPathExpression From(IExpression source) { ArgumentNullException.ThrowIfNull(source); return new JsonPathExpression(_jsonPath, source); } /// /// Thrown when the body is not JSON or the value cannot be converted. public override T Evaluate(IExchange exchange) => EvaluateOn(ExpressionValues.ReadInput(_source, exchange), _source is not null); /// /// Runs the path against an already-resolved input. Used by the expression language, where the /// source arrives as a value rather than as an expression. /// internal T EvaluateOn(object? input, bool fromSource) { var body = input; if (body is null) throw new InvalidOperationException(ExpressionValues.NoInput(fromSource, "JsonPath")); JsonNode? root; try { root = JsonPathValues.ToNode(body, LenientText, PocoOptions); } catch (JsonException ex) { throw new InvalidOperationException($"JSON parsing error in JsonPathExpression: {ex.Message}", ex); } var matches = _compiled.Evaluate(root).Matches; var nodes = matches is null ? [] : matches.Select(m => m.Value).ToList(); try { return _compiled.IsSingular ? JsonPathValues.ConvertSingle(nodes.Count == 0 ? null : nodes[0], _jsonPath) : JsonPathValues.ConvertMany(nodes, _jsonPath, _isFilter); } catch (InvalidOperationException) { throw; } catch (Exception ex) when (ex is InvalidCastException or FormatException or JsonException or OverflowException) { throw new InvalidOperationException($"Error evaluating JsonPath '{_jsonPath}': {ex.Message}", ex); } } /// /// Always thrown because does not support setting values. public override void SetValue(IExchange exchange, object value) { throw new NotSupportedException("JsonPathExpression does not support setting values."); } /// public override string ToTemplateString() => $"${{jsonpath({_jsonPath})}}"; } /// Body → tree and node → CLR conversions of , kept apart so the rules read in one place. internal static class JsonPathValues { public static JsonNode? ToNode(object body, JsonDocumentOptions lenient, JsonSerializerOptions pocoOptions) => body switch { JsonNode node => node, JsonElement element => JsonSerializer.SerializeToNode(element), JsonDocument document => JsonSerializer.SerializeToNode(document.RootElement), string text => JsonNode.Parse(text, documentOptions: lenient), byte[] bytes => JsonNode.Parse(bytes, documentOptions: lenient), Stream stream => ParseStream(stream, lenient), _ => JsonSerializer.SerializeToNode(body, pocoOptions), }; /// /// A stream body is read from its current position and left there afterwards, so a second /// expression on the same exchange (or a redelivery) sees the same JSON. A stream that cannot seek /// is consumed — there is nothing to restore. /// private static JsonNode? ParseStream(Stream stream, JsonDocumentOptions lenient) { if (!stream.CanSeek) return JsonNode.Parse(stream, documentOptions: lenient); var position = stream.Position; try { return JsonNode.Parse(stream, documentOptions: lenient); } finally { stream.Position = position; } } /// A singular path: one node or nothing (the old SelectToken branch). public static T ConvertSingle(JsonNode? node, string path) { if (node is null) { if (IsNonNullableValueType()) throw new InvalidOperationException($"No value found for JsonPath: {path}"); return default!; } return (T)ConvertNode(node, typeof(T), path)!; } /// A non-singular path (wildcard, descent, slice, filter): the old SelectTokens branch. public static T ConvertMany(List nodes, string path, bool isFilter) { if (isFilter && typeof(T) == typeof(bool)) return (T)(object)(nodes.Count > 0); // A single scalar match unwraps — unless the caller asked for a collection, which keeps the array shape. if (nodes.Count == 1 && nodes[0] is JsonValue single && !IsCollectionType(typeof(T))) return (T)ConvertNode(single, typeof(T), path)!; if (nodes.Count > 0) { var array = new JsonArray(nodes.Select(n => n?.DeepClone()).ToArray()); if (typeof(T) == typeof(string)) return (T)(object)(nodes.All(n => n is null or JsonValue) ? string.Join(", ", nodes.Select(n => Text(n))) : array.ToJsonString()); return (T)ConvertNode(array, typeof(T), path)!; } if (IsNonNullableValueType()) throw new InvalidOperationException($"No values found for JsonPath: {path}"); return default!; } private static object? ConvertNode(JsonNode? node, Type target, string path) { if (node is null) { if (target.IsValueType && Nullable.GetUnderlyingType(target) is null) throw new InvalidOperationException($"JsonPath returned null but type {target.Name} is not nullable"); return null; } if (target == typeof(JsonNode) || target == node.GetType()) return node; switch (node) { case JsonArray array: if (target == typeof(string)) return array.ToJsonString(); if (target == typeof(object) || target == typeof(object[])) return TypedArray(array, target == typeof(object[])); return array.Deserialize(target) ?? throw new InvalidOperationException($"Cannot convert JsonPath '{path}' array to {target.Name}"); case JsonObject obj: if (target == typeof(object)) return obj; if (target == typeof(string)) return obj.ToJsonString(); return obj.Deserialize(target) ?? throw new InvalidOperationException($"Cannot convert JsonPath '{path}' object to {target.Name}"); case JsonValue value: var primitive = Primitive(value); if (primitive is null) { if (target.IsValueType && Nullable.GetUnderlyingType(target) is null) throw new InvalidOperationException($"JsonPath returned null but type {target.Name} is not nullable"); return null; } var effective = Nullable.GetUnderlyingType(target) ?? target; if (effective == typeof(object) || effective.IsInstanceOfType(primitive)) return primitive; if (effective == typeof(string)) return Text(value); if (effective == typeof(DateTimeOffset)) return DateTimeOffset.Parse(Text(value), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); if (effective == typeof(DateTime)) return DateTime.Parse(Text(value), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); if (effective == typeof(Guid)) return Guid.Parse(Text(value)); if (effective.IsEnum) return Enum.Parse(effective, Text(value), ignoreCase: true); return RouteDecimal.ChangeType(primitive, effective, CultureInfo.InvariantCulture); } return node.Deserialize(target); } /// Homogeneous scalar arrays become typed CLR arrays (int[], string[], double[], bool[]); anything else object[]. private static object TypedArray(JsonArray array, bool forceObject) { var items = array.Select(n => n is JsonValue v ? Primitive(v) : n).ToArray(); if (forceObject || items.Length == 0 || items.Any(i => i is null or JsonNode)) return items; var elementType = items[0]!.GetType(); if (items.All(i => i!.GetType() == elementType)) { var kind = elementType == typeof(long) && items.All(i => (long)i! is >= int.MinValue and <= int.MaxValue) ? typeof(int) : elementType; var typed = Array.CreateInstance(kind, items.Length); for (var i = 0; i < items.Length; i++) typed.SetValue(kind == typeof(int) ? (object)(int)(long)items[i]! : items[i], i); return typed; } return items; } /// /// JSON scalar → CLR: strings stay strings, integers are long, other numbers double, /// booleans bool. A may be backed by a parsed element or by a CLR value /// the path engine produced (a double even for a whole number), so both backings are read. /// private static object? Primitive(JsonValue value) { if (value.TryGetValue(out var s)) return s; if (value.TryGetValue(out var b)) return b; if (value.TryGetValue(out var l)) return l; if (value.TryGetValue(out var i)) return (long)i; if (value.TryGetValue(out var d)) return d == Math.Floor(d) && Math.Abs(d) < 9.2e18 && !double.IsInfinity(d) ? (long)d : d; if (value.TryGetValue(out var m)) return m == decimal.Truncate(m) && Math.Abs(m) < 9.2e18m ? (long)m : (double)m; var element = value.GetValue(); return element.ValueKind switch { JsonValueKind.String => element.GetString(), JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Null => null, JsonValueKind.Number => element.TryGetInt64(out var el) ? el : element.GetDouble(), _ => element.GetRawText(), }; } private static string Text(JsonNode? node) => node switch { null => string.Empty, JsonValue value => Primitive(value) switch { null => string.Empty, string s => s, bool b => b ? "true" : "false", IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), var other => other.ToString() ?? string.Empty, }, _ => node.ToJsonString(), }; private static bool IsNonNullableValueType() => typeof(T).IsValueType && Nullable.GetUnderlyingType(typeof(T)) is null; private static bool IsCollectionType(Type type) => type != typeof(string) && (type.IsArray || typeof(System.Collections.IEnumerable).IsAssignableFrom(type)); } Path: redb-route/redb.Route/Expressions/ObjectKeyFacts.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/Expressions/ObjectKeyFacts.cs ---- namespace redb.Route.Expressions; /// /// The file facts of an object in an object store (S3, Firebase Storage), for the file keys in the options of their /// consumers. The name is the whole object key, as ${file:name} has always meant for S3 (in/a.csv waits /// for in/a.csv.done); the parent is the key prefix up to the last /. A key has no path of its own, so /// the path keys write nothing; the size and the time are the object's when the store gives them, otherwise nothing. /// internal sealed class ObjectKeyFacts(string objectKey, long? length = null, DateTimeOffset? lastModified = null) : IFileFacts { private int LastSlash => objectKey.LastIndexOf('/'); private int ExtensionDot => objectKey.LastIndexOf('.') is var dot && dot > LastSlash ? dot : -1; public string? Name => objectKey; public string? NameOnly => ExtensionDot < 0 ? objectKey : objectKey[..ExtensionDot]; public string? Extension => ExtensionDot < 0 ? "" : objectKey[(ExtensionDot + 1)..]; public string? Parent => LastSlash < 0 ? "" : objectKey[..LastSlash]; public string? AbsolutePath => null; public string? RelativePath => null; public long? Length => length; public DateTimeOffset? LastModified => lastModified; } Path: redb-route/redb.Route/Expressions/PlaceholderExpression.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/Expressions/PlaceholderExpression.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// A text with {{key}} / {{key:default}} placeholders, resolved through the route context's configuration /// (IConfiguration, then the context's properties) the way an endpoint URI is. The value a route sets from /// configuration: <setHeader name="x" value="{{ldap.user}}"/> in markup, new PlaceholderExpression("{{ldap.user}}") /// in C#. Resolved once per route context and then reused; a key with no value and no default fails the exchange with /// the same message an endpoint URI gives. /// public sealed class PlaceholderExpression : Expression { private (IRouteContext? Context, string Value)? _resolved; /// Creates the expression over . public PlaceholderExpression(string text) { ArgumentNullException.ThrowIfNull(text); Text = text; } /// The text as written, placeholders included. public string Text { get; } /// public override T Evaluate(IExchange exchange) { var value = Resolve(exchange.Context); if (value is T typed) return typed; return (T)RouteDecimal.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture); } /// The text with its placeholders resolved through ; without one, defaults only. public string Resolve(IRouteContext? context) { if (_resolved is { } cached && ReferenceEquals(cached.Context, context)) return cached.Value; var value = context is RouteContext live ? live.ResolvePlaceholders(Text) : PropertyPlaceholderResolver.Resolve(Text, _ => null); _resolved = (context, value); return value; } /// /// Always: a value from configuration is read-only. public override void SetValue(IExchange exchange, object value) => throw new NotSupportedException("A placeholder expression cannot be written to."); /// public override string ToTemplateString() => Text; } Path: redb-route/redb.Route/Expressions/PropertyExpression.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/Expressions/PropertyExpression.cs ---- using System; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Expression for accessing properties in an . /// /// /// Allows extracting exchange property values /// for use in predicates and routing logic. /// public class PropertyExpression : Expression { private readonly string _propertyName; /// /// Initializes a new instance of the class. /// /// The property name (case-sensitive). /// Thrown when is null. public PropertyExpression(string propertyName) { _propertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName)); } /// /// Thrown when is null. /// Thrown when the property type is not compatible with . /// Thrown when the property is not found. public override T Evaluate(IExchange exchange) { if (exchange == null) throw new ArgumentNullException(nameof(exchange)); return exchange.getProperty(_propertyName); } /// /// Thrown when is null. public override void SetValue(IExchange exchange, object value) { if (exchange == null) throw new ArgumentNullException(nameof(exchange)); exchange.setProperty(_propertyName, value); } /// public override string ToTemplateString() => $"${{property.{_propertyName}}}"; } Path: redb-route/redb.Route/Expressions/RegistryRefSite.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/Expressions/RegistryRefSite.cs ---- using System.Runtime.CompilerServices; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// One ref:name in a compiled expression: the object registered under that name. The expression is compiled /// once and shared by every context, so the object is looked up per route context, on the first evaluation there, as /// a bean: call resolves its bean (). A weak table keeps no context alive. Refused /// under , as bean: is. /// internal sealed class RegistryRefSite(string reference) { private readonly ConditionalWeakTable _resolved = new(); /// The registered object. public object Get(IExchange exchange) { var context = exchange.Context ?? throw new InvalidOperationException( $"ref:{reference}: the exchange has no route context, so there is no registry to find the object in."); if (ExpressionSandbox.IsActive) throw new ExpressionSandboxViolationException("ref:" + reference); return _resolved.GetValue(context, Resolve); } private object Resolve(IRouteContext context) => context.GetFromRegistry(reference) ?? throw new InvalidOperationException( $"ref:{reference}: '{reference}' is not in the context registry. " + "Register it with AddToRegistry or a declaration."); } Path: redb-route/redb.Route/Expressions/StringExpression.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/Expressions/StringExpression.cs ---- using System.Text.RegularExpressions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// Expression that evaluates a string expression template via . /// Supports ${...} template interpolation and raw expression strings. /// /// Unifies the two expression worlds: typed objects and string-based /// ${...} templates. Inherits all predicate methods from /// (isEqualTo, contains, isGreaterThan, etc.), so string expressions can be used anywhere /// an is expected. /// /// /// /// // In RouteBuilder: /// .SetBody(Expr("${header.source}")) /// .Filter(Expr("${header.amount}").isGreaterThan(1000)) /// .SetHeader("full", Expr("${header.first} ${header.last}")) /// /// /// public sealed class StringExpression : Expression { private readonly string _template; private readonly bool _isTemplate; private readonly Func? _compiledValue; private readonly Func? _compiledTemplate; /// /// Initializes a new instance with the specified expression template. /// /// /// Expression string. Can be a ${...} template (e.g. "${header.x} world") /// or a raw expression (e.g. "header.amount + 100"). /// public StringExpression(string template) { ArgumentException.ThrowIfNullOrEmpty(template, nameof(template)); _template = template; // Determine mode: template interpolation (contains ${...}) vs raw value expression. // A whole-string placeholder is a third case: it keeps the CLR type of its value, so // "${header.a}" with an int header yields the int, not "10". Mixed templates render text. _isTemplate = TemplateScanner.HasPlaceholder(template); if (_isTemplate && ExpressionResolver.TryGetSinglePlaceholder(template, out var placeholder)) { _isTemplate = false; _compiledValue = ExpressionResolver.GetCompiledPlaceholder(placeholder); } else if (_isTemplate) { _compiledTemplate = ExpressionResolver.GetCompiledTemplate(template); } else { _compiledValue = ExpressionResolver.GetCompiledValueExpression(template); } } /// Gets the original expression template string. public string Template => _template; /// public override T Evaluate(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); object? result; if (_isTemplate) { // "${header.x} world" → string interpolation result = _compiledTemplate!(exchange); } else { // "header.amount + 100" → value expression result = _compiledValue!(exchange); } if (result is null) return default!; if (result is T typed) return typed; // A whole-string placeholder keeps the CLR type; when the caller wants text it is rendered the // same way a hole in a mixed template is — culture-invariant, dates as ISO 8601. if (typeof(T) == typeof(string)) return (T)(object)ExpressionResolver.TemplateText(result); return (T)RouteDecimal.ChangeType(result, typeof(T), System.Globalization.CultureInfo.InvariantCulture); } /// /// String expressions are read-only — they compute a value but have no target to write to. /// /// Always thrown. public override void SetValue(IExchange exchange, object value) => throw new NotSupportedException( $"StringExpression '{_template}' is read-only. " + "Use Body(), Header(name), or Property(name) for settable expressions."); /// public override string ToString() => $"Expr(\"{_template}\")"; /// public override string ToTemplateString() => _template; } Path: redb-route/redb.Route/Expressions/TemplateScanner.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/Expressions/TemplateScanner.cs ---- namespace redb.Route.Expressions; /// /// Finds the ${...} holes of a template: the one reader every place that looks for them uses (the template /// compiler, , , the single-placeholder test, the /// pack gate). A hole closes at the } that balances its ${, so a hole may hold another one /// (${bean:svc.Check(${body})}) and a quoted literal may hold a } (${header.a == '}'}). /// /// A plain { does not nest and an empty ${} is no hole, as before. A quote that never ends inside a /// hole is read as a character, not as a literal (${header.O'Brien}). A ${ that nothing closes is an /// error: the expression was started, so it is a mistake (owner decision 2026-11-05); see . /// A literal ${ is written \${: an escape opens nothing and renders as ${. /// /// internal static class TemplateScanner { /// One hole: is the index of $, spans to the closing }. internal readonly record struct Hole(int Start, int Length) { /// The text between ${ and the closing }. public string InnerOf(string template) => template.Substring(Start + 2, Length - 3); } /// /// The holes of a template, the index of every ${ that nothing closes, and the index of every escape /// \${ (a literal ${ in the text). /// internal sealed record ScanResult(IReadOnlyList Holes, IReadOnlyList Unclosed, IReadOnlyList Escapes); /// /// The holes of , in order. Throws naming /// the position of the first ${ that nothing closes. /// internal static IReadOnlyList Holes(string template) { var scan = Scan(template); if (scan.Unclosed.Count > 0) throw new ExpressionCompilationException(Unclosed(template, scan.Unclosed[0])); return scan.Holes; } /// /// Whether starts at least one ${...}, closed or not: an unclosed one is a /// template too, and fails where it is compiled. /// internal static bool HasPlaceholder(string template) { if (!template.Contains("${", StringComparison.Ordinal)) return false; var scan = Scan(template); return scan.Holes.Count > 0 || scan.Unclosed.Count > 0 || scan.Escapes.Count > 0; } /// The message for a ${ at that nothing closes. internal static string Unclosed(string template, int index) => $"unclosed '${{' at position {index + 1} of \"{template}\": the placeholder has no closing '}}'."; /// Scans ; see the class remarks for the reading. internal static ScanResult Scan(string template) { ArgumentNullException.ThrowIfNull(template); var holes = new List(); var unclosed = new List(); var escapes = new List(); var i = 0; while (i < template.Length - 1) { // \${ is a literal ${ (findings register row 16): it opens nothing, and the compiler writes ${ in its place. if (template[i] == '\\' && i + 2 < template.Length && template[i + 1] == '$' && template[i + 2] == '{') { escapes.Add(i); i += 3; continue; } if (template[i] != '$' || template[i + 1] != '{') { i++; continue; } var close = Close(template, i, quotes: true) ?? Close(template, i, quotes: false); if (close is null) { unclosed.Add(i); break; } if (close.Value - i - 2 > 0) { holes.Add(new Hole(i, close.Value - i + 1)); i = close.Value + 1; } else { i++; } } return new ScanResult(holes, unclosed, escapes); } /// The index of the } that balances the ${ at , or null. private static int? Close(string template, int start, bool quotes) { var depth = 0; var j = start; while (j < template.Length) { var c = template[j]; if (c == '$' && j + 1 < template.Length && template[j + 1] == '{') { depth++; j += 2; continue; } if (c == '}') { depth--; if (depth == 0) return j; j++; continue; } if (quotes && (c == '\'' || c == '"')) { var endQuote = EndOfQuoted(template, j); if (endQuote < 0) return null; j = endQuote + 1; continue; } j++; } return null; } /// The index of the quote that ends the literal opened at , or -1. private static int EndOfQuoted(string template, int open) { var quote = template[open]; for (var j = open + 1; j < template.Length; j++) { if (template[j] == '\\') { j++; continue; } if (template[j] == quote) return j; } return -1; } } Path: redb-route/redb.Route/Expressions/Tokenizers/JsonArrayTokenizer.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/Expressions/Tokenizers/JsonArrayTokenizer.cs ---- using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; namespace redb.Route.Expressions.Tokenizers; /// /// Splits a JSON array body into individual elements, each as its JSON text. /// JSON text (, , byte[]) is read with /// ; any other body is taken as jpath takes it (a System.Text.Json tree, /// an array such as the object[] a jpath returns, or a POCO). /// internal static class JsonArrayTokenizer { // Element text as close to the source as the tree allows: non-ASCII stays as written, not \u-escaped. private static readonly JsonSerializerOptions ElementText = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; // C# member names, as jpath serializes a POCO body. private static readonly JsonSerializerOptions PocoOptions = new(); /// Tokenizes a JSON array body into individual raw-text elements. /// Exchange body: JSON text, a JSON tree, a CLR array or collection, or a POCO. /// Cancellation token. internal static async IAsyncEnumerable Tokenize( object? body, [EnumeratorCancellation] CancellationToken ct = default) { if (body is not (Stream or byte[] or string)) { if (body is null) throw new InvalidOperationException("SplitJsonArray: the body is null."); if (JsonPathValues.ToNode(body, default, PocoOptions) is not JsonArray array) throw new InvalidOperationException("SplitJsonArray: body is not a JSON array."); foreach (var element in array) { ct.ThrowIfCancellationRequested(); yield return element is null ? "null" : element.ToJsonString(ElementText); } yield break; } var stream = body switch { Stream s => s, byte[] b => new MemoryStream(b, writable: false), _ => new MemoryStream(Encoding.UTF8.GetBytes((string)body)), }; var ownsStream = body is not Stream; try { await foreach (var element in ReadArrayElementsAsync(stream, ct).ConfigureAwait(false)) { yield return element; } } finally { if (ownsStream) await stream.DisposeAsync().ConfigureAwait(false); } } private static async IAsyncEnumerable ReadArrayElementsAsync( Stream stream, [EnumeratorCancellation] CancellationToken ct) { using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: ct) .ConfigureAwait(false); if (doc.RootElement.ValueKind != JsonValueKind.Array) throw new InvalidOperationException("SplitJsonArray: body is not a JSON array."); foreach (var element in doc.RootElement.EnumerateArray()) { ct.ThrowIfCancellationRequested(); yield return element.GetRawText(); } } } Path: redb-route/redb.Route/Expressions/Tokenizers/LineTokenizer.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/Expressions/Tokenizers/LineTokenizer.cs ---- using System.Runtime.CompilerServices; using System.Text; namespace redb.Route.Expressions.Tokenizers; /// /// Splits body content into lines using a configurable separator. /// Supports , , and byte[] bodies. /// internal static class LineTokenizer { /// Tokenizes the body into individual lines. /// Exchange body (Stream, string, or byte[]). /// Line separator string. /// Whether to skip empty/whitespace lines. /// Cancellation token. internal static async IAsyncEnumerable Tokenize( object? body, string separator, bool skipEmpty, [EnumeratorCancellation] CancellationToken ct = default) { switch (body) { case Stream stream: using (var reader = new StreamReader(stream, leaveOpen: true)) { while (await reader.ReadLineAsync(ct).ConfigureAwait(false) is { } line) { if (skipEmpty && string.IsNullOrWhiteSpace(line)) continue; yield return line; } } break; case string str: foreach (var line in str.Split(separator)) { ct.ThrowIfCancellationRequested(); if (skipEmpty && string.IsNullOrWhiteSpace(line)) continue; yield return line; } break; case byte[] bytes: var text = Encoding.UTF8.GetString(bytes); foreach (var line in text.Split(separator)) { ct.ThrowIfCancellationRequested(); if (skipEmpty && string.IsNullOrWhiteSpace(line)) continue; yield return line; } break; } } } Path: redb-route/redb.Route/Expressions/Tokenizers/XmlTokenizer.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/Expressions/Tokenizers/XmlTokenizer.cs ---- using System.Runtime.CompilerServices; using System.Xml; namespace redb.Route.Expressions.Tokenizers; /// /// Splits XML body content by extracting elements matching the given local name. /// Uses async for streaming parse with XXE protection. /// internal static class XmlTokenizer { /// Tokenizes XML body by extracting elements with the given name. /// Exchange body (Stream, string, or byte[]). /// Local name of the elements to extract. /// Optional parent element name whose namespaces should be injected. /// Cancellation token. internal static async IAsyncEnumerable Tokenize( object? body, string elementName, string? inheritNamespaceFrom, [EnumeratorCancellation] CancellationToken ct = default) { using var reader = CreateXmlReader(body); Dictionary? parentNamespaces = null; var needRead = true; while (needRead ? await reader.ReadAsync().ConfigureAwait(false) : reader.ReadState == System.Xml.ReadState.Interactive) { needRead = true; ct.ThrowIfCancellationRequested(); // Collect namespaces from parent element if (inheritNamespaceFrom != null && reader.NodeType == XmlNodeType.Element && reader.LocalName == inheritNamespaceFrom) { parentNamespaces = CollectNamespaces(reader); } // Found target element if (reader.NodeType == XmlNodeType.Element && reader.LocalName == elementName) { var outerXml = await reader.ReadOuterXmlAsync().ConfigureAwait(false); if (parentNamespaces is { Count: > 0 }) outerXml = InjectNamespaces(outerXml, parentNamespaces); yield return outerXml; // ReadOuterXmlAsync already positioned reader on next node needRead = false; } } } private static XmlReader CreateXmlReader(object? body) { var settings = new XmlReaderSettings { Async = true, DtdProcessing = DtdProcessing.Prohibit }; return body switch { Stream s => XmlReader.Create(s, settings), string str => XmlReader.Create(new StringReader(str), settings), byte[] b => XmlReader.Create(new MemoryStream(b, writable: false), settings), _ => throw new InvalidOperationException( $"SplitXml: unsupported body type {body?.GetType().Name ?? "null"}") }; } private static Dictionary CollectNamespaces(XmlReader reader) { var ns = new Dictionary(); if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); if (reader.Prefix == "xmlns" || (reader.Prefix == "" && reader.LocalName == "xmlns")) ns[reader.Name] = reader.Value; } reader.MoveToElement(); } return ns; } private static string InjectNamespaces(string outerXml, Dictionary namespaces) { var insertPos = outerXml.IndexOf('>'); if (insertPos < 0) return outerXml; if (outerXml[insertPos - 1] == '/') insertPos--; var nsAttrs = string.Join(" ", namespaces .Where(kv => !outerXml.Contains(kv.Key)) .Select(kv => $"{kv.Key}=\"{kv.Value}\"")); if (nsAttrs.Length == 0) return outerXml; return outerXml.Insert(insertPos, " " + nsAttrs); } } Path: redb-route/redb.Route/Expressions/TypedJsonPathExpression.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/Expressions/TypedJsonPathExpression.cs ---- using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// A JsonPath expression that remembers the target CLR type . /// When the pipeline calls Evaluate<object>(exchange), the stored type is used /// for the internal call, ensuring proper /// type conversion (e.g., jpath<bool>("$.isHired") returns a boxed /// instead of a raw ). /// /// The target CLR type for JsonPath result conversion. public sealed class TypedJsonPathExpression : Expression { private readonly JsonPathExpression _inner; private readonly string _path; /// /// Initializes a new instance of the class. /// /// The JsonPath expression string. /// What to run the path against; null means the message body. public TypedJsonPathExpression(string jsonPath, IExpression? source = null) { _path = jsonPath; _inner = new JsonPathExpression(jsonPath, source); } /// public TypedJsonPathExpression From(IExpression source) => new(_path, source); /// public override T Evaluate(IExchange exchange) { // When the processor asks for Evaluate, we evaluate with the stored TValue // so that JsonPathExpression performs proper type conversion. if (typeof(T) == typeof(object)) { var typed = _inner.Evaluate(exchange); return (T)(object)typed!; } // If the caller requests a specific type, forward directly return _inner.Evaluate(exchange); } /// public override void SetValue(IExchange exchange, object value) { _inner.SetValue(exchange, value); } } Path: redb-route/redb.Route/Expressions/TypedXPathExpression.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/Expressions/TypedXPathExpression.cs ---- using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// An XPath expression that remembers the target CLR type . /// When the pipeline calls Evaluate<object>(exchange), the stored type is used /// for the internal call, ensuring proper /// type conversion (e.g., xpath<bool>("//active") returns a boxed /// instead of a raw string). /// /// The target CLR type for XPath result conversion. public sealed class TypedXPathExpression : Expression { private readonly XPathExpression _inner; /// /// Initializes a new instance of the class. /// /// The XPath expression string. /// /// The XPath-level type of the result, applied before conversion to . /// /// What to run the path against; null means the message body. public TypedXPathExpression(string xpath, XPathResult result = XPathResult.NodeSet, IExpression? source = null) : this(new XPathExpression(xpath, null, result, source)) { } private TypedXPathExpression(XPathExpression inner) => _inner = inner; /// public TypedXPathExpression From(IExpression source) => new(_inner.From(source)); /// public TypedXPathExpression WithNamespaces(params (string Prefix, string Uri)[] namespaces) => new(_inner.WithNamespaces(namespaces)); /// public TypedXPathExpression Trimmed(bool trim = true) => new(_inner.Trimmed(trim)); /// public TypedXPathExpression WithParameters(params (string Name, IExpression Value)[] parameters) => new(_inner.WithParameters(parameters)); /// public override T Evaluate(IExchange exchange) { // When the processor asks for Evaluate, we evaluate with the stored TValue // so that XPathExpression performs proper type conversion. if (typeof(T) == typeof(object)) { var typed = _inner.Evaluate(exchange); return (T)(object)typed!; } // If the caller requests a specific type, forward directly return _inner.Evaluate(exchange); } /// public override void SetValue(IExchange exchange, object value) { _inner.SetValue(exchange, value); } } Path: redb-route/redb.Route/Expressions/XPathExpression.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/Expressions/XPathExpression.cs ---- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Predicates; namespace redb.Route.Expressions; /// /// Expression for evaluating XPath queries against the message body in an . /// /// /// Extracts data from an XML document using W3C XPath 1.0 expressions. /// Supports , , string XML, and POCO bodies /// (auto-serialized to XML). Optionally accepts an /// for querying namespace-qualified documents. /// public class XPathExpression : Expression, IPredicateExpression { private readonly string _xpath; private readonly string _effectivePath; private readonly IXmlNamespaceResolver? _namespaceResolver; private readonly XPathResult _result; private readonly IExpression? _source; private readonly bool _trim; private readonly IReadOnlyList<(string Name, IExpression Value)>? _parameters; /// /// Initializes a new instance of the class. /// /// The XPath expression used to extract data. /// /// Optional namespace resolver for querying documents with XML namespaces. /// /// /// The XPath-level type of the result. The default, , is /// XPath's own default. /// /// /// What to run the path against. null — the default — means the message body. /// /// Trim whitespace off extracted text. Default false. /// Thrown when is null. public XPathExpression( string xpath, IXmlNamespaceResolver? namespaceResolver = null, XPathResult result = XPathResult.NodeSet, IExpression? source = null, bool trim = false) : this(xpath, namespaceResolver, result, source, trim, null) { } private XPathExpression( string xpath, IXmlNamespaceResolver? namespaceResolver, XPathResult result, IExpression? source, bool trim, IReadOnlyList<(string Name, IExpression Value)>? parameters) { _xpath = xpath ?? throw new ArgumentNullException(nameof(xpath)); _namespaceResolver = namespaceResolver; _result = result; _source = source; _trim = trim; _parameters = parameters; // string(), number() and boolean() are XPath's own coercions, so asking the engine for // them is both shorter and more faithful than converting the node-set ourselves. _effectivePath = result switch { XPathResult.String => $"string({_xpath})", XPathResult.Number => $"number({_xpath})", XPathResult.Boolean => $"boolean({_xpath})", _ => _xpath }; } /// /// Initializes a new instance of the class with an explicit /// XPath-level result type. /// /// The XPath expression used to extract data. /// The XPath-level type of the result. public XPathExpression(string xpath, XPathResult result) : this(xpath, null, result) { } /// /// Returns the same expression reading instead of the message body. /// /// /// XPath("/invoice/id").From(Header("original-request")). Without it, parsing XML that /// arrived in a header means moving it into the body first — an extra step that also damages /// the body for the rest of the route. /// /// The expression producing the XML to read. /// A new expression; this one is unchanged. public XPathExpression From(IExpression source) { ArgumentNullException.ThrowIfNull(source); return new XPathExpression(_xpath, _namespaceResolver, _result, source, _trim, _parameters); } /// /// Returns the same expression with prefixes bound to namespace URIs, so a path can address a /// namespace-qualified document. /// /// /// /// XPath("/s:Envelope/s:Body").WithNamespaces(("s", "http://schemas.xmlsoap.org/soap/envelope/")). /// The expression has always accepted an , but only through /// its constructor — a route written in the DSL had no way to reach it, which made every /// namespaced document unqueryable from a route without dropping out of the DSL. /// /// /// The prefixes are the expression's own: they need not match the ones in the document, only /// the URIs must. Camel keeps namespace sets in a registry and refers to them by name /// (namespacesRef) because its XML DSL cannot write a map inline; in C# the map is /// ordinary code, so a shared set is an ordinary variable. /// /// /// Prefix/URI pairs. /// A new expression; this one is unchanged. public XPathExpression WithNamespaces(params (string Prefix, string Uri)[] namespaces) { ArgumentNullException.ThrowIfNull(namespaces); var manager = new XmlNamespaceManager(new NameTable()); foreach (var (prefix, uri) in namespaces) { ArgumentException.ThrowIfNullOrWhiteSpace(prefix, nameof(namespaces)); ArgumentException.ThrowIfNullOrWhiteSpace(uri, nameof(namespaces)); manager.AddNamespace(prefix, uri); } return new XPathExpression(_xpath, manager, _result, _source, _trim, _parameters); } /// /// Returns the same expression with whitespace trimmed off the text it extracts. /// /// /// Off by default, which is where this library has always been and differs from Camel's /// trim=true. For a single value XPath answers this itself — /// XPath("normalize-space(/order/name)") — but a node-set of several values cannot be /// normalised from inside XPath 1.0, and an indented document gives every one of them the /// surrounding whitespace. /// /// Whether to trim; the parameter exists so the option can be turned back off. /// A new expression; this one is unchanged. public XPathExpression Trimmed(bool trim = true) => new(_xpath, _namespaceResolver, _result, _source, trim, _parameters); /// /// Returns the same expression with named XPath variables bound to expressions, so a value from /// the message can take part in the query without being pasted into its text. /// /// /// /// XPath("/order[@id=$id]").WithParameters(("id", Header("orderId"))). The value is /// passed to the engine as a value: it is compared, never parsed, so a header holding /// B-2' or '1'='1 selects an order with that literal id and matches nothing, rather than /// changing what the query asks. /// /// /// The alternative is building the path by concatenation, which Camel offers as /// allowSimple — and which is the reason XPath injection has a CodeQL query and an OWASP /// entry of its own. Binding values instead is old and settled practice: JAXP's /// XPathVariableResolver, XQuery's declare variable $x external, .NET's /// XsltArgumentList, and prepared statements in SQL are all the same idea. /// /// /// The path also stays one constant string whatever the data, which is what lets a compiled /// expression be reused; concatenation defeats that by construction. /// /// /// XPath only. jpath has no equivalent, and not because of the library: RFC 9535 has no /// variables at all, so there is nothing for JsonPath.Net to expose. /// /// /// Variable names (without the $) and the expressions producing their values. /// A new expression; this one is unchanged. public XPathExpression WithParameters(params (string Name, IExpression Value)[] parameters) { ArgumentNullException.ThrowIfNull(parameters); foreach (var (name, value) in parameters) { ArgumentException.ThrowIfNullOrWhiteSpace(name, nameof(parameters)); ArgumentNullException.ThrowIfNull(value, nameof(parameters)); if (name[0] == '$') throw new ArgumentException( $"XPath parameter name '{name}' must be written without the '$': the '$' belongs " + "in the path, not in the binding.", nameof(parameters)); } var merged = _parameters is null or { Count: 0 } ? parameters : [.. _parameters, .. parameters]; return new XPathExpression(_xpath, _namespaceResolver, _result, _source, _trim, merged); } /// /// Parameters are evaluated against a message, so an evaluation that has no message cannot /// honour them — and silently dropping a binding would turn a query into a different query. /// private IExchange RequireExchange(IExchange? exchange) => exchange ?? throw new InvalidOperationException( $"XPath '{_xpath}' has bound parameters, which need an exchange to evaluate against. " + "The two-argument xpath() function of the expression language does not carry them; " + "use the expression object form."); /// /// /// Thrown when the exchange body is null or the XPath expression cannot be evaluated. /// public override T Evaluate(IExchange exchange) => ConvertResult(EvaluateRaw(exchange)); /// /// Evaluates the expression in a condition position. /// /// /// /// A node-set answers whether the path matched: XPath 1.0 reads a node-set as true exactly /// when it is non-empty, and the content of the matched nodes never enters the question. So /// Filter(XPath("/order/discount")) passes a message whose discount is 0, and an /// empty <vip/> counts as a match. /// /// /// A scalar — from string(...), count(...) > 0, or an explicit /// — is a value like any other and goes through the single DSL /// truthiness rule, so "0" is false there. To read a node's content as a /// boolean instead, ask for the CLR type: XPath<bool>("/order/flag"). /// /// /// The exchange to test. /// true when the expression holds for the exchange. public bool Matches(IExchange exchange) { var raw = EvaluateRaw(exchange); return raw is IEnumerable nodes ? nodes.Any() : RouteTruthiness.ToBoolean(raw); } /// /// Runs the XPath and returns the engine's own result: a string, a double, a bool, or an /// of nodes. /// private object EvaluateRaw(IExchange exchange) => EvaluateRawOn(ExpressionValues.ReadInput(_source, exchange), _source is not null, exchange); /// /// Runs the XPath against an already-resolved input, whatever produced it. Used by the /// expression language, where the source arrives as a value rather than as an expression. /// internal T EvaluateOn(object? input, bool fromSource) => ConvertResult(EvaluateRawOn(input, fromSource, null)); private object EvaluateRawOn(object? input, bool fromSource, IExchange? exchange) { try { var body = input; if (body == null) throw new InvalidOperationException(ExpressionValues.NoInput(fromSource, "XPath")); var node = ResolveXNode(body); // Parameters are bound per message, so the resolver they travel in is built per // evaluation; without them the expression's own namespace resolver is passed straight // through, which is the path every existing route takes. var resolver = _parameters is null or { Count: 0 } ? _namespaceResolver : XPathVariableContext.Build(_namespaceResolver, _parameters, RequireExchange(exchange)); // XPathEvaluate returns: string, double, bool, or IEnumerable (node-set) var raw = System.Xml.XPath.Extensions.XPathEvaluate(node, _effectivePath, resolver); // NODE is a node-set narrowed to its first member in document order. if (_result == XPathResult.Node && raw is IEnumerable nodes) return nodes.Take(1).ToList(); return raw; } catch (InvalidOperationException) { throw; } catch (XmlException ex) { throw new InvalidOperationException($"XML parsing error in XPathExpression: {ex.Message}", ex); } catch (Exception ex) { throw new InvalidOperationException($"Error evaluating XPath '{_xpath}': {ex.Message}", ex); } } // ── Body → XNode ── /// /// Resolves the exchange body to an suitable for XPath evaluation. /// internal static XNode ResolveXNode(object body) { if (body is XDocument xDoc) return xDoc; if (body is XElement xElem) return xElem; if (body is string s) { s = s.Trim(); if (s.Length == 0) throw new InvalidOperationException("Exchange body is an empty string. Cannot evaluate XPath expression."); return SafeXml.Parse(s); } // POCO → serialize to XML via XmlSerializer return SerializeToXDocument(body); } private static XDocument SerializeToXDocument(object body) { var serializer = new XmlSerializer(body.GetType()); using var sw = new StringWriter(); using var xw = XmlWriter.Create(sw, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false }); serializer.Serialize(xw, body); return SafeXml.Parse(sw.ToString()); } // ── Result conversion ── private T ConvertResult(object raw) { // XPathEvaluate returns IEnumerable for node-set results if (raw is IEnumerable nodes) return ProcessNodeList(nodes); // Scalar results (string, double, bool) return ConvertScalar(raw); } /// /// Converts a scalar XPath result (string, double, bool) to the requested type. /// private T ConvertScalar(object value) { // A string scalar is text the same way a node's value is, so trimming applies to both. if (_trim && value is string text) value = text.Trim(); if (value is T direct) return direct; if (typeof(T) == typeof(string)) return (T)(object)(value?.ToString() ?? string.Empty); if (typeof(T) == typeof(object)) return (T)SmartConvertScalar(value); // double → numeric types if (value is double d) { if (typeof(T) == typeof(int)) return (T)(object)(int)d; if (typeof(T) == typeof(long)) return (T)(object)(long)d; if (typeof(T) == typeof(float)) return (T)(object)(float)d; if (typeof(T) == typeof(decimal)) return (T)(object)RouteDecimal.FromDouble(d); if (typeof(T) == typeof(double)) return (T)(object)d; if (typeof(T) == typeof(bool)) return (T)(object)(d != 0); } // bool → other types if (value is bool b) { if (typeof(T) == typeof(int)) return (T)(object)(b ? 1 : 0); if (typeof(T) == typeof(string)) return (T)(object)(b ? "true" : "false"); } try { return (T)RouteDecimal.ChangeType(value, typeof(T)); } catch (Exception ex) { throw new InvalidOperationException( $"Cannot convert XPath scalar result '{value}' ({value?.GetType().Name}) to {typeof(T).Name}.", ex); } } /// /// Smart conversion for Evaluate<object>: keeps original scalar type. /// private static object SmartConvertScalar(object value) { // double that is actually an integer → return int if (value is double d && d == Math.Truncate(d) && d is >= int.MinValue and <= int.MaxValue) return (int)d; return value; } // ── Node-set processing ── /// /// Processes a node-set (IEnumerable<object>) returned by XPathEvaluate. /// Nodes can be , , , /// , or . /// private T ProcessNodeList(IEnumerable nodes) { var list = nodes.ToList(); if (list.Count == 0) { if (typeof(T).IsValueType && Nullable.GetUnderlyingType(typeof(T)) == null) throw new InvalidOperationException($"No values found for XPath expression (expected non-nullable {typeof(T).Name})."); return default!; } // ── Single node ── if (list.Count == 1) return ConvertSingleNode(list[0]); // ── Multiple nodes ── return ConvertMultipleNodes(list); } /// /// Converts a single XPath node to the requested type. /// private T ConvertSingleNode(object node) { // For T=object, extract text and smart-parse (int, double, bool, or string) if (typeof(T) == typeof(object)) { var objectText = Text(node); return (T)SmartParseText(objectText); } // Return the raw node if the caller expects XElement, XAttribute, XObject, etc. if (node is T directMatch) return directMatch; var text = Text(node); if (typeof(T) == typeof(string)) return (T)(object)text; // Value types: parse from text return ParseText(text); } /// /// Converts multiple XPath nodes to the requested type. /// private T ConvertMultipleNodes(List nodeList) { var textValues = nodeList.Select(Text).ToArray(); // string → comma-joined if (typeof(T) == typeof(string)) return (T)(object)string.Join(", ", textValues); // string[] → direct if (typeof(T) == typeof(string[])) return (T)(object)textValues; // int[] if (typeof(T) == typeof(int[])) return (T)(object)textValues.Select(v => int.Parse(v)).ToArray(); // double[] if (typeof(T) == typeof(double[])) return (T)(object)textValues.Select(v => double.Parse(v, System.Globalization.CultureInfo.InvariantCulture)).ToArray(); // XElement[] if (typeof(T) == typeof(XElement[])) return (T)(object)nodeList.OfType().ToArray(); // List if (typeof(T) == typeof(List)) return (T)(object)nodeList.OfType().ToList(); // object → return string[] for multiple text values if (typeof(T) == typeof(object)) return (T)(object)textValues; // Try T[] via element-wise parsing if (typeof(T).IsArray) { var elemType = typeof(T).GetElementType()!; var arr = Array.CreateInstance(elemType, textValues.Length); for (int i = 0; i < textValues.Length; i++) arr.SetValue(RouteDecimal.ChangeType(textValues[i], elemType, System.Globalization.CultureInfo.InvariantCulture), i); return (T)(object)arr; } throw new InvalidOperationException( $"Cannot convert {nodeList.Count} XPath nodes to {typeof(T).Name}."); } // ── Helpers ── /// /// Extracts a string value from an XPath node (XElement, XAttribute, XText, etc.). /// private string Text(object node) { var value = ExtractTextValue(node); return _trim ? value.Trim() : value; } /// /// Extracts a string value from an XPath node (XElement, XAttribute, XText, etc.). /// internal static string ExtractTextValue(object node) => node switch { XElement e => e.Value, XAttribute a => a.Value, XText t => t.Value, XComment c => c.Value, XProcessingInstruction pi => pi.Data, _ => node?.ToString() ?? string.Empty }; /// /// Tries to parse a text value to the best-fitting CLR type (int, double, bool, or string). /// Used for Evaluate<object>. /// private static object SmartParseText(string text) { if (int.TryParse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var i)) return i; if (double.TryParse(text, System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands, System.Globalization.CultureInfo.InvariantCulture, out var d)) return d; if (bool.TryParse(text, out var b)) return b; return text; } /// /// Parses a text value to a specific type. /// private static T ParseText(string text) { var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); if (targetType == typeof(bool)) { // Support both "true"/"false" and "1"/"0" if (bool.TryParse(text, out var b)) return (T)(object)b; if (text == "1") return (T)(object)true; if (text == "0") return (T)(object)false; } try { return (T)RouteDecimal.ChangeType(text, targetType, System.Globalization.CultureInfo.InvariantCulture); } catch (Exception ex) { throw new InvalidOperationException( $"Cannot convert XPath text value '{text}' to {typeof(T).Name}.", ex); } } /// public override void SetValue(IExchange exchange, object value) { throw new NotSupportedException("XPathExpression does not support setting values."); } /// /// /// Thrown when the expression carries anything the template cannot: a non-default /// , a source, or bound parameters. The one-argument xpath() /// function of the expression language takes the path and nothing else, so a template string /// would quietly drop the rest and mean something different from the expression it was /// serialized from — a parameterised path would even fail at evaluation, its $name /// left unbound. Refusing loudly beats serialising a lie. /// public override string ToTemplateString() { if (_result != XPathResult.NodeSet) throw new NotSupportedException( $"XPathExpression with result type {_result} cannot be serialized to a template string: " + "the xpath() function takes only a path."); if (_source is not null) throw new NotSupportedException( "XPathExpression with a source cannot be serialized to a template string: " + "the template would silently read the body instead."); if (_parameters is { Count: > 0 }) throw new NotSupportedException( "XPathExpression with bound parameters cannot be serialized to a template string: " + "the bindings would be dropped, leaving the path's $variables unbound."); return $"${{xpath({_xpath})}}"; } } Path: redb-route/redb.Route/Expressions/XPathResult.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/Expressions/XPathResult.cs ---- namespace redb.Route.Expressions; /// /// The type an XPath expression produces, at the XPath level. /// /// /// /// This is a different question from the CLR type the caller wants back. XPath 1.0 has four types /// of its own — node-set, string, number, boolean — and an expression produces one of them before /// .NET conversion is even considered. XPath("/order/total", XPathResult.Number) says "read /// this the way XPath's number() reads it"; XPath<int>("/order/total") says /// "give me the result as an ". The two compose, and either can be used alone. /// /// /// The distinction matters most in a condition, where the default asks /// whether the path matched anything at all, while asks what the match says. /// Apache Camel draws the same line, as resultQName against resultType. /// /// public enum XPathResult { /// /// Every matching node (the default, and XPath's own default). In a condition a node-set is /// true when it is non-empty, whatever the matched nodes contain. /// NodeSet, /// /// The first matching node in document order, or nothing. In a condition it reads as /// "a node was found". /// Node, /// /// XPath's string() of the result: the text of the first matching node, or an empty /// string when nothing matched. The value is then read by the ordinary DSL rules, so in a /// condition "0" is false — the same as a header holding "0". /// String, /// /// XPath's number() of the result, as a . Text that is not a number /// yields . /// Number, /// /// XPath's boolean() of the result: a non-empty node-set, a non-empty string and a /// non-zero number are true. /// Boolean } Path: redb-route/redb.Route/Expressions/XPathVariableContext.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/Expressions/XPathVariableContext.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// Supplies bound values to the $name variables of an XPath expression. /// /// /// /// The BCL resolves XPath variables only through an , which it accepts in /// the same slot as a plain namespace resolver — so one object carries both the prefixes and the /// values. derives from , which is what /// makes carrying both natural rather than a trick. /// /// /// Built per evaluation, because the values come from the message. The path is not rebuilt, which /// is the whole point: the same query text runs whatever the data. /// /// internal sealed class XPathVariableContext : XsltContext { private readonly Dictionary _values = new(StringComparer.Ordinal); private XPathVariableContext() : base(new NameTable()) { } internal static XPathVariableContext Build( IXmlNamespaceResolver? namespaces, IReadOnlyList<(string Name, IExpression Value)> parameters, IExchange exchange) { var context = new XPathVariableContext(); if (namespaces is not null) { foreach (var (prefix, uri) in namespaces.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml)) context.AddNamespace(prefix, uri); } foreach (var (name, value) in parameters) context._values[name] = ToXPathValue(value.Evaluate(exchange)); return context; } /// /// Converts a CLR value to one of the four types XPath 1.0 knows. /// /// /// XPath has no integers, no dates and no null: numbers are doubles, and everything it cannot /// place is a string. Converting here rather than at the call site keeps the coercion in one /// place, and keeps it invariant — a decimal separator that follows the server's locale would /// make the same route match different documents on different machines. /// private static object ToXPathValue(object? value) => value switch { null => string.Empty, bool b => b, string s => s, double d => d, float f => (double)f, decimal m => (double)m, sbyte or byte or short or ushort or int or uint or long or ulong => Convert.ToDouble(value, CultureInfo.InvariantCulture), IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), _ => value.ToString() ?? string.Empty }; /// /// /// Only unprefixed variables resolve. WithParameters binds local names alone — it /// rejects even a leading $ — so $x:id can never have a binding here, and /// matching it to the binding named id would answer a different question than the one /// the path asked. Returning null lets the engine fail with its own "variable not /// defined", which is the honest outcome. /// public override IXsltContextVariable? ResolveVariable(string prefix, string name) => string.IsNullOrEmpty(prefix) && _values.TryGetValue(name, out var value) ? new BoundValue(value) : null; /// public override IXsltContextFunction? ResolveFunction(string prefix, string name, XPathResultType[] argTypes) => null; /// public override bool Whitespace => true; /// public override bool PreserveWhitespace(XPathNavigator node) => true; /// public override int CompareDocument(string baseUri, string nextbaseUri) => 0; /// One bound value, presented to the engine with the XPath type it actually has. private sealed class BoundValue(object value) : IXsltContextVariable { public bool IsLocal => false; public bool IsParam => false; public XPathResultType VariableType => value switch { double => XPathResultType.Number, bool => XPathResultType.Boolean, _ => XPathResultType.String }; public object Evaluate(XsltContext xsltContext) => value; } } Path: redb-route/redb.Route/Extensions/DataFormatRegistrationExtensions.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/Extensions/DataFormatRegistrationExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Extensions; /// /// Registers a data format in the context's so it can be addressed /// by content type: Marshal("text/csv"), Unmarshal<T>("text/csv"), and the /// content-type-driven Unmarshal<T>() / ConvertBody<T>(). Format packages wrap this /// in a named helper (AddCsvDataFormat()). /// public static class DataFormatRegistrationExtensions { /// Registers under its , its and any extra content types. public static IRouteContext AddDataFormat(this IRouteContext context, IMessageSerializer serializer, params string[] additionalContentTypes) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(serializer); var registry = context.GetService() ?? throw new InvalidOperationException("IDataFormatRegistry is not available on the route context."); registry.Register(serializer.ContentType, serializer); foreach (var contentType in additionalContentTypes) registry.Register(contentType, serializer); return context; } /// DI form: the format is registered on the hosted context when it is built. public static RedbRouteBuilder AddDataFormat(this RedbRouteBuilder builder, IMessageSerializer serializer, params string[] additionalContentTypes) { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(serializer); builder.Services.AddSingleton(new DataFormatConfigurator(serializer, additionalContentTypes)); return builder; } private sealed class DataFormatConfigurator(IMessageSerializer serializer, string[] additionalContentTypes) : IRouteContextConfigurator { public void Configure(RouteContext context) => context.AddDataFormat(serializer, additionalContentTypes); } } Path: redb-route/redb.Route/Extensions/HealthCheckExtensions.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/Extensions/HealthCheckExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; namespace redb.Route.Extensions; /// /// Extension methods for adding route engine health checks. /// public static class HealthCheckExtensions { /// /// Adds a health check for the redb.Route engine. /// /// Health checks builder. /// Health check name (default: "redb-route"). /// /// Status to report on failure (default: ). /// /// Optional tags for filtering. /// The builder for chaining. public static IHealthChecksBuilder AddRedbRouteCheck( this IHealthChecksBuilder builder, string name = "redb-route", HealthStatus? failureStatus = HealthStatus.Degraded, IEnumerable? tags = null) { return builder.AddCheck(name, failureStatus, tags ?? []); } } Path: redb-route/redb.Route/Extensions/RedbRouteCodecExtensions.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/Extensions/RedbRouteCodecExtensions.cs ---- using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Serialization; namespace redb.Route.Extensions; /// /// Fluent extensions for configuring message codecs on a . /// /// These extensions operate on , which lives inside /// (not the DI container). Registration is deferred via /// so it is applied at context-start time. /// /// public static class RedbRouteCodecExtensions { /// /// Replaces the default application/json codec in the route context's /// with one built from the supplied action. /// /// Route builder. /// Action applied to a fresh /// instance (already seeded with /// and case-insensitive property matching). Mutate to taste. /// /// Profile-scoped codecs (SCIM, Problem Details, …) registered by other modules /// (e.g. AddRedbIdentityServer) are not affected — this tunes only the /// generic application/json entry. /// public static RedbRouteBuilder ConfigureJsonCodec( this RedbRouteBuilder builder, Action configure) { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configure); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; configure(options); builder.Services.AddSingleton( new JsonCodecConfigurator(options)); return builder; } /// /// Applies a bound instance to the default /// application/json codec. Callers typically populate the options from /// IConfiguration.GetSection("redbRoute:Codecs:Json").Get<JsonCodecOptions>() /// in their host composition root. /// /// Route builder. /// Bound codec options; may not be null. public static RedbRouteBuilder ConfigureJsonCodec( this RedbRouteBuilder builder, JsonCodecOptions options) { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(options); return builder.ConfigureJsonCodec(jso => { jso.PropertyNamingPolicy = ParseNamingPolicy(options.PropertyNamingPolicy); jso.PropertyNameCaseInsensitive = options.PropertyNameCaseInsensitive; jso.DefaultIgnoreCondition = options.IgnoreNullValues ? JsonIgnoreCondition.WhenWritingNull : JsonIgnoreCondition.Never; jso.WriteIndented = options.WriteIndented; jso.Encoder = options.UnsafeRelaxedEscaping ? JavaScriptEncoder.UnsafeRelaxedJsonEscaping : JavaScriptEncoder.Default; }); } private static JsonNamingPolicy? ParseNamingPolicy(string? name) => name switch { null => null, "" => null, _ when string.Equals(name, "None", StringComparison.OrdinalIgnoreCase) => null, _ when string.Equals(name, "CamelCase", StringComparison.OrdinalIgnoreCase) => JsonNamingPolicy.CamelCase, _ when string.Equals(name, "SnakeCaseLower", StringComparison.OrdinalIgnoreCase) => JsonNamingPolicy.SnakeCaseLower, _ when string.Equals(name, "SnakeCaseUpper", StringComparison.OrdinalIgnoreCase) => JsonNamingPolicy.SnakeCaseUpper, _ when string.Equals(name, "KebabCaseLower", StringComparison.OrdinalIgnoreCase) => JsonNamingPolicy.KebabCaseLower, _ when string.Equals(name, "KebabCaseUpper", StringComparison.OrdinalIgnoreCase) => JsonNamingPolicy.KebabCaseUpper, _ => throw new ArgumentException( $"Unknown JSON naming policy '{name}'. Supported: None, CamelCase, SnakeCaseLower, SnakeCaseUpper, KebabCaseLower, KebabCaseUpper.") }; private sealed class JsonCodecConfigurator : IRouteContextConfigurator { private readonly JsonSerializerOptions _options; public JsonCodecConfigurator(JsonSerializerOptions options) => _options = options; public void Configure(RouteContext context) { var registry = context.GetService() ?? throw new InvalidOperationException( "IDataFormatRegistry is not available on RouteContext. " + "Ensure AddRedbRoute() was called before ConfigureJsonCodec()."); // Replace the generic application/json entry. Media-type aliases fan out // automatically via DataFormatRegistry.Register + MediaTypes contract. registry.Register("application/json", new JsonMessageSerializer(_options)); } } } Path: redb-route/redb.Route/Extensions/RouteContextExtensions.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/Extensions/RouteContextExtensions.cs ---- using System.Reflection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components; namespace redb.Route.Extensions; /// /// Extension methods for — component auto-discovery and convenience helpers. /// public static class RouteContextExtensions { /// /// Resolves a service the context was given, looking in both places it can live: the services /// set on the context itself (AddService, or a constructor argument), then the DI /// container behind . Returns null when /// neither holds one — the caller decides whether that is a default, its own instance, or a /// refusal. /// /// This is the shape a component needs when the host builds it by scanning: nothing can be /// injected through its constructor, so the one shared instance is looked up instead. Having it /// in one place keeps the two sources in one order everywhere — the metrics subscriber, the /// template options and the shared HTTP host all resolve through it. /// /// /// Service type. /// Route context; a null context resolves to null. public static T? Resolve(this IRouteContext? context) where T : class => context?.GetService() ?? context?.GetServiceProvider()?.GetService(typeof(T)) as T; /// /// The stream cache options in force for : a registered /// service, else the engine's /// , else the defaults. The .StreamCaching() step /// resolves them the same way; a connector that spools through takes them from here. /// /// Route context; null gives the defaults. public static Configuration.StreamCacheOptions GetStreamCacheOptions(this IRouteContext? context) => context?.GetService() ?? (context as Core.RouteContext)?.StreamCacheOptions ?? new Configuration.StreamCacheOptions(); /// /// The attachment options in force for : the engine's /// , the defaults without a context. There is no second /// source (no separately registered service), so RedbRoute:Attachments:MaxReplayableBytes means the same for /// the checkpoint and for the Tsak DLQ. /// /// Route context; null gives the defaults. public static Configuration.AttachmentOptions GetAttachmentOptions(this IRouteContext? context) => (context as Core.RouteContext)?.AttachmentOptions ?? new Configuration.AttachmentOptions(); /// /// Resolves a named object from the context registry and FAILS LOUD when nothing is /// registered under the name. A typo in connectionFactory=… must never silently /// fall back to URI parameters or defaults — a working configuration and a /// misconfiguration must be distinguishable. A null context (no /// registry at all) fails the same way. /// /// Expected registered type. /// Route context (may be null — still a loud failure). /// Registry name the endpoint referenced. public static T GetRequiredFromRegistry(this IRouteContext? context, string name) where T : class { ArgumentException.ThrowIfNullOrWhiteSpace(name); return context?.GetFromRegistry(name) ?? throw new InvalidOperationException( $"'{name}' is not registered in the context registry (expected {typeof(T).Name}). " + "Register it with AddToRegistry(name, ...) before Start()."); } /// /// Scans the specified assemblies for concrete implementations /// and registers any that are not already present in the context. /// A component is created with a public constructor callable without arguments: none at all, or only optional ones, /// called with their defaults (the rule the XML catalog follows too). A component without one, or whose constructor /// throws, is left out with a warning naming it; register it with AddComponent. /// /// The route context to register components in. /// One or more assemblies to scan. /// The context (for fluent chaining). public static IRouteContext AddComponents(this IRouteContext context, params Assembly[] assemblies) { ArgumentNullException.ThrowIfNull(context); var logger = context.GetService()?.CreateLogger("redb.Route.AddComponents"); foreach (var assembly in assemblies) { Type[] types; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { // Some types may fail to load (missing deps); use whatever loaded successfully types = ex.Types.Where(t => t is not null).ToArray()!; } var components = ComponentConstruction.Create(types, (type, reason) => logger?.LogWarning( "AddComponents: {Type} is not registered: {Reason}; register it with AddComponent", type.FullName, reason)); foreach (var component in components) { if (context.HasComponent(component.Scheme)) continue; context.AddComponent(component); } } return context; } /// /// Registers a ${prefix.rest} resolver for the expressions of this context only ( /// ends with a dot). It lives with the context: no unregistering when the context goes, and an unloaded module's /// delegate stays nowhere. It is consulted before the process-wide resolvers of /// . /// public static IRouteContext RegisterPrefixResolver(this IRouteContext context, string prefix, Func resolver) { Expressions.ExpressionPrefixResolvers.For(context).Register(prefix, resolver); return context; } } Path: redb-route/redb.Route/Extensions/RouteDefinitionAliasExtensions.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/Extensions/RouteDefinitionAliasExtensions.cs ---- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Transactions; namespace redb.Route.Abstractions; /// /// Convenience alias and End* navigation extension methods on . /// They map alternative names that tests and v1 callers expect onto the canonical v2 DSL surface. /// public static class RouteDefinitionAliasExtensions { // --------------------------------------------------------------------- // End* navigation - walks the Parent chain looking for a scope of the // requested type and closes everything up to and including it. This means // .EndChoice() called from inside a Log scope inside a When closes the Log // and the When and the Choice in one shot, returning the parent route. // --------------------------------------------------------------------- private static IRouteDefinition CloseToScope(IRouteDefinition self, string scopeName) where TScope : class, IProcessorDefinition { IProcessorDefinition? cur = self as IProcessorDefinition; while (cur is not null) { if (cur is TScope match) { var parent = match.Parent ?? throw new InvalidOperationException( $"End{scopeName}() found a {typeof(TScope).Name} with no parent — this scope is not attached to a route."); if (parent is IRouteDefinition rd) return rd; throw new InvalidOperationException( $"End{scopeName}() resolved a parent of type {parent.GetType().Name} which does not implement IRouteDefinition."); } cur = cur.Parent; } throw new InvalidOperationException( $"End{scopeName}() called outside a {scopeName} scope (current step: {self.GetType().Name}). " + $"Open a {scopeName} scope first."); } /// Closes the nearest enclosing Filter scope. public static IRouteDefinition EndFilter(this IRouteDefinition self) => CloseToScope(self, "Filter"); /// Closes the nearest enclosing Traced block. public static IRouteDefinition EndTraced(this IRouteDefinition self) => CloseToScope(self, "Traced"); /// Closes the nearest enclosing Metered block. public static IRouteDefinition EndMetered(this IRouteDefinition self) => CloseToScope(self, "Metered"); /// Closes the nearest enclosing IdempotentConsumer scope. public static IRouteDefinition EndIdempotentConsumer(this IRouteDefinition self) => CloseToScope(self, "IdempotentConsumer"); /// Closes the nearest enclosing Saga scope. public static IRouteDefinition EndSaga(this IRouteDefinition self) => CloseToScope(self, "Saga"); /// Closes the nearest enclosing Choice scope (and any open When/Otherwise inside it). public static IRouteDefinition EndChoice(this IRouteDefinition self) => CloseToScope(self, "Choice"); /// Closes the nearest enclosing When branch and returns its parent Choice (typed as IRouteDefinition). public static IRouteDefinition EndWhen(this IRouteDefinition self) => CloseToScope(self, "When"); /// Closes the nearest enclosing Otherwise branch and returns its parent Choice (typed as IRouteDefinition). public static IRouteDefinition EndOtherwise(this IRouteDefinition self) => CloseToScope(self, "Otherwise"); /// Closes the nearest enclosing Split scope. public static IRouteDefinition EndSplit(this IRouteDefinition self) => CloseToScope(self, "Split"); /// Closes the nearest enclosing Multicast scope. public static IRouteDefinition EndMulticast(this IRouteDefinition self) => CloseToScope(self, "Multicast"); /// Closes the nearest enclosing Aggregate scope. public static IRouteDefinition EndAggregate(this IRouteDefinition self) => CloseToScope(self, "Aggregate"); /// Closes the nearest enclosing CircuitBreaker scope. public static IRouteDefinition EndCircuitBreaker(this IRouteDefinition self) => CloseToScope(self, "CircuitBreaker"); /// Closes the nearest enclosing Throttle scope. public static IRouteDefinition EndThrottle(this IRouteDefinition self) => CloseToScope(self, "Throttle"); /// Closes the nearest enclosing Debounce scope. public static IRouteDefinition EndDebounce(this IRouteDefinition self) => CloseToScope(self, "Debounce"); /// Closes the nearest enclosing Loop scope. public static IRouteDefinition EndLoop(this IRouteDefinition self) => CloseToScope(self, "Loop"); /// Closes the nearest enclosing TryCatch scope (and any open Catch/Finally inside it). public static IRouteDefinition EndTryCatch(this IRouteDefinition self) => CloseToScope(self, "TryCatch"); /// Closes the nearest enclosing OnException scope. public static IRouteDefinition EndOnException(this IRouteDefinition self) => CloseToScope(self, "OnException"); /// Closes the nearest enclosing Transaction scope. public static IRouteDefinition EndTransaction(this IRouteDefinition self) => CloseToScope(self, "Transaction"); /// Closes the nearest enclosing Log (rich) scope. public static IRouteDefinition EndLog(this IRouteDefinition self) => CloseToScope(self, "Log"); /// Closes the nearest enclosing Resequence scope. public static IRouteDefinition EndResequence(this IRouteDefinition self) => CloseToScope(self, "Resequence"); /// /// Universal scope close — walks up to the nearest enclosing /// and closes it. Equivalent to calling the matching End*() method. /// public static IRouteDefinition End(this IRouteDefinition self) { IProcessorDefinition? cur = self as IProcessorDefinition; while (cur is not null) { if (cur is IRouteScope scope) return scope.End(); cur = cur.Parent; } throw new InvalidOperationException( $"End() called outside any open scope (current step: {self.GetType().Name})."); } // --------------------------------------------------------------------- // Sibling-branch openers — When() / Otherwise() reachable from anywhere // inside an open Choice scope, even after a sub-scope was just closed // (e.g. .EndSplit().When(...) — typed as IRouteDefinition but the real // current node is a WhenDefinition whose Parent is a ChoiceDefinition). // --------------------------------------------------------------------- private static ChoiceDefinition FindEnclosingChoice(IRouteDefinition self, string method) { IProcessorDefinition? cur = self as IProcessorDefinition; while (cur is not null) { if (cur is ChoiceDefinition choice) return choice; cur = cur.Parent; } throw new InvalidOperationException( $"{method}() called outside a Choice scope (current step: {self.GetType().Name}). Open a Choice scope first."); } /// Opens (or continues) a When branch on the nearest enclosing Choice scope. public static WhenDefinition When(this IRouteDefinition self, Func predicate) => FindEnclosingChoice(self, "When").When(predicate); /// Opens (or continues) a When branch on the nearest enclosing Choice scope. public static WhenDefinition When(this IRouteDefinition self, IExpression expression) => FindEnclosingChoice(self, "When").When(expression); /// Opens (or continues) a When branch on the nearest enclosing Choice scope using a Simple condition. public static WhenDefinition When(this IRouteDefinition self, string simpleTemplate) => FindEnclosingChoice(self, "When").When(simpleTemplate); /// Opens the Otherwise branch on the nearest enclosing Choice scope. public static OtherwiseDefinition Otherwise(this IRouteDefinition self) => FindEnclosingChoice(self, "Otherwise").Otherwise(); // --------------------------------------------------------------------- // Transaction alias (Transacted in v1 / Camel). // --------------------------------------------------------------------- public static TransactionDefinition Transacted(this IRouteDefinition self) => self.Transaction(); public static TransactionDefinition Transacted(this IRouteDefinition self, TransactionPolicy policy) { ArgumentNullException.ThrowIfNull(policy); return self.Transaction(policy); } public static TransactionDefinition Transacted(this IRouteDefinition self, string policyName) { ArgumentException.ThrowIfNullOrWhiteSpace(policyName); return self.Transaction(TransactionPolicy.FromName(policyName)); } // --------------------------------------------------------------------- // Expression aliases - map *Expression(IExpression) to canonical setters. // --------------------------------------------------------------------- public static IRouteDefinition SetBodyExpression(this IRouteDefinition self, IExpression expression) => self.SetBody(expression); public static IRouteDefinition SetHeaderExpression(this IRouteDefinition self, string name, IExpression expression) => self.SetHeader(name, expression); public static IRouteDefinition SetPropertyExpression(this IRouteDefinition self, string name, IExpression expression) => self.SetProperty(name, expression); public static IRouteDefinition TransformExpression(this IRouteDefinition self, IExpression expression) => self.Transform(expression); public static LoopDefinition LoopExpression(this IRouteDefinition self, IExpression expression) => self.Loop(ex => expression.Evaluate(ex)); // --------------------------------------------------------------------- // TryCatch aliases (Camel-style doTry / doCatch / doFinally). // --------------------------------------------------------------------- public static TryCatchDefinition DoTry(this IRouteDefinition self) => self.TryCatch(); public static CatchDefinition DoCatch(this IRouteDefinition self) where TException : Exception { return self switch { TryCatchDefinition tc => tc.Catch(typeof(TException)), CatchDefinition cd => cd.EndCatch().Catch(typeof(TException)), FinallyDefinition => throw new InvalidOperationException("DoCatch() cannot follow Finally() — catches must precede the finally block."), _ => throw new InvalidOperationException($"DoCatch() requires the previous step to be DoTry or DoCatch (got {self.GetType().Name})."), }; } public static FinallyDefinition DoFinally(this IRouteDefinition self) { return self switch { TryCatchDefinition tc => tc.Finally(), CatchDefinition cd => cd.Finally(), _ => throw new InvalidOperationException($"DoFinally() requires the previous step to be DoTry or DoCatch (got {self.GetType().Name})."), }; } // --------------------------------------------------------------------- // Context accessor. // --------------------------------------------------------------------- public static IRouteContext? GetContext(this IRouteDefinition self) { // Walk the Parent chain to reach the root RouteDefinition (every scope // class — WhenDefinition, LoopDefinition, TracedDefinition, etc. — // inherits from RouteDefinitionBase, not from RouteDefinition, // so a direct `self as RouteDefinition` cast only matches the root). IProcessorDefinition? cur = self as IProcessorDefinition; while (cur is not null) { if (cur is RouteDefinition rd) return rd.Context; cur = cur.Parent; } return null; } // --------------------------------------------------------------------- // RouteDefinition-level aliases. // --------------------------------------------------------------------- public static IRouteDefinition ShowRouteId(this IRouteDefinition self, bool value = true) { throw new InvalidOperationException( $"ShowRouteId() called outside a Log() scope (current step: {self.GetType().Name}). Open a scope with .Log(name) first."); } // --------------------------------------------------------------------- // OnException-scope aliases (work when previous step is OnExceptionDefinition). // --------------------------------------------------------------------- private static T RequireScope(IRouteDefinition self, string method) where T : class { if (self is T t) return t; throw new InvalidOperationException( $"{method}() must be called on a {typeof(T).Name} scope (got {self.GetType().Name})."); } public static IRouteDefinition MaximumRedeliveries(this IRouteDefinition self, int count) => RequireScope(self, "MaximumRedeliveries").MaximumRedeliveries(count); public static IRouteDefinition Handled(this IRouteDefinition self, bool value = true) => RequireScope(self, "Handled").Handled(value); public static IRouteDefinition Continued(this IRouteDefinition self, bool value = true) => RequireScope(self, "Continued").Continued(value); public static IRouteDefinition RedeliveryPolicy(this IRouteDefinition self, RedeliveryPolicy policy) => RequireScope(self, "RedeliveryPolicy").RedeliveryPolicy(policy); public static IRouteDefinition OnWhen(this IRouteDefinition self, Func predicate) => RequireScope(self, "OnWhen").OnWhen(predicate); public static IRouteDefinition OnRedelivery(this IRouteDefinition self, Action action) => RequireScope(self, "OnRedelivery").OnRedelivery(action); public static IRouteDefinition OnExceptionOccurred(this IRouteDefinition self, Action action) => RequireScope(self, "OnExceptionOccurred").OnExceptionOccurred(action); public static IRouteDefinition RetryAttemptedLogLevel(this IRouteDefinition self, LogLevel level) => RequireScope(self, "RetryAttemptedLogLevel").RetryAttemptedLogLevel(level); public static IRouteDefinition RetriesExhaustedLogLevel(this IRouteDefinition self, LogLevel level) => RequireScope(self, "RetriesExhaustedLogLevel").RetriesExhaustedLogLevel(level); public static IRouteDefinition BackOffMultiplier(this IRouteDefinition self, double multiplier) => RequireScope(self, "BackOffMultiplier").BackOffMultiplier(multiplier); public static IRouteDefinition UseExponentialBackOff(this IRouteDefinition self, bool value = true) => RequireScope(self, "UseExponentialBackOff").UseExponentialBackOff(value); // --------------------------------------------------------------------- // Saga-scope aliases. // --------------------------------------------------------------------- public static IRouteDefinition SagaStep(this IRouteDefinition self, Action action, Action compensate) => RequireScope(self, "SagaStep").SagaStep(action, compensate); public static IRouteDefinition SagaStep(this IRouteDefinition self, Action action) => RequireScope(self, "SagaStep").SagaStep(action); public static IRouteDefinition OnSagaCompletion(this IRouteDefinition self, Action callback) => RequireScope(self, "OnSagaCompletion").OnSagaCompletion(callback); } Path: redb-route/redb.Route/Extensions/RouteDefinitionCamelDslExtensions.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/Extensions/RouteDefinitionCamelDslExtensions.cs ---- using System; using System.Collections.Generic; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Abstractions; /// /// Apache Camel parity overloads for : /// /// nested-lambda configurators for every scope-opener EIP (Filter, Choice, Loop, etc.) — the configurator runs against the opened scope and the parent route is returned; /// string-template (Simple language) overloads for expression-based methods; /// convenience overloads that accept a registry name (idempotent repositories). /// /// All overloads are pure facades over the canonical surface; /// they do not introduce new behaviour at runtime. /// public static class RouteDefinitionCamelDslExtensions { // ── helpers ─────────────────────────────────────────────────────────────── private static IRouteDefinition RunNested(TScope scope, Action configure) where TScope : class, IRouteScope { ArgumentNullException.ThrowIfNull(scope); ArgumentNullException.ThrowIfNull(configure); configure(scope); return scope.End(); } // ── Filter (nested + string template) ───────────────────────────────────── /// Apache Camel: opens a Filter scope, runs against it, then closes the scope. public static IRouteDefinition Filter(this IRouteDefinition self, Func predicate, Action configure) => RunNested(self.Filter(predicate), configure); /// Apache Camel: opens a Filter scope (expression predicate), runs , then closes the scope. public static IRouteDefinition Filter(this IRouteDefinition self, IExpression expression, Action configure) => RunNested(self.Filter(expression), configure); /// /// Apache Camel: Filter using a Simple language condition, either a template /// ("${header.enabled}") or a boolean expression ("header.amount > 1000"). /// public static FilterDefinition Filter(this IRouteDefinition self, string simpleTemplate) { ArgumentNullException.ThrowIfNull(self); var def = self.Filter(PredicateFactory.FromString(simpleTemplate)); def.SourceTemplate = simpleTemplate; return def; } /// Apache Camel: Filter using a Simple condition plus a nested configurator. public static IRouteDefinition Filter(this IRouteDefinition self, string simpleTemplate, Action configure) => RunNested(self.Filter(simpleTemplate), configure); /// Apache Camel: Filter using an with nested configurator. public static IRouteDefinition Filter(this IRouteDefinition self, IPredicate predicate, Action configure) => RunNested(self.Filter(predicate), configure); // ── When / OrIfElse adapters ────────────────────────────────────────────── /// /// Apache Camel: When using a Simple language condition, either a template /// ("${header.flag}") or a boolean expression ("header.type == 'vip'"). /// public static WhenDefinition When(this ChoiceDefinition self, string simpleTemplate) { ArgumentNullException.ThrowIfNull(self); var w = self.When(PredicateFactory.FromString(simpleTemplate)); w.SourceTemplate = simpleTemplate; return w; } /// Apache Camel: When using a Simple language condition (from WhenDefinition). public static WhenDefinition When(this WhenDefinition self, string simpleTemplate) { ArgumentNullException.ThrowIfNull(self); var w = self.When(PredicateFactory.FromString(simpleTemplate)); w.SourceTemplate = simpleTemplate; return w; } // ── Choice (nested) ─────────────────────────────────────────────────────── /// Apache Camel: opens a Choice scope, runs , then closes the scope. public static IRouteDefinition Choice(this IRouteDefinition self, Action configure) => RunNested(self.Choice(), configure); // ── Multicast (nested) ──────────────────────────────────────────────────── /// Apache Camel: opens a Multicast scope, runs , then closes the scope. public static IRouteDefinition Multicast(this IRouteDefinition self, Action configure) => RunNested(self.Multicast(), configure); /// Apache Camel parity: multicast to a static list of URIs. public static IRouteDefinition Multicast( this IRouteDefinition self, System.Collections.Generic.IEnumerable uris, bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null) { ArgumentNullException.ThrowIfNull(self); ArgumentNullException.ThrowIfNull(uris); var mc = self.Multicast() .ParallelProcessing(parallelProcessing) .StopOnException(stopOnException); if (aggregationStrategy != null) mc = mc.AggregationStrategy(aggregationStrategy); foreach (var uri in uris) mc.To(uri); return mc.EndMulticast(); } // ── Split (nested) ──────────────────────────────────────────────────────── /// Apache Camel: opens a Split scope, runs , then closes the scope. public static IRouteDefinition Split(this IRouteDefinition self, Func> splitter, Action configure) => RunNested(self.Split(splitter), configure); /// Apache Camel: opens a streaming (async) Split scope. public static IRouteDefinition Split(this IRouteDefinition self, Func> asyncSplitter, Action configure) => RunNested(self.Split(asyncSplitter), configure); /// Apache Camel: opens a streaming (async) Split scope with options. public static IRouteDefinition Split( this IRouteDefinition self, Func> asyncSplitter, Action configure, bool stopOnException = false, bool parallelProcessing = false) { var split = self.Split(asyncSplitter).StopOnException(stopOnException).Parallel(parallelProcessing); return RunNested(split, configure); } /// Apache Camel: opens a Split scope (expression splitter), runs , then closes the scope. public static IRouteDefinition Split(this IRouteDefinition self, IExpression expression, Action configure) => RunNested(self.Split(expression), configure); // ── Loop (nested + string template) ─────────────────────────────────────── /// Apache Camel: opens a fixed-iteration Loop scope, runs , then closes it. public static IRouteDefinition Loop(this IRouteDefinition self, int count, Action configure, bool copy = false, bool shareScope = true) => RunNested(self.Loop(count, copy, shareScope), configure); /// Apache Camel: opens a conditional Loop scope, runs , then closes it. public static IRouteDefinition Loop(this IRouteDefinition self, Func condition, Action configure) => RunNested(self.Loop(condition), configure); /// Apache Camel: opens a count-by-factory Loop scope, runs , then closes it. public static IRouteDefinition Loop(this IRouteDefinition self, Func countFactory, Action configure) => RunNested(self.Loop(countFactory), configure); /// /// Apache Camel parity: opens a Loop scope that repeats while the condition string holds. /// The counterpart of Loop(string), which takes an /// iteration count rather than a condition. The condition is compiled the same way as in /// Filter and When. /// public static LoopDefinition LoopWhile(this IRouteDefinition self, string condition, bool copy = false, bool shareScope = true) { ArgumentNullException.ThrowIfNull(self); var predicate = PredicateFactory.FromString(condition); return self.Loop(predicate, copy, shareScope); } /// Apache Camel parity: LoopWhile with a nested configurator that runs against the opened scope. public static IRouteDefinition LoopWhile(this IRouteDefinition self, string condition, Action configure, bool copy = false, bool shareScope = true) => RunNested(self.LoopWhile(condition, copy, shareScope), configure); /// Apache Camel: LoopExpression with a nested configurator (IExpression overload). public static IRouteDefinition LoopExpression( this IRouteDefinition self, IExpression expression, Action configure, bool copy = false, bool shareScope = true) { ArgumentNullException.ThrowIfNull(self); ArgumentNullException.ThrowIfNull(expression); var loop = self.Loop(ex => expression.Evaluate(ex), copy, shareScope); return RunNested(loop, configure); } // ── CircuitBreaker (nested) ─────────────────────────────────────────────── /// /// Apache Camel: opens a CircuitBreaker scope and runs to set /// options (Threshold/ResetTimeout/FallBack/...). Returns the still-open CircuitBreaker /// definition so subsequent chained calls (e.g. .Process(...), .To(...)) /// become the protected body. Close explicitly with EndCircuitBreaker() if you /// need to chain steps outside the breaker. /// public static IRouteDefinition CircuitBreaker(this IRouteDefinition self, Action configure) { ArgumentNullException.ThrowIfNull(configure); var cb = self.CircuitBreaker(); configure(cb); return cb; } // ── TryCatch (nested) ───────────────────────────────────────────────────── /// Apache Camel: opens a TryCatch scope, runs , then closes the scope. public static IRouteDefinition TryCatch(this IRouteDefinition self, Action configure) => RunNested(self.TryCatch(), configure); // ── Throttle (nested) ───────────────────────────────────────────────────── /// Apache Camel: opens a Throttle scope, runs , then closes the scope. public static IRouteDefinition Throttle(this IRouteDefinition self, int maxPerPeriod, Action configure) => RunNested(self.Throttle(maxPerPeriod), configure); /// Apache Camel parity: opens a Throttle scope with explicit period. public static ThrottleDefinition Throttle(this IRouteDefinition self, int maxPerPeriod, TimeSpan period) => self.Throttle(maxPerPeriod).Period(period); // ── Idempotent consumer (registry-name + nested overloads) ──────────────── /// Apache Camel idempotent consumer overload (keyExtractor first, then repository instance). public static IdempotentConsumerDefinition IdempotentConsumer( this IRouteDefinition self, Func keyExtractor, IIdempotentRepository repository, bool skipDuplicate = true) { ArgumentNullException.ThrowIfNull(self); return self.IdempotentConsumer(repository, keyExtractor, skipDuplicate); } /// Apache Camel idempotent consumer (keyExtractor + named registry). public static IdempotentConsumerDefinition IdempotentConsumer( this IRouteDefinition self, Func keyExtractor, string repositoryName, bool skipDuplicate = true) { ArgumentNullException.ThrowIfNull(self); return self.IdempotentConsumer(keyExtractor, repositoryName, skipDuplicate); } /// Apache Camel idempotent consumer overload with nested configurator (registry name). public static IRouteDefinition IdempotentConsumer( this IRouteDefinition self, Func keyExtractor, string repositoryName, Action configure) { ArgumentNullException.ThrowIfNull(self); return RunNested(self.IdempotentConsumer(keyExtractor, repositoryName), configure); } /// Apache Camel idempotent consumer overload with nested configurator (repository instance). public static IRouteDefinition IdempotentConsumer( this IRouteDefinition self, Func keyExtractor, IIdempotentRepository repository, Action configure) => RunNested(self.IdempotentConsumer(keyExtractor, repository), configure); /// Apache Camel idempotent consumer overload with nested configurator (repository, keyExtractor — canonical order). public static IRouteDefinition IdempotentConsumer( this IRouteDefinition self, IIdempotentRepository repository, Func keyExtractor, Action configure) => RunNested(self.IdempotentConsumer(repository, keyExtractor), configure); // ── Validate (string condition) ─────────────────────────────────────────── /// /// Apache Camel parity: validates the exchange against a condition string, throwing or /// flagging when it does not hold. Uses the same condition compilation as Filter and When. /// public static IRouteDefinition Validate(this IRouteDefinition self, string condition, string errorMessage = "Validation failed", bool throwOnFailure = true) { ArgumentNullException.ThrowIfNull(self); var predicate = PredicateFactory.FromString(condition); return self.Validate(predicate, errorMessage, throwOnFailure); } // ── String-template expression aliases ──────────────────────────────────── // SetBodyExpression / SetHeaderExpression / SetPropertyExpression used to be declared here as // extensions too. They were unreachable — the same names are members of IRouteDefinition, and a // member always wins over an extension — and, until the template engines were unified, they // led into a different dialect than the members did. Removed 2026-08-28. // // TransformExpression(string) went the same way in 4.0: // the suffix means "takes an IExpression" everywhere else in the DSL, and a string form of the // same thing is a second way to say it. Write Transform(Expr("${...}")). /// Apache Camel: Throttle whose limit comes from an , evaluated on every message. public static ThrottleDefinition ThrottleExpression(this IRouteDefinition self, IExpression expression, TimeSpan period) { ArgumentNullException.ThrowIfNull(self); ArgumentNullException.ThrowIfNull(expression); return self.Throttle(ex => expression.Evaluate(ex)).Period(period); } // ── OnException scope alias (RedeliveryDelay after pipeline downgrade) ──── /// /// Apache Camel alias for /// surfaced on the parent facade (the scope-opener returns /// the strongly-typed definition; subsequent extension calls downgrade the static type). /// public static IRouteDefinition RedeliveryDelay(this IRouteDefinition self, TimeSpan delay) { if (self is OnExceptionDefinition oe) return oe.RedeliveryDelay(delay); throw new InvalidOperationException( $"RedeliveryDelay() must be called inside an OnException scope (got {self.GetType().Name})."); } // ── RichLog scope guards (only valid inside Log() scope) ────────────────── /// Guard: Message is only valid inside a Log() scope. public static IRouteDefinition Message(this IRouteDefinition self, string message) => throw new InvalidOperationException( "Message() must be called inside a Log() scope."); /// Guard: Message (factory) is only valid inside a Log() scope. public static IRouteDefinition Message(this IRouteDefinition self, Func factory) => throw new InvalidOperationException( "Message() must be called inside a Log() scope."); /// Guard: Header reader is only valid inside a Log() scope. public static IRouteDefinition Header(this IRouteDefinition self, string headerName) => throw new InvalidOperationException( "Header() must be called inside a Log() scope."); /// Guard: Property reader is only valid inside a Log() scope. public static IRouteDefinition Property(this IRouteDefinition self, string propertyName) => throw new InvalidOperationException( "Property() must be called inside a Log() scope."); // ── String overloads for the remaining lambda-only EIPs ─────────────────── // The rule set by the 4.0 breaking bundle: the string form lives on the verb itself, never // under an *Expression name. Every string compiles at declaration (StringExpression), so a // malformed expression fails while the route is built, not on the first message. /// /// Recipient List from a route-language expression. The expression may yield a collection of /// URIs or a single delimited string ("${header.targets}" with "direct:a,direct:b"). /// public static IRouteDefinition RecipientList( this IRouteDefinition self, string recipientsExpression, string delimiter = ",", bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(recipientsExpression); ArgumentException.ThrowIfNullOrEmpty(delimiter); var expression = new StringExpression(recipientsExpression); return self.RecipientList( e => SplitUris(expression.Evaluate(e), delimiter), parallelProcessing, stopOnException, aggregationStrategy); } /// /// Dynamic Router from a route-language expression evaluated before every hop: the next URI, /// or null/empty to stop routing ("property.step == 0 ? 'direct:a' : null"). /// public static IRouteDefinition DynamicRouter(this IRouteDefinition self, string routingExpression) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(routingExpression); var expression = new StringExpression(routingExpression); return self.DynamicRouter(e => { var uri = expression.Evaluate(e)?.ToString(); return string.IsNullOrWhiteSpace(uri) ? null : uri; }); } /// Resequencer keyed by a route-language expression ("header.seqNum"), converted to a long. public static ResequenceDefinition Resequence( this IRouteDefinition self, string keyExpression, int batchSize = 100, TimeSpan? timeout = null) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(keyExpression); var expression = new StringExpression(keyExpression); return self.Resequence(e => expression.Evaluate(e), batchSize, timeout); } /// Debounce keyed by a route-language expression ("header.deviceId"). public static DebounceDefinition Debounce( this IRouteDefinition self, string keyExpression, TimeSpan quietPeriod) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(keyExpression); var expression = new StringExpression(keyExpression); return self.Debounce(e => expression.Evaluate(e)?.ToString() ?? string.Empty, quietPeriod); } /// Idempotent consumer from a key expression and a repository registry name. public static IdempotentConsumerDefinition IdempotentConsumer( this IRouteDefinition self, string keyExpression, string repositoryName, bool skipDuplicate = true) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(keyExpression); var expression = new StringExpression(keyExpression); return self.IdempotentConsumer( e => expression.Evaluate(e)?.ToString() ?? string.Empty, repositoryName, skipDuplicate); } /// /// Aggregate from a correlation expression, with completion by condition, size, an inactivity /// timeout (Apache Camel completionTimeout: the clock restarts on every arrival for the /// group), or any combination — whichever fires first completes the group. At least one /// completion criterion is required: an aggregate that can never complete is a leak, not a /// default. /// public static AggregateDefinition Aggregate( this IRouteDefinition self, string correlationExpression, Func aggregationStrategy, string? completionCondition = null, int? completionSize = null, TimeSpan? completionTimeout = null) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(correlationExpression); ArgumentNullException.ThrowIfNull(aggregationStrategy); if (completionCondition is null && completionSize is null && completionTimeout is null) throw new ArgumentException( "Aggregate needs at least one completion criterion: completionCondition, completionSize or completionTimeout."); if (completionSize is < 1) throw new ArgumentOutOfRangeException(nameof(completionSize), "completionSize must be at least 1."); var correlation = new StringExpression(correlationExpression); var conditionPredicate = completionCondition is null ? null : PredicateFactory.FromString(completionCondition); var definition = self.Aggregate( e => correlation.Evaluate(e)?.ToString() ?? string.Empty, aggregationStrategy, e => conditionPredicate?.Matches(e) == true); definition.CompletionTimeout = completionTimeout; definition.CompletionSize = completionSize; return definition; } /// /// Non-generic OfType: opens the same guarded section as /// OfType<T>() for a type known only at load time — following steps run only for /// matching bodies, exactly like the generic form. Cold path: the generic method is closed by /// reflection once, while the route is being built. /// public static IRouteDefinition OfType(this IRouteDefinition self, Type bodyType) { ArgumentNullException.ThrowIfNull(self); ArgumentNullException.ThrowIfNull(bodyType); var open = typeof(IRouteDefinition).GetMethod(nameof(IRouteDefinition.OfType)) ?? throw new InvalidOperationException("IRouteDefinition.OfType() not found."); var section = open.MakeGenericMethod(bodyType).Invoke(self, null) ?? throw new InvalidOperationException($"OfType({bodyType}) returned null."); return (IRouteDefinition)section; } /// Sticky load balancing keyed by a route-language expression ("header.customerId"). public static ILoadBalancerDefinition UseSticky(this ILoadBalancerDefinition self, string keyExpression) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(keyExpression); var expression = new StringExpression(keyExpression); return self.UseSticky(e => expression.Evaluate(e)?.ToString() ?? string.Empty); } /// Normalizer clause from a condition string (compiled like Filter(string)). public static INormalizerDefinition When( this INormalizerDefinition self, string condition, Func transform) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(condition); ArgumentNullException.ThrowIfNull(transform); var predicate = PredicateFactory.FromString(condition); return self.When(predicate.Matches, transform); } private static IEnumerable SplitUris(object? value, string delimiter) { switch (value) { case null: return []; case string text: return text.Split(delimiter, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); case IEnumerable strings: return strings; case System.Collections.IEnumerable items: return EnumerateUris(items); default: return [value.ToString() ?? string.Empty]; } static IEnumerable EnumerateUris(System.Collections.IEnumerable items) { foreach (var item in items) if (item?.ToString() is { Length: > 0 } uri) yield return uri; } } } Path: redb-route/redb.Route/Extensions/RouteHealthCheck.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/Extensions/RouteHealthCheck.cs ---- #pragma warning disable CS0619 using Microsoft.Extensions.Diagnostics.HealthChecks; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Extensions; /// /// Health check that reports per-route status and endpoint health. /// Aggregates route lifecycle state and endpoint statistics into an overall health result. /// /// Unhealthy: an Errored route, or a route whose source endpoint is Critical or Failed. /// Degraded: a stopped or suspended route, a source endpoint with a Warning, or an endpoint the routes send to /// that is Critical or Failed (a broker that blocks it, a high error rate); those are listed under /// endpoints by masked URI, at most . URIs in the result never carry secrets. /// /// public sealed class RouteHealthCheck : IHealthCheck { /// How many failing send-side endpoints the result lists; the rest are counted in endpointsNotListed. public const int MaxListedEndpoints = 10; private readonly IRouteContext _context; /// Creates a route context health check. /// The route context instance. public RouteHealthCheck(IRouteContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } /// public Task CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = default) { var routes = _context.Routes; if (routes.Count == 0) { return Task.FromResult(HealthCheckResult.Degraded( "No routes are registered.")); } var overallStatus = HealthStatus.Healthy; var routeDetails = new List(routes.Count); foreach (var route in routes) { var endpointHealth = GetEndpointHealth(route); routeDetails.Add(new Dictionary { ["routeId"] = route.RouteId, ["fromUri"] = route.FromUri, ["status"] = route.Status.ToString(), ["endpointHealth"] = endpointHealth?.ToString(), ["errors"] = GetErrorCount(route), ["lastError"] = GetLastError(route), }); // Route status aggregation // An Errored route is Unhealthy unless ConsumerStartRetry's UnhealthyOnRestarting / UnhealthyOnExhausted // say Degraded for its phase (Camel's supervising route controller switches). if (route.Status == RouteStatus.Errored && (_context is not RouteContext routeContext || routeContext.IsErroredRouteUnhealthy(route))) { overallStatus = HealthStatus.Unhealthy; } else if (route.Status == RouteStatus.Errored) { if (overallStatus != HealthStatus.Unhealthy) overallStatus = HealthStatus.Degraded; } else if (route.Status is RouteStatus.Stopped or RouteStatus.Suspended or RouteStatus.Suspending or RouteStatus.Stopping && overallStatus != HealthStatus.Unhealthy) { overallStatus = HealthStatus.Degraded; } // Endpoint health aggregation if (endpointHealth is EndpointHealthStatus.Critical or EndpointHealthStatus.Failed) { overallStatus = HealthStatus.Unhealthy; } else if (endpointHealth == EndpointHealthStatus.Warning && overallStatus != HealthStatus.Unhealthy) { overallStatus = HealthStatus.Degraded; } } // The endpoints the routes send to. One that knows it is broken (a broker that blocks it, a high error rate) // makes the context Degraded, never Unhealthy: the routes still run and their consumers still take messages, // so a readiness probe must not read a broker's alarm as a dead node. Only such endpoints are listed, at most // MaxListedEndpoints, under their masked URIs: a context with many dynamic endpoints keeps a small payload. var sources = new HashSet(routes.Select(r => r.Endpoint), ReferenceEqualityComparer.Instance); var failingEndpoints = new List(); var notListed = 0; foreach (var endpoint in _context.GetEndpoints()) { if (sources.Contains(endpoint) || endpoint is not IEndpointStatistics stats) continue; var status = stats.HealthStatus; if (status is not (EndpointHealthStatus.Critical or EndpointHealthStatus.Failed)) continue; if (overallStatus == HealthStatus.Healthy) overallStatus = HealthStatus.Degraded; if (failingEndpoints.Count == MaxListedEndpoints) { notListed++; continue; } failingEndpoints.Add(new Dictionary { ["uri"] = endpoint.Uri.ToMaskedUriString(), ["endpointHealth"] = status.ToString(), ["reason"] = stats.HealthReason, }); } var data = new Dictionary { ["routeCount"] = routes.Count, ["routes"] = routeDetails, }; if (failingEndpoints.Count > 0) { data["endpoints"] = failingEndpoints; if (notListed > 0) data["endpointsNotListed"] = notListed; } var description = overallStatus switch { HealthStatus.Healthy => $"{routes.Count} route(s) running.", HealthStatus.Degraded => $"{routes.Count} route(s), some degraded.", _ => $"{routes.Count} route(s), errors detected." }; var result = new HealthCheckResult(overallStatus, description, data: data); return Task.FromResult(result); } private static EndpointHealthStatus? GetEndpointHealth(CompiledRoute route) { return route.Endpoint is IEndpointStatistics stats ? stats.HealthStatus : null; } private static long GetErrorCount(CompiledRoute route) { return route.Endpoint is IEndpointStatistics stats ? stats.Errors : 0; } private static string? GetLastError(CompiledRoute route) { if (route.Endpoint is IEndpointStatistics stats && !string.IsNullOrEmpty(stats.LastErrorMessage)) return stats.LastErrorMessage; return null; } } Path: redb-route/redb.Route/Extensions/RouteHostedService.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/Extensions/RouteHostedService.cs ---- using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace redb.Route.Extensions; /// /// integration for the route context. /// Starts and stops routes with the application lifecycle. /// Register via . /// public sealed class RouteHostedService : IHostedService, IAsyncDisposable { private readonly RouteContext _context; private readonly IEnumerable _configurators; private readonly ILogger _logger; /// Creates a new hosted service wrapping the route context. /// Route context instance (resolved from DI). /// Context configurators (route builders, components, inline routes). /// Logger. public RouteHostedService( RouteContext context, IEnumerable configurators, ILogger logger) { _context = context ?? throw new ArgumentNullException(nameof(context)); _configurators = configurators ?? throw new ArgumentNullException(nameof(configurators)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Starting redb.Route hosted service..."); // Apply all DI-registered configurators (route builders, components, inline routes) foreach (var configurator in _configurators) { configurator.Configure(_context); } await _context.Start(cancellationToken).ConfigureAwait(false); _logger.LogInformation("redb.Route hosted service started with {Count} route(s).", _context.Routes.Count); } /// public async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stopping redb.Route hosted service..."); await _context.Stop(cancellationToken).ConfigureAwait(false); _logger.LogInformation("redb.Route hosted service stopped."); } /// public async ValueTask DisposeAsync() { await _context.DisposeAsync().ConfigureAwait(false); } } Path: redb-route/redb.Route/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/Extensions/ServiceCollectionExtensions.cs ---- #pragma warning disable CS0619 using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Extensions; /// /// Extension methods for registering redb.Route in a Microsoft.Extensions.DependencyInjection container. /// public static class ServiceCollectionExtensions { /// /// Registers the route context, hosted service, and route builders. /// /// /// services.AddRedbRoute(route => /// { /// route.AddRouteBuilder<MyRoutes>(); /// route.AddComponent(new RedisComponent()); /// }); /// /// /// /// Service collection. /// Optional configuration action. /// The service collection for chaining. public static IServiceCollection AddRedbRoute( this IServiceCollection services, Action? configure = null) { ArgumentNullException.ThrowIfNull(services); // Register context as singleton — one context per host services.TryAddSingleton(sp => { var loggerFactory = sp.GetService(); var options = sp.GetService>()?.Value; return new RouteContext(loggerFactory: loggerFactory, options: options); }); // Shared registry for cross-context direct-vm / vm components services.TryAddSingleton(); // Register IRouteContext as the same singleton services.TryAddSingleton(sp => sp.GetRequiredService()); // Register the hosted service services.AddHostedService(); // Apply user configuration if (configure != null) { var builder = new RedbRouteBuilder(services); configure(builder); } return services; } /// /// Registers a component as a singleton and hooks it into the route context through /// — the hook /// applies at startup. This is THE registration primitive for connector packages /// (AddRedbRouteKafka() and friends): a lazy marker singleton that nobody /// resolves never reaches the context. /// /// Concrete component type. public static IServiceCollection AddRouteComponent(this IServiceCollection services) where TComponent : class, IComponent { services.TryAddSingleton(); services.AddSingleton(sp => new ComponentConfigurator(sp)); return services; } /// /// Registers an arbitrary startup callback as an . /// For connectors whose registration is more than a bare AddComponent — wiring a /// shared server manager, several components, named registry entries. /// public static IServiceCollection AddRouteContextConfigurator( this IServiceCollection services, Action configure) { ArgumentNullException.ThrowIfNull(configure); services.AddSingleton(sp => new DelegateContextConfigurator(sp, configure)); return services; } } /// Applies a delegate against the context at startup (see ). internal sealed class DelegateContextConfigurator : IRouteContextConfigurator { private readonly IServiceProvider _sp; private readonly Action _configure; public DelegateContextConfigurator(IServiceProvider sp, Action configure) { _sp = sp; _configure = configure; } public void Configure(RouteContext context) => _configure(_sp, context); } /// /// Fluent builder for configuring route context registration within DI. /// public sealed class RedbRouteBuilder { private readonly IServiceCollection _services; /// Creates a new builder. internal RedbRouteBuilder(IServiceCollection services) { _services = services; } /// Gets the underlying service collection for advanced scenarios. public IServiceCollection Services => _services; /// /// Registers a implementation. /// Instances are resolved from DI, so constructor injection works. /// /// Concrete route builder type. /// This builder for chaining. /// was already added by . public RedbRouteBuilder AddRouteBuilder() where TBuilder : RouteBuilder { if (IsDiscovered(typeof(TBuilder))) throw new InvalidOperationException( $"Route builder '{typeof(TBuilder).FullName}' was already added by AddRouteBuilders. " + "Leave it out of the discovery with the filter, or do not add it again."); // Register the CONCRETE type (the configurator resolves TBuilder) and expose the SAME singleton as the // base RouteBuilder for enumeration. Registering only the base left GetRequiredService() // unresolvable, so host startup threw "No service for type '…' has been registered". _services.AddSingleton(); _services.AddSingleton(sp => sp.GetRequiredService()); // Hook up to context via a post-configure callback _services.AddSingleton(sp => new RouteBuilderConfigurator(sp)); return this; } /// /// Registers every route builder of — each public, non-abstract, closed class /// deriving from — as does, so constructor /// injection works (Apache Camel's routes discovery). /// /// Assemblies to scan; at least one. /// This builder for chaining. /// /// A builder type is already registered, or an assembly's types cannot all be loaded. Nothing is registered then. /// public RedbRouteBuilder AddRouteBuilders(params Assembly[] assemblies) => AddDiscoveredRouteBuilders(assemblies, filter: null); /// /// with a filter choosing which builders to take — the place for a /// condition (environment, configuration) and for leaving a builder out. /// /// Assemblies to scan; at least one. /// Returns true for a builder type to register. /// This builder for chaining. /// As . public RedbRouteBuilder AddRouteBuilders(IEnumerable assemblies, Func filter) { ArgumentNullException.ThrowIfNull(filter); return AddDiscoveredRouteBuilders(assemblies, filter); } private RedbRouteBuilder AddDiscoveredRouteBuilders(IEnumerable assemblies, Func? filter) { var types = RouteBuilderDiscovery.FindBuilderTypes(assemblies, filter); // A type already registered would add its routes twice and fail only at host start with a duplicate route // id; said now, with the type's name. Checked for all before any is registered. foreach (var type in types) { if (_services.Any(d => d.ServiceType == type) || IsDiscovered(type)) throw new InvalidOperationException( $"Route builder '{type.FullName}' is already registered. " + "Leave it out of the discovery with the filter, or do not register it explicitly."); } foreach (var type in types) { // The AddRouteBuilder shape: the concrete type, the same singleton as RouteBuilder, a configurator // that adds it to the context — the container builds it, so its constructor may take services. _services.AddSingleton(type); _services.AddSingleton(sp => (RouteBuilder)sp.GetRequiredService(type)); _services.AddSingleton(sp => new DiscoveredRouteBuilderConfigurator(sp, type)); _services.AddSingleton(new DiscoveredRouteBuilder(type)); } return this; } private bool IsDiscovered(Type builderType) => _services.Any(d => d.ImplementationInstance is DiscoveredRouteBuilder discovered && discovered.BuilderType == builderType); /// /// Registers a component for a custom URI scheme. /// /// Concrete component type. /// This builder for chaining. public RedbRouteBuilder AddComponent() where TComponent : class, IComponent { // Same fix as AddRouteBuilder: the ComponentConfigurator resolves the concrete TComponent, so register // it directly and expose the same singleton as IComponent for enumeration. _services.AddSingleton(); _services.AddSingleton(sp => sp.GetRequiredService()); _services.AddSingleton(sp => new ComponentConfigurator(sp)); return this; } /// /// Registers an inline route builder using an action. /// /// Action to define routes inline. /// This builder for chaining. public RedbRouteBuilder AddRoutes(Action configure) { ArgumentNullException.ThrowIfNull(configure); _services.AddSingleton( _ => new InlineRouteConfigurator(configure)); return this; } } /// /// Contract for context configuration callbacks applied before start. /// Implementations are resolved from DI and applied by . /// public interface IRouteContextConfigurator { /// Applies configuration to the context. void Configure(RouteContext context); } internal sealed class RouteBuilderConfigurator : IRouteContextConfigurator where TBuilder : RouteBuilder { private readonly IServiceProvider _sp; public RouteBuilderConfigurator(IServiceProvider sp) => _sp = sp; public void Configure(RouteContext context) { var builder = _sp.GetRequiredService(); context.AddRoutes(builder); } } /// Adds a route builder registered by to the context. internal sealed class DiscoveredRouteBuilderConfigurator : IRouteContextConfigurator { private readonly IServiceProvider _sp; private readonly Type _builderType; public DiscoveredRouteBuilderConfigurator(IServiceProvider sp, Type builderType) { _sp = sp; _builderType = builderType; } public void Configure(RouteContext context) => context.AddRoutes((RouteBuilder)_sp.GetRequiredService(_builderType)); } /// Marks a route builder type registered by assembly discovery, so a second registration of it is refused. internal sealed record DiscoveredRouteBuilder(Type BuilderType); internal sealed class ComponentConfigurator : IRouteContextConfigurator where TComponent : class, IComponent { private readonly IServiceProvider _sp; public ComponentConfigurator(IServiceProvider sp) => _sp = sp; public void Configure(RouteContext context) { var component = _sp.GetRequiredService(); context.AddComponent(component); } } internal sealed class InlineRouteConfigurator : IRouteContextConfigurator { private readonly Action _configure; public InlineRouteConfigurator(Action configure) => _configure = configure; public void Configure(RouteContext context) => context.AddRoutes(_configure); } Path: redb-route/redb.Route/Fluent/Direct.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/Fluent/Direct.cs ---- namespace redb.Route; /// /// Fluent entry point for Direct (synchronous in-process) endpoints. /// /// .From(Direct.Endpoint("input")) /// .To(Direct.Endpoint("processing")) /// /// public static class Direct { /// Reference a named direct endpoint (no configuration parameters). public static DirectBuilder Endpoint(string name) => new(name); } /// Fluent builder for Direct endpoint URIs. public sealed class DirectBuilder { private readonly string _name; internal DirectBuilder(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _name = name; } public string Build() => $"direct:{_name}"; public static implicit operator string(DirectBuilder b) => b.Build(); public override string ToString() => Build(); } Path: redb-route/redb.Route/Fluent/LogDsl.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/Fluent/LogDsl.cs ---- using System.Text; namespace redb.Route; /// /// Fluent entry point for Log producer endpoints. /// /// .To(LogDsl.Info("myLogger").ShowHeaders().ShowBody()) /// .To(LogDsl.Debug("trace")) /// /// public static class LogDsl { public static LogBuilder Trace(string name) => new(name, "Trace"); public static LogBuilder Debug(string name) => new(name, "Debug"); public static LogBuilder Info(string name) => new(name, "Information"); public static LogBuilder Warn(string name) => new(name, "Warning"); public static LogBuilder Error(string name) => new(name, "Error"); } /// Fluent builder for Log endpoint URIs. public sealed class LogBuilder { private readonly string _name; private readonly string _level; private bool _showHeaders; private bool _showBody; internal LogBuilder(string name, string level) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _name = name; _level = level; } /// Include message headers in log output. public LogBuilder ShowHeaders() { _showHeaders = true; return this; } /// Include message body in log output. public LogBuilder ShowBody() { _showBody = true; return this; } public string Build() { var sb = new StringBuilder(); sb.Append("log:"); sb.Append(_name); var sep = '?'; void Append(string key, string v) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(v); sep = '&'; } void AppendBool(string key, bool v) { if (v) Append(key, "true"); } Append("level", _level); AppendBool("showHeaders", _showHeaders); AppendBool("showBody", _showBody); return sb.ToString(); } public static implicit operator string(LogBuilder b) => b.Build(); public override string ToString() => Build(); } Path: redb-route/redb.Route/Fluent/MockDsl.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/Fluent/MockDsl.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route; /// /// Fluent entry point for Mock endpoints (testing). /// /// .To(MockDsl.Endpoint("result").ExpectedMessageCount(3)) /// /// public static class MockDsl { /// Create a named mock endpoint. public static MockBuilder Endpoint(string name) => new(name); } /// Fluent builder for Mock endpoint URIs. public sealed class MockBuilder { private readonly string _name; private string? _expectedMessageCount; internal MockBuilder(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _name = name; } /// Expected number of messages to receive. public MockBuilder ExpectedMessageCount(int count) { _expectedMessageCount = count.ToString(); return this; } /// Expected message count from an expression. public MockBuilder ExpectedMessageCount(IExpression count) { _expectedMessageCount = count.ToTemplateString(); return this; } public string Build() { var sb = new StringBuilder(); sb.Append("mock:"); sb.Append(_name); if (_expectedMessageCount != null) { sb.Append("?expectedMessageCount="); sb.Append(_expectedMessageCount); } return sb.ToString(); } public static implicit operator string(MockBuilder b) => b.Build(); public override string ToString() => Build(); } Path: redb-route/redb.Route/Fluent/Seda.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/Fluent/Seda.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route; /// /// Fluent entry point for SEDA (Staged Event-Driven Architecture) in-memory queue endpoints. /// /// .From(Seda.Consume("orders").ConcurrentConsumers(5).Size(1000)) /// .To(Seda.Send("orders")) /// /// public static class Seda { /// Consume from a named SEDA queue. public static SedaBuilder Consume(string name) => new(name); /// Send to a named SEDA queue. public static SedaBuilder Send(string name) => new(name); } /// Fluent builder for SEDA endpoint URIs. public sealed class SedaBuilder { private readonly string _name; private string? _concurrentConsumers; private string? _size; private string? _timeout; internal SedaBuilder(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _name = name; } /// Number of concurrent consumer threads. Default 1. public SedaBuilder ConcurrentConsumers(int count) { _concurrentConsumers = count.ToString(); return this; } /// Concurrent consumers from an expression. public SedaBuilder ConcurrentConsumers(IExpression count) { _concurrentConsumers = count.ToTemplateString(); return this; } /// Maximum queue capacity. Default unbounded. public SedaBuilder Size(int size) { _size = size.ToString(); return this; } /// Queue size from an expression. public SedaBuilder Size(IExpression size) { _size = size.ToTemplateString(); return this; } /// Timeout in ms when queue is full. Default infinite. public SedaBuilder Timeout(int ms) { _timeout = ms.ToString(); return this; } /// Timeout from an expression. public SedaBuilder Timeout(IExpression ms) { _timeout = ms.ToTemplateString(); return this; } /// Builds the SEDA URI string. public string Build() { var sb = new StringBuilder(); sb.Append("seda:"); sb.Append(_name); var sep = '?'; void AppendIf(string key, string? v) { if (v != null) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(v); sep = '&'; } } AppendIf("concurrentConsumers", _concurrentConsumers); AppendIf("size", _size); AppendIf("timeout", _timeout); return sb.ToString(); } public static implicit operator string(SedaBuilder b) => b.Build(); public override string ToString() => Build(); } Path: redb-route/redb.Route/Fluent/TimerDsl.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/Fluent/TimerDsl.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route; /// /// Fluent entry point for Timer consumer endpoints. /// /// .From(Timer.Every("heartbeat").Period(5000).Delay(1000)) /// .From(Timer.Once("init")) /// /// public static class TimerDsl { /// Create a named repeating timer. public static TimerBuilder Every(string name) => new(name); /// Create a timer that fires once (repeatCount=1). public static TimerBuilder Once(string name) => new TimerBuilder(name).RepeatCount(1); } /// Fluent builder for Timer endpoint URIs. public sealed class TimerBuilder { private readonly string _name; private string? _period; private string? _delay; private string? _repeatCount; internal TimerBuilder(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _name = name; } /// Interval between ticks in milliseconds. Default 1000. public TimerBuilder Period(int ms) { _period = ms.ToString(); return this; } /// Interval from an expression. public TimerBuilder Period(IExpression ms) { _period = ms.ToTemplateString(); return this; } /// Initial delay before first tick in milliseconds. public TimerBuilder Delay(int ms) { _delay = ms.ToString(); return this; } /// Initial delay from an expression. public TimerBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; } /// Number of times to fire. Default unlimited (0). public TimerBuilder RepeatCount(int count) { _repeatCount = count.ToString(); return this; } /// Repeat count from an expression. public TimerBuilder RepeatCount(IExpression count) { _repeatCount = count.ToTemplateString(); return this; } public string Build() { var sb = new StringBuilder(); sb.Append("timer:"); sb.Append(_name); var sep = '?'; void AppendIf(string key, string? v) { if (v != null) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(v); sep = '&'; } } AppendIf("period", _period); AppendIf("delay", _delay); AppendIf("repeatCount", _repeatCount); return sb.ToString(); } public static implicit operator string(TimerBuilder b) => b.Build(); public override string ToString() => Build(); } Path: redb-route/redb.Route/Predicates/AndPredicate.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/Predicates/AndPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that performs a logical AND between an expression and another predicate. /// Returns true only when both the expression evaluates to true and the predicate matches. /// public class AndPredicate : IPredicate { private readonly IExpression _expression; private readonly IPredicate _predicate; /// /// Initializes a new instance combining an expression and a predicate with logical AND. /// /// The expression to evaluate (left-hand side of AND). /// The predicate to check (right-hand side of AND). public AndPredicate(IExpression expression, IPredicate predicate) { _expression = expression; _predicate = predicate; } /// public bool Matches(IExchange exchange) { bool expressionResult = _expression.Evaluate(exchange); return expressionResult && _predicate.Matches(exchange); } /// public async Task MatchesAsync(IExchange exchange) { bool expressionResult = _expression.Evaluate(exchange); return expressionResult && await _predicate.MatchesAsync(exchange).ConfigureAwait(false); } } Path: redb-route/redb.Route/Predicates/BetweenPredicate.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/Predicates/BetweenPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result falls between two values (inclusive). /// public class BetweenPredicate : IPredicate { private readonly IExpression _expression; private readonly IComparable _low; private readonly IComparable _high; /// /// Initializes a new instance with the specified expression and boundary values. /// /// The expression to evaluate. /// The lower bound (inclusive, must implement ). /// The upper bound (inclusive, must implement ). public BetweenPredicate(IExpression expression, object low, object high) { _expression = expression; _low = (IComparable)low; _high = (IComparable)high; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result?.CompareTo(_low) >= 0 && result?.CompareTo(_high) <= 0; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/ContainsPredicate.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/Predicates/ContainsPredicate.cs ---- using System.Collections; using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether a string contains a substring or a collection contains an element. /// public class ContainsPredicate : IPredicate { private readonly IExpression _expression; private readonly object _value; /// /// Initializes a new instance with the specified expression and value to search for. /// /// The expression to evaluate. /// The substring or element to look for. public ContainsPredicate(IExpression expression, object value) { _expression = expression; _value = value; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); if (result is string str && _value is string substr) return str.Contains(substr); if (result is IEnumerable enumerable) { foreach (var item in enumerable) { if (object.Equals(item, _value)) return true; } } return false; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/EndsWithPredicate.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/Predicates/EndsWithPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether a string expression result ends with a given value. /// public class EndsWithPredicate : IPredicate { private readonly IExpression _expression; private readonly string _value; /// /// Initializes a new instance with the specified expression and suffix value. /// /// The expression to evaluate. /// The suffix to check for. public EndsWithPredicate(IExpression expression, object value) { _expression = expression; _value = value?.ToString() ?? string.Empty; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result?.EndsWith(_value) == true; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/EqualsPredicate.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/Predicates/EqualsPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result equals a given value. /// public class EqualsPredicate : IPredicate { private readonly IExpression _expression; private readonly object _value; /// /// Initializes a new instance with the specified expression and comparison value. /// /// The expression to evaluate. /// The value to compare against. public EqualsPredicate(IExpression expression, object value) { _expression = expression; _value = value; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return Equals(result, _value); } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/GreaterThanOrEqualPredicate.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/Predicates/GreaterThanOrEqualPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result is greater than or equal to a given value. /// public class GreaterThanOrEqualPredicate : IPredicate { private readonly IExpression _expression; private readonly IComparable _value; /// /// Initializes a new instance with the specified expression and comparison value. /// /// The expression to evaluate. /// The value to compare against (must implement ). public GreaterThanOrEqualPredicate(IExpression expression, object value) { _expression = expression; _value = (IComparable)value; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result?.CompareTo(_value) >= 0; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/GreaterThanPredicate.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/Predicates/GreaterThanPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result is greater than a given value. /// public class GreaterThanPredicate : IPredicate { private readonly IExpression _expression; private readonly IComparable _value; /// /// Initializes a new instance with the specified expression and comparison value. /// /// The expression to evaluate. /// The value to compare against (must implement ). public GreaterThanPredicate(IExpression expression, object value) { _expression = expression; _value = (IComparable)value; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result?.CompareTo(_value) > 0; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/InPredicate.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/Predicates/InPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result is contained in a specified set of values. /// public class InPredicate : IPredicate { private readonly IExpression _expression; private readonly HashSet _values; /// /// Initializes a new instance with the specified expression and allowed values. /// /// The expression to evaluate. /// The set of values to check membership against. public InPredicate(IExpression expression, params object[] values) { _expression = expression; _values = new HashSet(values); } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return _values.Contains(result); } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/IsNotNullPredicate.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/Predicates/IsNotNullPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result is not null. /// public class IsNotNullPredicate : IPredicate { private readonly IExpression _expression; /// /// Initializes a new instance with the specified expression. /// /// The expression to evaluate. public IsNotNullPredicate(IExpression expression) { _expression = expression; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result != null; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/IsNullPredicate.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/Predicates/IsNullPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result is null. /// public class IsNullPredicate : IPredicate { private readonly IExpression _expression; /// /// Initializes a new instance with the specified expression. /// /// The expression to evaluate. public IsNullPredicate(IExpression expression) { _expression = expression; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result == null; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/LambdaPredicate.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/Predicates/LambdaPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that wraps a delegate for inline predicate logic. /// public class LambdaPredicate : IPredicate { private readonly Func _predicate; /// /// Initializes a new instance with the specified delegate. /// /// The delegate that evaluates the predicate condition. public LambdaPredicate(Func predicate) { _predicate = predicate ?? throw new ArgumentNullException(nameof(predicate)); } /// public bool Matches(IExchange exchange) { return _predicate(exchange); } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/LessThanOrEqualPredicate.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/Predicates/LessThanOrEqualPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result is less than or equal to a given value. /// public class LessThanOrEqualPredicate : IPredicate { private readonly IExpression _expression; private readonly IComparable _value; /// /// Initializes a new instance with the specified expression and comparison value. /// /// The expression to evaluate. /// The value to compare against (must implement ). public LessThanOrEqualPredicate(IExpression expression, object value) { _expression = expression; _value = (IComparable)value; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result?.CompareTo(_value) <= 0; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/LessThanPredicate.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/Predicates/LessThanPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result is less than a given value. /// public class LessThanPredicate : IPredicate { private readonly IExpression _expression; private readonly IComparable _value; /// /// Initializes a new instance with the specified expression and comparison value. /// /// The expression to evaluate. /// The value to compare against (must implement ). public LessThanPredicate(IExpression expression, object value) { _expression = expression; _value = (IComparable)value; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result?.CompareTo(_value) < 0; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/NotEqualsPredicate.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/Predicates/NotEqualsPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether an expression result does not equal a given value. /// public class NotEqualsPredicate : IPredicate { private readonly IExpression _expression; private readonly object _value; /// /// Initializes a new instance with the specified expression and comparison value. /// /// The expression to evaluate. /// The value to compare against. public NotEqualsPredicate(IExpression expression, object value) { _expression = expression; _value = value; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return !object.Equals(result, _value); } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/NotPredicate.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/Predicates/NotPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that negates the boolean result of an expression (logical NOT). /// public class NotPredicate : IPredicate { private readonly IExpression _expression; /// /// Initializes a new instance with the expression to negate. /// /// The expression whose boolean result will be inverted. public NotPredicate(IExpression expression) { _expression = expression ?? throw new ArgumentNullException(nameof(expression)); } /// public bool Matches(IExchange exchange) { return !_expression.Evaluate(exchange); } /// public Task MatchesAsync(IExchange exchange) { return Task.Run(() => { return !_expression.Evaluate(exchange); }); } } Path: redb-route/redb.Route/Predicates/OrPredicate.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/Predicates/OrPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that performs a logical OR between an expression and another predicate. /// Returns true when either the expression evaluates to true or the predicate matches. /// public class OrPredicate : IPredicate { private readonly IExpression _expression; private readonly IPredicate _predicate; /// /// Initializes a new instance combining an expression and a predicate with logical OR. /// /// The expression to evaluate (left-hand side of OR). /// The predicate to check (right-hand side of OR). public OrPredicate(IExpression expression, IPredicate predicate) { _expression = expression; _predicate = predicate; } /// public bool Matches(IExchange exchange) { bool expressionResult = _expression.Evaluate(exchange); return expressionResult || _predicate.Matches(exchange); } /// public async Task MatchesAsync(IExchange exchange) { bool expressionResult = _expression.Evaluate(exchange); return expressionResult || await _predicate.MatchesAsync(exchange).ConfigureAwait(false); } } Path: redb-route/redb.Route/Predicates/PredicateFactory.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/Predicates/PredicateFactory.cs ---- using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Predicates; /// /// The single place that turns a DSL condition string into an . /// Every string-taking condition overload (Filter, When, LoopWhile, Validate) routes through it, /// so a condition behaves identically no matter where it was written. /// /// A condition is a boolean expression, which is a different position in the language from a /// value: SetBody("black and white") must stay a literal, while /// Filter("header.a>10") must be a comparison. The two positions therefore compile /// differently, and this type is the boundary between them. /// /// public static class PredicateFactory { /// /// Builds a predicate from a condition string. Three shapes, one rule each: /// /// a ${...} template is interpolated to a string and read for truthiness; /// a condition carrying a comparison or word-logic operator is a boolean expression /// and is parsed by the AST parser, which tokenises the input: whitespace between tokens /// carries no meaning (header.a>10, header.a > 10 and a tab- or /// newline-separated form are one expression) and an operator inside a quoted literal is /// not an operator; /// anything else is a value read for truthiness, which keeps a bare accessor such as /// property.cfg.enabled resolving exactly as it always has. /// /// Compilation happens here, while the route is being built, so a condition the parser cannot /// accept fails at build time instead of turning into a constant answer on live traffic. /// /// The condition string as written by the route author. /// A predicate that evaluates the condition against an exchange. /// Thrown when is null, empty or whitespace. /// Thrown when the condition cannot be compiled. public static IPredicate FromString(string condition) { ArgumentException.ThrowIfNullOrWhiteSpace(condition); if (ExpressionResolver.IsTemplate(condition)) { var template = ExpressionResolver.GetCompiledTemplate(condition); return new LambdaPredicate(exchange => RouteTruthiness.ToBoolean(template(exchange))); } var compiled = ExpressionResolver.ContainsComparisonOrWordLogicOperator(condition) ? ExpressionResolver.GetCompiledValueExpressionWithAst(condition) : ExpressionResolver.GetCompiledValueExpression(condition); return new LambdaPredicate(exchange => RouteTruthiness.ToBoolean(compiled(exchange))); } /// /// Builds a predicate from an expression instance used in a condition position. /// /// An expression born from a string (Expr("header.amount>1000")) is a condition /// string that happened to be wrapped, so it takes the same path as /// : compiled as a condition, whitespace-insensitive, fail-fast. /// Reading it as a value first would resurrect the original silent-drop defect: the value /// dialect turned the unspaced comparison into a lookup of a header named /// amount>1000, which never exists. /// /// /// An expression that implements answers the condition itself. /// A query language brings its own notion of a match that evaluating-then-reading-truthiness /// cannot reconstruct: XPath("/order/discount") in a condition asks whether the path /// matched, and flattening the node-set to a value first would answer with the node's content /// instead — <discount>0</discount> would read as "no match". Asking the /// expression keeps that decision where the language's semantics live. /// /// /// Any other expression is evaluated and read through . /// /// /// The expression written in a condition position. /// A predicate that evaluates the expression against an exchange. public static IPredicate FromExpression(IExpression expression) { ArgumentNullException.ThrowIfNull(expression); if (expression is StringExpression text) return FromString(text.Template); // An expression that is a predicate too (Method()) answers the condition itself, asynchronously included. if (expression is IPredicate predicate) return predicate; if (expression is IPredicateExpression self) return new LambdaPredicate(self.Matches); return new LambdaPredicate(exchange => RouteTruthiness.ToBoolean(expression.Evaluate(exchange))); } } Path: redb-route/redb.Route/Predicates/RegexPredicate.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/Predicates/RegexPredicate.cs ---- using System.Text.RegularExpressions; using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether a string expression result matches a regular expression pattern. /// public class RegexPredicate : IPredicate { private readonly IExpression _expression; private readonly Regex _regex; /// /// Initializes a new instance with the specified expression and regex pattern. /// /// The expression to evaluate. /// The regular expression pattern to match against. public RegexPredicate(IExpression expression, string pattern) { _expression = expression; _regex = new Regex(pattern); } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result != null && _regex.IsMatch(result); } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Predicates/RouteTruthiness.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/Predicates/RouteTruthiness.cs ---- namespace redb.Route.Predicates; /// /// The single truthiness rule of the DSL. Every place that turns a value into a boolean — the /// condition positions (Filter, When, LoopWhile, Validate), the word-logic operators /// (AND/OR/XOR/NOT) and the logical() function — goes through /// this one method, so a value cannot be true in one position and false in another. /// /// The rule: a bool is itself; a number is "non-zero means true"; a string is parsed as a boolean /// word first (true/false, 1/0, yes/no, on/off, y/n) and /// otherwise read as "non-empty means true"; null is false; any other object exists and is /// therefore true. /// /// /// History note: until 2026-08-28 three different rules coexisted — this one (without the numeric /// and word cases), the AST operand conversion, and the hand-written logical branch — and they /// disagreed on 0, "0" and "no": Filter("${header.zero}") passed a /// message while Filter("logical(header.zero)") dropped it. The merge is recorded in the /// changelog; the characterisation snapshot pins every form the merge moved. /// /// internal static class RouteTruthiness { /// Converts an evaluated expression result to a boolean by the DSL truthiness rule. /// The evaluated expression result. /// The boolean reading of . internal static bool ToBoolean(object? value) => value switch { null => false, bool b => b, string s => StringToBoolean(s), sbyte n => n != 0, byte n => n != 0, short n => n != 0, ushort n => n != 0, int n => n != 0, uint n => n != 0, long n => n != 0, ulong n => n != 0, float n => n != 0f, double n => n != 0d, decimal n => n != 0m, _ => true }; /// /// Reads a string as a boolean: a recognised boolean word wins, anything else is /// "non-empty means true". /// private static bool StringToBoolean(string value) => TryParseBooleanWord(value, out var parsed) ? parsed : value.Length > 0; /// /// Tries to read a string as an explicit boolean word. Shared with the expression engine so /// the words recognised by logical(), by equality coercion and by the condition /// positions never drift apart. The set is English-only by design: a routing language must /// not change meaning with the author's locale (the historical set also recognised Russian /// words; they now read as ordinary non-empty strings). /// /// The string to parse. /// The parsed boolean when recognised. /// true when the string is a recognised boolean word. internal static bool TryParseBooleanWord(string value, out bool result) { result = false; if (string.IsNullOrEmpty(value)) return false; if (bool.TryParse(value, out result)) return true; switch (value.Trim().ToLowerInvariant()) { case "1" or "yes" or "y" or "on": result = true; return true; case "0" or "no" or "n" or "off": result = false; return true; default: return false; } } } Path: redb-route/redb.Route/Predicates/StartsWithPredicate.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/Predicates/StartsWithPredicate.cs ---- using redb.Route.Abstractions; namespace redb.Route.Predicates; /// /// Predicate that checks whether a string expression result starts with a given value. /// public class StartsWithPredicate : IPredicate { private readonly IExpression _expression; private readonly string _value; /// /// Initializes a new instance with the specified expression and prefix value. /// /// The expression to evaluate. /// The prefix to check for. public StartsWithPredicate(IExpression expression, object value) { _expression = expression; _value = value?.ToString() ?? string.Empty; } /// public bool Matches(IExchange exchange) { var result = _expression.Evaluate(exchange); return result?.StartsWith(_value) == true; } /// public Task MatchesAsync(IExchange exchange) => Task.FromResult(Matches(exchange)); } Path: redb-route/redb.Route/Processors/AggregatorProcessor.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/Processors/AggregatorProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Aggregates multiple exchanges into a single exchange using a correlation key and completion predicate. /// Collects exchanges with the same correlation key, then applies the aggregation strategy /// when the completion predicate is satisfied. /// public class AggregatorProcessor : IProcessor, IAsyncDisposable, IStopAwareProcessor { /// /// Apache Camel forceCompletionOnStop: the groups still open when the context stops complete with what they /// have. Without it they are dropped, with a warning naming how many. /// internal bool ForceCompletionOnStop { get; init; } /// Logs groups dropped or failing to complete on stop. internal ILogger? Logger { get; init; } /// /// The target for a group completed by the timeout or on stop — after every exchange that fed it has left the /// route's error wrappers: the target wrapped by the route's error scope. null outside a route compiler, /// where the target is used as it is. /// internal IProcessor? DetachedTarget { get; init; } /// /// Apache Camel completionSize: a group completes once it has combined this many exchanges. Checked after /// the completion predicate, as Camel checks them. null: no size criterion. /// public int? CompletionSize { get => _completionSize; init { if (value is < 1) throw new ArgumentOutOfRangeException(nameof(CompletionSize), "completionSize must be at least 1."); _completionSize = value; } } private readonly int? _completionSize; /// Values of , Camel's names. internal static class CompletedBy { public const string Size = "size"; public const string Predicate = "predicate"; public const string Timeout = "timeout"; public const string Force = "force"; } private readonly Func _correlationKey; private readonly Func _aggregationStrategy; private readonly Func _completionPredicate; private readonly IProcessor _target; // A group outlives the calls that fed it, so it holds exchanges of its own (Camel copies an exchange into its // aggregation repository): every arrival is taken over - its bodies and a way to a DI scope - and all of them are // released once the group has gone on down the route, or has been dropped. private sealed class Group(string key, IExchange aggregate) { public string Key { get; } = key; public IExchange Aggregate { get; set; } = aggregate; public List Members { get; } = [aggregate]; /// Number of exchanges combined so far (Camel's CamelAggregatedSize). public int Size { get; set; } = 1; } private readonly Dictionary _aggregated = new(StringComparer.Ordinal); private readonly object _lock = new(); // ── Inactivity timeout (Camel completionTimeout parity) ────────────────────────────── // A group whose last arrival is older than the timeout completes with what it has. The // flush rides a periodic scan timer, the same shape the resequencer established: the // callback is fire-and-forget, an exception from the target lands on the exchange. private readonly TimeSpan? _completionTimeout; private readonly Dictionary _lastArrival = new(StringComparer.Ordinal); private Timer? _timer; private readonly CancellationTokenSource _disposeCts = new(); private int _disposed; /// Creates an aggregator processor. /// Function to extract the correlation key from an exchange. /// /// Function to merge a new exchange into the existing aggregate. /// Receives (oldAggregate, newExchange) and returns the merged exchange. /// /// /// Predicate that returns true when aggregation is complete for a given group. /// Evaluated after each merge. /// /// Processor to handle the completed aggregate. public AggregatorProcessor( Func correlationKey, Func aggregationStrategy, Func completionPredicate, IProcessor target) : this(correlationKey, aggregationStrategy, completionPredicate, target, completionTimeout: null) { } /// /// Creates an aggregator with an inactivity timeout: a group that receives nothing for /// completes with what it has accumulated (Apache Camel /// completionTimeout semantics — the clock restarts on every arrival for the group). /// public AggregatorProcessor( Func correlationKey, Func aggregationStrategy, Func completionPredicate, IProcessor target, TimeSpan? completionTimeout) { _correlationKey = correlationKey ?? throw new ArgumentNullException(nameof(correlationKey)); _aggregationStrategy = aggregationStrategy ?? throw new ArgumentNullException(nameof(aggregationStrategy)); _completionPredicate = completionPredicate ?? throw new ArgumentNullException(nameof(completionPredicate)); _target = target ?? throw new ArgumentNullException(nameof(target)); if (completionTimeout is { } t && t <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(completionTimeout), "completionTimeout must be positive."); _completionTimeout = completionTimeout; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var key = _correlationKey(exchange); // The caller disposes its exchange as soon as this returns; the group keeps a copy that owns the bodies. var held = exchange is Core.Exchange own ? own.TakeOver() : exchange.Clone(); Group? completed = null; string? completedBy = null; var groupCreated = false; lock (_lock) { if (_aggregated.TryGetValue(key, out var group)) { var merged = _aggregationStrategy(group.Aggregate, held); group.Members.Add(held); if (!group.Members.Contains(merged)) group.Members.Add(merged); group.Aggregate = merged; group.Size++; } else { group = new Group(key, held); _aggregated[key] = group; groupCreated = true; } // As Camel's: the aggregate carries its size and key while it collects, so the completion predicate can // read them. MarkAggregate(group); completedBy = CompletionOf(group); if (completedBy is not null) { completed = group; RemoveGroup(key); groupCreated = false; } else { TouchGroup(key); } } if (groupCreated) ProcessorMetrics.AggregatorInflightGroups.Add(1); if (completed != null) { ProcessorMetrics.AggregatorCompleted.Add(1); if (completed.Size > 1) ProcessorMetrics.AggregatorInflightGroups.Add(-1); // Completed by this arrival: a failure of the completed group is this call's failure too, as it was when // the group went on with the caller's own exchange. var aggregate = await CompleteAsync(completed, completedBy!, _target, ct).ConfigureAwait(false); if (aggregate.Exception is { } failure && !aggregate.ExceptionHandled) exchange.Exception ??= failure; } // Pre-completion inputs are consumed silently: only completed aggregates flow to // _target (the route tail). The aggregator is wired as tail-consuming, so no // downstream pipeline steps follow it inside the same PipelineProcessor. } /// Gets the number of currently pending aggregation groups. public int PendingGroupCount { get { lock (_lock) return _aggregated.Count; } } private static void MarkAggregate(Group group) { group.Aggregate.Properties[ExchangePropertyKeys.AggregatedSize] = group.Size; group.Aggregate.Properties[ExchangePropertyKeys.AggregatedCorrelationKey] = group.Key; } /// What completes the group after this arrival, in Camel's order: the predicate, then the size. private string? CompletionOf(Group group) { if (_completionPredicate(group.Aggregate)) return CompletedBy.Predicate; if (_completionSize is { } size && group.Size >= size) return CompletedBy.Size; return null; } /// /// Sends a completed group on down the route in a DI scope of its own, then releases every exchange it held. /// Returns the aggregate, released; its outcome stays readable. /// private async Task CompleteAsync(Group group, string completedBy, IProcessor target, CancellationToken ct) { var aggregate = group.Aggregate; MarkAggregate(group); aggregate.Properties[ExchangePropertyKeys.AggregatedCompletedBy] = completedBy; (aggregate as Core.Exchange)?.EnsureOwnScope(); try { await target.Process(aggregate, ct).ConfigureAwait(false); } finally { await ReleaseAsync(group).ConfigureAwait(false); } return aggregate; } private static async Task ReleaseAsync(Group group) { foreach (var member in group.Members) await member.DisposeAsync().ConfigureAwait(false); } // ── Inactivity-timeout plumbing ────────────────────────────────────────── /// Under : stamps the group's last arrival and arms the scan timer. private void TouchGroup(string key) { if (_completionTimeout is not { } timeout) return; _lastArrival[key] = DateTime.UtcNow; if (_timer is null && Volatile.Read(ref _disposed) == 0) { // Periodic scan at half the timeout (floor 50 ms): expiry detection is at most half a // period late, and an idle aggregator costs two no-op callbacks per timeout. var period = TimeSpan.FromMilliseconds(Math.Max(timeout.TotalMilliseconds / 2, 50)); _timer = new Timer(OnScanTimer, null, period, period); } } /// Under : removes the group and its arrival stamp. private void RemoveGroup(string key) { _aggregated.Remove(key); _lastArrival.Remove(key); } private void OnScanTimer(object? state) { // Timer callback — flush expired groups on the thread pool. Fire-and-forget is the // resequencer's established shape: an exception from the target lands on the exchange. _ = FlushExpired(_disposeCts.Token); } private async Task FlushExpired(CancellationToken ct) { if (_completionTimeout is not { } timeout) return; List? expired = null; lock (_lock) { var cutoff = DateTime.UtcNow - timeout; List? keys = null; foreach (var (key, last) in _lastArrival) { if (last > cutoff) continue; (keys ??= []).Add(key); } if (keys is not null) { expired = new List(keys.Count); foreach (var key in keys) { expired.Add(_aggregated[key]); RemoveGroup(key); } } } if (expired is null) return; foreach (var group in expired) { if (ct.IsCancellationRequested) { await ReleaseAsync(group).ConfigureAwait(false); continue; } ProcessorMetrics.AggregatorCompleted.Add(1); ProcessorMetrics.AggregatorInflightGroups.Add(-1); try { await CompleteAsync(group, CompletedBy.Timeout, DetachedTarget ?? _target, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { group.Aggregate.Exception = ex; Logger?.LogError(ex, "Completing an aggregation group on timeout failed"); } } } /// async Task IStopAwareProcessor.OnConsumersStoppedAsync(CancellationToken ct) { var groups = TakeAllGroups(); if (groups.Count == 0) return; if (!ForceCompletionOnStop) { Logger?.LogWarning( "{Count} aggregation group(s) not yet complete were dropped on stop; set forceCompletionOnStop to complete them.", groups.Count); await ReleaseAsync(groups).ConfigureAwait(false); return; } foreach (var group in groups) { ProcessorMetrics.AggregatorCompleted.Add(1); try { await CompleteAsync(group, CompletedBy.Force, DetachedTarget ?? _target, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { group.Aggregate.Exception = ex; Logger?.LogError(ex, "Completing an aggregation group on stop failed"); } } } /// Removes every open group, for stop and dispose. private List TakeAllGroups() { List groups; lock (_lock) { groups = [.. _aggregated.Values]; _aggregated.Clear(); _lastArrival.Clear(); } if (groups.Count > 0) ProcessorMetrics.AggregatorInflightGroups.Add(-groups.Count); return groups; } private static async Task ReleaseAsync(List groups) { foreach (var group in groups) await ReleaseAsync(group).ConfigureAwait(false); } /// public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; await _disposeCts.CancelAsync().ConfigureAwait(false); if (_timer is not null) await _timer.DisposeAsync().ConfigureAwait(false); _disposeCts.Dispose(); // A context disposed without a stop still holds its groups: they are dropped, not silently. var groups = TakeAllGroups(); if (groups.Count > 0) { Logger?.LogWarning("{Count} aggregation group(s) not yet complete were dropped when the aggregator was disposed.", groups.Count); await ReleaseAsync(groups).ConfigureAwait(false); } } } Path: redb-route/redb.Route/Processors/CheckpointProcessor.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/Processors/CheckpointProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Compiled body of a .Replayable("name") marker (a save-point). On each pass it captures a /// deep, isolated into /// [] (last marker wins), /// then runs the marker's body. The same compiled is what /// /// re-runs from a stored snapshot — no synthetic endpoint. /// /// SECURITY: the snapshot is a verbatim, UNREDACTED copy of the mid-flight exchange — body, headers /// and Properties may hold decrypted tokens, PII or secrets. Nothing is masked here (URI redaction /// covers endpoint URIs, NOT payloads). Enabling .Replayable() accepts that; storing or /// exposing snapshots is the platform's responsibility, not the route's. /// /// public sealed class CheckpointProcessor : IProcessor { private readonly string _markerName; private readonly IProcessor _body; private readonly ILogger? _logger; /// The marker's compiled body — the tail re-run on replay. public IProcessor Body => _body; /// The save-point name (unique within the route). public string MarkerName => _markerName; /// Creates a checkpoint processor wrapping the marker body. public CheckpointProcessor(string markerName, IProcessor body, ILogger? logger = null) { _markerName = markerName ?? throw new ArgumentNullException(nameof(markerName)); _body = body ?? throw new ArgumentNullException(nameof(body)); _logger = logger; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { try { EnsureAttachmentsReplayable(exchange); // Freeze the state at this marker — deep, isolated (NOT Clone). Last marker wins. exchange.Properties[RouteCheckpoint.PropertyKey] = new RouteCheckpoint(exchange.RouteId ?? string.Empty, _markerName, exchange.Snapshot()); } catch (NotSupportedException ex) { // A non-snapshot-able body, or attachments above RedbRoute:Attachments:MaxReplayableBytes, must NEVER break // the happy path: degrade gracefully — this pass captures no checkpoint (replay simply won't be available // for it) and processing continues. The exception says which of the two it was. _logger?.LogWarning(ex, "Checkpoint '{Marker}' not captured: {Reason} Replay unavailable for this pass.", _markerName, ex.Message); } return _body.Process(exchange, ct); } // A replay snapshot copies attachment content into memory, so it keeps at most RedbRoute:Attachments:MaxReplayableBytes // of it (the Tsak DLQ stores this checkpoint, so the same limit holds there). Checked here, not in Snapshot itself: // other snapshot users (a deferred transactional write) are not replays and have no such limit. private static void EnsureAttachmentsReplayable(IExchange exchange) { var total = Core.MessageAttachments.TotalLength(exchange.In) + (exchange.Out is { } outMessage ? Core.MessageAttachments.TotalLength(outMessage) : 0); if (total == 0) return; var limit = Extensions.RouteContextExtensions.GetAttachmentOptions(exchange.Context).MaxReplayableBytes; if (total > limit) throw new NotSupportedException( $"the attachments of the exchange hold {total} bytes, more than RedbRoute:Attachments:MaxReplayableBytes ({limit})."); } } Path: redb-route/redb.Route/Processors/ChoiceProcessor.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/Processors/ChoiceProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// A single condition-action pair used by . /// When the predicate matches, the associated processor executes. /// public class WhenClause { /// Predicate to evaluate against the exchange. public Func Predicate => Condition.Matches; /// The condition of this branch, awaited through . public IPredicate Condition { get; } /// Processor to execute when the predicate is true. public IProcessor Processor { get; } /// Creates a when clause with a predicate and action. /// The condition to check. /// The processor to run when condition is met. public WhenClause(IPredicate condition, IProcessor processor) { Condition = condition ?? throw new ArgumentNullException(nameof(condition)); Processor = processor ?? throw new ArgumentNullException(nameof(processor)); } /// Creates a clause from a delegate, wrapped as a . public WhenClause(Func predicate, IProcessor processor) : this(new Predicates.LambdaPredicate(predicate ?? throw new ArgumentNullException(nameof(predicate))), processor) { } } /// /// Content-based router: evaluates when-clauses in order, /// executes the first matching branch. Falls through to Otherwise if no match. /// public class ChoiceProcessor : IProcessor { private readonly List _whenClauses = []; private IProcessor? _otherwise; /// Gets the list of when-clauses. public IReadOnlyList WhenClauses => _whenClauses; /// Gets the fallback processor (executed when no when-clause matches). public IProcessor? Otherwise => _otherwise; /// Adds a when-clause to the choice. /// Condition to evaluate. /// Processor to run if condition is true. /// This instance for fluent chaining. public ChoiceProcessor When(Func predicate, IProcessor processor) { _whenClauses.Add(new WhenClause(predicate, processor)); return this; } /// Adds a When branch guarded by a predicate instance. /// The condition of the branch. /// The processor to run when the condition holds. /// This processor for fluent chaining. public ChoiceProcessor When(IPredicate condition, IProcessor processor) { _whenClauses.Add(new WhenClause(condition, processor)); return this; } /// Sets the otherwise (fallback) processor. /// Fallback processor. /// This instance for fluent chaining. public ChoiceProcessor SetOtherwise(IProcessor processor) { _otherwise = processor ?? throw new ArgumentNullException(nameof(processor)); return this; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { foreach (var clause in _whenClauses) { if (await clause.Condition.MatchesAsync(exchange).ConfigureAwait(false)) { await clause.Processor.Process(exchange, ct).ConfigureAwait(false); return; } } if (_otherwise != null) { await _otherwise.Process(exchange, ct).ConfigureAwait(false); } } } Path: redb-route/redb.Route/Processors/CircuitBreakerProcessor.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/Processors/CircuitBreakerProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Circuit breaker states following the standard pattern. /// public enum CircuitState { /// Normal operation — requests pass through. Closed, /// Circuit is tripped — requests go to fallback. Open, /// Probing state — limited requests allowed to test recovery. HalfOpen } /// /// Implements the Circuit Breaker pattern. When consecutive failures exceed a threshold, /// the circuit "opens" and routes exchanges to a fallback processor. After a reset timeout, /// the circuit enters a half-open state allowing limited probing calls. /// All state transitions happen under a single lock to avoid TOCTOU races. /// Thread-safe for concurrent pipeline usage. /// public sealed class CircuitBreakerProcessor : IProcessor { private readonly IProcessor _next; private readonly IProcessor? _fallback; private readonly int _failureThreshold; private readonly TimeSpan _resetTimeout; private readonly int _halfOpenMaxCalls; private readonly ILogger? _logger; private readonly object _lock = new(); private CircuitState _state = CircuitState.Closed; private int _consecutiveFailures; private int _halfOpenCallCount; private int _halfOpenSuccessCount; private DateTimeOffset _openedAt; /// Gets the current circuit state. public CircuitState State { get { lock (_lock) return GetEffectiveStateLocked(); } } /// Creates a circuit breaker processor. /// The protected processor. /// Number of consecutive failures before opening. /// Time to wait before transitioning from Open to HalfOpen. /// Max probe calls allowed in HalfOpen state. /// Optional fallback processor when circuit is open. /// Optional logger. public CircuitBreakerProcessor( IProcessor next, int failureThreshold = 5, TimeSpan? resetTimeout = null, int halfOpenMaxCalls = 1, IProcessor? fallback = null, ILogger? logger = null) { _next = next ?? throw new ArgumentNullException(nameof(next)); if (failureThreshold <= 0) throw new ArgumentOutOfRangeException(nameof(failureThreshold)); _failureThreshold = failureThreshold; _resetTimeout = resetTimeout ?? TimeSpan.FromSeconds(30); _halfOpenMaxCalls = halfOpenMaxCalls > 0 ? halfOpenMaxCalls : 1; _fallback = fallback; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // Acquire state atomically — decide whether to let this call through CircuitState stateForThisCall; lock (_lock) { stateForThisCall = GetEffectiveStateLocked(); if (stateForThisCall == CircuitState.Open) { // Don't release lock with pending work — just flag and handle below } else if (stateForThisCall == CircuitState.HalfOpen) { if (_halfOpenCallCount >= _halfOpenMaxCalls) { // Probe limit reached — treat as open stateForThisCall = CircuitState.Open; } else { _halfOpenCallCount++; } } } if (stateForThisCall == CircuitState.Open) { ProcessorMetrics.CircuitBreakerRejected.Add(1); if (_fallback != null) { await _fallback.Process(exchange, ct).ConfigureAwait(false); return; } exchange.Exception = new CircuitBreakerOpenException( $"Circuit breaker is open. Will retry after {_resetTimeout.TotalSeconds}s."); return; } // stateForThisCall is Closed or HalfOpen — execute protected processor try { await _next.Process(exchange, ct).ConfigureAwait(false); if (exchange.Exception != null) { OnFailure(); } else { OnSuccess(stateForThisCall); } } catch (Exception ex) { OnFailure(); exchange.Exception = ex; } } /// /// Evaluates the effective state. Must be called under . /// Handles the time-based Open → HalfOpen transition. /// private CircuitState GetEffectiveStateLocked() { if (_state == CircuitState.Open && DateTimeOffset.UtcNow - _openedAt >= _resetTimeout) { _state = CircuitState.HalfOpen; _halfOpenCallCount = 0; _halfOpenSuccessCount = 0; } return _state; } private void OnSuccess(CircuitState stateAtEntry) { lock (_lock) { _consecutiveFailures = 0; if (stateAtEntry == CircuitState.HalfOpen) { _halfOpenSuccessCount++; // Close only when ALL probe calls succeeded if (_halfOpenSuccessCount >= _halfOpenMaxCalls) { _state = CircuitState.Closed; } } else { // Closed state — just reset failures (already done above) } } } private void OnFailure() { lock (_lock) { _consecutiveFailures++; if (_state == CircuitState.HalfOpen) { // Any failure in HalfOpen → Open immediately _state = CircuitState.Open; _openedAt = DateTimeOffset.UtcNow; ProcessorMetrics.CircuitBreakerTripped.Add(1); _logger?.LogWarning("Circuit breaker tripped to Open (HalfOpen probe failed)."); } else if (_consecutiveFailures >= _failureThreshold) { _state = CircuitState.Open; _openedAt = DateTimeOffset.UtcNow; ProcessorMetrics.CircuitBreakerTripped.Add(1); _logger?.LogWarning("Circuit breaker tripped to Open after {Failures} consecutive failures.", _consecutiveFailures); } } } } /// /// Exception thrown when the circuit breaker is in Open state and no fallback is configured. /// public sealed class CircuitBreakerOpenException : Exception { /// Creates a new circuit breaker open exception. /// Exception message. public CircuitBreakerOpenException(string message) : base(message) { } /// Creates a new circuit breaker open exception with inner exception. /// Exception message. /// Inner exception. public CircuitBreakerOpenException(string message, Exception inner) : base(message, inner) { } } Path: redb-route/redb.Route/Processors/ClaimCheckProcessor.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/Processors/ClaimCheckProcessor.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Processor for the Claim Check EIP pattern. /// Handles all five operations: Set, Get, GetAndRemove, Push, Pop. /// Store operations replace the exchange body with a claim key. /// Retrieve operations restore the exchange body from the repository. /// public sealed class ClaimCheckProcessor : IProcessor { private readonly IClaimCheckRepository _repository; private readonly ClaimCheckOperation _operation; private readonly string? _key; private readonly TimeSpan? _ttl; private readonly ILogger? _logger; /// /// Creates a new Claim Check processor. /// /// The claim check repository. /// The operation to perform. /// Explicit key for Set/Get/GetAndRemove. Ignored for Push/Pop. /// TTL for stored data. Only used by Set/Push. /// Optional logger. public ClaimCheckProcessor( IClaimCheckRepository repository, ClaimCheckOperation operation, string? key = null, TimeSpan? ttl = null, ILogger? logger = null) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); _operation = operation; _key = key; _ttl = ttl; _logger = logger; // Validate key requirements if (_operation is ClaimCheckOperation.Set or ClaimCheckOperation.Get or ClaimCheckOperation.GetAndRemove && string.IsNullOrEmpty(_key)) { // Key can also come from header at runtime, so we don't throw here } } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); switch (_operation) { case ClaimCheckOperation.Set: await StoreBody(exchange, _key, ct).ConfigureAwait(false); break; case ClaimCheckOperation.Push: await PushBody(exchange, ct).ConfigureAwait(false); break; case ClaimCheckOperation.Get: await RetrieveBody(exchange, remove: false, ct).ConfigureAwait(false); break; case ClaimCheckOperation.GetAndRemove: await RetrieveBody(exchange, remove: true, ct).ConfigureAwait(false); break; case ClaimCheckOperation.Pop: await PopBody(exchange, ct).ConfigureAwait(false); break; default: throw new InvalidOperationException($"Unknown claim check operation: {_operation}"); } } private async Task StoreBody(IExchange exchange, string? explicitKey, CancellationToken ct) { var body = exchange.In.Body; var data = ClaimCheckSerializer.Serialize(body); // Save original type info in headers SaveBodyMetadata(exchange, body); string claimKey; if (!string.IsNullOrEmpty(explicitKey)) { await _repository.Store(explicitKey, data, _ttl, ct).ConfigureAwait(false); claimKey = explicitKey; } else { claimKey = await _repository.Store(data, _ttl, ct).ConfigureAwait(false); } exchange.In.Headers[ClaimCheckHeaders.Key] = claimKey; exchange.In.Body = claimKey; _logger?.LogDebug("Claim check: stored body under key {Key} ({Bytes} bytes)", claimKey, data.Length); } private async Task PushBody(IExchange exchange, CancellationToken ct) { var body = exchange.In.Body; var data = ClaimCheckSerializer.Serialize(body); SaveBodyMetadata(exchange, body); var claimKey = await _repository.Store(data, _ttl, ct).ConfigureAwait(false); // Push key onto the per-exchange stack var stack = GetOrCreateStack(exchange); stack.Push(claimKey); exchange.In.Headers[ClaimCheckHeaders.Key] = claimKey; exchange.In.Body = claimKey; _logger?.LogDebug("Claim check: pushed body as key {Key} (stack depth: {Depth})", claimKey, stack.Count); } private async Task RetrieveBody(IExchange exchange, bool remove, CancellationToken ct) { var claimKey = ResolveKey(exchange); if (string.IsNullOrEmpty(claimKey)) { _logger?.LogWarning("Claim check: no claim key found for {Operation}. Skipping.", _operation); return; } var data = remove ? await _repository.RetrieveAndRemove(claimKey, ct).ConfigureAwait(false) : await _repository.Retrieve(claimKey, ct).ConfigureAwait(false); if (data is null) { _logger?.LogWarning("Claim check: no data found for key {Key} (operation={Operation})", claimKey, _operation); return; } RestoreBody(exchange, data); _logger?.LogDebug("Claim check: restored body from key {Key} ({Bytes} bytes, remove={Remove})", claimKey, data.Length, remove); } private async Task PopBody(IExchange exchange, CancellationToken ct) { var stack = GetExistingStack(exchange); if (stack is null || !stack.TryPop(out var claimKey)) { _logger?.LogWarning("Claim check: pop called but stack is empty."); return; } var data = await _repository.RetrieveAndRemove(claimKey, ct).ConfigureAwait(false); if (data is null) { _logger?.LogWarning("Claim check: pop found key {Key} on stack but data is missing.", claimKey); return; } RestoreBody(exchange, data); _logger?.LogDebug("Claim check: popped body from key {Key} (stack depth: {Depth})", claimKey, stack.Count); } private string? ResolveKey(IExchange exchange) { // Explicit key from step configuration takes priority if (!string.IsNullOrEmpty(_key)) return _key; // Fall back to key from header if (exchange.In.Headers.TryGetValue(ClaimCheckHeaders.Key, out var headerKey) && headerKey is string keyStr && !string.IsNullOrEmpty(keyStr)) return keyStr; // Fall back to body as key (e.g., when body was replaced with key by Set) if (exchange.In.Body is string bodyKey && !string.IsNullOrEmpty(bodyKey)) return bodyKey; return null; } private static void SaveBodyMetadata(IExchange exchange, object? body) { if (exchange.In.ContentType != null) exchange.In.Headers[ClaimCheckHeaders.OriginalContentType] = exchange.In.ContentType; if (body != null) exchange.In.Headers[ClaimCheckHeaders.OriginalBodyType] = body.GetType().FullName; } private static void RestoreBody(IExchange exchange, byte[] data) { var originalType = exchange.In.Headers.TryGetValue(ClaimCheckHeaders.OriginalBodyType, out var typeObj) ? typeObj as string : null; exchange.In.Body = ClaimCheckSerializer.Deserialize(data, originalType); // Restore original content type if (exchange.In.Headers.TryGetValue(ClaimCheckHeaders.OriginalContentType, out var ct)) { exchange.In.ContentType = ct as string; exchange.In.Headers.Remove(ClaimCheckHeaders.OriginalContentType); } // Clean up metadata headers exchange.In.Headers.Remove(ClaimCheckHeaders.OriginalBodyType); exchange.In.Headers.Remove(ClaimCheckHeaders.Key); } private static Stack GetOrCreateStack(IExchange exchange) { if (exchange.Properties.TryGetValue(ClaimCheckHeaders.StackPropertyKey, out var existing) && existing is Stack stack) return stack; var newStack = new Stack(); exchange.Properties[ClaimCheckHeaders.StackPropertyKey] = newStack; return newStack; } private static Stack? GetExistingStack(IExchange exchange) { if (exchange.Properties.TryGetValue(ClaimCheckHeaders.StackPropertyKey, out var existing) && existing is Stack stack) return stack; return null; } } Path: redb-route/redb.Route/Processors/ClaimCheckSerializer.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/Processors/ClaimCheckSerializer.cs ---- using System; using System.Text; using System.Text.Json; namespace redb.Route.Processors; /// /// Default serialization helper for the Claim Check pattern. /// Handles byte[], string, and arbitrary objects (via JSON). /// internal static class ClaimCheckSerializer { /// /// Serializes a message body to a byte array. /// /// The body to serialize. May be null, byte[], string, or any serializable object. /// Binary representation of the body. public static byte[] Serialize(object? body) { if (body is null) return []; if (body is byte[] bytes) return bytes; if (body is string str) return Encoding.UTF8.GetBytes(str); if (body is ReadOnlyMemory rom) return rom.ToArray(); if (body is Memory mem) return mem.ToArray(); return JsonSerializer.SerializeToUtf8Bytes(body, body.GetType()); } /// /// Deserializes a byte array back to a message body. /// Returns the data as a string (UTF-8) by default; callers can use ConvertBody afterwards. /// /// The binary data to deserialize. /// Original CLR type name, or null. /// The deserialized body. public static object? Deserialize(byte[] data, string? originalBodyType) { if (data.Length == 0) return null; // If original was byte[], return byte[] if (originalBodyType == typeof(byte[]).FullName) return data; // Default: return as UTF-8 string return Encoding.UTF8.GetString(data); } } Path: redb-route/redb.Route/Processors/ContextErrorLayerProcessor.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/Processors/ContextErrorLayerProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// The outermost layer of a route's error scope (): the context's error handling for a /// failure no OnException took — as Apache Camel's context error handler, which works only when no /// onException matched. An that takes a failure returns (with /// Handled(false) the failure stays on the exchange), one that does not take it rethrows; so this layer sees /// exactly the failures nobody took. /// /// The lookup is that of : a local handler of the route, a global handler, /// . A handler that marks the exchange handled ( /// — a dead letter channel) ends the failure; otherwise it goes on to the caller, as with Camel's DefaultErrorHandler, /// and so it does when nothing matched. /// /// internal sealed class ContextErrorLayerProcessor : IProcessor { private readonly IProcessor _inner; private readonly RouteContext _context; private readonly string _routeId; internal ContextErrorLayerProcessor(IProcessor inner, RouteContext context, string routeId) { _inner = inner; _context = context; _routeId = routeId; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { try { await _inner.Process(exchange, ct).ConfigureAwait(false); } // A genuine cancellation is never handled; a downstream timeout is named a TimeoutException, as in OnException. catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct)) { // The route id is the compiled one: an exchange that went through a direct: route carries that route's id. var handled = await _context.HandleWithContextHandlers(exchange, RouteCancellation.Normalize(ex, ct), _routeId, ct) .ConfigureAwait(false); if (!handled || !exchange.ExceptionHandled) throw; } } } Path: redb-route/redb.Route/Processors/ContextStampProcessor.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/Processors/ContextStampProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Outermost per-route wrapper that stamps for the duration of the /// route and restores the previous value on exit. /// /// /// Save/set/restore rather than set-once, so "current" means the route actually executing: inside /// a direct: or vm: sub-route the exchange sees the inner route's context — Camel's /// reading — and the caller sees its own again when the sub-route returns. An exchange that never /// entered a route keeps null, including after it comes back from one. /// internal sealed class ContextStampProcessor : IProcessor { private readonly IProcessor _inner; private readonly IRouteContext _context; public ContextStampProcessor(IProcessor inner, IRouteContext context) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _context = context ?? throw new ArgumentNullException(nameof(context)); } public async Task Process(IExchange exchange, CancellationToken ct = default) { if (exchange is not Exchange stampable) { await _inner.Process(exchange, ct).ConfigureAwait(false); return; } var previous = stampable.Context; stampable.Context = _context; try { await _inner.Process(exchange, ct).ConfigureAwait(false); } finally { stampable.Context = previous; } } } Path: redb-route/redb.Route/Processors/DeadLetterChannelProcessor.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/Processors/DeadLetterChannelProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Wraps an inner processor and, on uncaught exception, sends the exchange to the configured /// dead-letter URI before re-throwing (when configured as transaction-aware so the outer /// transaction can still roll back) or swallowing the exception (best-effort handle mode). /// Apache Camel parity: errorHandler(deadLetterChannel("...")). /// Producer is cached for the lifetime of the processor. /// public sealed class DeadLetterChannelProcessor : IProcessor { private readonly IRouteContext _context; private readonly IProcessor _inner; private readonly string _deadLetterUri; private readonly bool _rethrow; private readonly ILogger? _logger; private IProducer? _producer; private IEndpoint? _endpoint; private readonly SemaphoreSlim _producerLock = new(1, 1); /// Creates a dead-letter channel processor. /// Route context used to resolve the dead-letter endpoint. /// Inner processor whose failures should be dead-lettered. /// URI of the dead-letter endpoint. /// If true, the original exception is re-thrown after dead-lettering /// (so an enclosing transactional scope can still roll back). Default true to match /// Camel's transactional semantics. /// Optional logger. public DeadLetterChannelProcessor( IRouteContext context, IProcessor inner, string deadLetterUri, bool rethrow = true, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(inner); ArgumentException.ThrowIfNullOrWhiteSpace(deadLetterUri); _context = context; _inner = inner; _deadLetterUri = deadLetterUri; _rethrow = rethrow; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { try { await _inner.Process(exchange, ct).ConfigureAwait(false); } // A downstream timeout is an OperationCanceledException whose token (ours) is still live — a failure // to dead-letter, not a cancellation. Named a TimeoutException. A genuine cancellation passes. catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct)) { var failure = RouteCancellation.Normalize(ex, ct); exchange.Exception = failure; _logger?.LogWarning(failure, "Dead-lettering exchange to {Uri}.", EndpointUri.Sanitize(_deadLetterUri)); try { var (endpoint, producer) = await GetOrCreatePair(ct).ConfigureAwait(false); await Core.CountedSend.Process(endpoint, producer, exchange, ct).ConfigureAwait(false); ProcessorMetrics.DeadLetterSent.Add(1); } catch (Exception sendEx) { _logger?.LogError(sendEx, "Dead-letter delivery to {Uri} failed.", EndpointUri.Sanitize(_deadLetterUri)); } if (_rethrow) throw; exchange.Exception = null; } } private async Task<(IEndpoint, IProducer)> GetOrCreatePair(CancellationToken ct) { if (_producer is not null) return (_endpoint!, _producer); await _producerLock.WaitAsync(ct).ConfigureAwait(false); try { if (_producer is not null) return (_endpoint!, _producer); var endpoint = _context.GetEndpoint(_deadLetterUri); var producer = endpoint.CreateProducerOnItsSide(); await producer.Start(ct).ConfigureAwait(false); (_context as RouteContext)?.TrackProducer(producer); _endpoint = endpoint; _producer = producer; return (endpoint, producer); } finally { _producerLock.Release(); } } } Path: redb-route/redb.Route/Processors/DebounceProcessor.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/Processors/DebounceProcessor.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Per-key debounce: suppresses rapid-fire messages and forwards only the last /// exchange for each key after a configurable quiet period. /// When a new message arrives for a key that already has a pending timer, /// the previous exchange is discarded and the timer is reset. /// Thread-safe for concurrent pipeline usage. /// internal sealed class DebounceProcessor : IProcessor, IAsyncDisposable, IDisposable { private readonly IProcessor _next; private readonly Func _keyExtractor; private readonly TimeSpan _quietPeriod; private readonly ILogger? _logger; private readonly TimeProvider _time; private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); private int _disposed; /// Creates a debounce processor. /// Next processor in the pipeline. /// Function extracting the debounce key from the exchange. /// Duration of silence required before forwarding the last exchange. /// Optional logger for diagnostics. /// The clock of the quiet period; when omitted. public DebounceProcessor( IProcessor next, Func keyExtractor, TimeSpan quietPeriod, ILogger? logger = null, TimeProvider? timeProvider = null) { _next = next ?? throw new ArgumentNullException(nameof(next)); _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); if (quietPeriod <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(quietPeriod), "Must be positive."); _quietPeriod = quietPeriod; _logger = logger; _time = timeProvider ?? TimeProvider.System; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { ObjectDisposedException.ThrowIf(_disposed != 0, this); var key = _keyExtractor(exchange) ?? string.Empty; // Create or update the entry for this key _entries.AddOrUpdate( key, _ => CreateEntry(key, exchange, ct), (k, existing) => { ProcessorMetrics.DebounceDiscarded.Add(1); existing.Reset(exchange, ct); ScheduleFlush(k, existing); return existing; }); // Return immediately — the downstream call happens asynchronously after quiet period return Task.CompletedTask; } private DebounceEntry CreateEntry(string key, IExchange exchange, CancellationToken ct) { var entry = new DebounceEntry(exchange, ct); ScheduleFlush(key, entry); return entry; } private void ScheduleFlush(string key, DebounceEntry entry) { var cts = entry.Cts; // Capture ambient trace + transaction state on the scheduling (originating) thread. The // flush below runs detached after the quiet period — by then the originating route call, // and any ambient TransactionScope it ran in, has unwound. See DetachedDispatch. var origin = DetachedDispatch.Capture(); _ = Task.Delay(_quietPeriod, _time, cts.Token).ContinueWith(async _ => { if (_entries.TryRemove(key, out var removed)) { // Suppress the leaked ambient transaction and re-root telemetry as a span linked // to the originating trace, so the flushed forward does not enlist in an // already-completed TransactionScope nor parent under an already-stopped span. using var frame = DetachedDispatch.Enter(origin, "redb.route.debounce.flush"); try { await _next.Process(removed.Exchange, removed.UpstreamCt).ConfigureAwait(false); ProcessorMetrics.DebounceFlushed.Add(1); } catch (Exception ex) { removed.Exchange.Exception = ex; _logger?.LogError(ex, "Debounce flush failed for key '{Key}'", key); } finally { removed.Dispose(); } } }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } /// Flush all pending entries immediately (used during graceful shutdown). public async Task FlushAsync() { var keys = _entries.Keys.ToArray(); foreach (var key in keys) { if (_entries.TryRemove(key, out var entry)) { try { await _next.Process(entry.Exchange, entry.UpstreamCt).ConfigureAwait(false); } catch (Exception ex) { entry.Exchange.Exception = ex; _logger?.LogError(ex, "Debounce flush failed for key '{Key}'", key); } finally { entry.Dispose(); } } } } /// Cancels pending timers and disposes all entries. public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; foreach (var kvp in _entries) { kvp.Value.Dispose(); } _entries.Clear(); } /// Flushes pending entries and disposes. public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; await FlushAsync().ConfigureAwait(false); _entries.Clear(); } private sealed class DebounceEntry : IDisposable { private CancellationTokenSource _cts; private IExchange _exchange; private CancellationToken _upstreamCt; public DebounceEntry(IExchange exchange, CancellationToken upstreamCt) { _cts = new CancellationTokenSource(); _exchange = exchange; _upstreamCt = upstreamCt; } public CancellationTokenSource Cts => Volatile.Read(ref _cts); public IExchange Exchange => Volatile.Read(ref _exchange); public CancellationToken UpstreamCt => _upstreamCt; /// Replaces the stored exchange and resets the timer. public void Reset(IExchange newExchange, CancellationToken ct) { var oldCts = Interlocked.Exchange(ref _cts, new CancellationTokenSource()); try { oldCts.Cancel(); } catch (ObjectDisposedException) { } oldCts.Dispose(); Volatile.Write(ref _exchange, newExchange); _upstreamCt = ct; } public void Dispose() { try { _cts.Cancel(); } catch (ObjectDisposedException) { } _cts.Dispose(); } } } Path: redb-route/redb.Route/Processors/DelayProcessor.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/Processors/DelayProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Delays processing by a specified duration. Supports cancellation. /// public class DelayProcessor : IProcessor { private readonly TimeSpan _delay; /// Gets the delay duration. public TimeSpan Delay => _delay; /// Creates a delay processor with the specified duration. /// Time to delay before continuing. public DelayProcessor(TimeSpan delay) { if (delay < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(delay), "Delay must be non-negative."); _delay = delay; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { if (_delay > TimeSpan.Zero) { await InflightWaits.DelayAsync(exchange, _delay, ct).ConfigureAwait(false); } } } Path: redb-route/redb.Route/Processors/DelegateProcessor.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/Processors/DelegateProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Processes a message exchange asynchronously using a delegate function. /// Simplest processor — wraps a user-provided Func. /// public class DelegateProcessor : IProcessor { private readonly Func _action; /// Creates a processor from an async delegate. /// The async action to execute on each exchange. public DelegateProcessor(Func action) { _action = action ?? throw new ArgumentNullException(nameof(action)); } /// Creates a processor from a synchronous delegate. /// The synchronous action to execute on each exchange. public DelegateProcessor(Action action) { ArgumentNullException.ThrowIfNull(action); _action = (ex, _) => { action(ex); return Task.CompletedTask; }; } /// public Task Process(IExchange exchange, CancellationToken ct = default) => _action(exchange, ct); } Path: redb-route/redb.Route/Processors/DetachedExecutor.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/Processors/DetachedExecutor.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Extensions.Logging; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// The bounded pool of one detached step (a WireTap, an asynchronous OnCompletion), built from a /// : at most branches run, at most /// wait, and a branch that finds both full is handled by the profile's /// rejected policy. Each step has a pool of its own, as each Camel EIP gets its own executor from the profile. /// internal sealed class DetachedExecutor { private readonly ThreadPoolProfile _profile; private readonly ILogger? _logger; private readonly TagList _tags; private readonly string _description; private readonly ConcurrentQueue> _queue = new(); private int _active; private int _queued; private long _rejected; private long _callerRuns; /// The profile's name for metrics and logs: default or the executorService name. /// The bounds. /// The step for metrics and logs: wireTap, onCompletion. /// The route the step is in, when known. /// Logs a rejected branch and what shutdown left. public DetachedExecutor(string profileName, ThreadPoolProfile profile, string step, string? routeId, ILogger? logger) { _profile = profile; _logger = logger; _tags = new TagList { { "profile", profileName }, { "step", step }, { "route", routeId ?? "(unknown)" } }; _description = $"{step} on route '{routeId ?? "(unknown)"}' (thread pool profile '{profileName}': {profile})"; } /// Branches running now. internal int Active => Volatile.Read(ref _active); /// Branches waiting now. internal int Queued => Volatile.Read(ref _queued); /// Branches dropped or refused so far. internal long Rejected => Interlocked.Read(ref _rejected); /// Branches the caller ran itself so far. internal long CallerRuns => Interlocked.Read(ref _callerRuns); /// /// Runs on the pool. Returns once it is handed to the pool or queued, or, when both are /// full, once the caller ran it (CallerRuns). Returns false when the branch was dropped (Discard); throws /// when it was refused (Abort). The branch handles its own failures; one /// that escapes is counted. /// public async ValueTask Execute(Func branch) { if (TryTakeSlot()) { Start(branch); return true; } if (Interlocked.Increment(ref _queued) <= _profile.MaxQueueSize) { _queue.Enqueue(branch); ProcessorMetrics.PoolQueued.Add(1, _tags); // A runner that found the queue empty a moment ago may have left: take its slot for what waits. if (TryTakeSlot()) { if (TryDequeue() is { } next) Start(next); else ReleaseSlot(); } return true; } Interlocked.Decrement(ref _queued); switch (_profile.RejectedPolicy) { case ThreadPoolRejectedPolicy.CallerRuns: Interlocked.Increment(ref _callerRuns); ProcessorMetrics.PoolCallerRuns.Add(1, _tags); await RunOne(branch).ConfigureAwait(false); return true; case ThreadPoolRejectedPolicy.Discard: Interlocked.Increment(ref _rejected); ProcessorMetrics.PoolRejected.Add(1, _tags); _logger?.LogWarning("A branch of {Step} was dropped: its pool and queue are full.", _description); return false; default: Interlocked.Increment(ref _rejected); ProcessorMetrics.PoolRejected.Add(1, _tags); throw new RejectedExecutionException($"A branch of {_description} was refused: its pool and queue are full."); } } /// /// Waits until no branch runs or waits, or until ends the wait; what is left then is counted /// and logged with its number. Branches keep running after that; they are not cancelled. /// public async Task DrainAsync(CancellationToken ct) { try { while (Active > 0 || Queued > 0) await Task.Delay(20, ct).ConfigureAwait(false); } catch (OperationCanceledException) { var left = Active + Queued; if (left > 0) { ProcessorMetrics.PoolNotDrained.Add(left, _tags); _logger?.LogWarning( "{Count} branch(es) of {Step} were still running or waiting when the shutdown timeout ran out " + "({Active} running, {Queued} waiting).", left, _description, Active, Queued); } } } private bool TryTakeSlot() { while (true) { var active = Volatile.Read(ref _active); if (active >= _profile.MaxConcurrency) return false; if (Interlocked.CompareExchange(ref _active, active + 1, active) == active) { ProcessorMetrics.PoolActive.Add(1, _tags); return true; } } } private void ReleaseSlot() { Interlocked.Decrement(ref _active); ProcessorMetrics.PoolActive.Add(-1, _tags); } private Func? TryDequeue() { if (!_queue.TryDequeue(out var branch)) return null; Interlocked.Decrement(ref _queued); ProcessorMetrics.PoolQueued.Add(-1, _tags); return branch; } /// Starts a runner on a slot already taken: it runs the branch, then what waits, then gives the slot back. private void Start(Func first) => _ = Task.Run(async () => { var next = first; while (true) { while (next is not null) { await RunOne(next).ConfigureAwait(false); next = TryDequeue(); } ReleaseSlot(); // A branch queued between the last empty look and the release would wait for the next Execute: take it. if (_queue.IsEmpty || !TryTakeSlot()) return; next = TryDequeue(); if (next is null) { ReleaseSlot(); return; } } }); private async Task RunOne(Func branch) { try { await branch().ConfigureAwait(false); } catch (Exception ex) { ProcessorMetrics.PoolFailed.Add(1, _tags); _logger?.LogWarning(ex, "A branch of {Step} failed.", _description); } } } Path: redb-route/redb.Route/Processors/DynamicEndpointResolver.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/Processors/DynamicEndpointResolver.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Processors; /// /// Per-instance cache that resolves an endpoint URI per exchange (via a /// ${...} template, an , or a factory delegate), /// then looks up the matching component, creates a producer for the resolved URI, /// starts it, caches it by resolved URI string, and reuses it on subsequent calls. /// /// Used by dynamic-endpoint processors (, dynamic /// WireTap/Enrich/PollEnrich/RecipientList) so producers are not recreated on every /// message. Producers are also registered with so they /// participate in the standard graceful-shutdown flow. /// /// public sealed class DynamicEndpointResolver { private readonly IRouteContext _context; private readonly Func _uriFactory; // Endpoint rides along so the sender can record producer-side statistics (CountedSend). private readonly ConcurrentDictionary>> _producers = new(); /// Creates a resolver that calls per exchange. public DynamicEndpointResolver(IRouteContext context, Func uriFactory) { _context = context ?? throw new ArgumentNullException(nameof(context)); _uriFactory = uriFactory ?? throw new ArgumentNullException(nameof(uriFactory)); } /// Creates a resolver that resolves a ${...} template per exchange. public static DynamicEndpointResolver FromTemplate(IRouteContext context, string template) { ArgumentException.ThrowIfNullOrWhiteSpace(template); return new DynamicEndpointResolver(context, ex => ExpressionResolver.ProcessTemplate(template, ex)); } /// Creates a resolver that evaluates an per exchange. public static DynamicEndpointResolver FromExpression(IRouteContext context, IExpression expression) { ArgumentNullException.ThrowIfNull(expression); return new DynamicEndpointResolver(context, ex => expression.Evaluate(ex) ?? throw new InvalidOperationException( "Dynamic endpoint expression evaluated to null.")); } // One evaluation per message even when interception wraps the send: the wrapper resolves the URI // and parks it on the exchange under a key private to this resolver; the send that follows takes // it from there instead of evaluating the template again. private readonly string _parkedUriKey = "__redb_tod:" + Guid.NewGuid().ToString("N"); /// Resolves the URI for and returns a (cached) started producer. public async Task ResolveProducerAsync(IExchange exchange, CancellationToken ct) => (await ResolvePairAsync(exchange, ct).ConfigureAwait(false)).Producer; /// Same as , with the endpoint for statistics recording. internal async Task<(IEndpoint Endpoint, IProducer Producer)> ResolvePairAsync(IExchange exchange, CancellationToken ct) { string resolved; if (exchange.Properties.TryGetValue(_parkedUriKey, out var parked) && parked is string parkedUri) { resolved = parkedUri; exchange.Properties.Remove(_parkedUriKey); } else { resolved = ResolveUri(exchange); } return await GetOrCreatePairAsync(resolved, ct).ConfigureAwait(false); } /// Returns the started producer for an already-resolved URI, creating and caching it on first use. public async Task GetOrCreateProducerAsync(string resolvedUri, CancellationToken ct) => (await GetOrCreatePairAsync(resolvedUri, ct).ConfigureAwait(false)).Producer; /// Same as , with the endpoint for statistics recording. internal async Task<(IEndpoint Endpoint, IProducer Producer)> GetOrCreatePairAsync(string resolvedUri, CancellationToken ct) { // Cache key is the fully-resolved URI; one producer per distinct URI. var lazy = _producers.GetOrAdd(resolvedUri, uri => new Lazy>(() => CreateAsync(uri, ct))); try { return await lazy.Value.ConfigureAwait(false); } catch (OperationCanceledException) { // The first caller's token was cancelled while its producer started; drop the entry so the // next message creates the producer instead of awaiting a cancelled task forever. _producers.TryRemove(new KeyValuePair>>(resolvedUri, lazy)); throw; } } /// /// Resolves the URI and parks it for the send that follows on this exchange; /// tells whether this call parked it (the owner clears it with , so a skipped /// send never leaves a stale value for a later pass through the same node). /// internal string ResolveAndPark(IExchange exchange, out bool parked) { if (exchange.Properties.TryGetValue(_parkedUriKey, out var existing) && existing is string existingUri) { parked = false; return existingUri; } var resolved = ResolveUri(exchange); exchange.Properties[_parkedUriKey] = resolved; parked = true; return resolved; } /// Removes the parked URI (see ). internal void Unpark(IExchange exchange) => exchange.Properties.Remove(_parkedUriKey); /// Resolves the target URI for this exchange without creating a producer (used by InterceptSendToEndpoint). public string ResolveUri(IExchange exchange) { var resolved = _uriFactory(exchange); if (string.IsNullOrWhiteSpace(resolved)) throw new InvalidOperationException( "Dynamic endpoint URI resolved to an empty value."); return resolved; } private async Task<(IEndpoint, IProducer)> CreateAsync(string resolvedUri, CancellationToken ct) { var endpoint = _context.GetEndpoint(resolvedUri); var producer = endpoint.CreateProducerOnItsSide(); await producer.Start(ct).ConfigureAwait(false); (_context as RouteContext)?.TrackProducer(producer); return (endpoint, producer); } } Path: redb-route/redb.Route/Processors/DynamicRouterProcessor.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/Processors/DynamicRouterProcessor.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Dynamic Router: evaluates a routing function on each exchange to determine the next endpoint. /// The exchange is sent to the returned URI, then the routing function is called again. /// Routing continues until the function returns null (slip routing). /// Implements the Dynamic Router / Routing Slip EIP pattern. /// Producers are cached per URI to avoid repeated creation for hot paths. /// internal sealed class DynamicRouterProcessor : IProcessor, IAsyncDisposable { private readonly IRouteContext _context; private readonly Func _routingFunction; private readonly ConcurrentDictionary _producerCache = new(StringComparer.Ordinal); private readonly ILogger? _logger; /// Creates a dynamic router processor. /// Route context for resolving endpoints. /// /// Function that returns the next URI to route to, or null to stop routing. /// The function is called after each hop, so the exchange state may change between calls. /// public DynamicRouterProcessor( IRouteContext context, Func routingFunction, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _routingFunction = routingFunction ?? throw new ArgumentNullException(nameof(routingFunction)); _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { const int maxHops = 1000; // Safety guard against infinite loops int hops = 0; while (!ct.IsCancellationRequested && !exchange.IsStopped) { var nextUri = _routingFunction(exchange); if (nextUri is null) break; _logger?.LogDebug("DynamicRouter: hop {Hop} → {Uri}", hops + 1, EndpointUri.Sanitize(nextUri)); if (++hops > maxHops) throw new InvalidOperationException( $"DynamicRouter exceeded maximum hop count ({maxHops}). " + "Possible infinite routing loop detected."); var (endpoint, producer) = await GetOrCreatePairAsync(nextUri, ct).ConfigureAwait(false); await Core.CountedSend.Process(endpoint, producer, exchange, ct).ConfigureAwait(false); } } private async Task<(IEndpoint Endpoint, IProducer Producer)> GetOrCreatePairAsync(string uri, CancellationToken ct) { if (_producerCache.TryGetValue(uri, out var cached)) return cached; var endpoint = _context.GetEndpoint(uri); var producer = endpoint.CreateProducerOnItsSide(); await producer.Start(ct).ConfigureAwait(false); (_context as RouteContext)?.TrackProducer(producer); // Use TryAdd to avoid overwriting if another thread added concurrently if (!_producerCache.TryAdd(uri, (endpoint, producer))) { // Another thread won the race — stop our duplicate and use theirs await producer.Stop(ct).ConfigureAwait(false); return _producerCache[uri]; } return (endpoint, producer); } /// Stops all cached producers. public async ValueTask DisposeAsync() { foreach (var kvp in _producerCache) { try { await kvp.Value.Producer.Stop().ConfigureAwait(false); } catch { // Best-effort cleanup during disposal } } _producerCache.Clear(); } } Path: redb-route/redb.Route/Processors/EnrichProcessor.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/Processors/EnrichProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Content Enricher: calls an external endpoint and merges the result into the current exchange. /// Implements the Content Enricher EIP pattern. The producer is cached for the lifetime /// of this processor and started on first use. /// public sealed class EnrichProcessor : IProcessor { private IEndpoint? _endpoint; private readonly IRouteContext _context; private readonly string? _resourceUri; private readonly DynamicEndpointResolver? _resolver; private readonly Func _mergeStrategy; private IProducer? _producer; /// Creates an enrich processor. /// Route context for resolving the resource endpoint. /// URI of the enrichment endpoint. /// Function merging original and enrichment exchanges: (original, enriched) → merged. public EnrichProcessor( IRouteContext context, string resourceUri, Func mergeStrategy) { _context = context ?? throw new ArgumentNullException(nameof(context)); _resourceUri = resourceUri ?? throw new ArgumentNullException(nameof(resourceUri)); (context as RouteContext)?.NoteStaticEndpoint(resourceUri); _mergeStrategy = mergeStrategy ?? throw new ArgumentNullException(nameof(mergeStrategy)); } /// Creates an enrich processor with a dynamic endpoint resolver. public EnrichProcessor( IRouteContext context, DynamicEndpointResolver resolver, Func mergeStrategy) { _context = context ?? throw new ArgumentNullException(nameof(context)); _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); _mergeStrategy = mergeStrategy ?? throw new ArgumentNullException(nameof(mergeStrategy)); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var resourceExchange = exchange.CorrelatedCopyLinked(); try { resourceExchange.Pattern = ExchangePattern.InOut; var (endpoint, producer) = _resolver is not null ? await _resolver.ResolvePairAsync(resourceExchange, ct).ConfigureAwait(false) : await GetOrCreatePairAsync(ct).ConfigureAwait(false); await CountedSend.Process(endpoint, producer, resourceExchange, ct).ConfigureAwait(false); // Merge the response back into the original exchange var merged = _mergeStrategy(exchange, resourceExchange); exchange.In.Body = merged.In.Body; foreach (var header in merged.In.Headers) exchange.In.Headers[header.Key] = header.Value; if (merged.Exception != null) exchange.Exception = merged.Exception; } finally { // As Apache Camel's Enrich hands the resource exchange's completions over: a streamed body merged into the // original keeps its connection until the original ends, not until this copy is disposed. ExchangeResources.HandOver(resourceExchange, exchange); if (resourceExchange is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } private async Task<(IEndpoint, IProducer)> GetOrCreatePairAsync(CancellationToken ct) { if (_producer is not null) return (_endpoint!, _producer); _endpoint = _context.GetEndpoint(_resourceUri!); _producer = _endpoint.CreateProducerOnItsSide(); await _producer.Start(ct).ConfigureAwait(false); (_context as RouteContext)?.TrackProducer(_producer); return (_endpoint, _producer); } } /// /// Poll Enricher: sends a request to an endpoint with a timeout, merging the result /// into the current exchange. If the endpoint does not respond within the timeout, /// the merge strategy receives a null exchange, allowing graceful handling. /// The producer is cached for the lifetime of this processor. /// public sealed class PollEnrichProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _resourceUri; private readonly DynamicEndpointResolver? _resolver; private readonly Func _mergeStrategy; private readonly TimeSpan _timeout; private IProducer? _producer; private IEndpoint? _endpoint; /// Creates a poll enrich processor. /// Route context for resolving the resource endpoint. /// URI of the polling endpoint. /// Function merging original and polled exchanges: (original, polled?) → merged. /// Timeout waiting for data (default: 1 second). public PollEnrichProcessor( IRouteContext context, string resourceUri, Func mergeStrategy, TimeSpan? timeout = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _resourceUri = resourceUri ?? throw new ArgumentNullException(nameof(resourceUri)); (context as RouteContext)?.NoteStaticEndpoint(resourceUri); _mergeStrategy = mergeStrategy ?? throw new ArgumentNullException(nameof(mergeStrategy)); _timeout = timeout ?? TimeSpan.FromSeconds(1); } /// Creates a poll enrich processor with a dynamic endpoint resolver. public PollEnrichProcessor( IRouteContext context, DynamicEndpointResolver resolver, Func mergeStrategy, TimeSpan? timeout = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); _mergeStrategy = mergeStrategy ?? throw new ArgumentNullException(nameof(mergeStrategy)); _timeout = timeout ?? TimeSpan.FromSeconds(1); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { IExchange? pollExchange = null; IExchange? resourceExchange = null; try { try { using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); timeoutCts.CancelAfter(_timeout); // As Camel's pollEnrich, the polled exchange is not the caller's: an id of its own, no correlation id. pollExchange = exchange.CorrelatedCopyLinked(); pollExchange.Properties.Remove(ExchangePropertyKeys.CorrelationId); pollExchange.Pattern = ExchangePattern.InOut; var (endpoint, producer) = _resolver is not null ? await _resolver.ResolvePairAsync(pollExchange, timeoutCts.Token).ConfigureAwait(false) : GetOrCreatePair(); await CountedSend.Process(endpoint, producer, pollExchange, timeoutCts.Token).ConfigureAwait(false); resourceExchange = pollExchange; } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { // Timeout — resourceExchange stays null } // Merge (polled may be null if timeout) var merged = _mergeStrategy(exchange, resourceExchange); exchange.In.Body = merged.In.Body; foreach (var header in merged.In.Headers) exchange.In.Headers[header.Key] = header.Value; if (merged.Exception != null) exchange.Exception = merged.Exception; } finally { // The polled exchange's resources go with the original, as in Process. if (pollExchange is not null) ExchangeResources.HandOver(pollExchange, exchange); if (pollExchange is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } private (IEndpoint, IProducer) GetOrCreatePair() { if (_producer is not null) return (_endpoint!, _producer); _endpoint = _context.GetEndpoint(_resourceUri!); _producer = _endpoint.CreateProducerOnItsSide(); return (_endpoint, _producer); } } Path: redb-route/redb.Route/Processors/ExchangeEventsProcessor.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/Processors/ExchangeEventsProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Outermost per-route wrapper that publishes exchange-level lifecycle events /// (, , /// ) to the context's listener set. /// /// Sits outside inflight tracking and every error handler and reaches the consumer's verdict: "failed" /// means an exception is about to reach the consumer, or the route returned with a failure left /// unhandled on the exchange or a rollback-only mark; "completed" means the consumer acknowledges. /// When no listener is registered the wrapper is a plain pass-through with no awaits added. /// /// internal sealed class ExchangeEventsProcessor : IProcessor { private readonly IProcessor _inner; private readonly RouteContext _context; private readonly string _routeId; public ExchangeEventsProcessor(IProcessor inner, RouteContext context, string routeId) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _context = context ?? throw new ArgumentNullException(nameof(context)); _routeId = routeId ?? throw new ArgumentNullException(nameof(routeId)); } public Task Process(IExchange exchange, CancellationToken ct = default) => _context.HasLifecycleListeners ? ProcessWithEvents(exchange, ct) : _inner.Process(exchange, ct); private async Task ProcessWithEvents(IExchange exchange, CancellationToken ct) { await _context.NotifyExchangeReceived(_routeId, exchange, ct).ConfigureAwait(false); try { await _inner.Process(exchange, ct).ConfigureAwait(false); } // A cooperative cancellation is neither completed nor failed — the exchange was abandoned // by its caller (BR-10). The listener hears it arrive and then hears nothing, which is the // truthful account; "failed" would make NotifyBuilder count a closed dashboard tab as a // route failure. The filter lets the exception fly past without a notify. catch (Exception ex) when (!Core.StatisticsProcessor.IsCooperativeCancellation(ex, ct)) { await _context.NotifyExchangeFailed(_routeId, exchange, ex, ct).ConfigureAwait(false); throw; } // A normal return with a failure left unhandled on the exchange (OnException without Handled) or a rollback-only // mark (.RollbackAll()) is a failure: the consumer does not acknowledge it. if (ExchangeFailureExtensions.FailureOf(exchange) is { } failure) await _context.NotifyExchangeFailed(_routeId, exchange, failure, ct).ConfigureAwait(false); else await _context.NotifyExchangeCompleted(_routeId, exchange, ct).ConfigureAwait(false); } } Path: redb-route/redb.Route/Processors/ExpressionProcessors.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/Processors/ExpressionProcessors.cs ---- using System.Collections; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Processors; /// /// Resolves a string template: single ${expr} preserves CLR type, /// composite templates (with surrounding text) return string. /// internal static class ExpressionHelper { internal static object? ResolveTypedOrTemplate(string template, IExchange exchange) => ExpressionResolver.ResolveTypedOrTemplate(template, exchange); } /// /// Processor that evaluates an and sets the result as the exchange body. /// Used by the DSL .SetBody(IExpression) and .Transform(IExpression). /// public sealed class ExpressionBodyProcessor : IProcessor { private readonly IExpression _expression; /// Creates a new instance with the specified expression. /// Expression producing the new body value. public ExpressionBodyProcessor(IExpression expression) { _expression = expression ?? throw new ArgumentNullException(nameof(expression)); } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var result = _expression.Evaluate(exchange); exchange.In.Body = result; return Task.CompletedTask; } } /// /// Processor that evaluates an and sets the result as a header. /// Used by .SetHeader(key, IExpression). /// public sealed class ExpressionHeaderProcessor : IProcessor { private readonly string _headerName; private readonly IExpression _expression; /// Creates a new instance. /// Header key to set. /// Expression producing the header value. public ExpressionHeaderProcessor(string headerName, IExpression expression) { _headerName = headerName ?? throw new ArgumentNullException(nameof(headerName)); _expression = expression ?? throw new ArgumentNullException(nameof(expression)); } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var result = _expression.Evaluate(exchange); exchange.In.Headers[_headerName] = result; return Task.CompletedTask; } } /// /// Processor that evaluates an and sets the result as a property. /// Used by .SetProperty(key, IExpression). /// public sealed class ExpressionPropertyProcessor : IProcessor { private readonly string _propertyName; private readonly IExpression _expression; /// Creates a new instance. /// Property key to set. /// Expression producing the property value. public ExpressionPropertyProcessor(string propertyName, IExpression expression) { _propertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName)); _expression = expression ?? throw new ArgumentNullException(nameof(expression)); } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var result = _expression.Evaluate(exchange); exchange.Properties[_propertyName] = result; return Task.CompletedTask; } } /// /// Processor that logs a message using ExpressionResolver template syntax. /// Supports ${body}, ${header.name}, ${property.name} placeholders. /// Used by .Log(string) when the message contains ${...} placeholders. /// public sealed class TemplateLogProcessor : IProcessor { private readonly string _template; private readonly LogLevel _level; private readonly ILogger? _logger; /// Creates a new instance. /// Template string with ${...} placeholders. /// Log level. /// Logger instance (null = NullLogger). public TemplateLogProcessor(string template, LogLevel level, ILogger? logger = null) { _template = template ?? throw new ArgumentNullException(nameof(template)); _level = level; _logger = logger; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { if (_logger is not null && _logger.IsEnabled(_level)) { var resolved = ExpressionResolver.ProcessTemplate(_template, exchange); _logger.Log(_level, "{Message}", resolved); } return Task.CompletedTask; } } Path: redb-route/redb.Route/Processors/FilterProcessor.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/Processors/FilterProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Predicates; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Evaluates a predicate on the exchange and passes through only if true. /// When predicate returns false, the exchange is skipped (no processing). /// /// The predicate is held as an and awaited through /// , so a predicate that has to consult a store or a /// service can do so without blocking. A plain delegate is wrapped in a /// at the boundary. /// /// public class FilterProcessor : IProcessor { private readonly IPredicate _predicate; private readonly IProcessor _next; /// Creates a filter processor from a predicate instance. /// Predicate that must hold for processing to continue. /// The processor to execute when the predicate holds. public FilterProcessor(IPredicate predicate, IProcessor next) { _predicate = predicate ?? throw new ArgumentNullException(nameof(predicate)); _next = next ?? throw new ArgumentNullException(nameof(next)); } /// Creates a filter processor from a delegate, wrapped as a . /// Predicate that must return true for processing to continue. /// The processor to execute when predicate is true. public FilterProcessor(Func predicate, IProcessor next) : this(new LambdaPredicate(predicate ?? throw new ArgumentNullException(nameof(predicate))), next) { } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { if (await _predicate.MatchesAsync(exchange).ConfigureAwait(false)) { await _next.Process(exchange, ct).ConfigureAwait(false); return; } ProcessorMetrics.FilterDropped.Add(1); } }