Path: redb-route/redb.Route/Core/EndpointOptions.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/EndpointOptions.cs ---- using System.Collections.Concurrent; using System.Reflection; using System.Text.RegularExpressions; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Core; /// /// Base class for all endpoint options. Handles URI parameter binding via reflection. /// Subclass per component with typed properties. BindFromUri maps string params to properties. /// public abstract class EndpointOptions { private Dictionary? _unmapped; // Options types whose [Sensitive] properties have already been registered. Reflection runs // once per type, not per endpoint. Weak per type: the options of a component an unloadable module // (collectible load context) declares do not stay alive here. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable _sensitiveScanned = new(); private static readonly object Scanned = new(); /// /// Feeds every -marked property name of /// into , so the URI renderer redacts those parameters /// by declaration instead of by name-guessing. Runs once per options type. /// /// This is the .NET equivalent of the Camel build plugin that generates /// SensitiveUtils.SENSITIVE_KEYS from @UriParam(secret = true): the keyword set is /// derived from the declarations, never hand-written. Note the harvest is lazy — it happens when /// an options type is first bound — so the name-keyword backstop in /// still matters for a URI rendered before any endpoint /// of that scheme exists. /// /// private static void RegisterSensitiveKeys(Type type) { if (!_sensitiveScanned.TryAdd(type, Scanned)) return; // A member of an option group is written group.member: that is the key to mask. var names = BindableOptions(type) .Where(o => o.Member.IsDefined(typeof(SensitiveAttribute), inherit: true)) .Select(o => o.Name) .ToArray(); if (names.Length > 0) EndpointUri.AddSensitiveKeys(names); } /// /// The values of this instance's -marked string properties that are set: what the /// endpoint knows to be secret, so a text that quotes one (a token in a request URL, a key in a driver message) can /// be masked by value. /// internal IEnumerable SensitiveValues() => BindableOptions(GetType()) .Where(o => o.Member.PropertyType == typeof(string) && o.Member.GetIndexParameters().Length == 0 && o.Member.IsDefined(typeof(SensitiveAttribute), inherit: true)) .Select(o => (o.Group is null ? this : o.Group.GetValue(this)) is { } owner ? o.Member.GetValue(owner) as string : null) .OfType() .Where(v => v.Length > 0); /// /// One option as a URI writes it: is the parameter name (the property's name, or /// Group.Member for a member of an option group, or Group for its /// value member); is the property the value goes /// into; is the group property that holds it, null for an option of the endpoint itself. /// public sealed record BindableOption(string Name, PropertyInfo Member, PropertyInfo? Group); // Weak per options type, as _sensitiveScanned. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable> _bindable = new(); /// /// The options a URI can set on , by the parameter name it writes: each settable /// property, and for an option group each of its members as /// Group.Member (and its value member as Group). The binder, the masking of [Sensitive] options and the /// Route-XML catalog all read this one list. Read by reflection, without an endpoint. /// public static IReadOnlyList BindableOptions(Type optionsType) { ArgumentNullException.ThrowIfNull(optionsType); return _bindable.GetValue(optionsType, static type => { var options = new List(); foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite)) { if (!property.IsDefined(typeof(OptionGroupAttribute), inherit: true)) { options.Add(new BindableOption(property.Name, property, null)); continue; } var groupType = property.PropertyType; if (!groupType.IsClass || groupType == typeof(string) || groupType.GetConstructor(Type.EmptyTypes) is null) throw new InvalidOperationException( $"{type.Name}.{property.Name} is an [OptionGroup]: its type must be a class with a public " + "parameterless constructor."); var members = groupType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite).ToArray(); var values = members.Where(m => m.IsDefined(typeof(OptionGroupValueAttribute), inherit: true)).ToArray(); if (values.Length > 1) throw new InvalidOperationException( $"{groupType.Name} marks {values.Length} members [OptionGroupValue]; the bare {property.Name}= binds one."); foreach (var member in members) options.Add(new BindableOption( member == values.FirstOrDefault() ? property.Name : $"{property.Name}.{member.Name}", member, property)); } return options; }); } /// Parameters from URI that were not mapped to typed properties. public IReadOnlyDictionary UnmappedParameters => _unmapped ?? (IReadOnlyDictionary)new Dictionary(0); /// /// Binds raw string parameters from URI to typed properties. /// - string/int/bool properties: standard conversion. /// - DynamicValue{T} properties with ${...}: compiled expression (one time). /// - DynamicValue{T} properties without ${...}: static wrap. /// - Unmatched parameters go to UnmappedParameters; unless the options type is /// lenient, they are then refused with /// , each one named with the nearest option. /// - A known option whose value does not convert to its type is refused with /// : the option must not silently keep its default. /// /// Raw string parameters from EndpointUriParser. public void BindFromUri(IReadOnlyDictionary parameters) { // Harvest [Sensitive] declarations before anything else, so the set is populated even for // an endpoint whose URI carries no parameters at all. RegisterSensitiveKeys(GetType()); if (parameters.Count == 0) return; _unmapped = new Dictionary(StringComparer.OrdinalIgnoreCase); var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); var options = BindableOptions(GetType()); foreach (var (key, rawValue) in parameters) { var option = options.FirstOrDefault(o => o.Name.Equals(key, StringComparison.OrdinalIgnoreCase)); if (option is null) { if (GroupOf(options, key) is { } group) throw UnknownGroupMember(options, group, key); if (options.Any(o => o.Group is { } g && g.Name.Equals(key, StringComparison.OrdinalIgnoreCase))) throw BareGroup(options, key); _unmapped[key] = rawValue; continue; } var prop = option.Member; var target = option.Group is { } groupProperty ? GroupInstance(groupProperty) : this; var propType = prop.PropertyType; if (IsDynamicValueType(propType, out var innerType)) { if (!BindDynamicValue(prop, target, rawValue, innerType!)) throw Unconvertible(prop, key, rawValue, innerType!, acceptsExpressions: true); } else { var converted = ConvertValue(rawValue, propType); if (converted == null) throw Unconvertible(prop, key, rawValue, propType, acceptsExpressions: false); prop.SetValue(target, converted); } } if (WrittenBesideConnectionFactory(GetType(), parameters) is { Count: > 0 } beside) throw BesideConnectionFactory(parameters, beside); if (_unmapped.Count > 0 && !IsLenient(GetType())) throw UnknownParameters(props); } /// /// Whether takes parameters it has no property for /// (). Read by reflection, without an endpoint. /// public static bool IsLenient(Type optionsType) { ArgumentNullException.ThrowIfNull(optionsType); return optionsType.IsDefined(typeof(LenientPropertiesAttribute), inherit: true); } // Weak per options type, as _sensitiveScanned. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable _connectionDeclarations = new(); private sealed record ConnectionDeclaration(PropertyInfo? Reference, HashSet Parameters); /// /// The parameters wrote, as written, that a connection factory sets /// (), when the URI also names a factory /// (). Empty when it names none. The core refuses them when the /// options are bound; tooling asks the same question without an endpoint. /// /// The type declares connection parameters but no factory reference, or more than one. public static IReadOnlyList WrittenBesideConnectionFactory(Type optionsType, EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); return WrittenBesideConnectionFactory(optionsType, uri.RawParameters); } private static IReadOnlyList WrittenBesideConnectionFactory(Type optionsType, IReadOnlyDictionary parameters) { ArgumentNullException.ThrowIfNull(optionsType); var (reference, connectionParameters) = ConnectionDeclarations(optionsType); if (reference is null || !parameters.Any(p => p.Key.Equals(reference.Name, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(p.Value))) return []; return parameters.Keys.Where(connectionParameters.Contains).ToList(); } private static ConnectionDeclaration ConnectionDeclarations(Type optionsType) => _connectionDeclarations.GetValue(optionsType, static type => { var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); var parameters = props.Where(p => p.IsDefined(typeof(ConnectionParameterAttribute), inherit: true)) .Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); var references = props.Where(p => p.IsDefined(typeof(ConnectionFactoryReferenceAttribute), inherit: true)).ToArray(); if (references.Length > 1) throw new InvalidOperationException( $"{type.Name} marks {references.Length} options [ConnectionFactoryReference]; one option names the factory."); if (parameters.Count > 0 && references.Length == 0) throw new InvalidOperationException( $"{type.Name} declares [ConnectionParameter] options but no [ConnectionFactoryReference] option: the core " + "does not guess which option names the connection factory."); return new ConnectionDeclaration(references.FirstOrDefault(), parameters); }); private ArgumentException BesideConnectionFactory(IReadOnlyDictionary parameters, IReadOnlyList beside) { var reference = ConnectionDeclarations(GetType()).Reference!; var factory = parameters.First(p => p.Key.Equals(reference.Name, StringComparison.OrdinalIgnoreCase)); // By name only: the values are connection settings, credentials among them. return new ArgumentException( $"{EndpointName(GetType())} endpoint: {factory.Key} '{factory.Value}' sets the whole connection, so " + $"{string.Join(", ", beside)} cannot be given on the URI as well. Set them on the factory, or drop " + $"{factory.Key} and give the connection on the URI.", beside[0]); } private static string EndpointName(Type optionsType) { var name = optionsType.Name; foreach (var suffix in new[] { "EndpointOptions", "Options" }) if (name.EndsWith(suffix, StringComparison.Ordinal) && name.Length > suffix.Length) return name[..^suffix.Length]; return name; } /// The side of an endpoint that reads (); null for both. public static EndpointRole? RoleOf(PropertyInfo option) { ArgumentNullException.ThrowIfNull(option); return option.GetCustomAttribute(inherit: true)?.Role; } /// /// The parameters wrote, as written, whose option only the other side of an endpoint reads: /// a consumer being created ( = ) gets the /// producer-only ones, and the other way round. The connector refuses them, naming the parameters and never their /// values. /// /// The endpoint's options type. /// The endpoint URI as written. /// The side being created. public static IReadOnlyList WrittenForOtherRole(Type optionsType, EndpointUri uri, EndpointRole creating) { ArgumentNullException.ThrowIfNull(optionsType); ArgumentNullException.ThrowIfNull(uri); // A member of an option group belongs to the side its group belongs to. var otherSide = BindableOptions(optionsType) .Where(o => RoleOf(o.Group ?? o.Member) is { } role && role != creating) .Select(o => o.Name) .ToHashSet(StringComparer.OrdinalIgnoreCase); return uri.RawParameters.Keys.Where(otherSide.Contains).ToList(); } /// /// A connector's own words for a parameter name it does not know — typically a name it used to /// take and what replaced it — appended to the core refusal, which already names the nearest /// option. null = nothing to add. /// /// The parameter as the URI wrote it. protected virtual string? UnknownParameterHint(string name) => null; private ArgumentException UnknownParameters(PropertyInfo[] props) { var endpoint = EndpointName(GetType()); var names = props.Where(p => p.CanWrite).Select(p => char.ToLowerInvariant(p.Name[0]) + p.Name[1..]).ToArray(); // By name only: the value may be a secret. var parts = _unmapped!.Keys.Select(key => { var text = $"'{key}' is not an option of the {endpoint} endpoint."; if (UnknownParameterHint(key) is { Length: > 0 } hint) return text + " " + hint; return Nearest(key, names) is { } nearest ? $"{text} Did you mean '{nearest}'?" : text; }); return new ArgumentException(string.Join(" ", parts), _unmapped.Keys.First()); } /// The option name closest to a misspelt one, or null when none is close. private static string? Nearest(string name, string[] candidates) { string? best = null; var bestDistance = int.MaxValue; foreach (var candidate in candidates) { var distance = EditDistance(name.ToLowerInvariant(), candidate.ToLowerInvariant()); if (distance < bestDistance) { best = candidate; bestDistance = distance; } } // A third of the name, at least two edits: "tll" finds "ttl", "foo" finds nothing. return bestDistance <= Math.Max(2, name.Length / 3) ? best : null; } private static int EditDistance(string a, string b) { var previous = new int[b.Length + 1]; var current = new int[b.Length + 1]; for (var j = 0; j <= b.Length; j++) previous[j] = j; for (var i = 1; i <= a.Length; i++) { current[0] = i; for (var j = 1; j <= b.Length; j++) current[j] = Math.Min(Math.Min(current[j - 1] + 1, previous[j] + 1), previous[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1)); (previous, current) = (current, previous); } return previous[b.Length]; } /// /// A connector's own words for an option whose value was refused (what the modes mean, which /// one to pick), appended to the core message that already names the value and what the option /// takes. null = nothing to add. /// /// The option's property name. protected virtual string? OptionValueHint(string optionName) => null; private ArgumentException Unconvertible(PropertyInfo prop, string key, string rawValue, Type type, bool acceptsExpressions) { var shown = prop.IsDefined(typeof(SensitiveAttribute), inherit: true) ? "***" : rawValue; var message = $"'{key}={shown}' is not a valid value: {key} takes {Describe(key, type)}."; if (!acceptsExpressions && rawValue.Contains("${", StringComparison.Ordinal)) message += " This option does not accept ${...} expressions; use a constant or a {{property}} placeholder."; if (OptionValueHint(prop.Name) is { Length: > 0 } hint) message += " " + hint; return new ArgumentException(message, key); } private static string Describe(string key, Type type) { type = Nullable.GetUnderlyingType(type) ?? type; if (type.IsEnum) // Written the way the URI takes them, so the message can be copied back as is. return "one of " + string.Join(", ", Enum.GetNames(type).Select(n => $"{key}={n.ToLowerInvariant()}")); if (type == typeof(bool)) return "true or false"; if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte) || type == typeof(uint) || type == typeof(ulong) || type == typeof(ushort) || type == typeof(sbyte)) return $"a whole number ({type.Name})"; if (type == typeof(double) || type == typeof(float) || type == typeof(decimal)) return "a number with a '.' decimal point"; if (type == typeof(TimeSpan)) return "a time span (hh:mm:ss)"; return type.Name; } /// Validates required parameters and constraints. Called after BindFromUri. public abstract void Validate(); private ConcurrentDictionary>? _expressionCache; /// /// Resolves a string option value per message. /// If the value contains ${...} expressions, compiles it once and evaluates per exchange. /// Static values pass through with only a fast Contains check. /// /// Option value (may contain ${...} expressions). /// Current exchange for expression resolution. /// Resolved value, or the original value if no expressions found. public string? ResolveOption(string? value, IExchange exchange) { if (value is null || !value.Contains("${")) return value; _expressionCache ??= new(); var resolver = _expressionCache.GetOrAdd(value, static v => ExpressionResolver.GetCompiledTemplate(v)); return resolver(exchange); } private static bool IsDynamicValueType(Type type, out Type? innerType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(DynamicValue<>)) { innerType = type.GenericTypeArguments[0]; return true; } // Nullable> var underlying = Nullable.GetUnderlyingType(type); if (underlying != null && underlying.IsGenericType && underlying.GetGenericTypeDefinition() == typeof(DynamicValue<>)) { innerType = underlying.GenericTypeArguments[0]; return true; } innerType = null; return false; } /// Binds a dynamic option; false when a plain value does not convert. /// The option group a group.member key names by its prefix; null when the key names none. private static PropertyInfo? GroupOf(IReadOnlyList options, string key) { var dot = key.IndexOf('.'); if (dot <= 0) return null; var prefix = key[..dot]; return options.Select(o => o.Group).FirstOrDefault(g => g is not null && g.Name.Equals(prefix, StringComparison.OrdinalIgnoreCase)); } /// The group object of on this instance, created on first use. private object GroupInstance(PropertyInfo group) { if (group.GetValue(this) is { } existing) return existing; var created = Activator.CreateInstance(group.PropertyType)!; group.SetValue(this, created); return created; } // The name as a URI writes it: each segment camelCase (searchTerm.fromSentDate). private static string OptionName(string name) => string.Join('.', name.Split('.').Select(part => part.Length == 0 ? part : char.ToLowerInvariant(part[0]) + part[1..])); private static string MembersOf(IReadOnlyList options, PropertyInfo group) => string.Join(", ", options.Where(o => o.Group == group).Select(o => OptionName(o.Name))); private ArgumentException UnknownGroupMember(IReadOnlyList options, PropertyInfo group, string key) { // By name only: the value may be a secret. var text = $"'{key}' is not an option of the {EndpointName(GetType())} endpoint: the group {OptionName(group.Name)} " + $"takes {MembersOf(options, group)}."; var names = options.Where(o => o.Group == group).Select(o => OptionName(o.Name)).ToArray(); return new ArgumentException(Nearest(key, names) is { } nearest ? $"{text} Did you mean '{nearest}'?" : text, key); } private ArgumentException BareGroup(IReadOnlyList options, string key) { var group = options.First(o => o.Group is { } g && g.Name.Equals(key, StringComparison.OrdinalIgnoreCase)).Group!; return new ArgumentException( $"'{key}' is a group of options of the {EndpointName(GetType())} endpoint, written {OptionName(group.Name)}.member: " + $"{MembersOf(options, group)}.", key); } private static bool BindDynamicValue(PropertyInfo prop, object target, string rawValue, Type innerType) { var dvType = typeof(DynamicValue<>).MakeGenericType(innerType); // Detect ${...} expression → create dynamic value via StringExpression if (Expressions.TemplateScanner.HasPlaceholder(rawValue)) { var expression = new StringExpression(rawValue); var fromExpr = dvType.GetMethod("FromExpression", [typeof(Abstractions.IExpression)])!; var dv = fromExpr.Invoke(null, [expression]); prop.SetValue(target, dv); return true; } // Plain value → static wrap var converted = ConvertValue(rawValue, innerType); if (converted == null) return false; var fromStatic = dvType.GetMethod("FromStatic")!; var dv2 = fromStatic.Invoke(null, [converted]); prop.SetValue(target, dv2); return true; } private static object? ConvertValue(string rawValue, Type targetType) { var converted = OptionValueConverter.Convert(rawValue, targetType); // Enum.Parse also takes a number, which may name no member at all. A [Flags] enum is left // alone: its valid values are combinations, not members. var enumType = Nullable.GetUnderlyingType(targetType) ?? targetType; if (converted is not null && enumType.IsEnum && !enumType.IsDefined(typeof(FlagsAttribute), inherit: false) && !Enum.IsDefined(enumType, converted)) return null; return converted; } /// /// Registers the -marked property names of an arbitrary type /// with the URI redaction set — the same harvest performs for options /// types, reusable by components that bind URI parameters onto user objects (bean:). /// internal static void RegisterSensitiveKeysFor(Type type) => RegisterSensitiveKeys(type); } /// /// The one string-to-typed-value converter behind , /// extracted for reuse (bean: property binding, the XML loader's value /// conversion). Invariant culture throughout; an unconvertible value yields null and the caller /// decides whether that is an error or an unmapped parameter. /// internal static class OptionValueConverter { /// Converts a raw URI/attribute string to , or null. internal static object? Convert(string rawValue, Type targetType) { try { if (targetType == typeof(string)) return rawValue; if (targetType == typeof(int)) return int.Parse(rawValue, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(long)) return long.Parse(rawValue, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(bool)) return bool.Parse(rawValue); // Float, not the default Float | AllowThousands: "1,5" is a comma typed for a decimal // point, and reading it as 15 would be a silent wrong value. if (targetType == typeof(double)) return double.Parse(rawValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(float)) return float.Parse(rawValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(decimal)) return decimal.Parse(rawValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); if (targetType == typeof(TimeSpan)) return TimeSpan.Parse(rawValue, System.Globalization.CultureInfo.InvariantCulture); if (targetType.IsEnum) return Enum.Parse(targetType, rawValue, ignoreCase: true); // Nullable var underlying = Nullable.GetUnderlyingType(targetType); if (underlying != null) return Convert(rawValue, underlying); return System.Convert.ChangeType(rawValue, targetType, System.Globalization.CultureInfo.InvariantCulture); } catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException or ArgumentException) { // Not convertible to the requested type: the caller treats null as "unmapped" (options) // or as a declaration error (bean:). Anything else — reflection failures, type-load // errors — keeps flying. return null; } } }