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-ID s 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