Path: redb-route/redb.Route/Core/RouteBuilder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Core/RouteBuilder.cs
----
using redb.Route.Abstractions;
using redb.Route.Definitions;
using redb.Route.Expressions;
namespace redb.Route.Core;
///
/// Abstract base class for defining routes using the new DSL.
/// Subclass and implement to define routes with the canonical
/// ProcessorDefinition model.
///
///
/// public class MyRoutes : RouteBuilder
/// {
/// protected override void Configure()
/// {
/// From("direct://input")
/// .SetBody("hello")
/// .To("direct://output");
///
/// From("timer://heartbeat?period=5000")
/// .Log("tick");
/// }
/// }
///
/// context.AddRoutes(new MyRoutes());
///
///
///
public abstract class RouteBuilder : IRouteBuilder
{
private readonly List _definitions = [];
private readonly List _exceptionDefinitions = [];
private readonly List _intercepts = [];
private readonly List _onCompletions = [];
private readonly List _routeConfigurations = [];
///
/// Route configurations declared on this builder (, a
/// <routeConfiguration> of a markup file) — unlike the builder's own handlers they apply to the routes
/// of every builder of the context.
///
public IReadOnlyList RouteConfigurations => _routeConfigurations;
///
/// Starts a route configuration (Apache Camel's Route Configuration): error handling for the routes of every
/// builder of the context, not only of this one. Without an it is the default one: it
/// applies to every route that has no configurations assigned. With an id it applies to the routes that name it
/// with .RouteConfigurationId("id"); an id is unique within a context. A class that holds nothing but
/// configurations reads best as a .
///
/// The id of the configuration, or null for the default one.
protected RouteConfigurationDefinition RouteConfiguration(string? id = null) => AddRouteConfiguration(id);
/// Declares a route configuration on this builder from outside it (the markup loader).
internal RouteConfigurationDefinition AddRouteConfiguration(string? id)
{
var configuration = new RouteConfigurationDefinition(id);
_routeConfigurations.Add(configuration);
return configuration;
}
/// What the builder is called in a log line: its type, or the document a markup builder was loaded from.
internal virtual string SourceName => GetType().Name;
/// Gets the route definitions created during .
public IReadOnlyList Definitions => _definitions;
/// Exception handlers declared on this builder via — they apply to every route it defines, and to no route of another builder.
public IReadOnlyList ExceptionDefinitions => _exceptionDefinitions;
/// Intercepts declared on this builder — they apply to every route it defines, and to no route of another builder.
public IReadOnlyList Intercepts => _intercepts;
/// OnCompletion blocks declared on this builder — they apply to every route it defines, and to no route of another builder.
public IReadOnlyList OnCompletions => _onCompletions;
/// Steps that run before every step of every route in this builder (Camel intercept()).
public InterceptDefinition Intercept() => Register(new InterceptDefinition(InterceptKind.EveryStep, null));
/// Steps that run when a message enters any route of this builder whose From matches the mask (all routes when null).
public InterceptDefinition InterceptFrom(string? uriPattern = null) => Register(new InterceptDefinition(InterceptKind.From, uriPattern));
/// Steps that run before any To / ToD in this builder whose target matches the mask; .SkipSendToOriginalEndpoint() replaces the send.
public InterceptDefinition InterceptSendToEndpoint(string uriPattern) => Register(new InterceptDefinition(InterceptKind.SendToEndpoint, uriPattern));
/// Steps that run after any route of this builder finished with an exchange (on a copy, outside the route's transaction).
public OnCompletionDefinition OnCompletion()
{
var def = new OnCompletionDefinition();
_onCompletions.Add(def);
return def;
}
private InterceptDefinition Register(InterceptDefinition def)
{
_intercepts.Add(def);
return def;
}
///
/// Override this method to define routes using .
///
protected abstract void Configure();
///
/// Starts a new route definition with the given source endpoint. Public so that DSL layers built
/// on top of routes (the REST DSL, generators) can add routes to a builder from outside
/// ; inside a subclass it reads as before.
///
/// Source endpoint URI (e.g., "direct://input", "timer://ping?period=1000").
/// The new route definition for fluent chaining.
public IRouteDefinition From(string uri)
{
var def = new RouteDefinition();
def._context = Context;
def.From(uri);
_definitions.Add(def);
return def;
}
///
/// Defines an exception handler for all routes of this builder (Apache Camel's RouteBuilder scope) — not for
/// the routes of another builder of the same context; for those, see . Between
/// this handler and a route's own the one whose exception type is nearest to the failure wins, the route's own
/// on a tie.
///
///
/// OnException<IOException>()
/// .MaximumRedeliveries(3)
/// .Handled()
/// .Log("IO error: ${exception.message}");
///
///
///
/// Exception type to handle.
/// Definition for fluent chaining of handler steps and configuration.
public OnExceptionDefinition OnException() where TException : Exception
{
var def = new OnExceptionDefinition(new[] { typeof(TException) });
_exceptionDefinitions.Add(def);
return def;
}
///
/// Defines an exception handler for multiple exception types at once, for all routes of this builder.
///
/// Exception types to handle.
/// Definition for fluent chaining.
public OnExceptionDefinition OnException(params Type[] exceptionTypes)
{
if (exceptionTypes is not { Length: > 0 })
throw new ArgumentException("At least one exception type must be specified.", nameof(exceptionTypes));
foreach (var t in exceptionTypes)
if (!typeof(Exception).IsAssignableFrom(t))
throw new ArgumentException($"Type '{t.Name}' is not an Exception type.", nameof(exceptionTypes));
var def = new OnExceptionDefinition(exceptionTypes);
_exceptionDefinitions.Add(def);
return def;
}
/// Gets the route context, available inside after registration.
protected IRouteContext? Context { get; private set; }
///
/// Called by to populate by running .
///
internal void InternalBuild(IRouteContext? context = null)
{
_definitions.Clear();
_exceptionDefinitions.Clear();
_intercepts.Clear();
_onCompletions.Clear();
_routeConfigurations.Clear();
Context = context;
Configure();
IsBuilt = true;
}
/// Whether has run at least once (AdviceWith builds early; a builder added later has not been built yet).
internal bool IsBuilt { get; private set; }
///
void IRouteBuilder.Configure(IRouteContext context) => InternalBuild(context);
// ── Expression DSL helpers ──────────────────────────────────────────────
/// Creates a JsonPath expression for extracting data from the message body.
/// JsonPath expression (e.g., "$.store.books[0].title").
protected static JsonPathExpression JPath(string path) => new(path);
/// Creates a typed JsonPath expression that converts the result to .
protected static TypedJsonPathExpression JPath(string path) => new(path);
///
/// Java-style alias.
protected static JsonPathExpression jpath(string path) => new(path);
///
/// Java-style alias.
protected static TypedJsonPathExpression jpath(string path) => new(path);
/// Creates an XPath expression for extracting data from an XML message body.
/// XPath 1.0 expression.
///
/// In a condition the result is a node-set, so the expression asks whether the path matched
/// rather than what the matched node says. Use or
/// to ask the other question.
///
protected static XPathExpression XPath(string path) => new(path);
/// Creates an XPath expression with an explicit XPath-level result type.
/// XPath 1.0 expression.
/// The XPath-level type of the result: node-set, node, string, number or boolean.
protected static XPathExpression XPath(string path, XPathResult result) => new(path, result);
/// Creates a typed XPath expression that converts the result to .
protected static TypedXPathExpression XPath(string path) => new(path);
///
/// Java-style alias.
protected static XPathExpression xpath(string path) => new(path);
///
/// Java-style alias.
protected static XPathExpression xpath(string path, XPathResult result) => new(path, result);
///
/// Java-style alias.
protected static TypedXPathExpression xpath(string path) => new(path);
/// Creates an expression that reads the exchange message body.
protected static BodyExpression Body() => new();
/// Creates an expression that reads a message header value.
/// Header name.
protected static HeaderExpression Header(string name) => new(name);
/// Creates an expression that reads an exchange property value.
/// Property name.
protected static PropertyExpression Property(string name) => new(name);
/// Creates a constant expression that always returns the specified value.
/// The constant value.
protected static ConstantExpression Constant(object value) => new(value);
/// Creates an expression evaluated from the exchange using a delegate.
/// Function that accepts an and returns a value.
protected static ExchangeExpression Exchange(Func func) => new(func);
///
/// Creates a string expression that evaluates a ${...} template or raw expression.
/// .SetBody(Expr("${header.source}"))
///
/// Expression string with ${...} placeholders or raw expression.
///
/// A ${...} template (or any expression text) as an :
/// SetBody(Expr("Hello ${header.name}")). Public and static, so it also reads well from the
/// lambda style, where a protected member of the builder would be out of reach:
/// ctx.AddRoutes(b => b.From("...").SetBody(RouteBuilder.Expr("${header.x}"))).
/// Equivalent to new StringExpression(template).
///
public static StringExpression Expr(string template) => new(template);
///
/// Apache Camel's method(ref, "name"): a registry bean's method as an expression or a condition, for
/// Filter, When, Validate, SetBody, Split and every other expression slot.
/// .Filter(Method("#loyalty", "IsGold(${header.name})")) is the typed form of
/// ${bean:loyalty.IsGold(header.name)}: the same bean, binding and resolution. In a condition a method may
/// return Task<bool>, which the engine awaits; in a value position the call is synchronous.
///
/// The registry name, #name or name.
///
/// The method in the bean: URI spelling: Name, or Name(arg, ...) with route-language arguments
/// (IsGold(${header.name}), Gross(${header.qty}, 2.5)).
///
public static IPredicateExpression Method(string reference, string methodSpec) => new BeanMethodExpression(reference, methodSpec);
///
/// A value from configuration: {{key}} / {{key:default}} resolved through the route context, as in an
/// endpoint URI: SetHeader("redbLdap.AuthDn", Placeholder("{{ldap.user}}")). Equivalent to
/// new PlaceholderExpression(text); what value="{{key}}" of a markup step becomes.
///
public static PlaceholderExpression Placeholder(string text) => new(text);
// ── Streaming tokenizer helpers ─────────────────────────────────────────
/// Creates a splitter function that splits the body into lines.
/// Line separator (default: newline).
/// Whether to skip empty/whitespace lines.
protected static Func> SplitLines(
string separator = "\n", bool skipEmpty = false) =>
exchange => Expressions.Tokenizers.LineTokenizer.Tokenize(exchange.In.Body, separator, skipEmpty);
/// Creates a splitter function that extracts XML elements by local name.
/// Local name of elements to extract.
/// Optional parent element whose namespaces should be injected.
protected static Func> SplitXml(
string elementName, string? inheritNamespaceFrom = null) =>
exchange => Expressions.Tokenizers.XmlTokenizer.Tokenize(exchange.In.Body, elementName, inheritNamespaceFrom);
/// Creates a splitter function that splits a JSON array body into individual elements.
protected static Func> SplitJsonArray() =>
exchange => Expressions.Tokenizers.JsonArrayTokenizer.Tokenize(exchange.In.Body);
}
///
/// Route builder that accepts an inline configure action, for use with
/// .
///
public sealed class InlineRouteBuilder : RouteBuilder
{
private readonly Action _configure;
/// Creates an inline route builder.
public InlineRouteBuilder(Action configure)
{
_configure = configure ?? throw new ArgumentNullException(nameof(configure));
}
///
protected override void Configure() => _configure(this);
}