Path: redb-route/redb.Route.Core/Xml/RedbXmlContributions.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.Core/Xml/RedbXmlContributions.cs
----
using System.Globalization;
using System.Xml.Linq;
using redb.Route.Abstractions;
using redb.Route.Components.Bean;
using redb.Route.RedbCore.Extensions;
using redb.Route.RedbCore.Transactions;
using redb.Route.Xml;
namespace redb.Route.RedbCore.Xml;
///
/// The redb storage elements of the route markup (contributions of this
/// package): <redbGet>, <redbSave>, <redbDelete>,
/// <redbQuery> in routes and the <redb> bridge block in
/// context.xml. Parse, schema shape and C# printing live together per element.
///
internal static class RedbXml
{
internal static Type? ResolveType(XElement element, string typeName, XmlParseContext context)
{
var resolver = context.RouteContext.GetService()
?? DefaultBeanTypeResolver.Instance;
var type = resolver.Resolve(typeName);
if (type is null)
context.AddError(element, $"props type '{typeName}' was not found in the loaded assemblies.");
return type;
}
internal static string? OptionalArgs(XElement element, out int? depth, out string? storage, out string? target)
{
depth = element.Attribute("depth")?.Value is { } d
? int.Parse(d, CultureInfo.InvariantCulture)
: null;
storage = element.Attribute("storage")?.Value;
target = element.Attribute("target")?.Value;
return null;
}
/// The element's text content (CDATA included), null when there is none.
internal static string? Text(XElement element)
{
var text = string.Concat(element.Nodes().OfType().Select(t => t.Value));
return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}
}
/// The <redbGet> element: typed load with type=, raw-JSON load without.
public sealed class RedbGetXmlContribution : IXmlElementContribution
{
///
public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"];
///
public string Name => "redbGet";
///
public XmlElementKind Kind => XmlElementKind.Step;
///
public ElementSpec Spec => ElementSpec.Leaf(Name,
new AttributeSpec("id", AttributeType.Expression, Required: true),
new AttributeSpec("type", AttributeType.TypeName),
new AttributeSpec("depth", AttributeType.Int),
new AttributeSpec("storage", AttributeType.String),
new AttributeSpec("target", AttributeType.String));
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
var id = context.RequiredAttr(element, "id");
if (id is null)
return current;
RedbXml.OptionalArgs(element, out var depth, out var storage, out var target);
if (element.Attribute("type")?.Value is { } typeName)
{
var type = RedbXml.ResolveType(element, typeName, context);
return type is null
? current
: current.RedbGet(type, id, depth ?? 10, storage, target);
}
return current.RedbGetJson(id, depth ?? 10, storage, target);
}
///
public void Print(XElement element, XmlCodeWriter code)
{
RedbXml.OptionalArgs(element, out var depth, out var storage, out var target);
var args = new List();
if (element.Attribute("type")?.Value is { } typeName)
args.Add(XmlCodeWriter.TypeRef(typeName));
args.Add(XmlCodeWriter.Str(element.Attribute("id")!.Value));
if (depth is { } d) args.Add($"depth: {d}");
if (storage is not null) args.Add($"storage: {XmlCodeWriter.Str(storage)}");
if (target is not null) args.Add($"target: {XmlCodeWriter.Str(target)}");
code.Verb(element, element.Attribute("type") is null ? "RedbGetJson" : "RedbGet", [.. args]);
}
}
/// The <redbSave> element: saves the body (JSON is materialized via type=).
public sealed class RedbSaveXmlContribution : IXmlElementContribution
{
///
public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"];
///
public string Name => "redbSave";
///
public XmlElementKind Kind => XmlElementKind.Step;
///
public ElementSpec Spec => ElementSpec.Leaf(Name,
new AttributeSpec("type", AttributeType.TypeName),
new AttributeSpec("byUnique", AttributeType.Bool),
new AttributeSpec("storage", AttributeType.String));
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
Type? type = null;
if (element.Attribute("type")?.Value is { } typeName)
{
type = RedbXml.ResolveType(element, typeName, context);
if (type is null)
return current;
}
var byUnique = context.Convert(element, "byUnique") ?? false;
if (byUnique && type is null)
{
context.AddError(element, "byUnique=\"true\" needs type= — the unique-key save is typed.");
return current;
}
return current.RedbSave(type, byUnique, element.Attribute("storage")?.Value);
}
///
public void Print(XElement element, XmlCodeWriter code)
{
var args = new List();
if (element.Attribute("type")?.Value is { } typeName)
args.Add(XmlCodeWriter.TypeRef(typeName));
if (element.Attribute("byUnique")?.Value == "true") args.Add("byUnique: true");
if (element.Attribute("storage")?.Value is { } storage)
args.Add($"storage: {XmlCodeWriter.Str(storage)}");
code.Verb(element, "RedbSave", [.. args]);
}
}
///
/// The <redbQuery> element: a server-side query — the where string (props)
/// and the whereRedb string (base fields of the stored object) ride the engine's ONE
/// expression AST into redb LINQ, filter="#spec" is the full-LINQ escape hatch. A
/// condition the translator refuses is a positioned load error.
///
public sealed class RedbQueryXmlContribution : IXmlElementContribution
{
///
public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"];
///
public string Name => "redbQuery";
///
public XmlElementKind Kind => XmlElementKind.Step;
///
public ElementSpec Spec => new(Name, Kind,
[
new AttributeSpec("type", AttributeType.TypeName, Required: true),
new AttributeSpec("where", AttributeType.Expression),
new AttributeSpec("orderBy", AttributeType.String),
new AttributeSpec("descending", AttributeType.Bool),
new AttributeSpec("take", AttributeType.Int),
new AttributeSpec("skip", AttributeType.Int),
new AttributeSpec("filter", AttributeType.Reference),
new AttributeSpec("storage", AttributeType.String),
new AttributeSpec("target", AttributeType.String),
// The base fields of the stored object (Id, ParentId, ValueGuid, DateCreate...) — redb
// WhereRedb / OrderByRedb; ANDed with where=, since one OR cannot mix the two.
new AttributeSpec("whereRedb", AttributeType.Expression),
new AttributeSpec("orderByRedb", AttributeType.String),
// The terminal operation: the list (default), FirstOrDefault, Count or Any.
new AttributeSpec("outputType", AttributeType.Enum, EnumValues: ["List", "First", "Count", "Any"]),
],
// The condition may live as the element's text instead of the where attribute — a
// CDATA block frees it from < escaping. Exactly one of the two forms.
[], AllowsTextContent: true);
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
var typeName = context.RequiredAttr(element, "type");
if (typeName is null)
return current;
var type = RedbXml.ResolveType(element, typeName, context);
if (type is null)
return current;
var whereAttribute = context.Attr(element, "where");
var whereInline = RedbXml.Text(element);
if (whereAttribute is not null && whereInline is not null)
{
context.AddError(element,
" takes the condition either as where= or as the element's text (CDATA welcome), not both.");
return current;
}
var output = context.Convert(element, "outputType");
if (output is null && context.Attr(element, "outputType") is not null)
return current; // the malformed value is already a positioned error
try
{
return current.RedbQuery(type,
where: whereAttribute ?? whereInline,
orderBy: context.Attr(element, "orderBy"),
descending: context.Convert(element, "descending") ?? false,
take: context.Convert(element, "take"),
skip: context.Convert(element, "skip"),
filter: context.Attr(element, "filter"),
storage: context.Attr(element, "storage"),
target: context.Attr(element, "target"),
whereRedb: context.Attr(element, "whereRedb"),
orderByRedb: context.Attr(element, "orderByRedb"),
outputType: output ?? RedbQueryOutput.List);
}
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException)
{
// The translator's refusals (and the unbounded-scan guard) become positioned
// document errors — collected with the rest, not a crash mid-parse.
context.AddError(element, ex.Message);
return current;
}
}
///
public void Print(XElement element, XmlCodeWriter code)
{
var args = new List { XmlCodeWriter.TypeRef(element.Attribute("type")!.Value) };
if ((element.Attribute("where")?.Value ?? RedbXml.Text(element)) is { } where)
args.Add($"where: {XmlCodeWriter.Str(where)}");
if (element.Attribute("orderBy")?.Value is { } orderBy) args.Add($"orderBy: {XmlCodeWriter.Str(orderBy)}");
if (element.Attribute("descending")?.Value == "true") args.Add("descending: true");
if (element.Attribute("take")?.Value is { } take) args.Add($"take: {take}");
if (element.Attribute("skip")?.Value is { } skip) args.Add($"skip: {skip}");
if (element.Attribute("filter")?.Value is { } filter) args.Add($"filter: {XmlCodeWriter.Str(filter)}");
if (element.Attribute("storage")?.Value is { } storage) args.Add($"storage: {XmlCodeWriter.Str(storage)}");
if (element.Attribute("target")?.Value is { } target) args.Add($"target: {XmlCodeWriter.Str(target)}");
if (element.Attribute("whereRedb")?.Value is { } whereRedb) args.Add($"whereRedb: {XmlCodeWriter.Str(whereRedb)}");
if (element.Attribute("orderByRedb")?.Value is { } orderByRedb) args.Add($"orderByRedb: {XmlCodeWriter.Str(orderByRedb)}");
if (element.Attribute("outputType")?.Value is { } outputType)
args.Add($"outputType: RedbQueryOutput.{Enum.Parse(outputType, ignoreCase: true)}");
code.Verb(element, "RedbQuery", [.. args]);
}
}
/// The <redbDelete> element: deletes by id, no props type needed.
public sealed class RedbDeleteXmlContribution : IXmlElementContribution
{
///
public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"];
///
public string Name => "redbDelete";
///
public XmlElementKind Kind => XmlElementKind.Step;
///
public ElementSpec Spec => ElementSpec.Leaf(Name,
new AttributeSpec("id", AttributeType.Expression, Required: true),
new AttributeSpec("storage", AttributeType.String));
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
var id = context.RequiredAttr(element, "id");
return id is null ? current : current.RedbDelete(id, element.Attribute("storage")?.Value);
}
///
public void Print(XElement element, XmlCodeWriter code)
{
var args = new List { XmlCodeWriter.Str(element.Attribute("id")!.Value) };
if (element.Attribute("storage")?.Value is { } storage)
args.Add($"storage: {XmlCodeWriter.Str(storage)}");
code.Verb(element, "RedbDelete", [.. args]);
}
}
///
/// The <redb> block of context.xml: scheme synchronization at context
/// startup and named idempotent repositories — the context-level face of the bridge.
///
public sealed class RedbContextXmlContribution : IXmlContextContribution
{
///
public string Name => "redb";
///
public XmlElementKind Kind => XmlElementKind.ContextLevel;
///
public ElementSpec Spec => new(Name, Kind,
[new AttributeSpec("storage", AttributeType.String)],
[
ElementSpec.Child("syncScheme", allowsSteps: false,
new AttributeSpec("type", AttributeType.TypeName, Required: true)),
ElementSpec.Child("idempotentRepository", allowsSteps: false,
// Registers a redb idempotent repository under this bare name — the key
// and a consumer's idempotentRepository= look up.
new AttributeSpec("name", AttributeType.String, Required: true)
{
Registers = $"{typeof(Repositories.RedbIdempotentRepository).FullName}, {typeof(Repositories.RedbIdempotentRepository).Assembly.GetName().Name}",
},
new AttributeSpec("ttl", AttributeType.Duration),
new AttributeSpec("processorName", AttributeType.String)),
],
AllowsSteps: false);
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
context.AddError(element, " is a context-level block — put it inside , not in a route.");
return current;
}
///
public void ApplyContext(XElement element, Route.Core.RouteContext context, XmlParseContext parseContext)
{
var storage = element.Attribute("storage")?.Value;
foreach (var child in element.Elements())
{
switch (child.Name.LocalName)
{
case "syncScheme":
if (parseContext.RequiredAttr(child, "type") is { } typeName
&& RedbXml.ResolveType(child, typeName, parseContext) is { } type)
context.SyncRedbScheme(type, storage);
break;
case "idempotentRepository":
if (parseContext.RequiredAttr(child, "name") is { } name)
context.AddRedbIdempotentRepository(name,
parseContext.Convert(child, "ttl"),
parseContext.Attr(child, "processorName"),
storage);
break;
default:
parseContext.AddError(child,
$"unknown child <{child.Name.LocalName}> (valid: , ).");
break;
}
}
}
}