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(StringComparer.Ordinal) { // ── leaves ────────────────────────────────────────────────────── ["to"] = AddressLeaf("to"), // The step form of . ref= or beanType=, method=, and any further // attribute is a bean: option (a bean property), as on the structured child. ["bean"] = ElementSpec.Leaf("bean", R("ref"), T("beanType"), S("method")) with { OpenAttributes = true }, ["toD"] = AddressLeaf("toD"), ["wireTap"] = AddressLeaf("wireTap", S("executorService")), ["enrich"] = AddressLeaf("enrich", S("strategy")), ["pollEnrich"] = AddressLeaf("pollEnrich", S("strategy"), D("timeout")), ["setHeader"] = ElementSpec.Leaf("setHeader", S("name", required: true), S("value"), E("expr")), ["setProperty"] = ElementSpec.Leaf("setProperty", S("name", required: true), S("value"), E("expr")), ["setBody"] = ElementSpec.Leaf("setBody", S("value"), E("expr")), ["transform"] = ElementSpec.Leaf("transform", E("expr", required: true)), ["removeHeader"] = ElementSpec.Leaf("removeHeader", S("name", required: true)), ["removeProperty"] = ElementSpec.Leaf("removeProperty", S("name", required: true)), ["removeBody"] = ElementSpec.Leaf("removeBody"), ["addAttachment"] = ElementSpec.Leaf("addAttachment", S("name"), E("expr"), B("fromBody"), S("file"), E("fileExpr"), S("fileName"), E("fileNameExpr"), S("contentType")), ["removeAttachment"] = ElementSpec.Leaf("removeAttachment", S("name", required: true)), ["removeAttachments"] = ElementSpec.Leaf("removeAttachments"), ["removeHeaders"] = ElementSpec.Leaf("removeHeaders", S("pattern", required: true), S("except")), ["removeProperties"] = ElementSpec.Leaf("removeProperties", S("pattern", required: true), S("except")), ["setHeaders"] = new("setHeaders", XmlElementKind.Step, [], [ElementSpec.Child("header", false, S("name", required: true), S("value"), E("expr"))]), ["setProperties"] = new("setProperties", XmlElementKind.Step, [], [ElementSpec.Child("property", false, S("name", required: true), S("value"), E("expr"))]), ["log"] = new("log", XmlElementKind.Step, [En("level", LogLevels), B("showRouteId")], [ new ElementSpec("message", XmlElementKind.ConfigChild, [], [], AllowsTextContent: true), ElementSpec.Child("header", false, S("name", required: true)), ElementSpec.Child("property", false, S("name", required: true)), ], AllowsTextContent: true), ["delay"] = ElementSpec.Leaf("delay", D("duration"), E("expr")), ["stop"] = ElementSpec.Leaf("stop") with { Terminal = true }, ["throwException"] = ElementSpec.Leaf("throwException", T("type", required: true), S("message")) with { Terminal = true }, ["convertBody"] = ElementSpec.Leaf("convertBody", T("type", required: true)), ["validate"] = ElementSpec.Leaf("validate", C("expr", required: true), S("message"), B("throwOnFailure")), ["sort"] = ElementSpec.Leaf("sort", E("expr", required: true), E("by"), B("descending")), ["sample"] = ElementSpec.Leaf("sample", L("messageFrequency"), D("period")), ["streamCaching"] = ElementSpec.Leaf("streamCaching", L("spoolThreshold")), ["messageHistory"] = ElementSpec.Leaf("messageHistory", B("value")), ["validateJsonSchema"] = new("validateJsonSchema", XmlElementKind.Step, [S("file"), B("throwOnFailure")], [], AllowsTextContent: true), ["validateXsd"] = new("validateXsd", XmlElementKind.Step, [S("file"), S("targetNamespace"), S("schemaRoot"), B("throwOnFailure")], [], AllowsTextContent: true), ["xslt"] = new("xslt", XmlElementKind.Step, [S("file"), En("output", Enum.GetNames()), B("failOnNullBody"), B("allowTemplateFromHeader")], [], AllowsTextContent: true), ["marshal"] = ElementSpec.Leaf("marshal", S("format"), T("type")) with { OpenAttributes = true }, ["unmarshal"] = ElementSpec.Leaf("unmarshal", S("format"), T("type"), T("target", required: true)) with { OpenAttributes = true }, ["controlBus"] = ElementSpec.Leaf("controlBus", En("action", Enum.GetNames(), required: true), S("routeId", required: true), B("async")), ["recipientList"] = ElementSpec.Leaf("recipientList", E("expr", required: true), S("delimiter"), B("parallel"), B("stopOnException"), S("strategy")), ["dynamicRouter"] = ElementSpec.Leaf("dynamicRouter", E("expr", required: true)), ["routingSlip"] = ElementSpec.Leaf("routingSlip", E("expr", required: true), S("delimiter"), B("ignoreInvalidEndpoints")), ["claimCheck"] = ElementSpec.Leaf("claimCheck", En("operation", Enum.GetNames(), required: true), E("key"), D("ttl"), R("repository") with { References = Named() }), ["beginTransaction"] = ElementSpec.Leaf("beginTransaction", En("policy", TransactionPolicies)), ["commitTransaction"] = ElementSpec.Leaf("commitTransaction"), ["rollbackTransaction"] = ElementSpec.Leaf("rollbackTransaction"), // Camel markRollbackOnly(): marks the exchange and stops the route (119e76d7). ["rollbackAll"] = ElementSpec.Leaf("rollbackAll") with { Terminal = true }, ["exceptionHandled"] = ElementSpec.Leaf("exceptionHandled"), ["routePolicy"] = ElementSpec.Leaf("routePolicy", R("ref", required: true)), // ── scopes ────────────────────────────────────────────────────── ["filter"] = ElementSpec.Scope("filter", C("expr"), R("predicate")), ["split"] = new("split", XmlElementKind.Scope, [E("expr"), B("parallel"), I("maxParallelism"), B("stopOnException")], [ ElementSpec.Child("tokenizeLines", false, S("separator"), B("skipEmpty")), ElementSpec.Child("tokenizeXml", false, S("element", required: true), S("inheritNamespaceFrom")), ElementSpec.Child("tokenizeJsonArray", false), ], AllowsSteps: true), ["multicast"] = ElementSpec.Scope("multicast", B("parallel"), I("maxParallelism"), B("stopOnException")), ["aggregate"] = ElementSpec.Scope("aggregate", E("correlation", required: true), S("strategy", required: true), E("completion"), I("completionSize"), D("completionTimeout"), B("forceCompletionOnStop")), ["loop"] = ElementSpec.Scope("loop", I("count"), E("expr"), C("while"), B("copy"), B("shareScope")), ["throttle"] = ElementSpec.Scope("throttle", E("maxPerPeriod", required: true), D("period"), E("key"), B("rejectOnOverflow")), ["debounce"] = ElementSpec.Scope("debounce", E("key", required: true), D("quietPeriod", required: true)), ["idempotentConsumer"] = ElementSpec.Scope("idempotentConsumer", E("key", required: true), R("repository", required: true) with { References = Named() }, B("skipDuplicate")), ["resequence"] = ElementSpec.Scope("resequence", E("key", required: true), I("batchSize"), D("timeout")), ["transaction"] = ElementSpec.Scope("transaction", En("policy", TransactionPolicies), U("deadLetterChannel"), I("retryAttempts"), D("retryDelay")), ["traced"] = ElementSpec.Scope("traced", S("name", required: true)), // context.xml only: the context's dead letter channel (DeadLetterChannelContextContribution). ["dataFormat"] = new("dataFormat", XmlElementKind.ContextLevel, [T("type", required: true), S("name")], [], AllowsSteps: false) { OpenAttributes = true }, ["deadLetterChannel"] = new("deadLetterChannel", XmlElementKind.ContextLevel, [U("uri", required: true)], [], AllowsSteps: false), // context.xml only: a C# route builder of the context (RouteBuilderContextContribution). ["routeBuilder"] = new("routeBuilder", XmlElementKind.ContextLevel, [T("type", required: true)], [], AllowsSteps: false), ["spanTag"] = ElementSpec.Leaf("spanTag", S("key", required: true), S("value"), E("expr"), En("target", Enum.GetNames())), ["metered"] = new("metered", XmlElementKind.Scope, [S("name", required: true)], [ElementSpec.Child("tag", allowsSteps: false, S("name", required: true), S("fromHeader"), E("expr"))], AllowsSteps: true), ["replayable"] = ElementSpec.Scope("replayable", S("name", required: true), B("exposed")), ["threads"] = ElementSpec.Scope("threads", I("poolSize", required: true), I("maxQueueSize"), D("enqueueTimeout")), ["ofType"] = ElementSpec.Scope("ofType", T("type", required: true)), ["circuitBreaker"] = new("circuitBreaker", XmlElementKind.Scope, [I("failureThreshold"), D("resetTimeout"), I("halfOpenMaxCalls")], [ElementSpec.Child("fallback", allowsSteps: true)], AllowsSteps: true), ["tryCatch"] = new("tryCatch", XmlElementKind.Scope, [], [ ElementSpec.Child("try", allowsSteps: true), ElementSpec.Child("catch", allowsSteps: true, TL("exceptions", required: true)), ElementSpec.Child("finally", allowsSteps: true), ]), ["onException"] = new("onException", XmlElementKind.Scope, [ TL("exceptions", required: true), B("handled"), B("continued"), I("maximumRedeliveries"), D("redeliveryDelay"), B("exponentialBackOff"), F("backOffMultiplier"), B("useOriginalBody"), B("logStackTrace"), B("logExhausted"), B("logHandled"), B("logContinued"), En("retryAttemptedLogLevel", LogLevels), En("retriesExhaustedLogLevel", LogLevels), R("onExceptionOccurred"), R("onRedelivery"), R("onPrepareFailure"), ], [WhenCondition, ElementSpec.Child("retryWhile", allowsSteps: false, C("expr", required: true))], AllowsSteps: true), ["intercept"] = new("intercept", XmlElementKind.Scope, [], [WhenCondition], AllowsSteps: true), ["interceptFrom"] = new("interceptFrom", XmlElementKind.Scope, [U("uri")], [WhenCondition], AllowsSteps: true), ["interceptSendToEndpoint"] = new("interceptSendToEndpoint", XmlElementKind.Scope, [U("uri", required: true), B("skipSendToOriginalEndpoint")], [WhenCondition], AllowsSteps: true), ["onCompletion"] = new("onCompletion", XmlElementKind.Scope, [B("onCompleteOnly"), B("onFailureOnly"), B("modeBeforeConsumer"), B("parallelProcessing"), S("executorService")], [WhenCondition], AllowsSteps: true), ["scatterGather"] = new("scatterGather", XmlElementKind.Step, [D("timeout"), B("parallel"), I("maxDop"), B("stopOnException"), S("strategy")], [ElementSpec.Child("recipient", false, U("uri", required: true))]), ["loadBalance"] = new("loadBalance", XmlElementKind.Step, [En("strategy", LoadBalanceStrategies, required: true), E("key")], [ElementSpec.Child("endpoint", false, U("uri", required: true), I("weight"))]), ["normalize"] = new("normalize", XmlElementKind.Step, [], [ ElementSpec.Child("when", false, C("expr", required: true), E("transform", required: true)), ElementSpec.Child("whenContentType", false, S("type", required: true), E("transform", required: true)), ElementSpec.Child("otherwise", false, E("transform", required: true)), ]), ["saga"] = new("saga", XmlElementKind.Step, [], [ElementSpec.Child("step", false, R("processor", required: true), R("compensate"))]), // ── branching ─────────────────────────────────────────────────── ["choice"] = new("choice", XmlElementKind.Branching, [], [ ElementSpec.Child("when", allowsSteps: true, C("expr"), R("predicate")), ElementSpec.Child("otherwise", allowsSteps: true), ]), }; } Path: redb-route/redb.Route.Xml/CoreElements/CoreContributions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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.cs ---- using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Xml.CoreElements; /// /// The core element set — every contribution is a facade over one DSL verb. This part /// holds the first vertical slice; the rest of the catalog lives in /// CoreContributions.Catalog.cs, all through the same registry. /// internal static partial class CoreContributions { internal static IReadOnlyList All { get; } = [.. Basic(), .. Catalog(), DeadLetterChannelContextContribution.Instance, DataFormatContextContribution.Instance, RouteBuilderContextContribution.Instance]; /// /// A value= with {{key}} placeholders as the expression that resolves them through the route context /// (as an endpoint URI is resolved), or null for a plain literal, which stays a constant. /// private static IExpression? FromConfiguration(string value) => Route.Core.PropertyPlaceholderResolver.HasPlaceholder(value) ? new PlaceholderExpression(value) : null; private static IXmlElementContribution[] Basic() => [ // ── leaves ────────────────────────────────────────────────────────── Step("to", (e, cur, ctx) => { var uri = StructuredEndpoint.Resolve(e, ctx, out var position); if (uri is null) return cur; ctx.NoteEndpointUri(position, uri); return cur.To(uri); }), // The step form (amended 2026-11-05): without the wrapper, one normalization into // the bean: URI. A root is a declaration and never reaches here (the section loaders take it). Step("bean", (e, cur, ctx) => { var uri = StructuredEndpoint.ResolveBeanStep(e, ctx); if (uri is null) return cur; ctx.NoteEndpointUri(e, uri); return cur.To(uri); }), Step("toD", (e, cur, ctx) => { var uri = StructuredEndpoint.Resolve(e, ctx, out _); return uri is null ? cur : cur.ToD(uri); }), Step("setHeader", (e, cur, ctx) => { var name = ctx.RequiredAttr(e, "name"); var pick = ctx.ExactlyOneOf(e, "value", "expr"); if (name is null || pick is null) return cur; return pick.Value.Name == "value" ? FromConfiguration(pick.Value.Value) is { } configured ? cur.SetHeader(name, configured) : cur.SetHeader(name, pick.Value.Value) : cur.SetHeader(name, new StringExpression(pick.Value.Value)); }), Step("setProperty", (e, cur, ctx) => { var name = ctx.RequiredAttr(e, "name"); var pick = ctx.ExactlyOneOf(e, "value", "expr"); if (name is null || pick is null) return cur; return pick.Value.Name == "value" ? FromConfiguration(pick.Value.Value) is { } configured ? cur.SetProperty(name, configured) : cur.SetProperty(name, pick.Value.Value) : cur.SetProperty(name, new StringExpression(pick.Value.Value)); }), Step("setBody", (e, cur, ctx) => { var pick = ctx.ExactlyOneOf(e, "value", "expr"); if (pick is null) return cur; return pick.Value.Name == "value" ? FromConfiguration(pick.Value.Value) is { } configured ? cur.SetBody(configured) : cur.SetBody(pick.Value.Value) : cur.SetBody(new StringExpression(pick.Value.Value)); }), Step("transform", (e, cur, ctx) => { var expr = ctx.RequiredAttr(e, "expr"); return expr is null ? cur : cur.Transform(new StringExpression(expr)); }), Step("removeHeader", (e, cur, ctx) => { var name = ctx.RequiredAttr(e, "name"); return name is null ? cur : cur.RemoveHeader(name); }), Step("removeProperty", (e, cur, ctx) => { var name = ctx.RequiredAttr(e, "name"); return name is null ? cur : cur.RemoveProperty(name); }), Step("removeBody", (e, cur, ctx) => cur.RemoveBody()), // One element, four content sources: an expression, the body, a file path literal or a file path expression. // As everywhere in the format, a literal and an expression are separate attributes (fileName / fileNameExpr, // file / fileExpr): the attribute used decides the meaning, never the text. Step("addAttachment", (e, cur, ctx) => { var sources = new[] { "expr", "fromBody", "file", "fileExpr" }.Where(a => ctx.Attr(e, a) is not null).ToArray(); if (sources.Length != 1) { ctx.AddError(e, " takes exactly one of 'expr', 'fromBody', 'file' or 'fileExpr'."); return cur; } if (ctx.Attr(e, "fileName") is not null && ctx.Attr(e, "fileNameExpr") is not null) { ctx.AddError(e, " takes 'fileName' or 'fileNameExpr', not both."); return cur; } var fileName = ctx.Attr(e, "fileName"); IExpression? fileNameExpr = ctx.Attr(e, "fileNameExpr") is { } fx ? new StringExpression(fx) : null; var contentType = ctx.Attr(e, "contentType"); switch (sources[0]) { case "file" or "fileExpr": if (fileName is not null || fileNameExpr is not null) { ctx.AddError(e, " from a file takes its file name from the file; use 'name' to name the attachment."); return cur; } return sources[0] == "file" ? cur.AddAttachmentFromFile(ctx.Attr(e, "file")!, ctx.Attr(e, "name"), contentType) : cur.AddAttachmentFromFile(new StringExpression(ctx.Attr(e, "fileExpr")!), ctx.Attr(e, "name"), contentType); case "fromBody": { if (ctx.Convert(e, "fromBody") is not true) { ctx.AddError(e, " must be 'true'; leave the attribute out otherwise."); return cur; } var name = ctx.RequiredAttr(e, "name"); if (name is null) return cur; return fileNameExpr is not null ? cur.AddAttachmentFromBody(name, fileNameExpr, contentType) : cur.AddAttachmentFromBody(name, fileName, contentType); } default: { var name = ctx.RequiredAttr(e, "name"); if (name is null) return cur; var content = new StringExpression(ctx.Attr(e, "expr")!); return fileNameExpr is not null ? cur.AddAttachment(name, content, fileNameExpr, contentType) : cur.AddAttachment(name, content, fileName, contentType); } } }), Step("removeAttachment", (e, cur, ctx) => { var name = ctx.RequiredAttr(e, "name"); return name is null ? cur : cur.RemoveAttachment(name); }), Step("removeAttachments", (e, cur, ctx) => cur.RemoveAttachments()), Step("removeHeaders", (e, cur, ctx) => { var pattern = ctx.RequiredAttr(e, "pattern"); if (pattern is null) return cur; var except = SplitList(ctx.Attr(e, "except")); return cur.RemoveHeaders(pattern, except); }), Step("removeProperties", (e, cur, ctx) => { var pattern = ctx.RequiredAttr(e, "pattern"); if (pattern is null) return cur; var except = SplitList(ctx.Attr(e, "except")); return cur.RemoveProperties(pattern, except); }), Step("log", (e, cur, ctx) => { // Children mean the rich scope, plain text means the simple form; both — error. var text = string.Concat(e.Nodes().OfType().Select(t => t.Value)); var children = e.Elements().ToList(); if (children.Count > 0 && !string.IsNullOrWhiteSpace(text)) { ctx.AddError(e, " carries either message text or child elements, not both."); return cur; } var level = Microsoft.Extensions.Logging.LogLevel.Information; if (ctx.Attr(e, "level") is { } levelName && !Enum.TryParse(levelName, ignoreCase: true, out level)) { ctx.AddError(e, $"'{levelName}' is not a log level (Trace, Debug, Information, Warning, Error, Critical)."); return cur; } if (children.Count == 0) { if (string.IsNullOrWhiteSpace(text)) { ctx.AddError(e, " needs message text or /
/ children."); return cur; } return cur.Log(text.Trim(), level); } var rich = cur.Log(level); if (ctx.Convert(e, "showRouteId") == true) rich.ShowRouteId(); foreach (var child in children) { switch (child.Name.LocalName) { case "message": rich.Message(child.Value); break; case "header": if (ctx.RequiredAttr(child, "name") is { } header) rich.Header(header); break; case "property": if (ctx.RequiredAttr(child, "name") is { } property) rich.Property(property); break; default: ctx.AddError(child, $" accepts ,
and children, found <{child.Name.LocalName}>."); break; } } return rich.EndLog(); }), Step("delay", (e, cur, ctx) => { var pick = ctx.ExactlyOneOf(e, "duration", "expr"); if (pick is null) return cur; if (pick.Value.Name == "expr") return cur.Delay(pick.Value.Value); if (TimeSpan.TryParse(pick.Value.Value, System.Globalization.CultureInfo.InvariantCulture, out var duration)) return cur.Delay(duration); ctx.AddError(e, $"'{pick.Value.Value}' is not a TimeSpan (use hh:mm:ss or hh:mm:ss.fff)."); return cur; }), Step("stop", (e, cur, ctx) => cur.Stop()), Step("throwException", (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; if (!typeof(Exception).IsAssignableFrom(type)) { ctx.AddError(e, $"'{typeName}' is not an Exception type."); return cur; } return cur.ThrowException(type, ctx.Attr(e, "message") ?? "error"); }), Step("convertBody", (e, cur, ctx) => { var typeName = ctx.RequiredAttr(e, "type"); if (typeName is null) return cur; var type = ResolveType(typeName, e, ctx); return type is null ? cur : cur.ConvertBody(type); }), Step("wireTap", (e, cur, ctx) => { var uri = StructuredEndpoint.Resolve(e, ctx, out var position); if (uri is null) return cur; ctx.NoteEndpointUri(position, uri); return cur.WireTap(uri, ctx.Attr(e, "executorService")); }), Step("validate", (e, cur, ctx) => { var expr = ctx.RequiredAttr(e, "expr"); if (expr is null) return cur; var throwOnFailure = ctx.Convert(e, "throwOnFailure") ?? true; return cur.Validate(expr, ctx.Attr(e, "message") ?? "Validation failed", throwOnFailure); }), // ── scopes ────────────────────────────────────────────────────────── new DelegateContribution("filter", XmlElementKind.Scope, (e, cur, ctx) => { var pick = ctx.ExactlyOneOf(e, "expr", "predicate"); if (pick is null) return cur; var scope = pick.Value.Name == "expr" ? cur.Filter(pick.Value.Value) : cur.Filter(ResolvePredicate(pick.Value.Value, e, ctx) ?? AlwaysFalse.Instance); ctx.ParseSteps(e, scope); return scope.EndFilter(); }), new DelegateContribution("split", XmlElementKind.Scope, (e, cur, ctx) => { // The source is the expr attribute or exactly one tokenizer child. var expr = ctx.Attr(e, "expr"); var tokenizers = e.Elements().Where(c => c.Name.LocalName is "tokenizeLines" or "tokenizeXml" or "tokenizeJsonArray").ToList(); if ((expr is null) == (tokenizers.Count == 0) || tokenizers.Count > 1) { ctx.AddError(e, " takes either expr or exactly one tokenizer child " + "(, , )."); return cur; } var scope = expr is not null ? cur.Split(new StringExpression(expr)) : cur.Split(Tokenizer(tokenizers[0], ctx)); 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: the default is true, so a false value must reach the // definition instead of being dropped (as scatterGather already does). if (ctx.Convert(e, "stopOnException") is { } stop) scope.StopOnException(stop); IRouteDefinition inner = scope; foreach (var child in e.Elements().Except(tokenizers)) inner = ctx.ParseStep(child, inner); return scope.EndSplit(); }), // ── branching ─────────────────────────────────────────────────────── new DelegateContribution("choice", XmlElementKind.Branching, (e, cur, ctx) => { var choice = cur.Choice(); foreach (var branch in e.Elements()) { switch (branch.Name.LocalName) { case "when": { var pick = ctx.ExactlyOneOf(branch, "expr", "predicate"); if (pick is null) continue; var when = pick.Value.Name == "expr" ? choice.When(pick.Value.Value) : choice.When(ResolvePredicate(pick.Value.Value, branch, ctx) ?? AlwaysFalse.Instance); ctx.ApplyBranchIdentity(branch, when); ctx.ParseSteps(branch, when); break; } case "otherwise": { var otherwise = choice.Otherwise(); ctx.ApplyBranchIdentity(branch, otherwise); ctx.ParseSteps(branch, otherwise); break; } default: ctx.AddError(branch, $" accepts only and , found <{branch.Name.LocalName}>."); break; } } return choice.EndChoice(); }), ]; // ── helpers ───────────────────────────────────────────────────────────── private static DelegateContribution Step( string name, Func apply) => new(name, XmlElementKind.Step, apply); private static Func> Tokenizer(XElement t, XmlParseContext ctx) { switch (t.Name.LocalName) { case "tokenizeLines": { var separator = ctx.Attr(t, "separator") ?? "\n"; var skipEmpty = ctx.Convert(t, "skipEmpty") ?? false; return exchange => redb.Route.Expressions.Tokenizers.LineTokenizer .Tokenize(exchange.In.Body, separator, skipEmpty); } case "tokenizeXml": { var elementName = ctx.RequiredAttr(t, "element") ?? ""; var inheritFrom = ctx.Attr(t, "inheritNamespaceFrom"); return exchange => redb.Route.Expressions.Tokenizers.XmlTokenizer .Tokenize(exchange.In.Body, elementName, inheritFrom); } default: return exchange => redb.Route.Expressions.Tokenizers.JsonArrayTokenizer .Tokenize(exchange.In.Body); } } private static string[] SplitList(string? csv) => string.IsNullOrWhiteSpace(csv) ? [] : csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); private static Type? ResolveType(string typeName, XElement e, XmlParseContext ctx) { var resolver = ctx.RouteContext.GetService() ?? redb.Route.Components.Bean.DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(typeName); if (type is null) ctx.AddError(e, $"type '{typeName}' was not found in the loaded assemblies."); return type; } private static IPredicate? ResolvePredicate(string reference, XElement e, XmlParseContext ctx) { var predicate = ctx.RouteContext.GetFromRegistry(reference); if (predicate is null) ctx.AddError(e, $"predicate '{reference}' is not in the context registry (expected an IPredicate)."); return predicate; } /// Substitute for a missing registry predicate, so the pass can continue collecting errors. private sealed class AlwaysFalse : IPredicate { public static readonly AlwaysFalse Instance = new(); public bool Matches(IExchange exchange) => false; } /// A contribution defined by a delegate — the shape every core element uses. internal sealed class DelegateContribution( string name, XmlElementKind kind, Func apply) : IXmlElementContribution { public string Name { get; } = name; public XmlElementKind Kind { get; } = kind; public ElementSpec Spec => SpecFor(Name, Kind); public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) => apply(element, current, context); public void Print(XElement element, XmlCodeWriter code) { if (!Printers.TryGetValue(Name, out var printer)) throw new NotSupportedException($"core element <{Name}> has no printer — the print face is missing."); printer(element, code); } } } Path: redb-route/redb.Route.Xml/CoreElements/DataFormatContextContribution.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/DataFormatContextContribution.cs ---- using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Extensions; namespace redb.Route.Xml.CoreElements; /// /// <dataFormat type="…" name="csv" delimiter=";"/> in context.xml: registers a data format on the /// context, as context.AddDataFormat(new CsvDataFormat(...)) does in code, so <marshal format="…"/> and /// content-type dispatch find it. The type is the format's serializer (an IMessageSerializer); the other attributes /// set its options, as on the per-step <marshal type="…"> form. The format answers to its own content type /// and media types, and to each name in name (comma-separated). /// internal sealed class DataFormatContextContribution : IXmlContextContribution { /// The one instance, in the core registry. internal static DataFormatContextContribution Instance { get; } = new(); // Not constructible from outside: a host that discovers package contributions by scanning assemblies for // IXmlElementContribution types with a parameterless constructor (redb.Tsak) must not register a core element twice. private DataFormatContextContribution() { } private static readonly string[] OwnAttributes = ["type", "name", "id", "description"]; /// public string Name => "dataFormat"; /// public XmlElementKind Kind => XmlElementKind.ContextLevel; /// public ElementSpec Spec => CoreContributions.Specs[Name]; /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { context.AddError(element, " registers a format for the whole context — put it inside , not in a route."); return current; } /// public void ApplyContext(XElement element, Core.RouteContext context, XmlParseContext parseContext) { if (parseContext.RequiredAttr(element, "type") is not { } typeName) return; var options = element.Attributes().Where(a => !OwnAttributes.Contains(a.Name.LocalName)).ToList(); if (CoreContributions.CreateSerializer(element, parseContext, typeName, options) is not { } serializer) return; var names = (parseContext.Attr(element, "name") ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); context.AddDataFormat(serializer, names); } } Path: redb-route/redb.Route.Xml/CoreElements/DeadLetterChannelContextContribution.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/DeadLetterChannelContextContribution.cs ---- using System.Xml.Linq; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.ErrorHandling; namespace redb.Route.Xml.CoreElements; /// /// <deadLetterChannel uri="direct://errors"/> in context.xml: the context's dead letter channel /// (), Apache Camel's errorHandlerRef on <camelContext>. Every route /// of the context sends to it a failure no OnException took. /// internal sealed class DeadLetterChannelContextContribution : IXmlContextContribution { /// The one instance, in the core registry. internal static DeadLetterChannelContextContribution Instance { get; } = new(); // Not constructible from outside: a host that discovers package contributions by scanning assemblies for // IXmlElementContribution types with a parameterless constructor (redb.Tsak) must not register a core element twice. private DeadLetterChannelContextContribution() { } /// public string Name => "deadLetterChannel"; /// public XmlElementKind Kind => XmlElementKind.ContextLevel; /// public ElementSpec Spec => CoreContributions.Specs[Name]; /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { context.AddError(element, " is the context's error handler — put it inside , not in a route."); return current; } /// public void ApplyContext(XElement element, Core.RouteContext context, XmlParseContext parseContext) { if (parseContext.RequiredAttr(element, "uri") is not { } uri) return; if (context.ErrorHandler is not null) { parseContext.AddError(element, "the context already has an error handler; would replace it — declare one of them."); return; } context.ErrorHandler = new DeadLetterErrorHandler(context, uri, context.GetService()?.CreateLogger()); } } Path: redb-route/redb.Route.Xml/CoreElements/RouteBuilderContextContribution.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/RouteBuilderContextContribution.cs ---- using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Core; namespace redb.Route.Xml.CoreElements; /// /// <routeBuilder type="Orders.Routes.OrdersRoute, Orders"/> in context.xml: adds a C# route builder to the /// context, as context.AddRoutes(new OrdersRoute()) does in code, so one package carries routes in markup and in the /// DSL, in one context. The type resolves through the context's type resolver, the same lookup as <bean type> /// (in a Tsak package: the package's own assemblies first). It must be a public, non-abstract class deriving from /// with a public parameterless constructor, the rule of AddRoutes(Assembly[]). /// internal sealed class RouteBuilderContextContribution : IXmlContextContribution { /// The one instance, in the core registry. internal static RouteBuilderContextContribution Instance { get; } = new(); // Not constructible from outside: a host that discovers package contributions by scanning assemblies for // IXmlElementContribution types with a parameterless constructor (redb.Tsak) must not register a core element twice. private RouteBuilderContextContribution() { } /// public string Name => "routeBuilder"; /// public XmlElementKind Kind => XmlElementKind.ContextLevel; /// public ElementSpec Spec => CoreContributions.Specs[Name]; /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { context.AddError(element, " adds C# routes to the whole context — put it inside , not in a route."); return current; } /// public void ApplyContext(XElement element, RouteContext context, XmlParseContext parseContext) { if (parseContext.RequiredAttr(element, "type") is not { } typeName) return; var resolver = context.GetService() ?? DefaultBeanTypeResolver.Instance; if (resolver.Resolve(typeName) is not { } type) { parseContext.AddError(element, $": type '{typeName}' was not found in the loaded assemblies."); return; } if (Refusal(type) is { } reason) { parseContext.AddError(element, $": '{typeName}' {reason}"); return; } // The same builder twice compiles its routes twice and fails only at Start, on a duplicate route id. if (element.ElementsBeforeSelf().Any(e => e.Name == element.Name && e.Attribute("type")?.Value is { Length: > 0 } earlier && resolver.Resolve(earlier) == type) || context.RouteBuilders.Any(b => b.GetType() == type)) { parseContext.AddError(element, $": '{type.FullName}' is already added to this context."); return; } RouteBuilder builder; try { builder = (RouteBuilder)Activator.CreateInstance(type)!; } catch (System.Reflection.TargetInvocationException ex) { parseContext.AddError(element, $": '{typeName}' threw from its constructor: {(ex.InnerException ?? ex).Message}"); return; } // Added once the whole document is valid: a context.xml with an error further down adds no routes (in Tsak the // module faults, and its routes must not run in the context it shares). parseContext.WhenValid(() => context.AddRoutes(builder)); } /// /// Why cannot be a markup route builder, or null when it can. The base type is matched by full /// name, so the packaging check can hold a type loaded in its own load context against the same rule. /// internal static string? Refusal(Type type) { if (!DerivesFrom(type, typeof(RouteBuilder).FullName!)) return $"does not derive from {typeof(RouteBuilder).FullName}."; if (type.FullName == typeof(InlineRouteBuilder).FullName) return "is the inline builder of AddRoutes(Action), not a route builder of its own."; if (!type.IsVisible) return "is not public."; if (type.IsAbstract) return "is abstract."; if (type.ContainsGenericParameters) return "is an open generic type."; if (type.GetConstructor(Type.EmptyTypes) is null) return "has no public parameterless constructor; a builder named in markup is created without arguments. " + "Read configuration through {{key}} properties and reach beans by their registry name."; return null; } private static bool DerivesFrom(Type type, string baseFullName) { for (var current = type.BaseType; current is not null; current = current.BaseType) { if (current.FullName == baseFullName) return true; } return false; } } Path: redb-route/redb.Route.Xml/ElementRegistry.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/ElementRegistry.cs ---- namespace redb.Route.Xml; /// /// The element registry: one name — one contribution, the union of the core set and the /// package extensions of a concrete installation. A duplicate name is a hard build error, never /// a silent override; the parser, the schema and the catalog all read this one list. /// public sealed class ElementRegistry { private readonly Dictionary _byName = new(StringComparer.Ordinal); /// Registers one contribution. A duplicate element name is refused loudly. public void Add(IXmlElementContribution contribution) { ArgumentNullException.ThrowIfNull(contribution); if (!_byName.TryAdd(contribution.Name, contribution)) throw new InvalidOperationException( $"XML element '{contribution.Name}' is already registered by " + $"{_byName[contribution.Name].GetType().FullName}. One name — one contribution; " + "rename the element or drop the duplicate registration."); } /// The contribution for a local element name, or null. public IXmlElementContribution? Find(string localName) => _byName.GetValueOrDefault(localName); /// Every registered element name (for diagnostics and the "did you mean" hint). public IReadOnlyCollection Names => _byName.Keys; /// Every registered contribution — the one list the schema and the catalog read. public IReadOnlyCollection Contributions => _byName.Values; /// The closest registered name by edit distance, or null when nothing is close. internal string? ClosestTo(string name) { string? best = null; var bestDistance = int.MaxValue; foreach (var candidate in _byName.Keys) { var d = Levenshtein(name, candidate); if (d < bestDistance) { bestDistance = d; best = candidate; } } return bestDistance <= Math.Max(2, name.Length / 3) ? best : null; } private static int Levenshtein(string a, string b) { var previous = new int[b.Length + 1]; var current = new int[b.Length + 1]; for (var j = 0; j <= b.Length; j++) previous[j] = j; for (var i = 1; i <= a.Length; i++) { current[0] = i; for (var j = 1; j <= b.Length; j++) { var substitution = previous[j - 1] + (char.ToLowerInvariant(a[i - 1]) == char.ToLowerInvariant(b[j - 1]) ? 0 : 1); current[j] = Math.Min(Math.Min(previous[j] + 1, current[j - 1] + 1), substitution); } (previous, current) = (current, previous); } return previous[b.Length]; } /// Builds the registry: the core contributions plus the supplied extensions. public static ElementRegistry CreateDefault(IReadOnlyList? extensions = null) { var registry = new ElementRegistry(); foreach (var contribution in CoreElements.CoreContributions.All) registry.Add(contribution); if (extensions is not null) foreach (var contribution in extensions) registry.Add(contribution); return registry; } } Path: redb-route/redb.Route.Xml/Packaging/IPackageCheck.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/Packaging/IPackageCheck.cs ---- using System.Xml; using System.Xml.Linq; namespace redb.Route.Xml.Packaging; /// /// A check a package of the route format runs over a route project at check and pack time, beside the /// gate's own. A connector or data format implements it where its exact rules need its own code (the xmljson format /// compiles the schema with its own reader and walks it). With --bin the tool creates every public, non-abstract /// implementation with a parameterless constructor in the redb.Route.*.dll of the build output, the same way it /// finds element contributions; without --bin none runs. /// public interface IPackageCheck { /// Examines the project and reports its findings through . void Check(PackageCheckContext context); } /// One route document of the project, loaded with line information. /// The path the findings name, relative to the project. /// The document; every node carries its line and position. public sealed record PackageDocument(string File, XDocument Document); /// What a sees of the project, and where it reports. public sealed class PackageCheckContext { private readonly List _findings; internal PackageCheckContext(string projectDirectory, IReadOnlyList documents, List findings) { ProjectDirectory = projectDirectory; Documents = documents; _findings = findings; } /// The project directory. public string ProjectDirectory { get; } /// The route documents of the project. public IReadOnlyList Documents { get; } /// /// The full path of a resource a route refers to, held to what the package ships (resources/), as the gate /// holds its own resource references; null with the reason when it is missing or outside resources/. /// /// The reference as written (order.xsd, resources/schemas/order.xsd). /// The reason, worded to follow the reference (is not under 'resources/'). public string? Resource(string reference, out string? problem) { ArgumentNullException.ThrowIfNull(reference); return RoutePackage.PackagedResource(ProjectDirectory, reference, out problem); } /// An error at a node of a document: the package does not build. public void Error(PackageDocument document, XObject at, string message) => Add(true, document, at, message); /// A warning at a node of a document. public void Warning(PackageDocument document, XObject at, string message) => Add(false, document, at, message); private void Add(bool error, PackageDocument document, XObject at, string message) { ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(at); ArgumentException.ThrowIfNullOrWhiteSpace(message); var line = (IXmlLineInfo)at; _findings.Add(new PackageFinding(error, $"{document.File}({line.LineNumber},{line.LinePosition})", message)); } } Path: redb-route/redb.Route.Xml/Packaging/PackageTypeResolver.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/Packaging/PackageTypeResolver.cs ---- using System.Reflection; using System.Runtime.Loader; namespace redb.Route.Xml.Packaging; /// /// The type lookup of the packaging checks with a build output at hand (redb-route-xml check|pack --bin): the /// assemblies of that output first, then the shared framework the worker runs on. A worker resolves a markup type name /// against everything its process has loaded, which includes framework assemblies a project's bin/ never carries /// (System.Net.Http for ); a check that looked in bin/ only /// refused markup the worker runs. /// public static class PackageTypeResolver { /// /// Loads every assembly of into a load context of its own and returns the lookup. /// A type name is Full.Name or Full.Name, Assembly. /// /// The build output directory. /// Receives a line for every DLL in the directory that is not a loadable assembly. public static Func Create(string binDir, Action? warn = null) { ArgumentException.ThrowIfNullOrWhiteSpace(binDir); var context = new AssemblyLoadContext("route-pack-check", isCollectible: false); context.Resolving += (loadContext, assemblyName) => { var candidate = Path.Combine(binDir, assemblyName.Name + ".dll"); return File.Exists(candidate) ? loadContext.LoadFromAssemblyPath(candidate) : null; }; foreach (var dll in Directory.GetFiles(binDir, "*.dll")) { try { context.LoadFromAssemblyPath(dll); } catch (BadImageFormatException) { warn?.Invoke($"warning: {Path.GetFileName(dll)} is not a loadable assembly — skipped by the deep bean checks."); } } return typeName => { ArgumentException.ThrowIfNullOrWhiteSpace(typeName); var comma = typeName.IndexOf(','); var fullName = (comma >= 0 ? typeName[..comma] : typeName).Trim(); var assemblyName = comma >= 0 ? typeName[(comma + 1)..].Trim() : null; var assemblies = assemblyName is null ? context.Assemblies : context.Assemblies.Where(a => string.Equals(a.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase)); foreach (var assembly in assemblies) { if (assembly.GetType(fullName) is { } type) return type; } return Type.GetType(typeName, throwOnError: false) ?? FrameworkType(fullName, assemblyName); }; } /// /// A type of the shared framework this process runs on: in the named assembly, or else in the assembly named like /// the type's namespace or a prefix of it (System.Net.Http.HttpRequestException → System.Net.Http), and /// only then in any framework assembly. Framework assemblies resolve their forwarders, so a type that moved /// (System.Net.Sockets.SocketException) is found through the assembly its name suggests. /// internal static Type? FrameworkType(string fullName, string? assemblyName) { var platform = PlatformAssemblies(); if (assemblyName is not null) return platform.TryGetValue(assemblyName, out var named) ? Load(named)?.GetType(fullName) : null; for (var dot = fullName.LastIndexOf('.'); dot > 0; dot = fullName.LastIndexOf('.', dot - 1)) { if (platform.TryGetValue(fullName[..dot], out var path) && Load(path)?.GetType(fullName) is { } type) return type; } foreach (var path in platform.Values) { if (Load(path)?.GetType(fullName) is { } type) return type; } return null; } private static Dictionary PlatformAssemblies() => Platform.Value; // The shared framework only (the directory System.Private.CoreLib is loaded from), not the tool's own dependencies, // which the trusted platform list also holds: the check must not accept a type that neither bin/ nor the framework has. private static readonly Lazy> Platform = new(() => { var frameworkDir = Path.GetDirectoryName(typeof(object).Assembly.Location) ?? string.Empty; var list = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string ?? string.Empty; var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var path in list.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { if (string.Equals(Path.GetDirectoryName(path), frameworkDir, StringComparison.OrdinalIgnoreCase)) byName.TryAdd(Path.GetFileNameWithoutExtension(path), path); } return byName; }); private static Assembly? Load(string path) { try { return AssemblyLoadContext.Default.LoadFromAssemblyName(AssemblyName.GetAssemblyName(path)); } catch (Exception ex) when (ex is BadImageFormatException or FileLoadException or FileNotFoundException) { return null; } } } Path: redb-route/redb.Route.Xml/Packaging/RoutePackage.ValidateXsd.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/Packaging/RoutePackage.ValidateXsd.cs ---- using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using redb.Route.Validation; namespace redb.Route.Xml.Packaging; /// /// The package check of <validateXsd file="…"/>: the schema is compiled as the route compiles it when it /// starts (), so an import that is missing, lies outside /// schemaRoot or points to the network fails at check and pack, not on the worker. A schemaRoot that /// leads out of resources/ is an error too: pack ships only that tree, so the imports there would not travel. /// public static partial class RoutePackage { private static void CheckXsdSchemas(string projectDir, List<(string File, XDocument Document)> documents, List findings) { var resources = Path.GetFullPath(Path.Combine(projectDir, ResourcesDir)); foreach (var (file, document) in documents) foreach (var element in document.Descendants()) if (element.Name.LocalName == "validateXsd" && element.Attribute("file") is { } schema) CheckXsdSchema(projectDir, resources, file, element, schema, findings); } private static void CheckXsdSchema(string projectDir, string resources, string file, XElement element, XAttribute schema, List findings) { var value = schema.Value; var targetNamespace = element.Attribute("targetNamespace")?.Value; var schemaRoot = element.Attribute("schemaRoot"); if (value.StartsWith("assembly:", StringComparison.OrdinalIgnoreCase) || HoldsPlaceholder(value) || HoldsPlaceholder(targetNamespace) || HoldsPlaceholder(schemaRoot?.Value)) return; // known only once configuration resolves it if (PackagedResource(projectDir, value, out _) is not { } path) return; // the resource check reports a schema the package does not ship if (schemaRoot is not null) { var root = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path)!, schemaRoot.Value)); var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (!string.Equals(root, resources, comparison) && !root.StartsWith(resources + Path.DirectorySeparatorChar, comparison)) { findings.Add(new PackageFinding(true, Position(file, schemaRoot), $"validateXsd schemaRoot='{schemaRoot.Value}' of schema '{value}' leads outside 'resources/': pack ships " + "only 'resources/', so the imports there would not reach the worker. Keep the schema and its imports under 'resources/'.")); return; } } try { XsdValidator.FromFile(path, targetNamespace, schemaRoot?.Value); } catch (Exception ex) when (ex is XmlSchemaException or XmlException or IOException or UnauthorizedAccessException) { findings.Add(new PackageFinding(true, Position(file, schema), $"validateXsd schema '{value}' does not compile: {ex.Message}")); } } private static bool HoldsPlaceholder(string? value) => value is not null && (value.Contains("{{", StringComparison.Ordinal) || value.Contains("${", StringComparison.Ordinal)); } Path: redb-route/redb.Route.Xml/Packaging/RoutePackage.XmlJson.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/Packaging/RoutePackage.XmlJson.cs ---- using System.Xml; using System.Xml.Linq; namespace redb.Route.Xml.Packaging; /// /// The package checks of the xmljson data format that need no code of the format, so they run without --bin: /// the format is recognised by its type name on <dataFormat type> and the per-step /// <marshal type> / <unmarshal type>; its arrays= paths are well formed; its schema is a /// file the package ships; a format with neither schema= nor arrays= is warned. What needs the schema /// compiled (an arrays= path through the schema's structure, wildcards, mixed content, the plural pairs) is the /// format's own , which runs with --bin. /// public static partial class RoutePackage { private const string XmlJsonType = "redb.Route.DataFormats.XmlJson.XmlJsonDataFormat"; private static void CheckXmlJsonFormats(string projectDir, List<(string File, XDocument Document)> documents, List findings) { foreach (var (file, document) in documents) foreach (var element in document.Descendants()) { if (element.Name.LocalName is not ("dataFormat" or "marshal" or "unmarshal")) continue; var type = element.Attribute("type")?.Value; if (type is null || !string.Equals(type.Split(',')[0].Trim(), XmlJsonType, StringComparison.Ordinal)) continue; CheckXmlJson(projectDir, file, element, findings); } } private static void CheckXmlJson(string projectDir, string file, XElement element, List findings) { var schema = element.Attribute("schema"); var arrays = element.Attribute("arrays"); var paths = (arrays?.Value ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var path in paths) if (XmlJsonPathProblem(path) is { } problem) findings.Add(new PackageFinding(true, Position(file, arrays!), $"xmljson arrays path '{path}' {problem}.")); if (schema is null) { if (paths.Length == 0) findings.Add(new PackageFinding(false, Position(file, element), "xmljson without schema= or arrays=: a single element becomes an object and two become an array, so one " + "message type gives two JSON shapes. Name the schema, or the repeated elements with arrays=.")); return; } var value = schema.Value; if (value.Contains("{{", StringComparison.Ordinal) || value.Contains("${", StringComparison.Ordinal)) return; // known only once configuration resolves it if (PackagedResource(projectDir, value, out var schemaProblem) is null) findings.Add(new PackageFinding(true, Position(file, schema), $"xmljson schema '{value}' {schemaProblem}.")); } /// What is wrong with an arrays path, worded after the format's own error; null when it is well formed. private static string? XmlJsonPathProblem(string path) { var anywhere = path.StartsWith("//", StringComparison.Ordinal); if (!anywhere && !path.StartsWith('/')) return "starts with '/' (from the root) or '//' (at any depth)"; var steps = path[(anywhere ? 2 : 1)..].Split('/'); return steps.Any(s => s.Length == 0 || s.Any(char.IsWhiteSpace)) ? "has an empty or blank step; write it as /Order/Items/Item or //Item" : null; } private static string Position(string file, XObject node) { var line = (IXmlLineInfo)node; return $"{file}({line.LineNumber},{line.LinePosition})"; } } Path: redb-route/redb.Route.Xml/Packaging/RoutePackage.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/Packaging/RoutePackage.cs ---- using System.IO.Compression; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using redb.Route.Core; namespace redb.Route.Xml.Packaging; /// /// The package manifest: the four fields Tsak modules always had, the three /// the XML artifacts add, and the required-configuration-keys manifest /// (every {{key}} without a default; the value legitimately arrives from ANY layer of /// the merged context configuration at deploy time, so packaging records the requirement /// instead of demanding a value). /// public sealed record RoutePackageManifest { public required string Name { get; init; } public required string Version { get; init; } public IReadOnlyList EntryPoints { get; init; } = []; public IReadOnlyList Dependencies { get; init; } = []; public IReadOnlyList Artifacts { get; init; } = []; public string SchemaVersion { get; init; } = "1.0"; public string Resources { get; init; } = "resources"; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Context { get; init; } public IReadOnlyList RequiredConfigKeys { get; init; } = []; } /// One finding of the packaging checks: a hard error or a warning. public sealed record PackageFinding(bool IsError, string File, string Message) { public override string ToString() => $"{(IsError ? "error" : "warning")}: {File}: {Message}"; } /// The result of building or checking a package. public sealed record PackageResult( RoutePackageManifest Manifest, IReadOnlyList Findings) { /// The findings that fail the check. public IEnumerable Errors => Findings.Where(f => f.IsError); /// The findings that are advisory only. public IEnumerable Warnings => Findings.Where(f => !f.IsError); } /// /// Builds a route package from a project directory (the Tsak-independent half): /// the package layout — manifest.json, the L4 identity config, the XML artifacts, the /// resources — with the packaging checks run first, so a broken reference is a build /// error, never a deployment surprise. The layout is exactly what the Tsak module loader will /// consume; nothing here depends on Tsak. /// public static partial class RoutePackage { /// The conventional project layout the builder and the scaffolder share. public const string RoutesDir = "routes"; /// Resources directory name (XSLT, schemas — resolved from the package root). public const string ResourcesDir = "resources"; /// Config directory name (the L4 identity file and the L3 deploy sample). public const string ConfigDir = "config"; /// The context-level document, loaded before the route artifacts. public const string ContextFile = "context.xml"; /// /// The first directory a route's file= references are looked up in outside a package. A /// route under {project}/routes/ reads {project}/resources/; any other file reads its /// own directory. The full search, with the project root after it, is /// . /// public static string ResourceRootFor(string routeFile) { ArgumentException.ThrowIfNullOrWhiteSpace(routeFile); var directory = Path.GetDirectoryName(Path.GetFullPath(routeFile))!; if (!string.Equals(Path.GetFileName(directory), RoutesDir, StringComparison.OrdinalIgnoreCase)) return directory; var project = Path.GetDirectoryName(directory)!; var resources = Path.Combine(project, ResourcesDir); return Directory.Exists(resources) ? resources : project; } /// /// Where a route's file= reference is read from outside a package, in order. A route under /// {project}/routes/ reads {project}/resources/{reference} (file="order.xsd"), then /// {project}/{reference} (file="resources/order.xsd"): the rule the packaging checks hold a /// project to and the Tsak loader applies to a package. Any other route file reads its own directory; a /// rooted reference is itself. /// public static IReadOnlyList ResourceCandidatesFor(string routeFile, string reference) { ArgumentException.ThrowIfNullOrWhiteSpace(routeFile); ArgumentException.ThrowIfNullOrWhiteSpace(reference); if (Path.IsPathRooted(reference)) return [reference]; var directory = Path.GetDirectoryName(Path.GetFullPath(routeFile))!; return string.Equals(Path.GetFileName(directory), RoutesDir, StringComparison.OrdinalIgnoreCase) ? ProjectResourceCandidates(Path.GetDirectoryName(directory)!, reference) : [Path.GetFullPath(Path.Combine(directory, reference))]; } /// /// Runs the implementations of the build output over the documents. A check that throws /// is a defect of that check, reported as an error naming it, and the others still run. /// private static void RunPackageChecks(string projectDir, List<(string File, XDocument Document)> documents, IReadOnlyList? checks, List findings) { if (checks is not { Count: > 0 }) return; var context = new PackageCheckContext(projectDir, documents.Select(d => new PackageDocument(d.File, d.Document)).ToList(), findings); foreach (var check in checks) { try { check.Check(context); } catch (Exception ex) { findings.Add(new PackageFinding(true, check.GetType().FullName ?? check.GetType().Name, $"the package check failed: {ex.GetType().Name}: {ex.Message}")); } } } /// /// Where a resource reference lands in the package, as the checks hold it (findings register row 42): Pack ships the /// resources/ tree, so a reference resolves only to a file inside it. Returns the file, or null with /// saying why: missing, or present outside resources/ (a file beside the project, /// which local runs find and the worker never gets). /// internal static string? PackagedResource(string projectDir, string reference, out string? problem) { problem = null; var resources = Path.GetFullPath(Path.Combine(projectDir, ResourcesDir)) + Path.DirectorySeparatorChar; var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; var candidates = Path.IsPathRooted(reference) ? [reference] : ProjectResourceCandidates(projectDir, reference); foreach (var candidate in candidates) if (File.Exists(candidate) && Path.GetFullPath(candidate).StartsWith(resources, comparison)) return candidate; problem = candidates.FirstOrDefault(File.Exists) is { } outside ? $"is at '{Path.GetRelativePath(projectDir, outside)}', outside '{ResourcesDir}/': pack ships only '{ResourcesDir}/', so the worker would not find it. Move it under '{ResourcesDir}/'" : $"is not under '{ResourcesDir}/'"; return null; } private static string[] ProjectResourceCandidates(string projectDir, string reference) => [ Path.GetFullPath(Path.Combine(projectDir, ResourcesDir, reference)), Path.GetFullPath(Path.Combine(projectDir, reference)), ]; /// /// Runs the packaging checks for a project directory without producing anything — the CI /// gate form (without a gate the checks would be skipped locally in a hurry). /// — when the built assemblies are at hand (the tool's /// --bin) — turns the bean checks DEEP: a renamed type, a non-public type, a typo in /// a property or a method= becomes a build error instead of a first-message surprise. /// — the component catalog of the same built output — holds every /// endpoint's parameters against its connector: a name a strict connector does not know /// ( false) is an error here, in the engine's own words, /// instead of a refusal when the route starts. /// — the manifest names of the packages this one needs opened first (a carrier of /// shared companion DLLs) — go into manifest.json as written; only their shape is checked here, since the /// packages they name are on the worker, not in this project. /// — the implementations of the build output — run after the /// gate's own checks, over the same documents; a check that throws is an error naming it. /// public static PackageResult Check(string projectDir, string name, string version, Func? typeResolver = null, IReadOnlyList? extensions = null, IReadOnlyList? catalog = null, IReadOnlyList? dependencies = null, IReadOnlyList? checks = null) { ArgumentException.ThrowIfNullOrWhiteSpace(projectDir); var findings = new List(); var artifacts = CollectArtifacts(projectDir, findings); CheckPackageConfigName(projectDir, name, findings); CheckDependencies(name, dependencies ?? [], findings); var requiredKeys = RunChecks(projectDir, artifacts, findings, typeResolver, extensions, catalog, checks); var manifest = BuildManifest(projectDir, name, version, artifacts, requiredKeys) with { Dependencies = [.. dependencies ?? []] }; return new PackageResult(manifest, findings); } /// /// A dependency is another package's manifest name: not blank, not a file (carrier.tpkg, a path), not this /// package, and listed once. Names compare ignoring case, as the worker matches them. /// private static void CheckDependencies(string name, IReadOnlyList dependencies, List findings) { const string where = "--depends"; var seen = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var dependency in dependencies) { if (string.IsNullOrWhiteSpace(dependency) || dependency.Trim() != dependency) findings.Add(new PackageFinding(true, where, $"'{dependency}' is not a package name: a dependency names another package's manifest Name, without spaces around it.")); else if (dependency.StartsWith('-')) findings.Add(new PackageFinding(true, where, $"'{dependency}' is an option, not a package name: --depends needs the name of the package after it.")); else if (dependency.IndexOfAny(['/', '\\']) >= 0 || dependency.EndsWith(".tpkg", StringComparison.OrdinalIgnoreCase) || dependency.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) findings.Add(new PackageFinding(true, where, $"'{dependency}' is a file; a dependency names the other package by its manifest Name (the --name it was packed with).")); else if (string.Equals(dependency, name, StringComparison.OrdinalIgnoreCase)) findings.Add(new PackageFinding(true, where, $"the package '{name}' cannot depend on itself.")); else if (!seen.Add(dependency)) findings.Add(new PackageFinding(true, where, $"'{dependency}' is listed more than once.")); } } /// /// Builds the package: checks first (errors refuse the build), then the package layout in /// , then the .tpkg zip beside it. Returns the result with /// the manifest and every finding. /// public static PackageResult Build(string projectDir, string name, string version, string outDir, IReadOnlyList? entryPoints = null, Func? typeResolver = null, IReadOnlyList? extensions = null, IReadOnlyList? catalog = null, IReadOnlyList? dependencies = null, IReadOnlyList? checks = null) { var result = Check(projectDir, name, version, typeResolver, extensions, catalog, dependencies, checks); if (result.Errors.Any()) return result; // An entry DLL is packed at the package root, so the manifest names it by its file name: the loader looks it up // in the zip by exactly this name, and a build path ("bin/Release/net10.0/X.dll") would not be found there. var manifest = result.Manifest with { EntryPoints = (entryPoints ?? []).Select(e => Path.GetFileName(Path.GetFullPath(e, projectDir))).ToList(), }; var stage = Path.Combine(outDir, $"{name}-{version}"); if (Directory.Exists(stage)) Directory.Delete(stage, recursive: true); Directory.CreateDirectory(stage); File.WriteAllText(Path.Combine(stage, "manifest.json"), JsonSerializer.Serialize(manifest, ManifestJson)); // L4 — the identity stub only (secrets never ride inside the package). var l4Source = FindPackageConfig(projectDir, name); File.WriteAllText(Path.Combine(stage, $"{name}.config.json"), l4Source is not null ? File.ReadAllText(l4Source) : JsonSerializer.Serialize(new { ContextName = manifest.Context ?? name, AutoStart = true }, ManifestJson)); foreach (var artifact in manifest.Artifacts) { var target = Path.Combine(stage, artifact); Directory.CreateDirectory(Path.GetDirectoryName(target)!); File.Copy(Path.Combine(projectDir, artifact), target); } if (File.Exists(Path.Combine(projectDir, ContextFile))) File.Copy(Path.Combine(projectDir, ContextFile), Path.Combine(stage, ContextFile)); var resources = Path.Combine(projectDir, ResourcesDir); if (Directory.Exists(resources)) CopyTree(resources, Path.Combine(stage, ResourcesDir)); foreach (var entryPoint in entryPoints ?? []) { var source = Path.GetFullPath(entryPoint, projectDir); File.Copy(source, Path.Combine(stage, Path.GetFileName(source)), overwrite: true); } var zipPath = Path.Combine(outDir, $"{name}-{version}.tpkg"); if (File.Exists(zipPath)) File.Delete(zipPath); ZipFile.CreateFromDirectory(stage, zipPath, CompressionLevel.Optimal, includeBaseDirectory: false); return new PackageResult(manifest, result.Findings); } private static readonly JsonSerializerOptions ManifestJson = new() { WriteIndented = true }; /// /// The package reads its L4 config from config/<name>.config.json only. When that file is absent but /// another *.config.json is there, the package name and the file disagree (a rename, a --name), and the /// build would write the default config instead: a warning naming both files. /// private static void CheckPackageConfigName(string projectDir, string name, List findings) { var configDir = Path.Combine(projectDir, ConfigDir); var expected = $"{name}.config.json"; if (!Directory.Exists(configDir) || FindPackageConfig(projectDir, name) is not null) return; var found = Directory.GetFiles(configDir, "*.config.json") .Select(f => $"{ConfigDir}/{Path.GetFileName(f)}") .OrderBy(f => f, StringComparer.Ordinal) .ToList(); if (found.Count == 0) return; findings.Add(new PackageFinding(false, $"{ConfigDir}/{expected}", $"the package '{name}' reads its config from {ConfigDir}/{expected}, which is missing, but {string.Join(", ", found)} " + $"is there; the package gets the default config (ContextName, AutoStart) instead. " + $"Rename the file to {expected}, or pack with the name it was made for (--name).")); } /// /// config/<name>.config.json with exactly this file name, letter case included, on every system. A plain /// ignored the case on Windows and macOS and kept it on Linux, so /// --name orders next to Orders.config.json packed that file on a Windows machine and the default /// config on a Linux build agent. /// private static string? FindPackageConfig(string projectDir, string name) { var configDir = Path.Combine(projectDir, ConfigDir); if (!Directory.Exists(configDir)) return null; var expected = $"{name}.config.json"; return Directory.EnumerateFiles(configDir, "*.config.json") .FirstOrDefault(f => string.Equals(Path.GetFileName(f), expected, StringComparison.Ordinal)); } private static List CollectArtifacts(string projectDir, List findings) { var routesDir = Path.Combine(projectDir, RoutesDir); if (!Directory.Exists(routesDir)) { findings.Add(new PackageFinding(true, RoutesDir, "the routes directory is missing — a route package carries at least one .route.xml.")); return []; } // Deterministic ordinal order — the manifest is the explicit, checkable list. return [.. Directory.GetFiles(routesDir, "*.route.xml") .Select(f => Path.GetRelativePath(projectDir, f).Replace('\\', '/')) .OrderBy(f => f, StringComparer.Ordinal)]; } private static RoutePackageManifest BuildManifest(string projectDir, string name, string version, List artifacts, IReadOnlyList requiredKeys) { string? contextName = null; if (FindPackageConfig(projectDir, name) is { } l4) { try { using var document = JsonDocument.Parse(File.ReadAllText(l4)); if (document.RootElement.TryGetProperty("ContextName", out var ctx)) contextName = ctx.GetString(); } catch (JsonException) { // reported by RunChecks } } return new RoutePackageManifest { Name = name, Version = version, Artifacts = artifacts, Context = contextName, RequiredConfigKeys = requiredKeys, }; } // ── The packaging checks ──────────────────────────────────────────────── private static readonly Regex Placeholder = new(@"\{\{([^{}:]+)(:[^{}]*)?\}\}", RegexOptions.Compiled); private static readonly Regex PasswordLikeOption = new(@"(?i)(password|passwd|pwd|secret)\s*=\s*(?!\{\{|\$\{)[^&\s""']+", RegexOptions.Compiled); private static readonly Regex BeanMethodOption = new(@"(?i)[?&]method=([A-Za-z0-9_]+)", RegexOptions.Compiled); /// /// Registry names the engine's own packages register at start, so no <bean> declares them: redb, the /// sql: data source of redb.Route.Core (dataSource=redb; dataSource=#redb:orders reads as /// redb by the position rule, and a bare redb:orders is no plain registry name). /// private static readonly HashSet RegisteredByTheEngine = new(StringComparer.Ordinal) { "redb" }; private static readonly Regex LeadingReference =new(@"^#([A-Za-z0-9_.\-]+)", RegexOptions.Compiled); private static readonly Regex UriScheme = new(@"^[A-Za-z][A-Za-z0-9+.\-]*:(//)?", RegexOptions.Compiled); /// /// Registry references by POSITION (a reference is a value that STARTS with '#'): /// the whole attribute value, the path right after the scheme (bean:#x) and every URI /// option value (dataSource=#main-db). A '#' anywhere else is text — the sql parameter /// :#name must not read as a dangling bean. /// private static IEnumerable RegistryReferences(string value) { if (LeadingReference.Match(value) is { Success: true } whole) { yield return whole.Groups[1].Value; yield break; } var query = value.IndexOf('?'); var address = query >= 0 ? value[..query] : value; if (UriScheme.Match(address) is { Success: true } scheme && LeadingReference.Match(address[scheme.Length..]) is { Success: true } path) yield return path.Groups[1].Value; if (query < 0) yield break; foreach (var pair in value[(query + 1)..].Split('&')) { var equals = pair.IndexOf('='); if (equals >= 0 && LeadingReference.Match(pair[(equals + 1)..]) is { Success: true } option) yield return option.Groups[1].Value; } } private static IReadOnlyList RunChecks(string projectDir, List artifacts, List findings, Func? typeResolver, IReadOnlyList? extensions = null, IReadOnlyList? catalog = null, IReadOnlyList? checks = null) { var registry = ElementRegistry.CreateDefault(extensions); var requiredKeys = new SortedSet(StringComparer.Ordinal); var declaredBeans = new HashSet(StringComparer.Ordinal); var beanDeclarations = new List<(string File, BeanDeclaration Bean)>(); var beanMethodCalls = new List<(string File, string Bean, string Method)>(); var referencedBeans = new List<(string File, string Name)>(); var typedReferences = new List(); var documents = new List<(string File, XDocument Document)>(); var contextPath = Path.Combine(projectDir, ContextFile); if (File.Exists(contextPath)) LoadDocument(ContextFile, contextPath, documents, findings); foreach (var artifact in artifacts) LoadDocument(artifact, Path.Combine(projectDir, artifact), documents, findings); foreach (var (file, document) in documents) { // XSD validation catches the broken markup wholesale (root name decides the flavor). if (document.Root?.Name.LocalName == "routes") { foreach (var (line, column, message) in XmlRouteSchema.Validate(document, registry)) findings.Add(new PackageFinding(true, $"{file}({line},{column})", message)); } foreach (var element in document.Descendants()) { foreach (var text in element.Nodes().OfType()) { if (text.Value.Contains("]]>", StringComparison.Ordinal)) findings.Add(new PackageFinding(true, file, $"<{element.Name.LocalName}> content contains ']]>' — silently broken XML on repackaging.")); ScanPlaceholders(text.Value, requiredKeys); } if (element.Name.LocalName == "bean" && element.Attribute("name")?.Value is { Length: > 0 } beanName) declaredBeans.Add(beanName); foreach (var attribute in element.Attributes()) { ScanPlaceholders(attribute.Value, requiredKeys); foreach (var reference in RegistryReferences(attribute.Value)) referencedBeans.Add((file, reference)); if (attribute.Value.StartsWith("bean:#", StringComparison.Ordinal) && BeanMethodOption.Match(attribute.Value) is { Success: true } methodMatch) { var beanRef = attribute.Value["bean:#".Length..]; var end = beanRef.IndexOf('?'); beanMethodCalls.Add((file, end >= 0 ? beanRef[..end] : beanRef, methodMatch.Groups[1].Value)); } if (PasswordLikeOption.IsMatch(attribute.Value)) findings.Add(new PackageFinding(false, file, $"<{element.Name.LocalName} {attribute.Name.LocalName}=…> looks like a literal secret — " + "supply secrets through the merged context configuration (L3/L5), never inside the package.")); if (IsResourceLocator(element, attribute, registry)) CheckResource(projectDir, file, element, attribute, findings); } } } CheckBeanDeclarations(documents, declaredBeans, beanDeclarations, findings); CheckXmlJsonFormats(projectDir, documents, findings); CheckXsdSchemas(projectDir, documents, findings); RunPackageChecks(projectDir, documents, checks, findings); // Elements that register objects under a name of their own () declare that name like a does; references that must name an object of a // given type () are held against it once types are known. var registered = new Dictionary(StringComparer.Ordinal); foreach (var (file, document) in documents) foreach (var element in document.Root?.Elements() ?? []) CollectRegistryAttributes(file, element, registry.Find(element.Name.LocalName)?.Spec, registry, registered, typedReferences); declaredBeans.UnionWith(registered.Keys); // bean: calls in expressions: a syntax error is an error at the attribute; the name joins the #name references, // so an undeclared one is the same warning; the method is held against a declared type below, with --bin. var expressionBeanCalls = new List(); foreach (var (file, document) in documents) if (document.Root is { } root) CollectExpressionBeanCalls(file, root, registry.Find(root.Name.LocalName)?.Spec, registry, expressionBeanCalls, findings); foreach (var call in expressionBeanCalls) referencedBeans.Add((call.File, call.Reference)); // Options marked [RegistryReference] name a registry object bare as well (connectionFactory=main): the core's // components always, the connectors of the built output with --bin. var markedReferences = new RegistryReferenceCollector(WithCoreComponents(catalog), referencedBeans, typedReferences); foreach (var (file, document) in documents) foreach (var element in document.Root?.Elements() ?? []) CheckEndpoints(file, element, registry.Find(element.Name.LocalName)?.Spec, registry, markedReferences); // A scheme on the side its component lacks ([EndpointRole] on the class), in the words the runtime refuses it // with: the core's components always, the connectors of the built output with --bin. var sides = new EndpointSideChecker(WithCoreComponents(catalog), findings); foreach (var (file, document) in documents) foreach (var element in document.Root?.Elements() ?? []) CheckEndpoints(file, element, registry.Find(element.Name.LocalName)?.Spec, registry, sides); foreach (var (file, document) in documents) foreach (var element in document.Descendants()) foreach (var attribute in element.Attributes()) markedReferences.CheckAttribute(file, element, attribute); // The registry is one per context, so a #name may be declared in ANY artifact // of the package; what remains unresolved is either external (module code) — a warning — // or a typo. Without the module's code we cannot tell, so the finding names both. Names the // engine's own packages register (RegisteredByTheEngine) are known and need no . foreach (var (file, name) in referencedBeans.DistinctBy(r => r.Name)) { if (!declaredBeans.Contains(name) && !RegisteredByTheEngine.Contains(name)) findings.Add(new PackageFinding(false, file, $"'#{name}' is not declared by any of this package — either module code registers it at startup (fine), or it is a dangling reference.")); } foreach (var (file, document) in documents) { if (document.Root is not { } root) continue; CheckUnreachableSteps(file, root, registry, findings); CheckConditionTemplates(file, root, registry.Find(root.Name.LocalName)?.Spec, registry, findings); CheckUnclosedPlaceholders(file, root, registry.Find(root.Name.LocalName)?.Spec, registry, findings); } CheckRouteBuilders(documents, typeResolver, findings); if (typeResolver is not null) { var instanceTypes = RunDeepBeanChecks(beanDeclarations, beanMethodCalls, typeResolver, findings); CheckExpressionBeanCalls(expressionBeanCalls, instanceTypes, findings); CheckTypedReferences(typedReferences, instanceTypes, registered, typeResolver, findings); foreach (var (file, document) in documents) foreach (var element in document.Root?.Elements() ?? []) CheckTypeAttributes(file, element, registry.Find(element.Name.LocalName)?.Spec, registry, typeResolver, findings); if (catalog is not null) { var parameters = new EndpointParameterChecker(catalog, typeResolver, findings); foreach (var (file, document) in documents) foreach (var element in document.Root?.Elements() ?? []) CheckEndpoints(file, element, registry.Find(element.Name.LocalName)?.Spec, registry, parameters); } } return [.. requiredKeys]; } /// /// Every <routeBuilder> of context.xml names its type; with the built assemblies at hand the type /// exists and is one the loader accepts (a public, non-abstract RouteBuilder with a public parameterless /// constructor). The worker would refuse the package on any of these, so the build does. /// private static void CheckRouteBuilders(List<(string File, XDocument Document)> documents, Func? typeResolver, List findings) { foreach (var (file, document) in documents) { if (document.Root?.Name.LocalName != "context") continue; foreach (var element in document.Root.Elements().Where(e => e.Name.LocalName == "routeBuilder")) { var line = (IXmlLineInfo)element; var at = $"{file}({line.LineNumber},{line.LinePosition})"; var typeName = element.Attribute("type")?.Value.Trim(); if (string.IsNullOrEmpty(typeName)) { findings.Add(new PackageFinding(true, at, " needs type=\"Namespace.Type, Assembly\".")); continue; } // A type that does not resolve is reported by the generic type-attribute check. if (typeResolver?.Invoke(typeName) is not { } type) continue; if (CoreElements.RouteBuilderContextContribution.Refusal(type) is { } reason) findings.Add(new PackageFinding(true, at, $": '{typeName}' {reason}")); } } } /// /// The assembly-backed half of the packaging checks: bean types resolve and are public, declared properties /// are writable, and every bean:#x?method=M names an existing public method. /// /// /// A step written after a terminal one (: stop, rollbackAll, /// throwException) in the same list never runs. Not an error - the route loads and works - but /// dead markup that reads as if it did something; the first such step is named with its /// position. Generic over the specs, so a contribution that declares a terminal step is covered. /// private static void CheckUnreachableSteps(string file, XElement parent, ElementRegistry registry, List findings) { XElement? terminal = null; foreach (var child in parent.Elements()) { var spec = registry.Find(child.Name.LocalName)?.Spec; var isStep = spec?.Kind is XmlElementKind.Step or XmlElementKind.Scope or XmlElementKind.Branching; if (terminal is not null && isStep) { var line = (IXmlLineInfo)child; findings.Add(new PackageFinding(false, $"{file}({line.LineNumber},{line.LinePosition})", $"<{child.Name.LocalName}> never runs: it comes after <{terminal.Name.LocalName}/>, " + "which ends the route for the exchange.")); terminal = null; } if (isStep && spec!.Terminal) terminal = child; CheckUnreachableSteps(file, child, registry, findings); } } /// /// A file the runtime will read from the package: the format's own file= (every /// element taking a file-or-content pair), or an attribute its spec marks /// — a package element that names its file otherwise. /// private static bool IsResourceLocator(XElement element, XAttribute attribute, ElementRegistry registry) => attribute.Name.LocalName == "file" || registry.Find(element.Name.LocalName)?.Spec.Attributes.Any(a => a.Resource && string.Equals(a.Name, attribute.Name.LocalName, StringComparison.Ordinal)) == true; /// /// The file is under resources/ (or at the project root), where the worker's resource /// resolver will look. Two kinds of value cannot be checked here and are left alone: an /// assembly: locator (the file ships inside an assembly) and a value that still holds /// a placeholder (it is only known once configuration resolves it). /// private static void CheckResource(string projectDir, string file, XElement element, XAttribute attribute, List findings) { var value = attribute.Value; if (value.StartsWith("assembly:", StringComparison.OrdinalIgnoreCase) || value.Contains("{{", StringComparison.Ordinal) || value.Contains("${", StringComparison.Ordinal)) return; if (PackagedResource(projectDir, value, out var problem) is null) { var line = (IXmlLineInfo)attribute; findings.Add(new PackageFinding(true, $"{file}({line.LineNumber},{line.LinePosition})", $"resource '{value}' referenced by <{element.Name.LocalName} {attribute.Name.LocalName}=…> {problem}.")); } } /// /// A condition written as a template is true whatever it renders: ${header.kind} == 'order' /// renders to the text «refund == 'order'», which is non-empty, so the branch always wins. The /// comparison has to be written without the braces — header.kind == 'order' — or entirely /// inside them. A WARNING, not an error: the gate names the line, the author decides. Driven by /// , so a package contribution's own condition is covered. /// private static void CheckConditionTemplates(string file, XElement element, ElementSpec? spec, ElementRegistry registry, List findings) { foreach (var attribute in element.Attributes()) { var attributeSpec = spec?.Attributes.FirstOrDefault(a => string.Equals(a.Name, attribute.Name.LocalName, StringComparison.Ordinal)); if (attributeSpec is not { Condition: true } || !LooksLikeTemplateComparison(attribute.Value)) continue; var line = (IXmlLineInfo)attribute; findings.Add(new PackageFinding(false, $"{file}({line.LineNumber},{line.LinePosition})", $"{attribute.Name.LocalName}=\"{attribute.Value}\" compares OUTSIDE ${{…}}: a condition holding a " + "placeholder is rendered to text first, and non-empty text is true whatever it says. Write the " + "comparison without the braces (header.kind == 'order') or entirely inside them.")); } foreach (var child in element.Elements()) { var childSpec = spec?.Children.FirstOrDefault(c => string.Equals(c.Name, child.Name.LocalName, StringComparison.Ordinal)) ?? registry.Find(child.Name.LocalName)?.Spec; CheckConditionTemplates(file, child, childSpec, registry, findings); } } /// /// The value carries a ${…} placeholder AND an operator outside of it. Both halves matter: /// a lone ${header.enabled} renders to «true»/«false» and reads correctly, and a comparison /// written entirely inside the braces is evaluated as an expression, not rendered. /// private static bool LooksLikeTemplateComparison(string value) { if (!value.Contains("${", StringComparison.Ordinal)) return false; var outside = new System.Text.StringBuilder(); var position = 0; foreach (var hole in redb.Route.Expressions.TemplateScanner.Scan(value).Holes) { outside.Append(value, position, hole.Start - position).Append(' '); position = hole.Start + hole.Length; } outside.Append(value, position, value.Length - position); var text = outside.ToString(); return Operators.Any(op => text.Contains(op, StringComparison.Ordinal)); } /// /// A ${ that nothing closes, in an attribute the engine reads as an expression or an endpoint URI, or in /// a structured endpoint child (its attributes and text are URI options): the load fails on it, so the build /// fails on it here, with the attribute's position. /// private static void CheckUnclosedPlaceholders(string file, XElement element, ElementSpec? spec, ElementRegistry registry, List findings, bool endpointChild = false) { // is the route's own element, not a contribution: its uri= and its endpoint child are addresses too. var isFrom = !endpointChild && element.Name.LocalName == "from"; foreach (var attribute in element.Attributes()) { if (attribute.IsNamespaceDeclaration || attribute.Name.NamespaceName.Length > 0) continue; var type = spec?.Attributes.FirstOrDefault(a => string.Equals(a.Name, attribute.Name.LocalName, StringComparison.Ordinal))?.Type; if (endpointChild || type is AttributeType.Expression or AttributeType.Uri || (isFrom && attribute.Name.LocalName == "uri")) ReportUnclosed(file, attribute, attribute.Value, $"{attribute.Name.LocalName}=", findings); } if (endpointChild) foreach (var text in element.Nodes().OfType()) ReportUnclosed(file, text, text.Value, $"<{element.Name.LocalName}> text", findings); foreach (var child in element.Elements()) { if ((spec is { TakesEndpoint: true } || isFrom) && !endpointChild) { CheckUnclosedPlaceholders(file, child, null, registry, findings, endpointChild: true); continue; } var childSpec = spec?.Children.FirstOrDefault(c => string.Equals(c.Name, child.Name.LocalName, StringComparison.Ordinal)) ?? registry.Find(child.Name.LocalName)?.Spec; CheckUnclosedPlaceholders(file, child, childSpec, registry, findings, endpointChild); } } /// /// One bean:name.Method(args) call an attribute or a text of the package makes, with its position; a /// ref:name is one with no method. /// private sealed record ExpressionBeanCall(string File, string At, string What, string Reference, string? Method, int Arguments); /// /// Every bean: call in the package's expressions, parsed as the engine parses it: a bare one in an /// expression attribute, one inside a ${...} of an expression or address attribute, of a structured /// endpoint child, or of an element's text. A call that does not parse is an error at its attribute. /// private static void CollectExpressionBeanCalls(string file, XElement element, ElementSpec? spec, ElementRegistry registry, List calls, List findings, bool endpointChild = false) { var isFrom = !endpointChild && element.Name.LocalName == "from"; foreach (var attribute in element.Attributes()) { if (attribute.IsNamespaceDeclaration || attribute.Name.NamespaceName.Length > 0) continue; var attributeSpec = spec?.Attributes.FirstOrDefault(a => string.Equals(a.Name, attribute.Name.LocalName, StringComparison.Ordinal)); var type = attributeSpec?.Type; var bare = type is AttributeType.Expression; if (bare || endpointChild || type is AttributeType.Uri || (isFrom && attribute.Name.LocalName == "uri")) CollectFrom(file, attribute, attribute.Value, $"{attribute.Name.LocalName}=", bare, condition: attributeSpec is { Condition: true }, endpoint: !bare, calls, findings, constantKey: attributeSpec is { ConstantKey: true }); } if (endpointChild || spec is { AllowsTextContent: true }) foreach (var text in element.Nodes().OfType()) CollectFrom(file, text, text.Value, $"<{element.Name.LocalName}> text", bare: false, condition: false, endpoint: endpointChild, calls, findings); foreach (var child in element.Elements()) { if ((spec is { TakesEndpoint: true } || isFrom) && !endpointChild) { CollectExpressionBeanCalls(file, child, null, registry, calls, findings, endpointChild: true); continue; } var childSpec = spec?.Children.FirstOrDefault(c => string.Equals(c.Name, child.Name.LocalName, StringComparison.Ordinal)) ?? registry.Find(child.Name.LocalName)?.Spec; CollectExpressionBeanCalls(file, child, childSpec, registry, calls, findings, endpointChild); } } /// The text of with every hole replaced by a space. private static string OutsideHoles(string value, redb.Route.Expressions.TemplateScanner.ScanResult scan) { var outside = new System.Text.StringBuilder(); var position = 0; foreach (var hole in scan.Holes) { outside.Append(value, position, hole.Start - position).Append(' '); position = hole.Start + hole.Length; } return outside.Append(value, position, value.Length - position).ToString(); } private static void CollectFrom(string file, XObject at, string value, string what, bool bare, bool condition, bool endpoint, List calls, List findings, bool constantKey = false) { var scan = redb.Route.Expressions.TemplateScanner.Scan(value); var whole = bare && scan.Holes.Count == 0 && scan.Unclosed.Count == 0; // A key that may be a constant () is the key as written when the engine reads it so. if (whole && constantKey && redb.Route.Expressions.ExpressionResolver.IsConstantKey(value)) return; IEnumerable expressions = whole ? [value] : scan.Holes.Select(h => h.InnerOf(value)).ToList(); var line = (IXmlLineInfo)at; var position = $"{file}({line.LineNumber},{line.LinePosition})"; // Each expression as the engine compiles it (findings register row 32): one that does not compile fails the // route at build, so it fails the package here, in the engine's words. In an endpoint, ${file:...} in any case // belongs to the file components, which check it themselves (row 34). // A bean:/ref: expression's error waits for the call check below, whose parser message is more precise. var deferred = new Dictionary(StringComparer.Ordinal); foreach (var expression in expressions.Distinct(StringComparer.Ordinal)) { if (endpoint && expression.TrimStart().StartsWith("file:", StringComparison.OrdinalIgnoreCase)) continue; var (error, warning) = redb.Route.Expressions.ExpressionResolver.GateCheck(expression, placeholder: !whole, condition); if (error is not null && redb.Route.Expressions.ExpressionResolver.ContainsNamespacedCall(expression)) deferred[expression] = error; else if (error is not null) findings.Add(new PackageFinding(true, position, $"{what} {error}")); if (warning is not null) findings.Add(new PackageFinding(false, position, $"{what} {warning}")); } if (!value.Contains("bean:", StringComparison.Ordinal) && !value.Contains("ref:", StringComparison.Ordinal)) { foreach (var error in deferred.Values) findings.Add(new PackageFinding(true, position, $"{what} {error}")); return; } // A bare call whose arguments are placeholders (bean:svc.M(${header.x})): the ${ makes the whole text a // template, so it renders to text instead of calling, and in a condition that text is always true. var outside = bare && scan.Holes.Count > 0 ? OutsideHoles(value, scan) : null; if (outside is not null && redb.Route.Expressions.ExpressionResolver.ContainsNamespace(outside, "bean")) findings.Add(new PackageFinding(false, position, $"{what} holds a bean: call outside ${{...}} with ${{...}} arguments: the text is a template and renders " + "instead of calling (in a condition it is always true). Write the arguments bare, bean:svc.Check(header.x), " + "or the whole call as one placeholder, ${bean:svc.Check(${header.x})}.")); // The same for a registry name: a ${ anywhere makes the whole text a template, so ref:x is text, not the object. if (outside is not null && redb.Route.Expressions.ExpressionResolver.ContainsNamespace(outside, "ref")) findings.Add(new PackageFinding(false, position, $"{what} holds a ref: name outside ${{...}} in a text with ${{...}}: the text is a template and renders " + "ref:name as text instead of reading the object (in a condition it is always true). Write the whole " + "expression bare, ref:limit > header.x, or as one placeholder, ${ref:limit > header.x}.")); foreach (var expression in expressions.Where(redb.Route.Expressions.ExpressionResolver.ContainsNamespacedCall)) { try { foreach (var call in redb.Route.Expressions.BeanCallSite.CallsIn(expression)) calls.Add(new ExpressionBeanCall(file, position, what, call.Reference, call.Method, call.Arguments.Count)); foreach (var reference in redb.Route.Expressions.BeanCallSite.RefsIn(expression)) calls.Add(new ExpressionBeanCall(file, position, what, reference.Reference, null, 0)); } catch (InvalidOperationException ex) { // The parser's words name a broken call better than the compile error recorded above. findings.Add(new PackageFinding(true, position, $"{what} {ex.Message}")); deferred.Remove(expression); } } foreach (var error in deferred.Values) findings.Add(new PackageFinding(true, position, $"{what} {error}")); } /// /// A call to a declared bean whose type resolves: the method exists with that many bindable parameters (the /// binding's own words), and it is synchronous. Both would fail the call on its first message. /// private static void CheckExpressionBeanCalls(List calls, IReadOnlyDictionary instanceTypes, List findings) { foreach (var call in calls.DistinctBy(c => (c.At, c.Reference, c.Method, c.Arguments))) { if (call.Method is null || !instanceTypes.TryGetValue(call.Reference, out var type)) continue; // a ref: calls nothing; undeclared: the #name warning; a C#-registered bean is checked when called try { var bound = redb.Route.Components.Bean.BeanInvoker.ForValues(type, call.Method, call.Arguments, "#" + call.Reference); if (redb.Route.Components.Bean.BeanInvoker.IsAwaitable(bound.Method.ReturnType)) findings.Add(new PackageFinding(true, call.At, $"{call.What} {redb.Route.Expressions.BeanCallSite.AwaitableRefused(call.Reference, call.Method, bound.Method.ReturnType)}")); } catch (InvalidOperationException ex) { findings.Add(new PackageFinding(true, call.At, $"{call.What} {ex.Message}")); } } } private static void ReportUnclosed(string file, XObject at, string value, string what, List findings) { if (!value.Contains("${", StringComparison.Ordinal) || redb.Route.Expressions.TemplateScanner.Scan(value).Unclosed is not [var index, ..]) return; var line = (IXmlLineInfo)at; findings.Add(new PackageFinding(true, $"{file}({line.LineNumber},{line.LinePosition})", $"{what} {redb.Route.Expressions.TemplateScanner.Unclosed(value, index)}")); } /// What turns a rendered condition into a comparison the author expected to be evaluated. private static readonly string[] Operators = ["==", "!=", "=~", ">=", "<=", ">", "<", "&&", "||", " and ", " or ", " eq ", " ne ", " range "]; /// /// Every attribute a spec declares as a type resolves against the built assemblies: the loader /// would fail on it at the worker, so the build fails on it here. Generic over the specs - no /// list of elements - so a package contribution's type attributes are checked the same way. /// Values carrying placeholders or expressions are left to the load. /// private static void CheckTypeAttributes(string file, XElement element, ElementSpec? spec, ElementRegistry registry, Func typeResolver, List findings) { if (spec is not null) { foreach (var attributeSpec in spec.Attributes.Where(a => a.Type is AttributeType.TypeName or AttributeType.TypeNameList)) { var value = element.Attribute(attributeSpec.Name)?.Value; if (string.IsNullOrWhiteSpace(value) || value.Contains("{{", StringComparison.Ordinal) || value.Contains("${", StringComparison.Ordinal)) continue; var names = attributeSpec.Type == AttributeType.TypeNameList ? value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [value.Trim()]; foreach (var name in names) { if (typeResolver(name) is not null) continue; var line = (IXmlLineInfo)element; findings.Add(new PackageFinding(true, $"{file}({line.LineNumber},{line.LinePosition})", $"<{element.Name.LocalName} {attributeSpec.Name}=...>: type '{name}' was not found in the built assemblies.")); } } } foreach (var child in element.Elements()) { var childSpec = spec?.Children.FirstOrDefault(c => c.Name == child.Name.LocalName) ?? registry.Find(child.Name.LocalName)?.Spec; CheckTypeAttributes(file, child, childSpec, registry, typeResolver, findings); } } /// /// Every top-level <bean> read by the loader's own grammar, in LOAD order — /// context.xml, then the artifacts as the manifest lists them, each top to bottom — and each /// reference held against the beans registered before it. A bean declared later is a hard /// error (the load would fail); a bean the package does not declare at all may come from /// module code, so that stays a warning. /// private static void CheckBeanDeclarations( List<(string File, XDocument Document)> documents, HashSet declaredBeans, List<(string File, BeanDeclaration Bean)> beanDeclarations, List findings) { var registeredSoFar = new HashSet(StringComparer.Ordinal); foreach (var (file, document) in documents) { foreach (var element in document.Root?.Elements().Where(e => e.Name.LocalName == "bean") ?? []) { var declaration = BeanModel.Parse(element, (at, message) => findings.Add(new PackageFinding(true, Position(file, at), message))); if (declaration is not null) { beanDeclarations.Add((file, declaration)); foreach (var reference in BeanModel.References(declaration)) { if (registeredSoFar.Contains(reference.Bean)) continue; findings.Add(declaredBeans.Contains(reference.Bean) ? new PackageFinding(true, Position(file, reference.At), $"bean reference '{reference.Bean}' points forward — beans are built in load order " + "(context.xml, then the route files as the manifest lists them, each top to bottom); declare it above.") : new PackageFinding(false, Position(file, reference.At), $"bean reference '{reference.Bean}' is not declared by any of this package — either module code " + "registers it before the XML loads (fine), or it is a dangling reference.")); } } if (element.Attribute("name")?.Value is { Length: > 0 } registered) registeredSoFar.Add(registered); } } } /// A reference attribute whose object must be of a given type (). private sealed record TypedReference(string File, XElement Element, string Attribute, string Name, string TypeName); /// /// Walks an element with its spec, as the parser does, and collects the attributes that /// register a name () and the references that must name /// an object of a given type (). /// private static void CollectRegistryAttributes(string file, XElement element, ElementSpec? spec, ElementRegistry registry, Dictionary registered, List typedReferences) { foreach (var attributeSpec in spec?.Attributes ?? []) { if (element.Attribute(attributeSpec.Name)?.Value is not { Length: > 0 } value) continue; if (attributeSpec.Registers is { } registeredType) registered[value] = registeredType; if (attributeSpec.References is { } referencedType) typedReferences.Add(new TypedReference(file, element, attributeSpec.Name, value.StartsWith('#') ? value[1..] : value, referencedType)); } foreach (var child in element.Elements()) { var childSpec = spec?.Children.FirstOrDefault(c => c.Name == child.Name.LocalName) ?? registry.Find(child.Name.LocalName)?.Spec; CollectRegistryAttributes(file, child, childSpec, registry, registered, typedReferences); } } /// /// With the built assemblies at hand: every typed reference names an object the engine will /// accept — a <bean> of that type, or an element that registers one. The wording /// follows the engine's refusal ('x' is registered as T, which is not an I…). A name /// nothing in the package declares is the undeclared-reference warning, not repeated here. /// private static void CheckTypedReferences( List typedReferences, IReadOnlyDictionary instanceTypes, IReadOnlyDictionary registered, Func typeResolver, List findings) { foreach (var reference in typedReferences) { var actual = instanceTypes.TryGetValue(reference.Name, out var beanType) ? beanType : registered.TryGetValue(reference.Name, out var registeredType) ? typeResolver(registeredType) : null; if (actual is null || typeResolver(reference.TypeName) is not { } expected || expected.IsAssignableFrom(actual)) continue; findings.Add(new PackageFinding(true, Position(reference.File, reference.Element), $"<{reference.Element.Name.LocalName} {reference.Attribute}=\"#{reference.Name}\">: '{reference.Name}' is registered as " + $"{actual.FullName}, which is not an {expected.Name}.")); } } private static IReadOnlyDictionary RunDeepBeanChecks( List<(string File, BeanDeclaration Bean)> beanDeclarations, List<(string File, string Bean, string Method)> beanMethodCalls, Func typeResolver, List findings) { // What each registered bean IS: the declared type, or what its factory method returns. var instanceTypes = new Dictionary(StringComparer.Ordinal); foreach (var (file, bean) in beanDeclarations) { var checker = new BeanTypeChecker(file, instanceTypes, typeResolver, findings); if (checker.Check(bean) is { } instanceType && bean.Name is { Length: > 0 } name) instanceTypes[name] = instanceType; } foreach (var (file, bean, method) in beanMethodCalls.DistinctBy(c => (c.Bean, c.Method))) { if (!instanceTypes.TryGetValue(bean, out var type)) continue; // undeclared bean — already a finding, or module code owns it if (!type.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public) .Any(m => m.Name == method)) findings.Add(new PackageFinding(true, file, $"bean '{bean}': type '{type.FullName}' has no public method '{method}' (bean:#{bean}?method={method}).")); } return instanceTypes; } /// /// The --bin half of the bean checks: every value of a declaration, nested beans and /// list items included, held against the type it will be bound to — the same rules /// applies at load, reported in its words. Text values are left to /// the load: they convert only after their placeholders resolve. /// private sealed class BeanTypeChecker( string file, IReadOnlyDictionary instanceTypes, Func typeResolver, List findings) { /// The type the bean's instance will have, or null after a finding. public Type? Check(BeanDeclaration bean) { var label = bean.Name is { Length: > 0 } name ? $"bean '{name}'" : "nested bean"; var type = typeResolver(bean.TypeName); if (type is null) return Error(bean.At, $"{label}: type '{bean.TypeName}' was not found in the built assemblies."); if (!type.IsPublic && !type.IsNestedPublic) return Error(bean.At, $"{label}: type '{bean.TypeName}' exists but is not public — bean: needs a public type."); var instanceType = type; List? argumentTypes = null; if (bean.TypedArguments) { argumentTypes = []; foreach (var argument in bean.ConstructorArgs) { if (typeResolver(argument.TypeName!) is not { } argumentType) return Error(argument.Value.At, $"{label}: : the type was not found in the built assemblies."); argumentTypes.Add(argumentType); } } if (bean.FactoryMethod is { } factory) { // The loader's own choice (BeanFactory.FactoryMethod): the exact signature, or the // single overload of that arity — several of them are refused, not guessed. MethodInfo method; try { method = BeanFactory.FactoryMethod(type, factory, bean.ConstructorArgs.Count, argumentTypes); } catch (InvalidOperationException ex) { return Error(bean.At, $"{label}: {ex.Message}"); } // The parameters after the given arguments are optional and take their defaults. var parameters = method.GetParameters(); for (var i = 0; i < bean.ConstructorArgs.Count; i++) CheckValue(bean.ConstructorArgs[i].Value, parameters[i].ParameterType, $"{factory} argument {i + 1}"); instanceType = method.ReturnType; } else if (argumentTypes is not null) { ConstructorInfo constructor; try { constructor = BeanFactory.Constructor(type, bean.ConstructorArgs.Count, argumentTypes); } catch (InvalidOperationException ex) { return Error(bean.At, $"{label}: {ex.Message}"); } var parameters = constructor.GetParameters(); for (var i = 0; i < bean.ConstructorArgs.Count; i++) CheckValue(bean.ConstructorArgs[i].Value, parameters[i].ParameterType, $"constructorArg {i + 1}"); } else if (bean.ConstructorArgs.Count > 0) { // The constructor is chosen at load from the built arguments (ActivatorUtilities): each argument goes to a // parameter its value is assignable to, text as System.String. So the arguments are checked as built. var built = new List(); for (var i = 0; i < bean.ConstructorArgs.Count; i++) { var value = bean.ConstructorArgs[i].Value; built.Add(value switch { ScalarBeanValue => typeof(string), RefBeanValue reference => instanceTypes.TryGetValue(reference.Bean, out var referenced) ? referenced : null, NestedBeanValue nested => Check(nested.Bean), ListBeanValue { ElementTypeName: { } element } => typeResolver(element)?.MakeArrayType(), _ => null, }); if (value is not NestedBeanValue) CheckValue(value, null, $"constructorArg {i + 1}"); } if (built.All(t => t is not null) && !type.GetConstructors().Any(c => TakesBuilt(c.GetParameters(), built!))) return Error(bean.At, $"{label}: no public constructor of '{type.FullName}' takes ({BeanFactory.Signature(built!)}): " + "without type= a constructorArg is passed as it is built, text as System.String." + TypedHint(type, bean.ConstructorArgs.Count)); } foreach (var property in bean.Properties) { if (instanceType.GetProperty(property.Key) is not { CanWrite: true } info) { Error(property.At, $"{label}: type '{instanceType.FullName}' has no writable public property '{property.Key}'."); continue; } CheckValue(property.Value, info.PropertyType, property.Key); } return instanceType; } /// /// Whether ActivatorUtilities could pass the built arguments to these parameters: every argument to its own /// parameter of a type it is assignable to (the parameters left over come from DI or their defaults). /// private static bool TakesBuilt(ParameterInfo[] parameters, IReadOnlyList built) { var taken = new bool[parameters.Length]; foreach (var argument in built) { var index = -1; for (var i = 0; i < parameters.Length && index < 0; i++) { if (!taken[i] && parameters[i].ParameterType.IsAssignableFrom(argument)) index = i; } if (index < 0) return false; taken[index] = true; } return true; } /// The type= to write when exactly one public constructor takes that many arguments. private static string TypedHint(Type type, int count) { var candidates = type.GetConstructors().Where(c => c.GetParameters().Length == count).ToList(); if (candidates.Count != 1) return " Name the parameter types with ."; var parameters = candidates[0].GetParameters(); return " Name the parameter types: " + string.Join(" ", parameters.Select(p => $"")) + "."; } private void CheckValue(BeanValue value, Type? target, string slot) { switch (value) { case RefBeanValue reference: if (target is not null && instanceTypes.TryGetValue(reference.Bean, out var referenced) && !target.IsAssignableFrom(referenced)) Error(reference.At, BeanFactory.NotAssignable(referenced, target, slot)); break; case NestedBeanValue nested: if (Check(nested.Bean) is { } nestedType && target is not null && !target.IsAssignableFrom(nestedType)) Error(nested.At, BeanFactory.NotAssignable(nestedType, target, slot)); break; case ListBeanValue list: CheckList(list, target, slot); break; } } private void CheckList(ListBeanValue list, Type? target, string slot) { Type? element = null; if (target is not null) { element = BeanFactory.ElementTypeOf(target); if (element is null) { Error(list.At, BeanFactory.NotAListShape(target, slot)); return; } } if (list.ElementTypeName is not null) { var named = typeResolver(list.ElementTypeName); if (named is null) { Error(list.At, $": the type was not found in the built assemblies."); return; } if (element is not null && named != element) { Error(list.At, BeanFactory.ElementTypeDiffers(named, element, slot)); return; } element = named; } else if (element is null) { Error(list.At, BeanFactory.ConstructorListNeedsOf(slot)); return; } for (var i = 0; i < list.Items.Count; i++) CheckValue(list.Items[i], element, $"{slot}[{i}]"); } private Type? Error(XElement at, string message) { findings.Add(new PackageFinding(true, Position(file, at), message)); return null; } } private static string Position(string file, XElement at) => at is IXmlLineInfo line && line.HasLineInfo() ? $"{file}({line.LineNumber},{line.LinePosition})" : file; /// /// Walks a document for endpoints — a uri attribute of an address-carrying element, /// or its structured endpoint child — and hands each one's parameters to the checker. /// interceptFrom / interceptSendToEndpoint carry a PATTERN to match, never an /// endpoint to create, so they bind nothing and are not held against a connector. /// private static void CheckEndpoints(string file, XElement element, ElementSpec? spec, ElementRegistry registry, IEndpointVisitor checker) { if (element.Name.LocalName is "interceptFrom" or "interceptSendToEndpoint") return; var takesEndpoint = element.Name.LocalName == "from" || spec?.TakesEndpoint == true; if (takesEndpoint) { // creates the consumer; every other address-carrying step creates a producer // (pollEnrich included — the engine polls through a producer). var side = element.Name.LocalName == "from" ? EndpointRole.Consumer : EndpointRole.Producer; if (element.Attribute("uri")?.Value is { } uri) { checker.CheckUri(file, element, uri, side); } else if (element.Elements().ToList() is [var endpoint]) { checker.CheckStructured(file, endpoint, side); } return; } foreach (var child in element.Elements()) { var childSpec = spec?.Children.FirstOrDefault(c => c.Name == child.Name.LocalName) ?? registry.Find(child.Name.LocalName)?.Spec; // Children with an address of their own (a recipient list's ) are // specs with a uri attribute of their own. if (childSpec?.Attributes.Any(a => a.Name == "uri" && a.Type == AttributeType.Uri) == true && !childSpec.TakesEndpoint && child.Attribute("uri")?.Value is { } childUri) { checker.CheckUri(file, child, childUri, EndpointRole.Producer); continue; } CheckEndpoints(file, child, childSpec, registry, checker); } } /// What hands each endpoint it finds to, in the URI form or the structured form. private interface IEndpointVisitor { void CheckUri(string file, XElement at, string uri, EndpointRole side); void CheckStructured(string file, XElement endpoint, EndpointRole side); } /// The components of the core (vm, direct-vm, bean, …), whose options the gate knows without --bin. private static readonly Lazy> CoreCatalog = new(() => ComponentCatalog.Build( typeof(EndpointOptions).Assembly.GetTypes() .Where(t => !t.IsAbstract && typeof(redb.Route.Abstractions.IComponent).IsAssignableFrom(t)) .Select(t => (Type: t, Constructor: t.GetConstructors().FirstOrDefault(c => c.GetParameters().All(p => p.IsOptional)))) .Where(c => c.Constructor is not null) // A constructor whose parameters are all optional counts as a default one: log takes an optional logger factory. .Select(c => (redb.Route.Abstractions.IComponent)c.Constructor!.Invoke( [.. c.Constructor.GetParameters().Select(p => p.DefaultValue)])))); /// The catalog of the built output, and the core components it does not list itself. private static IReadOnlyList WithCoreComponents(IReadOnlyList? catalog) { if (catalog is null) return CoreCatalog.Value; var schemes = catalog.Select(c => c.Scheme).ToHashSet(StringComparer.OrdinalIgnoreCase); return [.. catalog, .. CoreCatalog.Value.Where(c => !schemes.Contains(c.Scheme))]; } /// /// The registry names an endpoint writes into an option marked [RegistryReference] /// (). A bare name (connectionFactory=main) joins the package's /// references, as the position rule already adds a #name, so one no <bean> declares is the usual /// warning. A name in an option marked with a type, bare or with #, is held against that type, per connector /// (); an option marked without one (object) is never. A value built from /// configuration or an expression ({{…}}, ${…}) is not knowable here. /// private sealed class RegistryReferenceCollector( IReadOnlyList catalog, List<(string File, string Name)> references, List typed) : IEndpointVisitor { private readonly HashSet _endpointAttributes = []; public void CheckUri(string file, XElement at, string uri, EndpointRole side) { if (at.Attribute("uri") is { } attribute) _endpointAttributes.Add(attribute); Read(file, at, "uri", uri); } /// /// Any other attribute whose value is a URI with options (a constant recipientList expr="vm:a?…", a /// routingSlip or dynamicRouter address): read the same way, per scheme, as the gate has always /// read a #name there. The endpoint positions walks are read once, there. /// public void CheckAttribute(string file, XElement element, XAttribute attribute) { if (_endpointAttributes.Contains(attribute)) return; var value = attribute.Value; var query = value.IndexOf('?'); if (query < 0 || !UriScheme.IsMatch(value[..query])) return; Read(file, element, attribute.Name.LocalName, value); } private void Read(string file, XElement at, string attributeName, string uri) { if (uri.StartsWith("{{", StringComparison.Ordinal) || uri.StartsWith("${", StringComparison.Ordinal)) return; var colon = uri.IndexOf(':'); if (colon <= 0 || Find(uri[..colon]) is not { } component) return; Collect(file, at, component, EndpointUriParser.Parse(uri).RawParameters.Select(p => (p.Key, p.Value)), key => $"{attributeName}=…{key}"); } public void CheckStructured(string file, XElement endpoint, EndpointRole side) { if (Find(endpoint.Name.LocalName) is not { } component) return; // Shape errors of the structured form are the parameter checker's to report; here they only end the walk. if (StructuredEndpoint.Options(endpoint, component.PathSynonym, (_, _) => { }) is { } options) Collect(file, endpoint, component, options.Select(o => (o.Key, o.Value)), key => key); } private void Collect(string file, XElement at, CatalogComponent component, IEnumerable<(string Key, string Value)> parameters, Func attribute) { foreach (var (key, value) in parameters) { if (component.Options.FirstOrDefault(o => string.Equals(o.Name, key, StringComparison.OrdinalIgnoreCase)) is not { Reference: { } expected }) continue; var written = value.Trim(); if (written.Contains("{{", StringComparison.Ordinal) || written.Contains("${", StringComparison.Ordinal)) continue; // known only at run time var bare = !written.StartsWith('#'); if (LeadingReference.Match(bare ? "#" + written : written) is not { Success: true } match || match.Length != (bare ? written.Length + 1 : written.Length)) continue; // empty, or not a plain registry name var name = match.Groups[1].Value; if (bare) references.Add((file, name)); // a #name is read by the position rule already if (expected != "object") typed.Add(new TypedReference(file, at, attribute(key), name, expected)); } } private CatalogComponent? Find(string scheme) => catalog.FirstOrDefault(c => string.Equals(c.Scheme, scheme, StringComparison.OrdinalIgnoreCase) || c.AlternateSchemes.Contains(scheme, StringComparer.OrdinalIgnoreCase)); } /// /// Holds an endpoint's parameter names against its connector the way /// EndpointOptions.BindFromUri does when the endpoint is created: a name with no /// writable option is refused unless the connector is lenient. The wording is the engine's /// own — the checker binds the unknown names into a fresh options object and reports what /// the engine said, nearest option and connector hint included. Names built at run time /// (${…}, {{…}}) are not knowable here and are left to the engine. /// /// /// Refuses a scheme on the side its component does not have: <from uri="log:…"/>, /// <to><timer/></to>. The position is the step for the URI form and the endpoint element for the /// structured form; the message is the runtime's () after the step's name. /// private sealed class EndpointSideChecker(IReadOnlyList catalog, List findings) : IEndpointVisitor { public void CheckUri(string file, XElement at, string uri, EndpointRole side) { var separator = uri.IndexOf(':'); if (separator > 0) Check(file, at, at.Name.LocalName, uri[..separator], side); } public void CheckStructured(string file, XElement endpoint, EndpointRole side) => Check(file, endpoint, endpoint.Parent?.Name.LocalName ?? endpoint.Name.LocalName, endpoint.Name.LocalName, side); private void Check(string file, XElement at, string step, string scheme, EndpointRole side) { if (scheme.Contains("{{", StringComparison.Ordinal) || scheme.Contains("${", StringComparison.Ordinal)) return; var component = catalog.FirstOrDefault(c => string.Equals(c.Scheme, scheme, StringComparison.OrdinalIgnoreCase) || c.AlternateSchemes.Contains(scheme, StringComparer.OrdinalIgnoreCase)); if (component?.Role is { } only && only != side) findings.Add(new PackageFinding(true, Position(file, at), $"<{step}>: {EndpointSides.MissingSide(scheme, only, component.RoleHint)}")); } } private sealed class EndpointParameterChecker( IReadOnlyList catalog, Func typeResolver, List findings) : IEndpointVisitor { public void CheckUri(string file, XElement at, string uri, EndpointRole side) { // An address whose scheme itself comes from a placeholder or an expression names no // connector until run time — there is nothing to hold its parameters against here. if (uri.StartsWith("{{", StringComparison.Ordinal) || uri.StartsWith("${", StringComparison.Ordinal)) return; var scheme = SchemeOf(uri); if (scheme is null || Find(scheme) is null) return; Check(file, at, at, scheme, EndpointUriParser.Parse(uri).RawParameters.Select(p => (p.Key, p.Value)), side); } public void CheckStructured(string file, XElement endpoint, EndpointRole side) { var component = Find(endpoint.Name.LocalName); if (component is null) return; var options = StructuredEndpoint.Options(endpoint, component.PathSynonym, (at, message) => findings.Add(new PackageFinding(true, Position(file, at), message))); if (options is null) return; Check(file, endpoint, endpoint.Parent!, component.Scheme, options.Select(o => (o.Key, o.Value)), side); } /// The scheme the way reads it, or null when there is none. private static string? SchemeOf(string uri) { var colon = uri.IndexOf(':'); return colon > 0 ? uri[..colon].ToLowerInvariant() : null; } private void Check(string file, XElement at, XElement step, string scheme, IEnumerable<(string Key, string Value)> parameters, EndpointRole side) { if (Find(scheme) is not { } component) return; var pairs = parameters.ToList(); var written = pairs.Select(p => p.Key) .Where(k => !k.Contains("${", StringComparison.Ordinal) && !k.Contains("{{", StringComparison.Ordinal)) .Distinct(StringComparer.OrdinalIgnoreCase) .ToList(); // An option only the other side reads — the declaration the connector refuses it by // (EndpointRole), lenient connector or not. foreach (var key in written) { if (component.Options.FirstOrDefault(o => string.Equals(o.Name, key, StringComparison.OrdinalIgnoreCase)) is { Role: { } role } && role != side) { findings.Add(new PackageFinding(true, Position(file, at), $"<{scheme}>: '{key}' is read only by the {Side(role)} side of the {scheme} endpoint; " + $"<{step.Name.LocalName}> creates the {Side(side)}, which refuses it.")); } } // Beside the option that names the connection factory a connection parameter is refused, // the factory being the whole connection — the declarations and wording of // EndpointOptions.BindFromUri ([ConnectionFactoryReference], [ConnectionParameter]). if (component.Options.FirstOrDefault(o => o.ConnectionFactoryReference) is { } reference && pairs.FirstOrDefault(p => string.Equals(p.Key, reference.Name, StringComparison.OrdinalIgnoreCase)) is { Value.Length: > 0 } factory) { var beside = written .Where(k => component.Options.Any(o => o.ConnectionParameter && string.Equals(o.Name, k, StringComparison.OrdinalIgnoreCase))) .ToList(); if (beside.Count > 0) findings.Add(new PackageFinding(true, Position(file, at), $"<{scheme}>: {factory.Key} '{factory.Value}' sets the whole connection, so {string.Join(", ", beside)} " + $"cannot be given on the URI as well. Set them on the factory, or drop {factory.Key} and give the connection on the URI.")); } if (component is not { Lenient: false, OptionsType: { } optionsTypeName }) return; if (typeResolver(optionsTypeName) is not { } optionsType) return; // As the binder names them: a member of an option group is Group.Member. var writable = EndpointOptions.BindableOptions(optionsType) .Select(o => o.Name) .ToHashSet(StringComparer.OrdinalIgnoreCase); var unknown = written.Where(k => !writable.Contains(k)).ToList(); if (unknown.Count == 0) return; findings.Add(new PackageFinding(true, Position(file, at), $"<{scheme}>: {EngineWording(optionsType, scheme, unknown)}")); } private static string Side(EndpointRole role) => role == EndpointRole.Consumer ? "consumer" : "producer"; private CatalogComponent? Find(string scheme) => catalog.FirstOrDefault(c => string.Equals(c.Scheme, scheme, StringComparison.OrdinalIgnoreCase) || c.AlternateSchemes.Contains(scheme, StringComparer.OrdinalIgnoreCase)); /// /// The refusal the engine gives for these names. The options type comes from the built /// output, possibly in its own load context, so the call goes through reflection; the /// engine throws (a core type, shared by every context). /// private static string EngineWording(Type optionsType, string scheme, IReadOnlyList unknown) { // Without a parameterless constructor there is no options object to ask; the finding // stands all the same, named plainly. if (optionsType.GetConstructor(Type.EmptyTypes) is null) return string.Join(" ", unknown.Select(k => $"'{k}' is not an option of the {scheme} endpoint.")); var options = Activator.CreateInstance(optionsType)!; var bind = optionsType.GetMethod("BindFromUri", [typeof(IReadOnlyDictionary)]) ?? throw new InvalidOperationException($"{optionsType.FullName} has no BindFromUri — not an endpoint options type."); try { bind.Invoke(options, [unknown.ToDictionary(k => k, _ => string.Empty, StringComparer.OrdinalIgnoreCase)]); } catch (TargetInvocationException ex) when (ex.InnerException is ArgumentException refusal) { // .NET appends " (Parameter 'name')" to the message; the finding names the parameter already. var suffix = refusal.ParamName is { } parameter ? $" (Parameter '{parameter}')" : null; return suffix is not null && refusal.Message.EndsWith(suffix, StringComparison.Ordinal) ? refusal.Message[..^suffix.Length] : refusal.Message; } throw new InvalidOperationException( $"{optionsType.FullName} accepted {string.Join(", ", unknown)} although it has no such options and is not lenient — " + "the package gate and EndpointOptions.BindFromUri disagree."); } } private static void LoadDocument(string file, string path, List<(string, XDocument)> documents, List findings) { try { documents.Add((file, SafeXml.LoadFile(path, LoadOptions.SetLineInfo))); } catch (System.Xml.XmlException ex) { findings.Add(new PackageFinding(true, file, $"not well-formed XML: {ex.Message}")); } } private static void ScanPlaceholders(string value, SortedSet requiredKeys) { foreach (Match match in Placeholder.Matches(value)) { if (!match.Groups[2].Success) requiredKeys.Add(match.Groups[1].Value.Trim()); } } private static void CopyTree(string source, string target) { Directory.CreateDirectory(target); foreach (var file in Directory.GetFiles(source, "*", SearchOption.AllDirectories)) { var destination = Path.Combine(target, Path.GetRelativePath(source, file)); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(file, destination); } } } Path: redb-route/redb.Route.Xml/Packaging/RouteProjectResourceResolver.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/Packaging/RouteProjectResourceResolver.cs ---- using redb.Route.Abstractions; namespace redb.Route.Xml.Packaging; /// /// Reads a route's file= references from the project on disk by /// , the rule the packaging checks and the Tsak loader /// share: the tool's csharp and mermaid find exactly the files check accepts. /// /// The route file whose references are resolved. public sealed class RouteProjectResourceResolver(string routeFile) : IRouteResourceResolver { /// public string? Resolve(string reference) { ArgumentException.ThrowIfNullOrWhiteSpace(reference); return RoutePackage.ResourceCandidatesFor(routeFile, reference).FirstOrDefault(File.Exists); } /// public string DescribeSearch(string reference) => string.Join(", ", RoutePackage.ResourceCandidatesFor(routeFile, reference)); } Path: redb-route/redb.Route.Xml/Packaging/RouteProjectScaffold.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/Packaging/RouteProjectScaffold.cs ---- using System.Reflection; namespace redb.Route.Xml.Packaging; /// /// Scaffolds a route project (an ordinary .csproj — VS Code, Visual /// Studio and Rider all open it — carrying the XML artifacts, the context document and the /// layered configuration in OUR convention): the L4 config holds module identity ONLY, secrets /// arrive through the merged context configuration at deploy time (the identity/context.json /// conveyor, never the everything-in-the-package legacy style), the generated XSD wires editor /// autocompletion with no extension of ours, and redb-route-xml pack turns the project /// into the package layout with the packaging checks as the gate. /// public static class RouteProjectScaffold { /// Creates a new route project in /. /// Where to create the project directory. /// Project and package name. /// The route context name (defaults to the lowercased name). /// /// A local redb.Route.Xml.csproj path to reference instead of the NuGet package — /// for working against a checkout before the packages are published. /// /// The project directory. public static string Create(string parentDir, string name, string? contextName = null, string? runtimeProjectPath = null) { ArgumentException.ThrowIfNullOrWhiteSpace(parentDir); ArgumentException.ThrowIfNullOrWhiteSpace(name); contextName ??= name.ToLowerInvariant(); var dir = Path.Combine(parentDir, name); if (Directory.Exists(dir) && Directory.EnumerateFileSystemEntries(dir).Any()) throw new InvalidOperationException($"'{dir}' already exists and is not empty."); Directory.CreateDirectory(dir); Directory.CreateDirectory(Path.Combine(dir, RoutePackage.RoutesDir)); Directory.CreateDirectory(Path.Combine(dir, RoutePackage.ResourcesDir)); Directory.CreateDirectory(Path.Combine(dir, RoutePackage.ConfigDir)); Directory.CreateDirectory(Path.Combine(dir, "schema")); Directory.CreateDirectory(Path.Combine(dir, ".vscode")); var runtimeVersion = typeof(XmlRouteLoader).Assembly .GetCustomAttribute()?.InformationalVersion ?.Split('+')[0] ?? "4.0.0"; var runtimeReference = runtimeProjectPath is null ? $"""""" : $""""""; File.WriteAllText(Path.Combine(dir, $"{name}.csproj"), $""" net10.0 enable enable {name} {contextName} true {runtimeReference} """); File.WriteAllText(Path.Combine(dir, RoutePackage.ContextFile), """ """); File.WriteAllText(Path.Combine(dir, RoutePackage.RoutesDir, "main.route.xml"), $""" """); // L4 — module identity ONLY. Everything else arrives through the merged // context configuration at deploy time; secrets never ride inside the package. File.WriteAllText(Path.Combine(dir, RoutePackage.ConfigDir, $"{name}.config.json"), $$""" { "//": "L4 (in-package): module identity ONLY. Settings and secrets come from the merged context configuration (see config/context.sample.json).", "ContextName": "{{contextName}}", "AutoStart": true } """); File.WriteAllText(Path.Combine(dir, RoutePackage.ConfigDir, "context.sample.json"), $$$""" { "//": [ "L3 deploy sample — copy as context.json NEXT TO the package on the host; never commit real secrets here.", "Merged configuration, later layers win:", " L1 host appsettings: Contexts default section", " L2 host appsettings: this context's section", " L3 this file: Contexts.default + Contexts.{{{contextName}}}", " L4 in-package: ContextName + AutoStart only (module identity)", " L5 Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must receive a value from", "one of these layers; `redb-route-xml pack` lists them in manifest.json", "under RequiredConfigKeys, and the module fails fast at init when one is missing." ], "Contexts": { "default": {}, "{{{contextName}}}": { } } } """); File.WriteAllText(Path.Combine(dir, "schema", "redb-route-1.0.xsd"), XmlRouteSchema.Generate(ElementRegistry.CreateDefault()).ToString()); File.WriteAllText(Path.Combine(dir, ".vscode", "settings.json"), """ { "xml.fileAssociations": [ { "pattern": "**/*.route.xml", "systemId": "./schema/redb-route-1.0.xsd" } ] } """); File.WriteAllText(Path.Combine(dir, "README.md"), $""" # {name} A redb.Route XML route project. The layout is the packaging convention: | Path | What | |---|---| | `routes/*.route.xml` | the route artifacts (explicit manifest order) | | `context.xml` | components, context beans, the one-time init pipeline | | `resources/` | XSLT, schemas — resolved from the package root | | `config/{name}.config.json` | L4: module identity ONLY | | `config/context.sample.json` | L3 sample for deployment | | `schema/` | generated XSD — VS Code autocompletion via the RedHat XML extension | Build the package (checks are the gate — a broken reference is a build error): redb-route-xml pack . --version 1.0.0 Regenerate C# or a diagram from a route: redb-route-xml csharp routes/main.route.xml --namespace {name}.Routes redb-route-xml mermaid routes/main.route.xml Configuration is layered; secrets never ride inside the package. See `config/context.sample.json` for the conveyor and `manifest.json` of a built package for the required keys. """); return dir; } } Path: redb-route/redb.Route.Xml/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/README.md ---- # redb.Route.Xml > Documentation and articles: Declarative XML routes for [redb.Route](https://www.nuget.org/packages/redb.Route): `.route.xml` documents load into the existing fluent DSL — **one engine, no second semantics**. Every element is a thin facade over exactly one DSL verb; whatever the XML can say, C# can say, and the two spellings produce byte-identical definition trees (the test suite proves it for every shipped example). What you get on top of the engine: - the **full EIP vocabulary** as XML — ~60 elements covering every string-expressible verb of the DSL, plus container-level handlers and the REST DSL; - **load-time failure** for everything that can fail early: unknown elements (with a *did-you-mean* hint), malformed expressions, unregistered URI schemes, attribute typos — all collected in **one pass** with `file(line,column)` positions; - a **generated XSD** for editor autocompletion (VS Code / Visual Studio / Rider, no plugin of ours), a **component catalog** for property panels, a **C# generator** and **Mermaid diagrams** from the same parse; - **project scaffolding and packaging**: `redb-route-xml new` → an ordinary `.csproj` with routes, resources and layered configuration; `pack` → a signed-ready package layout with a manifest and a hard-error check gate. ## Quick start ```csharp await using var context = new RouteContext() .AddXmlRoutesFromContent(""" """); await context.Start(); ``` Files and globs work the same way — `AddXmlRoutes("routes/*.route.xml")` loads every match in deterministic order (relative paths resolve through the route resource resolver, never the process working directory), and a pattern matching nothing is an error naming the searched places. In a DI host, register inside `AddRedbRoute`: ```csharp services.AddRedbRoute(r => r.AddXmlRoutes("routes/*.route.xml")); ``` A document with errors registers **nothing** — there is no half-loaded state. ## The format at a glance The namespace is `urn:redb:route:1.0`; the major part changes only on a breaking format change, and a document carrying a newer minor is refused with "update the redb.Route.Xml package" rather than a confusing parse error. Every element lives in this namespace — a foreign-namespace element never passes just because its local name matches. Every element accepts `id=` and `description=`: they flow into step identity (message history node ids and labels, `WeaveById` targets, generated-code comments). **Leaf steps** — `to`, `toD`, `setHeader`, `setProperty`, `setBody`, `setHeaders`, `setProperties`, `transform`, `removeHeader/Property/Body/Headers/Properties`, `addAttachment` (exactly one of `expr`, `fromBody="true"`, `file`, `fileExpr`; `name`, `fileName` or `fileNameExpr`, `contentType`), `removeAttachment`, `removeAttachments`, `log`, `delay`, `stop`, `throwException`, `convertBody`, `wireTap`, `validate`, `sort`, `sample`, `streamCaching`, `validateJsonSchema`, `validateXsd`, `xslt`, `marshal`, `unmarshal`, `controlBus`, `enrich`, `pollEnrich`, `recipientList`, `dynamicRouter`, `routingSlip`, `claimCheck`, `beginTransaction`, `commitTransaction`, `rollbackTransaction`, `rollbackAll`, `exceptionHandled`, `routePolicy`, `saga`, `scatterGather`, `loadBalance`, `normalize`, `spanTag` (`key`, `value` or `expr`, `target="Inbound"` for the request's own span — a business key to find the trace by; exported unfiltered). **Scopes** (children are steps) — `filter`, `split` (with `tokenizeLines` / `tokenizeXml` / `tokenizeJsonArray` children), `multicast`, `aggregate`, `tryCatch` (`try`/`catch`/`finally`), `loop` (count / expr / while), `throttle` (plain and keyed), `debounce`, `circuitBreaker` (with `fallback`), `idempotentConsumer`, `resequence`, `transaction`, `traced`, `metered`, `replayable`, `threads`, `ofType`, `onException`, `intercept`, `interceptFrom`, `interceptSendToEndpoint`, `onCompletion`. **Branching** — `choice` with `when` (expression or `predicate="#name"` registry reference) and `otherwise`. **Pools of detached steps** (Apache Camel's attributes) — `` runs the tap on a pool built from that thread pool profile instead of the context's default profile. `` runs in the caller, which waits for it; `parallelProcessing="true"` runs it on a pool of its own built from the default profile and `executorService="name"` on one built from a named profile (it implies `parallelProcessing`). A profile is registered in `RedbRoute:ThreadPoolProfiles:` or with `IRouteContext.AddThreadPoolProfile`; an unknown name fails when the route is built. **Container level** (directly under ``; the handlers apply to the routes of this file) — `bean`, `onException`, `intercept`, `interceptFrom`, `interceptSendToEndpoint`, `onCompletion`, and package-contributed top-level elements such as `rest`. `routeConfiguration` is the container-level element whose `onException` blocks reach the routes of **other** files too. A few rules that keep documents unambiguous: - `value=` is a constant, `expr=` is an expression — **both at once is a schema error**, and which one you used decides the meaning, never the content of the string; - file-or-content elements (`xslt`, `validateXsd`, `validateJsonSchema`, `transformJson`, `payload`) take `file=`/locator **or** inline content (CDATA welcome) — not both; - `` keeps the file, so the schema's imports and includes resolve relative to it, from under `schemaRoot=` (relative to the schema's directory, which is the default); inline content is one schema, and `schemaRoot=` on it is an error; - `` requires an explicit `strategy` — there is no silent default; - a condition is written `header.kind == 'order'`, **not** `${header.kind} == 'order'`: with `${…}` the line is a template, and a template in a condition position renders to a non-empty string, which is true whatever the header holds; - a `${…}` placeholder in a **consumer** URI (``) is refused at load: there is no message to resolve it against. ## Expressions Positions decide meaning — the same rule the fluent DSL follows: | Position | Elements | Becomes | |---|---|---| | condition | `filter`, `when`, `validate`, `loop while=` | a predicate | | value | `setBody`, `setHeader`, `transform`, `toD`, keys and correlations | an evaluated object | | plain string | `uri`, `id`, `description`, `name`, literal `value=` | a literal, never parsed | The expression language is the engine's own — `${header.x}`, `count(property.items) > 2 ? 'many' : 'few'`, `${jpath('$.order.id')}`, `${xpath('/order/@id')}`, arithmetic, `uuid()`, `datediff(...)`, `messageHistory(...)` (the exchange's own trail: `'compact'`, `'count'`, `'slowestMs'`, ...), `stats(...)` (endpoint statistics, and the OpenTelemetry layer through `'otel:'`), the message attachments (`attachments.size`, `attachmentContentAsText('note')`, `attachmentContentType(...)`, `attachmentHeader(...)`) — and a broken expression fails **when the document loads**, not on the first message. Whitespace around operators is insignificant, so `expr="header.amount>1000"` avoids XML escaping entirely (`>` needs no escape in attribute values; `<` does). Membership is `in` / `not in`, against a list the message carries or a literal in parentheses: ```xml … … ``` Type-shaped checks the language cannot express go through the registry: `` resolves an `IPredicate` you registered from code. ### Calling code A bean declared with `` (or registered from code) is called as a step, or from any expression: ```xml ``` The step may call an asynchronous method; the `bean:` function is synchronous, as in Apache Camel's Simple, and refuses a method returning a task. `check` / `pack` verify each call, the method and its number of arguments included with `--bin`. The language guide is [EXPRESSIONS.md](../EXPRESSIONS.md). ## Endpoints: URI form and structured form Short addresses stay URIs. Long or option-heavy ones can be written structurally — the loader normalizes the element into **the same URI string** before any endpoint exists, so the whole engine pipeline (endpoint cache, statistics, mock masks, secret redaction) sees one canon: ```xml ``` The rules are generic — **no connector has XML-specific code**: - the element name is the scheme; every attribute becomes a query option verbatim — except an attribute in a foreign namespace, which is metadata for other tools and never reaches the connector; - the path part is the universal `path=` attribute, the component's declared one-line synonym (`kafka` → `topic`, `file` → `directory`), or the element's text content for text-path components (`sql` — and `path=` on those is refused: the query belongs in CDATA); - `` children become `param.name=…` family options; a child with content and no `name` becomes a long text option (``); - connection factories are ordinary options carrying registry references: `connectionFactory="#mainKafka"`, `dataSource="#main-db"`. ## Container level: beans, handlers, REST `` declares objects in the context registry — the factories your endpoints reference: ```xml ``` Values resolve `{{key}}` / `{{key:default}}` through the context's configuration chain (`IConfiguration` with the host's own sources, then context properties, then the OS environment only when the context has no `IConfiguration`) **before** type conversion — `{{ldap.port:636}}` binds to an `int`. Nested anonymous beans build option graphs inline. Objects with real dependencies stay in code; XML references them by `#name`. The same placeholders work in endpoint URIs, in `enabled=` of a route and in `value=` of ``, `` and ``: `` sets the configured value, resolved through the same chain when the route first runs (`Placeholder("{{ldap.user}}")` in C#). A key with no value and no default fails the exchange, in the words a URI uses. Inside an `expr=` the expression language reads the message, not the configuration: put a configured value into a header first and read `${header.…}`. A `` or `` takes exactly one of: `value=`, `ref=`, one nested anonymous ``, one ``. So a factory that holds an OBJECT - a certificate, a credentials object, a serializer - is declarable too. When the type is built by a static creator rather than a constructor, `factoryMethod=` names it and the `` values are its arguments: ```xml ``` A constructor or factory method is called the way C# calls it: the parameters after the given arguments must be optional and take their defaults (`LoadPkcs12FromFile` has two more), and an overload no markup value can reach (a `ReadOnlySpan` password) is not a candidate. When several overloads still fit the values, name the parameter types with `type=` on every ``, Spring's `constructor-arg type`; the values are then converted to exactly those types. The `(string, string)` constructor of `X509Certificate2` (obsolete in favour of `X509CertificateLoader`) is one of several two-argument ones: ```xml ``` `type=` goes on every argument or on none. Without it an ambiguous choice is a load error that lists the candidates, never a guess. A bean can point at another bean and hold a list. `ref="name"` (or `` inside a list) is the registered instance itself, not a copy. A `` holds `` text, ``, anonymous `` and nested `` items, and builds into the declared type of the property: `T[]`, `List`, `IList`, `ICollection`, `IReadOnlyList`, `IReadOnlyCollection` or `IEnumerable`. Each item is converted to or checked against `T`: ```xml {{as4.port}}8443 ``` Rules: - **References look back only.** Beans are built in load order: the context file first, then the route files in the order the package manifest lists them, each file from top to bottom. A reference must name a bean declared above it, or one that module code registers before the XML loads. A forward or unknown reference is a load error with its position, never a `null`. - **`ref` is the bare name:** `ref="acme"`, not `ref="#acme"`. The `#` belongs to URI options. - **`of=` names the element type where nothing else does.** On a property or a `factoryMethod` argument the target type is known, so `of=` may be left out. When `of=` is written, it must equal that element type. A constructor is chosen only after its arguments are built, so a list passed to a constructor needs ``; it is built as `T[]`, which a constructor taking `T[]`, `IEnumerable` or `IReadOnlyList` accepts. - `` appears only inside a ``; a single value is `value=` on the slot. `redb-route-xml check` reads beans with the loader's grammar. It reports a forward reference as an error. A reference the package does not declare is a warning, because module code may register it. With `--bin` it also checks every value against its target type: list items, nested beans, and the type a `factoryMethod` returns. Repositories are beans like any other. `repository="#dedup"` on `` or ``, and a consumer's `idempotentRepository=dedup`, look up the bare name `dedup` and check its type: ```xml … ``` The gate counts `` as a declaration of `dedup`, the same as a ``. With `--bin` it also checks that the named object implements what the reference needs: `IIdempotentRepository` for ``, `IClaimCheckRepository` for ``. Handlers declared at the container level apply to the routes **of their own file** — each file is a route builder, and a builder's `onException`, `intercept*` and `onCompletion` cover its own routes (Apache Camel's RouteBuilder scope; they used to leak to every route of the context — see the CHANGELOG). For a failure of any route of the context that no `onException` took, the context has its dead letter channel: `` in `context.xml` (see [The context document](#the-context-document)). ```xml [ERR] ${routeId}: ${exception.message} ``` ### Handlers shared by several files: `` Apache Camel's Route Configuration. Its `` blocks apply to the routes of every file and every C# builder of the context, so one file can hold the error handling of a whole module: ```xml [ERR] ${routeId}: ${exception.message} ``` ```xml ... ``` - `routeConfigurationId` takes exact ids, a wildcard ending in `*` or a regular expression, separated by commas. A route that names configurations does not get the default one. - An id is unique within the context; an exact id nobody declares fails `Start()`, naming the route. - The same element is valid in `context.xml`, beside ``. - Which handler takes a failure: the one whose exception type is nearest to it, among the route's own ``, its file's and its configurations'. On a tie the route's own wins, and a configuration's handler is used instead of its file's handler of the same type. - `` takes `` only; intercepts and `` stay at the container level of the file whose routes they serve. ### The retry policy of a handler `` spells everything its fluent counterpart does: ```xml ``` `` decides whether this handler takes the failure at all, `` whether another attempt follows; both are conditions of the handler, not steps of it. The three references name `IProcessor` beans from the registry and run at their own moments: `onExceptionOccurred` on every occurrence, `onRedelivery` before each retry, `onPrepareFailure` once, before the handler takes over for good. A name the registry does not hold is refused at load, with its position. The entry written when the retries are over follows `logHandled` / `logContinued`: a failure the handler handled is logged only with `logHandled="true"`, one it continued only with `logContinued="true"` (both `false` by default, as in Camel), and an unhandled failure is always logged. A rollback-only exchange is logged either way, its work having been rolled back. `logExhausted="false"` silences the entry altogether. `handled="true"` ends the route after the handler; `continued="true"` resumes it at the step **after** the one that failed, as Camel's `continued(true)` does. What the resumption does not replay: - the failing step itself — it is skipped, the rest goes on; - a `.Transacted()` block whose step failed: the transaction rolled back, so the route picks up after the block, not inside it; - the body of a `` whose failure a `` already took. A failure in a resumed step is handled again, but not retried: a redelivery restarts the route from its first step, so `maximumRedeliveries` does not apply to what the resumption replays. The REST DSL is a container-level element from the `redb.Route.Http` package: ```xml ``` A verb handles its request with `to=` **or** inline steps — one of the two. Path parameters arrive as `header.id`, query as `header.query.*`; OpenAPI is served at `{path}/openapi.json`. ## The context document Besides route files, a package can carry a `context.xml` — the context-level concerns: ```xml … ``` `` registers a format on the context, as `context.AddDataFormat(...)` does in code: ``, `` and content-type dispatch find it under its own content type and media types and under each name in `name` (comma-separated). The other attributes set the serializer's options by property name, as on the per-step ``, which needs no registration and suits a format used in one place. XML to JSON without a class is the xmljson format ([redb.Route.DataFormats.XmlJson](../redb.Route.DataFormats.XmlJson/README.md)): a named instance with its schema, ``, then ``. `check` and `pack` verify that the schema is in the package and compiles and that its `arrays=` paths name declared elements. `` adds a C# route builder to the context, as `context.AddRoutes(new OrdersRoute())` does in code, so one package keeps routes in markup and in the DSL side by side, in one context. The type resolves like a ``: in a Tsak package, from the package's own assemblies first, so a module built with `RoutePackageIncludeAssembly=true` names its builders by `Namespace.Type, Assembly`. The type must be a public, non-abstract class deriving from `RouteBuilder` with a public parameterless constructor, the rule of `AddRoutes(Assembly[])`. A builder reads its configuration through `{{key}}` properties and reaches the beans of `context.xml` by their registry name (`bean:#name`). It is added once the whole document is valid, and a builder already in the context, or named twice, is a load error. Route ids share one context with the markup routes: a clash fails the start. `redb-route-xml check --bin` and `pack --bin` hold the type against the same rule, so a wrong one fails the build. `` is a pipeline of ordinary format steps, run **once** in the engine's fail-fast bootstrap phase: a failed step keeps the context from accepting traffic, and the error names the source file. Load it with `AddXmlContext("context.xml")` / `AddXmlContextFromContent(...)` — before the route files, so `#references` and schemes resolve. ## Configuration and `enabled=` Configuration is layered; the package itself carries **identity only** (`ContextName`, `AutoStart`) — settings and secrets arrive from the host's merged configuration at deploy time. Every `{{key}}` without a `{{key:default}}` is recorded by the packaging tool in the manifest's `RequiredConfigKeys`, so a missing value fails fast at module init instead of surfacing as a malformed URI at 3 a.m. `enabled="{{features.orders:false}}"` on a `` resolves from the same chain at load — a route can be switched per environment without touching the package. `enabled="false"` skips registration entirely (stronger than `autoStart="false"`, which registers but does not start). ## Errors: one pass, positions, no half-states Everything wrong with a document is reported together: ```text routes/orders.route.xml(4,6): unknown element . Did you mean ? routes/orders.route.xml(7,10): takes 'value' or 'expr', not both. routes/orders.route.xml(12,8): [schema] The 'bogus' attribute is not allowed. routes/orders.route.xml(15,6): scheme 'kafkaa' is not registered in this context. ``` The parser's own findings win on a shared line; the generated-XSD pass (on by default, `ValidateAgainstSchema = false` to opt out) adds what the parser deliberately leaves to it — above all, attribute typos. Fixing ten mistakes takes one run, not ten. ## Testing an XML route An XML route is tested exactly like a C# route — with `redb.Route.TestKit`, no test host of its own: ```csharp await using var ctx = new RouteContext().AddXmlRoutesFromContent(xml); ctx.AdviceAllRoutes(a => a.MockEndpoints("kafka://*", "sql:*")); await ctx.Start(); var mock = ctx.Mock("kafka://orders").ExpectMessageCount(1).ExpectHeader("seen", "true"); await ctx.SendBody("direct://in", "payload"); await mock.AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2)); ``` - **Swapping transports.** `MockEndpoints("kafka://*")` rewrites the definition tree between load and `Start()` — the same seam for both spellings of a route. - **Weaving by id.** `AdviceRoute(id, a => a.WeaveById("step-id").Replace(...))` finds a step by its XML `id=` attribute. - **Secrets stay out of reports.** The query string of a URI — where passwords live — is not part of the mock name and never appears in a failed assertion's report (nor, from there, in CI logs). - **Why `mock:` and not a real broker.** A unit test asserts the ROUTE — branching, headers, bodies; a broker adds latency and flakiness to that claim. Keep one integration test per transport against the real thing; let every route test run on mocks. - **Structural comparison.** `redb.Route.Diagnostics.RouteDescriber` renders a definition tree as stable, diffable text — equivalence tests compare XML against its fluent C# twin byte-for-byte, and golden files pin the parse of every shipped example. ## Schema and editor support The XSD is **generated from the element registry** — the same list the parser reads, so they cannot drift. `XmlRouteSchema.Generate(registry)` covers the vocabulary with enum value hints (`level=`, `policy=`, `strategy=` complete from a list), required attributes, and rejection of unknown elements; foreign-**namespace** attributes are tolerated by design so other tools can annotate route files. Pass a `ComponentCatalog` to make structured endpoint children strict and typed per connector. A connector that refuses parameters it has no option for (every connector not marked `[LenientProperties]`; `http:`, `sql:` and `bean:` are lenient) gets no room for unknown attributes in that schema, so the editor flags `` the way the engine would refuse it at start. An option only one side of an endpoint reads (`[EndpointRole]`) is refused on the other side the same way: `username` / `authScheme` are what an `http:` producer sends and are an error inside `` (the editor names the type `producerOnlyOption`), while `inboundAuth` and its companions are what an `http:` consumer requires and are an error inside `` (`consumerOnlyOption`). `` creates the consumer; every other address-carrying step, `pollEnrich` included, creates a producer. Point any XSD-aware editor at it — VS Code with the RedHat XML extension: ```jsonc // .vscode/settings.json { "xml.fileAssociations": [ { "pattern": "**/*.route.xml", "systemId": "./schema/redb-route-1.0.xsd" } ] } ``` The component catalog (`ComponentCatalog.Build`, `ToJson`) describes every connector for a property panel — scheme, path synonym, options with types, defaults, enum values, `[Sensitive]` marks — by reflection over the connector's own `Options` class. A new connector appears in the structured form, the catalog and the schema with **zero XML-specific code**. An option whose value names a registry object (`connectionFactory=main`, `headerFilterStrategy=#filter`) carries `[RegistryReference(typeof(T))]` from `redb.Route.Core` (`[ConnectionFactoryReference]` is one too). The catalog writes it as the option's `reference`: the expected type as `Full.Name, Assembly`, or `object` when the mark names none; an option without the mark has no `reference`. A connector author marks such options so the editor and the package gate know them: in a marked option `check` reads a bare name (`connectionFactory=main`) as a reference, as it reads `#main` anywhere, in the URI and the structured form, and warns when no `` of the package declares it. The core's options are known without `--bin`, a connector's with it; values with `{{…}}` or `${…}` are left alone. With `--bin` a name in an option marked with a type is held against it, per connector: a `` of the package whose type is not assignable to the expected one is an error (`'main' is registered as Acme.Pool, which is not an RabbitMQConnectionFactory.`). An option marked without a type is not checked, and a bean whose type does not load, or that the package does not declare, gives no type error. ## Tooling: scaffold, pack, generate The `redb-route-xml` dotnet tool (package `redb.Route.Xml.CodeGen` — a developer tool, not part of the runtime): | Command | What it does | |---|---| | `new Orders --context orders` | scaffolds a route project: an ordinary `.csproj`, `context.xml`, `routes/`, `resources/`, layered `config/`, the generated XSD wired into `.vscode` | | `pack . --version 1.0.0 [--bin bin/Debug/net10.0] [--entry bin/Debug/net10.0/Orders.dll] [--depends shared-beans]` | runs the checks, then builds the package layout (`manifest.json`, config, artifacts, resources) and a `.tpkg` zip; `--entry` (repeatable) adds a DLL as the package's entry point; `--depends` (repeatable) names a package the worker opens before this one | | `check . [--depends shared-beans]` | the same gate for CI — findings only | | `catalog --out dir` | builds the component catalog + catalog-aware XSD from built connector assemblies | | `csharp routes/x.route.xml --namespace My.Routes` | fluent C# (readable, or `--style machine` with `#line` mapping diagnostics back to the XML) | | `mermaid routes/x.route.xml` | a flowchart from the same parse | | `xsd --out dir` | the generated schema for the core set | Packaging checks are **hard errors, not advice**: schema validation with positions, `]]>` inside CDATA, files missing from `resources/` (`file=`, and the files package elements name: ``, ``), undeclared `#name` references; with `--bin`, bean types are verified against the real assemblies — a renamed type, a non-public type, a typo in a `` or in `bean:…?method=` refuses the build. With `--bin` the gate also reads the connectors of that output and holds every endpoint's parameters against them, in the URI form and the structured form alike: a name a strict connector does not know is an error with its position, in the engine's own words (`'perod' is not an option of the Timer endpoint. Did you mean 'period'?`), instead of a refusal when the route starts. An option written on the side that does not read it is an error too, on any connector (`'username' is read only by the producer side of the http endpoint; creates the consumer, which refuses it.`). So is a connection parameter written beside the option that names a connection factory (`[ConnectionParameter]`, `[ConnectionFactoryReference]`): the factory is the whole connection (`connectionFactory 'main' sets the whole connection, so host cannot be given on the URI as well.`). A literal secret in a URI is a warning that names the fix (supply it through configuration). Add `-p:PackRouteOnBuild=true` to a scaffolded project to pack on every `dotnet build`. With `--bin` the gate also runs the package checks of that output: every public, non-abstract `IPackageCheck` (`redb.Route.Xml.Packaging`) with a parameterless constructor in its `redb.Route.*.dll`, found the way element contributions are. A check receives the project's route documents with line information and the package's resource lookup, and reports errors and warnings at nodes of those documents; one that throws is an error naming it. The xmljson format ships one: without `--bin` the gate checks only that its schema is a file of the package and that its `arrays=` paths are well formed, with `--bin` the format compiles the schema with its own reader and walks it (see the redb.Route.DataFormats.XmlJson README). The schema of `` is compiled by the gate as the route compiles it when it starts, without `--bin`: an import or include that is missing, lies outside `schemaRoot` or points to the network, and anything else the schema compiler reports, is an error at the `file=` attribute (`validateXsd schema 'order.xsd' does not compile: …`). A `schemaRoot` that leads out of `resources/` is an error too, since pack ships only that tree. A value that holds a placeholder is left to configuration, and inline content is not compiled here. A package carries only the DLLs passed with `--entry`. A project whose markup uses its own C# types (``) passes its build output: `--entry "$(TargetPath)"` in the build target. The DLL is packed at the package root and named in `manifest.json` by its file name; Tsak loads it into the package's own load context, where the markup's bean types are looked up first. The route-xml templates of `redb.Templates` do this when the project sets `true`. A package whose markup uses types another package ships (a carrier of shared companion DLLs) names that package with `--depends `, the manifest `Name` the carrier was packed with. The names go into `manifest.json` `Dependencies`, and the Tsak worker opens the carrier first, at startup and on hot reload. The gate checks only the shape of each name: not blank, not a file or a path, not the package itself, listed once. Whether the carrier is deployed is the worker's business, so `check` does not look for it. What the gate **warns** about, leaving the decision to the author: a step that never runs (anything after ``, `` or `` in the same list), an undeclared `#name` (module code may register it at startup), a literal secret in a URI, and a condition that compares outside a placeholder — `expr="${header.kind} == 'order'"` renders to text before it is read, and non-empty text is true whatever it says, so the branch always wins. A lone `${header.enabled}` and a comparison written entirely inside the braces are both read correctly and stay silent. About the generated C#: it is what the XML says, pronounced in C# — not what a person would have written. There are no lambdas in it, because there are none in XML. For migration that is exactly right; the mechanical guarantee is stronger than style — the generated code produces a definition tree **byte-identical** to loading the XML. ## Extending the format from your package A package with DSL of its own ships one class per element — parse, schema shape and C# printing together, so the loader, the XSD and the generator see the element together or not at all: ```csharp public sealed class CacheXmlContribution : IXmlElementContribution { public string Name => "cache"; public XmlElementKind Kind => XmlElementKind.Scope; public ElementSpec Spec => …; // attributes, enum values, children — feeds the XSD public IRouteDefinition Apply(…) => …; // calls the package's own fluent DSL, nothing else public void Print(…) => …; // the generator's face; missing = loud error } ``` Hosts register contributions via `XmlRouteLoaderOptions.Extensions`. A duplicate element name is a hard error, never a silent override. Container-level elements (like ``) implement `IXmlTopLevelContribution` and apply to the route builder. Shipping today: `` (redb.Route.Cache), `` (redb.Route.JsonTransform), `` (redb.Route.Templates), `` (redb.Route.Http). ## What XML deliberately does not do Lambdas, custom processors' logic, complex seeding — code. XML references it (`bean:#name`, `predicate="#name"`, ``), never embeds it: there is no compiler in the runtime and no second trust contour — a package's code is signed and verified before anything runs, and the XML only chooses which already-trusted types to use. The schema of the format is generated from the element registry: `redb-route-xml xsd ` writes it for exactly the packages in that directory, their contributed elements included, and the VS Code extension validates against it. See [XML Route Tools](../README.md#xml-route-tools). Path: redb-route/redb.Route.Xml/RedbRouteBuilderXmlExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/RedbRouteBuilderXmlExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Xml; /// /// The DI surface: the same three loading overloads plus context.xml on /// , applied at context-start time through the standard /// hook — an ordinary ASP.NET host loads XML routes /// with one line inside AddRedbRoute(...), no Tsak required. /// public static class RedbRouteBuilderXmlExtensions { /// Loads route files by a glob pattern (or one wildcard-free path) at context start. public static RedbRouteBuilder AddXmlRoutes(this RedbRouteBuilder self, string globPattern, XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(globPattern); return Configure(self, context => context.AddXmlRoutes(globPattern, options)); } /// Loads the named route files at context start. public static RedbRouteBuilder AddXmlRoutes(this RedbRouteBuilder self, params string[] filePaths) { ArgumentNullException.ThrowIfNull(self); if (filePaths.Length == 0) throw new ArgumentException("At least one route file path is required.", nameof(filePaths)); return Configure(self, context => context.AddXmlRoutes(filePaths)); } /// Parses the XML text at context start — tests and generated hosts. public static RedbRouteBuilder AddXmlRoutesFromContent(this RedbRouteBuilder self, string xml, string? sourceName = null, XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(xml); return Configure(self, context => context.AddXmlRoutesFromContent(xml, sourceName, options)); } /// Loads a context.xml (components, context beans, onInit) at context start. public static RedbRouteBuilder AddXmlContext(this RedbRouteBuilder self, string filePath, XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(self); ArgumentException.ThrowIfNullOrWhiteSpace(filePath); return Configure(self, context => context.AddXmlContext(filePath, options)); } private static RedbRouteBuilder Configure(RedbRouteBuilder self, Action apply) { self.Services.AddSingleton(new XmlLoadConfigurator(apply)); return self; } private sealed class XmlLoadConfigurator(Action apply) : IRouteContextConfigurator { public void Configure(RouteContext context) => apply(context); } } Path: redb-route/redb.Route.Xml/RouteContextXmlExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/RouteContextXmlExtensions.cs ---- using System.Xml.Linq; using redb.Route.Core; namespace redb.Route.Xml; /// /// Loading sugar on — the TestKit-style surface /// (new RouteContext().AddXmlRoutesFromContent(...)) and file loading. Both go through one /// . /// public static class RouteContextXmlExtensions { /// Parses the XML text and registers its routes. Errors carry positions and are aggregated. public static RouteContext AddXmlRoutesFromContent(this RouteContext context, string xml, string? sourceName = null, XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrWhiteSpace(xml); var document = SafeXml.Parse(xml, LoadOptions.SetLineInfo); new XmlRouteLoader(context, options).Load(document, sourceName); return context; } /// Loads every named .route.xml file, each parsed with its own positions. public static RouteContext AddXmlRoutes(this RouteContext context, params string[] filePaths) { ArgumentNullException.ThrowIfNull(context); if (filePaths.Length == 0) throw new ArgumentException("At least one route file path is required.", nameof(filePaths)); var loader = new XmlRouteLoader(context); foreach (var path in filePaths) LoadFile(loader, context, path); return context; } /// /// Loads route files by a glob pattern ("routes/*.route.xml"); a plain path without /// wildcards loads that one file. A pattern matching nothing is an error, not a silent empty /// context — same fail-fast rule the rest of the loader follows. /// public static RouteContext AddXmlRoutes(this RouteContext context, string globPattern, XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrWhiteSpace(globPattern); var loader = new XmlRouteLoader(context, options); if (!globPattern.Contains('*') && !globPattern.Contains('?')) { LoadFile(loader, context, globPattern); return context; } var directory = Path.GetDirectoryName(globPattern) is { Length: > 0 } dir ? dir : "."; var mask = Path.GetFileName(globPattern); var probed = new List(); string? found = null; foreach (var root in ProbeRoots(directory)) { probed.Add(root); if (Directory.Exists(root) && Directory.EnumerateFiles(root, mask).Any()) { found = root; break; } } if (found is null) { throw new XmlRouteException(globPattern, [$"no route files match '{mask}'. Searched: {string.Join("; ", probed.Distinct())}."]); } // Ordinal order keeps the load deterministic across file systems. foreach (var path in Directory.GetFiles(found, mask).OrderBy(p => p, StringComparer.Ordinal)) { var document = SafeXml.LoadFile(path, LoadOptions.SetLineInfo); loader.Load(document, path); } return context; } /// Parses a context.xml text: components, context beans, the onInit pipeline. public static RouteContext AddXmlContextFromContent(this RouteContext context, string xml, string? sourceName = null, XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrWhiteSpace(xml); var document = SafeXml.Parse(xml, LoadOptions.SetLineInfo); new XmlContextLoader(context, options).Load(document, sourceName); return context; } /// Loads a context.xml file through the route resource resolver. public static RouteContext AddXmlContext(this RouteContext context, string filePath, XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrWhiteSpace(filePath); var resolved = ResourceResolution.Resolve(context, filePath, "Context file"); var document = SafeXml.LoadFile(resolved, LoadOptions.SetLineInfo); new XmlContextLoader(context, options).Load(document, filePath); return context; } private static void LoadFile(XmlRouteLoader loader, RouteContext context, string path) { // Through the route resource resolver: a relative path must not depend on the process // working directory (the AppContext base wins over cwd). var resolved = ResourceResolution.Resolve(context, path, "Route file"); var document = SafeXml.LoadFile(resolved, LoadOptions.SetLineInfo); loader.Load(document, path); } private static IEnumerable ProbeRoots(string directory) { if (Path.IsPathRooted(directory)) { yield return directory; yield break; } yield return Path.Combine(AppContext.BaseDirectory, directory); yield return Path.GetFullPath(directory); } } Path: redb-route/redb.Route.Xml/StructuredEndpoint.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/StructuredEndpoint.cs ---- using System.Text; using System.Xml.Linq; using redb.Route.Abstractions; namespace redb.Route.Xml; /// /// The structured endpoint form: an address-carrying step (<from>, /// <to>, <toD>, <wireTap>, <enrich>, /// <pollEnrich>) takes either uri= or exactly one child endpoint element, /// normalized HERE into the same URI string a hand-written address would be — the engine /// (endpoint cache, statistics, mock masks, secret redaction) sees one canon and zero new code. /// One generic procedure for every scheme: no switch per connector, ever (owner rule /// 2026-09-02 — "one general approach, copy-paste ruled out by construction"). /// internal static class StructuredEndpoint { /// /// The endpoint URI of an address-carrying step, whichever form it uses. Returns null after /// recording errors; is the element to blame in messages (the /// endpoint child for the structured form, the step itself otherwise). /// internal static string? Resolve(XElement step, XmlParseContext ctx, out XElement position) { position = step; var uri = ctx.Attr(step, "uri"); var children = step.Elements().ToList(); if (uri is not null) { if (children.Count > 0) { ctx.AddError(step, $"<{step.Name.LocalName}> takes either uri= or a structured endpoint child, not both."); return null; } return uri; } if (children.Count == 0) { ctx.AddError(step, $"<{step.Name.LocalName}> requires the uri attribute or one endpoint child " + "(the structured form, e.g. …)."); return null; } if (children.Count > 1) { ctx.AddError(step, $"<{step.Name.LocalName}> takes exactly one endpoint child; {children.Count} found."); return null; } position = children[0]; return Build(children[0], ctx); } /// Builds scheme://path?options from one endpoint element. See the class remarks. private static string? Build(XElement endpoint, XmlParseContext ctx) { var scheme = endpoint.Name.LocalName; // The path part: the universal path= attribute, the component's own one-line synonym // (kafka → topic; read from the component, never from a list here), or the // element's text content (CDATA — the SQL-style connectors whose path IS a text). var component = (ctx.RouteContext as redb.Route.Core.RouteContext) ?.GetComponent(scheme) as redb.Route.Core.ComponentBase; var synonym = component?.StructuredPathSynonym is { Length: > 0 } s ? s : null; var pathAttr = ctx.Attr(endpoint, "path"); var synonymAttr = synonym is not null ? ctx.Attr(endpoint, synonym) : null; var text = Text(endpoint); if (component?.PathIsText == true && (pathAttr is not null || synonymAttr is not null)) { ctx.AddError(endpoint, $"the path of <{scheme}> is a text — put it in the element content (CDATA), not an attribute."); return null; } var pathSources = new[] { pathAttr, synonymAttr, text }.Count(v => v is not null); if (pathSources > 1) { ctx.AddError(endpoint, $"<{scheme}> carries its path more than once " + $"(path=, {(synonym is null ? "" : $"{synonym}=, ")}text content — exactly one)."); return null; } var path = pathAttr ?? synonymAttr ?? text ?? string.Empty; if (path.Contains('?')) { ctx.AddError(endpoint, $"the path of <{scheme}> contains '?', which starts the option part of a URI — " + "this address is not expressible as an endpoint URI."); return null; } var options = Options(endpoint, synonym, ctx.AddError); if (options is null) return null; return Compose(scheme, path, options); } /// The attributes of a step <bean> that are not options of the bean: endpoint. private static readonly string[] BeanStepAttributes = ["ref", "beanType", "id", "description"]; /// /// The bean: URI of a step <bean ref="#svc" method="Handle"/> (amended /// 2026-11-05): the structured endpoint child of <to> without the wrapper. ref= or /// beanType= carries what path= carries there; every other attribute is an option, exactly as on /// <to><bean/></to>. Null after recording errors. /// internal static string? ResolveBeanStep(XElement step, XmlParseContext ctx) => BeanStepUri(step, ctx.AddError); /// Context-free form of for the code generator. internal static string NormalizeBeanStepForPrint(XElement step) => BeanStepUri(step, (at, message) => throw new InvalidOperationException($"<{at.Name.LocalName}>: {message}"))!; /// The bean reference a step <bean> names: #name or Type, Assembly; null when malformed. internal static string? BeanStepReference(XElement step) { var reference = step.Attribute("ref")?.Value; var type = step.Attribute("beanType")?.Value; if (reference is { Length: > 0 } && type is null) return reference.StartsWith('#') ? reference : "#" + reference; if (type is { Length: > 0 } && reference is null) return type; return null; } private static string? BeanStepUri(XElement step, Action error) { if (step.Attribute("name") is not null || step.Attribute("type") is not null) { error(step, "a with name= or type= is a declaration: it belongs directly under or . " + "A step calls a bean: or ."); return null; } if (step.Attribute("path") is not null) { error(step, "a step names its bean with ref= or beanType=, not path= (path= belongs to )."); return null; } if (step.HasElements) { error(step, "a step takes attributes only; write the bean's options as attributes."); return null; } var reference = BeanStepReference(step); if (reference is null) { error(step, "a step takes exactly one of ref=\"#name\" and beanType=\"Type, Assembly\"."); return null; } if (reference.Contains('?')) { error(step, "the bean reference contains '?', which starts the option part of a URI; write the method as method=."); return null; } var options = Options(step, pathSynonym: null, error, BeanStepAttributes); return options is null ? null : Compose("bean", reference, options); } private static string Compose(string scheme, string path, IEnumerable<(string Key, string Value, XElement At)> options) { var builder = new StringBuilder(scheme).Append("://").Append(path); var separator = '?'; foreach (var (key, value, _) in options) { builder.Append(separator).Append(key).Append('=').Append(EscapeValue(value)); separator = '&'; } return builder.ToString(); } /// /// The query options one endpoint element writes, in document order, each with the element /// that wrote it — what puts after '?', and what the package gate holds /// against the connector's options. Null after reporting a malformed child. /// /// Every unqualified attribute is an option verbatim — the same names, the same /// converter, the same unknown-name rule the URI form has (typed validation happens where it /// always did: in BindFromUri at endpoint creation). path= and the component's /// path synonym are the path, not options. /// An attribute in a foreign namespace is metadata for other tools (tolerated, /// never read) — it is not an option, or a strict connector would refuse an editor's mark. /// Two generic child forms, both an orthography of URI options: a family /// entry <param name="login" value="…"/> → param.login=…; a long text /// option <onSuccess><![CDATA[…]]></onSuccess> → onSuccess=…. /// /// internal static List<(string Key, string Value, XElement At)>? Options( XElement endpoint, string? pathSynonym, Action error, IReadOnlyCollection? notOptions = null) { var options = new List<(string Key, string Value, XElement At)>(); foreach (var attribute in endpoint.Attributes()) { if (attribute.IsNamespaceDeclaration || attribute.Name.NamespaceName.Length > 0 || attribute.Name.LocalName == "path" || (pathSynonym is not null && attribute.Name.LocalName == pathSynonym) || (notOptions is not null && notOptions.Contains(attribute.Name.LocalName))) continue; options.Add((attribute.Name.LocalName, attribute.Value, endpoint)); } foreach (var child in endpoint.Elements()) { var name = child.Attribute("name")?.Value; var value = child.Attribute("value")?.Value; var content = Text(child); if (name is not null && value is not null && content is null && !child.Elements().Any()) { options.Add(($"{child.Name.LocalName}.{name}", value, child)); continue; } if (name is null && content is not null && !child.HasAttributes && !child.Elements().Any()) { options.Add((child.Name.LocalName, content, child)); continue; } error(child, $"<{child.Name.LocalName}> inside <{endpoint.Name.LocalName}> must be a family entry " + $"(<{child.Name.LocalName} name=… value=…/>) or a text option " + $"(<{child.Name.LocalName}>content)."); return null; } return options; } /// /// Option values travel raw, like hand-written URIs and the fluent builders — except the two /// characters the engine's query parse cannot survive: '&' splits pairs and '%' is /// unescaped by EndpointUriParser. Encoding just those keeps ordinary values /// byte-identical to the URI form and round-trips the rest exactly. /// private static string EscapeValue(string value) => value.Replace("%", "%25").Replace("&", "%26"); /// /// Context-free normalization for the code generator: no component lookup, so path synonyms /// are unavailable (the tool passes a catalog for those); the universal path=/content and /// the two child forms normalize identically to . /// internal static string NormalizeForPrint(XElement endpoint) { var scheme = endpoint.Name.LocalName; var path = endpoint.Attribute("path")?.Value ?? Text(endpoint) ?? string.Empty; var options = Options(endpoint, pathSynonym: null, (at, message) => throw new InvalidOperationException($"<{at.Name.LocalName}>: {message}"))!; return Compose(scheme, path, options); } /// The element's own text (CDATA included), null when blank. private static string? Text(XElement element) { var text = string.Concat(element.Nodes().OfType().Select(t => t.Value)); return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); } } Path: redb-route/redb.Route.Xml/XmlCodeGenerator.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/XmlCodeGenerator.cs ---- using System.Text; using System.Xml.Linq; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Core; namespace redb.Route.Xml; /// /// The code generator: a .route.xml document printed as the fluent C# it parses into — the /// same traversal as the loader with a different receiver, each element printed by its own /// contribution (the print face), so the parser and the generator cannot drift apart. /// Readable style is for a human migrating off XML (descriptions become comments); machine style /// adds #line directives so diagnostics point back at the XML. The honesty check is /// mechanical: load the XML, run the generated Configure, and compare the two trees with /// RouteDescriber — the tests do exactly that for every shipped example. /// public static class XmlCodeGenerator { /// Generates one RouteBuilder class from a route document. /// The parsed document (with line info for machine style). /// The class name (derive from the file name: orders → OrdersRoutes). /// The namespace of the generated class. /// Readable for migration, machine for a build step. /// The XML path — printed in the header and #line directives. /// Loader options carrying package contributions, if any. public static string Generate( XDocument document, string className, string ns, CodeGenStyle style = CodeGenStyle.Readable, string sourceName = "", XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(document); ArgumentException.ThrowIfNullOrWhiteSpace(className); ArgumentException.ThrowIfNullOrWhiteSpace(ns); var root = document.Root; if (root is null || root.Name.LocalName != "routes" || root.Name.NamespaceName != XmlRouteLoader.Namespace) throw new InvalidOperationException( $"the generator reads documents."); var registry = ElementRegistry.CreateDefault(options?.Extensions); var resources = sourceName != "" ? new Packaging.RouteProjectResourceResolver(sourceName) : null; var writer = new XmlCodeWriter(registry, style, sourceName, resources); writer.Line($"// "); writer.Line("#nullable enable"); writer.Line("using System;"); writer.Line("using System.Collections.Generic;"); writer.Line("using Microsoft.Extensions.Logging;"); writer.Line("using redb.Route.Abstractions;"); writer.Line("using redb.Route.Aggregation;"); writer.Line("using redb.Route.ControlBus;"); writer.Line("using redb.Route.Core;"); writer.Line("using redb.Route.Transactions;"); writer.Line("using redb.Route.Xml;"); writer.Line("using redb.Route.Xslt;"); // Namespaces the registered package printers ask for (GeneratedUsings face). foreach (var extra in (options?.Extensions ?? []) .SelectMany(c => c.GeneratedUsings).Distinct().Order(StringComparer.Ordinal)) writer.Line($"using {extra};"); writer.BlankLine(); writer.Line($"namespace {ns};"); writer.BlankLine(); writer.Line("/// A generated route builder — see the header for the source file."); writer.Line($"public sealed class {className} : RouteBuilder"); writer.Line("{"); writer.Indent(); writer.Line("protected override void Configure()"); writer.Line("{"); writer.Indent(); // Section order mirrors the loader: beans, container handlers, routes. foreach (var bean in root.Elements().Where(e => e.Name.LocalName == "bean")) PrintBean(bean, writer); foreach (var handler in root.Elements().Where(e => e.Name.LocalName is "onException" or "intercept" or "interceptFrom" or "interceptSendToEndpoint" or "onCompletion")) PrintContainerHandler(handler, writer); foreach (var configuration in root.Elements().Where(e => e.Name.LocalName == XmlRouteLoader.RouteConfigurationElement)) PrintRouteConfiguration(configuration, writer); foreach (var element in root.Elements()) { if (registry.Find(element.Name.LocalName) is { Kind: XmlElementKind.TopLevel } topLevel) topLevel.Print(element, writer); } foreach (var route in root.Elements().Where(e => e.Name.LocalName == "route")) PrintRoute(route, writer); writer.Outdent(); writer.Line("}"); writer.Outdent(); writer.Line("}"); if (style == CodeGenStyle.Machine) writer.Line("#line default"); return writer.Text; } private static void PrintBean(XElement bean, XmlCodeWriter writer) { var name = bean.Attribute("name")?.Value ?? ""; var problems = new List(); var declaration = BeanModel.Parse(bean, (at, message) => problems.Add(at is System.Xml.IXmlLineInfo line && line.HasLineInfo() ? $"({line.LineNumber},{line.LinePosition}): {message}" : message)); if (declaration is null) throw new InvalidOperationException($"bean '{name}': {string.Join("; ", problems)}"); writer.MapTo(bean); writer.Line($"Context!.AddToRegistry({XmlCodeWriter.Str(name)}, {BeanExpression(declaration)});"); } /// /// A bean as a XmlBeans.Create(...) expression. Registrations print in document order, /// so an XmlBeans.Ref finds what the XML section would have found at the same point. /// private static string BeanExpression(BeanDeclaration bean) { var args = new StringBuilder(); args.Append("XmlBeans.Create(Context!, ").Append(XmlCodeWriter.Str(bean.TypeName)); args.Append(", [").Append(string.Join(", ", bean.ConstructorArgs.Select(a => ValueExpression(a.Value)))).Append(']'); var properties = bean.Properties.Select(p => $"({XmlCodeWriter.Str(p.Key)}, {ValueExpression(p.Value)})"); args.Append(", [").Append(string.Join(", ", properties)).Append(']'); if (bean.FactoryMethod is not null) args.Append(", ").Append(XmlCodeWriter.Str(bean.FactoryMethod)); if (bean.TypedArguments) args.Append(", argumentTypes: [").Append(string.Join(", ", bean.ConstructorArgs.Select(a => XmlCodeWriter.Str(a.TypeName!)))).Append(']'); return args.Append(')').ToString(); } private static string ValueExpression(BeanValue value) => value switch { ScalarBeanValue scalar => XmlCodeWriter.Str(scalar.Text), RefBeanValue reference => $"XmlBeans.Ref(Context!, {XmlCodeWriter.Str(reference.Bean)})", NestedBeanValue nested => BeanExpression(nested.Bean), ListBeanValue list => $"XmlBeans.List(Context!, {(list.ElementTypeName is null ? "null" : XmlCodeWriter.Str(list.ElementTypeName))}, " + $"[{string.Join(", ", list.Items.Select(ValueExpression))}])", _ => throw new InvalidOperationException($"unhandled bean value {value.GetType().Name}."), }; private static void PrintContainerHandler(XElement handler, XmlCodeWriter writer) { // Builder-level: the same shapes as the route level, statements on a fresh variable, // no End call (a builder-level definition has no parent to return to). switch (handler.Name.LocalName) { case "onException": { var types = (handler.Attribute("exceptions")?.Value ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); writer.PushRoot($"OnException({string.Join(", ", types.Select(XmlCodeWriter.TypeRef))})", handler, "handler"); if (handler.Attribute("description")?.Value is { Length: > 0 } description) writer.Config($"Description({XmlCodeWriter.Str(description)})"); CoreElements.CoreContributions.PrintOnException(handler, writer); writer.PopReceiver(); break; } case "intercept": case "interceptFrom": case "interceptSendToEndpoint": { var verb = char.ToUpperInvariant(handler.Name.LocalName[0]) + handler.Name.LocalName[1..]; var arg = handler.Attribute("uri")?.Value is { } uri ? XmlCodeWriter.Str(uri) : ""; writer.PushRoot($"{verb}({arg})", handler, "handler"); if (handler.Attribute("skipSendToOriginalEndpoint")?.Value == "true") writer.Config("SkipSendToOriginalEndpoint()"); CoreElements.CoreContributions.PrintWhenConditionThenSteps(handler, writer); writer.PopReceiver(); break; } default: { writer.PushRoot("OnCompletion()", handler, "handler"); if (handler.Attribute("onCompleteOnly")?.Value == "true") writer.Config("OnCompleteOnly()"); if (handler.Attribute("onFailureOnly")?.Value == "true") writer.Config("OnFailureOnly()"); if (handler.Attribute("modeBeforeConsumer")?.Value == "true") writer.Config("ModeBeforeConsumer()"); if (handler.Attribute("parallelProcessing")?.Value == "true") writer.Config("ParallelProcessing()"); if (handler.Attribute("executorService")?.Value is { } pool) writer.Config($"ExecutorService({XmlCodeWriter.Str(pool)})"); CoreElements.CoreContributions.PrintWhenConditionThenSteps(handler, writer); writer.PopReceiver(); break; } } } /// /// A route configuration: one variable for the configuration, then each <onException> as statements /// on a variable of its own, the shapes of a builder-level handler. /// private static void PrintRouteConfiguration(XElement configuration, XmlCodeWriter writer) { var id = configuration.Attribute("id")?.Value is { Length: > 0 } value ? XmlCodeWriter.Str(value) : ""; var name = writer.PushRoot($"RouteConfiguration({id})", configuration, "configuration"); writer.PopReceiver(); foreach (var handler in configuration.Elements().Where(e => e.Name.LocalName == "onException")) { var types = (handler.Attribute("exceptions")?.Value ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); writer.PushRoot($"{name}.OnException({string.Join(", ", types.Select(XmlCodeWriter.TypeRef))})", handler, "handler"); if (handler.Attribute("description")?.Value is { Length: > 0 } description) writer.Config($"Description({XmlCodeWriter.Str(description)})"); CoreElements.CoreContributions.PrintOnException(handler, writer); writer.PopReceiver(); } } private static void PrintRoute(XElement route, XmlCodeWriter writer) { // enabled= is a load-time decision from live configuration; generated code has no // configuration at generation time, so the attribute is refused rather than mistranslated. if (route.Attribute("enabled") is { } enabled) { if (bool.TryParse(enabled.Value, out var isEnabled)) { if (!isEnabled) return; } else { throw new NotSupportedException( $"route '{route.Attribute("id")?.Value}': enabled=\"{enabled.Value}\" resolves from configuration " + "at load time — decide it before generating, or keep this route in XML."); } } writer.BlankLine(); if (writer.Style == CodeGenStyle.Readable && route.Attribute("description")?.Value is { Length: > 0 } comment) writer.Line($"// {comment}"); var from = route.Elements().First(e => e.Name.LocalName == "from"); var fromUri = from.Attribute("uri")?.Value is { } uri ? XmlCodeWriter.Str(uri) : XmlCodeWriter.Str(StructuredEndpoint.NormalizeForPrint(from.Elements().First())); writer.PushRoot($"From({fromUri})", route, "route"); if (route.Attribute("id")?.Value is { Length: > 0 } id) writer.Config($"RouteId({XmlCodeWriter.Str(id)})"); if (route.Attribute("description")?.Value is { Length: > 0 } description) writer.Config($"Description({XmlCodeWriter.Str(description)})"); if (route.Attribute("autoStart")?.Value is { } autoStart) writer.Config($"AutoStart({XmlCodeWriter.Bool(bool.Parse(autoStart))})"); if (route.Attribute("cluster")?.Value is { } cluster) writer.Config($"Cluster({XmlCodeWriter.Bool(bool.Parse(cluster))})"); if (route.Attribute("messageHistory")?.Value is { } history) writer.Config($"MessageHistory({XmlCodeWriter.Bool(bool.Parse(history))})"); if (route.Attribute("tracing")?.Value is { } tracing) writer.Config($"Tracing({XmlCodeWriter.Bool(bool.Parse(tracing))})"); if (route.Attribute("processingTimeout")?.Value is { } timeout) writer.Config($"ProcessingTimeout({XmlCodeWriter.Ts(TimeSpan.Parse(timeout, System.Globalization.CultureInfo.InvariantCulture))})"); if (route.Attribute("routePolicy")?.Value is { Length: > 0 } policy) writer.Config($"RoutePolicy({XmlCodeWriter.Str(policy)})"); if (route.Attribute("routeConfigurationId")?.Value is { Length: > 0 } configurations) writer.Config($"RouteConfigurationId({XmlCodeWriter.Str(configurations)})"); foreach (var step in route.Elements().Where(e => e.Name.LocalName != "from")) writer.PrintStep(step); writer.PopReceiver(); } } /// /// The runtime half of generated bean registrations: builds an instance the same way the /// <bean> section does — the registered IBeanTypeResolver decides what the /// type name means, and every value binds through the same factory as the XML section. /// public static class XmlBeans { /// /// Creates a bean instance for a generated registration. A value is a string (placeholders /// resolved, then converted to the target type the way a URI option is), an object built by a /// nested bean or taken by (assigned as it is), or a /// (built into the target's collection shape). names a public /// static creator to call instead of a constructor, with the constructor arguments as its parameters. /// — <constructorArg type=…> — names the parameter types: /// the constructor or factory method is then the one with exactly that signature. /// public static object Create( IRouteContext context, string typeName, object?[] constructorArgs, (string Key, object? Value)[] properties, string? factoryMethod = null, string[]? argumentTypes = null) { ArgumentNullException.ThrowIfNull(context); var resolver = context.GetService() ?? DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(typeName) ?? throw new InvalidOperationException($"bean type '{typeName}' was not found in the loaded assemblies."); var parameterTypes = argumentTypes?.Select(name => resolver.Resolve(name) ?? throw new InvalidOperationException($"constructor argument type '{name}' was not found in the loaded assemblies.")).ToList(); Func resolve = context is RouteContext live ? live.ResolvePlaceholders : text => text; var instance = BeanFactory.Instantiate( type, constructorArgs, parameterTypes, factoryMethod, context.GetServiceProvider() ?? EmptyProvider.Instance, resolve); foreach (var (key, value) in properties) BeanFactory.Assign(instance, key, value, resolve); return instance; } /// /// A registered bean for a ref: it must already be in the registry — generated /// registrations run in document order, exactly as the XML section builds them. /// public static object Ref(IRouteContext context, string name) { ArgumentNullException.ThrowIfNull(context); return context.GetFromRegistry(name) ?? throw new InvalidOperationException( $"bean reference '{name}' names nothing registered so far — declare it before the bean that refers to it."); } /// /// A <list> for : the items as raw values, the element type /// named by of= (null when the target property or parameter supplies it). /// public static object List(IRouteContext context, string? elementType, object?[] items) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(items); Type? type = null; if (elementType is not null) { var resolver = context.GetService() ?? DefaultBeanTypeResolver.Instance; type = resolver.Resolve(elementType) ?? throw new InvalidOperationException($"list element type '{elementType}' was not found in the loaded assemblies."); } return new BeanListValue(type, items); } private sealed class EmptyProvider : IServiceProvider { public static readonly EmptyProvider Instance = new(); public object? GetService(Type serviceType) => null; } } Path: redb-route/redb.Route.Xml/XmlCodeWriter.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/XmlCodeWriter.cs ---- using System.Globalization; using System.Text; using System.Xml; using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Xml; /// How the generated C# is shaped. public enum CodeGenStyle { /// For a human taking the code over: comments from descriptions, clean layout. Readable, /// For a build step (AOT): #line directives map diagnostics back to the XML. Machine, } /// /// The emitting side of the code generator: indentation, fluent-verb lines, literal rules /// (§3.2 — raw strings for anything with quotes or templates, never manual escaping) and typed /// arguments (§3.3 — s, enums and types print as code, not strings). /// Contributions print their element through this writer and recurse into children via /// . /// public sealed class XmlCodeWriter { private readonly StringBuilder _text = new(); private readonly ElementRegistry _registry; private readonly string _sourceName; private readonly IRouteResourceResolver? _resources; private int _indent; internal XmlCodeWriter(ElementRegistry registry, CodeGenStyle style, string sourceName, IRouteResourceResolver? resources) { _registry = registry; Style = style; _sourceName = sourceName; _resources = resources; } /// /// Reads a file the way the loader would (schema bodies referenced by file=): the /// generator inlines the content into the generated code. /// /// No probed location holds the file; the message names each one. public string ReadResource(string reference) { if (Path.IsPathRooted(reference) || _resources is null) return File.ReadAllText(reference); var path = _resources.Resolve(reference) ?? throw new FileNotFoundException( $"resource '{reference}' not found. Searched: {_resources.DescribeSearch(reference)}.", reference); return File.ReadAllText(path); } /// /// Finds a file the way does without reading it, for an element the generated code keeps /// as a file reference (<validateXsd file="…"/>): a missing file still fails the generation. /// /// No probed location holds the file; the message names each one. internal string LocateResource(string reference) { if (Path.IsPathRooted(reference) || _resources is null) return File.Exists(reference) ? reference : throw new FileNotFoundException($"resource '{reference}' not found.", reference); return _resources.Resolve(reference) ?? throw new FileNotFoundException( $"resource '{reference}' not found. Searched: {_resources.DescribeSearch(reference)}.", reference); } /// The requested output style. public CodeGenStyle Style { get; } internal string Text => _text.ToString(); // ── lines and indentation ──────────────────────────────────────────────── /// Writes one line at the current indentation. public XmlCodeWriter Line(string text) { _text.Append(' ', _indent * 4).Append(text).Append('\n'); return this; } /// Writes an empty line. public XmlCodeWriter BlankLine() { _text.Append('\n'); return this; } /// Increases indentation for a nested block. public XmlCodeWriter Indent() { _indent++; return this; } /// Decreases indentation. public XmlCodeWriter Outdent() { _indent--; return this; } /// /// In machine style, a #line directive pointing diagnostics at the XML element /// (Razor's trick, §2); a no-op in readable style. Directives ignore indentation. /// public XmlCodeWriter MapTo(XElement element) { if (Style == CodeGenStyle.Machine && ((IXmlLineInfo)element).HasLineInfo()) _text.Append("#line ").Append(((IXmlLineInfo)element).LineNumber) .Append(" \"").Append(_sourceName.Replace("\\", "/", StringComparison.Ordinal)).Append("\"\n"); return this; } // ── the statement model ────────────────────────────────────────────────── // Generated code is STATEMENTS against receiver variables, never one long chain: a chain // dies at the first scope closer (End* returns the IRouteDefinition facade and the concrete // members vanish), which is exactly why the equivalence tests were written with // variables. A scope introduces a fresh variable; a typed section (ofType) does too and // simply never closes — the siblings keep using the parent receiver. private readonly Stack _receivers = new(); private int _nextVar; /// The current receiver variable the next statement targets. public string Receiver => _receivers.Peek(); /// Pushes the root receiver (the route or builder-level definition variable). public string PushRoot(string declaration, XElement element, string prefix) { var name = Fresh(prefix); MapTo(element); Line($"var {name} = {declaration};"); _receivers.Push(name); return name; } /// Pops the current receiver. public void PopReceiver() => _receivers.Pop(); private string Fresh(string prefix) => $"{prefix}{_nextVar++}"; /// One statement on the current receiver: recv.Verb(args);. public XmlCodeWriter Verb(XElement element, string verb, params string[] args) { MapTo(element); return Line($"{Receiver}.{verb}({string.Join(", ", args)});"); } /// A configuration statement on the current receiver (no element mapping). public XmlCodeWriter Config(string call) => Line($"{Receiver}.{call};"); /// /// Prints a scope: a fresh variable opened from the current receiver, the children as /// statements on it, and the closing call. null = a typed /// section that never closes (ofType). /// public XmlCodeWriter Scope(XElement element, string openVerb, string[] args, string? closeVerb, Action? body = null) { var name = Fresh("s"); MapTo(element); Line($"var {name} = {Receiver}.{openVerb}({string.Join(", ", args)});"); _receivers.Push(name); if (body is not null) body(this); else PrintSteps(element); _receivers.Pop(); if (closeVerb is not null) Line($"{name}.{closeVerb}();"); return this; } /// Opens a branch child (when/catch) as a fresh variable on the current receiver. public string OpenBranch(XElement element, string verb, params string[] args) { var name = Fresh("b"); MapTo(element); Line($"var {name} = {Receiver}.{verb}({string.Join(", ", args)});"); if (element.Attribute("id")?.Value is { Length: > 0 }) throw new NotSupportedException( $"id= on a branch child <{element.Name.LocalName}> is not supported by the code generator " + "(the fluent DSL has no public seam to set a branch StepId before its steps)."); if (element.Attribute("description")?.Value is { Length: > 0 } description) Line($"{name}.Description({Str(description)});"); _receivers.Push(name); return name; } /// Closes a branch opened by . public void CloseBranch(string name, string? closeVerb = null) { _receivers.Pop(); if (closeVerb is not null) Line($"{name}.{closeVerb}();"); } /// Prints every child element as a step through its registered contribution. public XmlCodeWriter PrintSteps(XElement parent) { foreach (var child in parent.Elements()) PrintStep(child); return this; } /// Prints one element through its registered contribution. public XmlCodeWriter PrintStep(XElement element) { var contribution = _registry.Find(element.Name.LocalName) ?? throw new NotSupportedException( $"element <{element.Name.LocalName}> is not in the registry — the parser would refuse it too."); if (Style == CodeGenStyle.Readable && element.Attribute("description")?.Value is { Length: > 0 } description) Line($"// {description}"); contribution.Print(element, this); PrintIdentity(element); return this; } /// /// The trailing identity the parser applies: Id()/Description() on the /// receiver target its LAST output — the step just printed — exactly like the loader. /// public XmlCodeWriter PrintIdentity(XElement element) { if (element.Attribute("id")?.Value is { Length: > 0 } id) Config($"Id({Str(id)})"); if (element.Attribute("description")?.Value is { Length: > 0 } description) Config($"Description({Str(description)})"); return this; } // ── literals (§3.2–3.3) ────────────────────────────────────────────────── /// A C# string literal: plain when harmless, raw """…""" otherwise. public static string Str(string value) { if (!value.Contains('"') && !value.Contains('\\') && !value.Contains('\n') && !value.Contains('\r')) return $"\"{value}\""; if (!value.Contains('\n') && !value.Contains('\r') && !value.Contains("\"\"\"")) return $"\"\"\"{value}\"\"\""; var cleaned = value.Replace("\r", "", StringComparison.Ordinal); return "\"\"\"\n" + cleaned + "\n\"\"\""; } /// An expression argument: the route-language string wrapped in Expr(...). public static string Expr(string template) => $"Expr({Str(template)})"; /// A markup value= as code: a literal, or Placeholder("…") when it carries {{key}}. public static string Value(string value) => PropertyPlaceholderResolver.HasPlaceholder(value) ? $"Placeholder({Str(value)})" : Str(value); /// A as code (§3.3): round values by unit, otherwise Parse. public static string Ts(TimeSpan value) { if (value.Ticks % TimeSpan.TicksPerSecond == 0 && value.TotalSeconds is >= 1 and < 1000000) return $"TimeSpan.FromSeconds({value.TotalSeconds.ToString(CultureInfo.InvariantCulture)})"; if (value.Ticks % TimeSpan.TicksPerMillisecond == 0 && value.TotalMilliseconds is >= 1 and < 1000000) return $"TimeSpan.FromMilliseconds({value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)})"; return $"TimeSpan.Parse({Str(value.ToString("c", CultureInfo.InvariantCulture))}, System.Globalization.CultureInfo.InvariantCulture)"; } /// A typeof(...) when the type resolves now; the runtime lookup otherwise. public static string TypeRef(string typeName) { var resolved = Components.Bean.DefaultBeanTypeResolver.Instance.Resolve(typeName); return resolved?.FullName is { } fullName && !fullName.Contains('`') ? $"typeof(global::{fullName})" : $"Type.GetType({Str(typeName)}, throwOnError: true)!"; } /// A bool literal. public static string Bool(bool value) => value ? "true" : "false"; /// An enum member reference. public static string EnumRef(T value) where T : struct, Enum => $"{typeof(T).Name}.{value}"; } Path: redb-route/redb.Route.Xml/XmlContextLoader.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/XmlContextLoader.cs ---- using System.Xml.Linq; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Xml; /// /// Loads a context.xml document: the context-level /// sections a package carries besides its routes — an explicit <components> list, /// context-wide <bean> declarations, and the <onInit> pipeline of /// ordinary format steps, run ONCE at — /// the engine's only fail-fast bootstrap hook, so a failed step keeps the context from /// accepting traffic, exactly the module-init semantics the sketch asks for. Same eager /// collect-all parsing with positions as the routes loader. /// public sealed class XmlContextLoader { private readonly RouteContext _context; private readonly ElementRegistry _registry; private readonly bool _validate; private readonly bool _hasExtensions; /// Creates a loader for the given context. public XmlContextLoader(RouteContext context, XmlRouteLoaderOptions? options = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _registry = ElementRegistry.CreateDefault(options?.Extensions); _validate = options?.ValidateAgainstSchema ?? true; _hasExtensions = options?.Extensions is { Count: > 0 }; } /// Parses and applies every section of the document. See the class remarks. public void Load(XDocument document, string? sourceName = null) { ArgumentNullException.ThrowIfNull(document); sourceName ??= ""; var ctx = new XmlParseContext(_context, _registry, sourceName); var root = document.Root; if (root is null || root.Name.LocalName != "context") { throw new XmlRouteException(sourceName, [$"the document root must be , found <{root?.Name.LocalName ?? "nothing"}>."]); } if (root.Name.NamespaceName != XmlRouteLoader.Namespace) { throw new XmlRouteException(sourceName, [XmlRouteLoader.VersionError(root.Name.NamespaceName) ?? $"unexpected root namespace '{root.Name.NamespaceName}'; this loader reads '{XmlRouteLoader.Namespace}'."]); } ctx.CheckElementNamespaces(root); // Components first, then beans (a bean may need a component's types loaded), then init. foreach (var components in root.Elements().Where(e => e.Name.LocalName == "components")) RegisterComponents(components, ctx); foreach (var bean in root.Elements().Where(e => e.Name.LocalName == "bean")) BeanSection.Declare(bean, ctx); var onInits = root.Elements().Where(e => e.Name.LocalName == "onInit").ToList(); if (onInits.Count > 1) ctx.AddError(onInits[1], " takes at most one ."); // Context-level contributions: a package element beside // // (the redb bridge above all) applies to the context AFTER beans — a contribution may // reference #names — and BEFORE parsing, whose steps may rely on what the // contribution set up. foreach (var element in root.Elements()) { if (element.Name.LocalName is "components" or "bean" or "onInit" or XmlRouteLoader.RouteConfigurationElement) continue; if (ctx.Registry.Find(element.Name.LocalName) is IXmlContextContribution contextLevel && contextLevel.Kind == XmlElementKind.ContextLevel) { contextLevel.ApplyContext(element, _context, ctx); continue; } var contributed = ctx.Registry.Contributions .Where(c => c.Kind == XmlElementKind.ContextLevel) .Select(c => "<" + c.Name + ">"); ctx.AddError(element, $"unknown section <{element.Name.LocalName}> " + $"(valid: , , , {string.Concat(contributed.Select(n => ", " + n))})."); } // Route configurations: the context's shared error handling, for the routes of every file and builder. They // live on a builder of their own, built here so every error surfaces at Load, added once the document is valid. var configurationElements = root.Elements() .Where(e => e.Name.LocalName == XmlRouteLoader.RouteConfigurationElement).ToList(); XmlRouteLoader.XmlRoutesBuilder? configurations = null; if (configurationElements.Count > 0) { configurations = new XmlRouteLoader.XmlRoutesBuilder(sourceName, b => { foreach (var element in configurationElements) XmlRouteLoader.ParseRouteConfiguration(element, b, ctx); }); configurations.BuildNow(_context); } RouteDefinition? init = null; if (onInits.Count == 1) { // Ordinary steps of the format, parsed by the same registry; has no place in // an init pipeline and is rejected as an unknown element naturally. init = new RouteDefinition(); ctx.ParseSteps(onInits[0], init); } ctx.CheckSchemes(); if (_validate) { var schema = _hasExtensions ? XmlRouteSchema.For(_registry) : XmlRouteSchema.CoreSet; foreach (var (line, column, message) in XmlRouteSchema.Validate(document, schema)) { if (!ctx.ErrorLines.Contains(line)) ctx.AddRawError($"{sourceName}({line},{column}): [schema] {message}"); } } if (ctx.Errors.Count > 0) throw new XmlRouteException(sourceName, ctx.Errors); foreach (var work in ctx.ValidOnlyWork) work(); if (configurations is not null) _context.AddRoutes(configurations); if (init is not null && init.Outputs.Count > 0) _context.AddLifecycleListener(new XmlInitListener(init, sourceName)); } private void RegisterComponents(XElement section, XmlParseContext ctx) { foreach (var child in section.Elements()) { if (child.Name.LocalName != "component") { ctx.AddError(child, $" accepts only children, found <{child.Name.LocalName}>."); continue; } var typeName = ctx.RequiredAttr(child, "type"); if (typeName is null) continue; var resolver = _context.GetService() ?? DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(typeName); if (type is null) { ctx.AddError(child, $"component type '{typeName}' was not found in the loaded assemblies."); continue; } if (!typeof(IComponent).IsAssignableFrom(type)) { ctx.AddError(child, $"'{typeName}' does not implement IComponent."); continue; } try { var provider = _context.GetServiceProvider(); var component = (IComponent)(provider is not null ? ActivatorUtilities.CreateInstance(CollectibleTypeServiceProvider.For(provider), type) : Activator.CreateInstance(type) ?? throw new InvalidOperationException($"Activator returned null for {type}.")); _context.AddComponent(component); } catch (Exception ex) when (ex is MissingMethodException or MemberAccessException or InvalidOperationException) { ctx.AddError(child, $"component '{typeName}' could not be created: {ex.Message}"); } } } } /// /// Runs the parsed <onInit> pipeline once, in the fail-fast bootstrap phase. The /// steps compile through the ordinary node pipeline (so telemetry decoration and disposal /// registration apply) with the live context, and a step failure aborts Start(). /// internal sealed class XmlInitListener(RouteDefinition pipeline, string sourceName) : IRouteLifecycleListener { private bool _ran; // set only on success: a failed Start() must retry the init on the next Start() public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { if (_ran) return; var body = NodePipeline.Body(context, pipeline.Outputs); var exchange = new Exchange(new Message((object?)null)); try { await body.Process(exchange, ct).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception thrown) { // A step may throw directly or record on the exchange — both name the source file. throw new InvalidOperationException($" of '{sourceName}' failed: {thrown.Message}", thrown); } if (exchange.Exception is { } failure && !exchange.ExceptionHandled) throw new InvalidOperationException($" of '{sourceName}' failed: {failure.Message}", failure); _ran = true; } } Path: redb-route/redb.Route.Xml/XmlParseContext.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/XmlParseContext.cs ---- using System.Xml; using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Xml; /// /// The traversal state one document is parsed with: the registry, the error collector (every /// problem of the document in one pass, with positions), the value converter shared with the /// endpoint options, and the recursion helper scopes call for their children. /// public sealed class XmlParseContext { private readonly List _errors = []; private readonly List<(XElement Element, string Uri, EndpointRole Side)> _endpointUris = []; private readonly string _sourceName; internal XmlParseContext(IRouteContext routeContext, ElementRegistry registry, string sourceName) { RouteContext = routeContext; Registry = registry; _sourceName = sourceName; } /// The context routes are being loaded into (registry lookups, component names). public IRouteContext RouteContext { get; } /// The element registry the traversal dispatches through. public ElementRegistry Registry { get; } /// All collected errors, each with its file position. public IReadOnlyList Errors => _errors; /// Lines that already carry a parse error — schema validation skips them (§3.4 dedup). internal IReadOnlySet ErrorLines => _errorLines; private readonly HashSet _errorLines = []; // ── Errors and positions ───────────────────────────────────────────────── /// Records a problem at the element's position; parsing continues. public void AddError(XElement element, string message) { if (element is IXmlLineInfo { } info && info.HasLineInfo()) _errorLines.Add(info.LineNumber); _errors.Add($"{Position(element)}: {message}"); } /// Appends an already-positioned message (the schema validation path). internal void AddRawError(string positionedMessage) => _errors.Add(positionedMessage); /// /// Work that changes the context only once the whole document is valid (adding routes): the loader runs it after the /// last check, and a document with errors runs none of it. /// internal void WhenValid(Action action) => _whenValid.Add(action); /// The work collected, in document order. internal IReadOnlyList ValidOnlyWork => _whenValid; private readonly List _whenValid = []; /// The file(line,column) prefix of an element. public string Position(XElement element) => element is IXmlLineInfo info && info.HasLineInfo() ? $"{_sourceName}({info.LineNumber},{info.LinePosition})" : _sourceName; // ── Attributes ─────────────────────────────────────────────────────────── /// The attribute's value, or null when absent. Attributes of foreign namespaces are ignored. public string? Attr(XElement element, string name) => element.Attribute(name)?.Value; /// /// The attribute's value; records an error and returns null when absent or blank — the /// contribution then returns the current position unchanged and the pass continues. /// public string? RequiredAttr(XElement element, string name) { var value = element.Attribute(name)?.Value; if (string.IsNullOrWhiteSpace(value)) { AddError(element, $"<{element.Name.LocalName}> requires the '{name}' attribute."); return null; } return value; } /// /// Converts an attribute through the same converter the endpoint options use (invariant /// culture; enums by name). A malformed value records an error and returns null. /// public T? Convert(XElement element, string name) where T : struct { var raw = Attr(element, name); if (raw is null) return null; if (OptionValueConverter.Convert(raw, typeof(T)) is T converted) return converted; AddError(element, $"'{raw}' is not a valid {typeof(T).Name} for the '{name}' attribute."); return null; } /// /// Enforces the exactly-one-of rule for a pair of attributes (value vs /// expr, expr vs predicate). Returns which one is present, or null after /// recording the error. /// public (string Name, string Value)? ExactlyOneOf(XElement element, string first, string second) { var a = Attr(element, first); var b = Attr(element, second); if (a is not null && b is not null) { AddError(element, $"<{element.Name.LocalName}> takes '{first}' or '{second}', not both."); return null; } if (a is null && b is null) { AddError(element, $"<{element.Name.LocalName}> requires '{first}' or '{second}'."); return null; } return a is not null ? (first, a) : (second, b!); } // ── Traversal ──────────────────────────────────────────────────────────── /// /// Parses the child elements of as a step sequence into /// . Unknown elements and throwing contributions are recorded as /// errors and skipped, so one pass reports everything. The generic id / /// description attributes are applied after each step. /// public IRouteDefinition ParseSteps(XElement parent, IRouteDefinition current) { foreach (var element in parent.Elements()) current = ParseStep(element, current); return current; } /// Parses one element as a step (see ). public IRouteDefinition ParseStep(XElement element, IRouteDefinition current) { var name = element.Name.LocalName; var contribution = Registry.Find(name); if (contribution is null) { var hint = Registry.ClosestTo(name); AddError(element, hint is null ? $"unknown element <{name}>." : $"unknown element <{name}>. Did you mean <{hint}>?"); return current; } try { var next = contribution.Apply(element, current, this); ApplyIdentity(element, next); return next; } catch (Exception ex) { // Collect-all discipline: a throwing DSL call (a malformed expression, a bad enum) // becomes one positioned error and the pass continues with the next sibling. The // aggregate is thrown at the end of Load, so nothing is swallowed. AddError(element, ex.Message); return current; } } private static void ApplyIdentity(XElement element, IRouteDefinition current) { if (element.Attribute("id")?.Value is { Length: > 0 } id) current.Id(id); if (element.Attribute("description")?.Value is { Length: > 0 } description) current.Description(description); } /// /// Identity for a branch child (<when>, <otherwise>, /// <catch>, …) — parsed inside its parent's contribution, so the regular /// Id()/Description() chain (which targets the LAST OUTPUT) does not apply; /// the attributes land on the branch definition itself (common to all elements). /// public void ApplyBranchIdentity(XElement element, IRouteDefinition definition) { if (definition is not Definitions.ProcessorDefinition step) return; if (element.Attribute("id")?.Value is { Length: > 0 } id) step.StepId = id; if (element.Attribute("description")?.Value is { Length: > 0 } description) step.StepDescription = description; } // ── Endpoint URIs (the load-time scheme check) ─────────────────────────── /// /// Notes an endpoint URI a step sends to, for the post-parse scheme check. URIs led by {{…}} or /// ${…} are skipped — their scheme is known later. /// public void NoteEndpointUri(XElement element, string uri) => NoteEndpointUri(element, uri, EndpointRole.Producer); /// /// Notes an endpoint URI and the side the step creates (<from> the consumer, every other step the /// producer), for the post-parse checks of its scheme and of the side its component has. /// public void NoteEndpointUri(XElement element, string uri, EndpointRole side) { if (uri.StartsWith("{{", StringComparison.Ordinal) || uri.StartsWith("${", StringComparison.Ordinal)) return; _endpointUris.Add((element, uri, side)); } /// Checks every noted literal scheme against the context's registered components. /// /// One rule for the whole document: every element must live in the route namespace — an /// element from another (or the empty) namespace never passes as a core element on a /// local-name match. Package namespaces will widen the allowed set together with the /// catalog/XSD; until then the rule keeps every written document XSD-clean. /// internal void CheckElementNamespaces(XElement root) { foreach (var element in root.Descendants()) { if (element.Name.NamespaceName != XmlRouteLoader.Namespace) AddError(element, $"element <{element.Name.LocalName}> is in namespace " + $"'{element.Name.NamespaceName}'; only the route namespace " + $"'{XmlRouteLoader.Namespace}' is readable."); } } internal void CheckSchemes() { var known = new HashSet(RouteContext.GetComponentNames(), StringComparer.OrdinalIgnoreCase); foreach (var (element, uri, side) in _endpointUris) { var separator = uri.IndexOf(':'); if (separator <= 0) continue; // not a scheme-shaped URI; the endpoint parser will speak to it var scheme = uri[..separator]; if (scheme.Contains("{{") || scheme.Contains("${")) continue; if (!known.Contains(scheme)) { AddError(element, $"scheme '{scheme}' is not registered in the context. Reference the connector " + $"package and register its component (registered: {string.Join(", ", known.OrderBy(n => n))})."); continue; } // The side its component has ([EndpointRole] on the class), in the words the context refuses it with. if (RouteContext.GetComponent(scheme) is { } component && EndpointSides.Declaration(component.GetType()) is { } only && only.Role != side) { // The structured form notes the endpoint element; the step is its parent. var step = element.Attribute("uri") is null && element.Parent is { } parent ? parent : element; AddError(element, $"<{step.Name.LocalName}>: {EndpointSides.MissingSide(scheme, only.Role, only.Hint)}"); } } } } Path: redb-route/redb.Route.Xml/XmlRouteLoader.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/XmlRouteLoader.cs ---- using System.Reflection; using System.Xml.Linq; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Core; namespace redb.Route.Xml; /// /// Loads .route.xml documents into a through the existing /// fluent DSL — no second engine. The whole document is parsed eagerly at /// : beans first (so #name references resolve), then every route; /// every error of the document — unknown elements, malformed expressions, unregistered URI /// schemes — is collected in one pass and thrown as one with /// file positions. Nothing is registered when the document has errors. /// public sealed class XmlRouteLoader { /// The route-format XML namespace; the major part changes only on a breaking format change. public const string Namespace = "urn:redb:route:1.0"; /// The format version this loader reads: same major, minor not above. internal const int SupportedMajor = 1; internal const int SupportedMinor = 0; /// /// The §3.2 version policy on the root namespace: urn:redb:route:{major}.{minor} — /// the major must match, the minor must not exceed what this loader supports; a newer /// document says exactly what to update instead of failing on the first unknown element. /// Returns null when the namespace is not ours at all (the caller keeps its own message). /// internal static string? VersionError(string namespaceName) { const string prefix = "urn:redb:route:"; if (!namespaceName.StartsWith(prefix, StringComparison.Ordinal)) return null; var version = namespaceName[prefix.Length..]; var dot = version.IndexOf('.'); if (dot <= 0 || !int.TryParse(version[..dot], out var major) || !int.TryParse(version[(dot + 1)..], out var minor)) return $"'{namespaceName}' is not a valid route-format namespace (expected urn:redb:route:MAJOR.MINOR)."; if (major != SupportedMajor) return $"the document is format {major}.{minor}; this loader reads major version {SupportedMajor} " + $"({Namespace}) — a different major is a different format."; if (minor > SupportedMinor) return $"the document needs format {major}.{minor}; this loader supports up to " + $"{SupportedMajor}.{SupportedMinor} — update the redb.Route.Xml package."; return null; } private readonly RouteContext _context; private readonly ElementRegistry _registry; private readonly bool _validate; private readonly bool _hasExtensions; /// Creates a loader for the given context. public XmlRouteLoader(RouteContext context, XmlRouteLoaderOptions? options = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _registry = ElementRegistry.CreateDefault(options?.Extensions); _validate = options?.ValidateAgainstSchema ?? true; _hasExtensions = options?.Extensions is { Count: > 0 }; } /// /// The §3.4 pass: schema findings appended AFTER the parse, skipping lines the parser /// already reported — its messages (did-you-mean, exact rules) win on a shared line. /// internal void ValidateAgainstSchema(XDocument document, string sourceName, XmlParseContext ctx) { if (!_validate) return; var schema = _hasExtensions ? XmlRouteSchema.For(_registry) : XmlRouteSchema.CoreSet; foreach (var (line, column, message) in XmlRouteSchema.Validate(document, schema)) { if (!ctx.ErrorLines.Contains(line)) ctx.AddRawError($"{sourceName}({line},{column}): [schema] {message}"); } } /// Parses and registers every route of the document. See the class remarks. public void Load(XDocument document, string? sourceName = null) { ArgumentNullException.ThrowIfNull(document); sourceName ??= ""; var ctx = new XmlParseContext(_context, _registry, sourceName); var root = document.Root; if (root is null || root.Name.LocalName != "routes") { throw new XmlRouteException(sourceName, [$"the document root must be , found <{root?.Name.LocalName ?? "nothing"}>."]); } if (root.Name.NamespaceName != Namespace) { throw new XmlRouteException(sourceName, [VersionError(root.Name.NamespaceName) ?? $"unexpected root namespace '{root.Name.NamespaceName}'; this loader reads '{Namespace}'."]); } ctx.CheckElementNamespaces(root); // Section order: beans before routes, so registry references resolve. foreach (var bean in root.Elements().Where(e => e.Name.LocalName == "bean")) BeanSection.Declare(bean, ctx); var containerElements = new List(); var topLevelElements = new List<(XElement Element, IXmlTopLevelContribution Contribution)>(); var configurationElements = root.Elements().Where(e => e.Name.LocalName == RouteConfigurationElement).ToList(); foreach (var element in root.Elements()) { if (element.Name.LocalName is "bean" or "route" or RouteConfigurationElement) continue; if (element.Name.LocalName is "onException" or "intercept" or "interceptFrom" or "interceptSendToEndpoint" or "onCompletion") { // Declared on the builder — they apply to every route of the file. containerElements.Add(element); continue; } if (ctx.Registry.Find(element.Name.LocalName) is IXmlTopLevelContribution topLevel && topLevel.Kind == XmlElementKind.TopLevel) { // A package's container-level element (the REST DSL): applied to the builder. topLevelElements.Add((element, topLevel)); continue; } ctx.AddError(element, ctx.Registry.Find(element.Name.LocalName) is null ? $"unknown container element <{element.Name.LocalName}>." : $"<{element.Name.LocalName}> is not valid at the container level."); } // The parse runs inside the builder's Configure — InternalBuild clears and rebuilds a // builder, so definitions must be born there. Building eagerly here surfaces every error // at Load; IsBuilt then keeps Start() from re-running the parse. var routeElements = root.Elements().Where(e => e.Name.LocalName == "route").ToList(); var builder = new XmlRoutesBuilder(sourceName, b => { foreach (var element in containerElements) ParseContainerHandler(element, b, ctx); foreach (var element in configurationElements) ParseRouteConfiguration(element, b, ctx); foreach (var (element, contribution) in topLevelElements) { try { contribution.ApplyTopLevel(element, b, ctx); } catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException) { // Same collect-all net ParseStep has: a throwing DSL call becomes one // positioned error and the pass continues. ctx.AddError(element, ex.Message); } } foreach (var element in routeElements) ParseRoute(element, b, ctx); }); builder.BuildNow(_context); ctx.CheckSchemes(); ValidateAgainstSchema(document, sourceName, ctx); if (ctx.Errors.Count > 0) throw new XmlRouteException(sourceName, ctx.Errors); _context.AddRoutes(builder); } /// /// A container-level handler (<onException>, the intercepts, /// <onCompletion>): declared on the builder for every route of the file, and /// configured by the SAME helpers the route-level contributions use — no second copy. A /// builder-level definition has no parent, so no End…() is called here. /// private static void ParseContainerHandler(XElement element, XmlRoutesBuilder builder, XmlParseContext ctx) { switch (element.Name.LocalName) { case "onException": { var types = CoreElements.CoreContributions.ExceptionTypes(element, ctx); if (types.Length == 0) return; var handler = builder.OnException(types); ctx.ApplyBranchIdentity(element, handler); CoreElements.CoreContributions.ConfigureOnException(handler, element, ctx); return; } case "intercept": { var handler = builder.Intercept(); ctx.ApplyBranchIdentity(element, handler); CoreElements.CoreContributions.ConfigureIntercept(handler, element, ctx); return; } case "interceptFrom": { var handler = builder.InterceptFrom(ctx.Attr(element, "uri")); ctx.ApplyBranchIdentity(element, handler); CoreElements.CoreContributions.ConfigureIntercept(handler, element, ctx); return; } case "interceptSendToEndpoint": { var uri = ctx.RequiredAttr(element, "uri"); if (uri is null) return; var handler = builder.InterceptSendToEndpoint(uri); ctx.ApplyBranchIdentity(element, handler); CoreElements.CoreContributions.ConfigureIntercept(handler, element, ctx); return; } default: { var handler = builder.OnCompletion(); ctx.ApplyBranchIdentity(element, handler); CoreElements.CoreContributions.ConfigureOnCompletion(handler, element, ctx); return; } } } /// The element of a route configuration, in a routes file and in context.xml. internal const string RouteConfigurationElement = "routeConfiguration"; /// /// <routeConfiguration id="…"> (Apache Camel's Route Configuration): its <onException> /// blocks apply to the routes of every file and builder of the context — to the routes that name the id with /// routeConfigurationId, or, without an id, to every route that names none. Declared on the builder the /// document loads into; the handlers are configured by the helpers the route-level <onException> uses. /// internal static void ParseRouteConfiguration(XElement element, RouteBuilder builder, XmlParseContext ctx) { var id = ctx.Attr(element, "id"); if (id is { Length: 0 }) { ctx.AddError(element, ": leave the attribute out for the default configuration."); return; } var configuration = builder.AddRouteConfiguration(id); foreach (var child in element.Elements()) { if (child.Name.LocalName != "onException") { ctx.AddError(child, $" takes blocks, found <{child.Name.LocalName}>."); continue; } var types = CoreElements.CoreContributions.ExceptionTypes(child, ctx); if (types.Length == 0) continue; var handler = configuration.OnException(types); ctx.ApplyBranchIdentity(child, handler); CoreElements.CoreContributions.ConfigureOnException(handler, child, ctx); } if (configuration.ExceptionDefinitions.Count == 0 && !element.Elements().Any()) ctx.AddError(element, " declares nothing: add an ."); } private static void ParseRoute(XElement element, XmlRoutesBuilder builder, XmlParseContext ctx) { var from = element.Elements().FirstOrDefault(e => e.Name.LocalName == "from"); if (from is null) { ctx.AddError(element, " requires exactly one ."); return; } if (element.Elements().Count(e => e.Name.LocalName == "from") > 1) { ctx.AddError(element, " must have exactly one ; several found."); return; } var uri = StructuredEndpoint.Resolve(from, ctx, out var position); if (uri is null) return; if (uri.Contains("${", StringComparison.Ordinal)) { // V4: a ${...} placeholder in a consumer URI fails Start() — there is no message to // resolve against. The loader says it earlier and with the position. ctx.AddError(position, "a consumer URI cannot carry ${...} — only constants and {{key}} " + "configuration placeholders are valid in ."); return; } ctx.NoteEndpointUri(position, uri, EndpointRole.Consumer); // enabled=: false after {{...}} resolution — the route is // not registered at all. Placeholders resolve through the context's own lookup chain // (IConfiguration, then context properties), so per-stand switching needs no code. if (ctx.Attr(element, "enabled") is { } enabled) { string resolved; try { // A test double of IRouteContext has no placeholder chain — the literal is used. resolved = ctx.RouteContext is RouteContext live ? live.ResolvePlaceholders(enabled) : enabled; } catch (InvalidOperationException ex) { ctx.AddError(element, ex.Message); return; } if (!bool.TryParse(resolved, out var isEnabled)) { ctx.AddError(element, $"enabled=\"{enabled}\" resolved to '{resolved}', which is not a bool."); return; } if (!isEnabled) return; } IRouteDefinition route = builder.From(uri); ApplyRouteAttributes(element, route, ctx); foreach (var child in element.Elements().Where(c => c.Name.LocalName != "from")) route = ctx.ParseStep(child, route); } private static void ApplyRouteAttributes(XElement element, IRouteDefinition route, XmlParseContext ctx) { if (ctx.Attr(element, "id") is { Length: > 0 } id) route.RouteId(id); if (ctx.Attr(element, "description") is { Length: > 0 } description) route.Description(description); if (ctx.Convert(element, "autoStart") is { } autoStart) route.AutoStart(autoStart); if (ctx.Convert(element, "cluster") is { } cluster) route.Cluster(cluster); if (ctx.Convert(element, "messageHistory") is { } history) route.MessageHistory(history); if (ctx.Convert(element, "tracing") is { } tracing) route.Tracing(tracing); if (ctx.Convert(element, "processingTimeout") is { } timeout) route.ProcessingTimeout(timeout); if (ctx.Attr(element, "routePolicy") is { Length: > 0 } policy) route.RoutePolicy(policy); if (ctx.Attr(element, "routeConfigurationId") is { Length: > 0 } configurations) route.RouteConfigurationId(configurations); } /// /// The builder XML routes live in. The document parse IS its Configure — run eagerly by the /// loader so every error surfaces at Load; then keeps /// Start() from re-running it (InternalBuild clears a builder before configuring). /// internal sealed class XmlRoutesBuilder(string sourceName, Action parse) : RouteBuilder { internal override string SourceName => sourceName; protected override void Configure() => parse(this); internal void BuildNow(IRouteContext context) => InternalBuild(context); } } /// /// The <bean> container section: declares an object in the context registry. The /// markup is read by and built by — the same /// pair generated code and the package gate use. References resolve against the registry as it /// stands, so a bean may refer only to beans declared before it (document order, the context /// file first) or registered by module code; anything else is a positioned error. /// internal static class BeanSection { internal static void Declare(XElement element, XmlParseContext ctx) { // The step form (amended 2026-11-05) written at the container level: say where it belongs. if (element.Attribute("name") is null && element.Attribute("type") is null && (element.Attribute("ref") is not null || element.Attribute("beanType") is not null)) { ctx.AddError(element, "a or is a step: it belongs inside a . " + "At this level a is a declaration with name= and type=."); return; } var name = ctx.RequiredAttr(element, "name"); if (name is null) return; var declaration = BeanModel.Parse(element, ctx.AddError); if (declaration is null) return; var instance = Build(declaration, ctx); if (instance is not null) ctx.RouteContext.AddToRegistry(name, instance); } private static object? Build(BeanDeclaration bean, XmlParseContext ctx) { var resolver = ctx.RouteContext.GetService() ?? DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(bean.TypeName); if (type is null) { ctx.AddError(bean.At, $" type '{bean.TypeName}' was not found in the loaded assemblies."); return null; } var args = new List(); List? argumentTypes = bean.TypedArguments ? [] : null; foreach (var arg in bean.ConstructorArgs) { if (!TryRaw(arg.Value, ctx, out var raw)) return null; args.Add(raw); if (arg.TypeName is null) continue; if (resolver.Resolve(arg.TypeName) is not { } argumentType) { ctx.AddError(arg.Value.At, $": the type was not found in the loaded assemblies."); return null; } argumentTypes!.Add(argumentType); } var resolve = Placeholders(ctx); object instance; try { instance = BeanFactory.Instantiate( type, args, argumentTypes, bean.FactoryMethod, ctx.RouteContext.GetServiceProvider() ?? EmptyProvider.Instance, resolve); } catch (Exception ex) { ctx.AddError(bean.At, (ex as TargetInvocationException)?.InnerException?.Message ?? ex.Message); return null; } foreach (var property in bean.Properties) { if (!TryRaw(property.Value, ctx, out var raw)) continue; try { BeanFactory.Assign(instance, property.Key, raw, resolve); } catch (Exception ex) { ctx.AddError(property.At, (ex as TargetInvocationException)?.InnerException?.Message ?? ex.Message); } } return instance; } /// /// The raw form binds: text as it is written, a reference as the /// registered object, a nested bean as its instance, a list as its raw items. False after /// recording an error at the element that caused it. /// private static bool TryRaw(BeanValue value, XmlParseContext ctx, out object? raw) { raw = null; switch (value) { case ScalarBeanValue scalar: raw = scalar.Text; return true; case RefBeanValue reference: raw = ctx.RouteContext.GetFromRegistry(reference.Bean); if (raw is null) ctx.AddError(reference.At, $"bean reference '{reference.Bean}' names nothing registered so far — beans are built in " + "document order (the context file first), so declare it above this one, or register it from module code before the XML loads."); return raw is not null; case NestedBeanValue nested: raw = Build(nested.Bean, ctx); return raw is not null; case ListBeanValue list: { Type? elementType = null; if (list.ElementTypeName is not null) { var resolver = ctx.RouteContext.GetService() ?? DefaultBeanTypeResolver.Instance; elementType = resolver.Resolve(list.ElementTypeName); if (elementType is null) { ctx.AddError(list.At, $": the type was not found in the loaded assemblies."); return false; } } var items = new List(list.Items.Count); var complete = true; foreach (var item in list.Items) { complete &= TryRaw(item, ctx, out var itemRaw); items.Add(itemRaw); } raw = new BeanListValue(elementType, items); return complete; } default: throw new InvalidOperationException($"unhandled bean value {value.GetType().Name}."); } } /// /// Bean values may carry {{key}} / {{key:default}} — resolved through the /// context's own placeholder chain before type conversion; an unresolved key without a /// default throws, and the caller positions it at the slot. /// private static Func Placeholders(XmlParseContext ctx) => ctx.RouteContext is RouteContext live ? text => text.Contains("{{", StringComparison.Ordinal) ? live.ResolvePlaceholders(text) : text : text => text; private sealed class EmptyProvider : IServiceProvider { public static readonly EmptyProvider Instance = new(); public object? GetService(Type serviceType) => null; } } Path: redb-route/redb.Route.Xml/XmlRouteSchema.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/XmlRouteSchema.cs ---- using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using redb.Route.Core; namespace redb.Route.Xml; /// /// The XSD of the route format, GENERATED from the element registry: the parser, the /// schema and the catalog read one list, so they cannot drift apart. The schema covers the /// container skeleton (<routes>/<context>, <bean>, /// <route>) plus every registered element with its attributes, enum hints and /// content model. Package contributions appear automatically; the endpoint children of the /// structured form (§7.2) are open content until a component catalog supplies the scheme /// elements. One namespace, urn:redb:route:1.0; foreign-namespace attributes are /// tolerated (anyAttribute ##other lax), foreign elements are not. /// public static class XmlRouteSchema { private const string Ns = XmlRouteLoader.Namespace; private static readonly XNamespace Xs = "http://www.w3.org/2001/XMLSchema"; private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Cache = new(); private static readonly Lazy Core = new(() => For(ElementRegistry.CreateDefault())); /// The compiled schema of the core element set — generated and compiled once. public static XmlSchemaSet CoreSet => Core.Value; /// Validates against an already-compiled set (the loader's hot path). public static IReadOnlyList<(int Line, int Column, string Message)> Validate( XDocument document, XmlSchemaSet schema) { ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(schema); var problems = new List<(int, int, string)>(); var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = schema }; settings.ValidationEventHandler += (_, e) => problems.Add((e.Exception?.LineNumber ?? 0, e.Exception?.LinePosition ?? 0, e.Message)); using var reader = XmlReader.Create(document.CreateReader(), settings); while (reader.Read()) { } return problems; } /// The compiled schema for a registry (cached per registry instance). public static XmlSchemaSet For(ElementRegistry registry) { ArgumentNullException.ThrowIfNull(registry); return Cache.GetValue(registry, r => { var set = new XmlSchemaSet(); using var reader = Generate(r).CreateReader(); set.Add(Ns, reader); set.Compile(); return set; }); } /// /// Validates a document against the registry's schema. Returns one positioned message per /// problem; an empty list means the document is schema-valid. /// public static IReadOnlyList<(int Line, int Column, string Message)> Validate( XDocument document, ElementRegistry registry) { ArgumentNullException.ThrowIfNull(document); var schema = For(registry); var problems = new List<(int, int, string)>(); var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = schema }; settings.ValidationEventHandler += (_, e) => problems.Add((e.Exception?.LineNumber ?? 0, e.Exception?.LinePosition ?? 0, e.Message)); using var reader = XmlReader.Create(document.CreateReader(), settings); while (reader.Read()) { } return problems; } /// /// Validates against a schema that also knows the component catalog: the §7.2 endpoint /// children become a STRICT set of scheme elements with typed, enum-hinted options. /// public static IReadOnlyList<(int Line, int Column, string Message)> Validate( XDocument document, ElementRegistry registry, IReadOnlyList catalog) { ArgumentNullException.ThrowIfNull(document); var set = new XmlSchemaSet(); using (var reader = Generate(registry, catalog).CreateReader()) set.Add(Ns, reader); set.Compile(); var problems = new List<(int, int, string)>(); var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = set }; settings.ValidationEventHandler += (_, e) => problems.Add((e.Exception?.LineNumber ?? 0, e.Exception?.LinePosition ?? 0, e.Message)); using var validating = XmlReader.Create(document.CreateReader(), settings); while (validating.Read()) { } return problems; } /// Generates the schema document for a registry — also the file the tooling ships. public static XDocument Generate(ElementRegistry registry, IReadOnlyList? catalog = null) { ArgumentNullException.ThrowIfNull(registry); var contributions = registry.Contributions .OrderBy(c => c.Name, StringComparer.Ordinal) .ToList(); var stepNames = contributions .Where(c => c.Kind is XmlElementKind.Step or XmlElementKind.Scope or XmlElementKind.Branching) .Select(c => c.Name) .ToList(); var schema = new XElement(Xs + "schema", new XAttribute("targetNamespace", Ns), new XAttribute("elementFormDefault", "qualified"), new XAttribute(XNamespace.Xmlns + "xs", Xs), new XAttribute(XNamespace.Xmlns + "r", Ns)); // The step group: every registered step/scope/branching element. schema.Add(new XElement(Xs + "group", new XAttribute("name", "step"), new XElement(Xs + "choice", stepNames.Select(StepParticle)))); foreach (var contribution in contributions) schema.Add(contribution.Name == BeanStep ? NamedType(BeanStepType, contribution.Spec, catalog) : GlobalElement(contribution.Spec, catalog)); schema.Add(BeanElement()); schema.Add(BeanListType()); if (catalog is not null) { schema.Add(OtherSideTypes()); // One type per (component, side), referenced from every endpoint position (see // SchemeElement): a connector's options are declared once, not once per position. foreach (var endpointType in EndpointTypes(catalog)) schema.Add(endpointType); } schema.Add(RouteElement(catalog)); if (contributions.Any(c => c.Name == "onException")) schema.Add(RouteConfigurationElement()); schema.Add(RoutesElement(contributions)); schema.Add(ContextElement(contributions)); return new XDocument(schema); } // ── the container skeleton (owned by the loader, versioned with it) ────── private static XElement RoutesElement(IReadOnlyList contributions) { var containerHandlers = new[] { "onException", "intercept", "interceptFrom", "interceptSendToEndpoint", "onCompletion" } .Where(n => contributions.Any(c => c.Name == n)); var topLevel = contributions .Where(c => c.Kind == XmlElementKind.TopLevel) .Select(c => c.Name); return new XElement(Xs + "element", new XAttribute("name", "routes"), new XElement(Xs + "complexType", new XElement(Xs + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), new XElement(Xs + "element", new XAttribute("ref", "r:bean")), new XElement(Xs + "element", new XAttribute("ref", "r:route")), containerHandlers.Select(n => new XElement(Xs + "element", new XAttribute("ref", "r:" + n))), RouteConfigurationRef(contributions), topLevel.Select(n => new XElement(Xs + "element", new XAttribute("ref", "r:" + n)))), new XElement(Xs + "attribute", new XAttribute("name", "version"), new XAttribute("type", "xs:string")), ForeignAttributes())); } /// /// <routeConfiguration id="…">: <onException> blocks shared by the routes of the context. /// Part of the skeleton, as <route> is; present whenever <onException> is. /// private static XElement RouteConfigurationElement() => new(Xs + "element", new XAttribute("name", XmlRouteLoader.RouteConfigurationElement), new XElement(Xs + "complexType", new XElement(Xs + "sequence", new XElement(Xs + "element", new XAttribute("ref", "r:onException"), new XAttribute("minOccurs", "1"), new XAttribute("maxOccurs", "unbounded"))), Attribute(new AttributeSpec("id", AttributeType.String)), ForeignAttributes())); private static IEnumerable RouteConfigurationRef(IReadOnlyList contributions) => contributions.Any(c => c.Name == "onException") ? [new XElement(Xs + "element", new XAttribute("ref", "r:" + XmlRouteLoader.RouteConfigurationElement))] : []; private static XElement ContextElement(IReadOnlyList contributions) => new(Xs + "element", new XAttribute("name", "context"), new XElement(Xs + "complexType", new XElement(Xs + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), new XElement(Xs + "element", new XAttribute("name", "components"), new XElement(Xs + "complexType", new XElement(Xs + "sequence", new XElement(Xs + "element", new XAttribute("name", "component"), new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), new XElement(Xs + "complexType", Attribute(new AttributeSpec("type", AttributeType.TypeName, Required: true)), ForeignAttributes()))))), new XElement(Xs + "element", new XAttribute("ref", "r:bean")), new XElement(Xs + "element", new XAttribute("name", "onInit"), new XElement(Xs + "complexType", StepGroup(), ForeignAttributes())), RouteConfigurationRef(contributions), contributions .Where(c => c.Kind == XmlElementKind.ContextLevel) .Select(c => new XElement(Xs + "element", new XAttribute("ref", "r:" + c.Name)))))); private static XElement BeanElement() => new(Xs + "element", new XAttribute("name", "bean"), new XElement(Xs + "complexType", new XElement(Xs + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), // A slot holds exactly one of value=, ref=, a nested , a ; the // schema offers all four and the parser (BeanModel) rejects a second one. new XElement(Xs + "element", new XAttribute("name", "property"), BeanSlot(Attribute(new AttributeSpec("key", AttributeType.String, Required: true)))), new XElement(Xs + "element", new XAttribute("name", "constructorArg"), // type= names the parameter the value binds to (Spring constructor-arg type): // the constructor or factory method is then the one with exactly that signature. BeanSlot(Attribute(new AttributeSpec("type", AttributeType.TypeName))))), // name is required on a registered bean and absent on a nested anonymous one — // context-dependent, so the parser enforces it and the schema stays permissive. Attribute(new AttributeSpec("name", AttributeType.String)), Attribute(new AttributeSpec("type", AttributeType.TypeName, Required: true)), // A public static creator instead of a constructor; constructorArg values are its // arguments (X509CertificateLoader.LoadPkcs12FromFile is the shape this serves). Attribute(new AttributeSpec("factoryMethod", AttributeType.String)), ForeignAttributes())); private static XElement BeanSlot(params XElement[] attributes) => new(Xs + "complexType", new XElement(Xs + "choice", new XAttribute("minOccurs", "0"), new XElement(Xs + "element", new XAttribute("ref", "r:bean")), new XElement(Xs + "element", new XAttribute("name", "list"), new XAttribute("type", "r:beanList"))), attributes, Attribute(new AttributeSpec("value", AttributeType.String)), // A bean registered earlier, by its bare name (no '#': the attribute already says it). Attribute(new AttributeSpec("ref", AttributeType.String)), ForeignAttributes()); /// /// A named type because a list nests: its items are text values, references, anonymous beans /// and further lists. of= names the element type where the target does not (a constructor). /// private static XElement BeanListType() => new(Xs + "complexType", new XAttribute("name", "beanList"), new XElement(Xs + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), new XElement(Xs + "element", new XAttribute("name", "value"), new XAttribute("type", "xs:string")), new XElement(Xs + "element", new XAttribute("name", "ref"), new XElement(Xs + "complexType", Attribute(new AttributeSpec("bean", AttributeType.String, Required: true)), ForeignAttributes())), new XElement(Xs + "element", new XAttribute("ref", "r:bean")), new XElement(Xs + "element", new XAttribute("name", "list"), new XAttribute("type", "r:beanList"))), Attribute(new AttributeSpec("of", AttributeType.TypeName)), ForeignAttributes()); private static XElement RouteElement(IReadOnlyList? catalog) => new(Xs + "element", new XAttribute("name", "route"), new XElement(Xs + "complexType", new XElement(Xs + "sequence", new XElement(Xs + "element", new XAttribute("name", "from"), new XElement(Xs + "complexType", EndpointContent(catalog, EndpointRole.Consumer), Attribute(new AttributeSpec("uri", AttributeType.Uri)), ForeignAttributes())), StepGroup()), Attribute(new AttributeSpec("id", AttributeType.String)), Attribute(new AttributeSpec("description", AttributeType.String)), Attribute(new AttributeSpec("autoStart", AttributeType.Bool)), Attribute(new AttributeSpec("cluster", AttributeType.Bool)), Attribute(new AttributeSpec("messageHistory", AttributeType.Bool)), Attribute(new AttributeSpec("tracing", AttributeType.Bool)), Attribute(new AttributeSpec("processingTimeout", AttributeType.Duration)), Attribute(new AttributeSpec("routePolicy", AttributeType.Reference)), Attribute(new AttributeSpec("routeConfigurationId", AttributeType.String)), Attribute(new AttributeSpec("enabled", AttributeType.String)), ForeignAttributes())); // ── the step (amended 2026-11-05) ──────────────────────────────── // The one element name with two content models: the global is the declaration (, , // nested bean values); the step is declared locally in the step group with its own // type. Two global declarations of one name would make the schema invalid, so the special case lives here only. private const string BeanStep = "bean"; private const string BeanStepType = "beanStep"; private static XElement StepParticle(string name) => name == BeanStep ? new XElement(Xs + "element", new XAttribute("name", BeanStep), new XAttribute("type", "r:" + BeanStepType)) : new XElement(Xs + "element", new XAttribute("ref", "r:" + name)); private static XElement NamedType(string typeName, ElementSpec spec, IReadOnlyList? catalog) { var type = ComplexType(spec, catalog); type.Add(new XAttribute("name", typeName)); return type; } // ── one element from its spec ──────────────────────────────────────────── private static XElement GlobalElement(ElementSpec spec, IReadOnlyList? catalog) => new(Xs + "element", new XAttribute("name", spec.Name), ComplexType(spec, catalog)); private static XElement ComplexType(ElementSpec spec, IReadOnlyList? catalog = null) { var type = new XElement(Xs + "complexType"); if (spec.AllowsTextContent) type.Add(new XAttribute("mixed", "true")); var contentParticles = new List(); foreach (var child in spec.Children) contentParticles.Add(new XElement(Xs + "element", new XAttribute("name", child.Name), ComplexType(child))); if (spec.AllowsSteps) contentParticles.Add(new XElement(Xs + "group", new XAttribute("ref", "r:step"))); if (spec.TakesEndpoint) contentParticles.AddRange(EndpointParticles(catalog, EndpointRole.Producer)); if (contentParticles.Count > 0) { type.Add(new XElement(Xs + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), contentParticles)); } foreach (var attribute in spec.Attributes) type.Add(Attribute(attribute)); // Id/description on every element (unless the spec already claims the names). if (spec.Attributes.All(a => a.Name != "id")) type.Add(Attribute(new AttributeSpec("id", AttributeType.String))); if (spec.Attributes.All(a => a.Name != "description")) type.Add(Attribute(new AttributeSpec("description", AttributeType.String))); // An element whose further attributes are the options of a type it names (a serializer's Delimiter, Indented) // takes any attribute; the loader holds each against the type's writable properties. type.Add(spec.OpenAttributes ? new XElement(Xs + "anyAttribute", new XAttribute("namespace", "##any"), new XAttribute("processContents", "lax")) : ForeignAttributes()); return type; } private static XElement StepGroup() => new(Xs + "group", new XAttribute("ref", "r:step"), new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded")); /// /// The §7.2 endpoint children: open lax content without a catalog; with one — the STRICT /// set of scheme elements, each with its typed options, path/synonym attributes and open /// family/text-option children. /// private static IReadOnlyList EndpointParticles(IReadOnlyList? catalog, EndpointRole side) { if (catalog is null) { // skip, not lax: lax validates a child against a global declaration of the same name, and an endpoint // child may share its name with a step (, ) or with the // declaration. Without a catalog the schema knows no endpoint shapes; the child is normalized into the // URI and checked strictly where the endpoint is bound (BindFromUri). return [new XElement(Xs + "any", new XAttribute("namespace", "##targetNamespace"), new XAttribute("processContents", "skip"))]; } return [.. catalog .Where(c => HasSide(c, side)) .OrderBy(c => c.Scheme, StringComparer.Ordinal) .Select(c => SchemeElement(c, side))]; } /// /// Whether the component has : a component with one side () /// is left out of the other side's positions and gets no type for it. /// private static bool HasSide(CatalogComponent component, EndpointRole side) => component.Role is null || component.Role == side; private static XElement EndpointContent(IReadOnlyList? catalog, EndpointRole side) => new(Xs + "choice", new XAttribute("minOccurs", "0"), EndpointParticles(catalog, side)); /// /// The scheme element at an endpoint position: a reference to the ONE type carrying its options. /// The options used to be inlined at every position that takes an endpoint (from, to, /// enrich, pollEnrich, wireTap, interceptSendToEndpoint, both sides), so a /// connector's whole option set stood in the schema twelve times over. That is what the editor's /// language server pays for: it builds a content model per complex type, and the same options /// repeated across a dozen models, each inside a choice of every scheme, is not what a schema of the /// same size costs when it is written with named types (2026-10-08). One type per (component, side) /// is the whole difference. /// private static XElement SchemeElement(CatalogComponent component, EndpointRole side) => new(Xs + "element", new XAttribute("name", component.Scheme), new XAttribute("type", "r:" + EndpointTypeName(component, side))); /// The name of the type a scheme element refers to — one per component and side. private static string EndpointTypeName(CatalogComponent component, EndpointRole side) => component.Scheme + (side == EndpointRole.Producer ? "Producer" : "Consumer"); /// Every endpoint type the catalog needs, in a stable order (the scheme ordinal). private static IEnumerable EndpointTypes(IReadOnlyList catalog) => catalog .OrderBy(c => c.Scheme, StringComparer.Ordinal) .SelectMany(c => new[] { EndpointRole.Producer, EndpointRole.Consumer } .Where(side => HasSide(c, side)) .Select(side => EndpointType(c, side))); private static XElement EndpointType(CatalogComponent component, EndpointRole side) { var type = new XElement(Xs + "complexType", new XAttribute("name", EndpointTypeName(component, side)), new XAttribute("mixed", "true"), // Family entries () and long text options are open children. new XElement(Xs + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), new XElement(Xs + "any", new XAttribute("namespace", "##targetNamespace"), new XAttribute("processContents", "lax")))); // One declaration per attribute name, or the schema does not compile at all ("the // attribute 'queue' already exists"): a component whose path synonym is ALSO an option // — seda's queue, amqp's path — would declare it twice. The option wins, it carries the // type and the enum values; the synonym only names the path. var declared = new HashSet(component.Options.Select(o => CamelCase(o.Name)), StringComparer.Ordinal); if (!component.PathIsText) { if (declared.Add("path")) type.Add(Attribute(new AttributeSpec("path", AttributeType.String))); if (component.PathSynonym is { Length: > 0 } synonym && declared.Add(synonym)) type.Add(Attribute(new AttributeSpec(synonym, AttributeType.String))); } foreach (var option in component.Options) { // An option only the other side reads is refused by the connector (EndpointRole). A // strict connector simply does not declare it here, so the editor flags it as unknown; // a lenient one takes any attribute through its wildcard, so the option is declared // with a type no value satisfies — the editor's message names it (producerOnlyOption). if (option.Role is { } role && role != side) { if (component.Lenient) type.Add(new XElement(Xs + "attribute", new XAttribute("name", CamelCase(option.Name)), new XAttribute("type", "r:" + OtherSideType(role)))); continue; } if (option.Type is "enum" or "flags" && option.EnumValues is { Count: > 0 } members) { type.Add(new XElement(Xs + "attribute", new XAttribute("name", CamelCase(option.Name)), EnumOptionType(members, flags: option.Type == "flags"))); continue; } type.Add(Attribute(new AttributeSpec( CamelCase(option.Name), option.Type switch { "bool" => AttributeType.Bool, "int" => AttributeType.Int, "long" => AttributeType.Long, "double" => AttributeType.Double, "duration" => AttributeType.Duration, "enum" => AttributeType.Enum, _ => AttributeType.String, }, EnumValues: option.EnumValues))); } // The engine's own rule for an unknown parameter: a lenient connector takes it (http passes // it on, sql reads it), a strict one refuses the endpoint — so the editor refuses the // attribute too. A foreign-namespace attribute is never an option and stays legal. type.Add(new XElement(Xs + "anyAttribute", new XAttribute("namespace", component.Lenient ? "##any" : "##other"), new XAttribute("processContents", "lax"))); return type; } /// /// A connector's enum option as the engine reads it: member names in any case (the option /// converter parses with ignoreCase, and the engine's own messages write them lowercase — /// ackMode=manual). A union of the lowercase list, which the editor offers as /// completion, and a case-insensitive pattern, which accepts Manual as the engine does. /// A [Flags] enum takes several members joined by commas (Tls12,Tls13), which is a /// pattern and nothing else, so flags always take the union. /// /// A LONG pick-one list keeps the plain member list instead. The pattern spells every member out /// as character classes, and the catalog's 43 long options (fileExist, sortBy, postProcess, /// operation …) sit at the same sites the short ones do: with the union for all of them the schema /// reached 21k lines and 1.1 MB, and the editor's language server died with an out-of-memory error /// on the first completion (2026-10-08). A long list loses the case-insensitive spelling with it: /// the schema takes the names the catalog lists (fileExist="Append"), other cases only load /// in the engine. pins both halves of this. /// private static XElement EnumOptionType(IReadOnlyList members, bool flags) { if (!flags && members.Count > CaseInsensitiveUnionMaxMembers) { return new XElement(Xs + "simpleType", new XElement(Xs + "restriction", new XAttribute("base", "xs:string"), members.Select(m => new XElement(Xs + "enumeration", new XAttribute("value", m))))); } var member = "(" + string.Join("|", members.Select(AnyCase)) + ")"; var pattern = flags ? $@"{member}(\s*,\s*{member})*" : member; return new XElement(Xs + "simpleType", new XElement(Xs + "union", new XElement(Xs + "simpleType", new XElement(Xs + "restriction", new XAttribute("base", "xs:string"), members.Select(m => new XElement(Xs + "enumeration", new XAttribute("value", m.ToLowerInvariant()))))), new XElement(Xs + "simpleType", new XElement(Xs + "restriction", new XAttribute("base", "xs:string"), new XElement(Xs + "pattern", new XAttribute("value", pattern)))))); } /// Members up to which the case-insensitive union is worth its size (see ). private const int CaseInsensitiveUnionMaxMembers = 3; /// A member name as a case-insensitive XSD regex (Tls12 → [tT][lL][sS]12). private static string AnyCase(string name) => string.Concat(name.Select(c => char.IsLetter(c) ? $"[{char.ToLowerInvariant(c)}{char.ToUpperInvariant(c)}]" : c.ToString())); private static string OtherSideType(EndpointRole role) => role == EndpointRole.Producer ? "producerOnlyOption" : "consumerOnlyOption"; /// /// The types of an option written on the side that does not read it: an empty character class /// admits no value, so any use is a validation error, and the type name is the explanation. /// private static IEnumerable OtherSideTypes() => new[] { EndpointRole.Producer, EndpointRole.Consumer }.Select(role => new XElement(Xs + "simpleType", new XAttribute("name", OtherSideType(role)), new XElement(Xs + "annotation", new XElement(Xs + "documentation", role == EndpointRole.Producer ? "Read only by the producer (): the consumer () refuses it." : "Read only by the consumer (): the producer () refuses it.")), new XElement(Xs + "restriction", new XAttribute("base", "xs:string"), new XElement(Xs + "pattern", new XAttribute("value", "[a-[a]]"))))); // An option group member (SearchTerm.Subject) is written with every segment camelCase: searchTerm.subject. private static string CamelCase(string name) => string.Join('.', name.Split('.').Select(part => part.Length > 0 && char.IsUpper(part[0]) ? char.ToLowerInvariant(part[0]) + part[1..] : part)); private static XElement Attribute(AttributeSpec spec) { var attribute = new XElement(Xs + "attribute", new XAttribute("name", spec.Name)); if (spec.Required) attribute.Add(new XAttribute("use", "required")); if (spec.Type is AttributeType.Enum && spec.EnumValues is { Count: > 0 } values) { attribute.Add(new XElement(Xs + "simpleType", new XElement(Xs + "restriction", new XAttribute("base", "xs:string"), values.Select(v => new XElement(Xs + "enumeration", new XAttribute("value", v)))))); } else { attribute.Add(new XAttribute("type", BuiltInType(spec.Type))); } return attribute; } private static string BuiltInType(AttributeType type) => type switch { AttributeType.Bool => "xs:boolean", AttributeType.Int => "xs:int", AttributeType.Long => "xs:long", AttributeType.Double => "xs:double", // Duration is hh:mm:ss(.fff), not the ISO xs:duration — a string to the schema. _ => "xs:string", }; private static XElement ForeignAttributes() => new(Xs + "anyAttribute", new XAttribute("namespace", "##other"), new XAttribute("processContents", "lax")); } Path: redb-route/redb.Route.Xml/redb.Route.Xml.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: 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/redb.Route.Xml.csproj ---- redb.Route.Xml Declarative XML routes for redb.Route: .route.xml files load into the existing fluent DSL - one engine, a contribution registry extensible by packages, load-time failures with file positions. esb;messaging;xml;routes;eip;redb README.md