| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using Elsa.Workflows.Models; |
| | | 4 | | using Json.Schema; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Workflows; |
| | | 7 | | |
| | | 8 | | /// <inheritdoc /> |
| | | 9 | | public class OutputConverterSettingsValidator : IOutputConverterSettingsValidator |
| | | 10 | | { |
| | 0 | 11 | | private static readonly JsonElement EmptySettings = JsonDocument.Parse("{}").RootElement.Clone(); |
| | 138 | 12 | | private readonly ConcurrentDictionary<string, SchemaValidationPlan> _schemaValidationPlans = new(StringComparer.Ordi |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public IReadOnlyCollection<string> Validate( |
| | | 16 | | OutputConverterDescriptor descriptor, |
| | | 17 | | IOutputConverter converter, |
| | | 18 | | JsonElement? settings) |
| | | 19 | | { |
| | 12 | 20 | | var errors = new List<string>(); |
| | | 21 | | |
| | 12 | 22 | | if (settings is { ValueKind: not JsonValueKind.Object }) |
| | 0 | 23 | | errors.Add("Converter settings must be a JSON object."); |
| | | 24 | | |
| | 12 | 25 | | if (descriptor.SettingsSchema is { } schemaElement) |
| | | 26 | | { |
| | 2 | 27 | | var plan = _schemaValidationPlans.GetOrAdd(descriptor.Id, _ => CreateSchemaValidationPlan(schemaElement)); |
| | | 28 | | |
| | 1 | 29 | | if (plan.Schema == null) |
| | 0 | 30 | | errors.Add("The registered converter settings schema is invalid."); |
| | 1 | 31 | | else if (!plan.Schema.Evaluate(settings ?? EmptySettings).IsValid) |
| | 1 | 32 | | errors.Add("Converter settings do not satisfy the registered JSON Schema."); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | try |
| | | 36 | | { |
| | 12 | 37 | | errors.AddRange(converter.ValidateSettings(settings?.Clone()) ?? []); |
| | 12 | 38 | | } |
| | 0 | 39 | | catch |
| | | 40 | | { |
| | 0 | 41 | | errors.Add("Converter-owned settings validation failed."); |
| | 0 | 42 | | } |
| | | 43 | | |
| | 12 | 44 | | return errors; |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | private static SchemaValidationPlan CreateSchemaValidationPlan(JsonElement schemaElement) |
| | | 48 | | { |
| | | 49 | | try |
| | | 50 | | { |
| | 1 | 51 | | return new(JsonSchema.Build(schemaElement)); |
| | | 52 | | } |
| | 0 | 53 | | catch |
| | | 54 | | { |
| | 0 | 55 | | return new(null); |
| | | 56 | | } |
| | 1 | 57 | | } |
| | | 58 | | |
| | 3 | 59 | | private sealed record SchemaValidationPlan(JsonSchema? Schema); |
| | | 60 | | } |