Path: redb-route/redb.Route/Aggregation/AggregationStrategies.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/Aggregation/AggregationStrategies.cs
----
using System.Globalization;
using redb.Route.Abstractions;
using redb.Route.Expressions;
using redb.Route.Core;
namespace redb.Route.Aggregation;
///
/// Ready-made aggregation strategies (Apache Camel AggregationStrategies parity). Each is the
/// existing Func<IExchange, IExchange, IExchange> the DSL already takes, so one strategy
/// serves Aggregate , Multicast , ScatterGather , Split and Enrich .
///
/// Argument order is (accumulated, incoming) ; for Enrich that is (original, resource) .
/// Every strategy tolerates a null accumulator (Split calls the strategy for the first fragment
/// with null , Camel-style) and an accumulator that is still a plain first exchange (Multicast and
/// Aggregate start with the first result as the accumulator).
///
/// Named forms for the XML format: .
///
public static class AggregationStrategies
{
///
/// The list builds. A private subtype, so the strategy appends only to a
/// list it created itself: bodies are cloned by reference, and an incoming List<object?>
/// body is shared by the caller and every branch clone — appending to it would mutate the caller's
/// data and, when a branch kept that list as its body, add the list to itself.
///
private sealed class GroupedList : List;
/// Typed counterpart of for .
private sealed class GroupedList : List;
/// Collects the bodies into a List<object?> in the accumulated body.
public static Func GroupedBody() => (old, @new) =>
{
if (old is null) { @new.In.Body = new GroupedList { @new.In.Body }; return @new; }
if (old.In.Body is GroupedList list) list.Add(@new.In.Body);
else old.In.Body = new GroupedList { old.In.Body, @new.In.Body };
return old;
};
/// Collects the bodies into a typed List<T> ; a body that is not a fails with an explicit message.
public static Func GroupedBody() => (old, @new) =>
{
if (old is null) { @new.In.Body = new GroupedList { As(@new.In.Body) }; return @new; }
if (old.In.Body is GroupedList list) list.Add(As(@new.In.Body));
else old.In.Body = new GroupedList { As(old.In.Body), As(@new.In.Body) };
return old;
};
/// Collects the exchanges themselves into a List<IExchange> (for a Split whose fragments are processed later).
public static Func GroupedExchange() => (old, @new) =>
{
if (old is null) { @new.In.Body = new List { @new }; return @new; }
if (old.In.Body is List list) list.Add(@new);
else old.In.Body = new List { old, @new };
return old;
};
/// The incoming exchange wins (for Enrich : the response becomes the current message). Camel's default when no strategy is given.
public static Func UseLatest() => (_, @new) => @new;
/// The accumulated (first / original) exchange wins; the incoming one is dropped.
public static Func UseOriginal() => (old, @new) => old ?? @new;
/// Bodies as strings joined with .
public static Func Concat(string separator = "")
{
ArgumentNullException.ThrowIfNull(separator);
return (old, @new) =>
{
if (old is null) { @new.In.Body = Text(@new.In.Body); return @new; }
old.In.Body = Text(old.In.Body) + separator + Text(@new.In.Body);
return old;
};
}
/// Keeps the accumulated body; headers of the incoming exchange are merged in (the later one wins).
public static Func MergeHeaders() => (old, @new) =>
{
if (old is null) return @new;
foreach (var (key, value) in @new.In.Headers) old.In.Headers[key] = value;
return old;
};
/// Puts the incoming body into header of the accumulated exchange — the most common Enrich .
public static Func IntoHeader(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return (old, @new) =>
{
if (old is null) return @new;
old.In.Headers[name] = @new.In.Body;
return old;
};
}
/// Puts the incoming body into exchange property of the accumulated exchange.
public static Func IntoProperty(string key)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
return (old, @new) =>
{
if (old is null) return @new;
old.Properties[key] = @new.In.Body;
return old;
};
}
/// Numeric sum of a route-language expression ("body.amount" ) over the exchanges; the running total is the accumulated body (decimal).
public static Func Sum(string expression) => Fold(new StringExpression(expression), (a, b) => a + b);
/// Numeric sum of over the exchanges.
public static Func Sum(IExpression expression) => Fold(expression, (a, b) => a + b);
/// Maximum of a route-language expression over the exchanges.
public static Func Max(string expression) => Fold(new StringExpression(expression), Math.Max);
/// Maximum of over the exchanges.
public static Func Max(IExpression expression) => Fold(expression, Math.Max);
/// Minimum of a route-language expression over the exchanges.
public static Func Min(string expression) => Fold(new StringExpression(expression), Math.Min);
/// Minimum of over the exchanges.
public static Func Min(IExpression expression) => Fold(expression, Math.Min);
/// A caller-supplied strategy, wrapped so it reads like the others in a chain.
public static Func Custom(Func strategy)
=> strategy ?? throw new ArgumentNullException(nameof(strategy));
///
/// Resolves a strategy from its XML / configuration name: groupedBody , groupedExchange ,
/// useLatest , useOriginal , mergeHeaders , concat:<separator> ,
/// intoHeader:<name> , intoProperty:<key> , sum:<expression> ,
/// max:<expression> , min:<expression> . Case-insensitive.
///
public static Func ByName(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var colon = name.IndexOf(':');
var head = (colon >= 0 ? name[..colon] : name).Trim();
var argument = colon >= 0 ? name[(colon + 1)..] : null;
return head.ToLowerInvariant() switch
{
"groupedbody" => GroupedBody(),
"groupedexchange" => GroupedExchange(),
"uselatest" => UseLatest(),
"useoriginal" => UseOriginal(),
"mergeheaders" => MergeHeaders(),
"concat" => Concat(argument ?? ""),
"intoheader" => IntoHeader(Required(argument, name)),
"intoproperty" => IntoProperty(Required(argument, name)),
"sum" => Sum(Required(argument, name)),
"max" => Max(Required(argument, name)),
"min" => Min(Required(argument, name)),
_ => throw new ArgumentException(
$"Unknown aggregation strategy '{name}'. Known: groupedBody, groupedExchange, useLatest, useOriginal, mergeHeaders, " +
"concat:, intoHeader:, intoProperty:, sum:, max:, min:.", nameof(name)),
};
}
private static string Required(string? argument, string name)
=> string.IsNullOrWhiteSpace(argument)
? throw new ArgumentException($"Aggregation strategy '{name}' needs an argument after the colon.", nameof(name))
: argument;
/// Marks an accumulator whose body is the running value of a numeric fold.
private const string FoldMarker = "__redb_agg:fold";
///
/// Numeric fold. The accumulated body holds the running value once aggregation has started — marked
/// as such on the accumulator, because "the body is a number" is not proof: a plain first exchange
/// (Multicast / Aggregate seed the accumulator with the first result) may carry a numeric body of its
/// own, and its value must still be taken through the expression.
///
private static Func Fold(IExpression expression, Func combine)
{
ArgumentNullException.ThrowIfNull(expression);
return (old, @new) =>
{
var incoming = Number(expression.Evaluate(@new), expression);
if (old is null)
{
@new.In.Body = incoming;
@new.Properties[FoldMarker] = true;
return @new;
}
var running = old.Properties.ContainsKey(FoldMarker) && old.In.Body is { } body && IsNumber(body)
? RouteDecimal.From(body)
: Number(expression.Evaluate(old), expression);
old.In.Body = combine(running, incoming);
old.Properties[FoldMarker] = true;
return old;
};
}
private static decimal Number(object? value, IExpression expression) => value switch
{
null => throw new InvalidOperationException($"Aggregation: expression '{expression}' evaluated to null; a number is required."),
_ when IsNumber(value) => RouteDecimal.From(value),
string s when decimal.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out var parsed) => parsed,
_ => throw new InvalidOperationException($"Aggregation: expression '{expression}' evaluated to '{value}' ({value.GetType().Name}); a number is required."),
};
private static bool IsNumber(object value) => value is sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal;
private static string Text(object? body) => body switch
{
null => string.Empty,
string s => s,
byte[] bytes => System.Text.Encoding.UTF8.GetString(bytes),
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
_ => body.ToString() ?? string.Empty,
};
private static T As(object? body) => body switch
{
T typed => typed,
null when default(T) is null => default!,
_ => throw new InvalidOperationException($"GroupedBody<{typeof(T).Name}>: body is {body?.GetType().Name ?? "null"}, not {typeof(T).Name}."),
};
}