Bundle: redb-route / redb.Route.Xml (redb.Route.Xml.txt), 30 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.Xml/BeanFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/BeanFactory.cs
----
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Core;
namespace redb.Route.Xml;
///
/// A <list> on its way to a target: the items are raw bean values, the element type
/// is the one of= named (null when the target supplies it).
///
internal sealed record BeanListValue(Type? ElementType, IReadOnlyList Items);
///
/// Builds bean instances from raw values — the one place both the <bean> section
/// and generated code ( ) go through, so a list, a reference or a text
/// value binds the same way in either. A raw value is a (converted to the
/// target type after placeholder resolution), a (built into the
/// target's collection shape), or an object (assigned as it is, when the target accepts it).
/// Every failure is an naming the slot.
///
internal static class BeanFactory
{
/// The collection shapes a list builds into, for the messages.
internal const string ListShapes =
"T[], List, IList, ICollection, IReadOnlyList, IReadOnlyCollection, IEnumerable";
///
/// Creates the instance: through (a public static creator whose
/// parameters type the arguments), through the constructor the argument types name, or through a
/// constructor chosen by , which needs the arguments already
/// built — a list there must name its element type with of= .
///
internal static object Instantiate(
Type type, IReadOnlyList args, IReadOnlyList? argumentTypes, string? factoryMethod,
IServiceProvider provider, Func resolve)
{
if (factoryMethod is not null)
{
var method = FactoryMethod(type, factoryMethod, args.Count, argumentTypes);
return Invoke(method, args, $"{factoryMethod} argument", resolve)
?? throw new InvalidOperationException($"'{type.FullName}.{factoryMethod}' returned null.");
}
if (argumentTypes is not null)
{
// The signature is named: exactly that public constructor, each value bound to its
// parameter's type — no guessing among overloads, no DI-supplied parameters.
return Invoke(Constructor(type, args.Count, argumentTypes), args, "constructorArg", resolve)!;
}
// A module's bean asks for services closed over its own types (ILogger): they never reach the host's
// container, which would keep them, and with them the module's load context, for good.
var services = CollectibleTypeServiceProvider.For(provider);
if (args.Count == 0)
return ActivatorUtilities.CreateInstance(services, type);
var built = new object[args.Count];
for (var i = 0; i < args.Count; i++)
built[i] = Materialize(args[i], $"constructorArg {i + 1}", resolve);
return ActivatorUtilities.CreateInstance(services, type, built);
}
///
/// The static creator the arguments call, the way C# resolves a call: the parameters after the
/// given arguments must all be optional (their defaults are used). With argument types the
/// given parameters must be exactly those types; without them every overload a markup value can
/// reach counts, and more than one is refused — picking one would be a guess.
///
internal static MethodInfo FactoryMethod(Type type, string name, int argumentCount, IReadOnlyList? argumentTypes)
=> (MethodInfo)Choose(type, type.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m => m.Name == name),
argumentCount, argumentTypes, $"public static method '{name}'", $"public static methods '{name}'");
/// The public constructor the named argument types call — the same rule as .
internal static ConstructorInfo Constructor(Type type, int argumentCount, IReadOnlyList argumentTypes)
=> (ConstructorInfo)Choose(type, type.GetConstructors(), argumentCount, argumentTypes,
"public constructor", "public constructors");
private static MethodBase Choose(Type type, IEnumerable members, int count, IReadOnlyList? types,
string one, string many)
{
var candidates = members.Where(m => Accepts(m.GetParameters(), count, types)).ToList();
return candidates.Count switch
{
1 => candidates[0],
0 => throw new InvalidOperationException(types is null
? $"type '{type.FullName}' has no {one} taking {count} argument(s)."
: $"type '{type.FullName}' has no {one} ({Signature(types)})."),
_ => throw new InvalidOperationException(
$"type '{type.FullName}' has {candidates.Count} {many} taking {count} argument(s) " +
$"({string.Join("; ", candidates.Select(m => Signature([.. m.GetParameters().Select(p => p.ParameterType)])))}) — " +
(types is null
? "name the parameter types with ."
: "they differ only in optional parameters, so the call is ambiguous even with the types named.")),
};
}
///
/// Whether a member takes arguments: that many leading parameters, the
/// rest optional. Named types must match exactly; otherwise a parameter no markup value can
/// ever be (a by-ref-like type such as ReadOnlySpan<char> , a ref ) rules the
/// overload out — reflection cannot pass one, so it is not a candidate to be ambiguous with.
///
private static bool Accepts(ParameterInfo[] parameters, int count, IReadOnlyList? types)
{
if (parameters.Length < count || parameters.Skip(count).Any(p => !p.IsOptional))
return false;
var given = parameters.Take(count).Select(p => p.ParameterType).ToList();
return types is null
? given.All(t => !t.IsByRefLike && !t.IsByRef)
: given.SequenceEqual(types);
}
/// Binds the given arguments to their parameters, fills the optional rest with defaults, calls.
private static object? Invoke(MethodBase member, IReadOnlyList args, string label, Func resolve)
{
var parameters = member.GetParameters();
var bound = new object?[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
bound[i] = i < args.Count
? Bind(args[i], parameters[i].ParameterType, $"{label} {i + 1}", resolve)
: DefaultOf(parameters[i]);
return member is ConstructorInfo constructor ? constructor.Invoke(bound) : member.Invoke(null, bound);
}
///
/// An optional parameter's default as the call needs it. Reflection reports an enum default as
/// its underlying number (X509KeyStorageFlags.DefaultKeySet reads as 0), so it is converted back.
///
private static object? DefaultOf(ParameterInfo parameter)
{
var type = Nullable.GetUnderlyingType(parameter.ParameterType) ?? parameter.ParameterType;
if (!parameter.HasDefaultValue)
return parameter.ParameterType.IsValueType ? Activator.CreateInstance(parameter.ParameterType) : null;
return parameter.DefaultValue is { } value && type.IsEnum && !type.IsInstanceOfType(value)
? Enum.ToObject(type, value)
: parameter.DefaultValue;
}
internal static string Signature(IReadOnlyList types) => string.Join(", ", types.Select(t => t.FullName ?? t.Name));
/// Binds a raw value to a writable public property of the instance.
internal static void Assign(object instance, string key, object? raw, Func resolve)
{
var type = instance.GetType();
var property = type.GetProperty(key);
if (property is not { CanWrite: true })
throw new InvalidOperationException($"type '{type.FullName}' has no writable public property '{key}'.");
property.SetValue(instance, Bind(raw, property.PropertyType, key, resolve));
}
/// The element type a list builds for , or null when it is not a list shape.
internal static Type? ElementTypeOf(Type target)
{
if (target.IsArray)
return target.GetArrayRank() == 1 ? target.GetElementType() : null;
if (!target.IsGenericType)
return null;
var definition = target.GetGenericTypeDefinition();
return definition == typeof(List<>)
|| definition == typeof(IList<>)
|| definition == typeof(ICollection<>)
|| definition == typeof(IReadOnlyList<>)
|| definition == typeof(IReadOnlyCollection<>)
|| definition == typeof(IEnumerable<>)
? target.GetGenericArguments()[0]
: null;
}
///
/// Converts a raw value for a target of a known type: text through the shared option converter,
/// a list into the target's collection shape, an object when the target accepts it.
///
internal static object? Bind(object? raw, Type target, string slot, Func resolve)
{
switch (raw)
{
case string text:
{
var resolved = resolve(text);
return OptionValueConverter.Convert(resolved, target)
?? throw new InvalidOperationException($"'{resolved}' is not convertible to {target.Name} for '{slot}'.");
}
case BeanListValue list:
{
var element = ElementTypeOf(target)
?? throw new InvalidOperationException(NotAListShape(target, slot));
if (list.ElementType is not null && list.ElementType != element)
throw new InvalidOperationException(ElementTypeDiffers(list.ElementType, element, slot));
return Build(target, element, list, slot, resolve);
}
case null:
throw new InvalidOperationException($"'{slot}' got no value.");
default:
if (!target.IsInstanceOfType(raw))
throw new InvalidOperationException(NotAssignable(raw.GetType(), target, slot));
return raw;
}
}
///
/// A constructor argument before the constructor is chosen: text stays text (after
/// placeholders), an object stays itself, a list builds as T[] of its of= type
/// — an array passes wherever a constructor takes T[], IEnumerable<T> or IReadOnlyList<T>.
///
private static object Materialize(object? raw, string slot, Func resolve) => raw switch
{
string text => resolve(text),
BeanListValue { ElementType: { } element } list => Build(element.MakeArrayType(), element, list, slot, resolve),
BeanListValue => throw new InvalidOperationException(ConstructorListNeedsOf(slot)),
null => throw new InvalidOperationException($"'{slot}' got no value."),
_ => raw,
};
// The same mistakes found before load: the package gate reports them in these words.
internal static string NotAListShape(Type target, string slot)
=> $"'{slot}' is {target.Name}, which a does not build into (valid: {ListShapes}).";
internal static string ElementTypeDiffers(Type named, Type element, string slot)
=> $" differs from the element type {element.FullName} of '{slot}'.";
internal static string NotAssignable(Type actual, Type target, string slot)
=> $"'{actual.FullName}' is not assignable to {target.Name} for '{slot}'.";
internal static string ConstructorListNeedsOf(string slot)
=> $"'{slot}': a passed to a constructor names its element type with of= — the constructor is not chosen yet, so nothing else types it.";
private static object Build(Type target, Type element, BeanListValue list, string slot, Func resolve)
{
var items = Array.CreateInstance(element, list.Items.Count);
for (var i = 0; i < list.Items.Count; i++)
items.SetValue(Bind(list.Items[i], element, $"{slot}[{i}]", resolve), i);
if (target.IsArray)
return items;
// Every interface shape and List itself take a List: it is the one that also
// honours IList/ICollection writes, which an array refuses.
return Activator.CreateInstance(typeof(List<>).MakeGenericType(element), items)!;
}
}
Path: redb-route/redb.Route.Xml/BeanModel.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/BeanModel.cs
----
using System.Xml.Linq;
namespace redb.Route.Xml;
///
/// The parsed form of a <bean> declaration: one grammar for the loader, the C#
/// generator and the package gate, so none of them re-reads the markup by its own rules.
///
internal sealed record BeanDeclaration(
string? Name,
string TypeName,
string? FactoryMethod,
IReadOnlyList ConstructorArgs,
IReadOnlyList Properties,
XElement At)
{
///
/// Whether the arguments name their parameter types — then the constructor or factory method
/// is the one with exactly that signature. All arguments do or none do (the parser enforces it).
///
public bool TypedArguments => ConstructorArgs.Count > 0 && ConstructorArgs[0].TypeName is not null;
}
///
/// One <constructorArg> : its value and, when written, the parameter type it binds to
/// (type="System.String" , Spring's constructor-arg type ) — how a constructor or a
/// factory method is chosen among overloads the values alone do not tell apart.
///
internal sealed record BeanArgument(BeanValue Value, string? TypeName);
/// One <property key=…> of a bean with its parsed value.
internal sealed record BeanProperty(string Key, BeanValue Value, XElement At);
/// A value slot of a bean: a property, a constructor argument or a list item.
internal abstract record BeanValue(XElement At);
/// A literal text, {{key}} placeholders included; converted to the target type.
internal sealed record ScalarBeanValue(string Text, XElement At) : BeanValue(At);
/// A registered bean, by name: ref="name" or <ref bean="name"/> .
internal sealed record RefBeanValue(string Bean, XElement At) : BeanValue(At);
/// A nested anonymous bean, built in place and never registered.
internal sealed record NestedBeanValue(BeanDeclaration Bean) : BeanValue(Bean.At);
///
/// A <list> : its items build into the target's collection shape. of= names
/// the element type where the target does not (a constructor argument).
///
internal sealed record ListBeanValue(string? ElementTypeName, IReadOnlyList Items, XElement At) : BeanValue(At);
///
/// The <bean> grammar. A slot (<property> , <constructorArg> )
/// holds exactly one of: value= , ref= , a nested <bean> , a
/// <list> . A list item is exactly one of: <value>text</value> ,
/// <ref bean=…/> , <bean> , <list> . Every violation is
/// reported at its element; the parse returns null when anything was reported.
///
internal static class BeanModel
{
private const string SlotShape =
"takes exactly one of: value=, ref=, one nested anonymous , one ";
/// Parses a declaration; receives every problem with its element.
internal static BeanDeclaration? Parse(XElement bean, Action error)
{
var failed = false;
void Fail(XElement at, string message)
{
failed = true;
error(at, message);
}
var declaration = ParseBean(bean, Fail);
return failed ? null : declaration;
}
/// Every ref of a declaration, nested beans and lists included, in document order.
internal static IEnumerable References(BeanDeclaration bean)
=> bean.ConstructorArgs.Select(a => a.Value).Concat(bean.Properties.Select(p => p.Value)).SelectMany(References);
/// Every nested anonymous bean of a declaration, at any depth.
internal static IEnumerable NestedBeans(BeanDeclaration bean)
=> bean.ConstructorArgs.Select(a => a.Value).Concat(bean.Properties.Select(p => p.Value)).SelectMany(NestedBeans);
private static IEnumerable References(BeanValue value) => value switch
{
RefBeanValue reference => [reference],
NestedBeanValue nested => References(nested.Bean),
ListBeanValue list => list.Items.SelectMany(References),
_ => [],
};
private static IEnumerable NestedBeans(BeanValue value) => value switch
{
NestedBeanValue nested => NestedBeans(nested.Bean).Prepend(nested.Bean),
ListBeanValue list => list.Items.SelectMany(NestedBeans),
_ => [],
};
private static BeanDeclaration ParseBean(XElement bean, Action fail)
{
var typeName = bean.Attribute("type")?.Value;
if (string.IsNullOrWhiteSpace(typeName))
fail(bean, " requires the 'type' attribute.");
var args = new List();
var properties = new List();
foreach (var child in bean.Elements())
{
switch (child.Name.LocalName)
{
case "constructorArg":
var argType = child.Attribute("type")?.Value;
if (argType is not null && string.IsNullOrWhiteSpace(argType))
{
fail(child, " names no type.");
break;
}
if (ParseSlot(child, fail) is { } arg)
args.Add(new BeanArgument(arg, argType));
break;
case "property":
var key = child.Attribute("key")?.Value;
if (string.IsNullOrWhiteSpace(key))
{
fail(child, " requires the 'key' attribute.");
break;
}
if (ParseSlot(child, fail) is { } value)
properties.Add(new BeanProperty(key, value, child));
break;
default:
fail(child, $" does not take <{child.Name.LocalName}> (valid: , ).");
break;
}
}
// One contract per bean: the signature is named in full or chosen from the values alone.
if (args.Count > 0 && args.Any(a => a.TypeName is null) && args.Any(a => a.TypeName is not null))
fail(bean, " is written on some arguments only — name every parameter type, or none.");
return new BeanDeclaration(
bean.Attribute("name")?.Value, typeName ?? "", bean.Attribute("factoryMethod")?.Value is { Length: > 0 } factory ? factory : null,
args, properties, bean);
}
private static BeanValue? ParseSlot(XElement slot, Action fail)
{
var value = slot.Attribute("value");
var reference = slot.Attribute("ref");
var children = slot.Elements().ToList();
var forms = (value is null ? 0 : 1) + (reference is null ? 0 : 1) + children.Count;
if (forms != 1)
{
fail(slot, $"<{slot.Name.LocalName}> {SlotShape}.");
return null;
}
if (value is not null)
return new ScalarBeanValue(value.Value, slot);
if (reference is not null)
return ParseReference(reference.Value, slot, fail);
return children[0].Name.LocalName switch
{
"bean" => ParseNested(children[0], fail),
"list" => ParseList(children[0], fail),
_ => Refuse(children[0], $"<{slot.Name.LocalName}> {SlotShape}; <{children[0].Name.LocalName}> belongs inside a .", fail),
};
}
private static BeanValue? ParseItem(XElement item, Action fail)
{
switch (item.Name.LocalName)
{
case "value":
if (item.HasElements)
return Refuse(item, " holds text only.", fail);
return new ScalarBeanValue(item.Value, item);
case "ref":
return item.Attribute("bean")?.Value is { } name
? ParseReference(name, item, fail)
: Refuse(item, "[ requires the 'bean' attribute.", fail);
case "bean":
return ParseNested(item, fail);
case "list":
return ParseList(item, fail);
default:
return Refuse(item, $"] does not take <{item.Name.LocalName}> (valid: , [, ], ).", fail);
}
}
private static BeanValue? ParseNested(XElement bean, Action fail)
{
if (bean.Attribute("name") is not null)
return Refuse(bean, "a nested is anonymous — drop name=, or declare it at the top level and use ref=.", fail);
return new NestedBeanValue(ParseBean(bean, fail));
}
private static BeanValue ParseList(XElement list, Action fail)
{
var items = new List();
foreach (var item in list.Elements())
{
if (ParseItem(item, fail) is { } parsed)
items.Add(parsed);
}
return new ListBeanValue(list.Attribute("of")?.Value is { Length: > 0 } of ? of : null, items, list);
}
private static BeanValue? ParseReference(string name, XElement at, Action fail)
{
// One spelling: the attribute already says it is a reference, so the URI form '#name'
// is not repeated here.
if (name.Length == 0)
return Refuse(at, "a bean reference needs a name.", fail);
if (name.StartsWith('#'))
return Refuse(at, $"a bean reference is the bare name: '{name[1..]}', not '{name}'.", fail);
return new RefBeanValue(name, at);
}
private static BeanValue? Refuse(XElement at, string message, Action fail)
{
fail(at, message);
return null;
}
}
Path: redb-route/redb.Route.Xml/ComponentCatalog.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/ComponentCatalog.cs
----
using System.Globalization;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Xml;
/// One endpoint option in the catalog: name, kind, default, secrecy, enum hints, the side that reads it.
/// The option's property name (PascalCase; the URI and the markup take it case-insensitively).
/// The value kind: bool, int, long, double, duration, enum (one member), flags (members joined by commas) or string.
/// The default rendered invariantly, or null when unknown.
/// A secret ([Sensitive] ): redacted wherever the URI is shown.
/// The member names of an enum option, else null.
/// The only side of the endpoint that reads the option ( ):
/// a producer-only option on a <from> is refused, and the other way round. Null — both sides read it.
/// The connection factory sets it ([ConnectionParameter] ): beside the option that names
/// the factory it is refused, the factory being the whole connection.
/// This option names the connection factory ([ConnectionFactoryReference] ).
public sealed record CatalogOption(
string Name,
string Type,
string? Default,
bool Sensitive,
IReadOnlyList? EnumValues,
EndpointRole? Role,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool ConnectionParameter,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool ConnectionFactoryReference)
{
///
/// Set when the option names a registry object ([RegistryReference] , [ConnectionFactoryReference] ):
/// the type that object must have as Full.Name, Assembly , or object when the option does not say.
/// Null for every other option, and then not written.
///
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Reference { get; init; }
}
/// One component in the catalog — everything the editor's property panel shows.
/// The URI scheme and the structured-form element name.
/// Other schemes the component answers to.
/// The assembly the component lives in.
/// The full name of its options class, or null when it has none.
/// The attribute the structured form accepts for the path (kafka: topic), or null.
/// The path is the element's text content (the SQL-style connectors).
/// Its options, by name.
/// The connector takes parameters it has no option for ( ):
/// false = an unknown name is refused when the endpoint is created, so the schema and the package gate refuse it too.
public sealed record CatalogComponent(
string Scheme,
IReadOnlyList AlternateSchemes,
string? Package,
string? OptionsType,
string? PathSynonym,
bool PathIsText,
IReadOnlyList Options,
bool Lenient)
{
///
/// The only side the component has ([EndpointRole] on its class, Apache Camel's producerOnly /
/// consumerOnly ); null, and then not written, when it has both. The editor schema leaves the missing
/// side out, so the scheme is not offered there.
///
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public EndpointRole? Role { get; init; }
/// The component's hint for the missing side, so that check refuses in the runtime's words.
[JsonIgnore]
internal string? RoleHint { get; init; }
}
///
/// The component catalog: built by REFLECTION from what already exists — the
/// component's , its one-line §7.2 metadata, and its
/// subclass (found in the component's assembly by naming, else
/// as the single candidate). Nothing here is hand-kept per connector: a new component with
/// Options and Scheme appears in the catalog, the structured form and the generated XSD with
/// zero XML-specific code — the anti-copy-paste rule by construction.
///
public static class ComponentCatalog
{
/// Builds catalog records for the given components, ordered by scheme.
public static IReadOnlyList Build(IEnumerable components)
{
ArgumentNullException.ThrowIfNull(components);
var records = new List();
foreach (var component in components.GroupBy(c => c.Scheme).Select(g => g.First()))
{
var type = component.GetType();
var optionsType = FindOptionsType(type);
records.Add(new CatalogComponent(
component.Scheme,
[.. component.AlternateSchemes],
type.Assembly.GetName().Name,
optionsType?.FullName,
(component as ComponentBase)?.StructuredPathSynonym,
(component as ComponentBase)?.PathIsText ?? false,
optionsType is null ? [] : HarvestOptions(optionsType),
// No options class: nothing binds the parameters, so nothing refuses them either.
optionsType is null || EndpointOptions.IsLenient(optionsType))
{
Role = EndpointSides.Declaration(type)?.Role,
RoleHint = EndpointSides.Declaration(type)?.Hint,
});
}
return [.. records.OrderBy(r => r.Scheme, StringComparer.Ordinal)];
}
/// The catalog as pretty JSON — the file the editor tooling reads.
public static string ToJson(IReadOnlyList catalog)
=> JsonSerializer.Serialize(catalog, JsonOptions);
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
};
///
/// The component's options class: by naming (XComponent → XEndpointOptions /
/// XOptions ) in the component's assembly, else the assembly's single
/// subclass, else none (an options-less component is honest).
///
/// The TOptions of an endpoint type deriving from EndpointBase<TOptions> , or null.
private static Type? DeclaredOptions(Type endpointType)
{
for (var type = endpointType; type is not null && type != typeof(object); type = type.BaseType)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(EndpointBase<>))
return type.GetGenericArguments()[0];
}
return null;
}
private static Type? FindOptionsType(Type componentType)
{
var candidates = componentType.Assembly.GetTypes()
.Where(t => !t.IsAbstract && typeof(EndpointOptions).IsAssignableFrom(t))
.ToList();
if (candidates.Count == 0)
return null;
// The naming walk climbs the BASE chain too: HttpsComponent : HttpComponent finds
// HttpEndpointOptions — a derived component inherits its base's options.
for (var type = componentType; type is not null && type != typeof(object); type = type.BaseType)
{
var stem = type.Name.EndsWith("Component", StringComparison.Ordinal)
? type.Name[..^"Component".Length]
: type.Name;
// The endpoint the component creates declares its options as a type argument
// (ImapEndpoint : EndpointBase) — the code says it, no name to
// match. Three mail components share one options class, which naming never found.
if (componentType.Assembly.GetType($"{type.Namespace}.{stem}Endpoint") is { } endpoint
&& DeclaredOptions(endpoint) is { } declared)
return declared;
var byName = candidates.FirstOrDefault(t => t.Name == stem + "EndpointOptions")
?? candidates.FirstOrDefault(t => t.Name == stem + "Options");
if (byName is not null)
return byName;
}
// The single-candidate fallback is safe only in a single-component assembly —
// otherwise a neighbour's options would silently attach to the wrong scheme.
var componentCount = componentType.Assembly.GetTypes()
.Count(t => !t.IsAbstract && typeof(IComponent).IsAssignableFrom(t));
return candidates.Count == 1 && componentCount == 1 ? candidates[0] : null;
}
private static IReadOnlyList HarvestOptions(Type optionsType)
{
object? defaults;
try
{
defaults = Activator.CreateInstance(optionsType);
}
catch (Exception ex) when (ex is MissingMethodException or MemberAccessException or TargetInvocationException)
{
defaults = null; // no parameterless constructor — defaults stay unknown
}
// The options as a URI writes them (EndpointOptions.BindableOptions): a member of an option group is listed as
// Group.Member (its value member as Group), with the group's role and the member's own type, default and marks.
var options = new List();
var groupDefaults = new Dictionary();
foreach (var (name, property, group) in EndpointOptions.BindableOptions(optionsType))
{
// Only what the connector declares: the EndpointOptions base carries machinery
// (UnmappedParameters, …), not options.
if (property.DeclaringType == typeof(EndpointOptions))
continue;
object? owner = defaults;
if (group is not null && !groupDefaults.TryGetValue(group, out owner))
groupDefaults[group] = owner = defaults is null ? null : Activator.CreateInstance(group.PropertyType);
var underlying = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
options.Add(new CatalogOption(
name,
TypeLabel(underlying),
Render(owner is null ? null : property.GetValue(owner)),
property.GetCustomAttribute() is not null,
underlying.IsEnum ? Enum.GetNames(underlying) : null,
EndpointOptions.RoleOf(group ?? property),
property.IsDefined(typeof(ConnectionParameterAttribute), inherit: true),
property.IsDefined(typeof(ConnectionFactoryReferenceAttribute), inherit: true))
{
Reference = ReferenceOf(property),
});
}
return [.. options.OrderBy(o => o.Name, StringComparer.Ordinal)];
}
///
/// The catalog's of an option: the expected type of its
/// as Full.Name, Assembly , object when the mark gives none, or
/// null for an option that names no registry object.
///
internal static string? ReferenceOf(PropertyInfo option)
=> option.GetCustomAttribute(inherit: true) is not { } mark
? null
: mark.Expected is { } type ? ReferenceName(type) : "object";
/// A type as writes it: Full.Name, Assembly .
internal static string ReferenceName(Type type) => $"{type.FullName}, {type.Assembly.GetName().Name}";
private static string TypeLabel(Type type)
{
// A [Flags] enum takes several members at once ("Tls12,Tls13"), so it is not a pick-one list.
if (type.IsEnum) return type.IsDefined(typeof(FlagsAttribute), inherit: false) ? "flags" : "enum";
if (type == typeof(bool)) return "bool";
if (type == typeof(int)) return "int";
if (type == typeof(long)) return "long";
if (type == typeof(double) || type == typeof(float) || type == typeof(decimal)) return "double";
if (type == typeof(TimeSpan)) return "duration";
return "string";
}
private static string? Render(object? value) => value switch
{
null => null,
bool flag => flag ? "true" : "false",
Enum member => member.ToString(),
TimeSpan span => span.ToString("c", CultureInfo.InvariantCulture),
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
string text => text,
_ => null,
};
}
Path: redb-route/redb.Route.Xml/Contracts.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/Contracts.cs
----
using System.Xml.Linq;
using redb.Route.Abstractions;
namespace redb.Route.Xml;
///
/// What kind of element a contribution declares. The kind is metadata for the schema and the
/// catalog and for the editor; dispatch itself is uniform — every contribution gets full
/// control of its element through and the traversal
/// helpers on .
///
public enum XmlElementKind
{
/// A leaf step (<to> , <setHeader> ).
Step,
/// A scope whose children are steps (<filter> , <split> ).
Scope,
/// A node whose children are branches, not steps (<choice> ).
Branching,
/// A node whose children configure it rather than being steps (rich <log> ).
ConfigChild,
/// An element that lives beside <route> (<rest> , future).
TopLevel,
///
/// An element that lives inside <context> beside <components> /
/// <bean> /<onInit> (the redb bridge above all). Never a step.
///
ContextLevel,
}
/// The value kind of one XML attribute — what the schema and the editor say about it.
public enum AttributeType
{
/// A literal string (a name, a key, a literal value).
String,
/// A route-language expression or ${…} template — a string to the schema, annotated for the editor.
Expression,
/// An endpoint URI (may carry {{…}} placeholders).
Uri,
/// A #name reference into the context registry.
Reference,
/// A CLR type name (Full.Name, Assembly ).
TypeName,
/// true /false .
Bool,
/// A whole number.
Int,
/// A whole number, 64-bit.
Long,
/// A floating-point number, invariant culture.
Double,
/// A (hh:mm:ss / hh:mm:ss.fff ).
Duration,
/// One of a fixed set of names — .
Enum,
///
/// A comma-separated list of CLR type names (exceptions= ): the comma SEPARATES entries,
/// so an entry is a full name without an assembly suffix. Distinct from
/// because the pack gate resolves each entry, and an assembly-qualified single name also has
/// a comma. Appended LAST on purpose: package contributions compiled against an earlier
/// version store the numeric values of the members above, so an insertion would shift them.
///
TypeNameList,
}
/// One attribute of a format element — the schema/catalog/editor description.
public sealed record AttributeSpec(
string Name,
AttributeType Type,
bool Required = false,
IReadOnlyList? EnumValues = null)
{
///
/// The attribute is read as a CONDITION (a predicate), not as a value: <filter expr> ,
/// <when expr> , <loop while> . The pack gate reads this to warn about a
/// condition written as a template, which is true whatever it renders. An init property, never a
/// positional parameter: a released package contribution is compiled against this record.
///
public bool Condition { get; init; }
///
/// The attribute is a KEY that may be a constant: a value without ${...} that does not start with a root of
/// the exchange (header. , property. , body , exception. ), a namespace (bean: ,
/// ref: , env: ), a function call or a literal is the key as written (<cache key="orders-all"> );
/// any other value is an expression. The pack gate checks it by that rule. An init property, never a positional
/// parameter.
///
public bool ConstantKey { get; init; }
///
/// The attribute names a FILE the runtime reads from the package's resources/ — a
/// template, a transformation spec. The pack gate checks the file is there, exactly as it
/// checks the format's own file= ; a package element whose attribute is named
/// differently (<payload template> , <transformJson spec> ) says so
/// here. An init property, never a positional parameter: a released contribution compiled
/// against this record keeps working, it only goes unchecked until it opts in.
///
public bool Resource { get; init; }
///
/// For a : the CLR type (Full.Name, Assembly ) the
/// registry object it names must be assignable to — <idempotentConsumer repository>
/// names an IIdempotentRepository . The pack gate with the built assemblies at hand
/// holds the declared object against it, so a bean of the wrong type is a build error, not a
/// start-up refusal. An init property: a released contribution keeps working unchecked.
///
public string? References { get; init; }
///
/// The attribute's value is a registry NAME this element registers an object under, of the
/// CLR type given here (<redb><idempotentRepository name> registers a redb
/// idempotent repository). The pack gate counts it as a declaration, exactly like a
/// <bean name> , and knows the object's type for checks.
///
public string? Registers { get; init; }
}
///
/// The public description of one format element: the single source the parser hints,
/// the XSD generator and the catalog all read, so they cannot drift apart. Branch and
/// configuration children (<when> , <param> , …) are nested specs —
/// they are parsed inside their parent's contribution and have no registry entry of their own.
///
public sealed record ElementSpec(
string Name,
XmlElementKind Kind,
IReadOnlyList Attributes,
IReadOnlyList Children,
bool AllowsSteps = false,
bool AllowsTextContent = false,
bool TakesEndpoint = false)
{
///
/// The step ends the route for the exchange (stop , rollbackAll ,
/// throwException ): a step written after it in the same list never runs, and the pack
/// gate says so. An init-only property, not a constructor parameter, so a package
/// contribution compiled against an earlier version keeps binding.
///
public bool Terminal { get; init; }
///
/// The element takes attributes beyond : the options of the type it names (a serializer's
/// delimiter=";" on <marshal type="…"> or <dataFormat> ), which only that type knows. The
/// schema lets them through and the loader holds each against the type's writable properties. Init-only, as
/// .
///
public bool OpenAttributes { get; init; }
/// A leaf with attributes only.
public static ElementSpec Leaf(string name, params AttributeSpec[] attributes)
=> new(name, XmlElementKind.Step, attributes, []);
/// A scope: attributes plus the step group as content.
public static ElementSpec Scope(string name, params AttributeSpec[] attributes)
=> new(name, XmlElementKind.Scope, attributes, [], AllowsSteps: true);
/// A configuration/branch child, declared inline by its parent.
public static ElementSpec Child(string name, bool allowsSteps, params AttributeSpec[] attributes)
=> new(name, XmlElementKind.ConfigChild, attributes, [], AllowsSteps: allowsSteps);
}
///
/// One XML element of the route format: its name, kind, and the parse action that turns the
/// element into calls on the existing fluent DSL. The core registers its own elements through
/// this same contract; a package with DSL of its own (`Cache`, `Templates`, …) registers its
/// elements via . A contribution only calls DSL —
/// it never carries semantics of its own.
///
public interface IXmlElementContribution
{
/// The element's local name (to , filter ). Case-sensitive, camelCase.
string Name { get; }
/// The element's kind — metadata for the schema, catalog and editor.
XmlElementKind Kind { get; }
///
/// The element's public description for the schema, the catalog and the editor. The
/// default is an opaque spec (name and kind, nothing else) so existing contributions keep
/// working; a contribution that wants autocompletion and validation declares the full shape.
///
ElementSpec Spec => new(Name, Kind, [], [], AllowsSteps: Kind is XmlElementKind.Scope);
///
/// Applies the element to the route under construction and returns the current position for
/// the next sibling. A scope opens itself, parses its children through
/// , and returns the closed scope's parent. On a
/// recoverable problem the contribution records it via
/// and returns unchanged — the traversal collects every error of
/// the document in one pass.
///
IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context);
///
/// Prints the element as the fluent C# it parses into — the third face of the
/// contribution beside and , so the parser, the
/// schema and the generator cannot drift apart. The default refuses LOUDLY: a package
/// element without a printer is an explicit generator error, never a silent skip.
///
void Print(XElement element, XmlCodeWriter code) => throw new NotSupportedException(
$"element <{Name}> is not supported by the code generator " +
$"(contribution {GetType().FullName} declares no printer).");
///
/// The namespaces the printed C# needs (using lines the generator adds to the file
/// shell when this contribution is registered). Empty by default — a printer whose verbs
/// live outside the core namespaces declares its own.
///
IReadOnlyList GeneratedUsings => [];
}
///
/// A contribution whose element lives at the container level, beside <route>
/// ( — the REST DSL above all): it applies to the route
/// BUILDER, not to a route under construction. Parsed with the container handlers, before the
/// route elements, inside the builder's Configure.
///
public interface IXmlTopLevelContribution : IXmlElementContribution
{
/// Applies the container-level element to the builder.
void ApplyTopLevel(XElement element, redb.Route.Core.RouteBuilder builder, XmlParseContext context);
}
///
/// A contribution whose element lives at the CONTEXT level, inside <context>
/// ( — the redb bridge above all): it applies to the
/// route CONTEXT during context.xml loading, before any route document. Parsed by
/// XmlContextLoader ; in route position the element is an error.
///
public interface IXmlContextContribution : IXmlElementContribution
{
/// Applies the context-level element to the context being configured.
void ApplyContext(XElement element, redb.Route.Core.RouteContext context, XmlParseContext parseContext);
}
/// Options of the loader. Extensions are the registration channel for packages.
public sealed class XmlRouteLoaderOptions
{
/// Element contributions supplied by packages, merged into the core registry.
public IReadOnlyList Extensions { get; init; } = [];
///
/// Validates every document against the registry's generated XSD during load (on
/// by default). The parser's own findings win on a shared line; the schema adds what the
/// parser deliberately leaves to it — an unqualified attribute typo above all. Turn off for
/// documents that carry a newer schema's ##other extensions on purpose.
///
public bool ValidateAgainstSchema { get; init; } = true;
}
///
/// Every problem of one document, collected in one pass — file, line and column per entry, so
/// fixing ten typos does not take ten runs.
///
public sealed class XmlRouteException : Exception
{
/// The individual problems, each carrying its position.
public IReadOnlyList Errors { get; }
internal XmlRouteException(string sourceName, IReadOnlyList errors)
: base($"{sourceName}: {errors.Count} error(s) in the route document:{Environment.NewLine}" +
string.Join(Environment.NewLine, errors))
=> Errors = errors;
}
Path: redb-route/redb.Route.Xml/CoreElements/CoreContributions.Catalog.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/CoreElements/CoreContributions.Catalog.cs
----
using System.Globalization;
using System.Xml.Linq;
using redb.Route.Abstractions;
using redb.Route.Aggregation;
using redb.Route.ControlBus;
using redb.Route.Core;
using redb.Route.Definitions;
using redb.Route.Expressions;
using redb.Route.Extensions;
using redb.Route.Serialization;
using redb.Route.Transactions;
using redb.Route.Xslt;
namespace redb.Route.Xml.CoreElements;
internal static partial class CoreContributions
{
/// The rest of the catalog — same registry, same facade-over-one-verb rule.
private static IXmlElementContribution[] Catalog() =>
[
// ── leaves ──────────────────────────────────────────────────────────
Step("sort", (e, cur, ctx) =>
{
var expr = ctx.RequiredAttr(e, "expr");
if (expr is null) return cur;
return cur.Sort(expr, ctx.Attr(e, "by"), ctx.Convert(e, "descending") ?? false);
}),
Step("sample", (e, cur, ctx) =>
{
var pick = ctx.ExactlyOneOf(e, "messageFrequency", "period");
if (pick is null) return cur;
if (pick.Value.Name == "messageFrequency")
{
if (long.TryParse(pick.Value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var frequency))
return cur.Sample(frequency);
ctx.AddError(e, $"'{pick.Value.Value}' is not a message frequency (a whole number).");
return cur;
}
if (Duration(pick.Value.Value) is { } period)
return cur.Sample(period);
ctx.AddError(e, $"'{pick.Value.Value}' is not a TimeSpan (use hh:mm:ss or hh:mm:ss.fff).");
return cur;
}),
Step("streamCaching", (e, cur, ctx) => cur.StreamCaching(ctx.Convert(e, "spoolThreshold"))),
Step("messageHistory", (e, cur, ctx) => cur.MessageHistory(ctx.Convert(e, "value") ?? true)),
Step("validateJsonSchema", (e, cur, ctx) =>
{
var schema = FileOrContent(e, ctx, "JSON schema");
if (schema is null) return cur;
return cur.ValidateJsonSchema(schema, ctx.Convert(e, "throwOnFailure") ?? true);
}),
Step("validateXsd", (e, cur, ctx) =>
{
// The file form keeps the file, so its imports and includes resolve relative to it; inline content has
// no location and stays a single schema.
var file = ctx.Attr(e, "file");
var content = ElementText(e);
var schemaRoot = ctx.Attr(e, "schemaRoot");
var throwOnFailure = ctx.Convert(e, "throwOnFailure") ?? true;
if ((file is null) == (content is null))
{
ctx.AddError(e, " takes either the file attribute or inline content, not both.");
return cur;
}
if (content is not null)
{
if (schemaRoot is not null)
{
ctx.AddError(e, " needs the file attribute: inline content has no location for imports to resolve from.");
return cur;
}
return cur.ValidateXsd(ctx.Attr(e, "targetNamespace"), content, throwOnFailure);
}
try
{
// Checked here, so a missing file is still an error where the route is parsed.
ResourceResolution.Resolve(ctx.RouteContext, file!, "XSD schema");
}
catch (Exception ex) when (ex is FileNotFoundException or IOException or UnauthorizedAccessException)
{
ctx.AddError(e, ex.Message);
return cur;
}
return cur.ValidateXsdFile(file!, ctx.Attr(e, "targetNamespace"), schemaRoot, throwOnFailure);
}),
Step("xslt", (e, cur, ctx) =>
{
// The stylesheet path resolves at runtime through the route resource resolver,
// so the file form passes the reference through untouched.
var file = ctx.Attr(e, "file");
var content = ElementText(e);
if ((file is null) == (content is null))
{
ctx.AddError(e, " takes either the file attribute or inline stylesheet content, not both.");
return cur;
}
var output = XsltOutput.String;
if (ctx.Attr(e, "output") is { } outputName &&
!Enum.TryParse(outputName, ignoreCase: true, out output))
{
ctx.AddError(e, $"'{outputName}' is not an XSLT output kind ({string.Join(", ", Enum.GetNames())}).");
return cur;
}
var failOnNullBody = ctx.Convert(e, "failOnNullBody") ?? true;
var fromHeader = ctx.Convert(e, "allowTemplateFromHeader") ?? false;
return file is not null
? cur.Xslt(file, output, failOnNullBody, fromHeader)
: cur.XsltContent(content!, output, failOnNullBody, fromHeader);
}),
Step("marshal", (e, cur, ctx) =>
{
var serializer = SerializerFromElement(e, ctx, requireTarget: false, out _);
return serializer switch
{
string contentType => cur.Marshal(contentType),
IMessageSerializer instance => cur.Marshal(instance),
_ => cur,
};
}),
Step("unmarshal", (e, cur, ctx) =>
{
var serializer = SerializerFromElement(e, ctx, requireTarget: true, out var target);
if (target is null) return cur;
return serializer switch
{
string contentType => cur.Unmarshal(contentType, target),
IMessageSerializer instance => cur.Unmarshal(instance, target),
// No format and no type: dispatch by the message ContentType — the generic
// Unmarshal() closed over the declared target (cold path).
ContentTypeDispatch => (IRouteDefinition)typeof(IRouteDefinition)
.GetMethods()
.First(m => m.Name == nameof(IRouteDefinition.Unmarshal)
&& m.IsGenericMethodDefinition
&& m.GetGenericArguments().Length == 1
&& m.GetParameters().Length == 0)
.MakeGenericMethod(target)
.Invoke(cur, null)!,
_ => cur,
};
}),
Step("controlBus", (e, cur, ctx) =>
{
var actionName = ctx.RequiredAttr(e, "action");
var routeId = ctx.RequiredAttr(e, "routeId");
if (actionName is null || routeId is null) return cur;
if (!Enum.TryParse(actionName, ignoreCase: true, out var action))
{
ctx.AddError(e, $"'{actionName}' is not a control-bus action ({string.Join(", ", Enum.GetNames())}).");
return cur;
}
return cur.ControlBus(action, routeId, ctx.Convert(e, "async") ?? false);
}),
Step("enrich", (e, cur, ctx) =>
{
var uri = StructuredEndpoint.Resolve(e, ctx, out var position);
if (uri is null) return cur;
ctx.NoteEndpointUri(position, uri);
var strategy = MergeStrategy(e, ctx) ?? AggregationStrategies.UseLatest();
return cur.Enrich(uri, strategy);
}),
Step("pollEnrich", (e, cur, ctx) =>
{
var uri = StructuredEndpoint.Resolve(e, ctx, out var position);
if (uri is null) return cur;
ctx.NoteEndpointUri(position, uri);
var timeout = ctx.Convert(e, "timeout");
var strategy = MergeStrategy(e, ctx);
if (strategy is null)
return cur.PollEnrich(uri, timeout);
// The poll may return nothing; a named strategy only merges what actually arrived.
return cur.PollEnrich(uri, (original, polled) => polled is null ? original : strategy(original, polled), timeout);
}),
Step("recipientList", (e, cur, ctx) =>
{
var expr = ctx.RequiredAttr(e, "expr");
if (expr is null) return cur;
return cur.RecipientList(expr,
ctx.Attr(e, "delimiter") ?? ",",
ctx.Convert(e, "parallel") ?? false,
ctx.Convert(e, "stopOnException") ?? false,
MergeStrategy(e, ctx));
}),
Step("dynamicRouter", (e, cur, ctx) =>
{
var expr = ctx.RequiredAttr(e, "expr");
return expr is null ? cur : cur.DynamicRouter(expr);
}),
Step("routingSlip", (e, cur, ctx) =>
{
var expr = ctx.RequiredAttr(e, "expr");
if (expr is null) return cur;
return cur.RoutingSlip(expr,
ctx.Attr(e, "delimiter") ?? ",",
ctx.Convert(e, "ignoreInvalidEndpoints") ?? false);
}),
Step("claimCheck", (e, cur, ctx) =>
{
var operationName = ctx.RequiredAttr(e, "operation");
if (operationName is null) return cur;
if (!Enum.TryParse(operationName, ignoreCase: true, out var operation))
{
ctx.AddError(e, $"'{operationName}' is not a claim-check operation ({string.Join(", ", Enum.GetNames())}).");
return cur;
}
return cur.ClaimCheck(operation,
ctx.Attr(e, "key"),
ctx.Convert(e, "ttl"),
RegistryName(ctx.Attr(e, "repository")));
}),
Step("beginTransaction", (e, cur, ctx) =>
Policy(e, ctx) is { } policy ? cur.BeginTransaction(policy) : cur.BeginTransaction()),
Step("commitTransaction", (e, cur, ctx) => cur.CommitTransaction()),
Step("rollbackTransaction", (e, cur, ctx) => cur.RollbackTransaction()),
Step("rollbackAll", (e, cur, ctx) => cur.RollbackAll()),
Step("exceptionHandled", (e, cur, ctx) => cur.ExceptionHandled()),
Step("routePolicy", (e, cur, ctx) =>
{
var reference = ctx.RequiredAttr(e, "ref");
return reference is null ? cur : cur.RoutePolicy(RegistryName(reference)!);
}),
Step("setHeaders", (e, cur, ctx) =>
{
var headers = new List<(string Name, object? Value)>();
foreach (var child in e.Elements())
{
if (child.Name.LocalName != "header")
{
ctx.AddError(child, $" accepts only children, found <{child.Name.LocalName}>.");
continue;
}
var name = ctx.RequiredAttr(child, "name");
var pick = ctx.ExactlyOneOf(child, "value", "expr");
if (name is null || pick is null) continue;
headers.Add((name, pick.Value.Name == "value"
? pick.Value.Value
: new StringExpression(pick.Value.Value)));
}
if (headers.Count == 0)
{
ctx.AddError(e, " needs at least one or .");
return cur;
}
return cur.SetHeaders([.. headers]);
}),
Step("setProperties", (e, cur, ctx) =>
{
var properties = new List<(string Name, object? Value)>();
foreach (var child in e.Elements())
{
if (child.Name.LocalName != "property")
{
ctx.AddError(child, $" accepts only children, found <{child.Name.LocalName}>.");
continue;
}
var name = ctx.RequiredAttr(child, "name");
var pick = ctx.ExactlyOneOf(child, "value", "expr");
if (name is null || pick is null) continue;
properties.Add((name, pick.Value.Name == "value"
? pick.Value.Value
: new StringExpression(pick.Value.Value)));
}
if (properties.Count == 0)
{
ctx.AddError(e, " needs at least one or .");
return cur;
}
return cur.SetProperties([.. properties]);
}),
// ── scopes ──────────────────────────────────────────────────────────
Scope("multicast", (e, cur, ctx) =>
{
var scope = cur.Multicast();
if (ctx.Convert(e, "parallel") == true) scope.ParallelProcessing();
if (ctx.Convert(e, "maxParallelism") is { } dop) scope.MaxParallelism(dop);
// Pass the attribute through as it is, not only when it is true (same as and ).
if (ctx.Convert(e, "stopOnException") is { } stop) scope.StopOnException(stop);
ctx.ParseSteps(e, scope);
return scope.EndMulticast();
}),
Scope("aggregate", (e, cur, ctx) =>
{
var correlation = ctx.RequiredAttr(e, "correlation");
// Owner decision 2026-09-02: no silent default strategy — absence is a schema error.
var strategyName = ctx.RequiredAttr(e, "strategy");
if (correlation is null || strategyName is null) return cur;
var strategy = NamedStrategy(strategyName, e, ctx);
if (strategy is null) return cur;
var scope = cur.Aggregate(correlation, strategy,
ctx.Attr(e, "completion"),
ctx.Convert(e, "completionSize"),
ctx.Convert(e, "completionTimeout"));
// Apache Camel forceCompletionOnStop: an explicit false is kept, as the fluent call keeps it.
if (ctx.Convert(e, "forceCompletionOnStop") is { } forceCompletion)
scope.ForceCompletionOnStop(forceCompletion);
ctx.ParseSteps(e, scope);
return scope.EndAggregate();
}),
Scope("tryCatch", (e, cur, ctx) =>
{
var scope = cur.TryCatch();
foreach (var child in e.Elements())
{
switch (child.Name.LocalName)
{
case "try":
ctx.ParseSteps(child, scope);
break;
case "catch":
{
var list = ctx.RequiredAttr(child, "exceptions");
if (list is null) continue;
foreach (var typeName in list.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var type = ResolveType(typeName, child, ctx);
if (type is null) continue;
if (!typeof(Exception).IsAssignableFrom(type))
{
ctx.AddError(child, $"'{typeName}' is not an Exception type.");
continue;
}
var handler = scope.Catch(type);
ctx.ApplyBranchIdentity(child, handler);
ctx.ParseSteps(child, handler);
handler.EndCatch();
}
break;
}
case "finally":
{
var final = scope.Finally();
ctx.ApplyBranchIdentity(child, final);
ctx.ParseSteps(child, final);
final.EndFinally();
break;
}
default:
ctx.AddError(child, $" accepts only , and , found <{child.Name.LocalName}>.");
break;
}
}
return scope.EndTryCatch();
}),
Scope("loop", (e, cur, ctx) =>
{
var copy = ctx.Convert(e, "copy") ?? false;
var shareScope = ctx.Convert(e, "shareScope") ?? true;
var sources = new[] { "count", "expr", "while" }.Where(a => ctx.Attr(e, a) is not null).ToList();
if (sources.Count != 1)
{
ctx.AddError(e, " takes exactly one of count, expr or while.");
return cur;
}
LoopDefinition scope;
switch (sources[0])
{
case "count":
if (ctx.Convert(e, "count") is not { } count) return cur;
scope = cur.Loop(count, copy, shareScope);
break;
case "expr":
scope = cur.Loop(ctx.Attr(e, "expr")!, copy, shareScope);
break;
default:
scope = cur.LoopWhile(ctx.Attr(e, "while")!, copy, shareScope);
break;
}
ctx.ParseSteps(e, scope);
return scope.EndLoop();
}),
Scope("throttle", (e, cur, ctx) =>
{
var max = ctx.RequiredAttr(e, "maxPerPeriod");
if (max is null) return cur;
var period = ctx.Convert(e, "period");
var reject = ctx.Convert(e, "rejectOnOverflow") == true;
var maxIsConstant = int.TryParse(max, NumberStyles.Integer, CultureInfo.InvariantCulture, out var maxConstant);
if (ctx.Attr(e, "key") is { } keyExpr)
{
var key = new StringExpression(keyExpr);
Func keyExtractor = ex => key.Evaluate(ex)?.ToString() ?? string.Empty;
KeyedThrottleDefinition keyed;
if (maxIsConstant)
{
keyed = cur.Throttle(keyExtractor, maxConstant, period);
}
else
{
var maxExpression = new StringExpression(max);
keyed = cur.Throttle(keyExtractor, ex => maxExpression.Evaluate(ex), period);
}
if (reject) keyed.RejectOnOverflow();
ctx.ParseSteps(e, keyed);
return keyed.EndKeyedThrottle();
}
var scope = maxIsConstant ? cur.Throttle(maxConstant) : cur.Throttle(max, period);
if (maxIsConstant && period is { } p) scope.Period(p);
if (reject) scope.RejectOnOverflow();
ctx.ParseSteps(e, scope);
return scope.EndThrottle();
}),
Scope("debounce", (e, cur, ctx) =>
{
var key = ctx.RequiredAttr(e, "key");
var quiet = ctx.Convert(e, "quietPeriod");
if (key is null || quiet is null)
{
if (key is not null) ctx.AddError(e, " requires the quietPeriod attribute (a TimeSpan).");
return cur;
}
var scope = cur.Debounce(key, quiet.Value);
ctx.ParseSteps(e, scope);
return scope.EndDebounce();
}),
Scope("circuitBreaker", (e, cur, ctx) =>
{
var scope = cur.CircuitBreaker();
if (ctx.Convert(e, "failureThreshold") is { } threshold) scope.FailureThreshold(threshold);
if (ctx.Convert(e, "resetTimeout") is { } reset) scope.ResetTimeout(reset);
if (ctx.Convert(e, "halfOpenMaxCalls") is { } halfOpen) scope.HalfOpenMaxCalls(halfOpen);
foreach (var child in e.Elements())
{
if (child.Name.LocalName == "fallback")
{
var fallback = scope.OnFallback();
ctx.ApplyBranchIdentity(child, fallback);
ctx.ParseSteps(child, fallback);
fallback.EndFallback();
}
else
{
ctx.ParseStep(child, scope);
}
}
return scope.EndCircuitBreaker();
}),
Scope("idempotentConsumer", (e, cur, ctx) =>
{
var key = ctx.RequiredAttr(e, "key");
var repository = ctx.RequiredAttr(e, "repository");
if (key is null || repository is null) return cur;
var scope = cur.IdempotentConsumer(key, RegistryName(repository)!,
ctx.Convert(e, "skipDuplicate") ?? true);
ctx.ParseSteps(e, scope);
return scope.EndIdempotentConsumer();
}),
Scope("resequence", (e, cur, ctx) =>
{
var key = ctx.RequiredAttr(e, "key");
if (key is null) return cur;
var scope = cur.Resequence(key,
ctx.Convert(e, "batchSize") ?? 100,
ctx.Convert(e, "timeout"));
ctx.ParseSteps(e, scope);
return scope.EndResequence();
}),
Scope("transaction", (e, cur, ctx) =>
{
var scope = cur.Transaction(Policy(e, ctx));
if (ctx.Attr(e, "deadLetterChannel") is { } deadLetter) scope.DeadLetterChannel(deadLetter);
// Attempts and delay are one knob: half of it would retry after a pause nobody wrote.
var attempts = ctx.Convert(e, "retryAttempts");
var retryDelay = ctx.Convert(e, "retryDelay");
if (attempts is not null && retryDelay is not null)
scope.Retry(attempts.Value, retryDelay.Value);
else if (attempts is not null)
ctx.AddError(e, " needs retryDelay too — how long to wait between attempts.");
else if (ctx.Attr(e, "retryDelay") is not null)
ctx.AddError(e, " needs retryAttempts too — how many attempts to make.");
ctx.ParseSteps(e, scope);
return scope.EndTransaction();
}),
Scope("traced", (e, cur, ctx) =>
{
var name = ctx.RequiredAttr(e, "name");
if (name is null) return cur;
var scope = cur.Traced(name);
ctx.ParseSteps(e, scope);
return scope.EndTraced();
}),
// As : value is a literal, expr an expression — exactly one of them.
Step("spanTag", (e, cur, ctx) =>
{
var key = ctx.RequiredAttr(e, "key");
var pick = ctx.ExactlyOneOf(e, "value", "expr");
if (key is null || pick is null) return cur;
var target = redb.Route.Telemetry.SpanTarget.Enclosing;
if (ctx.Attr(e, "target") is { } targetName
&& !Enum.TryParse(targetName, ignoreCase: true, out target))
{
ctx.AddError(e, $"'{targetName}' is not a span target ({string.Join(", ", Enum.GetNames())}).");
return cur;
}
return pick.Value.Name == "value"
? cur.SpanTag(key, pick.Value.Value, target)
: cur.SpanTag(key, new StringExpression(pick.Value.Value), target);
}),
Scope("metered", (e, cur, ctx) =>
{
var name = ctx.RequiredAttr(e, "name");
if (name is null) return cur;
var scope = cur.Metered(name);
// splits the metric by a header or by an expression; the other children are steps.
foreach (var child in e.Elements())
{
if (child.Name.LocalName != "tag")
{
ctx.ParseStep(child, scope);
continue;
}
var tagName = ctx.RequiredAttr(child, "name");
var source = ctx.ExactlyOneOf(child, "fromHeader", "expr");
if (tagName is null || source is null) continue;
if (source.Value.Name == "fromHeader")
{
scope.TagFromHeader(tagName, source.Value.Value);
}
else
{
var expression = new StringExpression(source.Value.Value);
scope.Tag(tagName, exchange => expression.Evaluate(exchange));
}
}
return scope.EndMetered();
}),
Scope("replayable", (e, cur, ctx) =>
{
var name = ctx.RequiredAttr(e, "name");
if (name is null) return cur;
var scope = cur.Replayable(name, ctx.Convert(e, "exposed") ?? false);
ctx.ParseSteps(e, scope);
return CloseScope(scope, e, ctx);
}),
Scope("threads", (e, cur, ctx) =>
{
var poolSize = ctx.Convert(e, "poolSize");
if (poolSize is null)
{
ctx.AddError(e, " requires the poolSize attribute (a whole number).");
return cur;
}
var scope = cur.Threads(poolSize.Value);
if (ctx.Convert(e, "maxQueueSize") is { } maxQueueSize) scope.MaxQueueSize(maxQueueSize);
if (ctx.Convert(e, "enqueueTimeout") is { } enqueueTimeout) scope.EnqueueTimeout(enqueueTimeout);
ctx.ParseSteps(e, scope);
return CloseScope(scope, e, ctx);
}),
Scope("ofType", (e, cur, ctx) =>
{
var typeName = ctx.RequiredAttr(e, "type");
if (typeName is null) return cur;
var type = ResolveType(typeName, e, ctx);
if (type is null) return cur;
// A typed section, not a closable scope: the children belong to the section,
// the siblings continue on the parent — which is exactly XML nesting.
var section = cur.OfType(type);
ctx.ParseSteps(e, section);
return cur;
}),
Step("saga", (e, cur, ctx) =>
{
// The saga DSL is lambda-shaped; the declarative form references IProcessor
// instances from the context registry — resolved at parse, like predicates.
var steps = new List<(IProcessor Action, IProcessor? Compensate)>();
var broken = false;
foreach (var child in e.Elements())
{
if (child.Name.LocalName != "step")
{
ctx.AddError(child, " accepts only children.");
broken = true;
continue;
}
var actionRef = ctx.RequiredAttr(child, "processor");
if (actionRef is null) { broken = true; continue; }
var action = ctx.RouteContext.GetFromRegistry(actionRef);
if (action is null)
{
ctx.AddError(child, $"processor '{actionRef}' is not in the context registry (expected an IProcessor).");
broken = true;
continue;
}
IProcessor? compensate = null;
if (ctx.Attr(child, "compensate") is { } compensateRef)
{
compensate = ctx.RouteContext.GetFromRegistry(compensateRef);
if (compensate is null)
{
ctx.AddError(child, $"compensation '{compensateRef}' is not in the context registry (expected an IProcessor).");
broken = true;
continue;
}
}
steps.Add((action, compensate));
}
if (broken) return cur;
if (steps.Count == 0)
{
ctx.AddError(e, " needs at least one .");
return cur;
}
return cur.Saga(saga =>
{
foreach (var (action, compensate) in steps)
saga.Step(action, compensate);
});
}),
// These four exist at two levels: on a route here, and on for every
// route of the file — the loader reuses the same Configure* helpers, no second copy.
Scope("onException", (e, cur, ctx) =>
{
var types = ExceptionTypes(e, ctx);
if (types.Length == 0) return cur;
var scope = cur.OnException(types);
ConfigureOnException(scope, e, ctx);
return scope.EndOnException();
}),
Scope("intercept", (e, cur, ctx) =>
{
var scope = cur.Intercept();
ConfigureIntercept(scope, e, ctx);
return scope.EndIntercept();
}),
Scope("interceptFrom", (e, cur, ctx) =>
{
var scope = cur.InterceptFrom(ctx.Attr(e, "uri"));
ConfigureIntercept(scope, e, ctx);
return scope.EndIntercept();
}),
Scope("interceptSendToEndpoint", (e, cur, ctx) =>
{
var uri = ctx.RequiredAttr(e, "uri");
if (uri is null) return cur;
var scope = cur.InterceptSendToEndpoint(uri);
ConfigureIntercept(scope, e, ctx);
return scope.EndIntercept();
}),
Scope("onCompletion", (e, cur, ctx) =>
{
var scope = cur.OnCompletion();
ConfigureOnCompletion(scope, e, ctx);
return scope.EndOnCompletion();
}),
Step("scatterGather", (e, cur, ctx) =>
{
var uris = new List();
foreach (var child in e.Elements())
{
if (child.Name.LocalName != "recipient")
{
ctx.AddError(child, $" accepts only children, found <{child.Name.LocalName}>.");
continue;
}
if (ctx.RequiredAttr(child, "uri") is { } uri)
{
ctx.NoteEndpointUri(child, uri);
uris.Add(uri);
}
}
if (uris.Count == 0)
{
ctx.AddError(e, " needs at least one .");
return cur;
}
var strategy = MergeStrategy(e, ctx);
var timeout = ctx.Convert(e, "timeout");
var parallel = ctx.Convert(e, "parallel");
var maxDop = ctx.Convert(e, "maxDop");
var stopOnException = ctx.Convert(e, "stopOnException");
return cur.ScatterGather(definition =>
{
definition.Recipients([.. uris]);
if (strategy is not null) definition.AggregationStrategy(strategy);
if (timeout is { } t) definition.Timeout(t);
if (parallel is { } par) definition.ParallelProcessing(par);
if (maxDop is { } dop) definition.MaxDegreeOfParallelism(dop);
if (stopOnException is { } stop) definition.StopOnException(stop);
});
}),
Step("loadBalance", (e, cur, ctx) =>
{
var endpoints = new List();
var weights = new Dictionary();
foreach (var child in e.Elements())
{
if (child.Name.LocalName != "endpoint")
{
ctx.AddError(child, $" accepts only children, found <{child.Name.LocalName}>.");
continue;
}
if (ctx.RequiredAttr(child, "uri") is not { } uri) continue;
ctx.NoteEndpointUri(child, uri);
endpoints.Add(uri);
if (ctx.Convert(child, "weight") is { } weight) weights[uri] = weight;
}
var strategyName = ctx.RequiredAttr(e, "strategy");
if (strategyName is null || endpoints.Count == 0)
{
if (strategyName is not null)
ctx.AddError(e, " needs at least one .");
return cur;
}
var key = ctx.Attr(e, "key");
return cur.LoadBalance(definition =>
{
definition.Endpoints([.. endpoints]);
switch (strategyName)
{
case "roundRobin": definition.UseRoundRobin(); break;
case "random": definition.UseRandom(); break;
case "failover": definition.UseFailover(); break;
case "sticky":
if (key is null)
{
ctx.AddError(e, "strategy=\"sticky\" requires the key attribute (an expression).");
break;
}
definition.UseSticky(key);
break;
case "weighted":
if (weights.Count != endpoints.Count)
{
ctx.AddError(e, "strategy=\"weighted\" requires a weight on every .");
break;
}
definition.UseWeighted(weights);
break;
default:
ctx.AddError(e, $"'{strategyName}' is not a load-balancing strategy (roundRobin, random, failover, sticky, weighted).");
break;
}
});
}),
Step("normalize", (e, cur, ctx) =>
{
var branches = e.Elements().ToList();
if (branches.Count == 0)
{
ctx.AddError(e, " needs at least one , or child.");
return cur;
}
// Collected first so the configure callback never touches the parse context late.
var whens = new List<(string Condition, Func Transform)>();
var byContentType = new List<(string ContentType, Func Transform)>();
Func? otherwise = null;
foreach (var child in branches)
{
var transform = NormalizeTransform(child, ctx);
if (transform is null) continue;
switch (child.Name.LocalName)
{
case "when":
if (ctx.RequiredAttr(child, "expr") is { } condition)
whens.Add((condition, transform));
break;
case "whenContentType":
if (ctx.RequiredAttr(child, "type") is { } contentType)
byContentType.Add((contentType, transform));
break;
case "otherwise":
otherwise = transform;
break;
default:
ctx.AddError(child, $" accepts , and , found <{child.Name.LocalName}>.");
break;
}
}
return cur.Normalize(definition =>
{
foreach (var (condition, transform) in whens) definition.When(condition, transform);
foreach (var (contentType, transform) in byContentType) definition.WhenContentType(contentType, transform);
if (otherwise is not null) definition.Otherwise(otherwise);
});
}),
];
// ── helpers ─────────────────────────────────────────────────────────────
private static DelegateContribution Scope(
string name, Func apply)
=> new(name, XmlElementKind.Scope, apply);
/// Closes a scope through the uniform contract.
private static IRouteDefinition CloseScope(IRouteDefinition scope, XElement e, XmlParseContext ctx)
{
if (scope is IRouteScope closable)
return closable.End();
ctx.AddError(e, $"internal: {scope.GetType().Name} is not an IRouteScope and cannot be closed.");
return scope;
}
/// The exception-type list of an onException/catch attribute; errors are positioned.
internal static Type[] ExceptionTypes(XElement e, XmlParseContext ctx)
{
var list = ctx.RequiredAttr(e, "exceptions");
if (list is null) return [];
var types = new List();
foreach (var typeName in list.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var type = ResolveType(typeName, e, ctx);
if (type is null) continue;
if (!typeof(Exception).IsAssignableFrom(type))
{
ctx.AddError(e, $"'{typeName}' is not an Exception type.");
continue;
}
types.Add(type);
}
return [.. types];
}
/// Attributes and child steps of an onException — shared by the route and container levels.
internal static void ConfigureOnException(OnExceptionDefinition scope, XElement e, XmlParseContext ctx)
{
if (ctx.Convert(e, "handled") is { } handled) scope.Handled(handled);
if (ctx.Convert(e, "continued") is { } continued) scope.Continued(continued);
if (ctx.Convert(e, "maximumRedeliveries") is { } redeliveries) scope.MaximumRedeliveries(redeliveries);
if (ctx.Convert(e, "redeliveryDelay") is { } delay) scope.RedeliveryDelay(delay);
if (ctx.Convert(e, "exponentialBackOff") is { } backOff) scope.UseExponentialBackOff(backOff);
if (ctx.Convert(e, "backOffMultiplier") is { } multiplier) scope.BackOffMultiplier(multiplier);
if (ctx.Convert(e, "useOriginalBody") == true) scope.UseOriginalBody();
if (ctx.Convert(e, "logStackTrace") is { } stackTrace) scope.LogStackTrace(stackTrace);
if (ctx.Convert(e, "logExhausted") is { } exhausted) scope.LogExhausted(exhausted);
if (ctx.Convert(e, "logHandled") is { } logHandled) scope.LogHandled(logHandled);
if (ctx.Convert(e, "logContinued") is { } logContinued) scope.LogContinued(logContinued);
if (LogLevelOf(e, "retryAttemptedLogLevel", ctx) is { } attempted) scope.RetryAttemptedLogLevel(attempted);
if (LogLevelOf(e, "retriesExhaustedLogLevel", ctx) is { } exhaustedLevel) scope.RetriesExhaustedLogLevel(exhaustedLevel);
// The three moments a handler can step into, each a bean from the registry: on every
// occurrence, before every retry, once before the handler takes over for good.
if (ProcessorRef(e, "onExceptionOccurred", ctx) is { } occurred) scope.OnExceptionOccurred(occurred);
if (ProcessorRef(e, "onRedelivery", ctx) is { } redelivery) scope.OnRedelivery(redelivery);
if (ProcessorRef(e, "onPrepareFailure", ctx) is { } prepareFailure) scope.OnPrepareFailure(prepareFailure);
// decides whether this handler takes the failure at all, whether
// another attempt follows: conditions of the scope, like an intercept's. Everything
// else is the handler's own route.
foreach (var child in e.Elements())
{
if (IsConditionChild(child, ctx, out var condition))
{
if (condition is not null) scope.OnWhen(condition);
}
else if (child.Name.LocalName == "retryWhile")
{
if (child.Elements().Any())
ctx.AddError(child, " here is the scope's retry condition and takes no child steps — put the steps next to it.");
else if (ctx.RequiredAttr(child, "expr") is { } retryWhile)
scope.RetryWhile(retryWhile);
}
else
{
ctx.ParseStep(child, scope);
}
}
}
///
/// An optional reference to an bean; a name the registry does not hold is a
/// positioned error, so a misspelt reference is named at load instead of going silently unused.
///
private static IProcessor? ProcessorRef(XElement e, string attribute, XmlParseContext ctx)
{
if (ctx.Attr(e, attribute) is not { } reference) return null;
var processor = ctx.RouteContext.GetFromRegistry(reference);
if (processor is null)
ctx.AddError(e, $"{attribute} '{reference}' is not in the context registry (expected an IProcessor).");
return processor;
}
/// An optional log-level attribute; an unknown name is a positioned error, not a silent default.
private static Microsoft.Extensions.Logging.LogLevel? LogLevelOf(XElement e, string attribute, XmlParseContext ctx)
{
if (ctx.Attr(e, attribute) is not { } name) return null;
if (Enum.TryParse(name, ignoreCase: true, out var level))
return level;
ctx.AddError(e, $"'{name}' is not a log level (Trace, Debug, Information, Warning, Error, Critical).");
return null;
}
/// Attributes, condition and child steps of an intercept — shared by both levels.
internal static void ConfigureIntercept(InterceptDefinition scope, XElement e, XmlParseContext ctx)
{
if (ctx.Attr(e, "skipSendToOriginalEndpoint") is not null)
{
// Meaningful only where there IS an original send to skip; elsewhere it is a
// misplaced intention — say so instead of applying it silently.
if (e.Name.LocalName == "interceptSendToEndpoint")
{
if (ctx.Convert(e, "skipSendToOriginalEndpoint") == true)
scope.SkipSendToOriginalEndpoint();
}
else
{
ctx.AddError(e, "skipSendToOriginalEndpoint is valid only on .");
}
}
foreach (var child in e.Elements())
{
if (IsConditionChild(child, ctx, out var condition))
{
if (condition is not null) scope.When(condition);
}
else
{
ctx.ParseStep(child, scope);
}
}
}
/// Attributes, condition and child steps of an onCompletion — shared by both levels.
internal static void ConfigureOnCompletion(OnCompletionDefinition scope, XElement e, XmlParseContext ctx)
{
if (ctx.Convert(e, "onCompleteOnly") == true) scope.OnCompleteOnly();
if (ctx.Convert(e, "onFailureOnly") == true) scope.OnFailureOnly();
if (ctx.Convert(e, "modeBeforeConsumer") == true) scope.ModeBeforeConsumer();
if (ctx.Convert(e, "parallelProcessing") == true) scope.ParallelProcessing();
if (ctx.Attr(e, "executorService") is { } pool) scope.ExecutorService(pool);
foreach (var child in e.Elements())
{
if (IsConditionChild(child, ctx, out var condition))
{
if (condition is not null) scope.When(condition);
}
else
{
ctx.ParseStep(child, scope);
}
}
}
///
/// A childless <when expr=…/> inside intercepts and onCompletion is the scope's
/// condition, not a step; with children it would be ambiguous and is refused.
///
private static bool IsConditionChild(XElement child, XmlParseContext ctx, out string? condition)
{
condition = null;
if (child.Name.LocalName != "when")
return false;
if (child.Elements().Any())
{
ctx.AddError(child, " here is the scope's condition and takes no child steps — put the steps next to it.");
return true;
}
condition = ctx.RequiredAttr(child, "expr");
return true;
}
/// Resolves the optional strategy attribute: #name from the registry, otherwise a named strategy.
private static Func? MergeStrategy(XElement e, XmlParseContext ctx)
{
var name = ctx.Attr(e, "strategy");
return name is null ? null : NamedStrategy(name, e, ctx);
}
private static Func? NamedStrategy(string name, XElement e, XmlParseContext ctx)
{
if (name.StartsWith('#'))
{
var registered = ctx.RouteContext.GetFromRegistry>(name);
if (registered is null)
ctx.AddError(e, $"strategy '{name}' is not in the context registry (expected a Func).");
return registered;
}
try
{
return AggregationStrategies.ByName(name);
}
catch (ArgumentException ex)
{
ctx.AddError(e, ex.Message);
return null;
}
}
/// The transform of a normalize branch: an expression in the value position.
private static Func? NormalizeTransform(XElement child, XmlParseContext ctx)
{
var expr = ctx.RequiredAttr(child, "transform");
if (expr is null) return null;
var expression = new StringExpression(expr);
return exchange => expression.Evaluate(exchange);
}
private static TransactionPolicy? Policy(XElement e, XmlParseContext ctx)
{
var name = ctx.Attr(e, "policy");
if (name is null) return null;
var policy = name.ToLowerInvariant() switch
{
"default" => TransactionPolicy.Default,
"requiresnew" => TransactionPolicy.RequiresNew,
"suppress" => TransactionPolicy.Suppress,
"mandatory" => TransactionPolicy.Mandatory,
_ => null,
};
if (policy is null)
ctx.AddError(e, $"'{name}' is not a transaction policy (default, requiresNew, suppress, mandatory).");
return policy;
}
private static string? RegistryName(string? reference)
=> reference is { Length: > 0 } && reference.StartsWith('#') ? reference[1..] : reference;
/// Text of the element itself (CDATA included), ignoring child elements.
private static string? ElementText(XElement e)
{
var text = string.Concat(e.Nodes().OfType().Select(t => t.Value));
return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}
/// The file attribute or inline content, not both; files load through the route resource resolver.
private static string? FileOrContent(XElement e, XmlParseContext ctx, string what)
{
var file = ctx.Attr(e, "file");
var content = ElementText(e);
if ((file is null) == (content is null))
{
ctx.AddError(e, $"<{e.Name.LocalName}> takes either the file attribute or inline content, not both.");
return null;
}
if (content is not null)
return content;
try
{
return File.ReadAllText(ResourceResolution.Resolve(ctx.RouteContext, file!, what));
}
catch (Exception ex) when (ex is FileNotFoundException or IOException or UnauthorizedAccessException)
{
ctx.AddError(e, ex.Message);
return null;
}
}
///
/// The marshal/unmarshal source: a registered content type (format= , returned as
/// string) or a serializer type (type= , returned as a fresh instance with the extra
/// attributes bound to its properties). Extra attributes are refused with format= —
/// registry serializers are shared instances and must not be mutated per step.
///
private static object? SerializerFromElement(XElement e, XmlParseContext ctx, bool requireTarget, out Type? target)
{
target = null;
if (requireTarget)
{
var targetName = ctx.RequiredAttr(e, "target");
if (targetName is null) return null;
target = ResolveType(targetName, e, ctx);
if (target is null) return null;
}
var known = requireTarget
? new[] { "format", "type", "target", "id", "description" }
: ["format", "type", "id", "description"];
var extras = e.Attributes().Where(a => !known.Contains(a.Name.LocalName)).ToList();
var format = ctx.Attr(e, "format");
var typeName = ctx.Attr(e, "type");
if (format is not null && typeName is not null)
{
ctx.AddError(e, $"<{e.Name.LocalName}> takes either format or type, not both.");
return null;
}
if (format is not null)
{
if (extras.Count > 0)
ctx.AddError(e, $"format options ({string.Join(", ", extras.Select(a => a.Name.LocalName))}) " +
"need the type= form — a registered format is shared and takes no per-step options.");
return format;
}
if (typeName is null)
{
if (!requireTarget)
{
ctx.AddError(e, $"<{e.Name.LocalName}> requires format or type.");
return null;
}
return ContentTypeDispatch.Instance; // unmarshal dispatches by the message ContentType
}
return CreateSerializer(e, ctx, typeName, extras);
}
///
/// A serializer of the named type with its options set from the element's other attributes (delimiter=";" →
/// Delimiter ): the per-step form of <marshal> / <unmarshal> and the context-level
/// <dataFormat> . A serializer built from an options object (new CsvDataFormat(CsvDataFormatOptions) ,
/// the shape of the redb.Route.DataFormats.* packages) gets one with the attributes set on it; otherwise the serializer
/// is created with its parameterless constructor and the attributes set its own properties. Null after an error.
///
internal static IMessageSerializer? CreateSerializer(XElement e, XmlParseContext ctx, string typeName,
IReadOnlyList extras)
{
var type = ResolveType(typeName, e, ctx);
if (type is null) return null;
if (!typeof(IMessageSerializer).IsAssignableFrom(type))
{
ctx.AddError(e, $"'{typeName}' does not implement IMessageSerializer.");
return null;
}
// A parameterless constructor keeps the serializer's own properties as the options, as before; only a serializer
// without one is built from an options object.
var optionsConstructor = type.GetConstructor(Type.EmptyTypes) is not null ? null : type.GetConstructors()
.FirstOrDefault(c => c.GetParameters() is [{ ParameterType: { IsClass: true } p }]
&& p != typeof(string) && p.GetConstructor(Type.EmptyTypes) is not null);
try
{
if (optionsConstructor is not null)
{
var optionsType = optionsConstructor.GetParameters()[0].ParameterType;
var options = Activator.CreateInstance(optionsType)!;
SetOptions(e, ctx, options, extras, $"serializer '{type.Name}' options ({optionsType.Name})");
return (IMessageSerializer)optionsConstructor.Invoke([options]);
}
var instance = Activator.CreateInstance(type)
?? throw new InvalidOperationException($"Activator returned null for {type}.");
SetOptions(e, ctx, instance, extras, $"serializer '{type.Name}'");
return (IMessageSerializer)instance;
}
catch (Exception ex) when (ex is MissingMethodException or MemberAccessException or InvalidOperationException)
{
ctx.AddError(e, $"serializer '{typeName}' has no parameterless constructor and none taking an options object: {ex.Message}");
return null;
}
}
private static void SetOptions(XElement e, XmlParseContext ctx, object target, IReadOnlyList extras, string what)
{
var type = target.GetType();
foreach (var extra in extras)
{
var property = type.GetProperty(char.ToUpperInvariant(extra.Name.LocalName[0]) + extra.Name.LocalName[1..])
?? type.GetProperty(extra.Name.LocalName);
if (property is null || !property.CanWrite)
{
ctx.AddError(e, $"{what} has no writable property for option '{extra.Name.LocalName}'.");
continue;
}
var converted = OptionValueConverter.Convert(extra.Value, property.PropertyType);
if (converted is null)
{
ctx.AddError(e, $"'{extra.Value}' is not convertible to {property.PropertyType.Name} for option '{extra.Name.LocalName}'.");
continue;
}
property.SetValue(target, converted);
}
}
private static TimeSpan? Duration(string value)
=> TimeSpan.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
/// Marker: unmarshal with neither format nor type — resolve by the message ContentType.
private sealed class ContentTypeDispatch
{
public static readonly ContentTypeDispatch Instance = new();
}
}
Path: redb-route/redb.Route.Xml/CoreElements/CoreContributions.Print.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/CoreElements/CoreContributions.Print.cs
----
using System.Globalization;
using System.Xml.Linq;
namespace redb.Route.Xml.CoreElements;
internal static partial class CoreContributions
{
// ── The printers: element → the fluent C# its Apply parses into ─────────
// The third face of the one list. Generated code is statements against receiver variables
// (see XmlCodeWriter) — the model the equivalence tests proved compilable and
// tree-identical; a printer mirrors its contribution's DSL calls line for line.
private static string? A(XElement e, string name) => e.Attribute(name)?.Value;
private static string S6(XElement e, string name) => XmlCodeWriter.Str(A(e, name) ?? "");
private static string Reg(string? reference)
=> XmlCodeWriter.Str(reference is { Length: > 0 } && reference.StartsWith('#') ? reference[1..] : reference ?? "");
private static string StrategyArg(string name)
=> name.StartsWith('#')
? $"Context!.GetFromRegistry>({Reg(name)})!"
: $"AggregationStrategies.ByName({XmlCodeWriter.Str(name)})";
private static string PredicateArg(string reference)
=> $"Context!.GetFromRegistry({Reg(reference)})!";
private static string AddressUri(XElement e)
{
if (A(e, "uri") is { } uri)
return XmlCodeWriter.Str(uri);
var child = e.Elements().FirstOrDefault()
?? throw new NotSupportedException($"<{e.Name.LocalName}> carries neither uri= nor an endpoint child.");
return XmlCodeWriter.Str(StructuredEndpoint.NormalizeForPrint(child));
}
///
/// A step <bean> : .Bean(reference, method) when it carries nothing else, the normalized
/// To("bean://...") when it also sets bean properties (the sugar takes no options).
///
private static void PrintBeanStep(XElement e, XmlCodeWriter w)
{
var uri = StructuredEndpoint.NormalizeBeanStepForPrint(e);
var onlyMethod = e.Attributes().All(a => a.IsNamespaceDeclaration || a.Name.NamespaceName.Length > 0
|| a.Name.LocalName is "ref" or "beanType" or "method" or "id" or "description");
if (!onlyMethod)
{
w.Verb(e, "To", XmlCodeWriter.Str(uri));
return;
}
var reference = XmlCodeWriter.Str(StructuredEndpoint.BeanStepReference(e)!);
if (A(e, "method") is { } method)
w.Verb(e, "Bean", reference, XmlCodeWriter.Str(method));
else
w.Verb(e, "Bean", reference);
}
private static string ElementText6(XElement e)
=> string.Concat(e.Nodes().OfType().Select(t => t.Value)).Trim();
private static TimeSpan ParseTs(string value)
=> TimeSpan.Parse(value, CultureInfo.InvariantCulture);
/// Trailing-default trimming: print positional args up to the last non-null.
private static string[] Trim(params string?[] args)
{
var last = Array.FindLastIndex(args, a => a is not null);
return [.. args.Take(last + 1).Select(a => a ?? "null")];
}
private static void PrintRichOrPlainLog(XElement e, XmlCodeWriter w)
{
var level = A(e, "level");
var levelRef = level is null ? null : $"LogLevel.{Enum.Parse(level, true)}";
if (!e.Elements().Any())
{
var text = XmlCodeWriter.Str(ElementText6(e));
w.Verb(e, "Log", levelRef is null ? [text] : [text, levelRef]);
return;
}
w.Scope(e, "Log", [levelRef ?? "LogLevel.Information"], "EndLog", body: w2 =>
{
if (A(e, "showRouteId") == "true")
w2.Config("ShowRouteId()");
foreach (var child in e.Elements())
{
switch (child.Name.LocalName)
{
case "message": w2.Config($"Message({XmlCodeWriter.Str(child.Value)})"); break;
case "header": w2.Config($"Header({S6(child, "name")})"); break;
case "property": w2.Config($"Property({S6(child, "name")})"); break;
}
}
});
}
internal static readonly IReadOnlyDictionary> Printers =
new Dictionary>(StringComparer.Ordinal)
{
// ── leaves ──────────────────────────────────────────────────────
["to"] = (e, w) => w.Verb(e, "To", AddressUri(e)),
["bean"] = PrintBeanStep,
["toD"] = (e, w) => w.Verb(e, "ToD", AddressUri(e)),
["wireTap"] = (e, w) => w.Verb(e, "WireTap", A(e, "executorService") is { } pool
? [AddressUri(e), "executorService: " + XmlCodeWriter.Str(pool)]
: [AddressUri(e)]),
["enrich"] = (e, w) => w.Verb(e, "Enrich", A(e, "strategy") is { } s
? [AddressUri(e), StrategyArg(s)]
: [AddressUri(e)]),
["pollEnrich"] = (e, w) =>
{
var timeout = A(e, "timeout") is { } t ? XmlCodeWriter.Ts(ParseTs(t)) : null;
if (A(e, "strategy") is { } s)
{
var merge = $"(original, polled) => polled is null ? original : {StrategyArg(s)}(original, polled)";
w.Verb(e, "PollEnrich", Trim(AddressUri(e), merge, timeout));
}
else
{
w.Verb(e, "PollEnrich", Trim(AddressUri(e), timeout));
}
},
["setHeader"] = (e, w) => w.Verb(e, "SetHeader", S6(e, "name"),
A(e, "expr") is { } x ? XmlCodeWriter.Expr(x) : XmlCodeWriter.Value(A(e, "value") ?? "")),
["setProperty"] = (e, w) => w.Verb(e, "SetProperty", S6(e, "name"),
A(e, "expr") is { } x ? XmlCodeWriter.Expr(x) : XmlCodeWriter.Value(A(e, "value") ?? "")),
["setBody"] = (e, w) => w.Verb(e, "SetBody",
A(e, "expr") is { } x ? XmlCodeWriter.Expr(x) : XmlCodeWriter.Value(A(e, "value") ?? "")),
["transform"] = (e, w) => w.Verb(e, "Transform", XmlCodeWriter.Expr(A(e, "expr") ?? "")),
["removeHeader"] = (e, w) => w.Verb(e, "RemoveHeader", S6(e, "name")),
["removeProperty"] = (e, w) => w.Verb(e, "RemoveProperty", S6(e, "name")),
["removeBody"] = (e, w) => w.Verb(e, "RemoveBody"),
["addAttachment"] = (e, w) =>
{
// Optional arguments by name: a positional null would not pick between the literal and expression overloads.
string? Opt(string name) => A(e, name) is { } v ? XmlCodeWriter.Str(v) : null;
string[] Named(params (string Name, string? Value)[] args) =>
[.. args.Where(a => a.Value is not null).Select(a => $"{a.Name}: {a.Value}")];
string? FileName() => A(e, "fileNameExpr") is { } x ? XmlCodeWriter.Expr(x) : Opt("fileName");
if (A(e, "file") is { } file)
w.Verb(e, "AddAttachmentFromFile", [XmlCodeWriter.Str(file), .. Named(("name", Opt("name")), ("contentType", Opt("contentType")))]);
else if (A(e, "fileExpr") is { } fileExpr)
w.Verb(e, "AddAttachmentFromFile", [XmlCodeWriter.Expr(fileExpr), .. Named(("name", Opt("name")), ("contentType", Opt("contentType")))]);
else if (A(e, "fromBody") is not null)
w.Verb(e, "AddAttachmentFromBody", [S6(e, "name"), .. Named(("fileName", FileName()), ("contentType", Opt("contentType")))]);
else
w.Verb(e, "AddAttachment", [S6(e, "name"), XmlCodeWriter.Expr(A(e, "expr") ?? ""),
.. Named(("fileName", FileName()), ("contentType", Opt("contentType")))]);
},
["removeAttachment"] = (e, w) => w.Verb(e, "RemoveAttachment", S6(e, "name")),
["removeAttachments"] = (e, w) => w.Verb(e, "RemoveAttachments"),
["removeHeaders"] = (e, w) => w.Verb(e, "RemoveHeaders",
[S6(e, "pattern"), .. (A(e, "except") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(XmlCodeWriter.Str)]),
["removeProperties"] = (e, w) => w.Verb(e, "RemoveProperties",
[S6(e, "pattern"), .. (A(e, "except") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(XmlCodeWriter.Str)]),
["setHeaders"] = (e, w) => w.Verb(e, "SetHeaders", [.. e.Elements()
.Where(c => c.Name.LocalName == "header")
.Select(c => $"({S6(c, "name")}, {(A(c, "expr") is { } x ? XmlCodeWriter.Expr(x) : S6(c, "value"))})")]),
["setProperties"] = (e, w) => w.Verb(e, "SetProperties", [.. e.Elements()
.Where(c => c.Name.LocalName == "property")
.Select(c => $"({S6(c, "name")}, {(A(c, "expr") is { } x ? XmlCodeWriter.Expr(x) : S6(c, "value"))})")]),
["log"] = PrintRichOrPlainLog,
["delay"] = (e, w) => w.Verb(e, "Delay",
A(e, "expr") is { } x ? XmlCodeWriter.Str(x) : XmlCodeWriter.Ts(ParseTs(A(e, "duration") ?? "0:0:0"))),
["stop"] = (e, w) => w.Verb(e, "Stop"),
["throwException"] = (e, w) => w.Verb(e, "ThrowException",
XmlCodeWriter.TypeRef(A(e, "type") ?? ""), XmlCodeWriter.Str(A(e, "message") ?? "error")),
["convertBody"] = (e, w) => w.Verb(e, "ConvertBody", XmlCodeWriter.TypeRef(A(e, "type") ?? "")),
["validate"] = (e, w) => w.Verb(e, "Validate", Trim(
S6(e, "expr"),
XmlCodeWriter.Str(A(e, "message") ?? "Validation failed"),
A(e, "throwOnFailure") is { } t ? XmlCodeWriter.Bool(bool.Parse(t)) : null)),
["sort"] = (e, w) => w.Verb(e, "Sort", Trim(
S6(e, "expr"),
A(e, "by") is { } by ? XmlCodeWriter.Str(by) : A(e, "descending") is null ? null : "null",
A(e, "descending") is { } d ? XmlCodeWriter.Bool(bool.Parse(d)) : null)),
["sample"] = (e, w) => w.Verb(e, "Sample",
A(e, "messageFrequency") is { } f ? $"{f}L" : XmlCodeWriter.Ts(ParseTs(A(e, "period") ?? "0:0:1"))),
["streamCaching"] = (e, w) => w.Verb(e, "StreamCaching",
A(e, "spoolThreshold") is { } s ? [$"{s}L"] : []),
["messageHistory"] = (e, w) => w.Verb(e, "MessageHistory",
A(e, "value") is { } mh ? [XmlCodeWriter.Bool(bool.Parse(mh))] : []),
["validateJsonSchema"] = (e, w) => w.Verb(e, "ValidateJsonSchema", Trim(
XmlCodeWriter.Str(A(e, "file") is { } f ? w.ReadResource(f) : ElementText6(e)),
A(e, "throwOnFailure") is { } t ? XmlCodeWriter.Bool(bool.Parse(t)) : null)),
// The file form stays a file, so its imports resolve at runtime as in the markup; inline text stays text.
["validateXsd"] = (e, w) =>
{
var ns = A(e, "targetNamespace") is { } n ? XmlCodeWriter.Str(n) : null;
var throwOnFailure = A(e, "throwOnFailure") is { } t ? XmlCodeWriter.Bool(bool.Parse(t)) : null;
if (A(e, "file") is { } file)
{
w.LocateResource(file); // a missing schema still fails the generation, naming where it looked
w.Verb(e, "ValidateXsdFile", Trim(XmlCodeWriter.Str(file), ns,
A(e, "schemaRoot") is { } root ? XmlCodeWriter.Str(root) : null, throwOnFailure));
}
else
w.Verb(e, "ValidateXsd", Trim(ns ?? "null", XmlCodeWriter.Str(ElementText6(e)), throwOnFailure));
},
["xslt"] = (e, w) =>
{
var output = A(e, "output") is { } o ? $"XsltOutput.{Enum.Parse(o, true)}" : null;
var fail = A(e, "failOnNullBody") is { } fb ? XmlCodeWriter.Bool(bool.Parse(fb)) : null;
var fromHeader = A(e, "allowTemplateFromHeader") is { } h ? XmlCodeWriter.Bool(bool.Parse(h)) : null;
if (A(e, "file") is { } file)
w.Verb(e, "Xslt", Trim(XmlCodeWriter.Str(file), output, fail, fromHeader));
else
w.Verb(e, "XsltContent", Trim(XmlCodeWriter.Str(ElementText6(e)), output, fail, fromHeader));
},
["marshal"] = (e, w) =>
{
if (e.Attributes().Any(a => a.Name.LocalName is not ("format" or "type" or "id" or "description")))
throw new NotSupportedException(" with per-step format options is not supported by the code generator yet.");
w.Verb(e, "Marshal", A(e, "format") is { } f ? XmlCodeWriter.Str(f) : XmlCodeWriter.TypeRef(A(e, "type") ?? ""));
},
["unmarshal"] = (e, w) =>
{
var target = XmlCodeWriter.TypeRef(A(e, "target") ?? "");
if (A(e, "format") is { } f)
w.Verb(e, "Unmarshal", XmlCodeWriter.Str(f), target);
else if (A(e, "type") is { } t)
w.Verb(e, "Unmarshal", XmlCodeWriter.TypeRef(t), target);
else
throw new NotSupportedException(" by message ContentType is not supported by the code generator yet.");
},
["controlBus"] = (e, w) => w.Verb(e, "ControlBus",
$"ControlBusAction.{Enum.Parse(A(e, "action") ?? "", true)}",
S6(e, "routeId"),
XmlCodeWriter.Bool(A(e, "async") == "true")),
["recipientList"] = (e, w) => w.Verb(e, "RecipientList", Trim(
S6(e, "expr"),
A(e, "delimiter") is { } d ? XmlCodeWriter.Str(d) : (A(e, "parallel") ?? A(e, "stopOnException") ?? A(e, "strategy")) is null ? null : "\",\"",
A(e, "parallel") is { } p ? XmlCodeWriter.Bool(bool.Parse(p)) : (A(e, "stopOnException") ?? A(e, "strategy")) is null ? null : "false",
A(e, "stopOnException") is { } s ? XmlCodeWriter.Bool(bool.Parse(s)) : A(e, "strategy") is null ? null : "false",
A(e, "strategy") is { } st ? StrategyArg(st) : null)),
["dynamicRouter"] = (e, w) => w.Verb(e, "DynamicRouter", S6(e, "expr")),
["routingSlip"] = (e, w) => w.Verb(e, "RoutingSlip", Trim(
S6(e, "expr"),
A(e, "delimiter") is { } d ? XmlCodeWriter.Str(d) : A(e, "ignoreInvalidEndpoints") is null ? null : "\",\"",
A(e, "ignoreInvalidEndpoints") is { } i ? XmlCodeWriter.Bool(bool.Parse(i)) : null)),
["claimCheck"] = (e, w) => w.Verb(e, "ClaimCheck", Trim(
$"ClaimCheckOperation.{Enum.Parse(A(e, "operation") ?? "", true)}",
A(e, "key") is { } k ? XmlCodeWriter.Str(k) : (A(e, "ttl") ?? A(e, "repository")) is null ? null : "null",
A(e, "ttl") is { } t ? XmlCodeWriter.Ts(ParseTs(t)) : A(e, "repository") is null ? null : "null",
A(e, "repository") is { } r ? Reg(r) : null)),
["beginTransaction"] = (e, w) => w.Verb(e, "BeginTransaction",
A(e, "policy") is { } p ? [PolicyRef(p)] : []),
["commitTransaction"] = (e, w) => w.Verb(e, "CommitTransaction"),
["rollbackTransaction"] = (e, w) => w.Verb(e, "RollbackTransaction"),
["rollbackAll"] = (e, w) => w.Verb(e, "RollbackAll"),
["exceptionHandled"] = (e, w) => w.Verb(e, "ExceptionHandled"),
["routePolicy"] = (e, w) => w.Verb(e, "RoutePolicy", Reg(A(e, "ref"))),
// ── scopes ──────────────────────────────────────────────────────
["filter"] = (e, w) => w.Scope(e, "Filter",
[A(e, "predicate") is { } p ? PredicateArg(p) : S6(e, "expr")], "EndFilter"),
["split"] = (e, w) =>
{
var tokenizer = e.Elements().FirstOrDefault(c => c.Name.LocalName
is "tokenizeLines" or "tokenizeXml" or "tokenizeJsonArray");
var source = tokenizer is null
? XmlCodeWriter.Expr(A(e, "expr") ?? "")
: tokenizer.Name.LocalName switch
{
"tokenizeLines" => $"SplitLines({XmlCodeWriter.Str(A(tokenizer, "separator") ?? "\n")}, {XmlCodeWriter.Bool(A(tokenizer, "skipEmpty") == "true")})",
"tokenizeXml" => $"SplitXml({S6(tokenizer, "element")}{(A(tokenizer, "inheritNamespaceFrom") is { } inh ? ", " + XmlCodeWriter.Str(inh) : "")})",
_ => "SplitJsonArray()",
};
w.Scope(e, "Split", [source], "EndSplit", body: w2 =>
{
if (A(e, "parallel") == "true") w2.Config("ParallelProcessing()");
if (A(e, "maxParallelism") is { } dop) w2.Config($"MaxParallelism({dop})");
// StopOnException() defaults to true, so a false attribute has to be printed as
// StopOnException(false) — dropping it loses the setting on the way back to markup.
if (A(e, "stopOnException") is { } s)
w2.Config(bool.Parse(s) ? "StopOnException()" : "StopOnException(false)");
foreach (var child in e.Elements().Where(c => c != tokenizer))
w2.PrintStep(child);
});
},
["multicast"] = (e, w) => w.Scope(e, "Multicast", [], "EndMulticast", body: w2 =>
{
if (A(e, "parallel") == "true") w2.Config("ParallelProcessing()");
if (A(e, "maxParallelism") is { } dop) w2.Config($"MaxParallelism({dop})");
if (A(e, "stopOnException") is { } s)
w2.Config(bool.Parse(s) ? "StopOnException()" : "StopOnException(false)");
w2.PrintSteps(e);
}),
["aggregate"] = (e, w) => w.Scope(e, "Aggregate", Trim(
S6(e, "correlation"),
StrategyArg(A(e, "strategy") ?? ""),
A(e, "completion") is { } c ? XmlCodeWriter.Str(c) : (A(e, "completionSize") ?? A(e, "completionTimeout")) is null ? null : "null",
A(e, "completionSize") ?? (A(e, "completionTimeout") is null ? null : "null"),
A(e, "completionTimeout") is { } t ? XmlCodeWriter.Ts(ParseTs(t)) : null), "EndAggregate", w2 =>
{
// Before the steps: a flag of the aggregate itself, printed as the parser sets it.
if (A(e, "forceCompletionOnStop") is { } force)
w2.Config(bool.Parse(force) ? "ForceCompletionOnStop()" : "ForceCompletionOnStop(false)");
w2.PrintSteps(e);
}),
["loop"] = (e, w) =>
{
var copy = A(e, "copy") == "true";
var share = A(e, "shareScope");
string[] tail = share is not null
? [XmlCodeWriter.Bool(copy), XmlCodeWriter.Bool(bool.Parse(share))]
: copy ? [XmlCodeWriter.Bool(true)] : [];
if (A(e, "count") is { } count)
w.Scope(e, "Loop", [count, .. tail], "EndLoop");
else if (A(e, "expr") is { } expr)
w.Scope(e, "Loop", [XmlCodeWriter.Str(expr), .. tail], "EndLoop");
else
w.Scope(e, "LoopWhile", [XmlCodeWriter.Str(A(e, "while") ?? ""), .. tail], "EndLoop");
},
["throttle"] = (e, w) =>
{
var period = A(e, "period") is { } p ? XmlCodeWriter.Ts(ParseTs(p)) : null;
var max = A(e, "maxPerPeriod") ?? "";
var isConst = int.TryParse(max, NumberStyles.Integer, CultureInfo.InvariantCulture, out _);
if (A(e, "key") is { } key)
{
var extractor = $"ex => {XmlCodeWriter.Expr(key)}.Evaluate(ex)?.ToString() ?? string.Empty";
var maxArg = isConst ? max : $"ex => {XmlCodeWriter.Expr(max)}.Evaluate(ex)";
w.Scope(e, "Throttle", Trim(extractor, maxArg, period), "EndKeyedThrottle", body: w2 =>
{
if (A(e, "rejectOnOverflow") == "true") w2.Config("RejectOnOverflow()");
w2.PrintSteps(e);
});
return;
}
w.Scope(e, "Throttle", isConst ? [max] : Trim(XmlCodeWriter.Str(max), period), "EndThrottle", body: w2 =>
{
if (isConst && period is not null) w2.Config($"Period({period})");
if (A(e, "rejectOnOverflow") == "true") w2.Config("RejectOnOverflow()");
w2.PrintSteps(e);
});
},
["debounce"] = (e, w) => w.Scope(e, "Debounce",
[S6(e, "key"), XmlCodeWriter.Ts(ParseTs(A(e, "quietPeriod") ?? "0:0:1"))], "EndDebounce"),
["idempotentConsumer"] = (e, w) => w.Scope(e, "IdempotentConsumer", Trim(
S6(e, "key"), Reg(A(e, "repository")),
A(e, "skipDuplicate") is { } s ? XmlCodeWriter.Bool(bool.Parse(s)) : null), "EndIdempotentConsumer"),
["resequence"] = (e, w) => w.Scope(e, "Resequence", Trim(
S6(e, "key"),
A(e, "batchSize") ?? (A(e, "timeout") is null ? null : "100"),
A(e, "timeout") is { } t ? XmlCodeWriter.Ts(ParseTs(t)) : null), "EndResequence"),
["transaction"] = (e, w) => w.Scope(e, "Transaction",
A(e, "policy") is { } p ? [PolicyRef(p)] : [], "EndTransaction", body: w2 =>
{
if (A(e, "deadLetterChannel") is not null) w2.Config($"DeadLetterChannel({S6(e, "deadLetterChannel")})");
if (A(e, "retryAttempts") is { } attempts && A(e, "retryDelay") is { } retryDelay)
w2.Config($"Retry({attempts}, {XmlCodeWriter.Ts(ParseTs(retryDelay))})");
w2.PrintSteps(e);
}),
["traced"] = (e, w) => w.Scope(e, "Traced", [S6(e, "name")], "EndTraced"),
// Fully qualified: the generated file does not import redb.Route.Telemetry, and only a non-default target prints.
["spanTag"] = (e, w) => w.Verb(e, "SpanTag", Trim(S6(e, "key"),
A(e, "expr") is { } x ? XmlCodeWriter.Expr(x) : S6(e, "value"),
A(e, "target") is { } t && Enum.Parse(t, true) is var target
&& target != redb.Route.Telemetry.SpanTarget.Enclosing
? $"global::redb.Route.Telemetry.SpanTarget.{target}"
: null)),
["metered"] = (e, w) => w.Scope(e, "Metered", [S6(e, "name")], "EndMetered", body: w2 =>
{
foreach (var child in e.Elements())
{
if (child.Name.LocalName != "tag")
{
w2.PrintStep(child);
continue;
}
if (A(child, "fromHeader") is not null)
w2.Config($"TagFromHeader({S6(child, "name")}, {S6(child, "fromHeader")})");
else
w2.Config($"Tag({S6(child, "name")}, ex => {XmlCodeWriter.Expr(A(child, "expr") ?? "")}.Evaluate(ex))");
}
}),
["replayable"] = (e, w) => w.Scope(e, "Replayable", Trim(
S6(e, "name"), A(e, "exposed") is { } x ? XmlCodeWriter.Bool(bool.Parse(x)) : null), "EndReplayable"),
["threads"] = (e, w) => w.Scope(e, "Threads", [A(e, "poolSize") ?? "1"], "EndThreads", body: w2 =>
{
if (A(e, "maxQueueSize") is { } queue) w2.Config($"MaxQueueSize({queue})");
if (A(e, "enqueueTimeout") is { } enqueue) w2.Config($"EnqueueTimeout({XmlCodeWriter.Ts(ParseTs(enqueue))})");
w2.PrintSteps(e);
}),
// A typed section: the children belong to it, the siblings stay on the parent
// receiver — the statement model expresses that by simply not closing.
["ofType"] = (e, w) => w.Scope(e, "OfType", [XmlCodeWriter.TypeRef(A(e, "type") ?? "")], null),
["onException"] = (e, w) =>
{
var types = (A(e, "exceptions") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
w.Scope(e, "OnException", [.. types.Select(XmlCodeWriter.TypeRef)], "EndOnException",
body: w2 => PrintOnException(e, w2));
},
["intercept"] = (e, w) => PrintIntercept(e, w, "Intercept", []),
["interceptFrom"] = (e, w) => PrintIntercept(e, w, "InterceptFrom",
A(e, "uri") is { } u ? [XmlCodeWriter.Str(u)] : []),
["interceptSendToEndpoint"] = (e, w) => PrintIntercept(e, w, "InterceptSendToEndpoint",
[S6(e, "uri")]),
["onCompletion"] = (e, w) => w.Scope(e, "OnCompletion", [], "EndOnCompletion", body: w2 =>
{
if (A(e, "onCompleteOnly") == "true") w2.Config("OnCompleteOnly()");
if (A(e, "onFailureOnly") == "true") w2.Config("OnFailureOnly()");
if (A(e, "modeBeforeConsumer") == "true") w2.Config("ModeBeforeConsumer()");
if (A(e, "parallelProcessing") == "true") w2.Config("ParallelProcessing()");
if (A(e, "executorService") is { } pool) w2.Config($"ExecutorService({XmlCodeWriter.Str(pool)})");
PrintWhenConditionThenSteps(e, w2);
}),
["tryCatch"] = (e, w) => w.Scope(e, "TryCatch", [], "EndTryCatch", body: w2 =>
{
foreach (var child in e.Elements())
{
switch (child.Name.LocalName)
{
case "try":
w2.PrintSteps(child);
break;
case "catch":
foreach (var typeName in (A(child, "exceptions") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var handler = w2.OpenBranch(child, "Catch", XmlCodeWriter.TypeRef(typeName));
w2.PrintSteps(child);
w2.CloseBranch(handler, "EndCatch");
}
break;
case "finally":
var final = w2.OpenBranch(child, "Finally");
w2.PrintSteps(child);
w2.CloseBranch(final, "EndFinally");
break;
}
}
}),
["circuitBreaker"] = (e, w) => w.Scope(e, "CircuitBreaker", [], "EndCircuitBreaker", body: w2 =>
{
if (A(e, "failureThreshold") is { } ft) w2.Config($"FailureThreshold({ft})");
if (A(e, "resetTimeout") is { } rt) w2.Config($"ResetTimeout({XmlCodeWriter.Ts(ParseTs(rt))})");
if (A(e, "halfOpenMaxCalls") is { } ho) w2.Config($"HalfOpenMaxCalls({ho})");
foreach (var child in e.Elements())
{
if (child.Name.LocalName == "fallback")
{
var fallback = w2.OpenBranch(child, "OnFallback");
w2.PrintSteps(child);
w2.CloseBranch(fallback, "EndFallback");
}
else
{
w2.PrintStep(child);
}
}
}),
["choice"] = (e, w) => w.Scope(e, "Choice", [], "EndChoice", body: w2 =>
{
foreach (var branch in e.Elements())
{
switch (branch.Name.LocalName)
{
case "when":
{
var when = w2.OpenBranch(branch, "When",
A(branch, "predicate") is { } p ? PredicateArg(p) : S6(branch, "expr"));
w2.PrintSteps(branch);
w2.CloseBranch(when);
break;
}
case "otherwise":
{
var otherwise = w2.OpenBranch(branch, "Otherwise");
w2.PrintSteps(branch);
w2.CloseBranch(otherwise);
break;
}
}
}
}),
["scatterGather"] = (e, w) =>
{
var recipients = string.Join(", ", e.Elements()
.Where(c => c.Name.LocalName == "recipient").Select(c => S6(c, "uri")));
w.MapTo(e);
w.Line($"{w.Receiver}.ScatterGather(scatter =>");
w.Line("{");
w.Indent();
w.Line($"scatter.Recipients({recipients});");
if (A(e, "strategy") is { } st) w.Line($"scatter.AggregationStrategy({StrategyArg(st)});");
if (A(e, "timeout") is { } t) w.Line($"scatter.Timeout({XmlCodeWriter.Ts(ParseTs(t))});");
if (A(e, "parallel") is { } p) w.Line($"scatter.ParallelProcessing({XmlCodeWriter.Bool(bool.Parse(p))});");
if (A(e, "maxDop") is { } d) w.Line($"scatter.MaxDegreeOfParallelism({d});");
if (A(e, "stopOnException") is { } s) w.Line($"scatter.StopOnException({XmlCodeWriter.Bool(bool.Parse(s))});");
w.Outdent();
w.Line("});");
},
["loadBalance"] = (e, w) =>
{
var endpoints = e.Elements().Where(c => c.Name.LocalName == "endpoint").ToList();
var uris = string.Join(", ", endpoints.Select(c => S6(c, "uri")));
var strategyCall = A(e, "strategy") switch
{
"roundRobin" => "balance.UseRoundRobin();",
"random" => "balance.UseRandom();",
"failover" => "balance.UseFailover();",
"sticky" => $"balance.UseSticky({S6(e, "key")});",
_ => "balance.UseWeighted(new Dictionary { " +
string.Join(", ", endpoints.Select(c => $"[{S6(c, "uri")}] = {A(c, "weight")}")) + " });",
};
w.MapTo(e);
w.Line($"{w.Receiver}.LoadBalance(balance =>");
w.Line("{");
w.Indent();
w.Line($"balance.Endpoints({uris});");
w.Line(strategyCall);
w.Outdent();
w.Line("});");
},
["saga"] = (e, w) =>
{
w.MapTo(e);
w.Line($"{w.Receiver}.Saga(saga =>");
w.Line("{");
w.Indent();
foreach (var child in e.Elements().Where(c => c.Name.LocalName == "step"))
{
var action = $"Context!.GetFromRegistry({Reg(A(child, "processor"))})!";
var compensate = A(child, "compensate") is { } c
? $", Context!.GetFromRegistry({Reg(c)})!"
: "";
w.Line($"saga.Step({action}{compensate});");
}
w.Outdent();
w.Line("});");
},
["normalize"] = (e, w) =>
{
w.MapTo(e);
w.Line($"{w.Receiver}.Normalize(normalizer =>");
w.Line("{");
w.Indent();
foreach (var child in e.Elements())
{
var transform = $"ex => {XmlCodeWriter.Expr(A(child, "transform") ?? "")}.Evaluate(ex)";
switch (child.Name.LocalName)
{
case "when":
w.Line($"normalizer.When({S6(child, "expr")}, {transform});");
break;
case "whenContentType":
w.Line($"normalizer.WhenContentType({S6(child, "type")}, {transform});");
break;
case "otherwise":
w.Line($"normalizer.Otherwise({transform});");
break;
}
}
w.Outdent();
w.Line("});");
},
};
private static string PolicyRef(string name) => name.ToLowerInvariant() switch
{
"requiresnew" => "TransactionPolicy.RequiresNew",
"suppress" => "TransactionPolicy.Suppress",
"mandatory" => "TransactionPolicy.Mandatory",
_ => "TransactionPolicy.Default",
};
internal static void PrintOnExceptionConfig(XElement e, XmlCodeWriter w)
{
if (A(e, "handled") is { } h) w.Config($"Handled({XmlCodeWriter.Bool(bool.Parse(h))})");
if (A(e, "continued") is { } c) w.Config($"Continued({XmlCodeWriter.Bool(bool.Parse(c))})");
if (A(e, "maximumRedeliveries") is { } m) w.Config($"MaximumRedeliveries({m})");
if (A(e, "redeliveryDelay") is { } d) w.Config($"RedeliveryDelay({XmlCodeWriter.Ts(ParseTs(d))})");
if (A(e, "exponentialBackOff") is { } b) w.Config($"UseExponentialBackOff({XmlCodeWriter.Bool(bool.Parse(b))})");
if (A(e, "backOffMultiplier") is { } bm) w.Config($"BackOffMultiplier({bm})");
if (A(e, "useOriginalBody") == "true") w.Config("UseOriginalBody()");
if (A(e, "logStackTrace") is { } st) w.Config($"LogStackTrace({XmlCodeWriter.Bool(bool.Parse(st))})");
if (A(e, "logExhausted") is { } le) w.Config($"LogExhausted({XmlCodeWriter.Bool(bool.Parse(le))})");
if (A(e, "logHandled") is { } lh) w.Config($"LogHandled({XmlCodeWriter.Bool(bool.Parse(lh))})");
if (A(e, "logContinued") is { } lc) w.Config($"LogContinued({XmlCodeWriter.Bool(bool.Parse(lc))})");
if (A(e, "retryAttemptedLogLevel") is { } ra) w.Config($"RetryAttemptedLogLevel({LevelRef(ra)})");
if (A(e, "retriesExhaustedLogLevel") is { } re) w.Config($"RetriesExhaustedLogLevel({LevelRef(re)})");
foreach (var (attribute, verb) in OnExceptionProcessorRefs)
if (A(e, attribute) is { } reference)
w.Config($"{verb}(Context!.GetFromRegistry({Reg(reference)})!)");
}
/// The handler's bean-reference attributes and the DSL verb each one calls.
private static readonly (string Attribute, string Verb)[] OnExceptionProcessorRefs =
[
("onExceptionOccurred", "OnExceptionOccurred"),
("onRedelivery", "OnRedelivery"),
("onPrepareFailure", "OnPrepareFailure"),
];
private static string LevelRef(string level)
=> $"LogLevel.{Enum.Parse(level, true)}";
///
/// The whole body of an onException: its settings, then its conditions and steps. The
/// conditions are children that are NOT steps, so the walk cannot be a plain PrintSteps.
///
internal static void PrintOnException(XElement e, XmlCodeWriter w)
{
PrintOnExceptionConfig(e, w);
foreach (var child in e.Elements())
{
if (child.Name.LocalName == "when" && !child.Elements().Any())
w.Config($"OnWhen({S6(child, "expr")})");
else if (child.Name.LocalName == "retryWhile" && !child.Elements().Any())
w.Config($"RetryWhile({S6(child, "expr")})");
else
w.PrintStep(child);
}
}
private static void PrintIntercept(XElement e, XmlCodeWriter w, string verb, string[] args)
=> w.Scope(e, verb, args, "EndIntercept", body: w2 =>
{
if (A(e, "skipSendToOriginalEndpoint") == "true") w2.Config("SkipSendToOriginalEndpoint()");
PrintWhenConditionThenSteps(e, w2);
});
internal static void PrintWhenConditionThenSteps(XElement e, XmlCodeWriter w)
{
foreach (var child in e.Elements())
{
if (child.Name.LocalName == "when" && !child.Elements().Any())
w.Config($"When({S6(child, "expr")})");
else
w.PrintStep(child);
}
}
}
Path: redb-route/redb.Route.Xml/CoreElements/CoreContributions.Specs.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/CoreElements/CoreContributions.Specs.cs
----
using redb.Route.Xslt;
namespace redb.Route.Xml.CoreElements;
internal static partial class CoreContributions
{
// ── The public shapes of the core elements ──────────────────────────────
// One table, three consumers: parser hints, the XSD generator, the catalog. A test pins
// every registered core contribution to an entry here, so the shapes cannot drift from the
// parse code silently.
private static AttributeSpec S(string name, bool required = false) => new(name, AttributeType.String, required);
private static AttributeSpec E(string name, bool required = false) => new(name, AttributeType.Expression, required);
/// An expression read as a condition — a predicate, not a value.
private static AttributeSpec C(string name, bool required = false)
=> new(name, AttributeType.Expression, required) { Condition = true };
private static AttributeSpec U(string name, bool required = false) => new(name, AttributeType.Uri, required);
private static AttributeSpec R(string name, bool required = false) => new(name, AttributeType.Reference, required);
/// A CLR type as the markup names it: Full.Name, Assembly .
private static string Named() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}";
private static AttributeSpec T(string name, bool required = false) => new(name, AttributeType.TypeName, required);
private static AttributeSpec TL(string name, bool required = false) => new(name, AttributeType.TypeNameList, required);
private static AttributeSpec B(string name) => new(name, AttributeType.Bool);
private static AttributeSpec I(string name, bool required = false) => new(name, AttributeType.Int, required);
private static AttributeSpec L(string name) => new(name, AttributeType.Long);
private static AttributeSpec F(string name) => new(name, AttributeType.Double);
private static AttributeSpec D(string name, bool required = false) => new(name, AttributeType.Duration, required);
private static AttributeSpec En(string name, IReadOnlyList values, bool required = false)
=> new(name, AttributeType.Enum, required, values);
private static readonly string[] LogLevels =
["Trace", "Debug", "Information", "Warning", "Error", "Critical"];
private static readonly string[] TransactionPolicies =
["default", "requiresNew", "suppress", "mandatory"];
private static readonly string[] LoadBalanceStrategies =
["roundRobin", "random", "failover", "sticky", "weighted"];
private static ElementSpec AddressLeaf(string name, params AttributeSpec[] extra)
=> new(name, XmlElementKind.Step, [U("uri"), .. extra], [], TakesEndpoint: true);
private static readonly ElementSpec WhenCondition =
ElementSpec.Child("when", allowsSteps: false, C("expr", required: true));
/// The spec for a core element name; opaque for a name the table misses (test-guarded).
internal static ElementSpec SpecFor(string name, XmlElementKind kind)
=> Specs.TryGetValue(name, out var spec)
? spec
: new ElementSpec(name, kind, [], [], AllowsSteps: kind is XmlElementKind.Scope);
internal static readonly IReadOnlyDictionary Specs =
new Dictionary