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); } } }