Path: redb-route/redb.Route.Xml/ComponentCatalog.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/ComponentCatalog.cs ---- using System.Globalization; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Xml; /// One endpoint option in the catalog: name, kind, default, secrecy, enum hints, the side that reads it. /// The option's property name (PascalCase; the URI and the markup take it case-insensitively). /// The value kind: bool, int, long, double, duration, enum (one member), flags (members joined by commas) or string. /// The default rendered invariantly, or null when unknown. /// A secret ([Sensitive]): redacted wherever the URI is shown. /// The member names of an enum option, else null. /// The only side of the endpoint that reads the option (): /// a producer-only option on a <from> is refused, and the other way round. Null — both sides read it. /// The connection factory sets it ([ConnectionParameter]): beside the option that names /// the factory it is refused, the factory being the whole connection. /// This option names the connection factory ([ConnectionFactoryReference]). public sealed record CatalogOption( string Name, string Type, string? Default, bool Sensitive, IReadOnlyList? EnumValues, EndpointRole? Role, [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool ConnectionParameter, [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool ConnectionFactoryReference) { /// /// Set when the option names a registry object ([RegistryReference], [ConnectionFactoryReference]): /// the type that object must have as Full.Name, Assembly, or object when the option does not say. /// Null for every other option, and then not written. /// [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Reference { get; init; } } /// One component in the catalog — everything the editor's property panel shows. /// The URI scheme and the structured-form element name. /// Other schemes the component answers to. /// The assembly the component lives in. /// The full name of its options class, or null when it has none. /// The attribute the structured form accepts for the path (kafka: topic), or null. /// The path is the element's text content (the SQL-style connectors). /// Its options, by name. /// The connector takes parameters it has no option for (): /// false = an unknown name is refused when the endpoint is created, so the schema and the package gate refuse it too. public sealed record CatalogComponent( string Scheme, IReadOnlyList AlternateSchemes, string? Package, string? OptionsType, string? PathSynonym, bool PathIsText, IReadOnlyList Options, bool Lenient) { /// /// The only side the component has ([EndpointRole] on its class, Apache Camel's producerOnly / /// consumerOnly); null, and then not written, when it has both. The editor schema leaves the missing /// side out, so the scheme is not offered there. /// [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public EndpointRole? Role { get; init; } /// The component's hint for the missing side, so that check refuses in the runtime's words. [JsonIgnore] internal string? RoleHint { get; init; } } /// /// The component catalog: built by REFLECTION from what already exists — the /// component's , its one-line §7.2 metadata, and its /// subclass (found in the component's assembly by naming, else /// as the single candidate). Nothing here is hand-kept per connector: a new component with /// Options and Scheme appears in the catalog, the structured form and the generated XSD with /// zero XML-specific code — the anti-copy-paste rule by construction. /// public static class ComponentCatalog { /// Builds catalog records for the given components, ordered by scheme. public static IReadOnlyList Build(IEnumerable components) { ArgumentNullException.ThrowIfNull(components); var records = new List(); foreach (var component in components.GroupBy(c => c.Scheme).Select(g => g.First())) { var type = component.GetType(); var optionsType = FindOptionsType(type); records.Add(new CatalogComponent( component.Scheme, [.. component.AlternateSchemes], type.Assembly.GetName().Name, optionsType?.FullName, (component as ComponentBase)?.StructuredPathSynonym, (component as ComponentBase)?.PathIsText ?? false, optionsType is null ? [] : HarvestOptions(optionsType), // No options class: nothing binds the parameters, so nothing refuses them either. optionsType is null || EndpointOptions.IsLenient(optionsType)) { Role = EndpointSides.Declaration(type)?.Role, RoleHint = EndpointSides.Declaration(type)?.Hint, }); } return [.. records.OrderBy(r => r.Scheme, StringComparer.Ordinal)]; } /// The catalog as pretty JSON — the file the editor tooling reads. public static string ToJson(IReadOnlyList catalog) => JsonSerializer.Serialize(catalog, JsonOptions); private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }, }; /// /// The component's options class: by naming (XComponent → XEndpointOptions / /// XOptions) in the component's assembly, else the assembly's single /// subclass, else none (an options-less component is honest). /// /// The TOptions of an endpoint type deriving from EndpointBase<TOptions>, or null. private static Type? DeclaredOptions(Type endpointType) { for (var type = endpointType; type is not null && type != typeof(object); type = type.BaseType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(EndpointBase<>)) return type.GetGenericArguments()[0]; } return null; } private static Type? FindOptionsType(Type componentType) { var candidates = componentType.Assembly.GetTypes() .Where(t => !t.IsAbstract && typeof(EndpointOptions).IsAssignableFrom(t)) .ToList(); if (candidates.Count == 0) return null; // The naming walk climbs the BASE chain too: HttpsComponent : HttpComponent finds // HttpEndpointOptions — a derived component inherits its base's options. for (var type = componentType; type is not null && type != typeof(object); type = type.BaseType) { var stem = type.Name.EndsWith("Component", StringComparison.Ordinal) ? type.Name[..^"Component".Length] : type.Name; // The endpoint the component creates declares its options as a type argument // (ImapEndpoint : EndpointBase) — the code says it, no name to // match. Three mail components share one options class, which naming never found. if (componentType.Assembly.GetType($"{type.Namespace}.{stem}Endpoint") is { } endpoint && DeclaredOptions(endpoint) is { } declared) return declared; var byName = candidates.FirstOrDefault(t => t.Name == stem + "EndpointOptions") ?? candidates.FirstOrDefault(t => t.Name == stem + "Options"); if (byName is not null) return byName; } // The single-candidate fallback is safe only in a single-component assembly — // otherwise a neighbour's options would silently attach to the wrong scheme. var componentCount = componentType.Assembly.GetTypes() .Count(t => !t.IsAbstract && typeof(IComponent).IsAssignableFrom(t)); return candidates.Count == 1 && componentCount == 1 ? candidates[0] : null; } private static IReadOnlyList HarvestOptions(Type optionsType) { object? defaults; try { defaults = Activator.CreateInstance(optionsType); } catch (Exception ex) when (ex is MissingMethodException or MemberAccessException or TargetInvocationException) { defaults = null; // no parameterless constructor — defaults stay unknown } // The options as a URI writes them (EndpointOptions.BindableOptions): a member of an option group is listed as // Group.Member (its value member as Group), with the group's role and the member's own type, default and marks. var options = new List(); var groupDefaults = new Dictionary(); foreach (var (name, property, group) in EndpointOptions.BindableOptions(optionsType)) { // Only what the connector declares: the EndpointOptions base carries machinery // (UnmappedParameters, …), not options. if (property.DeclaringType == typeof(EndpointOptions)) continue; object? owner = defaults; if (group is not null && !groupDefaults.TryGetValue(group, out owner)) groupDefaults[group] = owner = defaults is null ? null : Activator.CreateInstance(group.PropertyType); var underlying = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; options.Add(new CatalogOption( name, TypeLabel(underlying), Render(owner is null ? null : property.GetValue(owner)), property.GetCustomAttribute() is not null, underlying.IsEnum ? Enum.GetNames(underlying) : null, EndpointOptions.RoleOf(group ?? property), property.IsDefined(typeof(ConnectionParameterAttribute), inherit: true), property.IsDefined(typeof(ConnectionFactoryReferenceAttribute), inherit: true)) { Reference = ReferenceOf(property), }); } return [.. options.OrderBy(o => o.Name, StringComparer.Ordinal)]; } /// /// The catalog's of an option: the expected type of its /// as Full.Name, Assembly, object when the mark gives none, or /// null for an option that names no registry object. /// internal static string? ReferenceOf(PropertyInfo option) => option.GetCustomAttribute(inherit: true) is not { } mark ? null : mark.Expected is { } type ? ReferenceName(type) : "object"; /// A type as writes it: Full.Name, Assembly. internal static string ReferenceName(Type type) => $"{type.FullName}, {type.Assembly.GetName().Name}"; private static string TypeLabel(Type type) { // A [Flags] enum takes several members at once ("Tls12,Tls13"), so it is not a pick-one list. if (type.IsEnum) return type.IsDefined(typeof(FlagsAttribute), inherit: false) ? "flags" : "enum"; if (type == typeof(bool)) return "bool"; if (type == typeof(int)) return "int"; if (type == typeof(long)) return "long"; if (type == typeof(double) || type == typeof(float) || type == typeof(decimal)) return "double"; if (type == typeof(TimeSpan)) return "duration"; return "string"; } private static string? Render(object? value) => value switch { null => null, bool flag => flag ? "true" : "false", Enum member => member.ToString(), TimeSpan span => span.ToString("c", CultureInfo.InvariantCulture), IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), string text => text, _ => null, }; }