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