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