Path: redb-route/redb.Route/Validation/ValidatorComponent.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/Validation/ValidatorComponent.cs ---- using System.Collections.Concurrent; using System.Xml; using System.Xml.Schema; using Json.Schema; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Validation; // ── Component ──────────────────────────────────────────────────────────────── /// /// Component for schema-based message validation. /// /// URI format: validator:path/to/schema.json or validator:path/to/schema.xsd. /// The schema format is auto-detected from the file extension (.xsd → XSD, otherwise JSON Schema). /// /// /// Parameters: /// /// format — Force format: json or xml (overrides auto-detection). /// throwOnFailure — Whether to throw on failure (true by default). /// targetNamespace — Target namespace for XSD schemas (optional). /// schemaRoot — For XSD: the directory imports and includes stay under, relative to the schema's directory (optional). /// /// /// [EndpointRole(EndpointRole.Producer, Hint = "Use .To(\"validator:...\").")] public sealed class ValidatorComponent : ComponentBase { /// public override string Scheme => "validator"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new ValidatorEndpointOptions(); options.BindFromUri(uri.RawParameters); // The schema path resolves through the context's resource resolver // (absolute → ResourceRoot → AppContext.BaseDirectory → working directory), so a schema // inside an unpacked package is found wherever the worker process happens to run from. options.SchemaPath = string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : ResourceResolution.Resolve(Context, uri.Path, "Schema file"); options.Validate(); return new ValidatorEndpoint(uri, this, options); } } // ── Options ────────────────────────────────────────────────────────────────── /// Options for the validator endpoint. public sealed class ValidatorEndpointOptions : EndpointOptions { /// Path to the schema file (JSON Schema or XSD). public string SchemaPath { get; set; } = string.Empty; /// /// Explicit format override: json or xml. If not set, auto-detected from file extension. /// public string? Format { get; set; } /// Whether to throw on validation failure. Default: true. public bool ThrowOnFailure { get; set; } = true; /// Target namespace for XSD schemas (optional). public string? TargetNamespace { get; set; } /// /// For XSD: the directory the schema's imports and includes stay under, relative to the schema's directory /// (.. for UBL's maindoc/ next to common/). Not set: the schema's directory itself. /// public string? SchemaRoot { get; set; } /// public override void Validate() { if (string.IsNullOrWhiteSpace(SchemaPath)) throw new ArgumentException("Schema path is required for the validator component."); if (!File.Exists(SchemaPath)) throw new FileNotFoundException($"Schema file not found: {SchemaPath}"); if (Format != null && !Format.Equals("json", StringComparison.OrdinalIgnoreCase) && !Format.Equals("xml", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException($"Invalid format '{Format}'. Supported: json, xml."); } } } // ── Endpoint ───────────────────────────────────────────────────────────────── /// Endpoint that performs schema validation (JSON Schema or XSD). public sealed class ValidatorEndpoint : EndpointBase { private readonly IMessageValidator _validator; private readonly bool _throwOnFailure; internal ValidatorEndpoint(EndpointUri uri, ValidatorComponent component, ValidatorEndpointOptions options) : base(uri, component, options) { _throwOnFailure = options.ThrowOnFailure; _validator = BuildValidator(options); } /// public override IProducer CreateProducer() => new ValidatorProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException("Validator component does not support consuming (from). Use .To(\"validator:...\") instead."); internal IMessageValidator Validator => _validator; internal bool ThrowOnFailure => _throwOnFailure; private static IMessageValidator BuildValidator(ValidatorEndpointOptions options) { // An XSD is read from its file, so its imports and includes resolve relative to it. if (IsXsdSchema(options)) return XsdValidator.FromFile("validator", options.SchemaPath, string.IsNullOrEmpty(options.TargetNamespace) ? null : options.TargetNamespace, options.SchemaRoot); if (options.SchemaRoot is not null) throw new ArgumentException($"schemaRoot applies to XSD schemas; '{options.SchemaPath}' is read as a JSON Schema."); return new JsonSchemaValidator(File.ReadAllText(options.SchemaPath)); } private static bool IsXsdSchema(ValidatorEndpointOptions options) { if (options.Format != null) return options.Format.Equals("xml", StringComparison.OrdinalIgnoreCase); // Auto-detect from file extension var ext = Path.GetExtension(options.SchemaPath); return ext.Equals(".xsd", StringComparison.OrdinalIgnoreCase); } } // ── Producer ───────────────────────────────────────────────────────────────── /// Producer that triggers validation when the route sends to this endpoint. public sealed class ValidatorProducer : IProducer { private readonly ValidatorEndpoint _endpoint; internal ValidatorProducer(ValidatorEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var result = _endpoint.Validator.Validate(exchange); exchange.Properties[ValidateProcessor.ValidationResultProperty] = result.IsValid; exchange.Properties[ValidateProcessor.ValidationErrorsProperty] = result.IsValid ? null : string.Join("; ", result.Errors); if (!result.IsValid && _endpoint.ThrowOnFailure) throw new ValidationException(result.Errors); return Task.CompletedTask; } /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; }