Path: redb-route/redb.Route/Definitions/RouteDefinitionBase.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Definitions/RouteDefinitionBase.cs
----
#pragma warning disable CS0619
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Processors;
using redb.Route.Telemetry;
using redb.Route.Transactions;
using redb.Route.Validation;
using redb.Route.Xslt;
namespace redb.Route.Definitions;
///
/// Generic CRTP base for every route / scope definition. All leaf-DSL methods are declared here
/// exactly once and return for fluent chaining inside the concrete
/// scope. The class implements ; covariant return types let the
/// typed leaf-DSL satisfy the interface contract whose declared return type is
/// .
///
/// Apache Camel parity: this mirrors ProcessorDefinition<Type extends ProcessorDefinition<Type>>
/// from camel-core-model. Scope-opener methods (Filter , Choice , Split , ...)
/// return concrete scope types; child are populated
/// via the inherited typed DSL.
///
///
public abstract partial class RouteDefinitionBase : ProcessorDefinition, IRouteDefinition
where TSelf : RouteDefinitionBase
{
/// Typed self-reference for fluent chaining; safe because is constrained to this class.
protected TSelf Self => (TSelf)(object)this;
// ── Route-level state (carried by the root RouteDefinition; scope instances inherit the
// fields but only the root reads them) ───────────────────────────────────────────────
private string? _routeId;
private string? _fromUri;
private bool _autoStart = true;
private TimeSpan? _processingTimeout;
private bool _cluster;
private bool? _messageHistory;
private bool? _tracing;
private IRoutePolicy? _routePolicy;
private string? _routePolicyName;
private string? _routeConfigurationId;
internal IRouteContext? _context;
/// Route context captured during compile (null until the route is added to a context).
public IRouteContext? Context
{
get
{
if (_context is not null) return _context;
// Walk up the parent chain to find the root RouteDefinition (which carries the context).
for (var p = Parent; p is not null; p = (p as ProcessorDefinition)?.Parent)
{
if (p is RouteDefinition rd && rd._context is not null) return rd._context;
}
return null;
}
}
/// Flag controlling whether the route id is shown in log/telemetry output (default false).
public bool ShowRouteIdValue { get; internal set; }
///
/// True when this route's compiled pipeline opens an explicit declarative
/// scope at the top level (Apache Camel parity).
///
public bool IsTransacted => Outputs.Any(o => o is TransactionDefinition);
// ── Route-level identity ──────────────────────────────────────────────────
///
public TSelf RouteId(string routeId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(routeId);
_routeId = routeId;
return Self;
}
///
public string? GetRouteId() => _routeId;
///
public TSelf Id(string id)
{
ArgumentException.ThrowIfNullOrWhiteSpace(id);
if (Outputs.Count == 0)
return RouteId(id);
if (Outputs[^1] is ProcessorDefinition step)
step.StepId = id;
return Self;
}
///
public TSelf Description(string description)
{
ArgumentException.ThrowIfNullOrWhiteSpace(description);
if (Outputs.Count == 0)
{
StepDescription = description;
return Self;
}
if (Outputs[^1] is ProcessorDefinition step)
step.StepDescription = description;
return Self;
}
// ── Interception / completion: registered on the root route, applied at compile ──────────
///
public InterceptDefinition Intercept() => RegisterIntercept(new InterceptDefinition(InterceptKind.EveryStep, null));
///
public InterceptDefinition InterceptFrom(string? uriPattern = null) => RegisterIntercept(new InterceptDefinition(InterceptKind.From, uriPattern));
///
public InterceptDefinition InterceptSendToEndpoint(string uriPattern) => RegisterIntercept(new InterceptDefinition(InterceptKind.SendToEndpoint, uriPattern));
///
public OnCompletionDefinition OnCompletion()
{
var def = new OnCompletionDefinition { Parent = this };
RootRoute("OnCompletion()").OnCompletions.Add(def);
return def;
}
private InterceptDefinition RegisterIntercept(InterceptDefinition def)
{
def.Parent = this;
var verb = def.Kind switch
{
InterceptKind.From => "InterceptFrom()",
InterceptKind.SendToEndpoint => "InterceptSendToEndpoint()",
_ => "Intercept()",
};
RootRoute(verb).Intercepts.Add(def);
return def;
}
/// The root this scope belongs to; intercepts and completions are route-wide, so they live there.
private RouteDefinition RootRoute(string verb)
{
for (IProcessorDefinition? node = this; node is not null; node = node.Parent)
if (node is RouteDefinition root) return root;
throw new InvalidOperationException($"{verb} must be declared on a route (From(...)) or on the RouteBuilder for all its routes.");
}
// ── Header / property / body sugar ────────────────────────────────────────
///
public TSelf SetHeaders(params (string Name, object? Value)[] headers)
{
AddOutput(new SetHeadersDefinition(headers));
return Self;
}
///
public TSelf SetProperties(params (string Name, object? Value)[] properties)
{
AddOutput(new SetPropertiesDefinition(properties));
return Self;
}
///
public TSelf RemoveHeaders(string pattern, params string[] except)
{
AddOutput(new RemoveByMaskDefinition(RemoveTarget.Headers, pattern, except ?? []));
return Self;
}
///
public TSelf RemoveProperties(string pattern, params string[] except)
{
AddOutput(new RemoveByMaskDefinition(RemoveTarget.Properties, pattern, except ?? []));
return Self;
}
///
public TSelf Sort(string collectionExpression, string? keyExpression = null, bool descending = false)
{
ArgumentException.ThrowIfNullOrWhiteSpace(collectionExpression);
var collection = new StringExpression(collectionExpression);
var key = keyExpression is null ? null : new StringExpression(keyExpression);
AddOutput(new SortDefinition(
exchange => collection.Evaluate(exchange) as System.Collections.IEnumerable,
key is null ? null : item => key.Evaluate(Exchange.Create(new Message(item), null)),
comparer: null,
descending));
return Self;
}
///
public TSelf Sort(Func> source, Func? key = null, bool descending = false, IComparer? comparer = null)
{
ArgumentNullException.ThrowIfNull(source);
AddOutput(new SortDefinition(
exchange => source(exchange),
key is null ? null : item => key((T)item!),
comparer,
descending,
items => items.Cast().ToList()));
return Self;
}
///
public TSelf AutoStart(bool value = true) { _autoStart = value; return Self; }
///
public bool GetAutoStart() => _autoStart;
///
public TSelf ProcessingTimeout(TimeSpan timeout)
{
if (timeout <= TimeSpan.Zero && timeout != System.Threading.Timeout.InfiniteTimeSpan)
throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive or Infinite.");
_processingTimeout = timeout;
return Self;
}
/// Gets the per-route processing timeout, or null if not set.
public TimeSpan? GetProcessingTimeout() => _processingTimeout;
// ── Source ───────────────────────────────────────────────────────────────
///
public TSelf From(string uri)
{
ArgumentException.ThrowIfNullOrWhiteSpace(uri);
_fromUri = uri;
return Self;
}
///
public string? GetFromUri() => _fromUri;
// ── Destination ──────────────────────────────────────────────────────────
///
public TSelf To(string uri)
{
AddOutput(new ToDefinition(uri));
return Self;
}
///
public TSelf ToD(string uriTemplate)
{
AddOutput(new ToDynamicDefinition(uriTemplate));
return Self;
}
///
public TSelf ToD(IExpression uriExpression)
{
AddOutput(new ToDynamicDefinition(uriExpression));
return Self;
}
///
public TSelf ToD(Func uriFactory)
{
AddOutput(new ToDynamicDefinition(uriFactory));
return Self;
}
// ── Processing delegates ──────────────────────────────────────────────────
///
public TSelf Process(Action action)
{
AddOutput(new ProcessActionDefinition(action));
return Self;
}
///
public TSelf Process(Func action)
{
AddOutput(new ProcessAsyncDefinition(action));
return Self;
}
///
public TSelf Process(IProcessor processor)
{
AddOutput(new ProcessInstanceDefinition(processor));
return Self;
}
// ── Transform / body ─────────────────────────────────────────────────────
///
public TSelf SetBody(object? value)
{
AddOutput(new SetBodyStaticDefinition(value));
return Self;
}
///
public TSelf SetBody(Func factory)
{
AddOutput(new SetBodyFactoryDefinition(factory));
return Self;
}
///
public TSelf SetBody(IExpression expression)
{
AddOutput(new SetBodyExpressionDefinition(expression));
return Self;
}
///
public TSelf Transform(Func transform)
{
AddOutput(new TransformDefinition(transform));
return Self;
}
///
public TSelf Transform(IExpression expression)
{
AddOutput(new TransformExpressionDefinition(expression));
return Self;
}
///
public TSelf RemoveBody()
{
AddOutput(new RemoveBodyDefinition());
return Self;
}
// ── Headers ──────────────────────────────────────────────────────────────
///
public TSelf SetHeader(string key, object? value)
{
AddOutput(new SetHeaderStaticDefinition(key, value));
return Self;
}
///
public TSelf SetHeader(string key, Func factory)
{
AddOutput(new SetHeaderFactoryDefinition(key, factory));
return Self;
}
///
public TSelf SetHeader(string name, IExpression expression)
{
AddOutput(new SetHeaderExpressionDefinition(name, expression));
return Self;
}
///
public TSelf RemoveHeader(string key)
{
AddOutput(new RemoveHeaderDefinition(key));
return Self;
}
// ── Attachments ──────────────────────────────────────────────────────────
///
public TSelf AddAttachment(string name, IExpression content, string? fileName = null, string? contentType = null)
{
AddOutput(AddAttachmentDefinition.FromExpression(name, content, AddAttachmentDefinition.Literal(fileName), contentType));
return Self;
}
///
public TSelf AddAttachment(string name, IExpression content, IExpression fileName, string? contentType = null)
{
ArgumentNullException.ThrowIfNull(fileName);
AddOutput(AddAttachmentDefinition.FromExpression(name, content, fileName, contentType));
return Self;
}
///
public TSelf AddAttachmentFromBody(string name, string? fileName = null, string? contentType = null)
{
AddOutput(AddAttachmentDefinition.FromBody(name, AddAttachmentDefinition.Literal(fileName), contentType));
return Self;
}
///
public TSelf AddAttachmentFromBody(string name, IExpression fileName, string? contentType = null)
{
ArgumentNullException.ThrowIfNull(fileName);
AddOutput(AddAttachmentDefinition.FromBody(name, fileName, contentType));
return Self;
}
///
public TSelf AddAttachmentFromFile(string path, string? name = null, string? contentType = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
AddOutput(AddAttachmentDefinition.FromFile(AddAttachmentDefinition.Literal(path)!, name, contentType));
return Self;
}
///
public TSelf AddAttachmentFromFile(IExpression path, string? name = null, string? contentType = null)
{
AddOutput(AddAttachmentDefinition.FromFile(path, name, contentType));
return Self;
}
///
public TSelf RemoveAttachment(string name)
{
AddOutput(new RemoveAttachmentDefinition(name));
return Self;
}
///
public TSelf RemoveAttachments()
{
AddOutput(new RemoveAttachmentsDefinition());
return Self;
}
// ── Properties ───────────────────────────────────────────────────────────
///
public TSelf SetProperty(string key, object? value)
{
AddOutput(new SetPropertyStaticDefinition(key, value));
return Self;
}
///
public TSelf SetProperty(string key, Func factory)
{
AddOutput(new SetPropertyFactoryDefinition(key, factory));
return Self;
}
///
public TSelf SetProperty(string key, IExpression expression)
{
AddOutput(new SetPropertyExpressionDefinition(key, expression));
return Self;
}
///
public TSelf RemoveProperty(string key)
{
AddOutput(new RemovePropertyDefinition(key));
return Self;
}
// ── Logging ──────────────────────────────────────────────────────────────
///
public TSelf Log(string message, LogLevel level = LogLevel.Information)
{
AddOutput(new LogStaticDefinition(message, level));
return Self;
}
///
public TSelf Log(Func messageFactory, LogLevel level = LogLevel.Information)
{
AddOutput(new LogDynamicDefinition(messageFactory, level));
return Self;
}
// ── Stop / Throw ──────────────────────────────────────────────────────────
///
public TSelf Stop()
{
AddOutput(new StopDefinition());
return Self;
}
///
public TSelf ThrowException()
{
AddOutput(new RethrowExceptionDefinition());
return Self;
}
///
public TSelf ThrowException(string message)
{
AddOutput(new ThrowMessageDefinition(message));
return Self;
}
///
public TSelf ThrowException(Exception exception)
{
AddOutput(new ThrowExceptionDefinition(exception));
return Self;
}
///
public TSelf ThrowException(Type exceptionType, string message)
{
AddOutput(new ThrowExceptionTypeDefinition(exceptionType, message));
return Self;
}
///
public TSelf ThrowException(string? message = null) where TException : Exception, new()
{
AddOutput(new ThrowExceptionTypeDefinition(typeof(TException), message));
return Self;
}
// ── Delay / Sampling ─────────────────────────────────────────────────────
///
public TSelf Delay(TimeSpan duration)
{
AddOutput(new DelayDefinition(duration));
return Self;
}
///
public TSelf Delay(Func factory)
{
AddOutput(new DelayFactoryDefinition(factory));
return Self;
}
///
public TSelf Delay(string durationExpression)
{
ArgumentException.ThrowIfNullOrWhiteSpace(durationExpression);
var expression = new StringExpression(durationExpression);
return Delay(exchange => DelayExpressionDefinition.ConvertToTimeSpan(expression.Evaluate(exchange)));
}
///
public TSelf Sample(long messageFrequency)
{
AddOutput(new SampleCountDefinition(messageFrequency));
return Self;
}
///
public TSelf Sample(TimeSpan period)
{
AddOutput(new SamplePeriodDefinition(period));
return Self;
}
// ── Stream caching ───────────────────────────────────────────────────────
///
public TSelf StreamCaching(long? spoolThreshold = null)
{
AddOutput(new StreamCachingDefinition(spoolThreshold));
return Self;
}
// ── Validation ───────────────────────────────────────────────────────────
///
public TSelf Validate(IMessageValidator validator, bool throwOnFailure = true)
{
AddOutput(new ValidateInstanceDefinition(validator, throwOnFailure));
return Self;
}
///
public TSelf Validate(Func predicate, string errorMessage = "Validation failed", bool throwOnFailure = true)
{
AddOutput(new ValidatePredicateDefinition(predicate, errorMessage, throwOnFailure));
return Self;
}
///
public TSelf Validate(IPredicate predicate, string errorMessage = "Validation failed", bool throwOnFailure = true)
{
ArgumentNullException.ThrowIfNull(predicate);
AddOutput(new ValidatePredicateDefinition(predicate, errorMessage, throwOnFailure));
return Self;
}
///
public TSelf Validate(IExpression condition, string errorMessage = "Validation failed", bool throwOnFailure = true)
{
ArgumentNullException.ThrowIfNull(condition);
return Validate(Predicates.PredicateFactory.FromExpression(condition), errorMessage, throwOnFailure);
}
///
public TSelf ValidateJsonSchema(string schemaJson, bool throwOnFailure = true)
{
AddOutput(new ValidateJsonSchemaStringDefinition(schemaJson, throwOnFailure));
return Self;
}
///
public TSelf ValidateJsonSchema(Json.Schema.JsonSchema schema, bool throwOnFailure = true)
{
AddOutput(new ValidateJsonSchemaObjectDefinition(schema, throwOnFailure));
return Self;
}
///
public TSelf ValidateXsd(string xsdContent, bool throwOnFailure = true)
{
AddOutput(new ValidateXsdStringDefinition(xsdContent, throwOnFailure));
return Self;
}
///
public TSelf ValidateXsd(string? targetNamespace, string xsdContent, bool throwOnFailure = true)
{
AddOutput(new ValidateXsdNamespaceDefinition(targetNamespace, xsdContent, throwOnFailure));
return Self;
}
///
public TSelf ValidateXsd(System.Xml.Schema.XmlSchemaSet schemaSet, bool throwOnFailure = true)
{
AddOutput(new ValidateXsdSchemaSetDefinition(schemaSet, throwOnFailure));
return Self;
}
///
public TSelf ValidateXsdFile(string schemaPath, string? targetNamespace = null, string? schemaRoot = null,
bool throwOnFailure = true)
{
AddOutput(new ValidateXsdFileDefinition(schemaPath, targetNamespace, schemaRoot, throwOnFailure));
return Self;
}
// ── XSLT ─────────────────────────────────────────────────────────────────
///
/// Apache Camel xslt: parity: transform the exchange body through an XSLT stylesheet loaded
/// from a file (compiled once, reused; xsl:import /xsl:include resolve relative
/// to the file). BCL XslCompiledTransform engine (XSLT 1.0).
///
public TSelf Xslt(string stylesheetPath, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false)
{
AddOutput(new XsltFileDefinition(stylesheetPath, output, failOnNullBody, allowTemplateFromHeader));
return Self;
}
///
/// Transform the exchange body through an inline XSLT stylesheet document (self-contained;
/// no xsl:import /xsl:include ).
///
public TSelf XsltContent(string stylesheetXml, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool allowTemplateFromHeader = false)
{
AddOutput(new XsltContentDefinition(stylesheetXml, output, failOnNullBody, allowTemplateFromHeader));
return Self;
}
// ── Control Bus ──────────────────────────────────────────────────────────
///
/// Apache Camel controlbus: parity: manage a route at runtime by sending a control message.
/// Sugar over .To("controlbus:route?routeId=...&action=...") . Use routeId "current"
/// to target the sending route. Stopping the current route uses async dispatch to avoid a self-deadlock.
///
public TSelf ControlBus(redb.Route.ControlBus.ControlBusAction action, string routeId, bool async = false)
{
ArgumentException.ThrowIfNullOrWhiteSpace(routeId);
var uri = $"controlbus:route?routeId={System.Uri.EscapeDataString(routeId)}&action={action.ToString().ToLowerInvariant()}";
if (async) uri += "&async=true";
return To(uri);
}
// ── Serialization ────────────────────────────────────────────────────────
///
public TSelf Marshal(Type serializerType)
{
AddOutput(new MarshalDefinition(serializerType));
return Self;
}
///
public TSelf Marshal() where TSerializer : class
{
AddOutput(new MarshalDefinition(typeof(TSerializer)));
return Self;
}
///
public TSelf Unmarshal(Type serializerType, Type targetType)
{
AddOutput(new UnmarshalDefinition(serializerType, targetType));
return Self;
}
///
public TSelf Unmarshal() where TSerializer : class
{
AddOutput(new UnmarshalDefinition(typeof(TSerializer), typeof(TTarget)));
return Self;
}
///
public TSelf Marshal(string contentType)
{
AddOutput(new MarshalDefinition(contentType));
return Self;
}
///
public TSelf Marshal(IMessageSerializer serializer)
{
AddOutput(new MarshalDefinition(serializer));
return Self;
}
///
public TSelf Unmarshal(string contentType)
{
AddOutput(new UnmarshalDefinition(contentType, typeof(T)));
return Self;
}
///
public TSelf Unmarshal(string contentType, Type targetType)
{
AddOutput(new UnmarshalDefinition(contentType, targetType));
return Self;
}
///
public TSelf Unmarshal(IMessageSerializer serializer)
{
AddOutput(new UnmarshalDefinition(serializer, typeof(T)));
return Self;
}
///
public TSelf Unmarshal(IMessageSerializer serializer, Type targetType)
{
AddOutput(new UnmarshalDefinition(serializer, targetType));
return Self;
}
///
/// Converts the body to via the registered type converters —
/// an alias of . This does not decode by format/ContentType;
/// for JSON/XML/etc. decoding use with
/// an explicit serializer.
///
public TSelf Unmarshal()
{
AddOutput(new ConvertBodyDefinition(typeof(T)));
return Self;
}
/// Apache Camel parity: convert the exchange body to .
public TSelf ConvertBody()
{
AddOutput(new ConvertBodyDefinition(typeof(T)));
return Self;
}
/// Apache Camel parity: convert the exchange body to .
public TSelf ConvertBody(Type targetType)
{
AddOutput(new ConvertBodyDefinition(targetType));
return Self;
}
///
/// Apache Camel parity: open a typed scope. Auto-converts the body to
/// and exposes typed Process /Filter /Transform overloads to its children.
///
public OfTypeDefinition OfType()
{
var def = new OfTypeDefinition();
AddOutput(def);
return def;
}
// ── Transactions ─────────────────────────────────────────────────────────
///
public TSelf BeginTransaction()
{
AddOutput(new BeginTransactionDefinition());
return Self;
}
///
public TSelf BeginTransaction(Transactions.TransactionPolicy policy)
{
AddOutput(new BeginTransactionDefinition(policy));
return Self;
}
///
public TSelf CommitTransaction()
{
AddOutput(new CommitTransactionDefinition());
return Self;
}
///
public TSelf RollbackTransaction()
{
AddOutput(new RollbackTransactionDefinition());
return Self;
}
///
public TransactionDefinition Transaction(TransactionPolicy? policy = null)
{
var def = new TransactionDefinition(policy);
AddOutput(def);
return def;
}
// ── Replay checkpoints ──────────────────────────────────────────────────
///
/// Opens a replay checkpoint (save-point). The steps that follow become the marker's body
/// (the tail re-run on replay). On each pass the exchange is snapshotted into
/// route.checkpoint . At the very start of a route no
/// is needed (the body is the whole pipeline); in the middle or with several markers, close with
/// or use the lambda-body overload.
///
/// Save-point name, unique within the route.
///
/// When true , the marker is also an addressable public entry (.To(...) / tests);
/// default false = internal replay only via .
///
public ReplayableDefinition Replayable(string name, bool exposed = false)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var def = new ReplayableDefinition(name, exposed);
AddOutput(def);
return def; // opener returns the child — subsequent steps fall into its body
}
///
/// Lambda-body form of — unambiguous at any nesting level.
/// The configures the marker's tail; the chain stays on the current
/// definition (no explicit End ).
///
public TSelf Replayable(string name, Action body, bool exposed = false)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentNullException.ThrowIfNull(body);
var def = new ReplayableDefinition(name, exposed);
AddOutput(def);
body(def);
return Self;
}
// ── Telemetry ────────────────────────────────────────────────────────────
///
public TracedDefinition Traced(string operationName)
{
var def = new TracedDefinition(operationName);
AddOutput(def);
return def;
}
///
public TSelf Traced(string operationName, Action action)
{
ArgumentException.ThrowIfNullOrWhiteSpace(operationName);
AddOutput(new ProcessInstanceDefinition(
new Telemetry.InstrumentedProcessor(new Processors.DelegateProcessor(action), operationName)));
return Self;
}
///
public TSelf Traced(string operationName, Func action)
{
ArgumentException.ThrowIfNullOrWhiteSpace(operationName);
ArgumentNullException.ThrowIfNull(action);
AddOutput(new ProcessInstanceDefinition(
new Telemetry.InstrumentedProcessor(new Processors.DelegateProcessor(action), operationName)));
return Self;
}
///
public TSelf Traced(string operationName, IProcessor processor)
{
ArgumentException.ThrowIfNullOrWhiteSpace(operationName);
ArgumentNullException.ThrowIfNull(processor);
AddOutput(new ProcessInstanceDefinition(
new Telemetry.InstrumentedProcessor(processor, operationName)));
return Self;
}
///
public MeteredDefinition Metered(string stepName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(stepName);
if (stepName.Contains("${"))
throw new ArgumentException(
$"Metered() step name must be a constant to avoid metric cardinality explosion (got dynamic template '{stepName}'). " +
"Use tags on the activity instead of templating the name.",
nameof(stepName));
var def = new MeteredDefinition(stepName);
AddOutput(def);
return def;
}
///
public TSelf Metered(string stepName, Action action)
{
ArgumentException.ThrowIfNullOrWhiteSpace(stepName);
ArgumentNullException.ThrowIfNull(action);
if (stepName.Contains("${"))
throw new ArgumentException(
$"Metered() step name must be a constant to avoid metric cardinality explosion (got dynamic template '{stepName}').",
nameof(stepName));
AddOutput(new ProcessInstanceDefinition(
new Telemetry.MeteredStepProcessor(new Processors.DelegateProcessor(action), stepName)));
return Self;
}
///
public TSelf Metered(string stepName, Func action)
{
ArgumentException.ThrowIfNullOrWhiteSpace(stepName);
ArgumentNullException.ThrowIfNull(action);
AddOutput(new ProcessInstanceDefinition(
new Telemetry.MeteredStepProcessor(new Processors.DelegateProcessor(action), stepName)));
return Self;
}
///
public TSelf Metered(string stepName, IProcessor processor)
{
ArgumentException.ThrowIfNullOrWhiteSpace(stepName);
ArgumentNullException.ThrowIfNull(processor);
AddOutput(new ProcessInstanceDefinition(
new Telemetry.MeteredStepProcessor(processor, stepName)));
return Self;
}
///
public TSelf SpanTag(string key, string value, Telemetry.SpanTarget target = Telemetry.SpanTarget.Enclosing)
{
// A constant tag that is never set is a mistake in the route, not a value to skip per message.
ArgumentException.ThrowIfNullOrEmpty(value);
return SpanTag(key, new Expressions.ConstantExpression(value), target);
}
///
public TSelf SpanTag(string key, IExpression value, Telemetry.SpanTarget target = Telemetry.SpanTarget.Enclosing)
{
AddOutput(new SpanTagDefinition(key, value, target));
return Self;
}
// ── Enrichment ───────────────────────────────────────────────────────────
///
public TSelf WireTap(string uri, string? executorService = null)
{
AddOutput(new WireTapDefinition(uri, executorService: executorService));
return Self;
}
///
public TSelf WireTap(string uri, Action onPrepare, string? executorService = null)
{
AddOutput(new WireTapDefinition(uri, onPrepare: onPrepare, executorService: executorService));
return Self;
}
///
public TSelf WireTap(string uri, Func newBodyFactory, string? executorService = null)
{
AddOutput(new WireTapDefinition(uri, newBodyFactory: newBodyFactory, executorService: executorService));
return Self;
}
///
public TSelf WireTap(string uri, Action onPrepare, Func newBodyFactory, string? executorService = null)
{
AddOutput(new WireTapDefinition(uri, onPrepare, newBodyFactory, executorService: executorService));
return Self;
}
///
public TSelf WireTap(Func uriFactory, string? executorService = null)
{
AddOutput(new WireTapDynamicDefinition(uriFactory, executorService: executorService));
return Self;
}
///
public TSelf WireTap(Func uriFactory, Action onPrepare, string? executorService = null)
{
AddOutput(new WireTapDynamicDefinition(uriFactory, onPrepare: onPrepare, executorService: executorService));
return Self;
}
///
public TSelf WireTap(Func uriFactory, Func newBodyFactory, string? executorService = null)
{
AddOutput(new WireTapDynamicDefinition(uriFactory, newBodyFactory: newBodyFactory, executorService: executorService));
return Self;
}
///
public TSelf WireTap(Func uriFactory, Action onPrepare, Func newBodyFactory, string? executorService = null)
{
AddOutput(new WireTapDynamicDefinition(uriFactory, onPrepare, newBodyFactory, executorService: executorService));
return Self;
}
///
public TSelf Enrich(string resourceUri, Func mergeStrategy)
{
AddOutput(new EnrichDefinition(resourceUri, mergeStrategy));
return Self;
}
///
public TSelf Enrich(Func uriFactory, Func mergeStrategy)
{
AddOutput(new EnrichDynamicDefinition(uriFactory, mergeStrategy));
return Self;
}
/// Apache Camel parity: poll an external endpoint and merge the polled result.
public TSelf PollEnrich(
string resourceUri,
Func mergeStrategy,
TimeSpan? timeout = null)
{
AddOutput(new PollEnrichDefinition(resourceUri, mergeStrategy, timeout));
return Self;
}
///
public TSelf PollEnrich(
Func uriFactory,
Func mergeStrategy,
TimeSpan? timeout = null)
{
AddOutput(new PollEnrichDynamicDefinition(uriFactory, mergeStrategy, timeout));
return Self;
}
///
public TSelf Enrich(string resourceUri) => Enrich(resourceUri, Aggregation.AggregationStrategies.UseLatest());
///
public TSelf Enrich(Func uriFactory) => Enrich(uriFactory, Aggregation.AggregationStrategies.UseLatest());
///
public TSelf Enrich(IExpression uri, Func mergeStrategy)
=> Enrich(Expressions.ExpressionValues.Required(uri, nameof(Enrich)), mergeStrategy);
///
public TSelf Enrich(IExpression uri) => Enrich(uri, Aggregation.AggregationStrategies.UseLatest());
///
public TSelf PollEnrich(string resourceUri, TimeSpan? timeout = null)
=> PollEnrich(resourceUri, static (original, polled) => polled ?? original, timeout);
///
public TSelf PollEnrich(Func uriFactory, TimeSpan? timeout = null)
=> PollEnrich(uriFactory, static (original, polled) => polled ?? original, timeout);
///
public TSelf PollEnrich(
IExpression uri,
Func mergeStrategy,
TimeSpan? timeout = null)
=> PollEnrich(Expressions.ExpressionValues.Required(uri, nameof(PollEnrich)), mergeStrategy, timeout);
///
public TSelf PollEnrich(IExpression uri, TimeSpan? timeout = null)
=> PollEnrich(uri, static (original, polled) => polled ?? original, timeout);
/// Apache Camel parity: route to a list of recipient URIs computed at runtime.
public TSelf RecipientList(
Func> recipientListFactory,
bool parallelProcessing = false,
bool stopOnException = false,
Func? aggregationStrategy = null)
{
AddOutput(new RecipientListDefinition(
recipientListFactory, parallelProcessing, stopOnException, aggregationStrategy));
return Self;
}
///
public TSelf RecipientList(
IExpression recipients,
bool parallelProcessing = false,
bool stopOnException = false,
Func? aggregationStrategy = null,
string uriDelimiter = ",")
=> RecipientList(
Expressions.ExpressionValues.UriList(recipients, uriDelimiter),
parallelProcessing,
stopOnException,
aggregationStrategy);
/// Apache Camel parity: iteratively route to URIs returned by a routing function.
public TSelf DynamicRouter(Func routingFunction)
{
AddOutput(new DynamicRouterDefinition(routingFunction));
return Self;
}
///
public TSelf DynamicRouter(IExpression routingExpression)
=> DynamicRouter(Expressions.ExpressionValues.Optional(routingExpression));
///
/// Apache Camel parity: Routing Slip — pipe the exchange through a list of endpoints computed
/// once up front by (contrast Dynamic Router, which recomputes
/// per hop). The same exchange is threaded through the endpoints in sequence (Out→In between hops).
///
public TSelf RoutingSlip(Func> slipFactory, bool ignoreInvalidEndpoints = false)
{
AddOutput(new RoutingSlipDefinition(slipFactory, ignoreInvalidEndpoints));
return Self;
}
///
/// Apache Camel parity: Routing Slip from an yielding a delimited URI
/// string (e.g. .RoutingSlip(Header("mySlip")) ). Default delimiter is , .
///
public TSelf RoutingSlip(IExpression slip, string uriDelimiter = ",", bool ignoreInvalidEndpoints = false)
{
AddOutput(new RoutingSlipDefinition(slip, uriDelimiter, ignoreInvalidEndpoints));
return Self;
}
///
/// Apache Camel parity: Routing Slip from a ${...} template (or a literal like
/// "direct:a,direct:b" ) resolving to a delimited URI string. Default delimiter is , .
///
public TSelf RoutingSlip(string slipTemplate, string uriDelimiter = ",", bool ignoreInvalidEndpoints = false)
{
AddOutput(new RoutingSlipDefinition(slipTemplate, uriDelimiter, ignoreInvalidEndpoints));
return Self;
}
///
/// Apache Camel parity: open a Resequencer scope. The contained child outputs receive
/// exchanges in the order determined by .
///
public ResequenceDefinition Resequence(
Func keySelector,
int batchSize = 100,
TimeSpan? timeout = null)
{
var def = new ResequenceDefinition(keySelector, batchSize, timeout);
AddOutput(def);
return def;
}
// ── Scope openers ────────────────────────────────────────────────────────
///
public FilterDefinition Filter(Func predicate)
{
var def = new FilterDefinition(predicate);
AddOutput(def);
return def;
}
///
public FilterDefinition Filter(IExpression expression)
{
ArgumentNullException.ThrowIfNull(expression);
var def = new FilterDefinition(Predicates.PredicateFactory.FromExpression(expression))
{
SourceExpression = expression,
};
AddOutput(def);
return def;
}
///
public FilterDefinition Filter(IPredicate predicate)
{
ArgumentNullException.ThrowIfNull(predicate);
var def = new FilterDefinition(predicate)
{
SourcePredicate = predicate,
};
AddOutput(def);
return def;
}
///
public IdempotentConsumerDefinition IdempotentConsumer(
IIdempotentRepository repository,
Func keyExtractor,
bool skipDuplicate = true)
{
var def = new IdempotentConsumerDefinition(repository, keyExtractor, skipDuplicate);
AddOutput(def);
return def;
}
///
/// Apache Camel parity overload that looks up the repository by registered name from the
/// route context's .
///
public IdempotentConsumerDefinition IdempotentConsumer(
Func keyExtractor,
string repositoryName,
bool skipDuplicate = true)
{
var def = new IdempotentConsumerDefinition(repositoryName, keyExtractor, skipDuplicate);
AddOutput(def);
return def;
}
///
public IdempotentConsumerDefinition IdempotentConsumer(
IIdempotentRepository repository,
IExpression messageId,
bool skipDuplicate = true)
=> IdempotentConsumer(
repository,
Expressions.ExpressionValues.Required(messageId, nameof(IdempotentConsumer)),
skipDuplicate);
///
public IdempotentConsumerDefinition IdempotentConsumer(
IExpression messageId,
string repositoryName,
bool skipDuplicate = true)
=> IdempotentConsumer(
Expressions.ExpressionValues.Required(messageId, nameof(IdempotentConsumer)),
repositoryName,
skipDuplicate);
///
public TSelf ClaimCheck(
ClaimCheckOperation operation,
string? key = null,
TimeSpan? ttl = null,
string? repositoryName = null)
{
AddOutput(new ClaimCheckDefinition(operation, key, ttl, repositoryName));
return Self;
}
///
public TSelf ClaimCheck(
IClaimCheckRepository repository,
ClaimCheckOperation operation,
string? key = null,
TimeSpan? ttl = null)
{
ArgumentNullException.ThrowIfNull(repository);
AddOutput(new ClaimCheckDefinition(repository, operation, key, ttl));
return Self;
}
IRouteDefinition IRouteDefinition.ClaimCheck(
ClaimCheckOperation operation, string? key, TimeSpan? ttl, string? repositoryName)
=> ClaimCheck(operation, key, ttl, repositoryName);
IRouteDefinition IRouteDefinition.ClaimCheck(
IClaimCheckRepository repository, ClaimCheckOperation operation, string? key, TimeSpan? ttl)
=> ClaimCheck(repository, operation, key, ttl);
///
public ChoiceDefinition Choice()
{
var def = new ChoiceDefinition();
AddOutput(def);
return def;
}
///
public SplitDefinition Split(Func> splitter)
{
var def = new SplitDefinition(splitter);
AddOutput(def);
return def;
}
///
public SplitDefinition Split(IExpression expression)
{
var def = new SplitDefinition(expression);
AddOutput(def);
return def;
}
///
public SplitDefinition Split(Func> splitter)
{
var def = new SplitDefinition(splitter);
AddOutput(def);
return def;
}
///
public MulticastDefinition Multicast()
{
var def = new MulticastDefinition();
AddOutput(def);
return def;
}
///
public ThreadsDefinition Threads(int poolSize)
{
var def = new ThreadsDefinition(poolSize);
AddOutput(def);
return def;
}
///
public TryCatchDefinition TryCatch()
{
var def = new TryCatchDefinition();
AddOutput(def);
return def;
}
///
public AggregateDefinition Aggregate(
Func correlationKey,
Func aggregationStrategy,
Func completionPredicate)
{
var def = new AggregateDefinition(correlationKey, aggregationStrategy, completionPredicate);
AddOutput(def);
return def;
}
///
public AggregateDefinition Aggregate(
IExpression correlationKey,
Func aggregationStrategy,
Func completionPredicate)
=> Aggregate(
Expressions.ExpressionValues.Required(correlationKey, nameof(Aggregate)),
aggregationStrategy,
completionPredicate);
///
public ThrottleDefinition Throttle(int maxPerPeriod)
{
var def = new ThrottleDefinition(maxPerPeriod);
AddOutput(def);
return def;
}
///
public ThrottleDefinition Throttle(Func maxPerPeriodFactory)
{
var def = new ThrottleDefinition(maxPerPeriodFactory);
AddOutput(def);
return def;
}
///
public ThrottleDefinition Throttle(string maxPerPeriodExpression, TimeSpan? period = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(maxPerPeriodExpression);
var expression = new StringExpression(maxPerPeriodExpression);
var def = Throttle(exchange => expression.Evaluate(exchange));
return period is null ? def : def.Period(period.Value);
}
///
public KeyedThrottleDefinition Throttle(
Func keyExtractor,
int maxPerPeriod,
TimeSpan? period = null)
{
var def = new KeyedThrottleDefinition(keyExtractor, maxPerPeriod, period);
AddOutput(def);
return def;
}
///
public KeyedThrottleDefinition Throttle(
Func keyExtractor,
Func maxPerPeriodFactory,
TimeSpan? period = null)
{
var def = new KeyedThrottleDefinition(keyExtractor, maxPerPeriodFactory, period);
AddOutput(def);
return def;
}
///
public KeyedThrottleDefinition Throttle(
string keyExpression,
string maxPerPeriodExpression,
TimeSpan? period = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyExpression);
ArgumentException.ThrowIfNullOrWhiteSpace(maxPerPeriodExpression);
var key = new StringExpression(keyExpression);
var limit = new StringExpression(maxPerPeriodExpression);
return Throttle(
e => key.Evaluate(e)?.ToString() ?? string.Empty,
e => limit.Evaluate(e),
period);
}
///
public CircuitBreakerDefinition CircuitBreaker()
{
var def = new CircuitBreakerDefinition();
AddOutput(def);
return def;
}
///
public DebounceDefinition Debounce(Func keyExtractor, TimeSpan quietPeriod)
{
var def = new DebounceDefinition(keyExtractor, quietPeriod);
AddOutput(def);
return def;
}
///
public LoopDefinition Loop(int count, bool copy = false, bool shareScope = true)
{
var def = new LoopDefinition(count, copy, shareScope);
AddOutput(def);
return def;
}
///
public LoopDefinition Loop(Func condition, bool copy = false, bool shareScope = true)
{
var def = new LoopDefinition(condition, copy, shareScope);
AddOutput(def);
return def;
}
///
public LoopDefinition Loop(IPredicate condition, bool copy = false, bool shareScope = true)
{
ArgumentNullException.ThrowIfNull(condition);
var def = new LoopDefinition(condition, copy, shareScope);
AddOutput(def);
return def;
}
///
public LoopDefinition Loop(Func countFactory, bool copy = false, bool shareScope = true)
{
var def = new LoopDefinition(countFactory, copy, shareScope);
AddOutput(def);
return def;
}
///
public LoopDefinition Loop(string countExpression, bool copy = false, bool shareScope = true)
{
ArgumentException.ThrowIfNullOrWhiteSpace(countExpression);
var expression = new StringExpression(countExpression);
return Loop(exchange => expression.Evaluate(exchange), copy, shareScope);
}
// ── Bean / Service Activator ──────────────────────────────────────────────
///
public TSelf Bean(Func method)
{
ArgumentNullException.ThrowIfNull(method);
AddOutput(new BeanDefinition(
typeof(TService),
(svc, exchange, ct) => method((TService)svc, exchange, ct)));
return Self;
}
///
public TSelf Bean(Func method)
{
ArgumentNullException.ThrowIfNull(method);
AddOutput(new BeanDefinition(
typeof(TService),
(svc, exchange, _) => method((TService)svc, exchange)));
return Self;
}
///
public TSelf Bean(Action method)
{
ArgumentNullException.ThrowIfNull(method);
AddOutput(new BeanDefinition(
typeof(TService),
(svc, exchange, _) => { method((TService)svc, exchange); return Task.CompletedTask; }));
return Self;
}
///
public TSelf Bean(string reference, string? method = null)
=> To(Components.Bean.BeanComponent.UriFor(reference, method));
// ── Scatter-Gather ────────────────────────────────────────────────────────
///
public TSelf ScatterGather(
Func aggregationStrategy,
params string[] recipients)
{
ArgumentNullException.ThrowIfNull(aggregationStrategy);
if (recipients is null || recipients.Length == 0)
throw new ArgumentException("At least one recipient is required.", nameof(recipients));
var def = new ScatterGatherDefinition();
((IScatterGatherDefinition)def).Recipients(recipients);
((IScatterGatherDefinition)def).AggregationStrategy(aggregationStrategy);
AddOutput(def);
return Self;
}
///
public TSelf ScatterGather(Action configure)
{
ArgumentNullException.ThrowIfNull(configure);
var def = new ScatterGatherDefinition();
configure(def);
if (def.AggregationStrategy is null)
throw new InvalidOperationException("AggregationStrategy is required for ScatterGather.");
if (def.StaticRecipients is null && def.DynamicRecipients is null)
throw new InvalidOperationException("Recipients are required for ScatterGather.");
AddOutput(def);
return Self;
}
// ── Saga ──────────────────────────────────────────────────────────────────
///
public TSelf Saga(Action configure)
{
ArgumentNullException.ThrowIfNull(configure);
var def = new SagaDefinition();
configure(def);
if (def.Entries.Count == 0)
throw new InvalidOperationException("Saga must have at least one step.");
AddOutput(def);
return Self;
}
///
public SagaDefinition Saga()
{
var def = new SagaDefinition();
AddOutput(def);
return def;
}
// ── LoadBalance ───────────────────────────────────────────────────────────
///
public TSelf LoadBalance(ILoadBalancerStrategy strategy, params string[] uris)
{
ArgumentNullException.ThrowIfNull(strategy);
if (uris is null || uris.Length == 0)
throw new ArgumentException("At least one endpoint URI is required.", nameof(uris));
var def = new LoadBalancerDefinition();
((ILoadBalancerDefinition)def).Endpoints(uris);
((ILoadBalancerDefinition)def).Strategy(strategy);
AddOutput(def);
return Self;
}
///
public TSelf LoadBalance(Action configure)
{
ArgumentNullException.ThrowIfNull(configure);
var def = new LoadBalancerDefinition();
configure(def);
if (def.Strategy is null)
throw new InvalidOperationException(
"Strategy is required for LoadBalance. Use UseRoundRobin(), UseFailover(), etc.");
if (def.Endpoints is null || def.Endpoints.Length == 0)
throw new InvalidOperationException("At least one endpoint is required for LoadBalance.");
AddOutput(def);
return Self;
}
// ── Normalizer ────────────────────────────────────────────────────────────
///
public TSelf Normalize(Action configure)
{
ArgumentNullException.ThrowIfNull(configure);
var def = new NormalizerDefinition();
configure(def);
if (def.IsEmpty)
throw new InvalidOperationException("Normalizer requires at least one When clause.");
AddOutput(def);
return Self;
}
// ── Exception handling ────────────────────────────────────────────────────
///
public TSelf ExceptionHandled()
{
AddOutput(new ExceptionHandledDefinition());
return Self;
}
///
public TSelf RollbackAll()
{
AddOutput(new RollbackAllDefinition());
return Self;
}
///
public OnExceptionDefinition OnException() where TException : Exception
=> OnException(typeof(TException));
///
public OnExceptionDefinition OnException(params Type[] exceptionTypes)
{
if (exceptionTypes is null || exceptionTypes.Length == 0)
throw new ArgumentException("At least one exception type is required.", nameof(exceptionTypes));
foreach (var type in exceptionTypes)
{
if (!typeof(Exception).IsAssignableFrom(type))
throw new ArgumentException(
$"{type.Name} is not an Exception type.", nameof(exceptionTypes));
}
var def = new OnExceptionDefinition(exceptionTypes);
AddOutput(def);
return def;
}
// ── Route-level policy ────────────────────────────────────────────────────
///
public TSelf Cluster(bool value = true)
{
_cluster = value;
return Self;
}
///
public bool GetCluster() => _cluster;
///
public TSelf MessageHistory(bool value = true)
{
_messageHistory = value;
return Self;
}
///
public bool? GetMessageHistory() => _messageHistory;
///
public TSelf Tracing(bool value = true)
{
_tracing = value;
return Self;
}
///
public bool? GetTracing() => _tracing;
///
public TSelf RoutePolicy(IRoutePolicy policy)
{
_routePolicy = policy ?? throw new ArgumentNullException(nameof(policy));
return Self;
}
///
public TSelf RoutePolicy(string policyName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(policyName);
_routePolicyName = policyName.TrimStart('#');
return Self;
}
///
public IRoutePolicy? GetRoutePolicy() => _routePolicy;
///
public string? GetRoutePolicyName() => _routePolicyName;
///
public TSelf RouteConfigurationId(string ids)
{
ArgumentException.ThrowIfNullOrWhiteSpace(ids);
_routeConfigurationId = ids;
return Self;
}
///
public string? GetRouteConfigurationId() => _routeConfigurationId;
// ── Rich logging scope ────────────────────────────────────────────────────
///
public RichLogScopeDefinition Log() => Log(LogLevel.Information);
///
public RichLogScopeDefinition Log(LogLevel level)
{
var def = new RichLogScopeDefinition(level);
AddOutput(def);
return def;
}
///
/// The DSL truthiness rule, shared with every string-condition path through
/// .
///
private protected static bool ConvertToBoolean(object? value)
=> Predicates.RouteTruthiness.ToBoolean(value);
}